File size: 56,196 Bytes
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
42bebde
 
 
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
 
 
 
a06d854
 
 
 
 
 
42bebde
a06d854
 
 
 
 
42bebde
a06d854
 
42bebde
a06d854
42bebde
a06d854
42bebde
 
 
 
 
 
 
 
a06d854
42bebde
 
 
 
 
 
 
 
 
a06d854
42bebde
 
 
 
 
 
 
 
 
 
a06d854
 
 
 
 
 
 
 
 
42bebde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a06d854
42bebde
 
a06d854
 
 
 
 
 
42bebde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
 
 
 
 
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42bebde
a06d854
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Fetch a checkpointed, zero-paid-API corpus from a URL manifest.

The safe default fetches cached Wikipedia article HTML and URLs that the teacher
already routed through r.jina.ai. Arbitrary direct-web fetching is opt-in so a
smoke test cannot accidentally crawl 12,000 domains.
"""

from __future__ import annotations

import argparse
import asyncio
import difflib
import hashlib
import json
import re
import time
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from html.parser import HTMLParser
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, quote, unquote, urlsplit, urlunsplit
from urllib.robotparser import RobotFileParser

import httpx

try:
    import pymupdf
except ImportError:  # optional direct-crawl dependency
    pymupdf = None

try:
    import trafilatura
except ImportError:  # optional direct-crawl dependency
    trafilatura = None

try:
    from charset_normalizer import from_bytes as detect_charset
except ImportError:  # httpx environments normally provide this, but keep a fallback
    detect_charset = None

try:
    from .common import read_jsonl
    from .corpus_db import connect, fts_counts, ingest_manifest, rebuild_fts, save_fetch_result, status_counts
except ImportError:  # direct script execution
    from common import read_jsonl
    from corpus_db import connect, fts_counts, ingest_manifest, rebuild_fts, save_fetch_result, status_counts


class HTMLTextExtractor(HTMLParser):
    BLOCK_TAGS = {
        "article",
        "blockquote",
        "br",
        "dd",
        "div",
        "dl",
        "dt",
        "figcaption",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "li",
        "main",
        "p",
        "pre",
        "section",
        "table",
        "td",
        "th",
        "tr",
    }
    IGNORED_TAGS = {"canvas", "footer", "form", "nav", "noscript", "script", "style", "svg"}

    def __init__(self, content_root_id: str | None = None) -> None:
        super().__init__(convert_charrefs=True)
        self.parts: list[str] = []
        self.title_parts: list[str] = []
        self.ignored_depth = 0
        self.in_title = False
        self.content_root_id = content_root_id
        self.capture_content = content_root_id is None
        self.root_tag = ""
        self.root_tag_depth = 0

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        tag = tag.casefold()
        if tag == "title":
            self.in_title = True
        if not self.capture_content:
            attributes = dict(attrs)
            if attributes.get("id") != self.content_root_id:
                return
            self.capture_content = True
            self.root_tag = tag
            self.root_tag_depth = 1
        elif self.content_root_id and tag == self.root_tag:
            self.root_tag_depth += 1
        if tag in self.IGNORED_TAGS:
            self.ignored_depth += 1
        if tag in self.BLOCK_TAGS and not self.ignored_depth:
            self.parts.append("\n")

    def handle_endtag(self, tag: str) -> None:
        tag = tag.casefold()
        if tag == "title":
            self.in_title = False
        if not self.capture_content:
            return
        if tag in self.IGNORED_TAGS and self.ignored_depth:
            self.ignored_depth -= 1
        if tag in self.BLOCK_TAGS and not self.ignored_depth:
            self.parts.append("\n")
        if self.content_root_id and tag == self.root_tag:
            self.root_tag_depth -= 1
            if self.root_tag_depth == 0:
                self.capture_content = False

    def handle_data(self, data: str) -> None:
        if self.in_title:
            self.title_parts.append(data)
        if not self.capture_content or self.ignored_depth or self.in_title:
            return
        self.parts.append(data)

    def result(self) -> tuple[str, str]:
        title = re.sub(r"\s+", " ", " ".join(self.title_parts)).strip()
        lines = [re.sub(r"[ \t\f\v]+", " ", line).strip() for line in "".join(self.parts).splitlines()]
        text = "\n".join(line for line in lines if line)
        return title, text


@dataclass
class HTTPBody:
    status_code: int
    content_type: str
    final_url: str
    body: bytes


@dataclass
class RobotsPolicy:
    """One origin's parsed robots.txt policy.

    The policy is cached per origin, but ``can_fetch`` must still be evaluated
    for every target URL because robots rules are path-specific.
    """

    robots_url: str
    parser: RobotFileParser | None
    default_allowed: bool
    status: str
    reason: str
    fetched_at: str
    http_status: int | None = None
    content_sha256: str = ""

    def decision(self, user_agent: str, target_url: str) -> tuple[bool, str]:
        if self.parser is None:
            return self.default_allowed, self.reason
        allowed = self.parser.can_fetch(user_agent, target_url)
        verdict = "allows" if allowed else "disallows"
        return allowed, f"robots.txt {verdict} this URL"


class FetchFailure(ValueError):
    """Expected fetch/extraction rejection with diagnostics worth persisting."""

    def __init__(
        self,
        message: str,
        *,
        http_status: int | None = None,
        content_type: str = "",
        source: str = "",
    ) -> None:
        super().__init__(message)
        self.http_status = http_status
        self.content_type = content_type
        self.source = source


class HostRateLimiter:
    def __init__(self, interval: float) -> None:
        self.interval = interval
        self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
        self._next: defaultdict[str, float] = defaultdict(float)
        self._host_intervals: defaultdict[str, float] = defaultdict(float)

    def set_host_interval(self, hostname: str, interval: float) -> None:
        self._host_intervals[hostname.casefold()] = max(self._host_intervals[hostname.casefold()], interval)

    async def defer(self, hostname: str, delay: float) -> None:
        """Apply server backpressure to every coroutine targeting a host."""
        hostname = hostname.casefold()
        async with self._locks[hostname]:
            self._next[hostname] = max(self._next[hostname], time.monotonic() + max(0.0, delay))

    async def wait(self, hostname: str) -> None:
        hostname = hostname.casefold()
        while True:
            async with self._locks[hostname]:
                now = time.monotonic()
                delay = self._next[hostname] - now
                if delay <= 0:
                    interval = max(self.interval, self._host_intervals[hostname])
                    self._next[hostname] = now + interval
                    return
            await asyncio.sleep(delay)


def retry_after_seconds(value: str, *, now: datetime | None = None) -> float | None:
    value = value.strip()
    if not value:
        return None
    try:
        return max(0.0, float(value))
    except ValueError:
        pass
    try:
        retry_at = parsedate_to_datetime(value)
        if retry_at.tzinfo is None:
            retry_at = retry_at.replace(tzinfo=timezone.utc)
        current = now or datetime.now(timezone.utc)
        return max(0.0, (retry_at - current).total_seconds())
    except (TypeError, ValueError, OverflowError):
        return None


def wikipedia_title(url: str) -> str:
    parsed = urlsplit(url)
    if parsed.path.startswith("/wiki/"):
        return unquote(parsed.path[len("/wiki/") :]).replace("_", " ")
    return parse_qs(parsed.query).get("title", [""])[0]


def title_tokens(value: str) -> list[str]:
    return re.findall(r"[^\W_]+", value.casefold(), flags=re.UNICODE)


def title_similarity(left: str, right: str) -> float:
    left_key = " ".join(title_tokens(left))
    right_key = " ".join(title_tokens(right))
    if not left_key or not right_key:
        return 0.0
    left_tokens = set(left_key.split())
    right_tokens = set(right_key.split())
    token_score = 2 * len(left_tokens & right_tokens) / (len(left_tokens) + len(right_tokens))
    return max(token_score, difflib.SequenceMatcher(None, left_key, right_key).ratio())


def safe_wikipedia_title_match(original: str, candidate: str) -> bool:
    original_token_list = title_tokens(original)
    candidate_token_list = title_tokens(candidate)
    original_tokens = set(original_token_list)
    candidate_tokens = set(candidate_token_list)
    if not original_tokens or not candidate_tokens:
        return False
    if (
        len(original_token_list) == len(candidate_token_list) + 1
        and original_token_list[0] in {"the", "a", "an"}
        and original_token_list[1:] == candidate_token_list
    ):
        # A stale title that differs only by an initial article is highly
        # ambiguous (for example, two different films named "The Little Lady"
        # and "Little Lady"). Prefer a miss over silently changing entities.
        return False
    original_coverage = len(original_tokens & candidate_tokens) / len(original_tokens)
    candidate_position = 0
    for token in original_token_list:
        if token == candidate_token_list[candidate_position]:
            candidate_position += 1
            if candidate_position == len(candidate_token_list):
                break
    return (
        candidate_tokens.issubset(original_tokens)
        and candidate_position == len(candidate_token_list)
        and original_coverage >= 2 / 3
        and title_similarity(original, candidate) >= 0.65
    )


def wikipedia_qualifier_supported(original: str, candidate: str, lead_text: str) -> bool:
    """Require a dropped parenthetical qualifier to be explicit in the article lead."""
    qualifier_match = re.search(r"\(([^()]*)\)\s*$", original)
    if not qualifier_match:
        return True
    aliases = {"tv": "television"}

    def normalized_tokens(value: str) -> list[str]:
        return [aliases.get(token, token) for token in title_tokens(value)]

    qualifier_tokens = normalized_tokens(qualifier_match.group(1))
    if not qualifier_tokens:
        return True
    candidate_tokens = set(normalized_tokens(candidate))
    if set(qualifier_tokens).issubset(candidate_tokens):
        return True
    qualifier_key = " ".join(qualifier_tokens)
    lead_key = " ".join(normalized_tokens(lead_text[:800]))
    return qualifier_key in lead_key


def wikipedia_qualifier_type_consistent(original: str, lead_text: str) -> bool:
    """Reject an explicit lead type that conflicts with a title qualifier.

    Search can return a work whose title happens to contain the qualifier word;
    for example ``Unity (band)`` resolves to the album *Unity Band*.  Limit this
    check to the first lead sentence and to unambiguous media-type conflicts so
    that later "other uses" text cannot turn a mismatch into false support.
    """
    qualifier_match = re.search(r"\(([^()]*)\)\s*$", original)
    if not qualifier_match:
        return True
    qualifier_key = " ".join(title_tokens(qualifier_match.group(1)))
    qualifier_tokens = set(qualifier_key.split())
    first_line = next((line.strip() for line in lead_text.splitlines() if line.strip()), "")
    first_sentence = re.split(r"[.!?](?:\s|$)", first_line, maxsplit=1)[0]
    about_match = re.search(
        r"\bthis article is about\s+(.{1,240}?)(?:[.!?](?:\s|$)|\bfor (?:other|the)\b)",
        lead_text[:1200],
        re.IGNORECASE | re.DOTALL,
    )
    if about_match:
        # A Wikipedia hatnote is stronger entity-type evidence than an
        # incidental mention later in the lead.  For example, the stale URL
        # ``My Sister Eileen (musical)`` redirects to a page which explicitly
        # says it is about the short stories and book, while merely listing a
        # musical among several adaptations farther down.
        first_sentence = about_match.group(1)
    elif first_sentence.casefold().startswith("for "):
        # Navigation hatnotes such as "For the film, see ..." describe a
        # different page and must not be treated as the current page's type.
        first_sentence = ""
    descriptor_tokens = set(title_tokens(first_sentence))
    sport_qualifiers = {
        "baseball",
        "basketball",
        "bridge",
        "cricket",
        "football",
        "golf",
        "hockey",
        "rugby",
        "tennis",
    }
    sport_conflicts = {"album", "book", "film", "movie", "novel", "painting", "single", "song"}
    if qualifier_tokens & sport_qualifiers and (
        {"video", "game"}.issubset(descriptor_tokens) or descriptor_tokens & sport_conflicts
    ):
        return False
    type_rules: tuple[tuple[set[str], set[str], set[str]], ...] = (
        (
            {"film", "director"},
            {"director", "filmmaker"},
            {"album", "book", "film", "movie", "novel", "painting", "single", "song"},
        ),
        (
            {"band"},
            {"band", "duo", "group", "trio"},
            {"album", "book", "film", "movie", "novel", "painting", "single", "song"},
        ),
        (
            {"song"},
            {"single", "song"},
            {"album", "band", "book", "film", "group", "movie", "novel", "painting"},
        ),
        (
            {"album"},
            {"album", "ep"},
            {"band", "book", "film", "group", "movie", "novel", "painting", "single", "song"},
        ),
        (
            {"film"},
            {"film", "movie"},
            {"album", "band", "book", "group", "novel", "painting", "single", "song"},
        ),
        (
            {"novel"},
            {"book", "novel"},
            {"album", "band", "film", "group", "movie", "painting", "single", "song"},
        ),
        (
            {"painting"},
            {"artwork", "painting"},
            {"album", "band", "book", "film", "group", "movie", "novel", "single", "song"},
        ),
        (
            {"musical"},
            {"musical"},
            {"book", "film", "movie", "novel", "series", "stories", "story", "television"},
        ),
    )
    matching_rule = next((rule for rule in type_rules if rule[0].issubset(qualifier_tokens)), None)
    if matching_rule is None:
        return True
    _, expected_types, conflicting_types = matching_rule
    if descriptor_tokens & expected_types:
        return True
    return not bool(descriptor_tokens & conflicting_types)


def wikipedia_dropped_title_tokens_supported(original: str, candidate: str, lead_text: str) -> bool:
    """Require title tokens omitted by a search candidate to occur early in its lead."""
    original_tokens = title_tokens(original)
    candidate_counts = Counter(title_tokens(candidate))
    missing_tokens: list[str] = []
    for token in original_tokens:
        if candidate_counts[token]:
            candidate_counts[token] -= 1
        else:
            missing_tokens.append(token)
    if not missing_tokens:
        return True
    if original_tokens[0] == "category" and any(token.isdecimal() for token in missing_tokens):
        # A year-specific category commonly resolves to its parent category,
        # whose member list mentions that year near the top.  That mention is
        # hierarchy navigation, not evidence that the narrower page survived.
        return False
    lead_tokens = set(title_tokens(lead_text)[:128])
    return all(token in lead_tokens for token in missing_tokens)


def is_wikipedia_disambiguation_lead(lead_text: str) -> bool:
    """Detect search results whose lead is a disambiguation list rather than an article."""
    return bool(re.search(r"\b(?:may|can|could)(?:\s+also)?\s+refer\s+to\b", lead_text[:1000], re.IGNORECASE))


def wikipedia_html_page_flags(html: str) -> tuple[bool, bool]:
    """Return MediaWiki disambiguation and set-index markers from raw HTML."""
    lowered = html.casefold()
    is_disambiguation = "mw:pageprop/disambiguation" in lowered
    is_set_index = any(
        marker in lowered
        for marker in (
            "category:all_set_index_articles",
            "category:set_index_articles",
            "template:ship_index",
        )
    )
    return is_disambiguation, is_set_index


def decode_text(body: bytes, content_type: str) -> str:
    """Decode web text using declared/meta charset before statistical fallback."""
    charset_match = re.search(r"charset\s*=\s*['\"]?([^\s;'\"]+)", content_type, flags=re.IGNORECASE)
    if not charset_match:
        charset_match = re.search(rb"(?i)charset\s*=\s*['\"]?([^\s;'\"/>]+)", body[:8192])
        declared = charset_match.group(1).decode("ascii", errors="ignore") if charset_match else ""
    else:
        declared = charset_match.group(1)
    if declared:
        try:
            return body.decode(declared)
        except (LookupError, UnicodeDecodeError):
            pass
    try:
        return body.decode("utf-8")
    except UnicodeDecodeError:
        pass
    if detect_charset is not None:
        match = detect_charset(body).best()
        if match is not None:
            return str(match)
    return body.decode("utf-8", errors="replace")


def extract_html_document(html: str, url: str, *, content_root_id: str | None = None) -> tuple[str, str, str]:
    """Extract an HTML title and main text, with a dependency-free fallback."""
    parser = HTMLTextExtractor(content_root_id=content_root_id)
    parser.feed(html)
    title, fallback_text = parser.result()
    if content_root_id or trafilatura is None:
        return title, fallback_text, "direct_html"
    extracted = trafilatura.extract(
        html,
        url=url,
        include_comments=False,
        include_tables=True,
        include_images=False,
        include_links=False,
        deduplicate=True,
        output_format="json",
        with_metadata=True,
    )
    try:
        payload = json.loads(extracted) if extracted else {}
    except json.JSONDecodeError:
        payload = {}
    if payload:
        title = str(payload.get("title") or title)
        main_text = str(payload.get("text") or "").strip()
    else:
        main_text = (extracted or "").strip()
    if main_text:
        return title, main_text, "direct_html_trafilatura"
    return title, fallback_text, "direct_html_fallback"


def clean_title(title: str, max_chars: int = 500) -> str:
    value = re.sub(r"\s+", " ", title or "").strip()
    if len(value) <= max_chars:
        return value
    return value[: max_chars - 1].rstrip() + "…"


def extract_pdf_document(body: bytes, url: str, max_pages: int) -> tuple[str, str]:
    """Extract reading-order text from a PDF with bounded page work."""
    if pymupdf is None:
        raise FetchFailure("PDF extraction requires PyMuPDF")
    try:
        with pymupdf.open(stream=body, filetype="pdf") as document:
            if document.needs_pass:
                raise FetchFailure("encrypted PDF requires a password")
            metadata = document.metadata or {}
            title = str(metadata.get("title") or "").strip()
            parts = [
                document[index].get_text("text", sort=True).strip()
                for index in range(min(document.page_count, max_pages))
            ]
            text = "\n\n".join(part for part in parts if part)
            if document.page_count > max_pages:
                text += f"\n\n[PDF truncated after {max_pages} of {document.page_count} pages]"
    except FetchFailure:
        raise
    except Exception as exc:
        raise FetchFailure(f"invalid/unreadable PDF: {exc}") from exc
    if not title:
        title = unquote(Path(urlsplit(url).path).name).removesuffix(".pdf").replace("_", " ")
    return title, text


def error_page_reason(title: str, text: str) -> str:
    """Return a reason for obvious challenge/error shells, otherwise empty."""
    title_key = re.sub(r"\s+", " ", title).strip().casefold().rstrip(" .")
    exact_titles = {
        "access denied",
        "attention required! | cloudflare",
        "bad gateway",
        "checking your browser",
        "error",
        "forbidden",
        "internal server error",
        "just a moment",
        "not found",
        "page not found",
        "robot challenge screen",
        "security check required",
        "service unavailable",
    }
    status_title = re.fullmatch(
        r"(?:4\d\d|5\d\d)(?:\s*[-:]?\s*)(?:access denied|bad gateway|error|forbidden|internal server error|not found|service unavailable)",
        title_key,
    )
    if title_key in exact_titles or status_title:
        return f"error/challenge title: {title or '(empty)'}"
    prefix = text[:3000].casefold()
    challenge_phrases = (
        "checking the site connection security",
        "checking your browser before accessing",
        "performing security verification",
        "please enable javascript and cookies to continue",
        "press and hold to confirm you are a human",
        "verify you are not a bot",
    )
    phrase = next((item for item in challenge_phrases if item in prefix), "")
    return f"challenge text: {phrase}" if phrase else ""


def parse_jina_reader(text: str) -> tuple[str, str]:
    """Strip Jina Reader's transport header and reject obvious error pages."""
    title_match = re.search(r"(?m)^Title:\s*(.+)$", text)
    title = title_match.group(1).strip() if title_match else ""
    content_match = re.search(r"(?m)^Markdown Content:\s*$", text)
    header = text[: content_match.start()] if content_match else ""
    content = text[content_match.end() :].strip() if content_match else text.strip()

    warnings = " ".join(re.findall(r"(?im)^Warning:\s*(.+)$", header))
    warning_key = warnings.casefold()
    rejected = (
        bool(error_page_reason(title, content))
        or "requiring captcha" in warning_key
        or bool(re.search(r"target url returned error\s+(?:4\d\d|5\d\d)", warning_key))
    )
    if rejected:
        reason = title or warnings or content[:120]
        raise ValueError(f"Jina Reader returned a challenge/error page: {reason}")
    return title, content


