lgwks_bot 2.2.0

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

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt;
use std::num::IntErrorKind;

use lgwks_std::hash::Hasher;
use lgwks_std::json::serde;
use lgwks_std::json::{Deserialize, Serialize};

use crate::error::BotError;
use crate::semantic::EmbedderIdentity;

/// Maximum JSON flow size accepted before parsing begins.
pub const MAX_FLOW_BYTES: usize = 2_097_152;

/// Alias for [`MAX_FLOW_BYTES`] with an explicit schema-oriented name.
pub const MAX_FLOW_SPEC_BYTES: usize = MAX_FLOW_BYTES;

/// Maximum bytes accepted in one answer utterance.
///
/// An ingress ceiling, checked before the utterance is resolved or recorded.
/// A person typing an answer does not need more than this, and a caller
/// feeding a session from a file or a socket is the case where an unbounded
/// one costs memory for nothing.
pub const MAX_UTTERANCE_BYTES: usize = 8_192;

/// Maximum bytes one stored variable value may occupy when rendered.
///
/// Applies to the *value*, not to the option string that produced it: an
/// integer stores its decimal digits whatever the candidate said, and a choice
/// candidate stores the declared spelling. It is therefore a bound on what
/// interpolation can later paste into a record, which is the size that matters.
pub const MAX_VALUE_BYTES: usize = 65_536;

/// Maximum bytes of one rendered record payload.
///
/// The ceiling that makes expansion a linear operation. Compiling and sizing a
/// template under this bound costs no more than the bound itself, so a
/// document of a few hundred kilobytes cannot become a record of a few
/// gigabytes: the expansion is refused before it is allocated.
pub const MAX_RECORD_BYTES: usize = 1_048_576;

/// Maximum bytes one session retains across all of its records and visited
/// node ids.
///
/// The aggregate ceiling. Per-record and per-value bounds compose into an
/// unbounded total only if the graph can be walked again, and a budget bounds
/// steps rather than bytes, so the sum needs its own bound.
pub const MAX_SESSION_BYTES: usize = 8_388_608;

/// The byte axis a [`ResourceLimits`] ceiling applies to.
///
/// Reported by [`BotError::ResourceLimitAboveCeiling`] so a refusal names which
/// limit was raised, and used to tighten one axis without spelling the other
/// three. A typed axis rather than a flag per axis, because a caller that wants
/// to raise every ceiling should have to write every axis down.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResourceAxis {
    /// Bytes accepted in one answer utterance ([`MAX_UTTERANCE_BYTES`]).
    Utterance,
    /// Bytes one stored variable value may occupy ([`MAX_VALUE_BYTES`]).
    Value,
    /// Bytes of one rendered record payload ([`MAX_RECORD_BYTES`]).
    Record,
    /// Bytes one session retains in total ([`MAX_SESSION_BYTES`]).
    Session,
}

impl ResourceAxis {
    /// The stable label naming this axis.
    ///
    /// A label for diagnostics and serialization prose, not a serde
    /// discriminator: a `ResourceLimits` document spells the axes as its field
    /// names.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match *self {
            Self::Utterance => "utterance",
            Self::Value => "value",
            Self::Record => "record",
            Self::Session => "session",
        }
    }
}

/// Byte ceilings applied to every session, and the one place they are resolved.
///
/// A validated flow bounds *shape*: steps, nodes, reachable transitions, and
/// templates whose markers name declared variables. It does not bound *bytes*,
/// and the two are independent — `${value}` repeated a hundred thousand times
/// in a two-hundred-kilobyte document is a valid flow that interpolates to ten
/// gigabytes. These four ceilings are the byte bound:
///
/// - [`ResourceAxis::Utterance`] — one answer;
/// - [`ResourceAxis::Value`] — one stored value;
/// - [`ResourceAxis::Record`] — one rendered record payload, checked against
///   the compiled template's computed expansion *before* it is allocated;
/// - [`ResourceAxis::Session`] — everything one session retains.
///
/// [`ResourceLimits::shipped`] is the operator's hard ceiling, and it is a
/// ceiling rather than a default: a shorthand constructor may ask for less on
/// any axis and never for more. A request above the ceiling is refused with
/// [`BotError::ResourceLimitAboveCeiling`] where it is made rather than clamped
/// quietly, because a bound that is silently ignored is a bound nobody can
/// reason about.
///
/// # Examples
///
/// ```
/// use lgwks_bot::{BotError, ResourceAxis, ResourceLimits};
///
/// let tight = ResourceLimits::shipped().tighten(ResourceAxis::Record, 4_096);
/// assert_eq!(tight.get(ResourceAxis::Record), 4_096);
/// assert_eq!(tight.get(ResourceAxis::Session), ResourceLimits::shipped().get(ResourceAxis::Session));
/// assert!(tight.within_ceiling().is_ok());
///
/// let greedy = ResourceLimits::shipped().tighten(ResourceAxis::Session, usize::MAX);
/// assert!(matches!(
///     greedy.within_ceiling(),
///     Err(BotError::ResourceLimitAboveCeiling {
///         axis: ResourceAxis::Session,
///         ..
///     })
/// ));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields, default)]
#[non_exhaustive]
pub struct ResourceLimits {
    /// Bytes accepted in one answer utterance.
    utterance_bytes: usize,
    /// Bytes one stored variable value may occupy when rendered.
    value_bytes: usize,
    /// Bytes of one rendered record payload.
    record_bytes: usize,
    /// Bytes one session retains in total.
    session_bytes: usize,
}

impl ResourceLimits {
    /// The operator's shipped ceilings, applied when nothing tighter is asked
    /// for.
    #[must_use]
    pub const fn shipped() -> Self {
        Self {
            utterance_bytes: MAX_UTTERANCE_BYTES,
            value_bytes: MAX_VALUE_BYTES,
            record_bytes: MAX_RECORD_BYTES,
            session_bytes: MAX_SESSION_BYTES,
        }
    }

    /// Return the ceiling applied to one axis.
    #[must_use]
    pub const fn get(self, axis: ResourceAxis) -> usize {
        match axis {
            ResourceAxis::Utterance => self.utterance_bytes,
            ResourceAxis::Value => self.value_bytes,
            ResourceAxis::Record => self.record_bytes,
            ResourceAxis::Session => self.session_bytes,
        }
    }

    /// Return these ceilings with one axis set to `bytes`.
    ///
    /// Tightening only in intent: a value above the operator's ceiling is
    /// accepted by this constructor and refused by [`Self::within_ceiling`],
    /// so the caller learns that the bound it asked for is not the bound in
    /// force. `const` so a caller can build a ceiling at compile time.
    #[must_use]
    pub const fn tighten(mut self, axis: ResourceAxis, bytes: usize) -> Self {
        match axis {
            ResourceAxis::Utterance => self.utterance_bytes = bytes,
            ResourceAxis::Value => self.value_bytes = bytes,
            ResourceAxis::Record => self.record_bytes = bytes,
            ResourceAxis::Session => self.session_bytes = bytes,
        }
        self
    }

    /// The stricter of two ceiling sets, axis by axis.
    ///
    /// How an author's tightening and an operator's tightening combine: the
    /// smaller bound wins, so neither can widen what the other narrowed.
    #[must_use]
    pub const fn narrowed(self, other: Self) -> Self {
        Self {
            utterance_bytes: smaller(self.utterance_bytes, other.utterance_bytes),
            value_bytes: smaller(self.value_bytes, other.value_bytes),
            record_bytes: smaller(self.record_bytes, other.record_bytes),
            session_bytes: smaller(self.session_bytes, other.session_bytes),
        }
    }

    /// Refuse any axis set above the operator's ceiling.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::ResourceLimitAboveCeiling`] naming the first axis
    /// that exceeds its ceiling.
    pub fn within_ceiling(self) -> Result<Self, BotError> {
        let ceiling = Self::shipped();
        for axis in [
            ResourceAxis::Utterance,
            ResourceAxis::Value,
            ResourceAxis::Record,
            ResourceAxis::Session,
        ] {
            let requested = self.get(axis);
            let allowed = ceiling.get(axis);
            if requested > allowed {
                let refusal = Err(BotError::ResourceLimitAboveCeiling {
                    axis,
                    requested,
                    ceiling: allowed,
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "within_ceiling: returning an error to the caller");
                return refusal;
            }
        }
        Ok(self)
    }
}

impl Default for ResourceLimits {
    /// The operator's shipped ceilings — not "no limits".
    fn default() -> Self {
        Self::shipped()
    }
}

/// The operator's shipped byte ceilings, as one named value.
///
/// The case a flow document that declares no ceilings is held to. A constant
/// rather than a call so the case is a *name* at the two places that take it,
/// beside the field whose absence selects it — `unwrap_or_default()` would hide
/// which of the two resource-limit sets a document without a request is held to,
/// and a bare `Default::default()` would say nothing at all.
const SHIPPED_LIMITS: ResourceLimits = ResourceLimits::shipped();

/// The smaller of two byte counts, named because `Ord::min` is not `const`.
const fn smaller(left: usize, right: usize) -> usize {
    if left < right { left } else { right }
}

/// Stable identifier of a flow node.
pub type NodeId = String;

/// The closed set of scalar values carried by a [`VarScope`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Value {
    /// A free-form string.
    String(String),
    /// A signed integer.
    Integer(i64),
    /// A boolean.
    Boolean(bool),
    /// A selected member of a declared choice variable.
    Choice(String),
}

impl fmt::Display for Value {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::String(ref value) | Self::Choice(ref value) => formatter.write_str(value),
            Self::Integer(value) => write!(formatter, "{value}"),
            Self::Boolean(value) => write!(formatter, "{value}"),
        }
    }
}

impl Value {
    /// The number of bytes this value occupies when a template interpolates
    /// it.
    ///
    /// The exact cost, computed without rendering the value: for the two string
    /// variants it is the string's length, and for the two scalar variants it is
    /// the width of the decimal or boolean spelling that [`fmt::Display`]
    /// produces. Sizing an expansion needs this before it has the text, and
    /// measuring by formatting would allocate the buffer the check exists to
    /// avoid allocating.
    #[must_use]
    pub fn rendered_bytes(&self) -> usize {
        match *self {
            Self::String(ref value) | Self::Choice(ref value) => value.len(),
            // "true" is four bytes and "false" is five, and both are constants
            // rather than a call into the boolean formatter.
            Self::Boolean(true) => 4,
            Self::Boolean(false) => 5,
            Self::Integer(value) => integer_bytes(value),
        }
    }
}

/// The number of bytes [`fmt::Display`] writes for one integer.
///
/// Division-free and conversion-free: the digit count is the number of
/// base-ten thresholds the magnitude reaches, and the sign is one more byte when
/// the value is negative. Zero has one digit and reaches no threshold.
///
/// The thresholds are walked in `u64` and counted in `usize`, so no value is
/// ever narrowed between the magnitude and the width. A logarithm would have
/// been one instruction, but it returns a `u32` and turning that into the width
/// the caller compares needs a conversion whose failure arm would have to put a
/// number in a byte count; twenty comparisons against a multiply is not a cost
/// anyone measures next to the formatting this exists to avoid.
fn integer_bytes(value: i64) -> usize {
    // `unsigned_abs` rather than `abs`, because `i64::MIN` has no positive
    // counterpart: negating it in `i64` overflows, and the digit count does not
    // care which side of zero the magnitude came from.
    let magnitude = value.unsigned_abs();
    let mut digits = 1_usize;
    let mut threshold = 10_u64;
    // Bounded by construction: `u64::MAX` has twenty digits, so the loop runs at
    // most nineteen times and `threshold` saturates rather than wrapping.
    while magnitude >= threshold {
        digits = digits.saturating_add(1);
        threshold = threshold.saturating_mul(10);
    }
    if value < 0 {
        digits.saturating_add(1)
    } else {
        digits
    }
}

/// Declared type of one variable in a flow.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum VarType {
    /// A free-form string assigned by an ask.
    String,
    /// A signed integer parsed from an answer.
    Integer,
    /// A boolean parsed from `true`/`false` or `yes`/`no`.
    Boolean,
    /// A finite set of allowed answer values.
    Choice(Vec<String>),
}

impl VarType {
    /// Returns how an answer to a question writing this variable must be read.
    ///
    /// `Integer` is the only declaration whose answers are not text. The other
    /// three are labels: a `Choice` answer is matched against its own option
    /// strings, and a `Boolean` answer is a word (`yes`/`no`) that the same
    /// punctuation folding should tolerate.
    #[must_use]
    pub const fn answer_domain(&self) -> AnswerDomain {
        match *self {
            Self::Integer => AnswerDomain::Integer,
            Self::String | Self::Boolean | Self::Choice(_) => AnswerDomain::Label,
        }
    }

    /// The stable label naming this declared type.
    ///
    /// Stable prose for diagnostics and nothing else: it is not the serde
    /// discriminator, which is `rename_all = "snake_case"` on the variants and
    /// should be read from the document instead of from here.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match *self {
            Self::String => "string",
            Self::Integer => "integer",
            Self::Boolean => "boolean",
            Self::Choice(_) => "choice",
        }
    }

    /// Decode one answer string into a value of this declared type.
    ///
    /// The single decoder. Flow validation runs it over every `ask` candidate
    /// when the document is loaded, and runtime assignment runs it over the
    /// option the resolver selected; one implementation means the two cannot
    /// disagree about which candidates are storable, and a flow that loads is
    /// a flow every one of whose options can be stored.
    ///
    /// A display label is therefore a *value* of the declared type rather than
    /// a free string: `"yes"` offered for a boolean variable stores
    /// [`Value::Boolean`]`(true)`, and a choice candidate that differs from the
    /// declared spelling only in case stores the declared spelling. The route
    /// is keyed by the label the resolver matched; the variable receives what
    /// this returns.
    ///
    /// # Errors
    ///
    /// Returns the [`AnswerRejection`] naming why the answer cannot be stored.
    pub fn decode_answer(&self, answer: &str) -> Result<Value, AnswerRejection> {
        let trimmed = answer.trim();
        match *self {
            // A free-form string accepts anything, including the untrimmed
            // bytes: trimming a person's answer for them is a decision the
            // flow author makes downstream, not one this decoder makes.
            Self::String => Ok(Value::String(answer.to_owned())),
            Self::Integer => match trimmed.parse::<i64>() {
                Ok(value) => Ok(Value::Integer(value)),
                Err(error) => Err(match *error.kind() {
                    IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => {
                        AnswerRejection::IntegerOutOfRange
                    }
                    _ => AnswerRejection::NotAnInteger,
                }),
            },
            Self::Boolean => {
                if trimmed.eq_ignore_ascii_case("true") || trimmed.eq_ignore_ascii_case("yes") {
                    Ok(Value::Boolean(true))
                } else if trimmed.eq_ignore_ascii_case("false")
                    || trimmed.eq_ignore_ascii_case("no")
                {
                    Ok(Value::Boolean(false))
                } else {
                    Err(AnswerRejection::NotABoolean)
                }
            }
            Self::Choice(ref options) => {
                let Some(option) = options
                    .iter()
                    .find(|option| option.eq_ignore_ascii_case(trimmed))
                else {
                    let refusal = Err(AnswerRejection::NotADeclaredChoice);
                    lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "decode_answer: returning an error to the caller");
                    return refusal;
                };
                Ok(Value::Choice(option.clone()))
            }
        }
    }
}

/// Decodes one whole-number answer, preserving its sign.
///
/// The **resolver's** reading of a whole number: presence-only, because the
/// question the tiered search asks is *does this decode to the value the person
/// named*, and the answer to that is yes or no. The scope's reading is
/// [`VarType::decode_answer`], which has to say *why* an answer cannot be
/// stored and therefore distinguishes an overflow from prose; both run the same
/// `parse::<i64>` over the same trimmed bytes, so they cannot disagree about
/// which answers are whole numbers.
///
/// `None` means *not a whole number in range* — an empty answer, prose, a
/// decimal, or a magnitude beyond [`i64`]. It is not an error: an unrecognized
/// answer is re-asked, and the caller decides whether that or a refusal is the
/// right report.
pub(crate) fn decode_integer(raw: &str) -> Option<i64> {
    raw.trim().parse::<i64>().ok()
}

/// How a question's answers are meant to be read.
///
/// A property of the *answer*, not of the option text. Two questions can offer
/// option lists that look identical and mean different things by them, and
/// nothing in the option strings says which: `["-5", "5"]` at an integer
/// question is two distinct answers, while the same pair at a label question is
/// two spellings the resolver cannot tell apart, because the label policy folds
/// punctuation and the sign is punctuation.
///
/// That is the whole reason this exists as an explicit product of states rather
/// than a flag on one code path. The folding is correct for labels — `"yes!"`
/// and `"yes"` are one answer, and a person should not be re-asked for typing an
/// exclamation mark — and it is destructive for numbers, where it silently turns
/// `-5` into `5` and reports it at maximum confidence. One policy cannot be
/// both, so the answer says which one applies and the resolver reads the
/// question accordingly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnswerDomain {
    /// Natural-language option labels: compared after [`crate::language::normalize`].
    Label,
    /// Whole numbers: compared as decoded values, sign preserved.
    Integer,
}

impl fmt::Display for AnswerDomain {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Label => formatter.write_str("label"),
            Self::Integer => formatter.write_str("integer"),
        }
    }
}

/// Why one answer string cannot be stored in a variable.
///
/// A closed verdict rather than a message, so a caller branches on the cause
/// instead of parsing prose, and so the set of ways an answer can be unusable
/// is stated where a reviewer reads it. It is what
/// [`VarType::decode_answer`] returns, and therefore what flow validation
/// reports through [`BotError::AskOptionNotAssignable`] when a candidate is
/// unusable at load.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnswerRejection {
    /// The answer is not a decimal integer.
    NotAnInteger,
    /// The answer is a decimal integer outside the signed 64-bit range.
    IntegerOutOfRange,
    /// The answer is not `true`/`false` or `yes`/`no`.
    NotABoolean,
    /// The answer is not one of the variable's declared choice values.
    NotADeclaredChoice,
}

impl fmt::Display for AnswerRejection {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::NotAnInteger => formatter.write_str("it is not a decimal integer"),
            Self::IntegerOutOfRange => {
                formatter.write_str("it is outside the signed 64-bit integer range")
            }
            Self::NotABoolean => formatter.write_str("it is not true/false or yes/no"),
            Self::NotADeclaredChoice => {
                formatter.write_str("it is not one of the declared choice values")
            }
        }
    }
}

/// A variable reference or literal used by a branch predicate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValueExpr {
    /// A literal scalar.
    Literal(Value),
    /// The current value of a named variable.
    Var(String),
}

impl ValueExpr {
    /// Construct a variable reference.
    #[must_use]
    pub fn variable(name: impl Into<String>) -> Self {
        Self::Var(name.into())
    }
}

/// Closed, side-effect-free branch predicate language.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Predicate {
    /// A constant predicate.
    Const(bool),
    /// Equality comparison.
    Eq(ValueExpr, ValueExpr),
    /// Inequality comparison.
    Ne(ValueExpr, ValueExpr),
    /// Less-than comparison.
    Lt(ValueExpr, ValueExpr),
    /// Less-than-or-equal comparison.
    Le(ValueExpr, ValueExpr),
    /// Greater-than comparison.
    Gt(ValueExpr, ValueExpr),
    /// Greater-than-or-equal comparison.
    Ge(ValueExpr, ValueExpr),
    /// Conjunction of predicates.
    And(Vec<Predicate>),
    /// Disjunction of predicates.
    Or(Vec<Predicate>),
    /// Negation of one predicate.
    Not(Box<Predicate>),
}

impl Predicate {
    /// Evaluate this predicate against a variable scope.
    pub fn evaluate(&self, scope: &VarScope) -> Result<bool, BotError> {
        match *self {
            Self::Const(value) => Ok(value),
            Self::Eq(ref left, ref right) => same_value(left, right, scope, true),
            Self::Ne(ref left, ref right) => same_value(left, right, scope, false),
            Self::Lt(ref left, ref right) => {
                compare_expr(left, right, scope, |ordering| ordering.is_lt())
            }
            Self::Le(ref left, ref right) => {
                compare_expr(left, right, scope, |ordering| ordering.is_le())
            }
            Self::Gt(ref left, ref right) => {
                compare_expr(left, right, scope, |ordering| ordering.is_gt())
            }
            Self::Ge(ref left, ref right) => {
                compare_expr(left, right, scope, |ordering| ordering.is_ge())
            }
            Self::And(ref items) => all_true(items, scope),
            Self::Or(ref items) => any_true(items, scope),
            Self::Not(ref inner) => Ok(!inner.evaluate(scope)?),
        }
    }
}

