Spaces:
Runtime error

File size: 76,603 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Knowledge memory crawl/index/retrieval service."""

from __future__ import annotations

import hashlib
import io
import re
import threading
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import unquote, urlparse, urlunparse
from uuid import UUID

import httpx

from src.core.source_evidence import _is_safe_public_url
from src.db import KnowledgeRepository, get_db
from src.models import (
    KnowledgeChunk,
    KnowledgeCrawlPhase,
    KnowledgeCrawlRun,
    KnowledgeCrawlStatus,
    KnowledgeCrawlTrigger,
    KnowledgePage,
    KnowledgeVersionState,
)
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger

logger = get_logger(__name__)

SCRIPT_RE = re.compile(r"(?is)<script.*?>.*?</script>")
STYLE_RE = re.compile(r"(?is)<style.*?>.*?</style>")
TAG_RE = re.compile(r"(?is)<[^>]+>")
TITLE_RE = re.compile(r"(?is)<title[^>]*>(.*?)</title>")
WS_RE = re.compile(r"\s+")
WORD_RE = re.compile(r"[a-z0-9]{3,}")


def _strip_html(raw: str) -> str:
    cleaned = SCRIPT_RE.sub(" ", raw or "")
    cleaned = STYLE_RE.sub(" ", cleaned)
    cleaned = TAG_RE.sub(" ", cleaned)
    return WS_RE.sub(" ", cleaned).strip()


def _extract_title(raw_html: str) -> str:
    match = TITLE_RE.search(raw_html or "")
    if not match:
        return ""
    value = WS_RE.sub(" ", str(match.group(1) or "")).strip()
    return value[:280]


def _normalize_url(url: str) -> str:
    raw = str(url or "").strip()
    if not raw:
        return ""
    try:
        parsed = urlparse(raw)
    except Exception:
        return ""
    if parsed.scheme not in {"http", "https"}:
        return ""
    cleaned = parsed._replace(fragment="")
    return urlunparse(cleaned).strip()


def _hash_text(value: str) -> str:
    return hashlib.sha256(str(value or "").encode("utf-8")).hexdigest()


def _tokenize(value: str) -> List[str]:
    return WORD_RE.findall(str(value or "").lower())


def _estimate_tokens(value: str) -> int:
    return max(1, int(len(str(value or "")) / 4))


def _sparse_embedding(value: str, max_terms: int = 80) -> Dict[str, float]:
    tokens = _tokenize(value)
    if not tokens:
        return {}
    counts: Dict[str, int] = {}
    for token in tokens:
        counts[token] = counts.get(token, 0) + 1
    ordered = sorted(counts.items(), key=lambda item: item[1], reverse=True)[:max_terms]
    norm = sum(freq * freq for _, freq in ordered) ** 0.5 or 1.0
    return {token: float(freq) / norm for token, freq in ordered}


def _sparse_cosine(left: Dict[str, float], right: Dict[str, float]) -> float:
    if not left or not right:
        return 0.0
    if len(left) > len(right):
        left, right = right, left
    score = 0.0
    for token, value in left.items():
        score += float(value) * float(right.get(token, 0.0))
    return float(score)


# Render free tier (512MB) cannot host more than ONE Chromium instance at
# a time without OOMing the FastAPI worker. Use a process-wide semaphore
# to serialize browser-fallback fetches across crawl runs. Tunable via env
# `KNOWLEDGE_BROWSER_MAX_CONCURRENCY` for paid tiers with more headroom.
def _build_browser_semaphore() -> threading.Semaphore:
    cap = max(env_int("KNOWLEDGE_BROWSER_MAX_CONCURRENCY", 1), 1)
    return threading.Semaphore(cap)


_BROWSER_SEMAPHORE: threading.Semaphore = _build_browser_semaphore()


class KnowledgeMemoryService:
    """Persistent source-memory service with crawl + lexical retrieval."""

    def __init__(self):
        self._lock = threading.Lock()
        self._running_runs: set[str] = set()

    @property
    def crawl_enabled(self) -> bool:
        return env_bool("KNOWLEDGE_CRAWL_ENABLED", True)

    @property
    def browser_fallback_enabled(self) -> bool:
        return env_bool("KNOWLEDGE_BROWSER_FALLBACK_ENABLED", True)

    @property
    def embeddings_enabled(self) -> bool:
        return env_bool("KNOWLEDGE_EMBEDDINGS_ENABLED", False)

    def start_crawl_for_source_version(
        self,
        *,
        workspace_id: UUID,
        source_id: UUID,
        source_version_id: UUID,
        trigger: KnowledgeCrawlTrigger,
        created_by: Optional[str],
        run_async: bool = True,
    ) -> KnowledgeCrawlRun:
        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            # Single-flight per source: if any run is currently QUEUED or
            # RUNNING for this source, skip starting a duplicate. Two
            # parallel crawl runs on the same source list saturate Render
            # free tier RAM (each browser_fallback pass spawns a Chromium).
            existing = repo.list_crawl_runs_for_source(source_id, workspace_id, limit=20)
            in_flight = [
                r for r in existing
                if r.status in (KnowledgeCrawlStatus.QUEUED, KnowledgeCrawlStatus.RUNNING)
            ]
            if in_flight:
                logger.info(
                    "knowledge_crawl: skipping duplicate start (run already in flight)",
                    extra={
                        "source_id": str(source_id),
                        "in_flight_run_ids": [str(r.id) for r in in_flight],
                    },
                )
                return in_flight[0]

            run = repo.create_crawl_run(
                KnowledgeCrawlRun(
                    workspace_id=workspace_id,
                    source_id=source_id,
                    source_version_id=source_version_id,
                    trigger=trigger,
                    status=KnowledgeCrawlStatus.QUEUED,
                    phase=KnowledgeCrawlPhase.HTTP_FETCH,
                    totals={
                        "total": 0,
                        "success": 0,
                        "failed": 0,
                        "unreadable": 0,
                        "indexed_pages": 0,
                        "indexed_chunks": 0,
                    },
                    created_by=created_by,
                )
            )

        if not self.crawl_enabled:
            db = get_db()
            with db.get_session() as session:
                repo = KnowledgeRepository(session)
                repo.update_crawl_run(
                    run.id,
                    run.workspace_id,
                    {
                        "status": KnowledgeCrawlStatus.CANCELLED.value,
                        "completed_at": datetime.now(),
                        "totals": {**(run.totals or {}), "failed": int((run.totals or {}).get("failed", 0))},
                    },
                )
            return run

        if run_async:
            thread = threading.Thread(
                target=self._run_crawl_guarded,
                kwargs={"run_id": run.id, "browser_fallback": False},
                daemon=True,
                name=f"knowledge-crawl-{run.id}",
            )
            thread.start()
        else:
            self._run_crawl_guarded(run.id, browser_fallback=False)
        return run

    def start_browser_fallback(self, run_id: UUID) -> None:
        thread = threading.Thread(
            target=self._run_crawl_guarded,
            kwargs={"run_id": run_id, "browser_fallback": True},
            daemon=True,
            name=f"knowledge-browser-fallback-{run_id}",
        )
        thread.start()

    def recover_orphan_runs(self) -> int:
        """Riprende i crawl run lasciati in queued/running da un crash o restart.

        Da chiamare al boot del processo. RUNNING viene riportato a QUEUED
        (l'avanzamento committato turno-per-turno è preservato sui chunk indicizzati,
        ma il run riparte dal task scheduler interno). Idempotente.

        Single-flight per source_id: se lo stesso source ha N run orphan
        (capita quando l'utente cliccava 'Reindicizza' due volte prima del
        single-flight check in start_crawl_for_source_version), recupera
        solo il più recente e marca gli altri come CANCELLED. Evita il
        problema OOM su Render free tier dove 2 Chromium paralleli sui
        stessi URL saturavano la RAM.
        """
        if not self.crawl_enabled:
            return 0
        statuses = [KnowledgeCrawlStatus.QUEUED.value, KnowledgeCrawlStatus.RUNNING.value]
        recovered = 0
        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            try:
                orphans = repo.list_orphan_crawl_runs(statuses)
            except Exception:
                logger.exception("knowledge-recovery: list_orphan_crawl_runs failed")
                return 0

            # Dedup per source: keep the newest, cancel the rest.
            from collections import defaultdict
            by_source: Dict[str, List[KnowledgeCrawlRun]] = defaultdict(list)
            for run in orphans:
                by_source[str(run.source_id)].append(run)
            keep: List[KnowledgeCrawlRun] = []
            duplicates: List[KnowledgeCrawlRun] = []
            for source_id, runs in by_source.items():
                runs.sort(key=lambda r: r.created_at or datetime.min, reverse=True)
                keep.append(runs[0])
                duplicates.extend(runs[1:])
            if duplicates:
                logger.warning(
                    "knowledge-recovery: cancelling duplicate orphan runs",
                    extra={
                        "kept": [str(r.id) for r in keep],
                        "cancelled": [str(r.id) for r in duplicates],
                    },
                )
                for dup in duplicates:
                    try:
                        repo.update_crawl_run(
                            dup.id,
                            dup.workspace_id,
                            {
                                "status": KnowledgeCrawlStatus.CANCELLED.value,
                                "completed_at": datetime.now(),
                                "totals": {
                                    **(dup.totals or {}),
                                    "error": "cancelled_duplicate_orphan",
                                },
                            },
                        )
                    except Exception:
                        logger.exception(
                            "knowledge-recovery: cancel duplicate failed",
                            extra={"run_id": str(dup.id)},
                        )

            for run in keep:
                if run.status == KnowledgeCrawlStatus.RUNNING:
                    try:
                        repo.update_crawl_run(
                            run.id,
                            run.workspace_id,
                            {"status": KnowledgeCrawlStatus.QUEUED.value},
                        )
                    except Exception:
                        logger.exception(
                            "knowledge-recovery: reset RUNNING->QUEUED failed",
                            extra={"run_id": str(run.id)},
                        )
                        continue
            try:
                session.commit()
            except Exception:
                session.rollback()

        for run in keep:
            run_key = str(run.id)
            with self._lock:
                if run_key in self._running_runs:
                    continue
            logger.info(
                "knowledge-recovery: respawning crawl run",
                extra={"run_id": str(run.id), "previous_status": run.status.value},
            )
            thread = threading.Thread(
                target=self._run_crawl_guarded,
                kwargs={"run_id": run.id, "browser_fallback": False},
                daemon=True,
                name=f"knowledge-crawl-recover-{run.id}",
            )
            thread.start()
            recovered += 1
        return recovered

    def _run_crawl_guarded(self, run_id: UUID, browser_fallback: bool) -> None:
        """Background-thread entry point. Catches and *persists* exceptions so
        that silent failures (the daemon dying without trace) become visible
        on the KnowledgeCrawlRun row instead of vanishing.
        """
        run_key = str(run_id)
        with self._lock:
            if run_key in self._running_runs:
                return
            self._running_runs.add(run_key)
        try:
            if not browser_fallback:
                delay_ms = max(env_int("KNOWLEDGE_CRAWL_START_DELAY_MS", 600), 0)
                if delay_ms:
                    time.sleep(delay_ms / 1000.0)
            logger.info(
                "knowledge_crawl: starting",
                extra={"run_id": run_key, "browser_fallback": browser_fallback},
            )
            self.run_crawl(run_id=run_id, browser_fallback=browser_fallback)
            logger.info("knowledge_crawl: completed", extra={"run_id": run_key})
        except Exception as exc:
            logger.exception(
                "knowledge_crawl: run failed",
                extra={"run_id": run_key, "error": str(exc)[:300]},
            )
            # Persist the failure on the run row so the operator can see
            # *why* the crawl never produced chunks.
            try:
                db = get_db()
                with db.get_session() as session:
                    repo = KnowledgeRepository(session)
                    run = repo.get_crawl_run(run_id)
                    if run:
                        summary = dict(run.summary or {})
                        summary["fatal_error"] = str(exc)[:1000]
                        summary["traceback_excerpt"] = tb.splitlines()[-1][:300] if tb else ""
                        repo.update_crawl_run(
                            run_id,
                            run.workspace_id,
                            {
                                "status": KnowledgeCrawlStatus.FAILED.value,
                                "completed_at": datetime.now(),
                                "summary": summary,
                            },
                        )
            except Exception as inner:  # pragma: no cover
                _emit(f"could not persist failure for run={run_id}: {inner}")
        finally:
            with self._lock:
                self._running_runs.discard(run_key)

    def run_crawl(self, *, run_id: UUID, browser_fallback: bool = False) -> Optional[KnowledgeCrawlRun]:
        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            run = repo.get_crawl_run(run_id)
            if not run:
                return None

            if browser_fallback:
                repo.update_crawl_run(
                    run.id,
                    run.workspace_id,
                    {
                        "status": KnowledgeCrawlStatus.RUNNING.value,
                        "phase": KnowledgeCrawlPhase.BROWSER_FALLBACK.value,
                    },
                )
            else:
                repo.update_crawl_run(
                    run.id,
                    run.workspace_id,
                    {
                        "status": KnowledgeCrawlStatus.RUNNING.value,
                        "phase": KnowledgeCrawlPhase.HTTP_FETCH.value,
                        "started_at": datetime.now(),
                    },
                )

            source_version = repo.get_version(run.source_id, run.source_version_id, run.workspace_id)
            if not source_version:
                repo.update_crawl_run(
                    run.id,
                    run.workspace_id,
                    {
                        "status": KnowledgeCrawlStatus.FAILED.value,
                        "completed_at": datetime.now(),
                        "totals": {
                            "total": 0,
                            "success": 0,
                            "failed": 1,
                            "unreadable": 0,
                            "indexed_pages": 0,
                            "indexed_chunks": 0,
                            "error": "source_version_not_found",
                        },
                    },
                )
                return repo.get_crawl_run(run.id)

            rows = list((source_version.parsed_payload or {}).get("rows", []) or [])
            urls: List[str] = []
            for row in rows:
                normalized = _normalize_url(str(row.get("source_url", "") or ""))
                if normalized:
                    urls.append(normalized)
            dedup_urls = list(dict.fromkeys(urls))
            if browser_fallback:
                unreadable_pages = repo.list_pages_for_run_unreadable(run)
                dedup_urls = [page.url_canonical for page in unreadable_pages if page.url_canonical]
            if browser_fallback:
                previous = dict(run.totals or {})
                totals = {
                    "total": int(previous.get("total") or len(dedup_urls)),
                    "success": int(previous.get("success") or 0),
                    "failed": int(previous.get("failed") or 0),
                    "unreadable": int(previous.get("unreadable") or len(dedup_urls)),
                    "indexed_pages": int(previous.get("indexed_pages") or 0),
                    "indexed_chunks": int(previous.get("indexed_chunks") or 0),
                }
            else:
                totals = {
                    "total": len(dedup_urls),
                    "success": 0,
                    "failed": 0,
                    "unreadable": 0,
                    "indexed_pages": 0,
                    "indexed_chunks": 0,
                }
            repo.update_crawl_run(run.id, run.workspace_id, {"totals": totals})

            cancelled = False
            for index, url in enumerate(dedup_urls):
                # Check for an external cancel signal every N iterations.
                # The /cancel endpoint sets status=CANCELLED on the DB row;
                # the worker thread only notices that on the next probe.
                # Probing every iteration would double DB load on huge lists,
                # so we batch — 10 URLs ≈ a few seconds of work.
                if index % 10 == 0:
                    fresh = repo.get_crawl_run(run.id, run.workspace_id)
                    if fresh and fresh.status == KnowledgeCrawlStatus.CANCELLED:
                        cancelled = True
                        break

                if browser_fallback:
                    fetch_data = self._fetch_url_browser(url)
                    fetch_method = "browser"
                else:
                    fetch_data = self._fetch_url_http(url)
                    fetch_method = "http"

                page = KnowledgePage(
                    workspace_id=run.workspace_id,
                    source_id=run.source_id,
                    source_version_id=run.source_version_id,
                    url=url,
                    url_canonical=url,
                    title=str(fetch_data.get("title") or "")[:280],
                    content_type=str(fetch_data.get("content_type") or "")[:250],
                    http_status=fetch_data.get("http_status"),
                    fetch_status=str(fetch_data.get("status") or "unknown"),
                    fetch_method=fetch_method,
                    content_hash=fetch_data.get("content_hash"),
                    raw_chars=int(fetch_data.get("raw_chars") or 0),
                    cleaned_text=str(fetch_data.get("text") or ""),
                    fetched_at=datetime.now(),
                    error=str(fetch_data.get("error") or "")[:1000] or None,
                )
                persisted_page = repo.upsert_page(page)

                ok_status = str(fetch_data.get("status") or "")
                if ok_status in {"ok", "browser_ok", "file_extract"}:
                    totals["success"] += 1
                    if browser_fallback and totals["unreadable"] > 0:
                        totals["unreadable"] -= 1
                    chunks = self._build_chunks_for_page(
                        workspace_id=run.workspace_id,
                        source_id=run.source_id,
                        source_version_id=run.source_version_id,
                        page_id=persisted_page.id,
                        text=page.cleaned_text,
                    )
                    saved_chunks = repo.replace_chunks_for_page(
                        persisted_page.id,
                        run.workspace_id,
                        chunks,
                    )
                    totals["indexed_pages"] += 1
                    totals["indexed_chunks"] += len(saved_chunks)
                elif ok_status in {"unreadable_http", "empty_content"}:
                    if not browser_fallback:
                        totals["unreadable"] += 1
                else:
                    totals["failed"] += 1

                repo.update_crawl_run(run.id, run.workspace_id, {"totals": dict(totals)})
                # Commit after every page so:
                # (1) live progress is visible via the API
                # (2) we don't hold a SQLite lock for the entire crawl
                #     (which can take many minutes on a 800+ URL list)
                # (3) on a daemon crash we don't lose pages already fetched.
                try:
                    session.commit()
                except Exception:
                    session.rollback()

            if cancelled:
                # Operator-requested stop — finalize as CANCELLED, never
                # auto-trigger fallback, never recurse. Page/chunk progress
                # already committed up to the cancel point is preserved.
                repo.update_crawl_run(
                    run.id,
                    run.workspace_id,
                    {
                        "status": KnowledgeCrawlStatus.CANCELLED.value,
                        "phase": KnowledgeCrawlPhase.HTTP_FETCH.value,
                        "completed_at": datetime.now(),
                        "totals": {**totals, "error": "cancelled_by_operator"},
                    },
                )
                logger.info(
                    "knowledge_crawl: cancelled by operator",
                    extra={"run_id": str(run.id), "processed": index},
                )
                return repo.get_crawl_run(run.id)

            final_status = KnowledgeCrawlStatus.COMPLETED.value
            final_phase = KnowledgeCrawlPhase.INDEXING.value
            should_auto_browser = (
                (not browser_fallback)
                and totals["unreadable"] > 0
                and self.browser_fallback_enabled
                and env_bool("KNOWLEDGE_CRAWL_AUTO_BROWSER_FALLBACK", True)
            )
            if (not browser_fallback) and totals["unreadable"] > 0:
                final_status = (
                    KnowledgeCrawlStatus.AWAITING_BROWSER_FALLBACK.value
                    if self.browser_fallback_enabled and not should_auto_browser
                    else (
                        KnowledgeCrawlStatus.RUNNING.value
                        if should_auto_browser
                        else KnowledgeCrawlStatus.COMPLETED.value
                    )
                )
                final_phase = (
                    KnowledgeCrawlPhase.BROWSER_FALLBACK.value
                    if should_auto_browser
                    else KnowledgeCrawlPhase.HTTP_FETCH.value
                )

            repo.update_crawl_run(
                run.id,
                run.workspace_id,
                {
                    "status": final_status,
                    "phase": final_phase,
                    "completed_at": (
                        None if should_auto_browser else datetime.now()
                    ),
                    "totals": totals,
                },
            )

        # Auto-chain browser fallback OUTSIDE the DB session: a second
        # invocation of run_crawl() reopens its own session. This is
        # important because the SPA-heavy URL lists in the wild produce
        # ~70% unreadable on http_fetch, and forcing the operator to
        # click the fallback button on every run is friction with no
        # safety value.
        if should_auto_browser:
            logger.info(
                "knowledge_crawl: auto-triggering browser fallback",
                extra={
                    "run_id": str(run_id),
                    "unreadable": totals["unreadable"],
                    "indexed_pages": totals["indexed_pages"],
                },
            )
            try:
                return self.run_crawl(run_id=run_id, browser_fallback=True)
            except Exception:
                logger.exception(
                    "knowledge_crawl: auto browser fallback failed",
                    extra={"run_id": str(run_id)},
                )
                # Fall through and return the http-only result; the operator
                # can still retry the fallback manually.

        # Frequency-based boilerplate cleanup automatico DOPO che il run
        # è realmente terminato. Si attiva quando lo status finale è
        # COMPLETED e nessun browser-fallback è pendente: vale sia nel
        # path http-only sia nell'inner call dell'auto-browser-fallback
        # (che è la chiamata che porta il run a COMPLETED quando il
        # fallback è eseguito).
        # Best-effort: errori qui non fanno fallire il run.
        if (
            final_status == KnowledgeCrawlStatus.COMPLETED.value
            and not should_auto_browser
            and env_bool("KNOWLEDGE_AUTO_BOILERPLATE_CLEANUP", True)
        ):
            try:
                outcome = self.cleanup_source_boilerplate(
                    workspace_id=run.workspace_id,
                    source_id=run.source_id,
                    dry_run=False,
                )
                logger.info(
                    "knowledge_crawl: post-crawl boilerplate cleanup applied",
                    extra={
                        "run_id": str(run.id),
                        "source_id": str(run.source_id),
                        "blocks_detected": outcome["totals"]["boilerplate_blocks_detected"],
                        "pages_modified": outcome["totals"]["pages_modified"],
                        "chars_removed": outcome["totals"]["chars_removed"],
                        "chunks_before": outcome["totals"]["chunks_before"],
                        "chunks_after": outcome["totals"]["chunks_after"],
                    },
                )
            except Exception:
                logger.exception(
                    "knowledge_crawl: post-crawl boilerplate cleanup failed",
                    extra={"run_id": str(run.id), "source_id": str(run.source_id)},
                )

        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            return repo.get_crawl_run(run_id)

    def _fetch_url_http(self, url: str) -> Dict[str, Any]:
        if not _is_safe_public_url(url):
            return {"status": "blocked_unsafe_url", "error": "unsafe_or_private_url"}

        timeout_seconds = max(env_int("KNOWLEDGE_CRAWL_TIMEOUT_SECONDS", 12), 2)
        max_bytes = max(env_int("KNOWLEDGE_CRAWL_MAX_BYTES", 2_000_000), 32_000)
        min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)
        retries = max(env_int("KNOWLEDGE_CRAWL_HTTP_RETRIES", 2), 0)

        last_error = ""
        for attempt in range(retries + 1):
            try:
                with httpx.Client(timeout=timeout_seconds, follow_redirects=True) as client:
                    response = client.get(
                        url,
                        headers={
                            "User-Agent": "AI-Tester-KnowledgeCrawler/1.0",
                            "Accept": "text/html,application/pdf,application/json,text/plain,*/*;q=0.1",
                        },
                    )
                raw_bytes = response.content or b""
                if len(raw_bytes) > max_bytes:
                    return {
                        "status": "too_large",
                        "http_status": int(response.status_code),
                        "content_type": (response.headers.get("content-type") or "").lower(),
                        "error": f"content_too_large>{max_bytes}",
                    }
                content_type = (response.headers.get("content-type") or "").lower()
                if int(response.status_code) >= 400:
                    return {
                        "status": "http_error",
                        "http_status": int(response.status_code),
                        "content_type": content_type,
                        "error": f"http_{int(response.status_code)}",
                    }

                title = ""
                text = ""
                if "application/pdf" in content_type or url.lower().endswith(".pdf"):
                    text = self._extract_text_from_pdf_bytes(raw_bytes)
                    title = urlparse(url).path.rsplit("/", 1)[-1]
                elif "application/json" in content_type:
                    decoded = raw_bytes.decode("utf-8", errors="replace")
                    compact = WS_RE.sub(" ", decoded).strip()
                    text = compact[:80000]
                    title = urlparse(url).hostname or "JSON source"
                else:
                    decoded = raw_bytes.decode("utf-8", errors="replace")
                    title = _extract_title(decoded) or (urlparse(url).hostname or "")
                    text = _strip_html(decoded)[:80000]

                if len(text.strip()) < min_chars:
                    return {
                        "status": "unreadable_http",
                        "http_status": int(response.status_code),
                        "content_type": content_type,
                        "title": title,
                        "text": text,
                        "raw_chars": len(text),
                        "error": "insufficient_readable_text",
                    }

                return {
                    "status": "ok",
                    "http_status": int(response.status_code),
                    "content_type": content_type,
                    "title": title,
                    "text": text,
                    "raw_chars": len(text),
                    "content_hash": _hash_text(text),
                }
            except Exception as exc:
                last_error = str(exc)[:220]
                if attempt < retries:
                    time.sleep(0.3 * (attempt + 1))
                    continue

        return {"status": "fetch_error", "error": last_error or "unknown_fetch_error"}

    def _fetch_url_browser(self, url: str) -> Dict[str, Any]:
        """SPA-aware browser fetch. Tries crawl4ai first (better extraction
        on JS-rendered sites), falls back to a minimal Playwright sync
        path if crawl4ai is missing or fails.

        Wrapped in a process-wide semaphore (_BROWSER_SEMAPHORE) so that
        even when two crawl runs are active in parallel, only one Chromium
        instance is alive at a time on tight-RAM hosts (Render free tier).

        Both paths share the same return contract so callers don't care
        which one ran:
            { status: ok|browser_ok|browser_failed|... ,
              title, text, raw_chars, content_hash, http_status,
              content_type, error? }
        """
        if not self.browser_fallback_enabled:
            return {"status": "browser_failed", "error": "browser_fallback_disabled"}
        if not _is_safe_public_url(url):
            return {"status": "blocked_unsafe_url", "error": "unsafe_or_private_url"}

        # Acquire a slot. With max_concurrency=1 (default) this serializes
        # all Chromium spawns. With higher caps it caps the number of
        # concurrent browsers — useful on paid tiers with more RAM.
        timeout_s = max(env_int("KNOWLEDGE_BROWSER_QUEUE_WAIT_S", 600), 30)
        if not _BROWSER_SEMAPHORE.acquire(timeout=timeout_s):
            return {
                "status": "browser_failed",
                "error": "browser_semaphore_timeout",
            }
        try:
            # Primary path: crawl4ai if available and not disabled by env.
            if env_bool("KNOWLEDGE_CRAWL_USE_CRAWL4AI", True):
                try:
                    from crawl4ai import AsyncWebCrawler  # type: ignore[import-not-found]  # noqa: F401

                    return self._fetch_with_crawl4ai(url)
                except ImportError:
                    logger.warning(
                        "knowledge_crawl: crawl4ai not installed, falling back to "
                        "Playwright sync. pip install crawl4ai to enable."
                    )
                except Exception as exc:
                    logger.warning(
                        "knowledge_crawl: crawl4ai failed, falling back to Playwright sync",
                        extra={"url": url, "error": str(exc)[:200]},
                    )

            # Fallback path: minimal Playwright sync, kept as safety net for
            # the rare case crawl4ai blows up on a specific URL.
            return self._fetch_with_playwright_sync(url)
        finally:
            _BROWSER_SEMAPHORE.release()

    def _fetch_with_crawl4ai(self, url: str) -> Dict[str, Any]:
        """Run crawl4ai's AsyncWebCrawler synchronously by spinning up a
        short-lived event loop. The caller is sync (`run_crawl()`),
        keeping the rest of the pipeline stable while we benefit from
        crawl4ai's smart Markdown extraction."""
        import asyncio

        from crawl4ai import AsyncWebCrawler, CrawlerRunConfig  # type: ignore[import-not-found]
        from crawl4ai.async_configs import BrowserConfig  # type: ignore[import-not-found]

        timeout_ms = max(env_int("KNOWLEDGE_BROWSER_FALLBACK_TIMEOUT_MS", 30000), 5000)
        min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)

        async def _run() -> Dict[str, Any]:
            browser_config = BrowserConfig(
                headless=True,
                java_script_enabled=True,
                user_agent="AI-Tester-KnowledgeCrawler/2.0 (+crawl4ai)",
                # Render free/starter has tight RAM — disable heavy features
                # we don't need for content extraction.
                light_mode=True,
            )
            run_config = CrawlerRunConfig(
                page_timeout=timeout_ms,
                wait_until="domcontentloaded",
                # Drop common nav/footer/cookie noise by tag heuristics —
                # crawl4ai's default markdown filter is good enough for
                # operator-curated link lists.
                excluded_tags=["nav", "footer", "header", "aside", "form", "script", "style"],
                remove_overlay_elements=True,
                word_count_threshold=10,
            )
            async with AsyncWebCrawler(config=browser_config) as crawler:
                return await crawler.arun(url=url, config=run_config)

        try:
            try:
                loop = asyncio.get_event_loop()
                if loop.is_running():
                    # Inside an already-running loop (rare from sync caller,
                    # but defensive). Spin a separate thread.
                    raise RuntimeError("nested_loop")
            except RuntimeError:
                loop = asyncio.new_event_loop()
            try:
                result = loop.run_until_complete(_run())
            finally:
                loop.close()

            if not result or not getattr(result, "success", False):
                err = (
                    str(getattr(result, "error_message", "") or "")[:220]
                    if result
                    else "no_result"
                )
                return {"status": "browser_failed", "error": err or "crawl4ai_failed"}

            # crawl4ai returns markdown (string) and metadata
            text = (getattr(result, "markdown", "") or "").strip()
            if not text:
                # Last-resort: cleaned plain text from the crawler.
                text = (getattr(result, "cleaned_html", "") or "").strip()
                text = WS_RE.sub(" ", text).strip()

            metadata = getattr(result, "metadata", None) or {}
            title = str(metadata.get("title") or "")[:280]
            http_status = int(getattr(result, "status_code", 0) or 200)

            if len(text) < min_chars:
                return {
                    "status": "browser_failed",
                    "title": title,
                    "text": text,
                    "raw_chars": len(text),
                    "error": "insufficient_readable_text_browser",
                }

            return {
                "status": "browser_ok",
                "http_status": http_status,
                "content_type": "text/markdown",
                "title": title,
                "text": text[:80000],
                "raw_chars": len(text),
                "content_hash": _hash_text(text),
            }
        except Exception as exc:
            return {"status": "browser_failed", "error": f"crawl4ai:{str(exc)[:200]}"}

    def _fetch_with_playwright_sync(self, url: str) -> Dict[str, Any]:
        """Legacy Playwright sync path. Kept as safety net behind crawl4ai."""
        try:
            from playwright.sync_api import sync_playwright
        except Exception:
            return {"status": "browser_failed", "error": "playwright_not_available"}

        timeout_ms = max(env_int("KNOWLEDGE_BROWSER_FALLBACK_TIMEOUT_MS", 30000), 5000)
        try:
            with sync_playwright() as p:
                browser = p.chromium.launch(headless=True)
                page = browser.new_page()
                page.goto(url, wait_until="networkidle", timeout=timeout_ms)
                title = str(page.title() or "")
                text = str(
                    page.evaluate(
                        "() => document && document.body ? (document.body.innerText || '') : ''"
                    )
                    or ""
                )
                browser.close()
            cleaned = WS_RE.sub(" ", text).strip()
            min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)
            if len(cleaned) < min_chars:
                return {
                    "status": "browser_failed",
                    "title": title[:280],
                    "text": cleaned,
                    "raw_chars": len(cleaned),
                    "error": "insufficient_readable_text_browser",
                }
            return {
                "status": "browser_ok",
                "http_status": 200,
                "content_type": "text/html",
                "title": title[:280],
                "text": cleaned[:80000],
                "raw_chars": len(cleaned),
                "content_hash": _hash_text(cleaned),
            }
        except Exception as exc:
            return {"status": "browser_failed", "error": str(exc)[:220]}

    def _extract_text_from_pdf_bytes(self, payload: bytes) -> str:
        try:
            from pypdf import PdfReader
        except Exception:
            return ""
        try:
            reader = PdfReader(io.BytesIO(payload))
        except Exception:
            return ""
        chunks: List[str] = []
        for page in reader.pages:
            text = WS_RE.sub(" ", str(page.extract_text() or "")).strip()
            if text:
                chunks.append(text)
        return "\n".join(chunks)[:80000]

    def _build_chunks_for_page(
        self,
        *,
        workspace_id: UUID,
        source_id: UUID,
        source_version_id: UUID,
        page_id: UUID,
        text: str,
    ) -> List[KnowledgeChunk]:
        chunk_size = max(env_int("KNOWLEDGE_CHUNK_SIZE_CHARS", 1200), 200)
        overlap = max(env_int("KNOWLEDGE_CHUNK_OVERLAP_CHARS", 180), 0)
        compact = WS_RE.sub(" ", str(text or "")).strip()
        if not compact:
            return []
        if len(compact) <= chunk_size:
            compact_chunks = [compact]
        else:
            compact_chunks = []
            cursor = 0
            while cursor < len(compact):
                end = min(cursor + chunk_size, len(compact))
                chunk = compact[cursor:end].strip()
                if chunk:
                    compact_chunks.append(chunk)
                if end >= len(compact):
                    break
                cursor = max(0, end - overlap)

        dedup = {}
        for idx, chunk in enumerate(compact_chunks):
            chunk_hash = _hash_text(chunk)
            if chunk_hash in dedup:
                continue
            dedup[chunk_hash] = KnowledgeChunk(
                workspace_id=workspace_id,
                page_id=page_id,
                source_id=source_id,
                source_version_id=source_version_id,
                chunk_index=idx,
                chunk_text=chunk,
                token_estimate=_estimate_tokens(chunk),
                chunk_hash=chunk_hash,
                embedding_json=_sparse_embedding(chunk) if self.embeddings_enabled else None,
            )
        return list(dedup.values())

    def cleanup_source_boilerplate(
        self,
        *,
        workspace_id: UUID,
        source_id: Optional[UUID] = None,
        dry_run: bool = True,
        freq_threshold: Optional[float] = None,
        boundary_threshold: Optional[float] = None,
        head_window: Optional[int] = None,
        tail_window: Optional[int] = None,
        min_pages: Optional[int] = None,
    ) -> Dict[str, Any]:
        """Frequency-based + boundary heuristics boilerplate cleanup.

        Per ciascuna source (filtrata o tutte della workspace), considera SOLO
        la version ACTIVE: identifica i blocchi che si ripetono tra le pagine,
        li rimuove dal `cleaned_text`, ricostruisce i chunks. Tutto in
        transazione single per ogni source. Se `dry_run=True`, non scrive,
        ritorna solo lo stimato.

        Le soglie usano default ragionevoli (env-overridabili) se i parametri
        non sono passati esplicitamente.
        """
        from src.core.boilerplate_detector import (
            BoilerplatePage,
            detect_boilerplate_blocks,
            detect_common_prefixes,
            detect_repeated_substrings,
            strip_boilerplate,
            strip_common_prefixes,
            strip_repeated_substrings,
        )

        ft = float(freq_threshold) if freq_threshold is not None else float(env_int("KNOWLEDGE_BOILERPLATE_FREQ_PCT", 70)) / 100.0
        bt = float(boundary_threshold) if boundary_threshold is not None else float(env_int("KNOWLEDGE_BOILERPLATE_BOUNDARY_PCT", 50)) / 100.0
        hw = int(head_window) if head_window is not None else env_int("KNOWLEDGE_BOILERPLATE_HEAD_WINDOW", 5)
        tw = int(tail_window) if tail_window is not None else env_int("KNOWLEDGE_BOILERPLATE_TAIL_WINDOW", 5)
        mp = int(min_pages) if min_pages is not None else env_int("KNOWLEDGE_BOILERPLATE_MIN_PAGES", 5)

        db = get_db()
        summary: Dict[str, Any] = {
            "dry_run": dry_run,
            "freq_threshold": ft,
            "boundary_threshold": bt,
            "sources": [],
            "totals": {
                "pages_processed": 0,
                "pages_modified": 0,
                "blocks_removed_from_pages": 0,
                "chars_removed": 0,
                "chunks_before": 0,
                "chunks_after": 0,
                "boilerplate_blocks_detected": 0,
            },
        }

        with db.get_session() as session:
            repo = KnowledgeRepository(session)

            if source_id is not None:
                source = repo.get_source(source_id, workspace_id)
                source_iter = [source] if source else []
            else:
                source_iter = list(repo.list_sources(workspace_id))

            for source in source_iter:
                versions = repo.list_versions(source.id, workspace_id)
                active = next(
                    (v for v in versions if v.state == KnowledgeVersionState.ACTIVE),
                    None,
                )
                if not active:
                    continue
                pages = repo.list_pages_for_source_version(active.id, workspace_id)

                source_entry: Dict[str, Any] = {
                    "source_id": str(source.id),
                    "source_name": source.name,
                    "version_id": str(active.id),
                    "pages": len(pages),
                    "skipped_reason": None,
                    "boilerplate_blocks": [],
                    "pages_modified": 0,
                    "blocks_removed_from_pages": 0,
                    "chars_removed": 0,
                    "chunks_before": 0,
                    "chunks_after": 0,
                }

                if len(pages) < mp:
                    source_entry["skipped_reason"] = f"too_few_pages ({len(pages)} < {mp})"
                    summary["sources"].append(source_entry)
                    continue

                # Frequency analysis a 2 livelli:
                # 1) per HOST: cattura header/footer del sito intero.
                # 2) per (HOST, primo path-segment): cattura header/footer di
                #    SEZIONE — siti grandi (cultura.regione.campania.it) hanno
                #    sotto-portali con loro propria intestazione che si ripete
                #    solo nelle pagine di quella sezione, sotto soglia globale.
                # Le fingerprint trovate vengono unite e applicate insieme.
                from urllib.parse import urlparse
                from collections import defaultdict as _dd

                def _page_groups(pages_in: List[Any]) -> Tuple[Dict[str, List[Any]], Dict[str, List[Any]]]:
                    by_host: Dict[str, List[Any]] = _dd(list)
                    by_section: Dict[str, List[Any]] = _dd(list)
                    for p in pages_in:
                        host = ""
                        path = ""
                        try:
                            parsed = urlparse(p.url or p.url_canonical or "")
                            host = (parsed.hostname or "").lower()
                            path = parsed.path or ""
                        except Exception:
                            host, path = "", ""
                        host_key = host or "_unknown"
                        by_host[host_key].append(p)
                        # Primo segmento del path, se non vuoto.
                        seg = ""
                        for token in (path or "").split("/"):
                            t = token.strip()
                            if t:
                                seg = t.lower()
                                break
                        if seg:
                            by_section[f"{host_key}/{seg}"].append(p)
                    return by_host, by_section

                groups_host, groups_section = _page_groups(pages)

                merged_fingerprints: Set[str] = set()
                merged_samples: Dict[str, str] = {}
                merged_counts: Dict[str, int] = {}
                merged_reasons: Dict[str, str] = {}
                pages_analyzed_total = 0

                def _run_detection(group_label: str, group_pages: List[Any]) -> None:
                    nonlocal pages_analyzed_total
                    if len(group_pages) < mp:
                        return
                    sub_report = detect_boilerplate_blocks(
                        [BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in group_pages],
                        freq_threshold=ft,
                        boundary_threshold=bt,
                        head_window=hw,
                        tail_window=tw,
                        min_pages=mp,
                    )
                    pages_analyzed_total += sub_report.pages_analyzed
                    for fp in sub_report.boilerplate_fingerprints:
                        merged_fingerprints.add(fp)
                        merged_samples.setdefault(fp, sub_report.sample_by_fingerprint.get(fp, ""))
                        merged_counts[fp] = merged_counts.get(fp, 0) + sub_report.page_count_by_fingerprint.get(fp, 0)
                        if fp not in merged_reasons:
                            merged_reasons[fp] = f"{group_label}:{sub_report.reason_by_fingerprint.get(fp, '?')}"

                # 1° passaggio: per host (header/footer del sito intero).
                for host, host_pages in groups_host.items():
                    _run_detection(host if host != "_unknown" else "no-host", host_pages)
                # 2° passaggio: per (host, sezione) — cattura header di
                # sotto-portali. Le fingerprint duplicate vengono ignorate
                # dal set.
                for section_key, section_pages in groups_section.items():
                    _run_detection(section_key, section_pages)

                # 3° passaggio: COMMON PREFIX detection per (host, sezione).
                # Cattura header densi dove titolo+menu sono concatenati
                # senza separatori sintattici (no newline, no punctuation):
                # il blocco-detector li tratta come unico blocco unico per
                # pagina, quindi non li rileva come ricorrenti. Il common-
                # prefix invece confronta i primi N char di ciascuna pagina
                # del gruppo e individua l'header condiviso. Solo per gruppi
                # con ≥ mp pagine.
                common_prefixes_by_group: Dict[str, List[str]] = {}
                for section_key, section_pages in groups_section.items():
                    if len(section_pages) < mp:
                        continue
                    prefixes = detect_common_prefixes(
                        [BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in section_pages],
                        threshold=bt,  # boundary threshold (default 0.5): più permissivo del 70%
                        min_pages=mp,
                    )
                    if prefixes:
                        common_prefixes_by_group[section_key] = prefixes
                        for px in prefixes:
                            # Rappresento il prefix come fingerprint speciale
                            # per visibilità in source_entry. Sample = primi 200
                            # char.
                            fp_key = f"__prefix__::{section_key}::{px[:64]}"
                            if fp_key not in merged_samples:
                                merged_samples[fp_key] = px[:200]
                                merged_counts[fp_key] = sum(
                                    1 for p in section_pages
                                    if (p.cleaned_text or '').strip().lower().startswith(px[:80])
                                )
                                merged_reasons[fp_key] = f"{section_key}:common_prefix:{len(px)}chars"

                # Mappa pagina -> lista prefissi applicabili: per ogni pagina
                # trovo a quale section_key appartiene, e prendo i prefissi di
                # quel gruppo.
                prefix_for_page: Dict[str, List[str]] = {}
                for section_key, section_pages in groups_section.items():
                    if section_key not in common_prefixes_by_group:
                        continue
                    pxs = common_prefixes_by_group[section_key]
                    for p in section_pages:
                        prefix_for_page.setdefault(str(p.id), []).extend(pxs)

                # 4° passaggio: SHINGLING (substring ripetuti). Cattura
                # menu/header/footer concatenati a contenuto unico per pagina
                # (es. titolo + menu + content): nessuno dei tre detector
                # precedenti li prende perché il blocco "titolo + menu" ha
                # fingerprint unica per pagina e il prefisso è anch'esso
                # unico (il titolo cambia). Lo shingling trova frasi/menu di
                # 10 parole ripetuti in ≥ 50% delle pagine del gruppo,
                # ovunque si trovino. Lavoro solo su (host, sezione) per non
                # esplodere su workspace globale (≥10k pagine).
                shingles_for_page: Dict[str, List[str]] = {}
                for section_key, section_pages in groups_section.items():
                    if len(section_pages) < mp:
                        continue
                    shingles = detect_repeated_substrings(
                        [BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in section_pages],
                        n_words=10,
                        threshold=bt,
                        min_pages=mp,
                    )
                    if not shingles:
                        continue
                    for p in section_pages:
                        shingles_for_page.setdefault(str(p.id), []).extend(shingles)
                    # Registra il primo shingle per source_entry visibility
                    fp_key = f"__shingle__::{section_key}"
                    if fp_key not in merged_samples and shingles:
                        merged_samples[fp_key] = shingles[0][:200]
                        merged_counts[fp_key] = len(shingles)
                        merged_reasons[fp_key] = f"{section_key}:shingles:{len(shingles)}"

                source_entry["pages_analyzed"] = pages_analyzed_total
                source_entry["hosts"] = sorted([h for h in groups_host.keys() if groups_host[h]])
                source_entry["boilerplate_blocks"] = [
                    {
                        "fingerprint_hash": str(abs(hash(fp)) % 10_000_000),
                        "sample": (merged_samples.get(fp, "") or "")[:200],
                        "page_count": merged_counts.get(fp, 0),
                        "reason": merged_reasons.get(fp, ""),
                    }
                    for fp in sorted(
                        merged_fingerprints,
                        key=lambda f: merged_counts.get(f, 0),
                        reverse=True,
                    )
                ]
                summary["totals"]["boilerplate_blocks_detected"] += len(merged_fingerprints)

                # Continua se ALMENO uno dei tre detector (block / prefix /
                # shingle) ha trovato qualcosa. La presenza di common_prefix
                # o shingles_for_page è sufficiente anche se merged_fingerprints
                # è vuoto.
                has_block_fp = bool(merged_fingerprints)
                has_prefixes = bool(common_prefixes_by_group)
                has_shingles = bool(shingles_for_page)
                if not (has_block_fp or has_prefixes or has_shingles):
                    source_entry["skipped_reason"] = "no_boilerplate_detected"
                    summary["sources"].append(source_entry)
                    continue
                fps = merged_fingerprints

                # Solo il conteggio serve: usiamo COUNT(*) invece di caricare
                # tutti i chunk con embedding_json (~6 KB/chunk). Fix egress
                # 2026-05-22 — vedi pg_stat_statements (26.6M rows con
                # questa query).
                chunks_before = repo.count_chunks_for_source_version(active.id, workspace_id)
                source_entry["chunks_before"] = chunks_before
                summary["totals"]["chunks_before"] += chunks_before

                chunks_after = chunks_before  # in dry_run rimane invariato

                for page in pages:
                    summary["totals"]["pages_processed"] += 1
                    original = page.cleaned_text or ""
                    if not original:
                        continue
                    # Apply in cascata: prefix → block → shingle. L'ordine
                    # conta poco (sono idempotenti su input pulito), ma
                    # prefix per primo riduce drasticamente il testo da
                    # processare nei passaggi successivi.
                    after_prefix = original
                    page_prefixes = prefix_for_page.get(str(page.id), [])
                    if page_prefixes:
                        after_prefix = strip_common_prefixes(after_prefix, page_prefixes)
                    after_blocks = strip_boilerplate(after_prefix, fps)
                    page_shingles = shingles_for_page.get(str(page.id), [])
                    cleaned = (
                        strip_repeated_substrings(after_blocks, page_shingles)
                        if page_shingles
                        else after_blocks
                    )
                    if cleaned == original:
                        continue
                    delta_chars = len(original) - len(cleaned)
                    source_entry["chars_removed"] += delta_chars
                    source_entry["pages_modified"] += 1
                    summary["totals"]["chars_removed"] += delta_chars
                    summary["totals"]["pages_modified"] += 1
                    # Conteggio blocchi rimossi: differenza tra blocchi-pagina
                    # nell'originale e nel pulito (proxy ragionevole, non
                    # serve esattezza chirurgica).
                    from src.core.boilerplate_detector import _split_blocks  # type: ignore
                    delta_blocks = max(len(_split_blocks(original)) - len(_split_blocks(cleaned)), 0)
                    source_entry["blocks_removed_from_pages"] += delta_blocks
                    summary["totals"]["blocks_removed_from_pages"] += delta_blocks

                    if not dry_run:
                        page.cleaned_text = cleaned
                        repo.upsert_page(page)
                        new_chunks = self._build_chunks_for_page(
                            workspace_id=workspace_id,
                            source_id=source.id,
                            source_version_id=active.id,
                            page_id=page.id,
                            text=cleaned,
                        )
                        repo.replace_chunks_for_page(page.id, workspace_id, new_chunks)

                if not dry_run:
                    # Stesso fix egress di chunks_before: count diretto.
                    chunks_after = repo.count_chunks_for_source_version(active.id, workspace_id)
                source_entry["chunks_after"] = chunks_after
                summary["totals"]["chunks_after"] += chunks_after
                summary["sources"].append(source_entry)

            if not dry_run:
                session.commit()

        return summary

    def build_session_memory_snapshot(
        self,
        *,
        workspace_id: UUID,
        bot_id: UUID,
    ) -> Dict[str, Any]:
        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            bindings = repo.list_active_source_versions_for_bot(
                workspace_id,
                bot_id,
                include_workspace_fallback=False,
            )
            source_version_ids: List[str] = []
            crawl_run_ids: List[str] = []
            indexed_pages = 0
            indexed_chunks = 0
            for item in bindings:
                version = item["version"]
                source_version_ids.append(str(version.id))
                latest = repo.get_latest_crawl_run_for_source_version(version.id, workspace_id)
                if latest:
                    crawl_run_ids.append(str(latest.id))
                stats = repo.get_memory_stats_for_source_version(version.id, workspace_id)
                indexed_pages += int(stats.get("indexed_pages") or 0)
                indexed_chunks += int(stats.get("indexed_chunks") or 0)
            return {
                "source_version_ids": source_version_ids,
                "crawl_run_ids": crawl_run_ids,
                "memory_status": {
                    "sources_count": len(bindings),
                    "indexed_pages": indexed_pages,
                    "indexed_chunks": indexed_chunks,
                    "ready": indexed_chunks > 0,
                },
            }

    def retrieve(
        self,
        *,
        workspace_id: UUID,
        bot_id: UUID,
        query: str,
        top_k: int = 5,
        source_scope: str = "linked_only",
    ) -> List[Dict[str, Any]]:
        query_tokens = _tokenize(query)
        if not query_tokens:
            return []
        query_embedding = _sparse_embedding(query) if self.embeddings_enabled else {}

        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            bindings = repo.list_active_source_versions_for_bot(
                workspace_id,
                bot_id,
                include_workspace_fallback=(source_scope == "workspace_fallback"),
            )
            scored: List[Tuple[float, Dict[str, Any]]] = []
            for item in bindings:
                source = item["source"]
                version = item["version"]
                pages = repo.list_pages_for_source_version(version.id, workspace_id)
                page_map = {str(page.id): page for page in pages}
                chunks = repo.list_chunks_for_source_version(version.id, workspace_id)
                for chunk in chunks:
                    score = self._lexical_score(query_tokens, chunk.chunk_text)
                    if score <= 0:
                        continue
                    semantic_score = 0.0
                    if self.embeddings_enabled:
                        stored_embedding = {}
                        if isinstance(chunk.embedding_json, dict):
                            stored_embedding = {
                                str(key): float(val)
                                for key, val in chunk.embedding_json.items()
                                if str(key) and isinstance(val, (int, float))
                            }
                        if not stored_embedding:
                            stored_embedding = _sparse_embedding(chunk.chunk_text)
                        semantic_score = _sparse_cosine(query_embedding, stored_embedding)
                        score = (score * 0.7) + (semantic_score * 0.3)
                    page = page_map.get(str(chunk.page_id))
                    scored.append(
                        (
                            score,
                            {
                                "source_id": str(source.id),
                                "source_name": source.name,
                                "version_id": str(version.id),
                                "page_id": str(chunk.page_id),
                                "chunk_id": str(chunk.id),
                                "url": page.url if page else "",
                                "title": (page.title if page else "") or source.name,
                                # 1500 (era 360): il judge fa match semantico
                                # sull'intero snippet. Con 360 char il match
                                # falliva su chunks lunghi dove il keyword del
                                # claim era oltre la soglia. 1500 copre la
                                # gran parte dei chunk integralmente senza
                                # esplodere la dimensione del prompt.
                                "snippet": chunk.chunk_text[:1500],
                                "score": round(float(score), 4),
                                "semantic_score": round(float(semantic_score), 4),
                            },
                        )
                    )
            scored.sort(key=lambda item: item[0], reverse=True)
            return [item[1] for item in scored[: max(1, top_k)]]

    def search_chunks(
        self,
        *,
        workspace_id: UUID,
        query: str,
        bot_id: Optional[UUID] = None,
        top_k: int = 10,
        min_score: float = 0.0,
    ) -> Dict[str, Any]:
        """Manual semantic search across active knowledge chunks.

        Pensata per audit/verifica manuale dell'operatore: data una query,
        ritorna i chunk più rilevanti delle source ATTIVE filtrate per bot
        (o cross-bot se bot_id è None). Non chiama LLM, è cheap come la
        search interna del judge.

        Stesso scoring di retrieve(): lexical (0.7) + semantic sparse (0.3)
        quando embeddings_enabled. Solo versioni is_active=true.
        """
        import time as _time

        started_at = _time.perf_counter()
        query_tokens = _tokenize(query)
        if not query_tokens:
            return {
                "results": [],
                "stats": {
                    "total_chunks_scanned": 0,
                    "sources_scanned": 0,
                    "took_ms": 0,
                    "embeddings_enabled": self.embeddings_enabled,
                },
            }
        query_embedding = _sparse_embedding(query) if self.embeddings_enabled else {}

        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)

            if bot_id is not None:
                bindings = repo.list_active_source_versions_for_bot(
                    workspace_id, bot_id, include_workspace_fallback=False
                )
            else:
                # Cross-bot: enumera tutte le source della workspace, prendi
                # SOLO la version ACTIVE di ciascuna. Coerente con il caso
                # bot-scoped che usa list_active_source_versions_for_bot.
                bindings = []
                for source in repo.list_sources(workspace_id):
                    versions = repo.list_versions(source.id, workspace_id)
                    active = next(
                        (v for v in versions if v.state == KnowledgeVersionState.ACTIVE),
                        None,
                    )
                    if active:
                        bindings.append({"source": source, "version": active})

            sources_scanned = len(bindings)
            total_chunks_scanned = 0
            scored: List[Dict[str, Any]] = []

            for item in bindings:
                source = item["source"]
                version = item["version"]
                pages = repo.list_pages_for_source_version(version.id, workspace_id)
                page_map = {str(page.id): page for page in pages}
                chunks = repo.list_chunks_for_source_version(version.id, workspace_id)
                total_chunks_scanned += len(chunks)
                for chunk in chunks:
                    lex = self._lexical_score(query_tokens, chunk.chunk_text)
                    if lex <= 0:
                        continue
                    sem = 0.0
                    if self.embeddings_enabled:
                        stored = (
                            chunk.embedding_json
                            if isinstance(chunk.embedding_json, dict)
                            else {}
                        )
                        if stored:
                            stored = {
                                str(k): float(v)
                                for k, v in stored.items()
                                if str(k) and isinstance(v, (int, float))
                            }
                        if not stored:
                            stored = _sparse_embedding(chunk.chunk_text)
                        sem = _sparse_cosine(query_embedding, stored)
                        score = (lex * 0.7) + (sem * 0.3)
                    else:
                        score = lex
                    if score < min_score:
                        continue
                    page = page_map.get(str(chunk.page_id)) if chunk.page_id else None
                    source_type_value = (
                        source.source_type.value
                        if hasattr(source.source_type, "value")
                        else str(source.source_type)
                    )
                    scored.append(
                        {
                            "source_id": str(source.id),
                            "source_name": source.name,
                            "source_type": source_type_value,
                            "version_id": str(version.id),
                            "version_label": version.version_label or "",
                            "chunk_id": str(chunk.id),
                            "chunk_text": chunk.chunk_text,
                            "score": round(float(score), 4),
                            "lexical_score": round(float(lex), 4),
                            "semantic_score": round(float(sem), 4),
                            "page_id": str(chunk.page_id) if chunk.page_id else None,
                            "page_url": page.url if page else None,
                            "page_title": (page.title if page else None) or source.name,
                        }
                    )

            scored.sort(key=lambda r: r["score"], reverse=True)
            top = scored[: max(1, int(top_k or 10))]
            took_ms = int((_time.perf_counter() - started_at) * 1000)
            return {
                "results": top,
                "stats": {
                    "total_chunks_scanned": total_chunks_scanned,
                    "sources_scanned": sources_scanned,
                    "took_ms": took_ms,
                    "embeddings_enabled": self.embeddings_enabled,
                },
            }

    def collect_topic_candidates(
        self,
        *,
        workspace_id: UUID,
        bot_id: UUID,
        max_topics: int = 80,
    ) -> Dict[str, Any]:
        db = get_db()
        with db.get_session() as session:
            repo = KnowledgeRepository(session)
            bindings = repo.list_active_source_versions_for_bot(
                workspace_id,
                bot_id,
                include_workspace_fallback=False,
            )
            topics: List[Dict[str, str]] = []
            seen = set()
            pages_count = 0
            chunks_count = 0
            for item in bindings:
                source = item["source"]
                version = item["version"]
                pages = repo.list_pages_for_source_version(version.id, workspace_id)
                # Solo il conteggio dei chunk serve: COUNT(*) invece di
                # SELECT * + len(). Le pages restano caricate perché il loop
                # sotto usa `page.title` e `page.cleaned_text`.
                # Fix egress 2026-05-22.
                pages_count += len(pages)
                chunks_count += repo.count_chunks_for_source_version(version.id, workspace_id)
                for page in pages:
                    label = str(page.title or "").strip()
                    if not label:
                        label = self._topic_from_url(page.url_canonical or page.url)
                    if not label:
                        label = source.name
                    key = re.sub(r"[^a-z0-9]+", " ", label.lower()).strip()
                    if not key or key in seen:
                        continue
                    seen.add(key)
                    preview = str(page.cleaned_text or "").strip()
                    topics.append(
                        {
                            "topic": label[:120],
                            "title": (page.title or label)[:140],
                            "source_url": page.url_canonical or page.url,
                            "detail": preview[:220],
                        }
                    )
                    if len(topics) >= max_topics:
                        break
                if len(topics) >= max_topics:
                    break
            return {
                "topic_candidates": topics,
                "sources_count": len(bindings),
                "pages_count": pages_count,
                "chunks_count": chunks_count,
            }

    def _lexical_score(self, query_tokens: List[str], chunk_text: str) -> float:
        """Lexical relevance score: density of query tokens + n-gram boost.

        Vecchia formula: `density + 0.2 * (len(chunk)/1200)` premiava i
        chunk LUNGHI a parità di density. Risultato: il boilerplate del
        sito ("Skip to main content REGIONE CAMPANIA...") con tutti i
        token del menu vinceva contro un chunk specifico breve che
        conteneva *letteralmente* la query (es. "Monastero del Deserto").

        Nuova formula:
        - `density` = overlap / len(query_tokens) — invariato.
        - `phrase_bonus` = +1.0 se la query (>= 2 token) compare LETTERALMENTE
          nel chunk: questo è il segnale più forte di rilevanza e ribalta
          il vantaggio dei boilerplate. Case-insensitive.
        - `length_penalty` = leggera penalità per chunk MOLTO lunghi
          (oltre 2500 char): tipici dei header/menu indicizzati intero.
        """
        chunk_tokens = _tokenize(chunk_text)
        if not chunk_tokens:
            return 0.0
        token_set = set(chunk_tokens)
        overlap = sum(1 for token in query_tokens if token in token_set)
        if overlap <= 0:
            return 0.0
        density = overlap / max(len(query_tokens), 1)
        # n-gram boost: phrase match LETTERALE (case-insensitive) è il
        # segnale di rilevanza più forte. Lo applichiamo per query che
        # rappresentano nomi propri / entità (≥ 2 token significativi).
        phrase_bonus = 0.0
        if len(query_tokens) >= 2:
            chunk_lower = chunk_text.lower()
            phrase = " ".join(query_tokens).lower()
            if phrase in chunk_lower:
                phrase_bonus = 1.0
            else:
                # Anche bigrammi: se gli ultimi 2 token consecutivi compaiono
                # consecutivi nel chunk, +0.4 (es. "del Deserto" preserva
                # parte della struttura della frase).
                for i in range(len(query_tokens) - 1):
                    bigram = " ".join(query_tokens[i:i+2]).lower()
                    if bigram in chunk_lower:
                        phrase_bonus = max(phrase_bonus, 0.4)
        # Penalty leggera per chunk boilerplate molto lunghi (>2500 char).
        length_penalty = 0.0
        if len(chunk_text) > 2500:
            length_penalty = -0.1
        # Boilerplate detection: chunks che sono header/footer/menù del sito
        # contengono spesso TUTTI i nomi di luoghi (per la navigazione) e
        # vincono falsamente il match anche su query specifiche. Pattern
        # tipici di Campania Divina e siti turistici simili. La penalità è
        # forte (-1.0) per spostare questi chunks ben sotto i contenuti reali.
        chunk_lower_full = chunk_text.lower()
        BOILERPLATE_MARKERS = (
            "skip to main content",
            "where to go things to do travel ideas",
            "lingua corrente: en eng",
            "powered by:",
            "covid-19 ultimo dpcm",
            "musei e parchi archeologici",
            "enogast",  # "Enogastronomia" tipico tag-cloud footer
            "talk to the a",  # "Talk to the AI Agent"
            "english español français",  # menu lingue multi-language
            "deutsch italiano cerca search",
            "cerca search home campania",
            "associazione alessandro scarlatti",  # tipico elenchi-archivio
            "biblioteche coinvolti nel progetto",
            "connette patrimoni provenienti",
        )
        boiler_hits = sum(1 for m in BOILERPLATE_MARKERS if m in chunk_lower_full)
        boilerplate_penalty = -1.0 * boiler_hits if boiler_hits else 0.0
        return float(density + phrase_bonus + length_penalty + boilerplate_penalty)

    def _topic_from_url(self, url: str) -> str:
        raw_url = str(url or "").strip()
        if not raw_url:
            return ""
        try:
            parsed = urlparse(raw_url)
            parts = [part for part in parsed.path.split("/") if part]
        except Exception:
            return ""
        for token in reversed(parts):
            cleaned = re.sub(r"\.[a-z0-9]{2,5}$", "", token.lower())
            cleaned = unquote(cleaned).replace("-", " ").replace("_", " ").strip()
            if len(cleaned) >= 4:
                return cleaned.title()
        return parsed.hostname or ""


knowledge_memory_service = KnowledgeMemoryService()