class Fetcher:
    def __init__(
        self,
        *,
        timeout: float,
        max_bytes: int,
        min_chars: int,
        per_host_interval: float,
        retries: int,
        wikipedia_source: str,
        max_pdf_pages: int,
        respect_robots: bool,
        wikipedia_search_fallback: bool,
        jina_direct_fallback: bool,
        direct_jina_fallback: bool,
        user_agent: str,
        robots_retries: int = 2,
    ) -> None:
        self.max_bytes = max_bytes
        self.min_chars = min_chars
        self.retries = retries
        self.wikipedia_source = wikipedia_source
        self.max_pdf_pages = max_pdf_pages
        self.respect_robots = respect_robots
        self.wikipedia_search_fallback = wikipedia_search_fallback
        self.jina_direct_fallback = jina_direct_fallback
        self.direct_jina_fallback = direct_jina_fallback
        self.robot_user_agent = user_agent.split(maxsplit=1)[0]
        self.robots_retries = robots_retries
        self._robots_tasks: dict[str, asyncio.Task[RobotsPolicy]] = {}
        self._robots_decisions: dict[str, dict[str, Any]] = {}
        self.rate_limiter = HostRateLimiter(per_host_interval)
        self.client = httpx.AsyncClient(
            follow_redirects=True,
            timeout=httpx.Timeout(timeout),
            headers={"User-Agent": user_agent, "Accept-Encoding": "gzip, deflate"},
        )

    async def close(self) -> None:
        await self.client.aclose()

    async def get_bytes(
        self,
        url: str,
        *,
        params: dict[str, str] | None = None,
        max_bytes: int | None = None,
        retries: int | None = None,
    ) -> HTTPBody:
        hostname = (urlsplit(url).hostname or "unknown").casefold()
        byte_limit = self.max_bytes if max_bytes is None else max_bytes
        retry_count = self.retries if retries is None else retries
        for attempt in range(retry_count + 1):
            await self.rate_limiter.wait(hostname)
            try:
                async with self.client.stream("GET", url, params=params) as response:
                    content_length = response.headers.get("content-length")
                    if content_length and int(content_length) > byte_limit:
                        raise ValueError(f"response too large: Content-Length={content_length}")
                    chunks: list[bytes] = []
                    size = 0
                    async for chunk in response.aiter_bytes():
                        size += len(chunk)
                        if size > byte_limit:
                            raise ValueError(f"response exceeded byte limit={byte_limit}")
                        chunks.append(chunk)
                    result = HTTPBody(
                        status_code=response.status_code,
                        content_type=response.headers.get("content-type", ""),
                        final_url=str(response.url),
                        body=b"".join(chunks),
                    )
                    retry_after = response.headers.get("retry-after", "")
                if result.status_code not in {429, 500, 502, 503, 504} or attempt == retry_count:
                    return result
                parsed_retry_after = retry_after_seconds(retry_after)
                if parsed_retry_after is not None:
                    # Respect server backpressure without letting one origin
                    # stall a resumable corpus job for minutes or hours.
                    parsed_retry_after = min(parsed_retry_after, 30.0)
                if result.status_code == 429:
                    delay = max(parsed_retry_after or 0.0, 30.0)
                    await self.rate_limiter.defer(hostname, delay)
                else:
                    delay = parsed_retry_after if parsed_retry_after is not None else min(2 ** (attempt + 1), 30)
                    await asyncio.sleep(delay)
            except httpx.TransportError:
                if attempt == retry_count:
                    raise
                await asyncio.sleep(min(2 ** (attempt + 1), 30))
        raise AssertionError("unreachable")

    async def _load_robots_policy(self, target_url: str) -> RobotsPolicy:
        parsed = urlsplit(target_url)
        robots_url = urlunsplit((parsed.scheme, parsed.netloc, "/robots.txt", "", ""))
        fetched_at = datetime.now(timezone.utc).isoformat()
        try:
            response = await self.get_bytes(robots_url, max_bytes=512_000, retries=self.robots_retries)
        except (httpx.HTTPError, UnicodeError, ValueError) as exc:
            return RobotsPolicy(
                robots_url=robots_url,
                parser=None,
                default_allowed=False,
                status="unavailable",
                reason=f"robots.txt unavailable: {type(exc).__name__}: {exc}",
                fetched_at=fetched_at,
            )
        if response.status_code in {401, 403, 429} or response.status_code >= 500:
            return RobotsPolicy(
                robots_url=robots_url,
                parser=None,
                default_allowed=False,
                status="unavailable",
                reason=f"robots.txt returned HTTP {response.status_code}",
                fetched_at=fetched_at,
                http_status=response.status_code,
            )
        if response.status_code >= 400:
            return RobotsPolicy(
                robots_url=robots_url,
                parser=None,
                default_allowed=True,
                status="absent",
                reason=f"robots.txt absent (HTTP {response.status_code})",
                fetched_at=fetched_at,
                http_status=response.status_code,
            )
        content_sha256 = hashlib.sha256(response.body).hexdigest()
        try:
            parser = RobotFileParser()
            parser.set_url(robots_url)
            parser.parse(decode_text(response.body, response.content_type).splitlines())
            hostname = (parsed.hostname or "").casefold()
            crawl_delay = parser.crawl_delay(self.robot_user_agent) or parser.crawl_delay("*")
            if crawl_delay is not None:
                self.rate_limiter.set_host_interval(hostname, float(crawl_delay))
        except (UnicodeError, ValueError) as exc:
            return RobotsPolicy(
                robots_url=robots_url,
                parser=None,
                default_allowed=False,
                status="invalid",
                reason=f"invalid robots.txt: {type(exc).__name__}: {exc}",
                fetched_at=fetched_at,
                http_status=response.status_code,
                content_sha256=content_sha256,
            )
        return RobotsPolicy(
            robots_url=robots_url,
            parser=parser,
            default_allowed=False,
            status="parsed",
            reason="robots.txt parsed",
            fetched_at=fetched_at,
            http_status=response.status_code,
            content_sha256=content_sha256,
        )

    async def robots_decision(self, target_url: str) -> dict[str, Any]:
        """Return an auditable, path-specific decision for one target URL."""
        parsed = urlsplit(target_url)
        origin = urlunsplit((parsed.scheme.casefold(), parsed.netloc.casefold(), "", "", ""))
        task = self._robots_tasks.get(origin)
        if task is None:
            task = asyncio.create_task(self._load_robots_policy(target_url))
            self._robots_tasks[origin] = task
        policy = await task
        allowed, reason = policy.decision(self.robot_user_agent, target_url)
        decision = {
            "target_url": target_url,
            "origin": origin,
            "robots_url": policy.robots_url,
            "user_agent": self.robot_user_agent,
            "allowed": allowed,
            "reason": reason,
            "policy_status": policy.status,
            "robots_http_status": policy.http_status,
            "robots_content_sha256": policy.content_sha256,
            "robots_fetched_at": policy.fetched_at,
            "checked_at": datetime.now(timezone.utc).isoformat(),
        }
        self._robots_decisions[target_url] = decision
        return decision

    async def enforce_robots(self, target_url: str) -> dict[str, Any] | None:
        if not self.respect_robots:
            return None
        decision = await self.robots_decision(target_url)
        if not decision["allowed"]:
            raise FetchFailure(str(decision["reason"]), source="robots")
        return decision

    async def fetch_wikipedia_api(self, canonical_url: str) -> dict[str, Any]:
        parsed = urlsplit(canonical_url)
        title = wikipedia_title(canonical_url)
        if not title:
            raise ValueError("could not extract a Wikipedia title")
        api_url = f"https://{parsed.hostname}/w/api.php"
        response = await self.get_bytes(
            api_url,
            params={
                "action": "query",
                "prop": "extracts|info",
                "explaintext": "1",
                "redirects": "1",
                "inprop": "url",
                "format": "json",
                "formatversion": "2",
                "titles": title,
            },
        )
        if response.status_code >= 400:
            raise RuntimeError(f"HTTP {response.status_code}")
        payload = json.loads(response.body.decode("utf-8"))
        pages = payload.get("query", {}).get("pages", [])
        if not pages or pages[0].get("missing") is True:
            raise ValueError("Wikipedia page is missing")
        page = pages[0]
        return {
            "title": str(page.get("title") or title),
            "text": str(page.get("extract") or ""),
            "source": "wikipedia_api",
            "http_status": response.status_code,
            "content_type": response.content_type,
        }

    async def fetch_wikipedia_search_fallback(self, canonical_url: str) -> dict[str, Any]:
        """Resolve a stale Wikipedia title through same-language MediaWiki search."""
        parsed = urlsplit(canonical_url)
        original_title = wikipedia_title(canonical_url)
        if not original_title:
            raise FetchFailure("Wikipedia URL has no recoverable title", source="wikipedia_search")
        api_url = f"https://{parsed.hostname}/w/api.php"
        response = await self.get_bytes(
            api_url,
            params={
                "action": "query",
                "list": "search",
                "srsearch": original_title,
                "srnamespace": "0",
                "srlimit": "5",
                "format": "json",
                "formatversion": "2",
            },
            retries=max(self.retries, 3),
        )
        if response.status_code >= 400:
            raise FetchFailure(
                f"Wikipedia search HTTP {response.status_code}",
                http_status=response.status_code,
                content_type=response.content_type,
                source="wikipedia_search",
            )
        payload = json.loads(decode_text(response.body, response.content_type))
        candidates = payload.get("query", {}).get("search", [])
        ranked = sorted(
            (
                (title_similarity(original_title, str(item.get("title") or "")), str(item.get("title") or ""))
                for item in candidates
            ),
            reverse=True,
        )
        safe_ranked = [item for item in ranked if safe_wikipedia_title_match(original_title, item[1])]
        if not safe_ranked:
            best = ranked[0] if ranked else (0.0, "")
            raise FetchFailure(
                f"Wikipedia title search found no close match for {original_title!r}; best={best[1]!r} score={best[0]:.3f}",
                source="wikipedia_search",
            )
        resolved_title = safe_ranked[0][1]
        resolved_path = "/wiki/" + quote(resolved_title.replace(" ", "_"), safe="()_,-")
        resolved_url = urlunsplit((parsed.scheme or "https", parsed.netloc, resolved_path, "", ""))
        raw = await self.fetch_generic(resolved_url, content_root_id="mw-content-text")
        raw["title"] = re.sub(r"\s+-\s+Wikipedia$", "", raw["title"]).strip()
        is_disambiguation = bool(raw.pop("_wikipedia_disambiguation", False))
        is_set_index = bool(raw.pop("_wikipedia_set_index", False))
        if is_disambiguation or is_wikipedia_disambiguation_lead(str(raw.get("text") or "")):
            raise FetchFailure(
                f"Wikipedia search candidate {resolved_title!r} is a disambiguation page",
                http_status=raw.get("http_status"),
                content_type=str(raw.get("content_type") or ""),
                source="wikipedia_search",
            )
        if is_set_index:
            raise FetchFailure(
                f"Wikipedia search candidate {resolved_title!r} is a set-index page",
                http_status=raw.get("http_status"),
                content_type=str(raw.get("content_type") or ""),
                source="wikipedia_search",
            )
        if not wikipedia_dropped_title_tokens_supported(
            original_title, resolved_title, str(raw.get("text") or "")
        ):
            raise FetchFailure(
                f"Wikipedia search candidate {resolved_title!r} does not support omitted title tokens from "
                f"{original_title!r}",
                http_status=raw.get("http_status"),
                content_type=str(raw.get("content_type") or ""),
                source="wikipedia_search",
            )
        if not wikipedia_qualifier_type_consistent(original_title, str(raw.get("text") or "")):
            raise FetchFailure(
                f"Wikipedia search candidate {resolved_title!r} has a lead type that conflicts with "
                f"{original_title!r}",
                http_status=raw.get("http_status"),
                content_type=str(raw.get("content_type") or ""),
                source="wikipedia_search",
            )
        if not wikipedia_qualifier_supported(original_title, resolved_title, str(raw.get("text") or "")):
            raise FetchFailure(
                f"Wikipedia search candidate {resolved_title!r} does not support the qualifier in {original_title!r}",
                http_status=raw.get("http_status"),
                content_type=str(raw.get("content_type") or ""),
                source="wikipedia_search",
            )
        raw["source"] = "wikipedia_search_html"
        return raw

    async def fetch_generic(self, fetch_url: str, *, content_root_id: str | None = None) -> dict[str, Any]:
        response = await self.get_bytes(fetch_url)
        if response.status_code >= 400:
            raise FetchFailure(
                f"HTTP {response.status_code}",
                http_status=response.status_code,
                content_type=response.content_type,
                source="http",
            )
        content_type = response.content_type.casefold()
        hostname = (urlsplit(fetch_url).hostname or "").casefold()
        wikipedia_disambiguation = False
        wikipedia_set_index = False
        if hostname == "r.jina.ai":
            decoded = decode_text(response.body, response.content_type)
            try:
                title, text = parse_jina_reader(decoded)
            except ValueError as exc:
                raise FetchFailure(
                    str(exc),
                    http_status=response.status_code,
                    content_type=response.content_type,
                    source="jina_reader",
                ) from exc
            source = "jina_reader"
        elif "application/pdf" in content_type or response.body.startswith(b"%PDF-"):
            title, text = await asyncio.to_thread(
                extract_pdf_document, response.body, response.final_url, self.max_pdf_pages
            )
            source = "direct_pdf_pymupdf"
        elif (
            content_type.startswith("text/") and "text/html" not in content_type and "text/xml" not in content_type
        ) or any(item in content_type for item in ("application/json", "application/ld+json")):
            decoded = decode_text(response.body, response.content_type)
            title = ""
            text = decoded
            source = "direct_text"
        else:
            if content_type.startswith(("audio/", "image/", "video/")) or any(
                item in content_type
                for item in ("application/gzip", "application/zip", "application/x-7z-compressed", "application/x-rar")
            ):
                raise FetchFailure(
                    f"non-text content type: {response.content_type}",
                    http_status=response.status_code,
                    content_type=response.content_type,
                    source="unsupported",
                )
            decoded = decode_text(response.body, response.content_type)
            prefix = decoded.lstrip().lower()
            if (
                "text/html" in content_type
                or "application/xhtml+xml" in content_type
                or prefix.startswith(("<!doctype html", "<html"))
            ):
                if hostname == "wikipedia.org" or hostname.endswith(".wikipedia.org"):
                    wikipedia_disambiguation, wikipedia_set_index = wikipedia_html_page_flags(decoded)
                title, text, source = await asyncio.to_thread(
                    extract_html_document,
                    decoded,
                    response.final_url,
                    content_root_id=content_root_id,
                )
            elif any(item in content_type for item in ("application/xml", "text/xml", "+xml")) or prefix.startswith(
                "<?xml"
            ):
                parser = HTMLTextExtractor()
                parser.feed(decoded)
                title, text = parser.result()
                source = "direct_xml"
            else:
                raise FetchFailure(
                    f"unsupported content type: {response.content_type or 'unknown'}",
                    http_status=response.status_code,
                    content_type=response.content_type,
                    source="unsupported",
                )
        reason = error_page_reason(title, text)
        if reason:
            raise FetchFailure(
                reason,
                http_status=response.status_code,
                content_type=response.content_type,
                source=source,
            )
        if len(text.strip()) < self.min_chars:
            raise FetchFailure(
                f"extracted only {len(text.strip())} characters",
                http_status=response.status_code,
                content_type=response.content_type,
                source=source,
            )
        result = {
            "title": title,
            "text": text,
            "source": source,
            "http_status": response.status_code,
            "content_type": response.content_type,
        }
        if hostname == "wikipedia.org" or hostname.endswith(".wikipedia.org"):
            result["_wikipedia_disambiguation"] = wikipedia_disambiguation
            result["_wikipedia_set_index"] = wikipedia_set_index
        return result

    def finalize(self, result: dict[str, Any] | Exception) -> dict[str, Any]:
        try:
            if isinstance(result, Exception):
                raise result
            text = re.sub(r"\x00", "", result.pop("text", "")).strip()
            if len(text) < self.min_chars:
                raise ValueError(f"extracted only {len(text)} characters")
            result["title"] = clean_title(str(result.get("title") or ""))
            result.update({"status": "success", "text": text, "error": ""})
        except (httpx.HTTPError, json.JSONDecodeError, RuntimeError, UnicodeError, ValueError) as exc:
            result = {
                "status": "failed",
                "title": "",
                "text": "",
                "source": str(getattr(exc, "source", "")),
                "http_status": getattr(exc, "http_status", None),
                "content_type": str(getattr(exc, "content_type", "")),
                "error": f"{type(exc).__name__}: {exc}"[:1000],
            }
        result["fetched_at"] = datetime.now(timezone.utc).isoformat()
        return result

    async def fetch_record(self, record: dict[str, Any]) -> dict[str, Any]:
        canonical_host = (urlsplit(record["canonical_url"]).hostname or "").casefold()
        try:
            if canonical_host == "wikipedia.org" or canonical_host.endswith(".wikipedia.org"):
                if self.wikipedia_source == "api":
                    raw = await self.fetch_wikipedia_api(record["canonical_url"])
                else:
                    try:
                        raw = await self.fetch_generic(record["canonical_url"], content_root_id="mw-content-text")
                        raw["title"] = re.sub(r"\s+-\s+Wikipedia$", "", raw["title"]).strip()
                        raw["source"] = "wikipedia_html"
                    except FetchFailure as direct_error:
                        if direct_error.http_status != 404 or not self.wikipedia_search_fallback:
                            raise
                        try:
                            raw = await self.fetch_wikipedia_search_fallback(record["canonical_url"])
                        except (httpx.HTTPError, json.JSONDecodeError, UnicodeError, ValueError) as search_error:
                            raise FetchFailure(
                                f"Wikipedia direct fetch failed ({direct_error}); search fallback failed ({search_error})",
                                http_status=getattr(search_error, "http_status", None),
                                content_type=str(getattr(search_error, "content_type", "")),
                                source="wikipedia_direct_then_search",
                            ) from search_error
            else:
                fetch_host = (urlsplit(record["fetch_url"]).hostname or "").casefold()
                if fetch_host == "r.jina.ai":
                    try:
                        raw = await self.fetch_generic(record["fetch_url"])
                    except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as jina_error:
                        if not self.jina_direct_fallback:
                            raise
                        try:
                            await self.enforce_robots(record["canonical_url"])
                            raw = await self.fetch_generic(record["canonical_url"])
                        except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as direct_error:
                            raise FetchFailure(
                                f"Jina failed ({jina_error}); direct fallback failed ({direct_error})",
                                http_status=getattr(direct_error, "http_status", None),
                                content_type=str(getattr(direct_error, "content_type", "")),
                                source="jina_then_direct",
                            ) from direct_error
                else:
                    try:
                        await self.enforce_robots(record["canonical_url"])
                        raw = await self.fetch_generic(record["canonical_url"])
                    except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as direct_error:
                        if not self.direct_jina_fallback or getattr(direct_error, "source", "") in {
                            "robots",
                            "unsupported",
                        }:
                            raise
                        reader_url = f"https://r.jina.ai/{record['canonical_url']}"
                        try:
                            raw = await self.fetch_generic(reader_url)
                        except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as jina_error:
                            raise FetchFailure(
                                f"Direct fetch failed ({direct_error}); Jina fallback failed ({jina_error})",
                                http_status=getattr(jina_error, "http_status", None),
                                content_type=str(getattr(jina_error, "content_type", "")),
                                source="direct_then_jina",
                            ) from jina_error
        except (httpx.HTTPError, json.JSONDecodeError, RuntimeError, UnicodeError, ValueError) as exc:
            raw = exc
        result = self.finalize(raw)
        robots_decision = self._robots_decisions.get(record["canonical_url"])
        if robots_decision is not None:
            result["_robots_decision"] = robots_decision
        return result


