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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Test Engine V3 - Realistic conversation flow, no contamination.
"""

import json
import random
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

from rich.console import Console
from rich.panel import Panel

from ..models import ActionType, Bot, Persona, Scenario, TestResult, TestSession
from ..utils.env import env_float, env_int
from ..utils.logging import get_logger
from .ai_client import AIClient
from .browser_controller import BrowserController
from .knowledge_boundary import fetch_duolly_boundary
from .knowledge_memory import knowledge_memory_service
from .question_planner import QuestionPlanner
from .rag_evaluator import RAGEvaluator
from .response_usefulness import is_response_useful_for_continuation
from .source_evidence import SourceEvidenceFetcher
from .tone_evaluator import ToneEvaluator
from .turn_evaluator import TurnEvaluator
from .turn_watchdog import TurnWatchdog

logger = get_logger(__name__)

console = Console()


@dataclass
class BotResponse:
    """Risposta del bot con contenuti testuali e non testuali."""

    text: str = ""
    has_map: bool = False
    has_image: bool = False
    has_link: bool = False
    has_button: bool = False
    has_list: bool = False
    has_table: bool = False
    links: List[Any] = field(default_factory=list)
    buttons: List[str] = field(default_factory=list)
    raw_html: str = ""

    def has_rich_content(self) -> bool:
        """Verifica se la risposta contiene contenuti non testuali."""
        return (
            self.has_map
            or self.has_image
            or self.has_link
            or self.has_button
            or self.has_list
            or self.has_table
        )

    def to_text(self) -> str:
        """Restituisce il testo completo per backward compatibility."""
        parts = [self.text]
        if self.has_map:
            parts.append("[Mappa fornita]")
        if self.has_image:
            parts.append("[Immagine fornita]")
        if self.links:
            rendered_links = []
            for link in self.links:
                if isinstance(link, dict):
                    title = str(link.get("title") or "").strip()
                    url = str(link.get("url") or "").strip()
                    rendered_links.append(f"{title} ({url})" if title else url)
                else:
                    rendered_links.append(str(link))
            parts.append(f"[Links: {', '.join(rendered_links)}]")
        if self.buttons:
            parts.append(f"[Bottoni: {', '.join(self.buttons)}]")
        return " ".join(parts)


class TestEngine:
    """Test engine with realistic conversation flow."""

    def __init__(
        self,
        ai_client: AIClient,
        rag_evaluator: RAGEvaluator,
        tone_evaluator: ToneEvaluator,
        turn_evaluator: Optional[TurnEvaluator] = None,
        output_dir: str = "./output",
        event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
        stop_requested: Optional[Callable[[], bool]] = None,
        save_callback: Optional[Callable[[TestResult], None]] = None,
        max_messages: Optional[int] = None,
        persona_system_prompt_override: Optional[str] = None,
    ):
        self.ai_client = ai_client
        self.rag_eval = rag_evaluator
        self.tone_eval = tone_evaluator
        self.turn_eval = turn_evaluator
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.event_handler = event_handler
        self.stop_requested = stop_requested
        self.save_callback = save_callback  # Callback to save intermediate results
        self.max_messages = max_messages  # Maximum messages allowed for this session
        self.persona_system_prompt_override = (
            str(persona_system_prompt_override).strip() if persona_system_prompt_override else None
        )
        self._knowledge_boundary = None
        source_timeout_seconds = max(
            env_float("SOURCE_EVIDENCE_TIMEOUT_SECONDS", 8.0),
            8.0,
        )
        source_total_budget_seconds = max(
            env_float("SOURCE_EVIDENCE_TOTAL_BUDGET_SECONDS", 24.0),
            source_timeout_seconds * 2,
        )
        self._source_fetcher = SourceEvidenceFetcher(
            max_sources_per_turn=max(env_int("SOURCE_EVIDENCE_MAX_PER_TURN", 3), 0),
            per_source_timeout_seconds=source_timeout_seconds,
            total_budget_seconds=source_total_budget_seconds,
            max_excerpt_chars=max(env_int("SOURCE_EVIDENCE_MAX_CHARS", 1800), 400),
        )

        self.browser: Optional[BrowserController] = None
        self.current_session: Optional[TestSession] = None
        self.interaction_history: List[Dict[str, Any]] = []
        self.conversation_log: List[Dict[str, Any]] = []
        self.last_bot_message: Optional[str] = None
        self.scenario_results: Dict[str, Any] = {}
        self._current_result: Optional[TestResult] = None  # Track current result for saving
        self._followup_topics: Dict[str, List[str]] = (
            {}
        )  # Track topics already followed up per scenario
        self._max_followups_per_step = 1  # Max 1 follow-up per step to stay on track
        self.messages_sent_count = 0
        self._limit_stop_emitted = False
        self._reserved_messages_for_future_scenarios = 0
        self._agent_deterministic_fallbacks: List[str] = []
        self.question_planner = QuestionPlanner(ai_client=ai_client)
        self._session_min_turns = 1
        # 8 (era 5): un singolo retrieval su query brevi e generiche tornava
        # solo 5 chunk, alcuni dei quali "boilerplate" del portale (header,
        # menu di navigazione). Con 8 abbiamo abbastanza copertura per i
        # claim multi-fatto (es. lista di monumenti con date e nomi).
        self._memory_top_k = max(env_int("KNOWLEDGE_RETRIEVE_TOP_K", 8), 1)

    def _emit(self, event: Dict[str, Any]) -> None:
        if self.event_handler:
            self.event_handler(event)

    def _emit_log(
        self,
        level: str,
        category: str,
        message: str,
        **meta: Any,
    ) -> None:
        """Emit a structured log event with category for easier debugging.

        Categories in use: browser | api | parse | engine | retrieval | evaluator.
        """
        payload: Dict[str, Any] = {
            "type": "log",
            "level": level,
            "category": category,
            "message": message,
        }
        if meta:
            payload.update(meta)
        self._emit(payload)

    def _arm_turn_watchdog(self, scenario_id: str, step_id: Optional[str]) -> None:
        """Start a one-shot timer that flags the turn as aborted on expiry.

        Disabled when WATCHDOG_TURN_TIMEOUT_SEC<=0. Disarm via
        _disarm_turn_watchdog() to cancel before the timer fires.
        """
        # Cancel any leftover watchdog from a prior turn (defensive — shouldn't
        # happen if the caller pairs arm/disarm correctly).
        prev = getattr(self, "_active_watchdog", None)
        if prev is not None:
            try:
                prev.__exit__(None, None, None)
            except Exception:
                pass
        self._turn_aborted = False
        timeout = env_int("WATCHDOG_TURN_TIMEOUT_SEC", 180)

        def _on_timeout() -> None:
            self._turn_aborted = True
            try:
                self._emit_log(
                    "warning",
                    "watchdog",
                    f"Turn watchdog fired after {timeout}s",
                    scenario_id=scenario_id,
                    step_id=step_id,
                )
            except Exception:
                pass
            try:
                logger.warning(
                    "watchdog_fired",
                    extra={
                        "scenario_id": scenario_id,
                        "step_id": step_id,
                        "timeout_sec": timeout,
                    },
                )
            except Exception:
                pass

        wd = TurnWatchdog(timeout, _on_timeout)
        wd.__enter__()
        self._active_watchdog = wd

    def _disarm_turn_watchdog(self) -> bool:
        """Cancel the active watchdog and return whether it had fired.

        Returns True if the turn was aborted by the watchdog (caller should
        downgrade the turn outcome to a transient failure).
        """
        wd = getattr(self, "_active_watchdog", None)
        if wd is not None:
            try:
                wd.__exit__(None, None, None)
            except Exception:
                pass
            self._active_watchdog = None
        aborted = bool(getattr(self, "_turn_aborted", False))
        self._turn_aborted = False
        return aborted

    def _trim_screenshot_urls(self, result: "TestResult") -> None:
        """Keep only the most recent N screenshot URLs in memory.

        On 100+ turn sessions the list would otherwise grow unbounded and
        bloat both the in-memory result and the DB blob on each save. The
        underlying files on Supabase Storage are not deleted — only the
        in-memory pointer list is trimmed. Default 200, 0 disables.
        """
        keep_last = max(0, env_int("SCREENSHOT_MEMORY_KEEP_LAST", 200))
        if keep_last <= 0:
            return
        urls = getattr(result, "screenshot_urls", None)
        if not urls:
            return
        if len(urls) > keep_last:
            del urls[: len(urls) - keep_last]

    def _is_stop_requested(self) -> bool:
        if not self.stop_requested:
            return False
        try:
            return bool(self.stop_requested())
        except Exception:
            return False

    def _has_reached_message_limit(self) -> bool:
        return bool(self.max_messages and self.messages_sent_count >= self.max_messages)

    def _remaining_message_budget(self) -> Optional[int]:
        if not self.max_messages:
            return None
        return max(self.max_messages - self.messages_sent_count, 0)

    def _should_rotate_to_next_scenario(
        self,
        *,
        remaining_scenarios_to_cover: int,
        current_scenario_covered: bool,
    ) -> bool:
        """Preserve budget so all selected scenarios are at least exercised."""
        budget = self._remaining_message_budget()
        if budget is None:
            return False
        if remaining_scenarios_to_cover <= 0:
            return False
        # Once current scenario has at least one turn, keep at least one message
        # for each remaining scenario.
        return current_scenario_covered and budget <= remaining_scenarios_to_cover

    def _stop_for_message_limit(self, result: TestResult) -> None:
        if not self.max_messages:
            return
        message = f"Maximum messages limit ({self.max_messages}) reached"
        if not self._limit_stop_emitted:
            console.print(f"\n[yellow]⚠️ {message}. Stopping session.[/yellow]")
            self._emit(
                {
                    "type": "status",
                    "status": "stopped",
                    "message": message,
                    "messages_sent": self.messages_sent_count,
                    "max_messages": self.max_messages,
                }
            )
            self._limit_stop_emitted = True
        result.status = "stopped"
        result.error_message = message
        result.completed_at = datetime.now()

    def run_multi_scenario_test(
        self,
        bot: Bot,
        scenarios: List[Scenario],
        persona: Persona,
        session: TestSession,
        headless: bool = False,
    ) -> TestResult:
        """Run multiple scenarios with retry logic (max 3 attempts per scenario)."""
        self.current_session = session
        # 2026-05-17: tieni il bot accessibile come attributo così
        # `_effective_fallbacks_for(step)` può costruire la lista bot+
        # scenario+sub+session con il helper centralizzato. Senza questo
        # avevamo solo `self._agent_deterministic_fallbacks` (bot-only),
        # ignorando i marker scenario/sub/session-level (BUG #1 audit).
        self._current_bot = bot
        # 2026-05-17 (no_sources_mode): se il bot non ha knowledge sources
        # assegnate, il judge non può verificare claim. In quel caso
        # tutte le risposte sostantive saranno marcate
        # `insufficient_sources` e l'unico verdict positivo possibile è
        # il match con i deterministic_fallbacks configurati a mano.
        # Calcoliamo il flag una volta a session-start; tutti i turni
        # usano lo stesso valore.
        self._no_sources_mode: bool = False
        try:
            from src.db.database import get_db as _get_db
            from src.db.repositories import KnowledgeRepository
            workspace_id = getattr(session, "workspace_id", None) or getattr(bot, "workspace_id", None)
            if workspace_id and getattr(bot, "id", None):
                _db = _get_db()
                with _db.get_session() as _s:
                    _repo = KnowledgeRepository(_s)
                    _bindings = _repo.list_active_source_versions_for_bot(
                        workspace_id, bot.id, include_workspace_fallback=False,
                    )
                    self._no_sources_mode = not bool(_bindings)
        except Exception:
            # Best-effort: in caso di errore manteniamo False (logica
            # standard del judge), evitiamo di degradare l'evaluation.
            self._no_sources_mode = False
        session_max_turns = getattr(session, "max_turns", None) or getattr(
            session, "max_messages", None
        )
        if session_max_turns is not None:
            self.max_messages = int(session_max_turns)
        self._session_min_turns = max(int(getattr(session, "min_turns", 1) or 1), 0)
        self.interaction_history = []
        self.conversation_log = []
        self.last_bot_message = None
        self.scenario_results = {}
        self._followup_topics = {}  # Reset follow-up tracking
        # Track sub-scenarios already covered with a satisfactory turn
        # (intent_label in {satisfied, partial}). Used to skip them on retry
        # attempts so we don't replay every step from scratch when only one
        # failed.
        self._covered_subscenarios: Dict[str, set] = {}
        self.messages_sent_count = 0
        self._limit_stop_emitted = False
        self._knowledge_boundary = self._load_knowledge_boundary(bot)
        self._agent_deterministic_fallbacks = [
            str(item).strip().lower()
            for item in (getattr(bot, "deterministic_fallbacks", []) or [])
            if str(item).strip()
        ]

        # Track scenario attempts and completions
        scenario_attempts = {}  # scenario_id -> attempt_count
        scenario_completed = {}  # scenario_id -> bool
        max_attempts_per_scenario = 3

        # Use session.id as scenario_id for multi-scenario tests (UUID compatible)
        result = TestResult(
            workspace_id=getattr(session, "workspace_id", None),
            session_id=session.id,
            scenario_id=session.id,  # Use session ID as scenario ID for multi tests
            persona_id=persona.id,
            status="pending",
            started_at=datetime.now(),
        )
        self._current_result = result

        limit_info = f" | Max messages: {self.max_messages}" if self.max_messages else ""
        console.print(
            Panel.fit(
                f"[bold blue]Multi-Scenario Test[/bold blue]\n"
                f"Bot: {bot.name} | Persona: {persona.name}\n"
                f"Scenarios: {len(scenarios)} | Max attempts: {max_attempts_per_scenario}{limit_info}",
                title="AI Test Engine V3",
            )
        )

        try:
            # 1. Initialize browser once for all scenarios.
            # Retry only on LAUNCH failures (Chromium missing, driver crash).
            # URL/navigation failures (Page.goto timeouts, net::ERR_*) are not
            # retryable: relaunching a fresh browser won't make a slow/unreachable
            # host respond. Spawning two Playwright processes back-to-back also
            # gives the visual impression of "multiple instances opening".
            def _is_launch_failure(detail: Optional[str]) -> bool:
                msg = (detail or "").lower()
                url_related = (
                    "page.goto" in msg
                    or "net::err" in msg
                    or "err_aborted" in msg
                    or "err_name_not_resolved" in msg
                    or "err_connection" in msg
                    or "err_timed_out" in msg
                    or "frame was detached" in msg
                )
                return bool(msg) and not url_related

            browser_ok = False
            browser_detail: Optional[str] = None
            for attempt in range(1, 3):  # 2 tentativi massimi
                if self._init_browser(bot, headless):
                    browser_ok = True
                    break
                browser_detail = (
                    getattr(self.browser, "last_error", None) if self.browser else None
                ) or browser_detail
                self._emit_log(
                    "warning",
                    "browser",
                    f"Browser startup failed (attempt {attempt}): {browser_detail or 'unknown error'}",
                    attempt=attempt,
                )
                # BrowserController.start() already cleans up on failure, but
                # defensively drop any lingering reference so the next attempt
                # starts from a clean slate.
                self.browser = None
                if not _is_launch_failure(browser_detail):
                    # Not worth retrying: it's a URL/navigation issue. Fail fast.
                    self._emit_log(
                        "warning",
                        "browser",
                        "Skipping retry: failure is URL/navigation related, not a browser launch error.",
                    )
                    break
                if attempt < 2:
                    time.sleep(1.0 * attempt)  # small backoff between launch retries
            if not browser_ok:
                result.status = "error"
                result.error_message = (
                    f"Failed to start browser: {browser_detail}"
                    if browser_detail
                    else "Failed to start browser"
                )
                self._emit_log(
                    "error",
                    "browser",
                    result.error_message,
                    fatal=True,
                )
                return result

            # 2. Execute all scenarios with retry logic
            # Track whether each scenario has been at least exercised with one user turn.
            scenario_coverage: Dict[str, bool] = {str(s.id): False for s in scenarios}

            def remaining_uncovered_after(index: int) -> int:
                return sum(
                    1
                    for future in scenarios[index + 1 :]
                    if not scenario_coverage.get(str(future.id), False)
                )

            for scenario_index, scenario in enumerate(scenarios):
                scenario_id = str(scenario.id)
                scenario_name = scenario.name
                scenario_rotated_for_budget = False

                # Initialize tracking for this scenario
                if scenario_id not in scenario_attempts:
                    scenario_attempts[scenario_id] = 0
                    scenario_completed[scenario_id] = False

                # Try up to max_attempts_per_scenario times to complete this scenario
                while (
                    scenario_attempts[scenario_id] < max_attempts_per_scenario
                    and not scenario_completed[scenario_id]
                    and not self._is_stop_requested()
                ):
                    remaining_to_cover = remaining_uncovered_after(scenario_index)
                    self._reserved_messages_for_future_scenarios = remaining_to_cover
                    if self._should_rotate_to_next_scenario(
                        remaining_scenarios_to_cover=remaining_to_cover,
                        current_scenario_covered=scenario_coverage.get(scenario_id, False),
                    ):
                        scenario_rotated_for_budget = True
                        budget = self._remaining_message_budget()
                        message = (
                            f"Rotating to next scenario to preserve coverage "
                            f"(remaining budget={budget}, scenarios left={remaining_to_cover})"
                        )
                        console.print(f"[yellow]⚖️ {message}[/yellow]")
                        self._emit({"type": "log", "level": "warning", "message": message})
                        break

                    # Check max messages limit: if budget is globally exhausted but there
                    # are other scenarios still uncovered, break out of this scenario loop
                    # so the outer loop can exercise the remaining ones.
                    if self._has_reached_message_limit():
                        if remaining_uncovered_after(scenario_index) > 0:
                            scenario_rotated_for_budget = True
                            self._emit_log(
                                "warning",
                                "engine",
                                "Global message limit reached; skipping remaining attempts for this scenario to keep coverage.",
                                scenario_id=scenario_id,
                            )
                            break
                        self._stop_for_message_limit(result)
                        return result

                    scenario_attempts[scenario_id] += 1
                    attempt_num = scenario_attempts[scenario_id]

                    console.print(
                        f"\n[bold cyan]Scenario: {scenario_name}[/bold cyan] "
                        f"(Attempt {attempt_num}/{max_attempts_per_scenario})"
                    )

                    # Emit scenario status
                    self._emit(
                        {
                            "type": "scenario_status",
                            "scenario_id": scenario_id,
                            "scenario_name": scenario_name,
                            "status": "in_progress",
                            "attempt": attempt_num,
                            "max_attempts": max_attempts_per_scenario,
                        }
                    )

                    # Get steps for this scenario
                    steps = scenario.steps if scenario.steps else []
                    if not steps:
                        steps = self._auto_generate_steps_for_scenario(scenario)

                    # Tag each step with scenario info
                    subscenario_lookup: Dict[str, Any] = {
                        str(getattr(sub, "id")): sub
                        for sub in (getattr(scenario, "subscenarios", []) or [])
                        if getattr(sub, "id", None)
                    }
                    for step in steps:
                        step.scenario_id = str(scenario.id)
                        step.scenario_name = scenario.name
                        step.attempt = attempt_num
                        subscenario_id = str(getattr(step, "subscenario_id", "") or "").strip()
                        subscenario = subscenario_lookup.get(subscenario_id)
                        # 2026-05-17: attach scenario/subscenario refs ai
                        # step così downstream `_effective_fallbacks_for`
                        # può estrarre `success_criteria.fallback_markers`
                        # dai due livelli. Prima esistevano solo
                        # `step.scenario_id`/`scenario_name` (string),
                        # insufficiente per leggere i markers.
                        step._scenario_obj = scenario  # type: ignore[attr-defined]
                        step._subscenario_obj = subscenario  # type: ignore[attr-defined]
                        if subscenario and not getattr(step, "subscenario_name", None):
                            step.subscenario_name = str(
                                getattr(subscenario, "name", "") or scenario.name
                            ).strip()
                        if subscenario and not getattr(step, "subscenario_goal", None):
                            step.subscenario_goal = str(
                                getattr(subscenario, "goal", "")
                                or scenario.description
                                or scenario.name
                            ).strip()

                        criteria_for_scope = (
                            getattr(subscenario, "success_criteria", None) if subscenario else None
                        ) or getattr(scenario, "success_criteria", None)
                        step.expected_scope = self._infer_scope_expectation_for_components(
                            success_criteria=criteria_for_scope,
                            category=(getattr(scenario, "category", "") or ""),
                            name=(
                                str(getattr(subscenario, "name", "")).strip()
                                if subscenario
                                else (scenario.name or "")
                            ),
                            description=(
                                str(getattr(subscenario, "goal", "")).strip()
                                if subscenario
                                else (scenario.description or "")
                            ),
                            tags=list(getattr(scenario, "tags", []) or []),
                        )

                        effective_followup_policy = getattr(step, "followup_policy", None)
                        if not effective_followup_policy:
                            effective_followup_policy = (
                                getattr(subscenario, "followup_policy", None)
                                if subscenario
                                else None
                            ) or getattr(scenario, "followup_policy", "limited")
                        step.followup_policy = self._normalize_followup_policy(
                            effective_followup_policy
                        )

                        effective_followup_max_turns = getattr(step, "followup_max_turns", None)
                        if effective_followup_max_turns is None:
                            effective_followup_max_turns = (
                                getattr(subscenario, "followup_max_turns", None)
                                if subscenario
                                else None
                            )
                            if effective_followup_max_turns is None:
                                effective_followup_max_turns = getattr(
                                    scenario,
                                    "followup_max_turns",
                                    self._max_followups_per_step,
                                )
                        step.followup_max_turns = int(
                            effective_followup_max_turns or self._max_followups_per_step
                        )

                    # Execute steps for this attempt
                    attempt_success = True
                    for step_idx, step in enumerate(steps):
                        # Retry skip: on attempts > 1, skip sub-scenarios that
                        # already produced a satisfactory turn in a previous
                        # attempt. Without this the runner replays every step
                        # from scratch and burns ~2x the turns on repeated
                        # intents (see plan: Issue 3).
                        step_subscenario_id = str(
                            getattr(step, "subscenario_id", "") or ""
                        ).strip()
                        if (
                            attempt_num > 1
                            and step_subscenario_id
                            and step_subscenario_id
                            in self._covered_subscenarios.get(scenario_id, set())
                        ):
                            sub_label = (
                                str(getattr(step, "subscenario_name", "") or "").strip()
                                or step_subscenario_id[:8]
                            )
                            self._emit(
                                {
                                    "type": "log",
                                    "level": "info",
                                    "message": (
                                        f"Sub-scenario '{sub_label[:40]}' già coperto, "
                                        f"skip su attempt {attempt_num}"
                                    ),
                                    "scenario_id": scenario_id,
                                    "step_id": getattr(step, "step_id", None),
                                }
                            )
                            continue

                        remaining_to_cover = remaining_uncovered_after(scenario_index)
                        self._reserved_messages_for_future_scenarios = remaining_to_cover
                        if self._should_rotate_to_next_scenario(
                            remaining_scenarios_to_cover=remaining_to_cover,
                            current_scenario_covered=scenario_coverage.get(scenario_id, False),
                        ):
                            scenario_rotated_for_budget = True
                            attempt_success = False
                            budget = self._remaining_message_budget()
                            message = (
                                f"Pausing scenario '{scenario_name}' to preserve "
                                f"{remaining_to_cover} message slot(s) for remaining scenarios "
                                f"(budget={budget})."
                            )
                            console.print(f"[yellow]⚖️ {message}[/yellow]")
                            self._emit({"type": "log", "level": "warning", "message": message})
                            break

                        if self._has_reached_message_limit():
                            if remaining_uncovered_after(scenario_index) > 0:
                                scenario_rotated_for_budget = True
                                attempt_success = False
                                self._emit_log(
                                    "warning",
                                    "engine",
                                    "Message limit reached mid-step; moving to next scenario for coverage.",
                                    scenario_id=scenario_id,
                                    step_id=getattr(step, "step_id", None),
                                )
                                break
                            self._stop_for_message_limit(result)
                            return result

                        if self._is_stop_requested():
                            result.status = "stopped"
                            result.error_message = "Stopped manually"
                            break

                        console.print(
                            f"\n[bold]Step {step_idx + 1}/{len(steps)}:[/bold] {step.step_id}"
                        )
                        before_messages = self.messages_sent_count
                        success = self._execute_conversation_turn(bot, persona, step, result)
                        if self._disarm_turn_watchdog():
                            # Watchdog fired during this turn: treat as transient
                            # failure, do NOT count it as a sent message, and let
                            # the scenario continue at the next step.
                            success = False
                            if self.messages_sent_count > before_messages:
                                self.messages_sent_count = before_messages
                            self._emit_log(
                                "warning",
                                "engine",
                                "Turn aborted by watchdog; continuing scenario.",
                                scenario_id=scenario_id,
                                step_id=getattr(step, "step_id", None),
                            )
                        if self.messages_sent_count > before_messages:
                            scenario_coverage[scenario_id] = True
                        if result.status == "stopped":
                            # If we hit the limit while there are still uncovered scenarios,
                            # continue with next scenario instead of ending the whole run.
                            if (
                                self._has_reached_message_limit()
                                and remaining_uncovered_after(scenario_index) > 0
                                and scenario_coverage.get(scenario_id, False)
                            ):
                                scenario_rotated_for_budget = True
                                attempt_success = False
                                result.status = "pending"
                                result.error_message = None
                                self._emit(
                                    {
                                        "type": "log",
                                        "level": "warning",
                                        "message": "Message limit reached for current scenario; moving to next scenario for coverage.",
                                    }
                                )
                                break
                            if (
                                self._has_reached_message_limit()
                                and scenario_id in self.scenario_results
                            ):
                                scenario_info = self.scenario_results[scenario_id]
                                expected_scope = scenario_info.get(
                                    "expected_scope"
                                ) or self._infer_scope_expectation(scenario)
                                scenario_info["status"] = "failed"
                                scenario_info["completed"] = False
                                if not scenario_info.get("outcome_type"):
                                    scenario_info["outcome_type"] = (
                                        "out_of_scope_fallback_fail"
                                        if expected_scope == "out_of_scope"
                                        else "in_scope_fail"
                                    )
                                scenario_info["completion_reason"] = (
                                    "Message budget exhausted before scenario completion"
                                )
                            # If there are remaining uncovered scenarios, don't abort
                            # the whole run — break out to let them try.
                            if remaining_uncovered_after(scenario_index) > 0:
                                scenario_rotated_for_budget = True
                                attempt_success = False
                                result.status = "pending"
                                result.error_message = None
                                break
                            return result
                        if not success:
                            console.print(f"[yellow]Step {step.step_id} had issues[/yellow]")
                            attempt_success = False
                            # Mid-session browser crash recovery: if the
                            # underlying Chromium died, try restarting it so
                            # the run can continue instead of failing the
                            # whole session. Capped by BROWSER_RECOVERY_MAX.
                            try:
                                if self.browser is not None and not self.browser.is_alive():
                                    self._try_recover_browser(bot, headless, result)
                            except Exception as recovery_exc:
                                self._emit_log(
                                    "error",
                                    "browser",
                                    f"Browser recovery check failed: {recovery_exc}",
                                )

                        # Pause between turns
                        time.sleep(random.uniform(1.5, 3.0))

                    self._reserved_messages_for_future_scenarios = 0

                    # Evaluate scenario outcome (in-scope / out-of-scope + fallback behavior)
                    scenario_outcome = self._evaluate_scenario_outcome(scenario, attempt_success)
                    if scenario_rotated_for_budget and not scenario_outcome.get("passed", False):
                        budget_reason = "Message budget preserved to ensure all selected scenarios are exercised"
                        existing_reason = str(scenario_outcome.get("reason") or "").strip()
                        if existing_reason and budget_reason.lower() not in existing_reason.lower():
                            scenario_outcome["reason"] = f"{budget_reason}. {existing_reason}"
                        else:
                            scenario_outcome["reason"] = budget_reason
                    is_completed = scenario_outcome.get("passed", False)
                    scenario_completed[scenario_id] = is_completed

                    if scenario_id in self.scenario_results:
                        self.scenario_results[scenario_id]["status"] = (
                            "completed" if is_completed else "failed"
                        )
                        self.scenario_results[scenario_id]["completed"] = bool(is_completed)
                        self.scenario_results[scenario_id]["attempts"] = attempt_num
                        self.scenario_results[scenario_id]["outcome_type"] = scenario_outcome.get(
                            "outcome_type"
                        )
                        self.scenario_results[scenario_id]["completion_reason"] = (
                            scenario_outcome.get("reason")
                        )
                        self.scenario_results[scenario_id]["fallback_detected"] = (
                            scenario_outcome.get("fallback_detected", False)
                        )
                        self.scenario_results[scenario_id]["fallback_required"] = (
                            scenario_outcome.get("fallback_required", True)
                        )
                        self.scenario_results[scenario_id]["boundary_violations_count"] = (
                            scenario_outcome.get("boundary_violations_count", 0)
                        )
                        subscenario_outcomes = scenario_outcome.get("subscenario_outcomes") or {}
                        if subscenario_outcomes:
                            sub_map = self.scenario_results[scenario_id].setdefault(
                                "subscenarios", {}
                            )
                            for sub_id, sub_outcome in subscenario_outcomes.items():
                                entry = sub_map.setdefault(
                                    str(sub_id),
                                    {
                                        "name": sub_outcome.get("name") or str(sub_id),
                                        "goal": sub_outcome.get("goal") or "",
                                        "turns": [],
                                    },
                                )
                                entry["name"] = sub_outcome.get("name") or entry.get("name")
                                entry["goal"] = sub_outcome.get("goal") or entry.get("goal")
                                entry["status"] = (
                                    "completed" if bool(sub_outcome.get("passed")) else "failed"
                                )
                                entry["completed"] = bool(sub_outcome.get("passed"))
                                entry["outcome_type"] = sub_outcome.get("outcome_type")
                                entry["completion_reason"] = sub_outcome.get("reason")
                                entry["fallback_detected"] = bool(
                                    sub_outcome.get("fallback_detected", False)
                                )
                                entry["fallback_required"] = bool(
                                    sub_outcome.get("fallback_required", True)
                                )
                                entry["boundary_violations_count"] = int(
                                    sub_outcome.get("boundary_violations_count", 0) or 0
                                )

                    if is_completed:
                        console.print(
                            f"[bold green]✅ Scenario '{scenario_name}' COMPLETED on attempt {attempt_num}![/bold green]"
                        )
                        self._emit(
                            {
                                "type": "scenario_status",
                                "scenario_id": scenario_id,
                                "scenario_name": scenario_name,
                                "status": "completed",
                                "attempt": attempt_num,
                                "message": f"Scenario completed successfully on attempt {attempt_num}",
                                "outcome_type": scenario_outcome.get("outcome_type"),
                                "reason": scenario_outcome.get("reason"),
                            }
                        )
                    elif scenario_rotated_for_budget:
                        console.print(
                            f"[yellow]⚖️ Scenario '{scenario_name}' paused after attempt {attempt_num} to keep coverage for remaining scenarios[/yellow]"
                        )
                    elif attempt_num < max_attempts_per_scenario:
                        console.print(
                            f"[yellow]⚠️ Scenario '{scenario_name}' not completed. Retrying...[/yellow]"
                        )
                        self._emit(
                            {
                                "type": "scenario_status",
                                "scenario_id": scenario_id,
                                "scenario_name": scenario_name,
                                "status": "retrying",
                                "attempt": attempt_num,
                                "message": f"Attempt {attempt_num} failed, will retry...",
                                "outcome_type": scenario_outcome.get("outcome_type"),
                                "reason": scenario_outcome.get("reason"),
                            }
                        )
                        # Wait before retry
                        time.sleep(random.uniform(2.0, 4.0))
                    else:
                        console.print(
                            f"[bold red]❌ Scenario '{scenario_name}' FAILED after {max_attempts_per_scenario} attempts[/bold red]"
                        )
                        self._emit(
                            {
                                "type": "scenario_status",
                                "scenario_id": scenario_id,
                                "scenario_name": scenario_name,
                                "status": "failed",
                                "attempt": attempt_num,
                                "message": f"Scenario failed after {max_attempts_per_scenario} attempts",
                                "outcome_type": scenario_outcome.get("outcome_type"),
                                "reason": scenario_outcome.get("reason"),
                            }
                        )

                    # Save intermediate results after each attempt
                    self._save_intermediate_results(result)

                    # Move to next scenario when current one is paused for budget balancing.
                    if scenario_rotated_for_budget:
                        break

                    if self._is_stop_requested():
                        break

                self._reserved_messages_for_future_scenarios = 0
                if self._is_stop_requested():
                    break

            # 4. Finalize
            # Determine status based on scenario completion
            completed_count = sum(1 for v in scenario_completed.values() if v)
            total_turns = len(self.conversation_log)
            if self._is_stop_requested():
                result.status = "stopped"
                result.termination_reason = "manual_stop"
            elif self._has_reached_message_limit():
                result.status = "failed"
                result.termination_reason = "max_turns"
            elif completed_count == len(scenarios) and total_turns >= self._session_min_turns:
                result.status = "passed"  # All scenarios completed
                result.termination_reason = "goal_reached"
            elif completed_count == len(scenarios) and total_turns < self._session_min_turns:
                result.status = "failed"
                result.termination_reason = "min_turns_not_met"
            else:
                result.status = "failed"  # Any missing scenario completion counts as failed
                result.termination_reason = "goal_not_reached"
            result.completed_at = datetime.now()
            result.conversation_log = json.dumps(
                self.conversation_log, ensure_ascii=False, default=str
            )
            result.scenario_results = self.scenario_results

            # Calculate final stats
            completed_count = sum(1 for v in scenario_completed.values() if v)
            total_scenarios = len(scenarios)

            console.print("\n[bold]=== Session Summary ===[/bold]")
            console.print(f"Scenarios completed: {completed_count}/{total_scenarios}")
            console.print(f"Total conversation turns: {total_turns}")

            self._emit(
                {
                    "type": "session_summary",
                    "scenarios_completed": completed_count,
                    "scenarios_total": total_scenarios,
                    "total_turns": total_turns,
                    "termination_reason": result.termination_reason,
                }
            )

        except Exception as e:
            console.print(f"[red]Test error: {e}[/red]")
            result.status = "error"
            result.error_message = str(e)
            result.termination_reason = "error"
            result.completed_at = datetime.now()
            # Still save what we have
            result.conversation_log = json.dumps(
                self.conversation_log, ensure_ascii=False, default=str
            )
            result.scenario_results = self.scenario_results

        finally:
            # Persist a final screenshot (useful even for failed runs), then save results.
            if self.browser:
                try:
                    final_path = self.browser.capture_screenshot("final")
                    if final_path:
                        result.screenshot_urls.append(final_path)
                        self._trim_screenshot_urls(result)
                except Exception:
                    pass

            # Always save final results
            self._save_intermediate_results(result)

            if self.browser:
                self.browser.cleanup()
                self.browser = None

        return result

    def run_test(
        self,
        bot: Bot,
        scenario: Scenario,
        persona: Persona,
        session: TestSession,
        headless: bool = False,
    ) -> TestResult:
        """Run a single scenario test."""
        return self.run_multi_scenario_test(bot, [scenario], persona, session, headless)

    def _try_recover_browser(self, bot: Bot, headless: bool, result: TestResult) -> bool:
        """Attempt to recover from a mid-session browser crash.

        Capped by BROWSER_RECOVERY_MAX per session (default 3, 0 disables).
        On success the run continues from the next step; on failure the
        caller stays in its normal failure path (status stays as-is).
        Cookie/login state inside the bot is lost, which is acceptable for
        the stateless chatbots this platform targets.
        """
        max_recoveries = max(0, env_int("BROWSER_RECOVERY_MAX", 3))
        if max_recoveries <= 0:
            return False
        attempts_used = int(getattr(self, "_browser_recovery_attempts", 0) or 0)
        if attempts_used >= max_recoveries:
            self._emit_log(
                "error",
                "browser",
                f"Browser recovery budget exhausted ({attempts_used}/{max_recoveries}).",
            )
            return False
        self._browser_recovery_attempts = attempts_used + 1
        self._emit_log(
            "warning",
            "browser",
            f"Detected dead browser mid-session — attempting recovery ({self._browser_recovery_attempts}/{max_recoveries}).",
        )
        try:
            if self.browser is not None:
                try:
                    self.browser.cleanup()
                except Exception:
                    pass
                self.browser = None
        except Exception:
            pass
        if not self._init_browser(bot, headless):
            self._emit_log(
                "error",
                "browser",
                "Browser recovery failed: relaunch did not succeed.",
            )
            return False
        self._emit(
            {
                "type": "browser_recovered",
                "attempt": self._browser_recovery_attempts,
                "max": max_recoveries,
                "message": "Browser recovered mid-session; continuing.",
            }
        )
        self._emit_log(
            "info",
            "browser",
            f"Browser recovered (attempt {self._browser_recovery_attempts}/{max_recoveries}).",
        )
        try:
            logger.info(
                "browser_recovered",
                extra={
                    "attempt": self._browser_recovery_attempts,
                    "max_recoveries": max_recoveries,
                    "session_id": str(getattr(result, "session_id", "")) or None,
                },
            )
        except Exception:
            pass
        return True

    def _init_browser(self, bot: Bot, headless: bool) -> bool:
        """Initialize and start browser."""
        self.browser = BrowserController(
            selectors=bot.selectors.model_dump(),
            output_dir=str(self.output_dir),
            headless=headless,
            slow_mo=env_int("BROWSER_SLOW_MO", 0),
        )

        if not self.browser.start(str(bot.url)):
            detail = getattr(self.browser, "last_error", None) or "Unknown error"
            console.print(f"[red]Failed to start browser: {detail}[/red]")
            # Surface the root cause to UI logs for production debugging.
            self._emit({"type": "error", "message": f"Failed to start browser: {detail}"})
            return False

        # Emit a first screenshot as soon as the page is loaded, so production
        # (headless) runs still provide visual confirmation immediately.
        current_url = getattr(getattr(self.browser, "page", None), "url", None) or str(bot.url)
        title = ""
        try:
            title = self.browser.page.title() if getattr(self.browser, "page", None) else ""
        except Exception:
            title = ""
        self._emit(
            {
                "type": "log",
                "level": "info",
                "message": f"Browser ready (headless={headless}). URL: {current_url}{' | ' + title if title else ''}",
            }
        )
        try:
            # Live preview (overwrites a single file) + persisted evidence (unique file).
            live_path = self.browser.capture_live_screenshot("live") if self.browser else None
            if live_path:
                self._emit(
                    {
                        "type": "screenshot",
                        "path": live_path,
                        "label": "browser_ready",
                        "live": True,
                    }
                )

            evidence_path = (
                self.browser.capture_screenshot("browser_ready") if self.browser else None
            )
            if evidence_path and self._current_result:
                self._current_result.screenshot_urls.append(evidence_path)
                self._trim_screenshot_urls(self._current_result)

            if not live_path and not evidence_path:
                self._emit(
                    {
                        "type": "log",
                        "level": "warning",
                        "message": "Browser ready, but screenshot capture returned no file (headless viewer may stay blank).",
                    }
                )
        except Exception as e:
            # Never fail the run due to screenshot/logging, but do surface the failure.
            self._emit(
                {
                    "type": "log",
                    "level": "warning",
                    "message": f"Browser ready, but screenshot capture failed: {e}",
                }
            )

        # Click "New Chat" if configured
        if bot.auto_click_new_chat:
            clicked = self.browser.click_new_chat()
            if clicked:
                console.print("[dim]Clicked 'New Chat'[/dim]")
                self.browser.wait(1.0)

        return True

    def _execute_conversation_turn(
        self,
        bot: Bot,
        persona: Persona,
        step,
        result: TestResult,
    ) -> bool:
        """
        Execute a single conversation turn with realistic flow:
        1. Read/understand current state (including last bot response)
        2. Think and decide what to say next
        3. Type message with realistic delay
        4. Wait for and read bot response
        5. Evaluate and record
        """
        scenario_id = str(getattr(step, "scenario_id", "unknown"))
        scenario_name = getattr(step, "scenario_name", "Unknown")

        # Backstop watchdog: a stuck LLM/Playwright/judge that ignores its own
        # timeout would otherwise freeze the whole run. The watchdog sets a
        # flag; the caller (run_multi_scenario_test) downgrades the turn to
        # failed and continues the scenario. Armed here, disarmed by the
        # caller via _disarm_turn_watchdog() right after the call returns.
        self._arm_turn_watchdog(scenario_id, getattr(step, "step_id", None))

        try:
            # === PHASE 1: PERCEIVE (Read current state) ===
            console.print("[dim]Phase 1: Reading conversation state...[/dim]")

            # Emit phase start
            self._emit(
                {
                    "type": "phase",
                    "phase": "perceive",
                    "message": "Reading conversation state...",
                    "step_id": step.step_id,
                }
            )

            context = self.browser.get_context()

            # Build rich context including conversation history
            conversation_summary = self._build_conversation_summary()

            # Emit what the AI sees
            self._emit(
                {
                    "type": "ai_sees",
                    "context_preview": context[:200] if context else "No context",
                    "conversation_history": conversation_summary,
                    "last_bot_message": (
                        self.last_bot_message[:150] if self.last_bot_message else "None"
                    ),
                    "step_id": step.step_id,
                }
            )

            # === PHASE 2: THINK (Understand and decide) ===
            console.print("[dim]Phase 2: Understanding and deciding action...[/dim]")

            # Emit phase start
            self._emit(
                {
                    "type": "phase",
                    "phase": "think",
                    "message": "Understanding and deciding action...",
                    "step_id": step.step_id,
                }
            )

            # Include scenario goal in reasoning
            scenario_context = self._build_scenario_context(step)

            # Emit persona and scenario info
            self._emit(
                {
                    "type": "ai_persona",
                    "persona_name": persona.name if persona else "Unknown",
                    "persona_mood": persona.mood if persona else "neutral",
                    "scenario_context": scenario_context,
                    "step_id": step.step_id,
                }
            )

            action = self.ai_client.decide_action(
                context=context,
                history=self.interaction_history,
                persona=persona,
                last_bot_message=self.last_bot_message,
                scenario_context=scenario_context,
                system_prompt_override=self.persona_system_prompt_override,
            )

            original_action_type = action.action_type
            console.print(
                Panel(
                    f"[yellow]{action.reasoning}[/yellow]\n"
                    f"Action: [bold]{action.action_type.value}[/bold] | "
                    f"Content: '{action.content[:50]}...'",
                    title="AI Decision",
                    border_style="blue",
                )
            )

            # Force step action type if specified
            if action.action_type != step.action_type:
                action.action_type = step.action_type
                self._emit(
                    {
                        "type": "log",
                        "level": "warning",
                        "message": (
                            f"Action adjusted for step contract: {original_action_type.value} -> "
                            f"{action.action_type.value}"
                        ),
                        "step_id": step.step_id,
                    }
                )

            # Emit detailed AI reasoning (after potential action normalization)
            self._emit(
                {
                    "type": "ai_reasoning",
                    "reasoning": action.reasoning,
                    "decision": action.action_type.value,
                    "content": action.content,
                    "confidence": action.confidence,
                    "step_id": step.step_id,
                }
            )
            if "api failure" in (action.reasoning or "").lower():
                self._emit(
                    {
                        "type": "log",
                        "level": "error",
                        "message": f"AI decision fallback triggered: {action.reasoning}",
                        "step_id": step.step_id,
                    }
                )

            # === PHASE 3: ACT (Type with realistic delay) ===
            console.print("[dim]Phase 3: Typing message with realistic delay...[/dim]")

            # Emit phase start
            self._emit(
                {
                    "type": "phase",
                    "phase": "act",
                    "message": f"Executing action: {action.action_type.value}",
                    "action_type": action.action_type.value,
                    "content": action.content,
                    "step_id": step.step_id,
                }
            )

            if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
                if not action.content and step.content:
                    action.content = step.content

                if self._has_reached_message_limit():
                    self._stop_for_message_limit(result)
                    return False

            action_success = self._perform_action(action)

            if not action_success:
                console.print("[red]Action failed[/red]")
                self._emit(
                    {
                        "type": "error",
                        "message": "Action failed",
                        "step_id": step.step_id,
                    }
                )
                return False

            if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
                self.messages_sent_count += 1

            # Emit action success
            self._emit(
                {
                    "type": "action_complete",
                    "action_type": action.action_type.value,
                    "content_sent": action.content,
                    "step_id": step.step_id,
                }
            )

            # Record user message
            self._emit(
                {
                    "type": "chat",
                    "sender": "user",
                    "text": action.content,
                    "step_id": step.step_id,
                    "scenario_id": scenario_id,
                }
            )

            # === PHASE 4: WAIT FOR RESPONSE ===
            if step.wait_for_response and action.action_type == ActionType.SEND_MESSAGE:
                console.print("[dim]Phase 4: Waiting for bot response...[/dim]")

                # Emit phase start
                self._emit(
                    {
                        "type": "phase",
                        "phase": "wait",
                        "message": "Waiting for bot response...",
                        "timeout": env_int("RESPONSE_TIMEOUT", 30),
                        "step_id": step.step_id,
                    }
                )

                # Add realistic reading time before expecting response
                time.sleep(random.uniform(0.5, 1.5))

                self._emit(
                    {
                        "type": "status",
                        "message": "Bot is typing...",
                        "step_id": step.step_id,
                    }
                )

                # Wait for response with a small retry loop: some bots take longer
                # than the hardcoded timeout on the first turn (cold start, network
                # wobble). Retry with exponential backoff before giving up.
                bot_response = None
                bot_response_truncated = False  # default safe se loop non eseguito
                base_timeout = env_int("RESPONSE_TIMEOUT", 30)
                max_wait_attempts = max(env_int("RESPONSE_MAX_RETRIES", 2), 1)
                wait_retry_count = 0
                for wait_attempt in range(1, max_wait_attempts + 1):
                    if self._is_stop_requested():
                        break
                    bot_response = self.browser.wait_for_bot_response(
                        timeout=base_timeout,
                        stop_requested=self._is_stop_requested,
                        on_live_screenshot=lambda path: self._emit(
                            {"type": "screenshot", "path": path, "live": True}
                        ),
                    )
                    # Leggi il flag emesso dal browser controller: True se
                    # la risposta è stata catturata in modo parziale per
                    # timeout. Lo salviamo nel log e nell'evidence_pack
                    # per il judge.
                    bot_response_truncated = bool(
                        getattr(self.browser, "last_response_was_truncated", False)
                    )
                    if bot_response and str(bot_response).strip():
                        break
                    wait_retry_count += 1
                    if wait_attempt < max_wait_attempts:
                        backoff = min(2 ** (wait_attempt - 1), 8)
                        self._emit_log(
                            "warning",
                            "api",
                            f"Empty/timeout bot response (attempt {wait_attempt}/{max_wait_attempts}); retrying in {backoff}s.",
                            step_id=getattr(step, "step_id", None),
                            attempt=wait_attempt,
                        )
                        time.sleep(backoff)

                # Get rich content data (maps, images, links, buttons)
                rich_content = {}
                if bot_response and self.browser:
                    try:
                        response_with_rich = self.browser.get_last_bot_response_with_rich_content()
                        rich_content = response_with_rich.get("rich_content", {})
                        if (
                            rich_content.get("has_map")
                            or rich_content.get("has_image")
                            or rich_content.get("has_link")
                        ):
                            console.print(
                                f"[dim]📎 Rich content detected: map={rich_content.get('has_map')}, image={rich_content.get('has_image')}, links={len(rich_content.get('links', []))}[/dim]"
                            )
                    except Exception as e:
                        console.print(f"[dim]Could not extract rich content: {e}[/dim]")

                source_evidence: List[Dict[str, Any]] = []
                factuality_sources: List[Dict[str, Any]] = []
                memory_hits: List[Dict[str, Any]] = []
                # Skip RAG retrieval triplo quando il judge inline è disattivato
                # (ENABLE_TURN_EVALUATOR=false / LIVE_JUDGE_ENABLED=false). Il
                # post-session judge `_run_session_judge_sync` re-esegue retrieval
                # e source matching su ogni turno, quindi non perdiamo
                # informazione: risparmiamo latenza e costo del retrieval ad
                # ogni turno live.
                if bot_response and self.turn_eval:
                    try:
                        # Triple retrieval per coprire tutti i fatti citati
                        # dal bot, anche quando il retrieve è lexical (token
                        # overlap) e non semantico:
                        #   1. Query user (topic generico)
                        #   2. Bot response (fatti specifici)
                        #   3. ENTITÀ ESTRATTE dalla bot response (nomi propri:
                        #      "Monastero del Deserto", "Santa Maria delle Grazie")
                        # Senza il punto 3, query lunghe come "monumenti
                        # storici di Sant'Agata" recuperano chunks con tanti
                        # token comuni ("monumenti", "storici") ma mancano
                        # i chunks specifici sull'entità citata.
                        primary_hits = self._retrieve_memory_hits(
                            bot=bot, query=action.content
                        )
                        bot_query = (bot_response or "").strip()[:600]
                        secondary_hits = (
                            self._retrieve_memory_hits(bot=bot, query=bot_query)
                            if bot_query
                            else []
                        )
                        # Estrai sequenze di parole capitalizzate (proper
                        # nouns multi-token tipo "Cappella Sansevero",
                        # "Santa Maria delle Grazie", "Monastero del
                        # Deserto"). Connettori interni (di, del, della,
                        # delle, dei, degli, sui, e, ai) sono permessi
                        # in lowercase tra parole capitalizzate.
                        import re as _re_entities
                        entity_re = _re_entities.compile(
                            r"\b[A-ZÀ-Ý][\wÀ-ÿ]+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?)\s+|\s+)?(?:[A-ZÀ-Ý][\wÀ-ÿ']+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?)\s+)?){0,4}"
                        )
                        candidates = entity_re.findall(bot_response or "")
                        # Re-estraggo direttamente con finditer per ottenere
                        # match completi (findall su gruppi è instabile).
                        entities = []
                        for m in _re_entities.finditer(
                            r"(?:[A-ZÀ-Ý][\wÀ-ÿ']+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?))?\s+)*[A-ZÀ-Ý][\wÀ-ÿ']{2,}",
                            bot_response or "",
                        ):
                            tok = m.group(0).strip()
                            # Filtra rumore: parole singole comuni, troppo corte.
                            if len(tok) < 6 or " " not in tok:
                                continue
                            entities.append(tok)
                        # Dedup mantenendo ordine, max 6 entità per turno.
                        seen_e: set = set()
                        unique_entities: List[str] = []
                        for e in entities:
                            k = e.lower()
                            if k in seen_e:
                                continue
                            seen_e.add(k)
                            unique_entities.append(e)
                            if len(unique_entities) >= 6:
                                break
                        entity_hits: List[Dict[str, Any]] = []
                        for ent in unique_entities:
                            try:
                                entity_hits.extend(
                                    self._retrieve_memory_hits(bot=bot, query=ent) or []
                                )
                            except Exception:
                                continue
                        seen_keys = set()
                        memory_hits = []
                        for hit in (primary_hits or []) + (secondary_hits or []) + entity_hits:
                            key = (
                                str(hit.get("source_id") or hit.get("source_name") or ""),
                                (str(hit.get("snippet") or "")[:120]),
                            )
                            if key in seen_keys:
                                continue
                            seen_keys.add(key)
                            memory_hits.append(hit)
                        source_evidence = self._collect_source_evidence(rich_content)
                        factuality_sources = self._build_factuality_sources(
                            bot=bot,
                            source_evidence=source_evidence,
                            memory_hits=memory_hits,
                        )
                    except Exception as e:
                        console.print(f"[yellow]Source evidence collection error: {e}[/yellow]")

                if bot_response:
                    console.print(
                        Panel(
                            bot_response[:300] + "..." if len(bot_response) > 300 else bot_response,
                            title="Bot Response",
                            border_style="green",
                        )
                    )

                    # Emit bot response received. `has_rich_html` segnala alla
                    # UI che il successivo evento `chat` includerà `text_html`
                    # (così la popup live può decidere se renderizzare HTML
                    # invece di plain text). Vedi `_sanitize_bot_html` in
                    # browser_controller.py.
                    _rich = rich_content if isinstance(rich_content, dict) else {}
                    self._emit(
                        {
                            "type": "bot_response_received",
                            "response_length": len(bot_response),
                            "response_preview": bot_response[:200],
                            "has_rich_html": bool(_rich.get("sanitized_html")),
                            "step_id": step.step_id,
                        }
                    )

                    # === PHASE 5: COMPREHEND AND RECORD ===
                    console.print("[dim]Phase 5: Processing response...[/dim]")

                    # Emit phase start
                    self._emit(
                        {
                            "type": "phase",
                            "phase": "comprehend",
                            "message": "Processing and evaluating response...",
                            "step_id": step.step_id,
                        }
                    )

                    # Screenshot during execution
                    screenshot_path = None
                    if self.browser:
                        screenshot_path = self.browser.capture_screenshot(
                            f"turn_{len(self.conversation_log) + 1}"
                        )
                        if screenshot_path:
                            self._emit(
                                {
                                    "type": "screenshot",
                                    "path": screenshot_path,
                                    "turn": len(self.conversation_log) + 1,
                                }
                            )

                    # Dialogic turn evaluation (AIS + intent + refusal handling).
                    turn_eval_result = None
                    if self.turn_eval:
                        try:
                            console.print("[dim]Running TurnEvaluator pipeline...[/dim]")
                            # Determine subscenario goal/intent for this step.
                            sub_goal = (
                                str(getattr(step, "subscenario_goal", "") or "").strip()
                                or str(getattr(step, "scenario_name", "") or "").strip()
                            )
                            scenario_label = str(getattr(step, "scenario_name", "") or "").strip()
                            boundary_text = (
                                getattr(self._knowledge_boundary, "content_raw", "")
                                if self._knowledge_boundary
                                else ""
                            ) or ""
                            # Effective fallbacks: bot + scenario + sub + session
                            # (fix 2026-05-17, audit pipeline fallback). Prima
                            # passava solo `_agent_deterministic_fallbacks`,
                            # ignorando i marker scenario-level configurati
                            # nello step 2 del wizard "Marcatori di fallback".
                            effective_fallbacks = self._effective_fallbacks_for(step=step)
                            turn_eval_result = self.turn_eval.evaluate(
                                user_query=action.content,
                                bot_response=bot_response,
                                agent_description=(bot.description or ""),
                                knowledge_boundary_text=boundary_text,
                                deterministic_fallbacks=effective_fallbacks,
                                retrieved_sources=factuality_sources,
                                subscenario_goal=sub_goal,
                                scenario_name=scenario_label,
                                no_sources_mode=getattr(self, "_no_sources_mode", False),
                            )
                            # Override AIS quando la cattura è stata troncata:
                            # non è giusto valutare claim su una risposta
                            # spezzata. Sostituiamo con `insufficient_sources`
                            # e una motivazione esplicita. L'intent_label
                            # resta quello del judge (può ancora esprimere
                            # un giudizio approssimato).
                            if bot_response_truncated and turn_eval_result is not None:
                                self._emit_log(
                                    "warning",
                                    "evaluator",
                                    "Risposta del bot troncata in cattura: AIS forzato a 'insufficient_sources' (claim non valutati su testo parziale).",
                                    step_id=getattr(step, "step_id", None),
                                )
                                turn_eval_result.ais_label = "insufficient_sources"
                                turn_eval_result.ais_reasoning = (
                                    "Risposta catturata in modo PARZIALE (timeout di cattura su streaming bot). "
                                    "I claim sul testo troncato non sono stati valutati per non penalizzare il bot. "
                                    + (turn_eval_result.ais_reasoning or "")
                                )
                            self._emit(
                                {
                                    "type": "turn_evaluation",
                                    "turn": len(self.conversation_log) + 1,
                                    "scenario_id": scenario_id,
                                    "step_id": step.step_id,
                                    "ais_label": turn_eval_result.ais_label,
                                    "ais_reasoning": turn_eval_result.ais_reasoning,
                                    "intent_label": turn_eval_result.intent_label,
                                    "response_type": turn_eval_result.response_type,
                                    "expected_behavior": turn_eval_result.expected_behavior,
                                    "actionability_label": turn_eval_result.actionability_label,
                                }
                            )
                            # Mark sub-scenario as covered when the evaluator
                            # confirmed the intent was at least partially met.
                            # This feeds the retry-skip logic above.
                            if turn_eval_result.intent_label in {"satisfied", "partial"}:
                                step_sub_id = str(
                                    getattr(step, "subscenario_id", "") or ""
                                ).strip()
                                if step_sub_id:
                                    self._covered_subscenarios.setdefault(
                                        scenario_id, set()
                                    ).add(step_sub_id)
                            console.print(
                                f"[dim]TurnEvaluator: ais={turn_eval_result.ais_label} intent={turn_eval_result.intent_label} "
                                f"resp={turn_eval_result.response_type} exp={turn_eval_result.expected_behavior}[/dim]"
                            )
                        except Exception as e:
                            console.print(f"[yellow]TurnEvaluator error: {e}[/yellow]")
                            self._emit_log(
                                "warning",
                                "evaluator",
                                f"TurnEvaluator failed for turn {len(self.conversation_log) + 1}: {e}",
                                step_id=step.step_id,
                            )

                    response_useful = is_response_useful_for_continuation(bot_response)
                    if not response_useful:
                        self._emit(
                            {
                                "type": "log",
                                "level": "warning",
                                "message": "Bot response is low-value for continuation; retry/follow-up may be needed.",
                                "step_id": step.step_id,
                            }
                        )

                    # Emit for UI. `text_html` viene dal sanitizer del
                    # browser_controller (`_sanitize_bot_html`) ed è una stringa
                    # HTML già pulita con whitelist tag/attr. Resta vuota se il
                    # widget chat è plain text — la popup live in tal caso usa
                    # `text` con whitespace-pre-wrap. Vedi sessions.html
                    # `addConversationMessage` e session_turns.html riga ~609.
                    bot_response_html_for_ui = ""
                    if isinstance(rich_content, dict):
                        bot_response_html_for_ui = (
                            rich_content.get("sanitized_html") or ""
                        )
                    self._emit(
                        {
                            "type": "chat",
                            "sender": "bot",
                            "text": bot_response,
                            "text_html": bot_response_html_for_ui,
                            "step_id": step.step_id,
                            "scenario_id": scenario_id,
                        }
                    )

                    # Use the new TurnEvaluator output for AIS / intent labelling.
                    if turn_eval_result is not None:
                        ais_label_value = turn_eval_result.ais_label
                        ais_reasoning_value = turn_eval_result.ais_reasoning
                        ais_claim_records = [c.to_dict() for c in turn_eval_result.claims]
                        intent_label_value = turn_eval_result.intent_label
                        intent_reasoning_value = turn_eval_result.intent_reasoning
                        response_type_value = turn_eval_result.response_type
                        expected_behavior_value = turn_eval_result.expected_behavior
                        fallback_similarity_value = turn_eval_result.fallback_similarity
                        matched_fallback_value = turn_eval_result.matched_fallback
                        actionability_label_value = turn_eval_result.actionability_label
                        actionability_reasoning_value = turn_eval_result.actionability_reasoning
                        evaluator_used = True
                    else:
                        ais_label_value = None
                        ais_reasoning_value = "Turn not evaluated: TurnEvaluator is disabled."
                        ais_claim_records = []
                        intent_label_value = None
                        intent_reasoning_value = "TurnEvaluator disabled."
                        response_type_value = None
                        expected_behavior_value = None
                        fallback_similarity_value = 0.0
                        matched_fallback_value = None
                        actionability_label_value = None
                        actionability_reasoning_value = ""
                        evaluator_used = False

                    evidence_pack = {
                        "source_evidence": source_evidence,
                        "memory_hits": memory_hits,
                        "cited_sources_total": len(source_evidence or []),
                        "memory_hits_total": len(memory_hits or []),
                        "evaluator_enabled": evaluator_used,
                        "evaluator_kind": "turn_evaluator" if evaluator_used else None,
                    }

                    # Log conversation
                    log_entry = {
                        "turn": len(self.conversation_log) + 1,
                        "scenario_id": scenario_id,
                        "scenario_name": scenario_name,
                        "subscenario_id": (
                            str(getattr(step, "subscenario_id", "")).strip() or None
                        ),
                        "subscenario_name": (
                            str(getattr(step, "subscenario_name", "")).strip() or None
                        ),
                        "step_id": step.step_id,
                        "question_source": (
                            (getattr(step, "metadata", {}) or {}).get("question_source")
                            or ("followup" if "_followup" in str(step.step_id) else "generated")
                        ),
                        "dedup_retries": int(
                            (getattr(step, "metadata", {}) or {}).get("dedup_retries") or 0
                        ),
                        "user_message": action.content,
                        "bot_response": bot_response,
                        "bot_response_data": rich_content,  # Rich content: maps, images, links, buttons
                        "source_evidence": source_evidence,
                        "factuality_context": {
                            "agent_description_available": bool((bot.description or "").strip()),
                            "knowledge_boundary_available": bool(self._knowledge_boundary),
                            "cited_sources_total": len(source_evidence),
                            "cited_sources_ok": sum(
                                1 for item in source_evidence if item.get("status") == "ok"
                            ),
                        },
                        "memory_hits": memory_hits,
                        "timestamp": datetime.now().isoformat(),
                        "goal_progress_delta": 1 if response_useful else 0,
                        "screenshot": screenshot_path,
                        "response_useful_for_continuation": response_useful,
                        # AIS verdict + new dialogic fields (response/expected/intent).
                        "correctness_label": ais_label_value,
                        "correctness_reasoning": ais_reasoning_value,
                        "claims_json": ais_claim_records,
                        "evidence_pack": evidence_pack,
                        "intent_label": intent_label_value,
                        "intent_reasoning": intent_reasoning_value,
                        "response_type": response_type_value,
                        "expected_behavior": expected_behavior_value,
                        "fallback_similarity": fallback_similarity_value,
                        "matched_fallback": matched_fallback_value,
                        "actionability_label": actionability_label_value,
                        "actionability_reasoning": actionability_reasoning_value,
                        # Flag ereditato dal browser_controller: True se la
                        # cattura del bot_response è terminata per timeout
                        "was_truncated_at_capture": bool(bot_response_truncated),
                    }
                    self.conversation_log.append(log_entry)
                    # Persist after every turn so the operator's UI reflects
                    # progress live (previously persistence was per-scenario,
                    # making long sessions look stuck for many minutes).
                    if self._current_result is not None:
                        try:
                            self._save_intermediate_results(self._current_result)
                        except Exception as save_exc:  # pragma: no cover
                            self._emit_log(
                                "warning",
                                "engine",
                                f"Per-turn persistence failed (will retry next turn): {save_exc}",
                                step_id=step.step_id,
                            )
                    self._emit(
                        {
                            "type": "turn_verdict",
                            "turn": log_entry["turn"],
                            "scenario_id": scenario_id,
                            "step_id": step.step_id,
                            "correctness_label": ais_label_value,
                            "correctness_reasoning": ais_reasoning_value,
                            "intent_label": intent_label_value,
                        }
                    )
                    self._emit(
                        {
                            "type": "memory_hits",
                            "turn": log_entry["turn"],
                            "memory_hits": memory_hits,
                            "count": len(memory_hits),
                        }
                    )

                    # Update scenario tracking
                    if scenario_id not in self.scenario_results:
                        self.scenario_results[scenario_id] = {
                            "name": scenario_name,
                            "turns": [],
                            "subscenarios": {},
                            "status": "in_progress",
                            "completed": False,
                            "expected_scope": getattr(step, "expected_scope", "in_scope"),
                            "outcome_type": None,
                            "completion_reason": None,
                            "fallback_detected": False,
                            "fallback_required": True,
                            "boundary_violations_count": 0,
                            "attempts": 0,
                        }
                    self.scenario_results[scenario_id]["turns"].append(log_entry)
                    subscenario_id = str(log_entry.get("subscenario_id") or "").strip()
                    if subscenario_id:
                        sub_map = self.scenario_results[scenario_id].setdefault("subscenarios", {})
                        if subscenario_id not in sub_map:
                            sub_map[subscenario_id] = {
                                "name": log_entry.get("subscenario_name") or subscenario_id,
                                "goal": str(getattr(step, "subscenario_goal", "") or "").strip(),
                                "turns": [],
                                "status": "in_progress",
                                "completed": False,
                                "outcome_type": None,
                                "completion_reason": None,
                            }
                        sub_map[subscenario_id]["turns"].append(log_entry)

                    # Update history for next turn
                    self.last_bot_message = bot_response
                    self.interaction_history.append(
                        {
                            "step_id": step.step_id,
                            "scenario_id": scenario_id,
                            "action": action.content,
                            "response": bot_response,
                        }
                    )

                    # Keep history manageable (last 10 exchanges)
                    if len(self.interaction_history) > 10:
                        self.interaction_history = self.interaction_history[-10:]

                    # Check if bot asked a follow-up question
                    if self._should_continue_conversation(bot_response, step):
                        if self._has_reached_message_limit():
                            self._stop_for_message_limit(result)
                            return False
                        console.print(
                            "[dim]Bot asked a follow-up. Continuing conversation...[/dim]"
                        )
                        self._handle_follow_up(bot, persona, step, result)

                    return True
                else:
                    console.print("[red]No bot response received[/red]")
                    return False
            else:
                # No wait needed
                console.print("[dim]Skipping response wait[/dim]")
                self.interaction_history.append(
                    {
                        "step_id": step.step_id,
                        "scenario_id": scenario_id,
                        "action": action.content,
                        "response": None,
                    }
                )
                return True

        except Exception as e:
            console.print(f"[red]Error in turn: {e}[/red]")
            return False

    def _build_conversation_summary(self) -> str:
        """Build summary of conversation so far."""
        if not self.interaction_history:
            return "Conversation just started."

        lines = ["\n--- Conversation History ---"]
        for i, h in enumerate(self.interaction_history[-5:], 1):  # Last 5 exchanges
            lines.append(f"{i}. User: {h['action'][:50]}...")
            if h.get("response"):
                lines.append(f"   Bot: {h['response'][:50]}...")
        lines.append("--- End History ---\n")
        return "\n".join(lines)

    def _build_scenario_context(self, step) -> str:
        """Build context about current scenario and goal.

        CRITICAL INSTRUCTION: After answering a follow-up question,
        ALWAYS return to the main scenario goal. Do NOT get lost in endless follow-ups.
        """
        lines = []
        scenario_id = str(getattr(step, "scenario_id", "unknown"))
        is_followup = getattr(step, "is_followup", False)

        if hasattr(step, "scenario_name"):
            lines.append(f"Current Scenario: {step.scenario_name}")
        if hasattr(step, "expected_intent") and step.expected_intent:
            lines.append(f"Goal: {step.expected_intent}")

        # Add critical instruction about follow-ups
        lines.append("")

        if is_followup:
            # Special instructions for follow-up steps
            lines.append("=== ⚠️ THIS IS A FOLLOW-UP RESPONSE ===")
            lines.append("The bot asked a clarification question.")
            lines.append("1. Answer directly to the question, keeping persona style.")
            lines.append("2. DO NOT ask new questions or start new topics.")
            lines.append("3. AFTER this response, we will RETURN to the main scenario goal above.")
            lines.append("4. Your next action after this MUST be to continue with the scenario.")
            lines.append("=== END FOLLOW-UP INSTRUCTIONS ===")
        else:
            lines.append("=== IMPORTANT INSTRUCTIONS ===")
            lines.append("1. Your PRIMARY objective is to achieve the scenario goal above.")
            lines.append(
                "2. If the bot asks a follow-up question, answer directly in persona style."
            )
            lines.append(
                "3. AFTER answering the follow-up, IMMEDIATELY return to the main scenario goal."
            )
            lines.append("4. DO NOT let the conversation drift away from testing the scenario.")
            lines.append("5. Stay focused: 1 follow-up max, then back to the scenario.")

            # Check if we already did a follow-up for this topic
            if scenario_id in self._followup_topics:
                topics = self._followup_topics[scenario_id]
                if topics:
                    lines.append(
                        f"6. ALREADY EXPLORED: {', '.join(t[:30] + '...' for t in topics[-2:])}"
                    )
                    lines.append(
                        "   → Do NOT explore these topics again. Proceed with main scenario."
                    )

            lines.append("=== END INSTRUCTIONS ===")

        # Log scenario goal in real-time
        if hasattr(step, "expected_intent") and step.expected_intent:
            self._emit(
                {
                    "type": "goal",
                    "goal": step.expected_intent,
                    "scenario_id": scenario_id,
                    "scenario_name": getattr(step, "scenario_name", "Unknown"),
                }
            )

        return "\n".join(lines)

    def _should_continue_conversation(self, bot_response: str, step) -> bool:
        """Check if the bot asked a follow-up question that we should answer.

        CRITICAL: Only answer 1 follow-up per topic, then return to main scenario.
        We want to test scenarios, not get lost in endless follow-ups.
        """
        if not bot_response:
            return False

        scenario_id = str(getattr(step, "scenario_id", "unknown"))
        subscenario_id = str(getattr(step, "subscenario_id", "") or "").strip()
        followup_policy = self._normalize_followup_policy(
            getattr(step, "followup_policy", "limited")
        )
        followup_max_turns = int(
            getattr(step, "followup_max_turns", self._max_followups_per_step)
            or self._max_followups_per_step
        )

        if followup_policy == "forbidden":
            self._emit(
                {
                    "type": "followup_check",
                    "message": "Follow-up disabled by policy (forbidden), proceeding with next planned step",
                    "step_id": step.step_id,
                }
            )
            return False

        # Preserve one message slot for each not-yet-covered scenario.
        if self.max_messages:
            remaining_budget = max(self.max_messages - self.messages_sent_count, 0)
            if remaining_budget <= int(self._reserved_messages_for_future_scenarios or 0):
                self._emit(
                    {
                        "type": "followup_check",
                        "message": (
                            "Skipping follow-up to preserve message budget "
                            "for remaining scenarios"
                        ),
                        "step_id": step.step_id,
                    }
                )
                return False

        # Check if this is already a follow-up step
        if "_followup" in str(step.step_id):
            # This IS a follow-up - don't do another one, return to scenario
            self._emit(
                {
                    "type": "followup_check",
                    "message": "Already in follow-up, returning to main scenario flow",
                    "step_id": step.step_id,
                }
            )
            return False

        # Check if we already did a follow-up for this step
        if scenario_id in self.scenario_results:
            turns = self.scenario_results[scenario_id].get("turns", [])
            if subscenario_id:
                turns = [
                    turn
                    for turn in turns
                    if str(turn.get("subscenario_id", "") or "").strip() == subscenario_id
                ]
            followup_count = sum(1 for t in turns if "_followup" in str(t.get("step_id", "")))
            if followup_count >= followup_max_turns:
                self._emit(
                    {
                        "type": "followup_check",
                        "message": f"Max follow-ups ({followup_max_turns}) reached for this step, continuing with scenario",
                    }
                )
                return False

        # Check if this topic was already followed up
        current_topic = getattr(step, "expected_intent", "unknown")
        if scenario_id in self._followup_topics:
            if current_topic in self._followup_topics[scenario_id]:
                self._emit(
                    {
                        "type": "followup_check",
                        "message": f"Topic '{current_topic[:30]}...' already explored, continuing with scenario",
                    }
                )
                return False

        # Check if response ends with a question
        response_lower = bot_response.lower()

        # Question indicators - keep focused
        question_words = [
            # Italiano
            "ti piacerebbe",
            "vorresti",
            "puoi dirmi",
            "hai bisogno",
            "vuoi",
            "preferisci",
            "potresti",
            "ti interessa",
            "posso aiutarti",
            "come posso",
            "dimmi",
            "fammi sapere",
            "seleziona",
            "scegli",
            # Inglese
            "would you like",
            "do you want",
            "can you tell me",
            "do you need",
            "would you prefer",
            "are you interested",
            "shall i",
            "let me know",
            "please select",
            "choose",
            "tell me",
        ]

        # Check for question marks
        has_question_mark = "?" in bot_response

        # Check for question phrases
        has_question_phrase = any(qw in response_lower for qw in question_words)

        # Check for interrogative words
        interrogative_words = [
            "quale",
            "quali",
            "come",
            "dove",
            "quando",
            "perché",
            "perche",
            "quanto",
            "chi",
            "cosa",
            "which",
            "what",
            "how",
            "where",
            "when",
            "why",
        ]
        has_interrogative = any(iw in response_lower for iw in interrogative_words)

        # Emittiamo log per debug
        self._emit(
            {
                "type": "followup_check",
                "has_question_mark": has_question_mark,
                "has_question_phrase": has_question_phrase,
                "has_interrogative": has_interrogative,
                "response_preview": bot_response[:100],
            }
        )

        # Only continue if there's a clear question
        should_continue = has_question_mark or has_question_phrase or has_interrogative

        if should_continue and followup_policy == "adaptive":
            # Lightweight contribution gate: avoid follow-up loops with generic prompts.
            weak_patterns = ("fammi sapere", "let me know", "if needed", "se vuoi")
            if any(pattern in response_lower for pattern in weak_patterns):
                self._emit(
                    {
                        "type": "followup_check",
                        "message": "Adaptive policy skipped low-value follow-up",
                    }
                )
                return False

        if should_continue:
            # Mark this topic as explored
            if scenario_id not in self._followup_topics:
                self._followup_topics[scenario_id] = []
            if current_topic not in self._followup_topics[scenario_id]:
                self._followup_topics[scenario_id].append(current_topic)

            self._emit(
                {
                    "type": "followup_check",
                    "message": f"Will answer 1 follow-up for '{current_topic[:30]}...' then return to scenario",
                }
            )

        return should_continue

    def _handle_follow_up(self, bot: Bot, persona: Persona, step, result: TestResult) -> bool:
        """Handle follow-up question from bot.

        CRITICAL: Answer the follow-up directly, then return to main scenario.
        """
        try:
            console.print("[bold yellow]🔄 Handling bot follow-up question...[/bold yellow]")

            # Emit that we're handling a follow-up
            self._emit(
                {
                    "type": "followup",
                    "message": "🔄 Bot asked a follow-up. Will answer briefly then return to scenario.",
                    "step_id": step.step_id,
                }
            )

            # Wait a bit for natural flow
            time.sleep(random.uniform(1.0, 2.0))

            # Create a new step for the follow-up
            from ..models import Step

            follow_up_step = Step(
                step_id=f"{step.step_id}_followup_{int(time.time())}",  # Unique ID
                action_type=step.action_type,
                content="",  # Will be decided by AI
                expected_intent=getattr(step, "expected_intent", ""),
                wait_for_response=True,
                metadata={"question_source": "followup", "dedup_retries": 0},
            )
            follow_up_step.scenario_id = str(getattr(step, "scenario_id", "unknown"))
            follow_up_step.scenario_name = getattr(step, "scenario_name", "Unknown")
            follow_up_step.subscenario_id = (
                str(getattr(step, "subscenario_id", "") or "").strip() or None
            )
            follow_up_step.subscenario_name = (
                str(getattr(step, "subscenario_name", "") or "").strip() or None
            )
            follow_up_step.subscenario_goal = (
                str(getattr(step, "subscenario_goal", "") or "").strip() or None
            )
            follow_up_step.followup_policy = self._normalize_followup_policy(
                getattr(step, "followup_policy", "limited")
            )
            follow_up_step.followup_max_turns = int(
                getattr(step, "followup_max_turns", self._max_followups_per_step)
                or self._max_followups_per_step
            )
            follow_up_step.is_followup = True  # Mark as follow-up
            follow_up_step.parent_step_id = step.step_id  # Track parent

            console.print(f"[dim]Created follow-up step: {follow_up_step.step_id}[/dim]")

            # Execute the follow-up turn
            success = self._execute_conversation_turn(bot, persona, follow_up_step, result)
            if self._disarm_turn_watchdog():
                # Watchdog fired during the follow-up turn — treat as failed.
                success = False
                self._emit_log(
                    "warning",
                    "engine",
                    "Follow-up turn aborted by watchdog.",
                    step_id=follow_up_step.step_id,
                )

            if success:
                console.print(
                    "[bold green]✅ Follow-up handled. Returning to main scenario...[/bold green]"
                )
                self._emit(
                    {
                        "type": "followup",
                        "message": "✅ Follow-up completed. Continuing with main scenario.",
                        "step_id": step.step_id,
                    }
                )
            else:
                console.print("[bold red]❌ Follow-up handling failed[/bold red]")

            return success

        except Exception as e:
            console.print(f"[bold red]Follow-up handling error: {e}[/bold red]")
            import traceback

            console.print(f"[red]{traceback.format_exc()}[/red]")
            return False

    def _perform_action(self, action) -> bool:
        """Execute action on browser."""
        if not self.browser:
            return False

        if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
            if not action.content:
                return False
            return self.browser.send_message(action.content, human_like=True)

        elif action.action_type == ActionType.CLICK:
            if not action.selector:
                return False
            return self.browser.click_element(action.selector)

        elif action.action_type == ActionType.WAIT:
            try:
                wait_time = float(action.content) if action.content else 2.0
                time.sleep(wait_time)
                return True
            except ValueError:
                time.sleep(2.0)
                return True

        return False

    def _load_knowledge_boundary(self, bot: Bot):
        """Load knowledge boundary once per session run."""
        boundary_url = getattr(bot, "knowledge_boundary_url", None)
        if not boundary_url:
            return None
        try:
            boundary = fetch_duolly_boundary(str(boundary_url))
            if boundary:
                self._emit(
                    {
                        "type": "log",
                        "level": "info",
                        "message": f"Knowledge boundary loaded: {str(boundary_url)}",
                    }
                )
                return boundary
            self._emit(
                {
                    "type": "log",
                    "level": "warning",
                    "message": f"Knowledge boundary unavailable: {str(boundary_url)}",
                }
            )
        except Exception as exc:
            self._emit(
                {
                    "type": "log",
                    "level": "warning",
                    "message": f"Knowledge boundary error: {str(exc)[:180]}",
                }
            )
        return None

    def _collect_source_evidence(self, rich_content: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Fetch excerpts from cited links in bot rich content."""
        links = []
        if isinstance(rich_content, dict):
            links = rich_content.get("links") or []
        if links:
            self._emit(
                {
                    "type": "log",
                    "level": "info",
                    "message": f"Factuality link candidates detected: {len(links)}",
                }
            )
        else:
            self._emit(
                {
                    "type": "log",
                    "level": "warning",
                    "message": "Factuality link candidates detected: 0 (no cited links found in response/aside)",
                }
            )
        evidence = self._source_fetcher.collect_from_links(links)
        if evidence:
            ok_count = sum(1 for item in evidence if item.get("status") == "ok")
            self._emit(
                {
                    "type": "log",
                    "level": "info",
                    "message": (
                        f"Factuality sources: {ok_count}/{len(evidence)} readable "
                        f"(max {self._source_fetcher.max_sources_per_turn} per turn)"
                    ),
                }
            )
        return evidence

    def _retrieve_memory_hits(self, *, bot: Bot, query: str) -> List[Dict[str, Any]]:
        workspace_id = (
            getattr(self.current_session, "workspace_id", None) if self.current_session else None
        )
        if not workspace_id or not str(query or "").strip():
            return []
        try:
            return knowledge_memory_service.retrieve(
                workspace_id=workspace_id,
                bot_id=bot.id,
                query=query,
                top_k=self._memory_top_k,
                source_scope="active",
            )
        except Exception as exc:
            self._emit(
                {
                    "type": "log",
                    "level": "warning",
                    "message": f"Knowledge memory retrieval error: {str(exc)[:180]}",
                }
            )
            return []

    def _build_factuality_sources(
        self,
        bot: Bot,
        source_evidence: List[Dict[str, Any]],
        memory_hits: Optional[List[Dict[str, Any]]] = None,
    ) -> List[Dict[str, Any]]:
        """Build normalized source payload for the AIS turn evaluator."""
        sources: List[Dict[str, Any]] = []

        agent_description = (getattr(bot, "description", None) or "").strip()
        if agent_description:
            sources.append(
                {
                    "source_id": "AGENT_DESC",
                    "source_type": "agent_description",
                    "title": "AI Agent description",
                    "url": None,
                    "content": agent_description[:2500],
                }
            )

        if self._knowledge_boundary:
            sources.append(
                {
                    "source_id": "BOUNDARY",
                    "source_type": "knowledge_boundary",
                    "title": "Knowledge boundary",
                    "url": getattr(self._knowledge_boundary, "source_url", None),
                    "content": (getattr(self._knowledge_boundary, "content_raw", "") or "")[:4000],
                }
            )

        for idx, item in enumerate(source_evidence, start=1):
            status = str(item.get("status") or "").strip().lower()
            excerpt = str(item.get("excerpt") or "").strip()
            source_id = f"SRC_{idx}"
            content = excerpt
            if not content:
                error = str(item.get("error") or "unavailable").strip()
                content = f"[SOURCE_UNAVAILABLE] status={status or 'unknown'}; error={error}"
            elif len(content) < 80:
                # SPA JS-rendered: il fetch HTTP ritorna solo lo skeleton
                # ("Skip to main content" o div vuoti) → ~15-30 char.
                # Marcando come UNAVAILABLE, la SRC non viene contata come
                # "real source" e il judge ricade sui MEM_n del RAG, evitando
                # falsi unsupported quando il bot cita una pagina SPA.
                content = (
                    f"[SOURCE_UNAVAILABLE] status=spa_or_thin_content; "
                    f"error=Fetched HTML had no readable text ({len(excerpt)} chars). "
                    "Probabile pagina SPA: il content è renderizzato lato client."
                )

            sources.append(
                {
                    "source_id": source_id,
                    "source_type": "cited_source",
                    "title": item.get("title") or f"Cited source {idx}",
                    "url": item.get("url"),
                    "fetch_status": status or "unknown",
                    "content": content,
                }
            )

        for idx, hit in enumerate(memory_hits or [], start=1):
            snippet = str(hit.get("snippet") or "").strip()
            if not snippet:
                continue
            sources.append(
                {
                    "source_id": f"MEM_{idx}",
                    "source_type": "knowledge_memory",
                    "title": hit.get("title") or hit.get("source_name") or f"Memory source {idx}",
                    "url": hit.get("url"),
                    "fetch_status": "indexed",
                    "content": snippet[:1800],
                }
            )

        return sources

    def _auto_generate_steps_for_scenario(self, scenario: Scenario) -> List[Any]:
        """Auto-generate steps for a scenario (supports subscenario sequencing)."""
        from ..models import Step

        goal = scenario.description or f"Test {scenario.name}"
        session_critical = list(getattr(self.current_session, "critical_questions", []) or [])
        steps: List[Any] = []

        subscenarios = sorted(
            list(getattr(scenario, "subscenarios", []) or []),
            key=lambda sub: (
                int(getattr(sub, "priority", 1) or 1),
                str(getattr(sub, "name", "") or ""),
            ),
        )
        if subscenarios:
            step_counter = 1
            for sub_index, subscenario in enumerate(subscenarios):
                sub_goal = str(getattr(subscenario, "goal", "") or "").strip() or goal
                sub_name = str(getattr(subscenario, "name", "") or "").strip() or scenario.name
                sub_seed_questions = [
                    str(item).strip()
                    for item in (getattr(subscenario, "seed_questions", []) or [])
                    if str(item).strip()
                ]
                effective_seed = sub_seed_questions or list(
                    getattr(scenario, "seed_questions", []) or []
                )
                effective_critical = session_critical if sub_index == 0 else []
                max_questions = 2 if len(subscenarios) == 1 else 1
                plan = self.question_planner.build(
                    critical_questions=effective_critical,
                    seed_questions=effective_seed,
                    scenario_name=f"{scenario.name} / {sub_name}",
                    scenario_goal=sub_goal,
                    max_questions=max_questions,
                )

                if not plan:
                    plan = self.question_planner.build(
                        critical_questions=[],
                        seed_questions=[],
                        scenario_name=f"{scenario.name} / {sub_name}",
                        scenario_goal=sub_goal,
                        max_questions=max_questions,
                    )

                for question in plan:
                    step = Step(
                        step_id=f"{scenario.id}_{step_counter}",
                        action_type=ActionType.SEND_MESSAGE,
                        content=question.text,
                        expected_intent=sub_goal,
                        wait_for_response=True,
                        metadata={
                            "question_source": question.source,
                            "dedup_retries": question.dedup_retries,
                            "subscenario_id": str(subscenario.id),
                            "subscenario_name": sub_name,
                        },
                    )
                    step.subscenario_id = str(subscenario.id)
                    step.subscenario_name = sub_name
                    step.subscenario_goal = sub_goal
                    step.followup_policy = self._normalize_followup_policy(
                        getattr(subscenario, "followup_policy", None)
                        or getattr(scenario, "followup_policy", "limited")
                    )
                    step.followup_max_turns = int(
                        getattr(subscenario, "followup_max_turns", None)
                        or getattr(scenario, "followup_max_turns", self._max_followups_per_step)
                        or self._max_followups_per_step
                    )
                    steps.append(step)
                    step_counter += 1
            return steps

        plan = self.question_planner.build(
            critical_questions=session_critical,
            seed_questions=list(getattr(scenario, "seed_questions", []) or []),
            scenario_name=scenario.name,
            scenario_goal=goal,
            max_questions=2,
        )

        if not plan:
            plan = self.question_planner.build(
                critical_questions=[],
                seed_questions=[],
                scenario_name=scenario.name,
                scenario_goal=goal,
                max_questions=2,
            )

        for idx, question in enumerate(plan, start=1):
            step = Step(
                step_id=f"{scenario.id}_{idx}",
                action_type=ActionType.SEND_MESSAGE,
                content=question.text,
                expected_intent=goal,
                wait_for_response=True,
                metadata={
                    "question_source": question.source,
                    "dedup_retries": question.dedup_retries,
                },
            )
            steps.append(step)
        return steps

    def _normalize_followup_policy(self, value: Any) -> str:
        """Normalize follow-up policy values coming from enums/string payloads."""
        raw = value.value if hasattr(value, "value") else value
        normalized = str(raw or "limited").strip().lower()
        if "." in normalized:
            normalized = normalized.split(".")[-1]
        if normalized not in {"forbidden", "limited", "adaptive"}:
            return "limited"
        return normalized

    def _infer_scope_expectation(self, scenario: Scenario) -> str:
        """Infer if the scenario is expected in-scope or out-of-scope."""
        return self._infer_scope_expectation_for_components(
            success_criteria=getattr(scenario, "success_criteria", None),
            category=(getattr(scenario, "category", "") or ""),
            name=(scenario.name or ""),
            description=(scenario.description or ""),
            tags=list(getattr(scenario, "tags", []) or []),
        )

    def _infer_scope_expectation_for_components(
        self,
        *,
        success_criteria: Optional[Any],
        category: str,
        name: str,
        description: str,
        tags: List[str],
    ) -> str:
        """Infer scope expectation from explicit criteria and textual markers."""
        explicit_scope = (
            str(getattr(success_criteria, "scope_expectation", "auto")).strip().lower()
            if success_criteria
            else "auto"
        )
        if explicit_scope in ("in_scope", "out_of_scope"):
            return explicit_scope

        normalized_category = str(category or "").lower()
        normalized_tags = [str(t).lower() for t in (tags or []) if isinstance(t, str)]
        normalized_name = str(name or "").lower()
        normalized_description = str(description or "").lower()
        searchable = " ".join(
            [normalized_category, normalized_name, normalized_description] + normalized_tags
        )

        out_of_scope_markers = (
            "out_of_scope",
            "out-of-scope",
            "oos",
            "fallback_expected",
            "knowledge_boundary_negative",
            "fuori scope",
            "fuori_scopo",
        )
        in_scope_markers = ("in_scope", "in-scope", "in scope", "dentro scope")

        if any(marker in searchable for marker in out_of_scope_markers):
            return "out_of_scope"
        if any(marker in searchable for marker in in_scope_markers):
            return "in_scope"
        return "in_scope"

    def _effective_fallbacks_for(
        self,
        step: Optional[Any] = None,
        scenario: Optional[Scenario] = None,
        subscenario: Optional[Any] = None,
        lowercase: bool = False,
    ) -> List[str]:
        """Resolve effective fallback markers per il contesto di questo step.

        Fix 2026-05-17 (audit pipeline fallback): unifica bot + scenario
        + subscenario + session usando `collect_effective_fallbacks`.
        Prima il live judge riceveva SOLO bot.deterministic_fallbacks,
        ignorando i marker scenario/sub/session-level → doppia verità
        outcome (heuristic) vs AIS label (judge).

        Argomenti:
            step: oggetto step con eventuali ref `_scenario_obj`/
                `_subscenario_obj` allegati da `run_multi_scenario_test`.
                Se None, usa scenario/subscenario passati esplicitamente.
            scenario, subscenario: override espliciti (utile da context
                diversi dal main loop).
            lowercase: se True normalizza tutto in lowercase (usato
                dall'heuristic detector che fa matching `in` su lower).

        Backward compat: se `_current_bot` non è stato impostato (test
        legacy che bypassano `run_multi_scenario_test`), pesca i marker
        bot da `_agent_deterministic_fallbacks` (vecchia interfaccia).
        """
        scen = scenario or getattr(step, "_scenario_obj", None) if step else scenario
        sub = subscenario or (getattr(step, "_subscenario_obj", None) if step else subscenario)
        from src.utils.fallback_resolution import collect_effective_fallbacks
        bot_obj = getattr(self, "_current_bot", None)
        if bot_obj is None and getattr(self, "_agent_deterministic_fallbacks", None):
            # Legacy path: nessun bot object disponibile, ma il chiamante
            # ha popolato _agent_deterministic_fallbacks. Creiamo un
            # SimpleNamespace al volo per il helper.
            from types import SimpleNamespace
            bot_obj = SimpleNamespace(
                deterministic_fallbacks=list(self._agent_deterministic_fallbacks)
            )
        return collect_effective_fallbacks(
            bot=bot_obj,
            scenario=scen,
            subscenario=sub,
            session=getattr(self, "current_session", None),
            lowercase=lowercase,
        )

    def _is_fallback_response(
        self,
        response: str,
        scenario: Optional[Scenario] = None,
        success_criteria: Optional[Any] = None,
    ) -> bool:
        """Detect safe fallback responses for out-of-scope queries.

        Generic hardcoded markers + tutti i marker custom (bot, scenario,
        subscenario, session) risolti via `_effective_fallbacks_for`.
        """
        if not response:
            return False
        response_lower = response.lower()
        # Hardcoded baseline (lingua-aware: IT + EN). Restano qui perché
        # sono pattern universali di refusal/limits che non dipendono dal
        # bot specifico.
        fallback_markers = [
            "non posso rispondere",
            "non posso aiutarti su questo",
            "non ho informazioni",
            "non dispongo di informazioni",
            "non rientra nelle mie competenze",
            "non rientra nel mio ambito",
            "fuori dal mio scope",
            "fuori dal mio ambito",
            "non sono autorizzato",
            "non posso fornire",
            "i don't have enough information",
            "i cannot answer",
            "outside my scope",
            "outside my knowledge",
        ]
        # Custom markers da bot/scenario/sub/session — risolti dal helper
        # centralizzato (2026-05-17). Quando success_criteria è passato
        # esplicitamente (chiamata legacy), la usiamo direttamente; in
        # tutti gli altri casi pesca dal contesto corrente.
        if success_criteria is not None:
            custom_markers = getattr(success_criteria, "fallback_markers", None)
            if custom_markers is None and isinstance(success_criteria, dict):
                custom_markers = success_criteria.get("fallback_markers")
            for marker in (custom_markers or []):
                m = str(marker).strip().lower()
                if m:
                    fallback_markers.append(m)
        # Aggiungi i marker effettivi (bot + scenario + sub + session)
        fallback_markers.extend(
            self._effective_fallbacks_for(scenario=scenario, lowercase=True)
        )
        return any(marker in response_lower for marker in fallback_markers)

    def _count_boundary_violations(self, turns: List[Dict[str, Any]]) -> int:
        """Boundary violations are no longer derived from per-turn 5D scores.

        Kept as zero for callers that still consult this counter; AIS labels
        ('not_attributable', 'inappropriate_fallback') are the new source of truth.
        """
        return 0

    def _check_goal_completion_from_turns(
        self,
        goal: str,
        scenario_turns: List[Dict[str, Any]],
    ) -> bool:
        """Evaluate goal completion using a normalized turn slice."""
        if not scenario_turns:
            return False
        goal_lower = str(goal or "").lower()
        goal_keywords = self._extract_goal_keywords(goal)
        last_bot_response = str(scenario_turns[-1].get("bot_response", "") or "").lower()

        keyword_matches = sum(1 for kw in goal_keywords if kw in last_bot_response)
        keyword_coverage = keyword_matches / len(goal_keywords) if goal_keywords else 0
        if keyword_coverage >= 0.3:
            return True

        completion_indicators = [
            "is ready",
            "has been created",
            "here is",
            "ti presento",
            "puoi trovare",
            "è disponibile",
            "ecco",
            "done",
            "completato",
            "puoi partire",
            "buon viaggio",
            "have a good trip",
        ]
        if any(ind in last_bot_response for ind in completion_indicators):
            return True

        if any(
            marker in last_bot_response
            for marker in ["€", "$", "euro", "dollar", "price", "cost", "prezzo"]
        ):
            if "booking" in goal_lower or "reservation" in goal_lower or "itinerary" in goal_lower:
                return True

        return self._analyze_rich_content(scenario_turns, goal_lower)

    def _evaluate_turn_group_outcome(
        self,
        *,
        turns: List[Dict[str, Any]],
        scope_expectation: str,
        success_criteria: Optional[Any],
        goal: str,
        attempt_success: bool,
        label: str,
    ) -> Dict[str, Any]:
        """Evaluate outcome for a scenario or subscenario turn group."""
        fallback_required = (
            bool(getattr(success_criteria, "fallback_required_if_out_of_scope", True))
            if success_criteria
            else True
        )
        if not attempt_success or not turns:
            if scope_expectation == "out_of_scope":
                return {
                    "passed": False,
                    "outcome_type": "out_of_scope_fallback_fail",
                    "reason": f"No valid response captured for {label} out-of-scope validation",
                    "fallback_detected": False,
                    "boundary_violations_count": 0,
                    "fallback_required": fallback_required,
                }
            return {
                "passed": False,
                "outcome_type": "in_scope_fail",
                "reason": f"No valid response captured for {label} in-scope validation",
                "fallback_detected": False,
                "boundary_violations_count": 0,
                "fallback_required": fallback_required,
            }

        last_response = str(turns[-1].get("bot_response", "") or "")
        fallback_detected = self._is_fallback_response(
            last_response,
            success_criteria=success_criteria,
        )
        boundary_violations_count = self._count_boundary_violations(turns)

        if scope_expectation == "out_of_scope":
            passed = (
                (fallback_detected and boundary_violations_count == 0)
                if fallback_required
                else boundary_violations_count == 0
            )
            reason = (
                "Fallback response detected for out-of-scope request"
                if passed and fallback_required
                else (
                    "No boundary violations detected for out-of-scope request"
                    if passed
                    else "Fallback missing or boundary violation detected"
                )
            )
            return {
                "passed": passed,
                "outcome_type": (
                    "out_of_scope_fallback_pass" if passed else "out_of_scope_fallback_fail"
                ),
                "reason": reason,
                "fallback_detected": fallback_detected,
                "boundary_violations_count": boundary_violations_count,
                "fallback_required": fallback_required,
            }

        # Criterio principale in-scope: intent satisfaction prodotto dal
        # judge. È l'unico segnale che valuta semanticamente "il bot ha
        # davvero risposto a quello che il sub-scenario chiedeva?".
        # Il vecchio `_check_goal_completion_from_turns` faceva text-matching
        # euristico tra goal e response: troppo brittle (passava risposte
        # tangenti, falliva risposte corrette ma riformulate).
        intent_labels = [
            str(t.get("intent_label") or "").strip().lower()
            for t in turns
        ]
        intent_labels = [lab for lab in intent_labels if lab and lab != "not_applicable"]
        if intent_labels:
            satisfied_or_partial = sum(1 for lab in intent_labels if lab in {"satisfied", "partial"})
            not_satisfied = sum(1 for lab in intent_labels if lab == "not_satisfied")
            # Pass se almeno un turno ha soddisfatto (anche parziale) l'intent
            # E nessun turno è stato esplicitamente classificato not_satisfied
            # E non ci sono violazioni di boundary.
            intent_passed = satisfied_or_partial > 0 and not_satisfied == 0
            passed = intent_passed and boundary_violations_count == 0
            if passed:
                reason = (
                    f"Intent soddisfatto: {satisfied_or_partial}/{len(intent_labels)} "
                    "turni con intent_label satisfied/partial."
                )
            elif not_satisfied > 0:
                reason = (
                    f"Intent non soddisfatto: {not_satisfied} turno/i marcati "
                    "not_satisfied dal judge."
                )
            elif boundary_violations_count > 0:
                reason = "Violazione di boundary rilevata (intent ignorato)."
            else:
                reason = "Nessun turno ha soddisfatto l'intent."
            return {
                "passed": passed,
                "outcome_type": "in_scope_pass" if passed else "in_scope_fail",
                "reason": reason,
                "fallback_detected": fallback_detected,
                "boundary_violations_count": boundary_violations_count,
                "fallback_required": fallback_required,
            }

        # Fallback: nessun turno è stato valutato dal judge (TurnEvaluator
        # spento o errore). Tornano al vecchio criterio testuale per non
        # bloccare le sessioni dove l'evaluator non è girato.
        goal_completed = self._check_goal_completion_from_turns(goal, turns)
        passed = goal_completed and boundary_violations_count == 0
        return {
            "passed": passed,
            "outcome_type": "in_scope_pass" if passed else "in_scope_fail",
            "reason": (
                "Goal achieved within in-scope expectations (heuristic — judge non disponibile)"
                if passed
                else "Goal not achieved or boundary violation detected (heuristic — judge non disponibile)"
            ),
            "fallback_detected": fallback_detected,
            "boundary_violations_count": boundary_violations_count,
            "fallback_required": fallback_required,
        }

    def _evaluate_scenario_outcome(
        self,
        scenario: Scenario,
        attempt_success: bool,
    ) -> Dict[str, Any]:
        """Evaluate scenario outcome with in-scope/out-of-scope semantics."""
        scenario_id = str(scenario.id)
        scenario_turns = [
            turn
            for turn in self.conversation_log
            if str(turn.get("scenario_id", "")) == scenario_id
        ]
        subscenarios = sorted(
            list(getattr(scenario, "subscenarios", []) or []),
            key=lambda sub: (
                int(getattr(sub, "priority", 1) or 1),
                str(getattr(sub, "name", "") or ""),
            ),
        )

        if subscenarios:
            subscenario_outcomes: Dict[str, Dict[str, Any]] = {}
            for subscenario in subscenarios:
                sub_id = str(getattr(subscenario, "id"))
                sub_name = str(getattr(subscenario, "name", "") or sub_id).strip()
                sub_goal = str(
                    getattr(subscenario, "goal", "") or scenario.description or scenario.name
                ).strip()
                sub_turns = [
                    turn
                    for turn in scenario_turns
                    if str(turn.get("subscenario_id", "") or "").strip() == sub_id
                ]
                sub_criteria = getattr(subscenario, "success_criteria", None) or getattr(
                    scenario, "success_criteria", None
                )
                sub_scope = self._infer_scope_expectation_for_components(
                    success_criteria=sub_criteria,
                    category=(getattr(scenario, "category", "") or ""),
                    name=sub_name,
                    description=sub_goal,
                    tags=list(getattr(scenario, "tags", []) or []),
                )
                sub_outcome = self._evaluate_turn_group_outcome(
                    turns=sub_turns,
                    scope_expectation=sub_scope,
                    success_criteria=sub_criteria,
                    goal=sub_goal,
                    attempt_success=attempt_success,
                    label=f"subscenario '{sub_name}'",
                )
                sub_outcome["name"] = sub_name
                sub_outcome["goal"] = sub_goal
                subscenario_outcomes[sub_id] = sub_outcome

            all_passed = bool(subscenario_outcomes) and all(
                bool(item.get("passed")) for item in subscenario_outcomes.values()
            )
            total_boundary_violations = sum(
                int(item.get("boundary_violations_count", 0) or 0)
                for item in subscenario_outcomes.values()
            )
            fallback_detected_any = any(
                bool(item.get("fallback_detected")) for item in subscenario_outcomes.values()
            )
            fallback_required_all = all(
                bool(item.get("fallback_required", True)) for item in subscenario_outcomes.values()
            )
            first_failure = next(
                (item for item in subscenario_outcomes.values() if not bool(item.get("passed"))),
                None,
            )
            if all_passed:
                return {
                    "passed": True,
                    "outcome_type": "in_scope_pass",
                    "reason": "All subscenarios completed successfully",
                    "fallback_detected": fallback_detected_any,
                    "boundary_violations_count": total_boundary_violations,
                    "fallback_required": fallback_required_all,
                    "subscenario_outcomes": subscenario_outcomes,
                }
            return {
                "passed": False,
                "outcome_type": (
                    "out_of_scope_fallback_fail"
                    if first_failure
                    and str(first_failure.get("outcome_type", "")).startswith("out_of_scope")
                    else "in_scope_fail"
                ),
                "reason": (
                    f"Subscenario failed: {first_failure.get('name')}. "
                    f"{str(first_failure.get('reason') or '').strip()}"
                    if first_failure
                    else "At least one subscenario failed"
                ),
                "fallback_detected": fallback_detected_any,
                "boundary_violations_count": total_boundary_violations,
                "fallback_required": fallback_required_all,
                "subscenario_outcomes": subscenario_outcomes,
            }

        scope_expectation = self._infer_scope_expectation(scenario)
        success_criteria = getattr(scenario, "success_criteria", None)
        goal = str(scenario.description or scenario.name or "").strip()
        return self._evaluate_turn_group_outcome(
            turns=scenario_turns,
            scope_expectation=scope_expectation,
            success_criteria=success_criteria,
            goal=goal,
            attempt_success=attempt_success,
            label=f"scenario '{scenario.name}'",
        )

    def _check_scenario_completion(self, scenario: Scenario, attempt_success: bool) -> bool:
        """
        Check if a scenario has been completed successfully.
        Uses AI to evaluate if the bot's responses satisfy the scenario goal.
        Also analyzes rich content (maps, images, links) in responses.
        """
        if not attempt_success:
            return False

        scenario_id = str(scenario.id)

        # Get conversation history for this scenario
        scenario_turns = []
        for turn in self.conversation_log:
            if turn.get("scenario_id") == scenario_id or turn.get("scenario_id") == str(
                scenario_id
            ):
                scenario_turns.append(turn)

        if not scenario_turns:
            return False

        goal = scenario.description or scenario.name
        return self._check_goal_completion_from_turns(goal, scenario_turns)

    def _analyze_rich_content(self, scenario_turns: List[Dict], goal_lower: str) -> bool:
        """Analyze rich content (maps, images, links) in bot responses."""

        # Collect all rich content from bot responses
        all_maps = []
        all_images = []
        all_links = []
        all_buttons = []

        for turn in scenario_turns:
            bot_response_data = turn.get("bot_response_data")
            if isinstance(bot_response_data, dict):
                if bot_response_data.get("has_map"):
                    all_maps.append(turn.get("bot_response", ""))
                if bot_response_data.get("has_image"):
                    all_images.append(turn.get("bot_response", ""))
                if bot_response_data.get("links"):
                    all_links.extend(bot_response_data.get("links", []))
                if bot_response_data.get("buttons"):
                    all_buttons.extend(bot_response_data.get("buttons", []))

        # Check if goal requires location/directions and map was provided
        if any(
            kw in goal_lower
            for kw in [
                "dove",
                "where",
                "posizione",
                "location",
                "indirizzo",
                "address",
                "mappa",
                "map",
            ]
        ):
            if all_maps:
                console.print(
                    "[green]Goal completion detected (map provided for location query)[/green]"
                )
                return True

        # Check if goal requires visual info and image was provided
        if any(
            kw in goal_lower
            for kw in ["foto", "photo", "image", "immagine", "vedere", "see", "look"]
        ):
            if all_images:
                console.print(
                    "[green]Goal completion detected (image provided for visual query)[/green]"
                )
                return True

        # Check if goal requires navigation/action and buttons were provided
        if any(
            kw in goal_lower
            for kw in ["prenotare", "book", "acquistare", "buy", "procedere", "proceed"]
        ):
            if all_buttons:
                console.print("[green]Goal completion detected (action buttons provided)[/green]")
                return True

        # Check if goal requires external resources and links were provided
        if any(kw in goal_lower for kw in ["link", "url", "sito", "website", "pagina", "page"]):
            if all_links:
                console.print("[green]Goal completion detected (links provided)[/green]")
                return True

        # General: if response contains rich content and matches goal type
        if all_maps and any(
            kw in goal_lower
            for kw in ["itinerario", "itinerary", "percorso", "route", "viaggio", "trip"]
        ):
            console.print("[green]Goal completion detected (itinerary map provided)[/green]")
            return True

        return False

    def _extract_goal_keywords(self, goal: str) -> List[str]:
        """Extract important keywords from scenario goal."""
        # Simple keyword extraction - remove common words and keep important terms
        common_words = {
            "the",
            "a",
            "an",
            "and",
            "or",
            "to",
            "in",
            "on",
            "at",
            "for",
            "with",
            "of",
            "is",
            "are",
            "be",
            "this",
            "that",
            "i",
            "want",
            "need",
            "would",
            "like",
            "can",
            "you",
            "help",
            "me",
            "un",
            "una",
            "e",
            "o",
            "il",
            "la",
            "di",
            "per",
            "con",
            "vorrei",
            "mi",
            "puoi",
            "aiutare",
        }

        words = goal.lower().split()
        keywords = [
            w.strip(".,;!?") for w in words if w.strip(".,;!?") not in common_words and len(w) > 2
        ]
        return keywords[:10]  # Max 10 keywords

    def _convert_log_to_steps(self) -> List[Dict[str, Any]]:
        """Convert conversation log to steps_results format for report compatibility."""
        steps = []
        for turn in self.conversation_log:
            step = {
                "step_id": turn.get("step_id", f"turn_{turn.get('turn', 0)}"),
                "action": "send_message",
                "content": turn.get("user_message", ""),
                "bot_response": turn.get("bot_response", ""),
                "expected_intent": turn.get("scenario_name", ""),
                "success": turn.get("bot_response") is not None
                and len(turn.get("bot_response", "")) > 0,
                "response_time_ms": None,  # Could be calculated if we track timestamps
                "rag_faithfulness": None,
                "tone_match": None,
                "intent_match": None,
                "sentiment_score": None,
                "sentiment_label": None,
                "screenshot": turn.get("screenshot"),
            }
            steps.append(step)
        return steps

    def _save_intermediate_results(self, result: TestResult):
        """Save intermediate results to ensure data persistence even if session fails."""
        try:
            # Update result object with current state
            result.conversation_log = json.dumps(
                self.conversation_log, ensure_ascii=False, default=str
            )
            result.scenario_results = self.scenario_results

            # Convert conversation log to steps_results for report compatibility
            result.steps_results = self._convert_log_to_steps()

            # Calculate current stats
            total_turns = len(self.conversation_log)
            completed_scenarios = (
                sum(1 for s in result.scenario_results.values() if s.get("completed", False))
                if result.scenario_results
                else 0
            )

            # Update result metrics
            result.total_steps = total_turns
            result.passed_steps = sum(1 for s in result.steps_results if s.get("success"))
            result.failed_steps = result.total_steps - result.passed_steps

            # Use save callback if available (for DB persistence)
            if self.save_callback:
                try:
                    self.save_callback(result)
                    console.print(
                        f"[dim]💾 Saved to database: {total_turns} turns, {completed_scenarios} scenarios completed[/dim]"
                    )
                except Exception as cb_err:
                    console.print(f"[yellow]Save callback error: {cb_err}[/yellow]")

            # Emit save event for real-time tracking
            self._emit(
                {
                    "type": "data_saved",
                    "turns_recorded": total_turns,
                    "scenarios_completed": completed_scenarios,
                    "timestamp": datetime.now().isoformat(),
                }
            )

            console.print(
                f"[dim]💾 Saved intermediate results: {total_turns} turns, {result.passed_steps} passed[/dim]"
            )

        except Exception as e:
            console.print(f"[yellow]Warning: Could not save intermediate results: {e}[/yellow]")