/// Whether the two sides resolve to the same value, or to different ones.
///
/// `equal` is `true` for `Eq` and `false` for `Ne`, so one resolution path
/// serves both: each side resolves exactly once, which matters because
/// resolution is fallible and a side that resolved twice could fail twice.
///
/// This deliberately does not go through `compare_expr`. That one refuses a
/// pair of different `Value` variants with `PredicateTypeMismatch`, where `==`
/// here answers `false`; routing `Eq` through it would turn a comparison that
/// has always answered into one that fails.
fn same_value(
    left: &ValueExpr,
    right: &ValueExpr,
    scope: &VarScope,
    equal: bool,
) -> Result<bool, BotError> {
    let left_value = resolve_expr(left, scope)?;
    let right_value = resolve_expr(right, scope)?;
    Ok((left_value == right_value) == equal)
}

/// Every item must hold; evaluation stops at the first that does not.
///
/// `Ok(true)` on an empty list, the identity for `and`. The two short-circuit
/// loops are helpers rather than arms because each was a loop with a
/// propagation operator inside it, so the `match` above held three of them
/// across two arms and a reader could not see the short-circuit rule without
/// reading both loops in full.
fn all_true(items: &[Predicate], scope: &VarScope) -> Result<bool, BotError> {
    for item in items {
        if !item.evaluate(scope)? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Some item must hold; evaluation stops at the first that does.
///
/// `Ok(false)` on an empty list, the identity for `or`.
fn any_true(items: &[Predicate], scope: &VarScope) -> Result<bool, BotError> {
    for item in items {
        if item.evaluate(scope)? {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Validates one `branch` node: its variable, its predicate and both edges.
///
/// A helper so every kind's arm in [`validate_node`] is one call. The order
/// inside is the order a refusal should name things in: the variable before the
/// predicate that reads it, and the predicate before either edge it chooses
/// between.
fn validate_branch_node(
    spec: &FlowSpec,
    node_id: &str,
    var: &str,
    when: &Predicate,
    then: &str,
    otherwise: &str,
) -> Result<(), BotError> {
    validate_variable_reference(spec, node_id, var)?;
    validate_predicate(spec, node_id, when)?;
    check_edge_pair(&spec.nodes, node_id, then, otherwise)
}

/// Validates one `refer` node: its template, and that it reaches a terminal.
///
/// A helper for the same reason as the other kinds. A `refer` hands the
/// conversation to someone else, so its target has to be a place the flow can
/// actually end -- validated here rather than discovered when the session had
/// already given the person away.
fn validate_refer_node(
    spec: &FlowSpec,
    node_id: &str,
    text: &str,
    limits: ResourceLimits,
) -> Result<(), BotError> {
    validate_template(spec, node_id, text, "refer.text", limits)?;
    for target in spec.edge_targets(node_id) {
        check_target(&spec.nodes, node_id, &target)?;
    }
    Ok(())
}

/// Validates one `say` node: its template, and that it has exactly one way out.
///
/// A helper so every kind's arm in [`validate_node`] is one call. A `say` node
/// that continues along two edges is ambiguous at run time -- which one the
/// driver follows is not written down anywhere -- and a `say` node with no
/// continuation and no terminal leaves the conversation with nowhere to go, so
/// both are refused at load rather than at the moment a person is waiting.
fn validate_say_node(
    spec: &FlowSpec,
    node_id: &str,
    text: &str,
    limits: ResourceLimits,
) -> Result<(), BotError> {
    validate_template(spec, node_id, text, "say.text", limits)?;
    if spec.edge_targets(node_id).len() > 1 {
        let refusal = Err(BotError::MalformedFlow {
            cause: format!("say node {node_id:?} has multiple continuations"),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_say_node: returning an error to the caller");
        return refusal;
    }
    if spec.edge_targets(node_id).is_empty() && !spec.terminals.contains_key(node_id) {
        let refusal = Err(BotError::MissingTransition {
            node: node_id.to_owned(),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_say_node: returning an error to the caller");
        return refusal;
    }
    Ok(())
}

/// Validates one `ask` node: its variable, its options and its routes.
///
/// A helper rather than the arm inline: as one block the arm carried the
/// variable lookup, the option decode, the byte check and the two route passes,
/// so `validate_node` read as a list of kinds when what it needed to say was
/// which parts of an `ask` node are checked and in what order -- decode with
/// the runtime's own decoder first, then the session's own ceiling, then the
/// routes, so a refusal names the earliest thing wrong rather than an arbitrary
/// one.
fn validate_ask_node(
    spec: &FlowSpec,
    node_id: &str,
    var: &str,
    options: &[String],
    routes: &BTreeMap<String, NodeId>,
    limits: ResourceLimits,
    writers: &mut BTreeSet<String>,
) -> Result<(), BotError> {
    let declared = declared_variable(spec, var)?;
    writers.insert(var.to_owned());
    if options.is_empty() || has_duplicate_strings(options) {
        let refusal = Err(BotError::MalformedFlow {
            cause: format!("ask node {node_id:?} has invalid options"),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
        return refusal;
    }
    // Distinct strings are not distinct answers. Two options the answer
    // policy cannot tell apart are one option the person cannot choose
    // between, and the resolver can only ever report the tie — so the
    // authoring mistake is refused here, where it names an option,
    // rather than at run time, where it names none.
    if let Some((first, second)) = colliding_options(options, answer_domain_of(spec, var)) {
        let refusal = Err(BotError::MalformedFlow {
            cause: format!(
                "ask node {node_id:?} offers {first:?} and {second:?} as the same \
                         {} answer",
                answer_domain_of(spec, var)
            ),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
        return refusal;
    }
    for option in options {
        let Some(target) = routes.get(option) else {
            let refusal = Err(BotError::MissingAskRoute {
                node: node_id.to_owned(),
                option: option.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
            return refusal;
        };
        check_target(&spec.nodes, node_id, target)?;
        // Every candidate is decoded with the same decoder the runtime
        // assigns with, so "the flow asks a question the variable
        // cannot hold an answer to" is a load-time refusal rather than
        // a conversation the person cannot complete.
        let value = match declared.decode_answer(option) {
            Ok(value) => value,
            Err(rejection) => {
                let refusal = Err(BotError::AskOptionNotAssignable {
                    node: node_id.to_owned(),
                    variable: var.to_owned(),
                    option: option.clone(),
                    expected: declared.label(),
                    cause: rejection.to_string(),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
                return refusal;
            }
        };
        // Then that the value fits the session that will store it.
        // "The candidate cannot be held" and "the candidate cannot be
        // held *here*" are different statements, and both are knowable
        // while the document is loading: the second one is a session
        // whose value ceiling is below the option it asked for, and
        // deferring it to the person's answer would charge them a step
        // for an operator's configuration.
        let value_bytes = limits.get(ResourceAxis::Value);
        if value.rendered_bytes() > value_bytes {
            let refusal = Err(BotError::AskOptionTooLarge {
                node: node_id.to_owned(),
                variable: var.to_owned(),
                option: option.clone(),
                bytes: value.rendered_bytes(),
                limit: value_bytes,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
            return refusal;
        }
    }
    for (option, target) in routes {
        if !options.iter().any(|candidate| candidate == option) {
            let refusal = Err(BotError::MalformedFlow {
                cause: format!("ask node {node_id:?} routes undeclared option {option:?}"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_ask_node: returning an error to the caller");
            return refusal;
        }
        check_target(&spec.nodes, node_id, target)?;
    }
    Ok(())
}

/// Checks both edges of a branch, in the order the branch names them.
///
/// A helper for the pair rather than two calls: the branch's whole contract is
/// that both targets resolve, and a reader checking one edge had no reason to
/// look for the other three lines below it.
fn check_edge_pair(
    nodes: &BTreeMap<NodeId, NodeKind>,
    node_id: &str,
    first: &str,
    second: &str,
) -> Result<(), BotError> {
    check_target(nodes, node_id, first)?;
    check_target(nodes, node_id, second)
}

/// A declared flow node and its closed operation kind.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum NodeKind {
    /// Emit interpolated text and follow its [`FlowEdge`] continuation.
    Say {
        /// Text shown to the user.
        text: String,
    },
    /// Ask for a value and route the recognized option.
    Ask {
        /// Variable receiving the selected option.
        var: String,
        /// Candidate answer strings passed to the resolver.
        options: Vec<String>,
        /// Route keyed by the selected option string.
        routes: BTreeMap<String, NodeId>,
    },
    /// Evaluate a predicate and choose one of two destinations.
    Branch {
        /// Variable read by the branch.
        var: String,
        /// Predicate deciding the `then` destination.
        when: Predicate,
        /// Destination when `when` is true.
        then: NodeId,
        /// Destination when `when` is false.
        otherwise: NodeId,
    },
    /// End the session with a handoff outcome.
    Handoff {
        /// Human or system target receiving the handoff.
        target: String,
    },
    /// End the session with a referral outcome after emitting text.
    Refer {
        /// Human or system target receiving the referral.
        target: String,
        /// Text shown before the referral is recorded.
        text: String,
    },
    /// Choose `dispatch` after an accepted answer, or `fallback` at a cold
    /// route with no accepted answer.
    Route {
        /// Destination used after a recognized answer.
        dispatch: NodeId,
        /// Destination used when no answer has been accepted.
        fallback: NodeId,
    },
    /// End the session. The flow terminal map can override the default
    /// [`Terminal::Completed`] outcome with a refusal.
    End,
}

/// Compatibility name for the reference flow representation.
pub type FlowNodeKind = NodeKind;

/// One explicit continuation in a flow graph.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum FlowEdge {
    /// Continue from one node to another.
    Next {
        /// Source node.
        from: NodeId,
        /// Destination node.
        to: NodeId,
    },
    /// Reference-compatible spelling for an unconditional continuation.
    After {
        /// Source node.
        from: NodeId,
        /// Destination node.
        to: NodeId,
    },
}

impl FlowEdge {
    /// Construct an unconditional continuation.
    #[must_use]
    pub fn next(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self::Next {
            from: from.into(),
            to: to.into(),
        }
    }

    /// Return the source and destination node ids.
    #[must_use]
    pub fn endpoints(&self) -> (&str, &str) {
        match *self {
            Self::Next { ref from, ref to } | Self::After { ref from, ref to } => (from, to),
        }
    }
}

/// How a run's workflow ended, without its payload.
///
/// The routing class: a consumer acting on a refusal, a referral or a handoff
/// matches here, and reads the detail from [`Terminal`]. Payload-free so it is
/// `Copy` and can be matched in a guard.
///
/// This says nothing about effects. It is deliberately a separate fact from
/// [`EffectLedger`] rather than an arm of one enum, because "the flow was
/// refused" and "an earlier effect may be live" are independent, and a single
/// classifier that prioritises either one destroys the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Disposition {
    /// The flow ran to its own end.
    Completed,
    /// The flow referred the caller to another tier.
    Referred,
    /// The flow handed ownership to another actor.
    HandedOff,
    /// The flow refused to continue. A *decided* outcome, which settles nothing
    /// about an effect an earlier step already attempted.
    Refused,
}

/// What a run knows about the effects it attempted.
///
/// Two counts, because they answer different questions and neither can be
/// inferred from the other. `confirmed` is what the run watched take effect.
/// `unsettled` is what it attempted and could not settle — the effects a domain
/// reported as [`BotError::EffectIndeterminate`].
///
/// A non-zero `unsettled` does **not** imply that anything succeeded. One
/// attempted effect whose response was lost may have produced zero effects or
/// one, and that ambiguity is what this type keeps rather than resolves: the
/// honest report is "nothing is confirmed, and one is in doubt", not "part of
/// the output exists".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct EffectLedger {
    /// Effects the run watched take effect.
    confirmed: usize,
    /// Effects whose occurrence could not be determined.
    unsettled: usize,
}

impl EffectLedger {
    /// Record a run's effect history.
    #[must_use]
    pub const fn new(confirmed: usize, unsettled: usize) -> Self {
        Self {
            confirmed,
            unsettled,
        }
    }

    /// Effects the run watched take effect.
    #[must_use]
    pub const fn confirmed(&self) -> usize {
        self.confirmed
    }

    /// Effects whose occurrence could not be determined.
    #[must_use]
    pub const fn unsettled(&self) -> usize {
        self.unsettled
    }

    /// Whether any attempted effect's occurrence is unknown, and therefore
    /// whether a retry is a possible duplicate rather than a repair.
    ///
    /// Reads the count and never the disposition: a refusal does not settle an
    /// earlier network outcome, so this stays `true` for a refused run that
    /// left an effect in doubt.
    #[must_use]
    pub const fn needs_reconciliation(&self) -> bool {
        self.unsettled > 0
    }
}

/// A run's report: what the workflow decided, and what is known about the
/// effects it attempted.
///
/// Two independent fields rather than arms of one enum. A refused run that also
/// leaves an effect in doubt is both *refused* and *in need of reconciliation*,
/// and no single arm can say that: an earlier version of this type returned
/// `Failure` for every refusal and erased the uncertainty, which is the exact
/// information [`BotError::EffectIndeterminate`] was introduced to preserve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct Outcome {
    /// What the workflow decided.
    disposition: Disposition,
    /// What is known about the effects it attempted.
    effects: EffectLedger,
}

impl Outcome {
    /// What the workflow decided.
    #[must_use]
    pub const fn disposition(&self) -> Disposition {
        self.disposition
    }

    /// What is known about the effects the run attempted.
    #[must_use]
    pub const fn effects(&self) -> EffectLedger {
        self.effects
    }

    /// Whether any attempted effect's occurrence is unknown.
    #[must_use]
    pub const fn needs_reconciliation(&self) -> bool {
        self.effects.needs_reconciliation()
    }
}

/// One predicate arm used by callers building a higher-level choice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct ChoiceArm {
    /// Predicate guarding the arm.
    when: Predicate,
    /// Destination selected by the arm.
    then: NodeId,
}

impl ChoiceArm {
    /// Construct one guarded destination.
    #[must_use]
    pub fn new(when: Predicate, then: impl Into<String>) -> Self {
        Self {
            when,
            then: then.into(),
        }
    }

    /// Return the guard predicate.
    #[must_use]
    pub fn when(&self) -> &Predicate {
        &self.when
    }

    /// Return the destination node id.
    #[must_use]
    pub fn then(&self) -> &str {
        &self.then
    }
}

/// A terminal outcome returned by a completed session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Terminal {
    /// The flow completed normally.
    Completed,
    /// The flow referred the user to another target.
    Referred {
        /// Referral target.
        target: String,
    },
    /// The flow handed the user to another target.
    HandedOff {
        /// Handoff target.
        target: String,
    },
    /// The flow refused to continue.
    Refused {
        /// Human-readable refusal reason.
        reason: String,
    },
}

impl Terminal {
    /// Report this terminal together with the run's effect history.
    ///
    /// Both facts are carried through unchanged, and that is the whole of the
    /// method. It does not classify, because classifying is where the
    /// information was being lost: an earlier version returned a single enum
    /// and had to choose, for a refused run that also left an effect unsettled,
    /// whether to report the refusal or the uncertainty. Both are true, both
    /// matter to different consumers, and a report that drops either one is
    /// wrong for whoever needed it.
    #[must_use]
    pub fn outcome(&self, effects: EffectLedger) -> Outcome {
        let disposition = match *self {
            Self::Completed => Disposition::Completed,
            Self::Referred { .. } => Disposition::Referred,
            Self::HandedOff { .. } => Disposition::HandedOff,
            Self::Refused { .. } => Disposition::Refused,
        };
        Outcome {
            disposition,
            effects,
        }
    }
}

/// Bounds applied to a flow and every session executing it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct FlowBounds {
    /// Maximum number of runtime steps, including answer attempts.
    budget: usize,
    /// Byte ceilings the document asks to be held to, if any.
    ///
    /// Absent means "whatever the operator enforces". Present means "no more
    /// than this", and the requested ceilings are checked against the
    /// operator's hard ceiling when the document loads: an author may declare
    /// that this flow's text is small and may not declare that it is allowed to
    /// be large.
    #[serde(default)]
    resources: Option<ResourceLimits>,
}

impl FlowBounds {
    /// Construct bounds with a declared step budget and the operator's shipped
    /// byte ceilings.
    #[must_use]
    pub const fn new(budget: usize) -> Self {
        Self {
            budget,
            resources: None,
        }
    }

    /// Return the declared step budget.
    #[must_use]
    pub const fn budget(self) -> usize {
        self.budget
    }

    /// Return the byte ceilings the document asks for, if it asks for any.
    #[must_use]
    pub const fn resources(self) -> Option<ResourceLimits> {
        self.resources
    }

    /// The byte ceilings in force for this document.
    ///
    /// Two cases, both declared by the type: a document that asked for ceilings
    /// gets the ones it asked for, and one that asked for none gets
    /// [`ResourceLimits::shipped`] — which is what "whatever the operator
    /// enforces" means, and is not a value standing in for a missing request.
    /// Either way the result goes through `within_ceiling` before anything runs,
    /// because an author's request above the operator's is refused rather than
    /// honoured.
    #[must_use]
    pub fn effective_resources(self) -> ResourceLimits {
        match self.resources {
            Some(requested) => requested,
            None => SHIPPED_LIMITS,
        }
    }

    /// Return these bounds with a declared byte-ceiling request attached.
    #[must_use]
    pub const fn with_resources(mut self, resources: ResourceLimits) -> Self {
        self.resources = Some(resources);
        self
    }
}

impl Default for FlowBounds {
    fn default() -> Self {
        Self::new(256)
    }
}

/// A validated, declarative flow document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct FlowSpec {
    /// Variable declarations.
    vars: BTreeMap<String, VarType>,
    /// Entry node id.
    entry: NodeId,
    /// Node map keyed by stable node id.
    nodes: BTreeMap<NodeId, NodeKind>,
    /// Explicit continuations, primarily used by [`NodeKind::Say`].
    #[serde(default)]
    edges: Vec<FlowEdge>,
    /// Explicit terminal outcomes keyed by node id.
    #[serde(default)]
    terminals: BTreeMap<NodeId, Terminal>,
    /// Static and runtime bounds.
    #[serde(default)]
    bounds: FlowBounds,
}

impl FlowSpec {
    /// Construct and validate a flow document.
    pub fn new(
        vars: BTreeMap<String, VarType>,
        entry: impl Into<String>,
        nodes: BTreeMap<NodeId, NodeKind>,
        edges: Vec<FlowEdge>,
        terminals: BTreeMap<NodeId, Terminal>,
        bounds: FlowBounds,
    ) -> Result<Self, BotError> {
        let spec = Self {
            vars,
            entry: entry.into(),
            nodes,
            edges,
            terminals,
            bounds,
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Construct a flow without explicit edges or terminal declarations.
    /// `Say` nodes still require a continuation edge, so this helper is useful
    /// only for flows made entirely from direct-transition node kinds.
    pub fn from_nodes(
        vars: BTreeMap<String, VarType>,
        entry: impl Into<String>,
        nodes: BTreeMap<NodeId, NodeKind>,
        bounds: FlowBounds,
    ) -> Result<Self, BotError> {
        Self::new(vars, entry, nodes, Vec::new(), BTreeMap::new(), bounds)
    }

    /// Serialize the validated flow using the shared JSON facade.
    pub fn to_json(&self) -> Result<String, lgwks_std::json::Error> {
        crate::json::to_string_pretty(self)
    }

    /// Serialize the validated flow as RON.
    ///
    /// RON is the estate's notation for human-facing documents, and a flow is
    /// one: a file a person writes and reads. The encoding is serde's, so the
    /// document is the same one [`to_json`](Self::to_json) writes, spelled with
    /// the unquoted keys, comments and trailing commas RON allows.
    pub fn to_ron(&self) -> Result<String, lgwks_std::ron::Error> {
        lgwks_std::ron::to_string_pretty(self)
    }

    /// Parse and validate a flow using the shared JSON facade.
    pub fn from_json(source: &str) -> Result<Self, BotError> {
        check_flow_size(source)?;
        reject_unknown_node_kinds(&merge_read_kinds(
            parse_json::<DeclaredNodes<false>>(source),
            parse_json::<DeclaredNodes<true>>(source),
        ))?;
        let spec = parse_json::<Self>(source).map_err(malformed_flow)?;
        spec.validate()?;
        Ok(spec)
    }

    /// Parse and validate a flow written in RON.
    ///
    /// Both codecs converge on the same validation, so the size limit, the
    /// unknown-node-kind diagnostic and the structural checks are identical
    /// whichever spelling a document arrives in. Only the parse differs, which
    /// is what keeps one document from being acceptable in one notation and
    /// refused in the other.
    ///
    /// Every enum in the document is externally tagged, so a variant is written
    /// with its own name, which is what makes a flow read as a script rather
    /// than as a tagged record:
    ///
    /// ```ron
    /// FlowSpec(
    ///     vars: {},
    ///     entry: "end",
    ///     nodes: { "end": End },
    /// )
    /// ```
    ///
    /// The cost is on the JSON side, where the same variant becomes
    /// `{"end": {}}`, and a unit variant becomes the bare string `"end"`.
    pub fn from_ron(source: &str) -> Result<Self, BotError> {
        check_flow_size(source)?;
        // No node-kind guard here, and the reason is RON's rather than a
        // choice: RON checks a variant name against the list it is handed, so
        // an unknown name is refused before any visitor of ours sees it, and
        // the name reaches the surface only through RON's own error. That error
        // names both the variant and the enum it was not a member of, which is
        // more than serde says on the JSON path. There, a name is not checked
        // against anything, so the guard is what supplies the name at all, and
        // with it the node that carried it.
        let spec = parse_ron::<Self>(source).map_err(malformed_flow)?;
        spec.validate()?;
        Ok(spec)
    }

    /// Re-run the structural validation for a flow already held in memory.
    pub fn validate(&self) -> Result<(), BotError> {
        flow::validate(self)
    }

    /// Return the declared variable map.
    #[must_use]
    pub fn vars(&self) -> &BTreeMap<String, VarType> {
        &self.vars
    }

    /// Return the entry node id.
    #[must_use]
    pub fn entry(&self) -> &str {
        &self.entry
    }

    /// Return the node map.
    #[must_use]
    pub fn nodes(&self) -> &BTreeMap<NodeId, NodeKind> {
        &self.nodes
    }

    /// Return the explicit continuation list.
    #[must_use]
    pub fn edges(&self) -> &[FlowEdge] {
        &self.edges
    }

    /// Return the explicit terminal map.
    #[must_use]
    pub fn terminals(&self) -> &BTreeMap<NodeId, Terminal> {
        &self.terminals
    }

    /// Return the applied bounds.
    #[must_use]
    pub const fn bounds(&self) -> FlowBounds {
        self.bounds
    }

    /// Look up one node by id.
    #[must_use]
    pub fn node(&self, id: &str) -> Option<&NodeKind> {
        self.nodes.get(id)
    }

    /// The outcome one node ends a session with, after the terminal map is
    /// consulted.
    ///
    /// The one calculation of "what does this document say happens here",
    /// shared by validation and execution. `None` means the node is not a
    /// terminal node — an `End`, `Handoff`, or `Refer` — and no outcome is
    /// defined for it.
    ///
    /// A declared terminal is authoritative for every terminal node, which is
    /// what makes an `End` node's refusal override work. On a `Handoff` or
    /// `Refer` node that same authority would silently discard the target the
    /// node was written to hand to, so a declaration that *contradicts* the
    /// node's own outcome is refused at load
    /// ([`BotError::ConflictingTerminalDeclaration`]) rather than accepted and
    /// ignored: a document that says a referral is refused is either corrected
    /// or rejected, never run as a permissive referral. A declaration that
    /// repeats the node's own outcome is accepted and is what this method
    /// returns, so the declaration is read rather than merely tolerated.
    #[must_use]
    pub fn effective_terminal(&self, node_id: &str) -> Option<Terminal> {
        // A `?` here is the non-terminal case, and it is why the declared
        // lookup cannot be written first: an `End`-only declaration on a `Say`
        // node is refused by validation and has no effective outcome.
        let intrinsic = self.intrinsic_terminal(node_id)?;
        match self.terminals.get(node_id) {
            Some(declared) => Some(declared.clone()),
            None => Some(intrinsic),
        }
    }

    /// The outcome a terminal node carries before the terminal map is
    /// consulted: `End` completes, `Handoff` names its target, and `Refer`
    /// names its target.
    ///
    /// Private because it is the half of [`Self::effective_terminal`] that is
    /// only meaningful inside the crate: a caller that wants the document's
    /// outcome wants the declared one, and getting the intrinsic half would be
    /// getting the answer this method exists to be corrected from.
    fn intrinsic_terminal(&self, node_id: &str) -> Option<Terminal> {
        match *self.nodes.get(node_id)? {
            NodeKind::End => Some(Terminal::Completed),
            NodeKind::Handoff { ref target } => Some(Terminal::HandedOff {
                target: target.clone(),
            }),
            NodeKind::Refer { ref target, .. } => Some(Terminal::Referred {
                target: target.clone(),
            }),
            _ => None,
        }
    }

    /// Return all explicit edge destinations from one node.
    fn edge_targets(&self, from: &str) -> Vec<NodeId> {
        self.edges
            .iter()
            .filter_map(|edge| {
                let (source, target) = edge.endpoints();
                (source == from).then(|| target.to_owned())
            })
            .collect()
    }
}

/// Flow validation entry point.
pub mod flow {
    use super::{BotError, FlowSpec, validate_flow};

    /// Validate every structural invariant required before a session can run.
    pub fn validate(spec: &FlowSpec) -> Result<(), BotError> {
        validate_flow(spec)
    }
}

/// Validate a flow's graph, variables, templates, and budget against the
/// operator's shipped byte ceilings.
fn validate_flow(spec: &FlowSpec) -> Result<(), BotError> {
    validate_flow_within(spec, ResourceLimits::shipped())
}

/// Validate a flow's graph, variables, templates, budget, and byte ceilings.
///
/// The ceilings are a parameter because two callers enforce different ones:
/// [`FlowSpec::validate`] applies the shipped ceilings a document must satisfy
/// on its own, and a session applies the effective ceilings it will run under —
/// its own, narrowed by whatever the document asked for. Both runs are the same
/// validation, so "the document is valid" and "the document can be run here"
/// cannot disagree about a candidate list or a template.
fn validate_flow_within(spec: &FlowSpec, limits: ResourceLimits) -> Result<(), BotError> {
    // First, and before any structural work: a document that asks for a
    // ceiling above the operator's gets a diagnostic naming the axis it asked
    // about, not a run under a bound it did not choose.
    let requested = spec.bounds.effective_resources().within_ceiling()?;
    let effective = requested.narrowed(limits);
    if spec.nodes.is_empty() {
        let refusal = Err(BotError::MalformedFlow {
            cause: "flow declares no nodes".into(),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_flow_within: returning an error to the caller");
        return refusal;
    }
    if !spec.nodes.contains_key(&spec.entry) {
        let refusal = Err(BotError::InvalidTransitionTarget {
            from: "<entry>".into(),
            target: spec.entry.clone(),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_flow_within: returning an error to the caller");
        return refusal;
    }
    if spec.bounds.budget == 0 || spec.nodes.len() > spec.bounds.budget {
        let refusal = Err(BotError::FlowBudgetExceeded {
            steps: spec.nodes.len(),
            budget: spec.bounds.budget,
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_flow_within: returning an error to the caller");
        return refusal;
    }

    validate_declarations(&spec.vars)?;
    validate_terminals(spec)?;

    let mut writers = BTreeSet::new();
    for (node_id, kind) in &spec.nodes {
        validate_node(spec, node_id, kind, effective, &mut writers)?;
    }
    for name in spec.vars.keys() {
        if !writers.contains(name) {
            let refusal = Err(BotError::VariableNeverWritten { name: name.clone() });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_flow_within: returning an error to the caller");
            return refusal;
        }
    }
    for edge in &spec.edges {
        let (from, to) = edge.endpoints();
        if !spec.nodes.contains_key(from) {
            let refusal = Err(BotError::InvalidTransitionTarget {
                from: from.to_owned(),
                target: from.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_flow_within: returning an error to the caller");
            return refusal;
        }
        check_target(&spec.nodes, from, to)?;
    }
    reject_uninitialized_reads(spec)?;
    reject_unreachable(spec)
}

/// Reject every read of a variable that is not definitely assigned on all
/// paths reaching the reading node.
///
/// A global writer set answers "does some node write this variable", which is
/// not the question a read has to pass: a session starts with an empty
/// [`VarScope`], so a writer that executes only after the read, or only on a
/// branch the read is not reached through, leaves the read with no value and
/// [`TemplateInterpolator`] returning [`BotError::VariableUnset`] on the first
/// step. This is a forward *must* (definite-assignment) analysis over the
/// execution graph instead of a membership test over the document.
///
/// The state of a node is the set of variables assigned on **every** path from
/// the entry to that node, which is a greatest fixed point: every node is
/// seeded with the full declaration set and each step intersects an outgoing
/// state into its successors, so states only shrink and a cycle converges. A
/// node no entry path reaches keeps that top element and is never accused
/// here — reachability is [`reject_unreachable`]'s single verdict, and one
/// defect must not surface as two.
///
/// Supported assignments and guards, stated so the boundary is not guessed at:
/// an [`NodeKind::Ask`] assigns its variable on each outgoing route and
/// nowhere earlier; every other node kind passes its incoming state through
/// unchanged. No symbolic reasoning about [`Predicate`] values is attempted,
/// so a branch is treated as able to take both successors, and a variable
/// assigned on one predecessor of a join but not another is *not* available at
/// the join. Both choices fail toward silence rather than rejecting a flow the
/// runner would have executed.
fn reject_uninitialized_reads(spec: &FlowSpec) -> Result<(), BotError> {
    let universe: BTreeSet<String> = spec.vars.keys().cloned().collect();
    let mut available: BTreeMap<NodeId, BTreeSet<String>> = spec
        .nodes
        .keys()
        .map(|node_id| (node_id.clone(), universe.clone()))
        .collect();
    available.insert(spec.entry.clone(), BTreeSet::new());

    let mut pending: VecDeque<NodeId> = spec.nodes.keys().cloned().collect();
    while let Some(node_id) = pending.pop_front() {
        let Some(kind) = spec.nodes.get(&node_id) else {
            continue;
        };
        let Some(incoming) = available.get(&node_id).cloned() else {
            continue;
        };
        let mut outgoing = incoming;
        if let NodeKind::Ask { ref var, .. } = *kind {
            outgoing.insert(var.clone());
        }
        for target in successor_targets(spec, &node_id, kind) {
            let Some(state) = available.get_mut(&target) else {
                continue;
            };
            let before = state.len();
            state.retain(|name| outgoing.contains(name));
            if state.len() != before {
                pending.push_back(target);
            }
        }
    }

    for (node_id, kind) in &spec.nodes {
        let Some(state) = available.get(node_id) else {
            continue;
        };
        for name in node_reads(spec, node_id, kind)? {
            if !state.contains(&name) {
                let refusal = Err(BotError::VariableReadBeforeInit {
                    node: node_id.clone(),
                    name,
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "reject_uninitialized_reads: returning an error to the caller");
                return refusal;
            }
        }
    }
    Ok(())
}

/// Collect every variable a node reads when it executes.
///
/// "Reads" means the references the executor actually resolves, not every name
/// a node mentions. [`NodeKind::Branch`] is the case that separates the two:
/// its `var` field is documented as the branch subject, but the executor
/// destructures `when` alone and never resolves `var` against the scope, so a
/// branch subject that some path leaves unassigned cannot fail a run and is
/// not counted here. The predicate's own [`ValueExpr::Var`] references are
/// where a branch reads, and they are counted.
///
/// Only declared names are returned. An undeclared one is already
/// [`BotError::UndeclaredVariable`] from `validate_node`, which runs first, so
/// the definite-assignment pass cannot preempt it with a second verdict on the
/// same defect.
fn node_reads(
    spec: &FlowSpec,
    node_id: &str,
    kind: &NodeKind,
) -> Result<BTreeSet<String>, BotError> {
    match *kind {
        NodeKind::Say { ref text } => declared_template_reads(spec, node_id, text, "say.text"),
        NodeKind::Refer { ref text, .. } => {
            declared_template_reads(spec, node_id, text, "refer.text")
        }
        NodeKind::Branch { ref when, .. } => {
            let mut names = BTreeSet::new();
            collect_predicate_variables(when, &mut names);
            names.retain(|name| spec.vars.contains_key(name));
            Ok(names)
        }
        NodeKind::Ask { .. }
        | NodeKind::Handoff { .. }
        | NodeKind::Route { .. }
        | NodeKind::End => Ok(BTreeSet::new()),
    }
}

/// Compiles `text`, attributing a malformed template to the node and field it
/// was reached through.
///
/// `compile` refuses with `MalformedTemplate` naming the placeholder
/// `"<runtime>"`, because it does not know its caller. The only thing this adds
/// is which node and field it was reached through, so the match is on the
/// variant rather than a map that would discard it: there is no detail in the
/// cause to keep, and a map would read as though there were.
fn compile_for_node<'a>(
    node_id: &str,
    field: &'static str,
    text: &'a str,
) -> Result<CompiledTemplate<'a>, BotError> {
    match CompiledTemplate::compile(text) {
        Ok(compiled) => Ok(compiled),
        Err(BotError::MalformedTemplate { .. }) => {
            let refusal = Err(BotError::MalformedTemplate {
                node: node_id.to_owned(),
                field,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), node = node_id, field, "compile_for_node: the template is malformed");
            refusal
        }
        Err(other) => {
            lgwks_std::trace::debug!(error = ?other, node = node_id, field, "compile_for_node: the template did not compile");
            Err(other)
        }
    }
}

/// Looks `name` up in `scope`, refusing with [`BotError::VariableUnset`] when it
/// holds no value.
///
/// One place for the refusal both the sizing pass and the render pass make, so a
/// marker with no value reads the same whichever of the two reached it first.
fn bound<'s>(scope: &'s VarScope, name: &str) -> Result<&'s Value, BotError> {
    match scope.get(name) {
        Some(value) => Ok(value),
        None => {
            let refusal = Err(BotError::VariableUnset {
                name: name.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), name, "bound: the marker has no value");
            refusal
        }
    }
}

/// Return the declared variables a template interpolates.
fn declared_template_reads(
    spec: &FlowSpec,
    node_id: &str,
    text: &str,
    field: &'static str,
) -> Result<BTreeSet<String>, BotError> {
    let compiled = compile_for_node(node_id, field, text)?;
    let mut names = BTreeSet::new();
    for part in compiled.parts() {
        if let TemplatePart::Variable(name) = *part
            && spec.vars.contains_key(name)
        {
            names.insert(name.to_owned());
        }
    }
    Ok(names)
}

/// The two operands of a comparison predicate, or `None` for anything else.
///
/// Every comparison — `Eq`, `Ne`, `Lt`, `Le`, `Gt`, `Ge` — binds the same two
/// operands and nothing else, and two walks over a predicate (the one that
/// collects its variables and the one that validates them) have to agree on
/// which variants those are. They read the list from here instead of each
/// restating six variants, which is how a new comparison would be collected by
/// one and skipped by the other.
fn comparison_operands(predicate: &Predicate) -> Option<(&ValueExpr, &ValueExpr)> {
    match *predicate {
        Predicate::Eq(ref left, ref right)
        | Predicate::Ne(ref left, ref right)
        | Predicate::Lt(ref left, ref right)
        | Predicate::Le(ref left, ref right)
        | Predicate::Gt(ref left, ref right)
        | Predicate::Ge(ref left, ref right) => Some((left, right)),
        Predicate::Const(_) | Predicate::And(_) | Predicate::Or(_) | Predicate::Not(_) => None,
    }
}

/// Collect the variable references of a predicate expression.
fn collect_predicate_variables(predicate: &Predicate, into: &mut BTreeSet<String>) {
    if let Some((left, right)) = comparison_operands(predicate) {
        collect_expr_variables(left, into);
        collect_expr_variables(right, into);
    } else {
        match *predicate {
            Predicate::Const(_) => {}
            Predicate::And(ref items) | Predicate::Or(ref items) => {
                for item in items {
                    collect_predicate_variables(item, into);
                }
            }
            Predicate::Not(ref inner) => collect_predicate_variables(inner, into),
            // Every comparison was taken above, and `comparison_operands` names
            // all six, so this arm can only be reached if that list and this
            // match have drifted apart — which is the point of naming it there.
            Predicate::Eq(..)
            | Predicate::Ne(..)
            | Predicate::Lt(..)
            | Predicate::Le(..)
            | Predicate::Gt(..)
            | Predicate::Ge(..) => {}
        }
    }
}

/// Collect the variable references of one predicate operand.
fn collect_expr_variables(expression: &ValueExpr, into: &mut BTreeSet<String>) {
    if let ValueExpr::Var(ref name) = *expression {
        into.insert(name.clone());
    }
}

/// Validate variable declaration names and choice contents.
fn validate_declarations(vars: &BTreeMap<String, VarType>) -> Result<(), BotError> {
    for (name, kind) in vars {
        if !valid_identifier(name) {
            let refusal = Err(BotError::MalformedFlow {
                cause: format!("invalid variable name {name:?}"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_declarations: returning an error to the caller");
            return refusal;
        }
        match *kind {
            VarType::Choice(ref options)
                if options.is_empty() || has_duplicate_strings(options) =>
            {
                let refusal = Err(BotError::MalformedFlow {
                    cause: format!("choice variable {name:?} has invalid options"),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_declarations: returning an error to the caller");
                return refusal;
            }
            _ => {}
        }
    }
    Ok(())
}

/// Validate one terminal declaration and its node kind.
///
/// Two invariants, and the second is the one that was missing: a declaration
/// must name a terminal node, and on a node whose kind already fixes the
/// outcome it must not contradict it. `End` completes with nothing said about
/// where the person goes, so every declared outcome is a genuine override and
/// is accepted. A `Handoff` or `Refer` node already names its target, so a
/// declaration of a different outcome — or of the same kind aimed somewhere
/// else — is an authoring contradiction between two statements in one
/// document, and refusing it is the only reading that cannot be wrong. A
/// declaration that repeats the node's own outcome is accepted; it is then
/// read by [`FlowSpec::effective_terminal`] rather than ignored.
fn validate_terminals(spec: &FlowSpec) -> Result<(), BotError> {
    for (node_id, declared) in &spec.terminals {
        let Some(kind) = spec.nodes.get(node_id) else {
            let refusal = Err(BotError::InvalidTransitionTarget {
                from: "<terminal>".into(),
                target: node_id.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_terminals: returning an error to the caller");
            return refusal;
        };
        if !matches!(
            *kind,
            NodeKind::End | NodeKind::Handoff { .. } | NodeKind::Refer { .. }
        ) {
            let refusal = Err(BotError::MalformedFlow {
                cause: format!("terminal declaration {node_id:?} names a non-terminal node"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_terminals: returning an error to the caller");
            return refusal;
        }
        // `End` has an intrinsic outcome too, but it is `Completed` — the
        // absence of a destination rather than a claim about one — so a
        // declaration replaces it instead of conflicting with it. Only the two
        // node kinds that name a target can be contradicted.
        if matches!(*kind, NodeKind::End) {
            continue;
        }
        let Some(intrinsic) = spec.intrinsic_terminal(node_id) else {
            // Unreachable on a validated document: the kind was just checked to
            // be one of the three terminal kinds, and every one of them has an
            // intrinsic outcome. Reported rather than skipped so a future node
            // kind added to the check above cannot silently lose the rule.
            let refusal = Err(BotError::MalformedFlow {
                cause: format!("terminal declaration {node_id:?} has no intrinsic outcome"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_terminals: returning an error to the caller");
            return refusal;
        };
        if intrinsic != *declared {
            let refusal = Err(BotError::ConflictingTerminalDeclaration {
                node: node_id.clone(),
                intrinsic,
                declared: declared.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_terminals: returning an error to the caller");
            return refusal;
        }
    }
    Ok(())
}

/// Validates one node's references, variables, and text.
///
/// The two kinds this skips are `handoff` and `end`, which carry no text, no
/// variable and no edge to resolve: there is nothing about them that a load-time
/// check could refuse. That is a claim about the kinds, so it is stated here
/// rather than left as two empty arms inside the dispatch.
///
/// One call rather than a `match` of seven: every arm was a single validator
/// call, which is the right shape for the reader and the wrong shape for a gate
/// that reads the whole `match` as one statement.
fn validate_node(
    spec: &FlowSpec,
    node_id: &str,
    kind: &NodeKind,
    limits: ResourceLimits,
    writers: &mut BTreeSet<String>,
) -> Result<(), BotError> {
    match *kind {
        NodeKind::Say { ref text } => validate_say_node(spec, node_id, text, limits),
        NodeKind::Ask {
            ref var,
            ref options,
            ref routes,
        } => validate_ask_node(spec, node_id, var, options, routes, limits, writers),
        NodeKind::Branch {
            ref var,
            ref when,
            ref then,
            ref otherwise,
        } => validate_branch_node(spec, node_id, var, when, then, otherwise),
        NodeKind::Refer { ref text, .. } => validate_refer_node(spec, node_id, text, limits),
        NodeKind::Route {
            ref dispatch,
            ref fallback,
        } => {
            check_target(&spec.nodes, node_id, dispatch)?;
            check_target(&spec.nodes, node_id, fallback)
        }
        NodeKind::Handoff { .. } | NodeKind::End => Ok(()),
    }
}

/// Returns how answers writing `name` are read in `spec`.
///
/// The flow's own reading of a node's answers, so validation and resolution
/// cannot disagree about which policy a question is under — the same reason
/// there is one decoder rather than two.
fn answer_domain_of(spec: &FlowSpec, name: &str) -> AnswerDomain {
    spec.vars
        .get(name)
        .map_or(AnswerDomain::Label, VarType::answer_domain)
}

/// Returns the first pair of options the answer policy cannot tell apart.
///
/// `None` under [`AnswerDomain::Integer`] for an option that is not a whole
/// number: an option that cannot produce the declared value is a different
/// defect, owned by the check that reports it, and folding it into a collision
/// report would name the wrong cause.
fn colliding_options(options: &[String], domain: AnswerDomain) -> Option<(String, String)> {
    let mut seen: BTreeMap<String, String> = BTreeMap::new();
    for option in options {
        let identity = match domain {
            AnswerDomain::Label => crate::language::normalize(option),
            AnswerDomain::Integer => match decode_integer(option) {
                Some(value) => value.to_string(),
                None => continue,
            },
        };
        if let Some(first) = seen.get(&identity) {
            return Some((first.clone(), option.clone()));
        }
        seen.insert(identity, option.clone());
    }
    None
}

/// Validate a variable reference in a node.
fn validate_variable_reference(spec: &FlowSpec, node_id: &str, name: &str) -> Result<(), BotError> {
    if spec.vars.contains_key(name) {
        Ok(())
    } else {
        let _ = node_id;
        Err(BotError::UndeclaredVariable {
            name: name.to_owned(),
        })
    }
}

/// Resolve a variable's declared type, refusing an undeclared name.
fn declared_variable<'a>(spec: &'a FlowSpec, name: &str) -> Result<&'a VarType, BotError> {
    spec.vars
        .get(name)
        .ok_or_else(|| BotError::UndeclaredVariable {
            name: name.to_owned(),
        })
}

/// Validate a predicate's variable references and non-empty boolean lists.
fn validate_predicate(
    spec: &FlowSpec,
    node_id: &str,
    predicate: &Predicate,
) -> Result<(), BotError> {
    if let Some((left, right)) = comparison_operands(predicate) {
        validate_expr(spec, node_id, left)?;
        return validate_expr(spec, node_id, right);
    }
    match *predicate {
        Predicate::Const(_) => Ok(()),
        Predicate::And(ref items) | Predicate::Or(ref items) => {
            if items.is_empty() {
                let refusal = Err(BotError::MalformedFlow {
                    cause: format!("node {node_id:?} has an empty predicate"),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_predicate: returning an error to the caller");
                return refusal;
            }
            for item in items {
                validate_predicate(spec, node_id, item)?;
            }
            Ok(())
        }
        Predicate::Not(ref inner) => validate_predicate(spec, node_id, inner),
        // Every comparison returned above, through the one list of them.
        Predicate::Eq(..)
        | Predicate::Ne(..)
        | Predicate::Lt(..)
        | Predicate::Le(..)
        | Predicate::Gt(..)
        | Predicate::Ge(..) => Ok(()),
    }
}

/// Validate one predicate expression.
fn validate_expr(spec: &FlowSpec, _node_id: &str, expression: &ValueExpr) -> Result<(), BotError> {
    if let ValueExpr::Var(ref name) = *expression
        && !spec.vars.contains_key(name)
    {
        let refusal = Err(BotError::UndeclaredVariable { name: name.clone() });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_expr: returning an error to the caller");
        return refusal;
    }
    Ok(())
}

/// Validate one template's syntax, its declared names, and its static floor.
///
/// The floor is the part of the expansion that is known without running the
/// flow: the literal bytes, which every render must contain whatever the
/// variables turn out to hold. A template whose literals alone exceed the
/// record ceiling can never render, so it is refused here rather than at the
/// node that would speak it. That is the only static size claim available —
/// the rest of the expansion depends on answers this cannot see — and it is
/// exactly the claim that is true unconditionally.
fn validate_template(
    spec: &FlowSpec,
    node_id: &str,
    template: &str,
    field: &'static str,
    limits: ResourceLimits,
) -> Result<(), BotError> {
    let compiled = compile_for_node(node_id, field, template)?;
    let mut literals = 0usize;
    for part in compiled.parts() {
        match *part {
            TemplatePart::Literal(text) => {
                literals = literals.checked_add(text.len()).ok_or(
                    BotError::TemplateExpansionTooLarge {
                        node: node_id.to_owned(),
                        bytes: usize::MAX,
                        limit: limits.get(ResourceAxis::Record),
                    },
                )?;
            }
            TemplatePart::Variable(name) => {
                if !spec.vars.contains_key(name) {
                    let refusal = Err(BotError::UndeclaredVariable {
                        name: name.to_owned(),
                    });
                    lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_template: returning an error to the caller");
                    return refusal;
                }
            }
        }
    }
    let record_bytes = limits.get(ResourceAxis::Record);
    if literals > record_bytes {
        let refusal = Err(BotError::TemplateExpansionTooLarge {
            node: node_id.to_owned(),
            bytes: literals,
            limit: record_bytes,
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "validate_template: returning an error to the caller");
        return refusal;
    }
    Ok(())
}

/// Validate that one target node exists.
fn check_target(
    nodes: &BTreeMap<NodeId, NodeKind>,
    from: &str,
    target: &str,
) -> Result<(), BotError> {
    if nodes.contains_key(target) {
        Ok(())
    } else {
        Err(BotError::InvalidTransitionTarget {
            from: from.to_owned(),
            target: target.to_owned(),
        })
    }
}

/// Reject a graph node that cannot be reached from the entry.
fn reject_unreachable(spec: &FlowSpec) -> Result<(), BotError> {
    let mut seen = BTreeSet::new();
    let mut pending = VecDeque::from([spec.entry.clone()]);
    while let Some(node_id) = pending.pop_front() {
        if !seen.insert(node_id.clone()) {
            continue;
        }
        let Some(kind) = spec.nodes.get(&node_id) else {
            continue;
        };
        for target in successor_targets(spec, &node_id, kind) {
            if !seen.contains(&target) {
                pending.push_back(target);
            }
        }
    }
    for node_id in spec.nodes.keys() {
        if !seen.contains(node_id) {
            let refusal = Err(BotError::UnreachableNode {
                node: node_id.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "reject_unreachable: returning an error to the caller");
            return refusal;
        }
    }
    Ok(())
}

/// Collect every statically possible destination from one node.
fn successor_targets(spec: &FlowSpec, node_id: &str, kind: &NodeKind) -> Vec<NodeId> {
    let mut targets = spec.edge_targets(node_id);
    match *kind {
        NodeKind::Ask { ref routes, .. } => targets.extend(routes.values().cloned()),
        NodeKind::Branch {
            ref then,
            ref otherwise,
            ..
        } => {
            targets.push(then.clone());
            targets.push(otherwise.clone());
        }
        NodeKind::Route {
            ref dispatch,
            ref fallback,
        } => {
            targets.push(dispatch.clone());
            targets.push(fallback.clone());
        }
        NodeKind::Say { .. }
        | NodeKind::Handoff { .. }
        | NodeKind::Refer { .. }
        | NodeKind::End => {}
    }
    targets
}

/// Reject repeated strings in a finite declaration.
fn has_duplicate_strings(values: &[String]) -> bool {
    let mut seen = BTreeSet::new();
    values.iter().any(|value| !seen.insert(value))
}

/// Return whether a variable or node id uses the supported identifier shape.
fn valid_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == '_')
        && chars.all(|character| character.is_ascii_alphanumeric() || character == '_')
}

/// Decode `text` as JSON, with the decoder's diagnostic as a string.
fn parse_json<T>(text: &str) -> Result<T, String>
where
    T: serde::de::DeserializeOwned,
{
    crate::json::from_str(text).map_err(|error| error.to_string())
}

/// Decode `text` as RON, with the decoder's diagnostic as a string.
fn parse_ron<T>(text: &str) -> Result<T, String>
where
    T: serde::de::DeserializeOwned,
{
    lgwks_std::ron::from_str(text).map_err(|error| error.to_string())
}

/// Refuse an oversized document before a decoder walks it.
///
/// Every notation is measured the same way, so a document cannot be too large
/// in one and acceptable in another.
fn check_flow_size(source: &str) -> Result<(), BotError> {
    if source.len() > MAX_FLOW_BYTES {
        let refusal = Err(BotError::FlowTooLarge {
            bytes: source.len(),
            limit: MAX_FLOW_BYTES,
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "check_flow_size: returning an error to the caller");
        return refusal;
    }
    Ok(())
}

/// A decoder failure, as a typed flow error.
///
/// The diagnostic is escaped before it is stored. A document is untrusted
/// input, and a raw newline or escape in one would otherwise forge lines in
/// whatever log line ends up carrying the refusal.
fn malformed_flow(error: impl std::fmt::Display) -> BotError {
    BotError::MalformedFlow {
        cause: error.to_string().escape_debug().to_string(),
    }
}

/// Reject unknown tagged node kinds before serde turns them into a generic
/// malformed-document diagnostic.
fn reject_unknown_node_kinds(declared: &BTreeMap<String, String>) -> Result<(), BotError> {
    for (node_id, kind) in declared {
        if !matches!(
            kind.as_str(),
            "say" | "ask" | "branch" | "handoff" | "refer" | "route" | "end"
        ) {
            let refusal = Err(BotError::UnknownNodeKind {
                node: node_id.clone(),
                kind: kind.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "reject_unknown_node_kinds: returning an error to the caller");
            return refusal;
        }
    }
    Ok(())
}

/// The node kinds a document declares, keyed by node id.
///
/// Both notations decode into this, so the guard is written once rather than
/// once per notation. It exists because the guard has to read a variant's name
/// before the flow's own types have accepted it: by the time `FlowSpec` refuses
/// an unknown kind, serde has already discarded which node carried it.
///
/// The name is `FlowSpec` because RON enforces a struct's name: a document
/// written `FlowSpec(..)` is refused by a type that calls itself anything else,
/// so a guard named after itself would read no document at all and would report
/// silence, which is indistinguishable from finding nothing wrong. Every other
/// field of the document is ignored here, which is serde's default.
#[derive(Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename = "FlowSpec")]
struct DeclaredNodes<const FIELDED: bool> {
    /// Every node's declared kind. Absent or empty is not this guard's
    /// business; the flow's own validation refuses an empty node map.
    #[serde(default)]
    nodes: BTreeMap<String, VariantName<FIELDED>>,
}

/// A variant's name, read through serde's enum path.
///
/// The enum path is the only one that carries the name: RON writes a unit
/// variant as a bare identifier, and asking the decoder for `Any` hands back a
/// nameless unit, so the name reaches a reader only as a variant name.
///
/// `FIELDED` is which of serde's two variant accessors to read the content
/// with. A unit variant must be consumed as a unit and a variant carrying
/// anything must not, serde offers no way to ask which a given variant is, and
/// guessing wrong fails the decode rather than reading the name. So both are
/// attempted: this is the only place the flow's types are not the authority on
/// their own shape, and the cost is one extra decode of a document already
/// capped at [`MAX_FLOW_BYTES`].
struct VariantName<const FIELDED: bool>(String);

impl<'de, const FIELDED: bool> Deserialize<'de> for VariantName<FIELDED> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// Reads a variant's name and discards whatever it carries.
        struct NameVisitor<const FIELDED: bool>;

        impl<'de, const FIELDED: bool> serde::de::Visitor<'de> for NameVisitor<FIELDED> {
            type Value = VariantName<FIELDED>;

            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                formatter.write_str("a node kind")
            }

            fn visit_enum<A>(self, data: A) -> Result<VariantName<FIELDED>, A::Error>
            where
                A: serde::de::EnumAccess<'de>,
            {
                use serde::de::VariantAccess;

                let (name, variant) = data.variant::<String>()?;
                if FIELDED {
                    variant.newtype_variant::<serde::de::IgnoredAny>()?;
                } else {
                    variant.unit_variant()?;
                }
                Ok(VariantName(name))
            }
        }

        deserializer.deserialize_enum("NodeKind", &[], NameVisitor::<FIELDED>)
    }
}

/// Merge what two shape-specific decodes of one document read.
///
/// A document holds unit variants and fielded ones at once, and serde reads a
/// variant's content through one accessor and not the other, so the guard
/// decodes the document once per shape and combines the results. A shape that
/// does not decode contributes nothing rather than failing the guard: a
/// document of only unit variants is exactly the case the fielded attempt
/// cannot read, and it is not an error. When neither shape reads, the guard has
/// no names to check and stays quiet, leaving the flow's own refusal to speak.
fn merge_read_kinds<const FIRST: bool, const SECOND: bool>(
    first: Result<DeclaredNodes<FIRST>, String>,
    second: Result<DeclaredNodes<SECOND>, String>,
) -> BTreeMap<String, String> {
    let mut merged = BTreeMap::new();
    if let Ok(declared) = first {
        for (node_id, name) in declared.nodes {
            merged.insert(node_id, name.0);
        }
    }
    if let Ok(declared) = second {
        for (node_id, name) in declared.nodes {
            merged.insert(node_id, name.0);
        }
    }
    merged
}

/// Named, typed variable declarations and their assigned values.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VarScope {
    /// Declared variable types.
    declarations: BTreeMap<String, VarType>,
    /// Values assigned by accepted answers.
    values: BTreeMap<String, Value>,
}

impl VarScope {
    /// Construct an empty-value scope from declarations.
    pub fn new(declarations: BTreeMap<String, VarType>) -> Result<Self, BotError> {
        validate_declarations(&declarations)?;
        Ok(Self {
            declarations,
            values: BTreeMap::new(),
        })
    }

    /// Return the declared variable types.
    #[must_use]
    pub fn declarations(&self) -> &BTreeMap<String, VarType> {
        &self.declarations
    }

    /// Returns how an answer writing `name` must be read.
    ///
    /// Defaults to [`AnswerDomain::Label`] for a name that is not declared,
    /// which is the permissive reading rather than a silent claim: flow
    /// validation rejects an undeclared writer, so reaching this with an unknown
    /// name is a caller's mistake and not a question about the answer.
    #[must_use]
    pub fn answer_domain(&self, name: &str) -> AnswerDomain {
        self.declarations
            .get(name)
            .map_or(AnswerDomain::Label, VarType::answer_domain)
    }

    /// Return all currently assigned values.
    #[must_use]
    pub fn values(&self) -> &BTreeMap<String, Value> {
        &self.values
    }

    /// Return one assigned value, if the variable has been written.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&Value> {
        self.values.get(name)
    }

    /// Assign a typed value after checking its declaration.
    pub fn set(&mut self, name: &str, value: Value) -> Result<(), BotError> {
        let Some(declared) = self.declarations.get(name) else {
            let refusal = Err(BotError::UndeclaredVariable {
                name: name.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "set: returning an error to the caller");
            return refusal;
        };
        if value_matches_type(declared, &value) {
            self.values.insert(name.to_owned(), value);
            Ok(())
        } else {
            Err(BotError::VariableTypeMismatch {
                name: name.to_owned(),
            })
        }
    }

    /// Parse and assign an answer according to the variable declaration.
    ///
    /// Runs [`VarType::decode_answer`], the same decoder flow validation runs
    /// over every ask candidate. For a validated flow the decode cannot fail:
    /// the candidate that reaches here is one validation already accepted. It
    /// stays a `Result` because this method is public and a caller may hold a
    /// scope that no `FlowSpec` validated.
    pub fn set_from_answer(&mut self, name: &str, answer: &str) -> Result<(), BotError> {
        self.set_from_answer_within(name, answer, MAX_VALUE_BYTES)
    }

    /// Parse and assign an answer under an explicit value ceiling.
    ///
    /// The decoder and the store, plus the third step a session needs: the
    /// value has to fit. Sizing happens between decoding and storing, so a
    /// candidate that decodes is refused before the scope holds it — which is
    /// what keeps "accepted" and "retained" the same word.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::InvalidVariableValue`] for an answer the declared
    /// type cannot hold, and [`BotError::ValueTooLarge`] for one that decodes
    /// to a value wider than `value_bytes`.
    pub fn set_from_answer_within(
        &mut self,
        name: &str,
        answer: &str,
        value_bytes: usize,
    ) -> Result<(), BotError> {
        let Some(declared) = self.declarations.get(name) else {
            let refusal = Err(BotError::UndeclaredVariable {
                name: name.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "set_from_answer_within: returning an error to the caller");
            return refusal;
        };
        // One decoder, not two: `VarType::decode_answer` is the same reading of
        // an answer that flow validation runs, so a value this store accepts is
        // a value the declaration would have accepted. The rejection is carried
        // into the error rather than dropped: the scope's contract is one
        // "cannot hold this" error, and naming *why* keeps a caller from having
        // to guess between a non-integer, an out-of-range integer, a bad boolean
        // and an undeclared choice.
        let value =
            declared
                .decode_answer(answer)
                .map_err(|rejection| BotError::InvalidVariableValue {
                    variable: name.to_owned(),
                    value: answer.to_owned(),
                    reason: rejection.to_string(),
                })?;
        let bytes = value.rendered_bytes();
        if bytes > value_bytes {
            let refusal = Err(BotError::ValueTooLarge {
                variable: name.to_owned(),
                bytes,
                limit: value_bytes,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "set_from_answer_within: returning an error to the caller");
            return refusal;
        }
        self.set(name, value)
    }

    /// Interpolate `${name}` markers using the assigned values, under the
    /// operator's shipped record ceiling.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::MalformedTemplate`] for invalid syntax,
    /// [`BotError::VariableUnset`] for an unresolved marker, and
    /// [`BotError::TemplateExpansionTooLarge`] past the ceiling.
    pub fn interpolate(&self, template: &str) -> Result<String, BotError> {
        self.interpolate_within(template, MAX_RECORD_BYTES)
    }

    /// Interpolate `${name}` markers under an explicit byte ceiling.
    ///
    /// A scope on its own has no session behind it, so the ceiling is an
    /// argument. The expansion is sized before it is allocated and refused
    /// rather than truncated: a truncated record would be a record the journal
    /// claims happened and that nobody can read.
    ///
    /// # Errors
    ///
    /// As [`Self::interpolate`], with `record_bytes` in place of the shipped
    /// ceiling.
    pub fn interpolate_within(
        &self,
        template: &str,
        record_bytes: usize,
    ) -> Result<String, BotError> {
        TemplateInterpolator::new().interpolate(template, self, "<scope>", record_bytes)
    }
}

/// Check one scalar against its declared type.
fn value_matches_type(declared: &VarType, value: &Value) -> bool {
    match *declared {
        VarType::String => matches!(value, &Value::String(_)),
        VarType::Integer => matches!(value, &Value::Integer(_)),
        VarType::Boolean => matches!(value, &Value::Boolean(_)),
        VarType::Choice(ref options) => match *value {
            Value::Choice(ref value) => options.contains(value),
            _ => false,
        },
    }
}

/// One compiled piece of a template.
///
/// Borrowed from the document rather than owned: a compiled template is a
/// second view of bytes that are already resident, and copying them would make
/// compiling cost what the expansion costs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TemplatePart<'a> {
    /// Text copied to the output unchanged.
    Literal(&'a str),
    /// A `${name}` marker replaced by the scope's value for `name`.
    Variable(&'a str),
}

/// A template compiled once into literal and variable parts.
///
/// Compilation is the step that makes a byte ceiling enforceable before
/// allocation. The parts are the template's placeholders resolved to nothing
/// but the names they mention, so the expanded size of the whole is one
/// addition per part, computed with checked arithmetic
/// ([`Self::expanded_bytes`]) and compared with the caller's ceiling *before*
/// [`Self::render`] allocates the output. Rendering an unbounded expansion to
/// find out that it is unbounded is exactly the failure this ordering removes.
///
/// # Examples
///
/// ```
/// use lgwks_bot::{CompiledTemplate, VarScope};
/// use std::collections::BTreeMap;
///
/// let scope = VarScope::new(BTreeMap::new())?;
/// let compiled = CompiledTemplate::compile("hello ${name}")?;
/// assert_eq!(compiled.parts().len(), 2);
/// // The name has no value, so the size cannot be known yet.
/// assert!(compiled.expanded_bytes(&scope).is_err());
/// # Ok::<(), lgwks_bot::BotError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CompiledTemplate<'a> {
    /// Literal and variable parts in source order.
    parts: Vec<TemplatePart<'a>>,
}

impl<'a> CompiledTemplate<'a> {
    /// Compile `${name}` markers into parts.
    ///
    /// The one template parser: the loader's template check uses it to confirm
    /// every marker names a declared variable, and the interpolator uses it to
    /// size and render. A second scanner would be a second grammar.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::MalformedTemplate`] for an unterminated marker or a
    /// name that is not an identifier.
    pub fn compile(template: &'a str) -> Result<Self, BotError> {
        let mut parts = Vec::new();
        let mut cursor = 0;
        while let Some(relative_start) = template[cursor..].find("${") {
            let start = cursor.saturating_add(relative_start);
            if start > cursor {
                parts.push(TemplatePart::Literal(&template[cursor..start]));
            }
            let name_start = start.saturating_add(2);
            let Some(relative_end) = template[name_start..].find('}') else {
                let refusal = Err(BotError::MalformedTemplate {
                    node: "<runtime>".into(),
                    field: "template",
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "compile: returning an error to the caller");
                return refusal;
            };
            let end = name_start.saturating_add(relative_end);
            let name = &template[name_start..end];
            if !valid_identifier(name) {
                let refusal = Err(BotError::MalformedTemplate {
                    node: "<runtime>".into(),
                    field: "template",
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "compile: returning an error to the caller");
                return refusal;
            }
            parts.push(TemplatePart::Variable(name));
            cursor = end.saturating_add(1);
        }
        if cursor < template.len() {
            parts.push(TemplatePart::Literal(&template[cursor..]));
        }
        Ok(Self { parts })
    }

    /// Return the compiled parts in source order.
    #[must_use]
    pub fn parts(&self) -> &[TemplatePart<'a>] {
        &self.parts
    }

    /// The exact number of bytes this template expands to under `scope`.
    ///
    /// Exact, and computed before any output is allocated. Every part
    /// contributes a known count, so the total is a checked sum and cannot
    /// overflow into a small number that would pass a ceiling it should fail.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::VariableUnset`] for a marker with no value, or
    /// [`BotError::TemplateExpansionTooLarge`] with `bytes` of [`usize::MAX`]
    /// if the sum overflows, which no real expansion can and which is reported
    /// rather than wrapped.
    pub fn expanded_bytes(&self, scope: &VarScope) -> Result<usize, BotError> {
        let mut total = 0usize;
        for part in &self.parts {
            let bytes = match *part {
                TemplatePart::Literal(text) => text.len(),
                TemplatePart::Variable(name) => bound(scope, name)?.rendered_bytes(),
            };
            total = total
                .checked_add(bytes)
                .ok_or(BotError::TemplateExpansionTooLarge {
                    node: "<runtime>".into(),
                    bytes: usize::MAX,
                    limit: usize::MAX,
                })?;
        }
        Ok(total)
    }

    /// Render the template into a new string.
    ///
    /// Allocates exactly [`Self::expanded_bytes`] and cannot fail where that
    /// did not: every marker was resolved during sizing, and the values are
    /// re-read from the same scope. Callers with a ceiling call
    /// [`Self::expanded_bytes`] first — [`Interpolate::interpolate`] is that
    /// caller — so the refusal happens before this runs rather than after it
    /// has produced the text it was supposed to avoid producing.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::VariableUnset`] if a value disappeared between
    /// sizing and rendering. A scope is not mutated during a render, so this is
    /// reachable only through a caller that interleaves the two.
    pub fn render(&self, scope: &VarScope) -> Result<String, BotError> {
        let mut output = String::new();
        for part in &self.parts {
            match *part {
                TemplatePart::Literal(text) => output.push_str(text),
                TemplatePart::Variable(name) => {
                    output.push_str(&bound(scope, name)?.to_string());
                }
            }
        }
        Ok(output)
    }
}

/// One question's candidate vocabulary, as the resolver seam sees it.
///
/// A resolver is handed three things and a slice of options is only two of
/// them: what the person typed, the options in front of them, and the *identity
/// of the question* those options belong to. The identity is not decoration. A
/// learned alias is a confirmed fact about a question — *in this question, "the
/// usual" means "Repeat last order"* — and a slice of strings is not a question:
/// the same slice can appear in two different questions, and the same question
/// offers a *different* slice after an edit or a reorder. Carrying the identity
/// alongside the options is what lets a confirmation follow its option to a new
/// position, and refuse to follow whatever occupies its old one.
///
/// Borrowed rather than owned, because the caller already holds both: an owned
/// copy would be a second copy of the same fact, and two copies of a fact drift.
///
/// The third fact is how the answers are read. [`AnswerDomain`] travels with the
/// options because it is a property of *this* question, and a resolver that had
/// to infer it from the option strings would be guessing: the same list is two
/// distinct answers at an integer question and one folded answer at a label
/// question.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Question<'a> {
    /// Stable identity of the question. In a flow this is the ask node id.
    id: &'a str,
    /// The options offered right now.
    options: &'a [String],
    /// How this question's answers are meant to be read.
    domain: AnswerDomain,
}

impl<'a> Question<'a> {
    /// Names one question's vocabulary, read as natural-language labels.
    #[must_use]
    pub const fn new(id: &'a str, options: &'a [String]) -> Self {
        Self {
            id,
            options,
            domain: AnswerDomain::Label,
        }
    }

    /// Reads this question's answers under `domain`.
    ///
    /// A builder rather than a fourth argument on [`Self::new`], because the
    /// overwhelming majority of questions are label questions and a resolver
    /// call site should not have to spell that out. The default is the one the
    /// option strings are written in; a caller that has a typed variable in hand
    /// has the one fact that changes it.
    #[must_use]
    pub const fn with_domain(self, domain: AnswerDomain) -> Self {
        Self { domain, ..self }
    }

    /// Returns the question's stable identity.
    #[must_use]
    pub const fn id(&self) -> &'a str {
        self.id
    }

    /// Returns the options offered right now.
    #[must_use]
    pub const fn options(&self) -> &'a [String] {
        self.options
    }

    /// Returns how this question's answers are meant to be read.
    #[must_use]
    pub const fn domain(&self) -> AnswerDomain {
        self.domain
    }
}

/// Interpolation seam for replacing the template engine later.
pub trait Interpolate {
    /// Expand `${name}` markers using the supplied scope, refusing an
    /// expansion larger than `limit` bytes.
    ///
    /// `limit` is a parameter rather than a property of the interpolator
    /// because the ceiling is the session's, not the engine's: the same
    /// interpolator serves a scope with the shipped ceiling and a session with
    /// a tighter one. `node` names the flow node the template came from and is
    /// carried into the refusal, which is what makes an oversized expansion
    /// attributable to the line that caused it.
    ///
    /// Implementations must check the size *before* allocating the output.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::MalformedTemplate`] for invalid syntax,
    /// [`BotError::VariableUnset`] for an unresolved marker, and
    /// [`BotError::TemplateExpansionTooLarge`] for an expansion over `limit`.
    fn interpolate(
        &self,
        template: &str,
        scope: &VarScope,
        node: &str,
        limit: usize,
    ) -> Result<String, BotError>;
}

/// The shipped bounded interpolation implementation.
///
/// Allocation-bounded in the strict sense: the expanded byte count is computed
/// from the compiled template and refused when it exceeds the caller's ceiling,
/// so the output buffer this creates is never larger than that ceiling no
/// matter how many times a placeholder repeats.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct TemplateInterpolator;

impl TemplateInterpolator {
    /// Construct the default interpolator.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl Interpolate for TemplateInterpolator {
    fn interpolate(
        &self,
        template: &str,
        scope: &VarScope,
        node: &str,
        limit: usize,
    ) -> Result<String, BotError> {
        let compiled = CompiledTemplate::compile(template).map_err(|error| match error {
            // The compile-time diagnostics name the runtime as their node,
            // because the compiler is not handed the node it is compiling for.
            // Here it is known, so it replaces the placeholder.
            BotError::MalformedTemplate { field, .. } => BotError::MalformedTemplate {
                node: node.to_owned(),
                field,
            },
            other => other,
        })?;
        let bytes = compiled.expanded_bytes(scope)?;
        if bytes > limit {
            let refusal = Err(BotError::TemplateExpansionTooLarge {
                node: node.to_owned(),
                bytes,
                limit,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "interpolate: returning an error to the caller");
            return refusal;
        }
        compiled.render(scope)
    }
}

/// Free-text option resolver seam.
pub trait Resolver {
    /// Resolves an utterance against the question in front of the person.
    ///
    /// Returns a [`Verdict`] — the [`Resolution`] together with the policy and
    /// model that produced it — and never an `Option<usize>`. The two-way form
    /// collapses *nothing matched* and *several matched equally well* into one
    /// `None`, and the second is the dangerous one: an answer that fits two
    /// options as well as each other is reported as unrecognized, so the
    /// session re-asks the full list and the identical answer resolves the
    /// identical way forever. A caller that cannot see the tie cannot narrow.
    ///
    /// The provenance is part of the return value rather than a second call,
    /// because *this score came from that model under that rule* is one fact.
    /// A caller that has to ask a resolver afterwards what it just did is
    /// re-deriving a fact it was already handed, and the derivation is only as
    /// good as the resolver's willingness to keep answering the same way.
    /// A question is more than its option list — see [`Question`] for why the
    /// identity travels with the options.
    fn resolve(&self, utterance: &str, question: &Question<'_>) -> Verdict;
}

/// The identity of the decision policy that produced a verdict.
///
/// Two fields rather than one string, because they answer different questions.
/// `label` names the tier whose parameters were in force, so a reader knows
/// what kind of decision this was before reading any score. `revision` is a
/// digest over the parameters themselves, so a threshold that moved is a
/// different version **without anyone remembering to bump a number by hand**:
/// a hand-bumped version is a promise, and a receipt cannot rest on a promise.
///
/// The parameters are hashed by their bit patterns rather than by their decimal
/// renderings, so two thresholds differing in the last bit are two versions and
/// no rounding stands between the value used and the value recorded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct PolicyVersion {
    /// The tier whose policy was in force, such as `lexicon` or `semantic`.
    label: String,
    /// Content digest over the parameters in force, as lowercase hex.
    revision: String,
}

impl PolicyVersion {
    /// Versions a policy from its label and the parameters in force.
    ///
    /// The label is hashed in as well, so two tiers that happen to declare the
    /// same parameters still have different revisions: a revision alone
    /// identifies one policy, which is what lets it be compared without reading
    /// the label beside it.
    #[must_use]
    pub fn new(label: impl Into<String>, parameters: &[f64]) -> Self {
        let label = label.into();
        let mut hasher = Hasher::new();
        hasher.update(label.as_bytes());
        for parameter in parameters {
            hasher.update(&parameter.to_bits().to_le_bytes());
        }
        Self {
            revision: hasher.finalize().to_hex(),
            label,
        }
    }

    /// Returns the tier label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the content digest over the policy's parameters.
    #[must_use]
    pub fn revision(&self) -> &str {
        &self.revision
    }
}

impl fmt::Display for PolicyVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}/{}", self.label, self.revision)
    }
}

/// What produced a verdict: the policy in force, and the model if there was one.
///
/// The two travel together because they are one fact. A receipt that named a
/// score and a tier but not the rule that scored it cannot answer the question
/// a score actually raises, which is *would this have decided the same way
/// yesterday*.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct Provenance {
    /// The decision policy in force when the verdict was reached.
    policy: PolicyVersion,
    /// The model consulted, when the verdict came from one.
    model: Option<EmbedderIdentity>,
}

impl Provenance {
    /// The deterministic tiers decided; no model was consulted.
    #[must_use]
    pub fn without_model(policy: PolicyVersion) -> Self {
        Self {
            policy,
            model: None,
        }
    }

    /// A model was consulted under a policy, whether or not it answered.
    ///
    /// A degraded verdict names its model deliberately. [`DegradedReason`] says
    /// the resolver never reached a verdict, and *which* model was unavailable
    /// is exactly what the repair needs; a record that dropped the identity on
    /// the failure path would describe the one case an operator has to act on
    /// as though no model had been involved.
    #[must_use]
    pub fn with_model(policy: PolicyVersion, model: EmbedderIdentity) -> Self {
        Self {
            policy,
            model: Some(model),
        }
    }

    /// Returns the policy in force.
    #[must_use]
    pub fn policy(&self) -> &PolicyVersion {
        &self.policy
    }

    /// Returns the model consulted, or `None` when none was.
    ///
    /// `None` is a finding rather than a missing value: the deterministic tiers
    /// answered, and naming a model here would claim a comparison that never
    /// happened.
    #[must_use]
    pub fn model(&self) -> Option<&EmbedderIdentity> {
        self.model.as_ref()
    }
}

/// A resolver's answer: the verdict, and what produced it.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Verdict {
    /// The three-way verdict.
    resolution: Resolution,
    /// The policy and model behind it.
    provenance: Provenance,
}

impl Verdict {
    /// Pairs a resolution with what produced it.
    #[must_use]
    pub const fn new(resolution: Resolution, provenance: Provenance) -> Self {
        Self {
            resolution,
            provenance,
        }
    }

    /// Returns the verdict.
    #[must_use]
    pub const fn resolution(&self) -> &Resolution {
        &self.resolution
    }

    /// Returns what produced the verdict.
    #[must_use]
    pub const fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// Consumes the verdict and returns the resolution alone.
    #[must_use]
    pub fn into_resolution(self) -> Resolution {
        self.resolution
    }
}

/// Order two scored candidates best-first, lowest index first on a tie.
///
/// The one comparator for the crate's two rankers — `language`'s lexicon and
/// `semantic`'s embedder — because they have to agree. A candidate the lexicon
/// placed above a tie must not be placed below one by the embedder, or the tier
/// decides the order rather than the score. Both callers feed it ascending
/// indices into a *stable* sort, so an equal score keeps lowest-index-first with
/// no tiebreak of its own.
///
/// A score with no order — a NaN on either side, the one pair `f64` cannot
/// compare — sorts **last**. `total_cmp` alone would rank it above every number,
/// handing the win to the one candidate that measured nothing, and treating it
/// as a tie would leave an unorderable entry in the list the caller then computes
/// its lead over. Neither ranker can produce a NaN today: both score through a
/// checked metric that refuses a degenerate vector, so this arm is a property of
/// the comparator rather than a branch anyone has taken.
pub(crate) fn by_score_descending(
    left: &(usize, MatchTier, f64),
    right: &(usize, MatchTier, f64),
) -> Ordering {
    match (left.2.is_nan(), right.2.is_nan()) {
        (true, false) => Ordering::Less,
        (false, true) => Ordering::Greater,
        _ => right.2.total_cmp(&left.2),
    }
}

/// Which match tier produced a resolution.
///
/// Reported rather than inferred, because it is what makes a wrong resolution
/// explicable and therefore repairable. An `Exact` miss is a learned alias
/// pointing at the wrong option; a `Phonetic` miss is the English bias of
/// [`crate::language::phonetic_key`]; a `Fuzzy` miss is a threshold. Three
/// different repairs, and a bare `usize` names none of them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum MatchTier {
    /// The utterance matched exactly, directly or through a learned alias.
    Exact,
    /// The utterance and the option reduce to the same sound-alike key.
    Phonetic,
    /// The utterance and the option are lexically close.
    Fuzzy,
    /// The utterance and the option are close in a model's embedding space.
    Semantic,
}

/// Why a resolver could not reach a verdict.
///
/// A closed set rather than a string, so a caller can branch on the cause
/// without parsing prose, and so the set of ways a resolver can fail is stated
/// where a reviewer reads it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DegradedReason {
    /// The semantic tier's embedder returned an error, or a vector of the
    /// wrong length.
    EmbedderUnavailable,
    /// An embedding came back as a value no angle can be computed from, so a
    /// comparison the decision needs was never made.
    ///
    /// The embedder answered, and its answer is not a direction: an all-zero
    /// vector, or one carrying `NaN` or an infinity. That is a different
    /// failure from [`Self::EmbedderUnavailable`] and has a different repair —
    /// nothing is down, one of the vectors is degenerate — which is why it is
    /// not folded into it.
    ///
    /// The finer cause is carried by [`lgwks_std::similarity::CosineError`],
    /// which separates a zero magnitude from a non-finite one. It is not
    /// repeated here because the routing is identical: a comparison set missing
    /// even one member cannot produce the `Resolved` or `Absent` verdict a
    /// complete set produces, so the session re-asks and records the cause
    /// whichever of the two it was.
    UnmeasurableEmbedding,
}

impl fmt::Display for DegradedReason {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::EmbedderUnavailable => formatter.write_str("the embedder is unavailable"),
            Self::UnmeasurableEmbedding => {
                formatter.write_str("an embedding could not be measured")
            }
        }
    }
}

/// The outcome of resolving an utterance against the candidate options.
///
/// Serializable, and not only for convenience: this is the shape a
/// [`DecisionReceipt`] carries verbatim, so a receipt cannot hold a verdict the
/// journal could not write down.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Resolution {
    /// One option matched and led the runner-up by the required margin.
    Resolved {
        /// Index of the selected option.
        index: usize,
        /// The tier that produced the match.
        tier: MatchTier,
        /// The match score.
        score: f64,
        /// The lead held over the runner-up *within the winning tier*.
        ///
        /// Within, not across: tier scores are not comparable, and a resolver
        /// that applied precedence has already excluded every lower tier from
        /// the comparison. A `lead` of `1.0` on a lone exact candidate therefore
        /// says "nothing in the exact tier contested this", not "nothing at all
        /// came close".
        lead: f64,
    },
    /// Options matched but none led by the required margin.
    ///
    /// The caller narrows its re-ask to [`Self::Ambiguous::tied`] rather than
    /// repeating the full list. This is the state `Option<usize>` cannot
    /// express, and the one that made a repeated ambiguous answer a loop.
    Ambiguous {
        /// Every option index still in play, lowest first.
        tied: Vec<usize>,
        /// The tier whose candidates tied.
        ///
        /// Reported for the reason [`Self::Resolved::tier`] is: two exact
        /// candidates that fold to one normalized form, two phonetic candidates
        /// that share a sound-alike key, and two fuzzy candidates inside a
        /// margin are three different ties with three different repairs, and a
        /// bare list of indices names none of them.
        tier: MatchTier,
        /// The highest score observed.
        score: f64,
    },
    /// No option matched.
    Absent {
        /// The highest score observed.
        best_score: f64,
    },
    /// The person used a phrase whose confirmed meaning has been withdrawn.
    ///
    /// Distinct from [`Self::Absent`] in the same way [`Self::Degraded`] is, and
    /// for the same reason: the two render identically in a transcript and need
    /// different repairs. `Absent` says the person's words did not fit the
    /// options and a rephrase may help. `StaleAlias` says the words *did* have a
    /// confirmed meaning, at this question, and the option it was bound to is no
    /// longer offered — so the answer is not a rephrase but a conversation, and
    /// the operator reading the record is the one who can have it.
    ///
    /// Returning this rather than a fuzzy reading is the whole point: the
    /// binding is authority a person granted, and re-spending it on whatever now
    /// occupies the old option's position would be using a confirmation the
    /// person never gave. The persona's own reading of the phrase still stands
    /// when the current list produces one; this verdict appears where the
    /// superseded binding is the only thing that would have matched.
    StaleAlias {
        /// The question whose vocabulary the confirmation was made in.
        question: String,
        /// The option text the confirmation bound, which is no longer offered.
        option: String,
    },
    /// The resolver could not reach a verdict at all.
    ///
    /// This is [`Self::Absent`]'s neighbour and not a spelling of it. `Absent`
    /// means the options were all considered and none fit: the person was not
    /// understood, and asking again in different words can help. `Degraded`
    /// means the resolver never got to consider them: a dependency it needs is
    /// unavailable, or answered with a value no comparison can be drawn from,
    /// and asking the person again cannot help — the same utterance will
    /// degrade identically.
    ///
    /// Carries no `best_score`, deliberately. There is no score; a failed
    /// resolver observed no similarity, and reporting `0.0` would be a
    /// measurement that was never taken. It is the same two-valued record
    /// [`Self::Ambiguous`] exists to remove — *nothing matched* versus *may have
    /// matched, and we could not look* — arriving a fourth time.
    ///
    /// That is also why an incomplete comparison set degrades instead of
    /// deciding: a winner measured against fewer competitors than the list
    /// holds is a winner over a field that was never fully looked at, and the
    /// margin it reports would be the whole of its own score.
    Degraded {
        /// The cause, for the caller to record and route on.
        reason: DegradedReason,
    },
}

/// Schema version of the [`DecisionReceipt`] this crate writes.
///
/// Bumped when a field's meaning changes or a field is removed. A reader that
/// finds a version it does not know can refuse the record rather than
/// misinterpret it, which is the only reason to version it at all: a receipt
/// outlives the code that wrote it, and the code that reads it is not always
/// the same revision.
pub const RECEIPT_VERSION: u32 = 1;

/// One structured record of a decision, written as part of the transition it
/// describes.
///
/// The receipt exists because a transcript cannot be the audit record. A
/// transcript is text: it says a person said something and the session moved,
/// and it cannot say which option was considered, on whose authority the
/// comparison was made, or whether a score of nothing meant *no similarity* or
/// *no measurement*. Those are the questions a run has to be able to answer
/// afterwards, and each field here is one of them:
///
/// - `session` and `flow` — which session, running which revision of the flow.
///   A receipt that names a node but not the document it came from cannot be
///   read against the flow a reader has on disk.
/// - `node` and `options` — where the decision was taken, and the *ordered*
///   candidate set it was taken against. The option list is digested rather
///   than counted, because a reordering is a different question with a
///   different right answer.
/// - `resolution` — the verdict verbatim, including the tier. A score is not
///   comparable across tiers, so a receipt holding a score without its tier
///   holds an unreadable number.
/// - `provenance` — the policy in force, and the model when one was consulted.
/// - `selected` and `route` — what was chosen, by the option's own text, and
///   where the session went. The text is what survives a reordering; the route
///   is what the session actually did.
///
/// Fields that were not measured are absent rather than zero. A [`Resolution`]
/// carries a score where a score was observed, and a [`Resolution::Degraded`]
/// carries none at all, which is the difference between *the options were
/// compared and nothing was close* and *nothing was compared*.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct DecisionReceipt {
    /// Schema version; see [`RECEIPT_VERSION`].
    version: u32,
    /// The session the decision was taken in.
    session: SessionId,
    /// Digest of the flow document the session is running.
    flow: String,
    /// The ask node the decision was taken at.
    node: NodeId,
    /// Digest of the ordered candidate options the verdict was reached against.
    options: String,
    /// The verdict, verbatim.
    resolution: Resolution,
    /// The policy in force, and the model when one was consulted.
    provenance: Provenance,
    /// The selected option's own text, when the verdict selected one.
    ///
    /// The text rather than the index: an index is a position in a list that
    /// can be reordered, and the text is the only thing that still names the
    /// choice once it is.
    selected: Option<String>,
    /// The node the accepted transition moved to, when it moved.
    route: Option<NodeId>,
}

impl DecisionReceipt {
    /// Returns the schema version.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Returns the session identity.
    #[must_use]
    pub fn session(&self) -> &SessionId {
        &self.session
    }

    /// Returns the flow revision digest.
    #[must_use]
    pub fn flow(&self) -> &str {
        &self.flow
    }

    /// Returns the ask node the decision was taken at.
    #[must_use]
    pub fn node(&self) -> &str {
        &self.node
    }

    /// Returns the digest of the ordered candidate options.
    #[must_use]
    pub fn options(&self) -> &str {
        &self.options
    }

    /// Returns the verdict.
    #[must_use]
    pub fn resolution(&self) -> &Resolution {
        &self.resolution
    }

    /// Returns the policy and model behind the verdict.
    #[must_use]
    pub fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// Returns the selected option's text, when the verdict selected one.
    #[must_use]
    pub fn selected(&self) -> Option<&str> {
        self.selected.as_deref()
    }

    /// Returns the node the accepted transition moved to, when it moved.
    #[must_use]
    pub fn route(&self) -> Option<&str> {
        self.route.as_deref()
    }
}

/// Where a journal accepted a decision receipt.
///
/// Reported by the sink rather than assumed by the session, because the two are
/// different facts and only the sink knows which one is true. A receipt held in
/// memory is evidence for the lifetime of the process; a receipt held durably
/// is evidence after it. A run that could not tell them apart would put the
/// second claim on the first record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ReceiptAcceptance {
    /// Held only in this process, and gone when it ends.
    InMemory,
    /// Written to a sink that outlives the process.
    Durable,
}

/// The failure a journal reports when it cannot accept a receipt.
///
/// A named sink and its own description rather than a closed enum of causes:
/// the failure belongs to the sink, which owns its vocabulary — a full disk, a
/// refused connection, a closed file — and this crate cannot enumerate another
/// component's failures without inventing a taxonomy the sink would then have
/// to translate into. What is fixed here is that the failure crosses the seam
/// as a value the session must handle, rather than a diagnostic it may print
/// and continue past.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct JournalError {
    /// The sink that refused the receipt.
    sink: String,
    /// The sink's own description of the failure.
    cause: String,
}

impl JournalError {
    /// Records a sink's failure to accept a receipt.
    #[must_use]
    pub fn new(sink: impl Into<String>, cause: impl Into<String>) -> Self {
        Self {
            sink: sink.into(),
            cause: cause.into(),
        }
    }

    /// Returns the sink that refused.
    #[must_use]
    pub fn sink(&self) -> &str {
        &self.sink
    }

    /// Returns the sink's description of the failure.
    #[must_use]
    pub fn cause(&self) -> &str {
        &self.cause
    }
}

impl fmt::Display for JournalError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "journal {} refused a decision receipt: {}",
            self.sink, self.cause
        )
    }
}

impl std::error::Error for JournalError {}

/// One receipt, and the way the journal accepted it.
///
/// The pair rather than a receipt carrying its own acceptance: the receipt is
/// what both sides hold, and the acceptance is the journal's answer about it.
/// Folding the answer into the record the journal was already given would mean
/// the two copies differ on the field that matters most.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RecordedDecision {
    /// The receipt the journal accepted.
    receipt: DecisionReceipt,
    /// Where the journal said it accepted it.
    acceptance: ReceiptAcceptance,
}

impl RecordedDecision {
    /// The journal receipt this decision was written under.
    ///
    /// Borrowed, not cloned, so a caller cannot present a receipt that is not
    /// the one the journal accepted. A receipt is the durable half of a decision:
    /// it is what makes the decision survive a restart that loses this record.
    #[must_use]
    pub fn receipt(&self) -> &DecisionReceipt {
        &self.receipt
    }

    /// Returns where the journal accepted it.
    #[must_use]
    pub const fn acceptance(&self) -> ReceiptAcceptance {
        self.acceptance
    }
}

/// Journal seam for session path records.
pub trait Journal {
    /// Receive a path node, role label, and rendered text record.
    fn record(&mut self, path_node: &str, role: &str, text: &str);

    /// Accept one decision receipt, reporting where it was accepted.
    ///
    /// Fallible, and required rather than defaulted. [`Self::record`] cannot
    /// report persistence failure, and neither could a defaulted version of
    /// this method: a sink that has to do nothing to look successful is a sink
    /// that silently drops every receipt, and the session would report an
    /// accepted transition whose audit record does not exist. Requiring it
    /// makes every implementation state what it does with a receipt — including
    /// [`MemoryJournal`], which says `InMemory` in as many words.
    ///
    /// `Err` aborts the transition. A receipt is not a log line written beside
    /// the work; it is part of accepting the answer, so a session that cannot
    /// record the decision has not taken it.
    fn record_decision(
        &mut self,
        receipt: &DecisionReceipt,
    ) -> Result<ReceiptAcceptance, JournalError>;
}

/// One in-memory transcript record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde", deny_unknown_fields)]
#[non_exhaustive]
pub struct TranscriptEntry {
    /// Node id at which the record was produced.
    path_node: String,
    /// Role label, such as `assistant` or `user`.
    role: String,
    /// Rendered record text.
    text: String,
}

impl TranscriptEntry {
    /// The node this transcript entry was recorded against.
    ///
    /// The *path* node rather than the current one: a session that loops back
    /// through a branch records entries against the node that was current when
    /// they happened, so a reader replaying the transcript follows the path the
    /// conversation actually took rather than the one it ended on.
    #[must_use]
    pub fn path_node(&self) -> &str {
        &self.path_node
    }

    /// Return the role label.
    #[must_use]
    pub fn role(&self) -> &str {
        &self.role
    }

    /// Return the rendered record text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }
}

/// Bounded-by-session in-memory journal implementation.
///
/// `PartialEq` but not `Eq`: the receipts it holds carry the scores a verdict
/// was reached on, and `f64` is not `Eq`. That is a property of the record
/// rather than a gap — `NaN` is not a score any tier produces, and `DecisionReceipt`
/// has no `Eq` for the same reason.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct MemoryJournal {
    /// Records in insertion order.
    records: Vec<TranscriptEntry>,
    /// Decision receipts in insertion order.
    receipts: Vec<DecisionReceipt>,
}

impl MemoryJournal {
    /// Construct an empty journal.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            records: Vec::new(),
            receipts: Vec::new(),
        }
    }

    /// Return records in insertion order.
    #[must_use]
    pub fn records(&self) -> &[TranscriptEntry] {
        &self.records
    }

    /// Return decision receipts in insertion order.
    #[must_use]
    pub fn receipts(&self) -> &[DecisionReceipt] {
        &self.receipts
    }

    /// Consume the journal and return its records.
    #[must_use]
    pub fn into_records(self) -> Vec<TranscriptEntry> {
        self.records
    }

    /// Consume the journal and return its decision receipts.
    #[must_use]
    pub fn into_receipts(self) -> Vec<DecisionReceipt> {
        self.receipts
    }
}

impl Journal for MemoryJournal {
    fn record(&mut self, path_node: &str, role: &str, text: &str) {
        self.records.push(TranscriptEntry {
            path_node: path_node.to_owned(),
            role: role.to_owned(),
            text: text.to_owned(),
        });
    }

    /// Accepts a receipt, and says so: `InMemory` is the honest answer for a
    /// sink whose whole storage is a `Vec` in this process. A caller that needs
    /// a durable record has to install a journal that says `Durable`, and can
    /// see from the receipt that this one did not.
    fn record_decision(
        &mut self,
        receipt: &DecisionReceipt,
    ) -> Result<ReceiptAcceptance, JournalError> {
        self.receipts.push(receipt.clone());
        Ok(ReceiptAcceptance::InMemory)
    }
}

/// Public identity of one in-memory session.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde")]
#[non_exhaustive]
pub struct SessionId(String);

impl SessionId {
    /// Construct an id from its stable string representation.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Return the stable string representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for SessionId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for SessionId {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// Synchronous cursor over one validated flow and its conversation state.
#[non_exhaustive]
pub struct Session {
    /// Stable session identity.
    id: SessionId,
    /// Validated flow document owned by this session.
    flow: FlowSpec,
    /// Digest of the flow document, computed once at construction.
    flow_revision: String,
    /// Current node, or `None` after terminal completion.
    current: Option<NodeId>,
    /// Typed variable scope.
    scope: VarScope,
    /// Nodes executed in order, including repeated cycle visits.
    visited: Vec<NodeId>,
    /// Transcript mirrored to the journal seam.
    transcript: Vec<TranscriptEntry>,
    /// Pluggable free-text resolver.
    resolver: Box<dyn Resolver>,
    /// Pluggable record sink.
    journal: Box<dyn Journal>,
    /// Decision receipts in insertion order, with how each was accepted.
    decisions: Vec<RecordedDecision>,
    /// Terminal outcome, if the cursor has stopped.
    terminal: Option<Terminal>,
    /// Number of charged execution and answer steps.
    steps: usize,
    /// Last accepted answer, used by [`NodeKind::Route`].
    last_utterance: Option<String>,
    /// Effective byte ceilings for this session.
    limits: ResourceLimits,
    /// Bytes retained so far: every transcript record and visited node id.
    retained: usize,
}

/// What one answer is being judged against: the ask it answers, the resolver's
/// verdict on it, and the person's own words.
///
/// Gathered so the helpers that apply a verdict take one borrowed value rather
/// than six positional arguments that can be passed in the wrong order.
struct Turn<'a> {
    /// The ask node being answered.
    node_id: &'a str,
    /// The variable a resolved answer binds.
    var: &'a str,
    /// The options the ask offered.
    options: &'a [String],
    /// Where each option leads.
    routes: &'a BTreeMap<String, NodeId>,
    /// The resolver's verdict.
    verdict: &'a Verdict,
    /// What the person said.
    utterance: &'a str,
}

impl Session {
    /// Start a session with the default language resolver and memory journal.
    pub fn new(id: impl Into<SessionId>, flow: FlowSpec) -> Result<Self, BotError> {
        Self::with_components(
            id,
            flow,
            crate::language::LanguageResolver::new(),
            MemoryJournal::new(),
        )
    }

    /// Start a session with a custom resolver and the default memory journal.
    pub fn with_resolver<R>(
        id: impl Into<SessionId>,
        flow: FlowSpec,
        resolver: R,
    ) -> Result<Self, BotError>
    where
        R: Resolver + 'static,
    {
        Self::with_components(id, flow, resolver, MemoryJournal::new())
    }

    /// Start a session with a custom resolver, a custom journal, and explicit
    /// byte ceilings.
    ///
    /// The operator's knob. `limits` may be tighter than
    /// [`ResourceLimits::shipped`] and may not be looser; a value above the
    /// shipped ceiling is refused with [`BotError::ResourceLimitAboveCeiling`]
    /// before the flow is even examined. What the session ends up enforcing is
    /// the narrower of `limits` and whatever the document asks for in its
    /// [`FlowBounds`], per axis, so neither side can widen what the other
    /// narrowed.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::ResourceLimitAboveCeiling`] for a ceiling above the
    /// operator's, and every error [`Self::with_components`] returns.
    pub fn with_components_and_limits<R, J>(
        id: impl Into<SessionId>,
        flow: FlowSpec,
        resolver: R,
        journal: J,
        limits: ResourceLimits,
    ) -> Result<Self, BotError>
    where
        R: Resolver + 'static,
        J: Journal + 'static,
    {
        // Both sets are checked against the ceiling and then narrowed against
        // each other, in that order: a request above the ceiling is a refusal
        // wherever it comes from, and two in-range requests combine by taking
        // the smaller. Doing it the other way round would let a document's
        // in-range tightening hide an operator's out-of-range one.
        let operator = limits.within_ceiling()?;
        let requested = flow.bounds.effective_resources().within_ceiling()?;
        let effective = operator.narrowed(requested);
        // Re-validated here rather than trusted from construction, because the
        // public `json` façade parses a `FlowSpec` without calling
        // `FlowSpec::from_json`, and because this is the point at which the
        // effective ceilings — the ones this session will actually enforce —
        // become known to validation.
        validate_flow_within(&flow, effective)?;
        let scope = VarScope::new(flow.vars.clone())?;
        let flow_revision = revision_of(&flow)?;
        let mut session = Self {
            id: id.into(),
            current: Some(flow.entry.clone()),
            flow,
            flow_revision,
            scope,
            visited: Vec::new(),
            transcript: Vec::new(),
            resolver: Box::new(resolver),
            journal: Box::new(journal),
            decisions: Vec::new(),
            terminal: None,
            steps: 0,
            last_utterance: None,
            limits: effective,
            retained: 0,
        };
        session.drive()?;
        Ok(session)
    }

    /// Start a session with explicit byte ceilings and the default seams.
    ///
    /// # Errors
    ///
    /// As [`Self::with_components_and_limits`].
    pub fn with_limits(
        id: impl Into<SessionId>,
        flow: FlowSpec,
        limits: ResourceLimits,
    ) -> Result<Self, BotError> {
        Self::with_components_and_limits(
            id,
            flow,
            crate::language::LanguageResolver::new(),
            MemoryJournal::new(),
            limits,
        )
    }

    /// Start a session with both replacement seams installed.
    pub fn with_components<R, J>(
        id: impl Into<SessionId>,
        flow: FlowSpec,
        resolver: R,
        journal: J,
    ) -> Result<Self, BotError>
    where
        R: Resolver + 'static,
        J: Journal + 'static,
    {
        Self::with_components_and_limits(id, flow, resolver, journal, ResourceLimits::shipped())
    }

    /// Return the session identity.
    #[must_use]
    pub fn id(&self) -> &SessionId {
        &self.id
    }

    /// Return the current node id, or `None` once terminal.
    #[must_use]
    pub fn current(&self) -> Option<&str> {
        self.current.as_deref()
    }

    /// Return the current node kind, or `None` once terminal.
    #[must_use]
    pub fn current_node(&self) -> Option<&NodeKind> {
        self.current.as_deref().and_then(|id| self.flow.node(id))
    }

    /// Return the typed variable scope.
    #[must_use]
    pub fn scope(&self) -> &VarScope {
        &self.scope
    }

    /// Return the visited node path.
    #[must_use]
    pub fn visited(&self) -> &[NodeId] {
        &self.visited
    }

    /// Return transcript records in insertion order.
    #[must_use]
    pub fn transcript(&self) -> &[TranscriptEntry] {
        &self.transcript
    }

    /// Return the decision receipts written so far, in insertion order.
    ///
    /// This is the audit record. [`Self::transcript`] is a rendering of the
    /// same events for a person to read; these are what a consumer reconciles
    /// against, and they carry what a rendering cannot: the policy in force,
    /// the model if one was consulted, the candidate set, and where each
    /// receipt was accepted.
    #[must_use]
    pub fn decisions(&self) -> &[RecordedDecision] {
        &self.decisions
    }

    /// Return the digest of the flow document this session is running.
    #[must_use]
    pub fn flow_revision(&self) -> &str {
        &self.flow_revision
    }

    /// Return the terminal outcome, if reached.
    #[must_use]
    pub fn terminal(&self) -> Option<&Terminal> {
        self.terminal.as_ref()
    }

    /// Return the number of charged steps.
    #[must_use]
    pub fn steps(&self) -> usize {
        self.steps
    }

    /// Return the byte ceilings this session enforces.
    ///
    /// The effective set: the operator's shipped ceiling, narrowed by whatever
    /// this session's caller and this flow's [`FlowBounds`] asked for. Reported
    /// because a bound a caller cannot read back is a bound they have to
    /// discover by running into it.
    #[must_use]
    pub const fn limits(&self) -> ResourceLimits {
        self.limits
    }

    /// Return the bytes this session currently retains.
    ///
    /// The sum of every transcript record's payload, path node, and role, plus
    /// every visited node id. Each is an owned allocation the session holds, so
    /// the total is what a caller needs to bound their own memory rather than
    /// an estimate of it.
    #[must_use]
    pub const fn retained_bytes(&self) -> usize {
        self.retained
    }

    /// Receipts the verdict, then records the person's answer.
    ///
    /// Every re-ask arm begins with this pair, and the order is the contract: the
    /// receipt is the durable fact that a verdict was reached, and the transcript
    /// line is what a reader sees later. Recording first would put an utterance
    /// in the transcript for a verdict that was never durably reached.
    fn receipt_and_record(&mut self, turn: &Turn<'_>) -> Result<(), BotError> {
        self.write_receipt(turn.node_id, turn.options, turn.verdict, None, None)?;
        self.record(turn.node_id, "user", turn.utterance)
    }

    /// Applies a resolved verdict: receipt, bind, record, then continue.
    ///
    /// A helper rather than the arm inline: as one block the arm held the
    /// option lookup, the route lookup, the receipt, the binding, the
    /// transcript line and the transition -- six fallible steps in one
    /// statement. The order is the contract `answer` documents above and is
    /// enforced here: a journal that refuses the receipt aborts the answer with
    /// the session untouched.
    fn accept_resolved(&mut self, turn: &Turn<'_>, index: usize) -> Result<(), BotError> {
        let Turn {
            node_id,
            var,
            options,
            routes,
            verdict,
            utterance,
        } = *turn;
        let Some(option) = options.get(index) else {
            let refusal = Err(BotError::ResolverReturnedInvalidOption {
                node: node_id.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "accept_resolved: returning an error to the caller");
            return refusal;
        };
        let Some(target) = routes.get(option).cloned() else {
            let refusal = Err(BotError::MissingAskRoute {
                node: node_id.to_owned(),
                option: option.clone(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "accept_resolved: returning an error to the caller");
            return refusal;
        };
        self.write_receipt(
            node_id,
            options,
            verdict,
            Some(option.clone()),
            Some(&target),
        )?;
        self.scope
            .set_from_answer_within(var, option, self.limits.get(ResourceAxis::Value))?;
        self.last_utterance = Some(utterance.to_owned());
        self.record(node_id, "user", utterance)?;
        self.current = Some(target);
        self.drive()
    }

    /// Applies one resolver verdict to the session.
    ///
    /// Every arm is its own refusal or its own transcript, and reading them side
    /// by side is what makes the differences between them -- a narrowed re-ask,
    /// a withdrawn binding, a degraded cause under its own role -- visible.
    /// Inside `answer` they read as one statement.
    /// Receipts a verdict, records the answer, then re-asks over `ask`.
    ///
    /// The shape every non-resolved verdict shares. `ask` is the option list the
    /// prompt should carry: the full list for an absent, stale or degraded answer,
    /// and a strictly smaller one for an ambiguous tie. That difference is the
    /// whole reason an ambiguous answer terminates rather than looping, so it is
    /// a parameter here instead of a branch repeated at each call site.
    fn reask(&mut self, turn: &Turn<'_>, ask: &[String]) -> Result<(), BotError> {
        self.receipt_and_record(turn)?;
        self.record_prompt(turn.node_id, ask)
    }

    /// Applies one resolver verdict to the session.
    ///
    /// Each arm is its own refusal or its own transcript, and reading them side
    /// by side is what makes the differences between them -- a narrowed re-ask,
    /// a withdrawn binding, a degraded cause under its own role -- visible.
    /// Inside `answer` they read as one statement.
    fn apply_resolution(
        &mut self,
        turn: &Turn<'_>,
        resolution: Resolution,
    ) -> Result<(), BotError> {
        let options = turn.options;
        match resolution {
            Resolution::Resolved { index, .. } => self.accept_resolved(turn, index),
            Resolution::Ambiguous { tied, .. } => {
                // Narrow the re-ask to the options still in play. Repeating the
                // full list is what a two-way verdict forced, and it is why an
                // ambiguous answer could loop: the same utterance resolves the
                // same way every time it is asked, so the session never leaves
                // the node. A re-ask that is strictly smaller terminates.
                let narrowed: Vec<String> = tied
                    .iter()
                    .filter_map(|candidate| options.get(*candidate).cloned())
                    .collect();
                // A narrowed set of one is not a question -- there is nothing
                // to choose between -- so the full list is asked again.
                let ask: &[String] = if narrowed.len() >= 2 {
                    &narrowed
                } else {
                    options
                };
                self.reask(turn, ask)
            }
            Resolution::Absent { .. } => self.reask(turn, options),
            Resolution::StaleAlias {
                question: bound_question,
                option,
            } => {
                // Re-ask, as for `Absent`, but record what was withdrawn under
                // its own role. The resolver is not asked to forget the binding:
                // the seam is read-only by design, and a session that silently
                // rewrote its resolver's learned vocabulary would be editing the
                // audit record it is supposed to be producing. The record names
                // the binding and the question; retiring it is the owner's call.
                // A re-ask is a decision, so it is receipted like every other
                // verdict; the receipt names the withdrawal, and the roles
                // below name it again for whoever reads the transcript.
                self.record_stale_alias(turn.node_id, &bound_question, &option)?;
                self.reask(turn, options)
            }
            Resolution::Degraded { reason } => {
                // Re-ask, as for `Absent`, but record the cause under its own
                // role: a transcript that renders a degraded re-ask exactly as
                // an unclear one is how an operator concludes the person was
                // being difficult while the embedder was down.
                self.record_degraded(turn.node_id, reason)?;
                self.reask(turn, options)
            }
        }
    }
    /// Submit one free-text answer. Unrecognized input is recorded, the same
    /// ask remains current, and the prompt is recorded again.
    ///
    /// Every verdict — resolved, ambiguous, absent, or degraded — writes a
    /// [`DecisionReceipt`], because a re-ask is a decision too and the one an
    /// operator most needs to see afterwards.
    ///
    /// The receipt is written through the journal before the transition it
    /// describes is applied, and a journal that refuses it aborts the answer
    /// with [`BotError::ReceiptNotRecorded`] leaving the session exactly as it
    /// was: not advanced, not terminated, the variable unwritten, the
    /// transcript untouched, and no receipt held. Recording is part of
    /// accepting an answer, not a report written beside it, so the one failure
    /// this ordering leaves behind is a decision that was reached and recorded
    /// whose answer could not then be stored — which is the direction an audit
    /// record must err in, and the opposite of an accepted answer with no
    /// record of why.
    pub fn answer(&mut self, utterance: &str) -> Result<(), BotError> {
        if self.terminal.is_some() {
            let refusal = Err(BotError::SessionTerminated);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "answer: returning an error to the caller");
            return refusal;
        }
        let Some(node_id) = self.current.clone() else {
            let refusal = Err(BotError::SessionNotAwaitingAnswer);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "answer: returning an error to the caller");
            return refusal;
        };
        let Some(NodeKind::Ask {
            var,
            options,
            routes,
        }) = self.flow.node(&node_id).cloned()
        else {
            let refusal = Err(BotError::SessionNotAwaitingAnswer);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "answer: returning an error to the caller");
            return refusal;
        };
        // The ingress ceiling, and it comes before the step is charged and
        // before the utterance is copied anywhere: a refused line must neither
        // consume budget nor leave a record that reads as part of the
        // conversation. The check is one comparison against a bounded length,
        // so refusing costs nothing that accepting would not have cost more of.
        let utterance_limit = self.limits.get(ResourceAxis::Utterance);
        if utterance.len() > utterance_limit {
            let refusal = Err(BotError::UtteranceTooLarge {
                bytes: utterance.len(),
                limit: utterance_limit,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "answer: returning an error to the caller");
            return refusal;
        }
        self.charge_step()?;
        let question =
            Question::new(&node_id, &options).with_domain(self.scope.answer_domain(&var));
        let verdict = self.resolver.resolve(utterance, &question);
        let turn = Turn {
            node_id: &node_id,
            var: &var,
            options: &options,
            routes: &routes,
            verdict: &verdict,
            utterance,
        };
        self.apply_resolution(&turn, verdict.resolution().clone())
    }

    /// Build one receipt and write it through the journal, or refuse the
    /// answer.
    ///
    /// The session's own copy is stored only after the sink has taken it, and
    /// the acceptance that comes back is stored beside it: what the journal
    /// said about the receipt is its own fact, and a receipt that carried its
    /// own acceptance would be the session answering a question only the sink
    /// can answer.
    fn write_receipt(
        &mut self,
        node_id: &str,
        options: &[String],
        verdict: &Verdict,
        selected: Option<String>,
        route: Option<&str>,
    ) -> Result<(), BotError> {
        let receipt = DecisionReceipt {
            version: RECEIPT_VERSION,
            session: self.id.clone(),
            flow: self.flow_revision.clone(),
            node: node_id.to_owned(),
            options: options_revision(options),
            resolution: verdict.resolution().clone(),
            provenance: verdict.provenance().clone(),
            selected,
            route: route.map(str::to_owned),
        };
        // The sink takes it first. The session's own copy is stored only once
        // the journal has accepted it, so a refusal leaves no receipt held.
        let acceptance = self.journal.record_decision(&receipt).map_err(|cause| {
            BotError::ReceiptNotRecorded {
                node: node_id.to_owned(),
                cause,
            }
        })?;
        self.decisions.push(RecordedDecision {
            receipt,
            acceptance,
        });
        Ok(())
    }

    /// Charge one bounded step or return [`BotError::SessionBudgetExceeded`].
    fn charge_step(&mut self) -> Result<(), BotError> {
        let attempted = self
            .steps
            .checked_add(1)
            .ok_or(BotError::SessionBudgetExceeded {
                steps: usize::MAX,
                budget: self.flow.bounds.budget,
            })?;
        if attempted > self.flow.bounds.budget {
            let refusal = Err(BotError::SessionBudgetExceeded {
                steps: attempted,
                budget: self.flow.bounds.budget,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "charge_step: returning an error to the caller");
            return refusal;
        }
        self.steps = attempted;
        Ok(())
    }

    /// Execute deterministic nodes until an ask or terminal is reached.
    /// Renders `text` and records it as the assistant's turn.
    ///
    /// `say` and `refer` both speak before either continues, and inline they
    /// each rendered and recorded as two statements, so the drive loop carried
    /// four of them across two arms and a reader could not see that the pair is
    /// one step. It matters that the record follows the render: a render that
    /// refuses must leave nothing said.
    fn speak(&mut self, node_id: &str, text: &str) -> Result<(), BotError> {
        let rendered = self.render(node_id, text)?;
        self.record(node_id, "assistant", &rendered)
    }

    /// Advances the session until it needs an answer or reaches an outcome.
    fn drive(&mut self) -> Result<(), BotError> {
        loop {
            let Some(node_id) = self.current.clone() else {
                return Ok(());
            };
            self.charge_step()?;
            // The path is retained like a record is, and charged like one: a
            // visited id is an owned copy of the node id the document carries,
            // so the same loop that produces unbounded records would otherwise
            // produce an unbounded path out of the same repetition.
            self.charge_retention(node_id.len())?;
            self.visited.push(node_id.clone());
            let Some(kind) = self.flow.node(&node_id).cloned() else {
                let refusal = Err(BotError::InvalidTransitionTarget {
                    from: "<session>".into(),
                    target: node_id,
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "drive: returning an error to the caller");
                return refusal;
            };
            if self.step(&node_id, kind)? {
                return Ok(());
            }
        }
    }

    /// Advances one node. Answers whether the session must stop and wait.
    ///
    /// A helper rather than the `match` inside the drive loop: as one block the
    /// loop carried the charge, the lookup and every arm's write as one
    /// statement, and the thing that actually varies -- what a node kind does --
    /// was indistinguishable from the thing that does not -- what every node
    /// does first.
    ///
    /// `Ok(true)` means the session is waiting for an answer, which is the only
    /// kind that stops the loop short of an outcome.
    /// Speaks a `say` node's text, then follows its single continuation.
    ///
    /// Speaking before the transition is the contract: a render that refuses must
    /// leave the session on the node it was already on, not halfway to the next.
    fn speak_then_follow(&mut self, node_id: &str, text: &str) -> Result<(), BotError> {
        self.speak(node_id, text)?;
        let Some(target) = self.flow.edge_targets(node_id).into_iter().next() else {
            let refusal = Err(BotError::MissingTransition {
                node: node_id.to_owned(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "speak_then_follow: returning an error to the caller");
            return refusal;
        };
        self.current = Some(target);
        Ok(())
    }

    /// Moves to whichever edge the `branch` node's predicate selects.
    ///
    /// A `branch` has exactly two edges and its predicate chooses between them,
    /// so this is a lookup rather than a decision: the predicate is the whole of
    /// the choice and it has already been validated at load.
    fn take_branch(
        &mut self,
        when: &Predicate,
        then: NodeId,
        otherwise: NodeId,
    ) -> Result<(), BotError> {
        self.current = Some(if when.evaluate(&self.scope)? {
            then
        } else {
            otherwise
        });
        Ok(())
    }

    /// Speaks a `refer` node's text, then ends with the referral it declares.
    ///
    /// The text is emitted before the outcome is set, and the only declared
    /// outcome a `refer` node can carry is the referral itself -- validation
    /// refuses anything else -- so this text is never spoken for an outcome that
    /// contradicts it.
    fn refer(&mut self, node_id: &str, text: &str) -> Result<(), BotError> {
        self.speak(node_id, text)?;
        self.finish(node_id)
    }

    /// Advances one node, and answers whether the session must stop and wait.
    ///
    /// `Ok(true)` is the ask: the only kind that stops the loop short of an
    /// outcome. Each arm is the one step its kind performs, named below.
    fn step(&mut self, node_id: &str, kind: NodeKind) -> Result<bool, BotError> {
        match kind {
            NodeKind::Say { text } => self.speak_then_follow(node_id, &text),
            NodeKind::Ask { options, .. } => {
                self.record_prompt(node_id, &options)?;
                return Ok(true);
            }
            NodeKind::Branch {
                when,
                then,
                otherwise,
                ..
            } => self.take_branch(&when, then, otherwise),
            // The two terminal kinds that emit nothing before they end.
            // Both read the outcome from the document rather than
            // constructing it from the node, so a declared outcome is
            // executed here and not only checked at load.
            NodeKind::Handoff { .. } | NodeKind::End => self.finish(node_id),
            NodeKind::Refer { text, .. } => self.refer(node_id, &text),
            NodeKind::Route { dispatch, fallback } => {
                self.current = Some(if self.last_utterance.is_some() {
                    dispatch
                } else {
                    fallback
                });
                Ok(())
            }
        }?;
        Ok(false)
    }

    /// End the session with the outcome the document gives one terminal node.
    ///
    /// The one place a session reads a terminal outcome. `drive` reaches this
    /// for every terminal node kind, so the outcome validation checked and the
    /// outcome execution returns are the same value from the same calculation
    /// ([`FlowSpec::effective_terminal`]) and cannot drift: an earlier runner
    /// consulted the terminal map for `End` alone, and a refusal declared on a
    /// `handoff` node was accepted by validation and ignored here.
    fn finish(&mut self, node_id: &str) -> Result<(), BotError> {
        let Some(outcome) = self.flow.effective_terminal(node_id) else {
            let refusal = Err(BotError::MalformedFlow {
                cause: format!("node {node_id:?} reached with no terminal outcome"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "finish: returning an error to the caller");
            return refusal;
        };
        self.terminal = Some(outcome);
        self.current = None;
        Ok(())
    }

    /// Render one node's template under this session's record ceiling.
    ///
    /// The ceiling is applied to the *computed* expansion, inside the
    /// interpolator, before the output buffer exists. What that buys is the
    /// whole of the amplification fix: a valid document can name a placeholder
    /// a million times, and the cost of discovering that is a million additions
    /// rather than a multi-gigabyte allocation.
    fn render(&self, node_id: &str, template: &str) -> Result<String, BotError> {
        TemplateInterpolator::new().interpolate(
            template,
            &self.scope,
            node_id,
            self.limits.get(ResourceAxis::Record),
        )
    }

    /// Charge `bytes` against the session's retention ceiling.
    ///
    /// Charged before the allocation, so a refused write leaves nothing behind
    /// to clean up: the journal has not been told, the transcript has not grown,
    /// and the counter has not moved.
    fn charge_retention(&mut self, bytes: usize) -> Result<(), BotError> {
        let limit = self.limits.get(ResourceAxis::Session);
        let total = self
            .retained
            .checked_add(bytes)
            .ok_or(BotError::SessionRetentionExceeded {
                bytes: usize::MAX,
                limit,
            })?;
        if total > limit {
            let refusal = Err(BotError::SessionRetentionExceeded {
                bytes: total,
                limit,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "charge_retention: returning an error to the caller");
            return refusal;
        }
        self.retained = total;
        Ok(())
    }

    /// Append one transcript record and forward it to the journal seam.
    ///
    /// Two ceilings, in this order, and both before either sink is touched: the
    /// payload against the per-record ceiling, which is what makes the refusal
    /// name the node whose text is too long, and the whole record against the
    /// aggregate, which is what bounds a conversation the graph lets repeat.
    /// The record's cost counts the path node and the role as well as the text,
    /// because all three are owned copies this session retains.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::RecordTooLarge`] or
    /// [`BotError::SessionRetentionExceeded`]. Neither has written anything.
    fn record(&mut self, node_id: &str, role: &str, text: &str) -> Result<(), BotError> {
        let record_bytes = self.limits.get(ResourceAxis::Record);
        if text.len() > record_bytes {
            let refusal = Err(BotError::RecordTooLarge {
                node: node_id.to_owned(),
                bytes: text.len(),
                limit: record_bytes,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "record: returning an error to the caller");
            return refusal;
        }
        let cost = text
            .len()
            .saturating_add(node_id.len())
            .saturating_add(role.len());
        self.charge_retention(cost)?;
        self.journal.record(node_id, role, text);
        self.transcript.push(TranscriptEntry {
            path_node: node_id.to_owned(),
            role: role.to_owned(),
            text: text.to_owned(),
        });
        Ok(())
    }

    /// Record the standard prompt for an ask node.
    ///
    /// The prompt is built from the node's candidates, so its size is checked
    /// before it is built rather than after: a node with many long options
    /// would otherwise allocate the joined string and *then* discover that the
    /// record ceiling refuses it. `checked_mul` for the separators and
    /// `checked_add` for each option, with the overflow case reported as the
    /// same refusal rather than wrapped.
    ///
    /// # Errors
    ///
    /// Returns [`BotError::RecordTooLarge`] for a prompt over the ceiling.
    fn record_prompt(&mut self, node_id: &str, options: &[String]) -> Result<(), BotError> {
        let bytes = prompt_bytes(options);
        let record_bytes = self.limits.get(ResourceAxis::Record);
        if bytes > record_bytes {
            let refusal = Err(BotError::RecordTooLarge {
                node: node_id.to_owned(),
                bytes,
                limit: record_bytes,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "record_prompt: returning an error to the caller");
            return refusal;
        }
        let prompt = format!("Choose one: {}", options.join(", "));
        self.record(node_id, "assistant", &prompt)
    }

    /// Records that the resolver could not reach a verdict.
    ///
    /// A distinct role rather than a second assistant prompt, because the two
    /// failures need different repairs and a transcript is where that is
    /// decided: an absent resolution says the person's words did not fit the
    /// options, and a degraded one says the resolver never got to compare them.
    fn record_degraded(&mut self, node_id: &str, reason: DegradedReason) -> Result<(), BotError> {
        let text = format!("Resolver unavailable: {reason}");
        self.record(node_id, "resolver-degraded", &text)
    }

    /// Records that a confirmed phrase's option is no longer offered.
    ///
    /// A distinct role for the reason the degraded case has one: this record is
    /// read by whoever maintains the vocabulary, and it has to name both halves
    /// of the broken binding — the question it was confirmed in and the option
    /// that went away — because either one alone is unactionable. "A stale alias
    /// was ignored" tells that reader nothing they can repair.
    fn record_stale_alias(
        &mut self,
        node_id: &str,
        question: &str,
        option: &str,
    ) -> Result<(), BotError> {
        let text = format!("Superseded alias: question {question} no longer offers \"{option}\"");
        self.record(node_id, "resolver-stale-alias", &text)
    }
}

/// The byte cost of the standard ask prompt for `options`.
///
/// Computed rather than measured, so the caller can refuse an oversized prompt
/// without building it. A width that saturates is the same refusal at a larger
/// size: [`usize::MAX`] bytes exceeds every record ceiling, so the caller's
/// ceiling check answers it without being told which of the two it was.
///
/// The prefix and separator are the literals [`Session::record_prompt`]
/// formats, and they are named here rather than repeated so the estimate and
/// the string cannot disagree.
fn prompt_bytes(options: &[String]) -> usize {
    /// Literal prefix in the recorded prompt.
    const PREFIX: &str = "Choose one: ";
    /// Literal separator between candidates.
    const SEPARATOR: &str = ", ";
    // Saturating rather than checked: the caller refuses a prompt whose width
    // exceeds the record ceiling, and a width that has saturated exceeds every
    // ceiling a `usize` can hold, so the same refusal answers both without the
    // caller having to tell which of the two it was looking at. `checked_sub(1)`
    // becomes a `saturating_sub`, which is the same value for the empty list —
    // no separator follows no candidate — and the right one past it.
    let separators = options
        .len()
        .saturating_sub(1)
        .saturating_mul(SEPARATOR.len());
    let candidates = options.iter().fold(PREFIX.len(), |total, option| {
        total.saturating_add(option.len())
    });
    candidates.saturating_add(separators)
}

/// Digest a flow document so a receipt names the revision it was decided under.
///
/// The document is digested through its JSON rendering rather than field by
/// field, so a field added to [`FlowSpec`] later is covered without anyone
/// remembering to extend a walk. `FlowSpec` holds `BTreeMap`s, so the rendering
/// is canonical: two flows that differ only in the order their maps were built
/// from digest identically, which is what makes this a *revision* rather than a
/// serialization accident.
fn revision_of(flow: &FlowSpec) -> Result<String, BotError> {
    crate::json::to_string(flow)
        .map(|rendered| lgwks_std::hash::blake3(rendered.as_bytes()).to_hex())
        .map_err(|error| BotError::MalformedFlow {
            cause: error.to_string().escape_debug().to_string(),
        })
}

/// Digest an ordered candidate list, so a reordering is a different identity.
///
/// Each option is length-prefixed rather than separated, because an option is
/// free text and could contain any separator: a digest that concatenated
/// `["a", "b"]` and `["ab"]` to the same bytes would report two different
/// questions as one identity, and the whole point of the field is to tell
/// whether the question changed.
fn options_revision(options: &[String]) -> String {
    let mut hasher = Hasher::new();
    for option in options {
        hasher.update(&option.len().to_le_bytes());
        hasher.update(option.as_bytes());
    }
    hasher.finalize().to_hex()
}

/// Resolve one scalar expression from a variable scope.
fn resolve_expr(expression: &ValueExpr, scope: &VarScope) -> Result<Value, BotError> {
    match *expression {
        ValueExpr::Literal(ref value) => Ok(value.clone()),
        ValueExpr::Var(ref name) => scope
            .get(name)
            .cloned()
            .ok_or_else(|| BotError::VariableUnset { name: name.clone() }),
    }
}

/// Compare two scalar expressions with a typed ordering operation.
fn compare_expr<F>(
    left: &ValueExpr,
    right: &ValueExpr,
    scope: &VarScope,
    predicate: F,
) -> Result<bool, BotError>
where
    F: FnOnce(std::cmp::Ordering) -> bool,
{
    let left = resolve_expr(left, scope)?;
    let right = resolve_expr(right, scope)?;
    let ordering = match (left, right) {
        (Value::String(left), Value::String(right))
        | (Value::Choice(left), Value::Choice(right)) => left.cmp(&right),
        (Value::Integer(left), Value::Integer(right)) => left.cmp(&right),
        (Value::Boolean(left), Value::Boolean(right)) => left.cmp(&right),
        _ => {
            let refusal = Err(BotError::PredicateTypeMismatch);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "compare_expr: returning an error to the caller");
            return refusal;
        }
    };
    Ok(predicate(ordering))
}

/// Reports the cursor's position and the session's accounting.
///
/// Manual rather than derived: the session holds its resolver and its journal
/// behind `dyn` seams, so a derive is not available, and it holds the transcript
/// in full, which a derived rendering would print entry by entry. What a reader
/// of a session's `Debug` wants is where the cursor is, what it is holding, and
/// what it has spent — so the collections are printed as the counts that answer
/// that, and `finish_non_exhaustive` marks the omission rather than hiding it.
impl core::fmt::Debug for Session {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Session")
            .field("id", &self.id)
            .field("current", &self.current)
            .field("terminal", &self.terminal)
            .field("steps", &self.steps)
            .field("visited", &self.visited.len())
            .field("transcript", &self.transcript.len())
            .field("decisions", &self.decisions.len())
            .field("retained", &self.retained)
            .field("limits", &self.limits)
            .finish_non_exhaustive()
    }
}

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

    /// Return a small validated flow used by focused unit tests.
    fn end_flow() -> Result<FlowSpec, BotError> {
        FlowSpec::new(
            BTreeMap::new(),
            "end",
            BTreeMap::from([(String::from("end"), NodeKind::End)]),
            Vec::new(),
            BTreeMap::new(),
            FlowBounds::new(4),
        )
    }

    #[test]
    fn predicates_compare_typed_values() -> Result<(), BotError> {
        let mut declarations = BTreeMap::new();
        declarations.insert(String::from("answer"), VarType::Integer);
        let mut scope = VarScope::new(declarations)?;
        scope.set_from_answer("answer", "7")?;
        let predicate = Predicate::Gt(
            ValueExpr::Var(String::from("answer")),
            ValueExpr::Literal(Value::Integer(3)),
        );
        assert!(predicate.evaluate(&scope)?);
        Ok(())
    }

    #[test]
    fn templates_use_scope_values() -> Result<(), BotError> {
        let mut declarations = BTreeMap::new();
        declarations.insert(String::from("name"), VarType::String);
        let mut scope = VarScope::new(declarations)?;
        scope.set_from_answer("name", "Ada")?;
        let rendered = scope.interpolate("Hello ${name}")?;
        assert_eq!(rendered, "Hello Ada");
        Ok(())
    }

    /// One declared type paired with candidate answer strings and the value
    /// each must decode to.
    fn decode_cases() -> Vec<(VarType, &'static str, Result<Value, AnswerRejection>)> {
        let choice = || VarType::Choice(vec![String::from("yes"), String::from("no")]);
        vec![
            // A string variable accepts anything, untrimmed: the declared type
            // is what decides, not a literal spelling.
            (
                VarType::String,
                "Continue",
                Ok(Value::String(String::from("Continue"))),
            ),
            (
                VarType::String,
                "  padded  ",
                Ok(Value::String(String::from("  padded  "))),
            ),
            (VarType::Integer, "7", Ok(Value::Integer(7))),
            (VarType::Integer, " -12 ", Ok(Value::Integer(-12))),
            (VarType::Integer, "007", Ok(Value::Integer(7))),
            (VarType::Integer, "7.5", Err(AnswerRejection::NotAnInteger)),
            (VarType::Integer, "", Err(AnswerRejection::NotAnInteger)),
            (
                VarType::Integer,
                "99999999999999999999",
                Err(AnswerRejection::IntegerOutOfRange),
            ),
            (VarType::Boolean, "yes", Ok(Value::Boolean(true))),
            (VarType::Boolean, " TRUE ", Ok(Value::Boolean(true))),
            (VarType::Boolean, "No", Ok(Value::Boolean(false))),
            (
                VarType::Boolean,
                "Continue",
                Err(AnswerRejection::NotABoolean),
            ),
            (choice(), "yes", Ok(Value::Choice(String::from("yes")))),
            (choice(), " No ", Ok(Value::Choice(String::from("no")))),
            (
                choice(),
                "approve",
                Err(AnswerRejection::NotADeclaredChoice),
            ),
        ]
    }

    #[test]
    fn the_answer_decoder_is_one_function_for_validation_and_assignment() {
        // The decode table is the whole statement of what "this candidate can
        // be stored" means, and both the load-time check and the runtime
        // assignment read it. Every branch of every declared type is here,
        // including the two integer failures, which are distinct verdicts: a
        // typo and a value too large to store need different repairs.
        for (declared, answer, expected) in decode_cases() {
            assert_eq!(
                declared.decode_answer(answer),
                expected,
                "decoding {answer:?} as {} disagreed with the table",
                declared.label()
            );
        }
    }

    #[test]
    fn assignment_uses_the_same_decoder_validation_does() -> Result<(), BotError> {
        // The property that makes the load-time check worth anything: for every
        // case the decoder accepts, assigning supplies the answer to a scope
        // and stores exactly the value the decoder named. A second, separately
        // written assignment path is what let a flow load and then be
        // unanswerable.
        for (declared, answer, expected) in decode_cases() {
            let mut declarations = BTreeMap::new();
            declarations.insert(String::from("slot"), declared.clone());
            let mut scope = VarScope::new(declarations)?;

            let assigned = scope.set_from_answer("slot", answer);
            match expected {
                Ok(value) => {
                    assigned?;
                    assert_eq!(
                        scope.get("slot"),
                        Some(&value),
                        "assigning {answer:?} as {} stored the wrong value",
                        declared.label()
                    );
                }
                Err(rejection) => {
                    assert!(
                        matches!(assigned, Err(BotError::InvalidVariableValue { .. })),
                        "assigning {answer:?} as {} must refuse with the typed value error, got \
                         {assigned:?} ({rejection})",
                        declared.label()
                    );
                    assert!(
                        scope.get("slot").is_none(),
                        "a refused assignment must not write the variable"
                    );
                }
            }
        }
        Ok(())
    }

    #[test]
    fn every_rejection_renders_a_cause_a_reader_can_act_on() {
        let rejections = [
            AnswerRejection::NotAnInteger,
            AnswerRejection::IntegerOutOfRange,
            AnswerRejection::NotABoolean,
            AnswerRejection::NotADeclaredChoice,
        ];
        for rejection in rejections {
            let rendered = rejection.to_string();
            assert!(
                !rendered.is_empty() && rendered.chars().any(char::is_alphabetic),
                "a rejection is rendered into a diagnostic, so it cannot be empty: {rendered:?}"
            );
        }
    }

    #[test]
    fn an_ask_whose_variable_cannot_hold_its_options_is_refused_at_load() -> Result<(), BotError> {
        // The counterexample the review filed: a boolean variable and a
        // question offering "Continue"/"Cancel". Every candidate is decodable
        // at load time, and neither one is storable, so the document is refused
        // rather than accepted and then unanswerable.
        let outcome = FlowSpec::new(
            BTreeMap::from([(String::from("decision"), VarType::Boolean)]),
            "ask",
            BTreeMap::from([
                (
                    String::from("ask"),
                    NodeKind::Ask {
                        var: String::from("decision"),
                        options: vec![String::from("Continue"), String::from("Cancel")],
                        routes: BTreeMap::from([
                            (String::from("Continue"), String::from("done")),
                            (String::from("Cancel"), String::from("done")),
                        ]),
                    },
                ),
                (String::from("done"), NodeKind::End),
            ]),
            Vec::new(),
            BTreeMap::new(),
            FlowBounds::new(8),
        );
        let BotError::AskOptionNotAssignable {
            node,
            variable,
            option,
            expected,
            cause,
        } = (match outcome {
            Err(error) => error,
            Ok(spec) => {
                return Err(BotError::MalformedFlow {
                    cause: format!("accepted a flow with {} nodes", spec.nodes().len()),
                });
            }
        })
        else {
            return Err(BotError::MalformedFlow {
                cause: String::from("refused for the wrong reason"),
            });
        };

        // The five facts the diagnostic has to carry: where, which variable,
        // which candidate, what type was expected, and why.
        assert_eq!(node, "ask", "the refusal names the ask node");
        assert_eq!(variable, "decision", "the refusal names the variable");
        assert_eq!(
            option, "Continue",
            "the refusal names the candidate, not just the node"
        );
        assert_eq!(expected, "boolean", "the refusal names the expected type");
        assert_eq!(
            cause,
            AnswerRejection::NotABoolean.to_string(),
            "the refusal carries the decoder's own reason"
        );
        Ok(())
    }

    #[test]
    fn an_ask_the_variable_can_hold_is_still_accepted() -> Result<(), BotError> {
        // The other half of the rule, so the check above cannot be satisfied by
        // refusing everything: a boolean variable offered boolean literals, a
        // choice variable offered its own declared values, and an integer
        // variable offered integers all load.
        let accepted = [
            (
                VarType::Boolean,
                vec![String::from("yes"), String::from("no")],
            ),
            (
                VarType::Integer,
                vec![String::from("0"), String::from("-1")],
            ),
            (
                VarType::Choice(vec![String::from("yes"), String::from("no")]),
                vec![String::from("Yes"), String::from("NO")],
            ),
            (
                VarType::String,
                vec![String::from("anything"), String::from("")],
            ),
        ];
        for (declared, options) in accepted {
            let routes = options
                .iter()
                .map(|option| (option.clone(), String::from("done")))
                .collect();
            let spec = FlowSpec::new(
                BTreeMap::from([(String::from("slot"), declared.clone())]),
                "ask",
                BTreeMap::from([
                    (
                        String::from("ask"),
                        NodeKind::Ask {
                            var: String::from("slot"),
                            options,
                            routes,
                        },
                    ),
                    (String::from("done"), NodeKind::End),
                ]),
                Vec::new(),
                BTreeMap::new(),
                FlowBounds::new(8),
            )?;
            assert_eq!(
                spec.nodes().len(),
                2,
                "a {} ask over storable candidates must load",
                declared.label()
            );
        }
        Ok(())
    }

    #[test]
    fn the_default_resolver_has_an_explicit_unrecognized_case() {
        let options = vec![String::from("yes"), String::from("no")];
        let question = Question::new("ask", &options);
        let resolver = crate::language::LanguageResolver::new();
        assert!(
            matches!(
                resolver.resolve("maybe", &question).into_resolution(),
                Resolution::Absent { .. }
            ),
            "an unrecognized answer is Absent, which is not the same as Ambiguous"
        );
        assert_eq!(
            resolver.resolve("yes", &question).into_resolution(),
            Resolution::Resolved {
                index: 0,
                tier: MatchTier::Exact,
                score: 1.0,
                lead: 1.0,
            }
        );
    }

    #[test]
    fn end_session_stops_at_terminal() -> Result<(), BotError> {
        let session = Session::new("test", end_flow()?)?;
        assert_eq!(session.current(), None);
        assert_eq!(session.terminal(), Some(&Terminal::Completed));
        Ok(())
    }

    /// The four terminals, each paired with the disposition it must report.
    fn terminals() -> [(Terminal, Disposition); 4] {
        [
            (Terminal::Completed, Disposition::Completed),
            (
                Terminal::Referred {
                    target: String::from("tier-2"),
                },
                Disposition::Referred,
            ),
            (
                Terminal::HandedOff {
                    target: String::from("agent"),
                },
                Disposition::HandedOff,
            ),
            (
                Terminal::Refused {
                    reason: String::from("out of scope"),
                },
                Disposition::Refused,
            ),
        ]
    }

    #[test]
    fn disposition_and_effect_knowledge_are_reported_independently() {
        // The cross-product: every terminal against every effect history. Each
        // axis comes back unchanged whatever the other says, because they are
        // two facts rather than two arms of one choice.
        let histories = [
            EffectLedger::new(0, 0), // nothing attempted
            EffectLedger::new(1, 0), // one effect, confirmed
            EffectLedger::new(0, 1), // one attempted, occurrence unknown
            EffectLedger::new(2, 1), // confirmed and unknown at once
            EffectLedger::new(3, 2),
        ];

        for (terminal, expected) in terminals() {
            for ledger in histories {
                let report = terminal.outcome(ledger);
                assert_eq!(
                    report.disposition(),
                    expected,
                    "no effect history may change what the workflow decided"
                );
                assert_eq!(
                    report.effects(),
                    ledger,
                    "no disposition may change what is known about the effects"
                );
                assert_eq!(
                    report.needs_reconciliation(),
                    ledger.unsettled() > 0,
                    "reconciliation follows the unsettled count and nothing else"
                );
            }
        }
    }

    #[test]
    fn a_refusal_no_longer_erases_an_unsettled_effect() {
        // The counterexample from the review, kept as a regression. Two runs
        // refused for the same reason, differing only in whether an earlier
        // effect was left in doubt. The old classifier returned `Failure` for
        // both, which is the one answer that cannot be acted on: only the
        // second one needs an effect reconciled before anyone retries.
        let refused = Terminal::Refused {
            reason: String::from("later step denied"),
        };

        let settled = refused.outcome(EffectLedger::new(0, 0));
        let unknown = refused.outcome(EffectLedger::new(0, 1));

        assert_eq!(
            settled.disposition(),
            unknown.disposition(),
            "both runs were refused, and the report says so in both cases"
        );
        assert!(
            !settled.needs_reconciliation(),
            "nothing was attempted, so there is nothing to reconcile"
        );
        assert!(
            unknown.needs_reconciliation(),
            "an earlier effect may be live; a refusal does not settle it"
        );
        assert_ne!(
            settled, unknown,
            "histories differing on a possibly-live effect must stay distinguishable"
        );
    }

    #[test]
    fn an_unsettled_effect_does_not_imply_a_confirmed_one() {
        // The second inference error the review named. `unsettled > 0` was
        // documented as "part of the output exists", which does not follow: one
        // attempted effect whose response was lost may have produced none, and
        // the report has to say what is known rather than the flattering half.
        let report = Terminal::Completed.outcome(EffectLedger::new(0, 1));

        assert_eq!(
            report.effects().confirmed(),
            0,
            "nothing was confirmed, so nothing may be claimed to exist"
        );
        assert_eq!(
            report.effects().unsettled(),
            1,
            "the unknown effect is still counted"
        );
        assert!(
            report.needs_reconciliation(),
            "the run needs reconciling, which is not the same statement as having \
             partly succeeded"
        );
    }

    #[test]
    fn an_indeterminate_effect_is_what_puts_a_run_in_doubt() {
        // The law tying the two halves of this change together: the error says
        // an effect may have happened, and that is exactly what puts the run in
        // doubt. Neither half is reachable in practice without the other.
        let errors = [BotError::EffectIndeterminate {
            domain: String::from("gh::merge"),
            cause: String::from("request timed out"),
        }];
        let unsettled = errors
            .iter()
            .filter(|error| matches!(**error, BotError::EffectIndeterminate { .. }))
            .count();

        assert_eq!(unsettled, 1, "the run left one effect unsettled");
        let report = Terminal::Completed.outcome(EffectLedger::new(0, unsettled));
        assert_eq!(
            report.disposition(),
            Disposition::Completed,
            "an unsettled effect does not change what the workflow decided"
        );
        assert!(
            report.needs_reconciliation(),
            "an indeterminate effect is what puts a completed run in doubt"
        );
    }

    #[test]
    fn a_report_round_trips_through_json() -> Result<(), Box<dyn std::error::Error>> {
        // A report is written to a journal and read back by whoever reconciles
        // it, so it has to survive the trip with both facts intact.
        let report = Terminal::Refused {
            reason: String::from("denied"),
        }
        .outcome(EffectLedger::new(2, 1));

        let json = crate::json::to_string(&report)?;
        let back: Outcome = crate::json::from_str(&json)?;

        assert_eq!(
            back, report,
            "a report has to survive the journal it is written to"
        );
        assert_eq!(
            back.disposition(),
            Disposition::Refused,
            "the refusal survives the round trip"
        );
        assert!(back.needs_reconciliation(), "so does the unresolved effect");
        Ok(())
    }
}