def domain_matches(hostname: str, allowed_domain: str) -> bool:
    host = hostname.casefold().strip(".")
    allowed = allowed_domain.casefold().strip(".")
    return host == allowed or host.endswith("." + allowed)


def is_wikipedia(record: dict[str, Any]) -> bool:
    host = (urlsplit(record["canonical_url"]).hostname or "").casefold()
    return host == "wikipedia.org" or host.endswith(".wikipedia.org")


def is_allowed(record: dict[str, Any], allow_domains: list[str], allow_direct_all: bool) -> bool:
    canonical_host = urlsplit(record["canonical_url"]).hostname or ""
    fetch_host = urlsplit(record["fetch_url"]).hostname or ""
    if canonical_host == "wikipedia.org" or canonical_host.endswith(".wikipedia.org"):
        return True
    if fetch_host.casefold() == "r.jina.ai":
        return True
    if allow_direct_all:
        return True
    return any(domain_matches(canonical_host, allowed) for allowed in allow_domains)


async def fetch_manifest(
    manifest_path: Path,
    database_path: Path,
    *,
    limit: int,
    concurrency: int,
    timeout: float,
    max_bytes: int,
    min_chars: int,
    per_host_interval: float,
    retries: int,
    wikipedia_source: str,
    max_pdf_pages: int,
    respect_robots: bool,
    wikipedia_search_fallback: bool,
    jina_direct_fallback: bool,
    direct_jina_fallback: bool,
    allow_domains: list[str],
    allow_direct_all: bool,
    only_wikipedia: bool,
    retry_failed: bool,
    user_agent: str,
    rebuild_index: bool,
    robots_retries: int = 2,
) -> dict[str, Any]:
    records = list(read_jsonl(manifest_path))
    by_id = {record["url_id"]: record for record in records}
    connection = connect(database_path)
    ingest_manifest(connection, records)
    status_by_id = {row["url_id"]: row["status"] for row in connection.execute("SELECT url_id, status FROM documents")}
    candidates = [
        record
        for record in records
        if is_allowed(record, allow_domains, allow_direct_all)
        and (not only_wikipedia or is_wikipedia(record))
        and (
            status_by_id.get(record["url_id"]) == "pending"
            or (retry_failed and status_by_id.get(record["url_id"]) == "failed")
        )
    ]
    candidates.sort(
        key=lambda record: (
            0 if record["domain"].endswith("wikipedia.org") else 1 if record.get("has_jina_reader_url") else 2,
            -int(record.get("visit_count", 0)),
            record["url_id"],
        )
    )
    if limit:
        candidates = candidates[:limit]

    queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
    for record in candidates:
        queue.put_nowait(record)
    progress: Counter[str] = Counter()
    progress_lock = asyncio.Lock()
    fetcher = Fetcher(
        timeout=timeout,
        max_bytes=max_bytes,
        min_chars=min_chars,
        per_host_interval=per_host_interval,
        retries=retries,
        wikipedia_source=wikipedia_source,
        max_pdf_pages=max_pdf_pages,
        respect_robots=respect_robots,
        wikipedia_search_fallback=wikipedia_search_fallback,
        jina_direct_fallback=jina_direct_fallback,
        direct_jina_fallback=direct_jina_fallback,
        user_agent=user_agent,
        robots_retries=robots_retries,
    )

    async def worker() -> None:
        while True:
            try:
                record = queue.get_nowait()
            except asyncio.QueueEmpty:
                return
            result = await fetcher.fetch_record(record)
            save_fetch_result(connection, record["url_id"], result)
            async with progress_lock:
                progress[result["status"]] += 1
                done = sum(progress.values())
                if done == 1 or done % 50 == 0 or done == len(candidates):
                    print(
                        f"fetched {done}/{len(candidates)} success={progress['success']} failed={progress['failed']}"
                    )
            queue.task_done()

    try:
        await asyncio.gather(*(worker() for _ in range(max(1, concurrency))))
    finally:
        await fetcher.close()
    indexed = rebuild_fts(connection) if rebuild_index else None
    index_counts = fts_counts(connection) if rebuild_index else None
    summary = {
        "manifest_records": len(by_id),
        "eligible_records": sum(is_allowed(record, allow_domains, allow_direct_all) for record in records),
        "attempted": len(candidates),
        "wikipedia_source": wikipedia_source,
        "respect_robots": respect_robots,
        "robots_retries": robots_retries,
        "wikipedia_search_fallback": wikipedia_search_fallback,
        "jina_direct_fallback": jina_direct_fallback,
        "direct_jina_fallback": direct_jina_fallback,
        "html_extractor": "trafilatura" if trafilatura is not None else "stdlib_fallback",
        "pdf_extractor": "pymupdf" if pymupdf is not None else "unavailable",
        "attempt_results": dict(progress),
        "database_status": status_counts(connection),
        "fts_documents": indexed,
        "fts_chunks": index_counts["chunks"] if index_counts else None,
        "database": str(database_path),
    }
    connection.close()
    return summary


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, required=True, help="urls.jsonl from extract_retrieval_manifest.py")
    parser.add_argument("--database", type=Path, required=True)
    parser.add_argument("--limit", type=int, default=0, help="maximum URLs this invocation; 0 means all eligible")
    parser.add_argument("--concurrency", type=int, default=4)
    parser.add_argument("--timeout", type=float, default=30.0)
    parser.add_argument("--max-bytes", type=int, default=8_000_000)
    parser.add_argument("--min-chars", type=int, default=100)
    parser.add_argument("--per-host-interval", type=float, default=0.25)
    parser.add_argument("--retries", type=int, default=3)
    parser.add_argument("--robots-retries", type=int, default=2)
    parser.add_argument("--max-pdf-pages", type=int, default=500)
    parser.add_argument(
        "--wikipedia-source",
        choices=("html", "api"),
        default="html",
        help="HTML is faster/cached; API produces cleaner plaintext but is much slower for full extracts",
    )
    parser.add_argument("--allow-domain", action="append", default=[], help="opt in a direct-fetch domain")
    parser.add_argument("--allow-direct-all", action="store_true", help="direct-fetch every domain; use responsibly")
    parser.add_argument(
        "--ignore-robots",
        action="store_true",
        help="ignore robots.txt for direct-origin requests (not recommended)",
    )
    parser.add_argument(
        "--wikipedia-search-fallback",
        action="store_true",
        help="resolve stale Wikipedia 404 titles via conservative same-language MediaWiki search",
    )
    parser.add_argument(
        "--only-wikipedia",
        action="store_true",
        help="restrict this invocation to Wikipedia records (useful for a slow recovery pass)",
    )
    parser.add_argument(
        "--jina-direct-fallback",
        action="store_true",
        help="when a recorded Jina Reader fetch fails, try the canonical origin subject to robots.txt",
    )
    parser.add_argument(
        "--direct-jina-fallback",
        action="store_true",
        help="when an allowed direct-origin request fails, try the public Jina Reader endpoint",
    )
    parser.add_argument("--retry-failed", action="store_true")
    parser.add_argument("--rebuild-index", action="store_true")
    parser.add_argument(
        "--user-agent",
        default="Miles-DeepResearch9K-Corpus/0.1 (local academic research)",
    )
    args = parser.parse_args()
    if (
        args.limit < 0
        or args.concurrency < 1
        or args.per_host_interval < 0
        or args.retries < 0
        or args.max_pdf_pages < 1
        or args.robots_retries < 0
    ):
        parser.error(
            "--limit/--retries must be non-negative, --concurrency/--max-pdf-pages >= 1, and --per-host-interval >= 0"
        )
    summary = asyncio.run(
        fetch_manifest(
            args.manifest,
            args.database,
            limit=args.limit,
            concurrency=args.concurrency,
            timeout=args.timeout,
            max_bytes=args.max_bytes,
            min_chars=args.min_chars,
            per_host_interval=args.per_host_interval,
            retries=args.retries,
            wikipedia_source=args.wikipedia_source,
            max_pdf_pages=args.max_pdf_pages,
            respect_robots=not args.ignore_robots,
            wikipedia_search_fallback=args.wikipedia_search_fallback,
            jina_direct_fallback=args.jina_direct_fallback,
            direct_jina_fallback=args.direct_jina_fallback,
            allow_domains=args.allow_domain,
            allow_direct_all=args.allow_direct_all,
            only_wikipedia=args.only_wikipedia,
            retry_failed=args.retry_failed,
            user_agent=args.user_agent,
            rebuild_index=args.rebuild_index,
            robots_retries=args.robots_retries,
        )
    )
    print(json.dumps(summary, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()