File size: 68,535 Bytes
8a62fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Collect public, non-fork DESIGN.md files using only Python's standard library.

Usage: python3 collect.py run --root RAW_ROOT --token-file TOKEN_FILE
       python3 collect.py resume --root RAW_ROOT --token-file TOKEN_FILE
       python3 collect.py status --root RAW_ROOT
       python3 collect.py verify --root RAW_ROOT

Discovery finishes before downloading pinned snapshots. Original bytes and
metadata retain the version-2 layout consumed by filter.py. This standalone
script has no local helper-module dependencies.
"""
from __future__ import annotations

import argparse
import base64
import fcntl
import hashlib
import json
import logging
import math
import os
import re
import signal
import sqlite3
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import closing
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from http.client import IncompleteRead
from pathlib import Path
from urllib.parse import quote

LOG = logging.getLogger(__name__)


# GitHub requests and rate limits

class APIError(RuntimeError):
    def __init__(self, status: int, path: str, message: str):
        self.status = status
        self.path = path
        super().__init__(f"GitHub HTTP {status} for {path.split('?')[0]}: {message}")


def retry_after_seconds(value):
    """Interpret Retry-After as seconds or an HTTP date, ignoring bad values."""
    if value is None:
        return 0.0
    try:
        seconds = float(value)
        return max(0.0, seconds) if math.isfinite(seconds) else 0.0
    except (TypeError, ValueError):
        try:
            deadline = parsedate_to_datetime(str(value))
            if deadline.tzinfo is None:
                deadline = deadline.replace(tzinfo=timezone.utc)
            return max(0.0, deadline.timestamp() - time.time())
        except (TypeError, ValueError, OverflowError):
            return 0.0


class SameHostRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        target = urllib.parse.urlparse(newurl)
        if target.scheme != "https" or target.netloc != "api.github.com":
            raise APIError(code, req.full_url, "refused cross-host redirect")
        return super().redirect_request(req, fp, code, msg, headers, newurl)


class GitHubClient:
    def __init__(self, token_file: Path):
        token = token_file.read_text(encoding="utf-8").strip()
        if not token or "\n" in token or "\r" in token:
            raise ValueError("Token file must contain one nonempty token")
        self._token = token
        self._opener = urllib.request.build_opener(SameHostRedirect())
        self._next = {"all": 0.0, "code": 0.0, "search": 0.0}
        self._quota = {}
        self.request_count = 0

    @staticmethod
    def bucket(path: str) -> str:
        return "code" if path.startswith("/search/code") else "search" if path.startswith("/search/") else "core"

    def _wait(self, path: str):
        bucket = self.bucket(path)
        now = time.time()
        due = max(self._next["all"], self._next.get(bucket, 0))
        # GitHub may report code search under either search or code_search.
        for resource in (("code_search", "search") if bucket == "code" else ("search",) if bucket == "search" else ("core",)):
            remaining, reset = self._quota.get(resource, (1, 0))
            if remaining <= 0 and reset > now:
                due = max(due, reset + 2)
        while due > time.time():
            delay = min(due - time.time(), 30)
            if delay > 5:
                LOG.info("Waiting %.0fs for GitHub rate limit (%s)", due - time.time(), bucket)
            time.sleep(max(0, delay))
        now = time.time()
        self._next["all"] = now + 1.05
        if bucket == "code":
            self._next["code"] = now + 7.6
        elif bucket == "search":
            self._next["search"] = now + 2.6

    def _remember_headers(self, headers):
        try:
            resource = headers.get("X-RateLimit-Resource")
            if resource:
                self._quota[resource] = (int(headers["X-RateLimit-Remaining"]), float(headers["X-RateLimit-Reset"]))
        except (TypeError, ValueError, KeyError):
            pass

    def _request(self, path: str, params=None) -> bytes:
        if not path.startswith("/") or path.startswith("//"):
            raise ValueError("API paths must be relative to api.github.com")
        url = "https://api.github.com" + path
        if params:
            url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
        headers = {"Authorization": "Bearer " + self._token, "Accept": "application/vnd.github+json",
                   "User-Agent": "design-md-corpus-collector/1.0", "X-GitHub-Api-Version": "2026-03-10"}
        for attempt in range(6):
            self._wait(path)
            self.request_count += 1
            try:
                request = urllib.request.Request(url, headers=headers)
                with self._opener.open(request, timeout=60) as response:
                    self._remember_headers(response.headers)
                    return response.read()
            except urllib.error.HTTPError as exc:
                self._remember_headers(exc.headers)
                try:
                    message = str(json.loads(exc.read()).get("message", "request failed"))
                except Exception:
                    message = "request failed"
                finally:
                    exc.close()
                # Never allow an upstream echo to disclose the credential.
                message = message.replace(self._token, "[REDACTED]")[:400]
                retryable = exc.code in (408, 429, 500, 502, 503, 504) or (exc.code == 403 and any(s in message.lower() for s in ("rate limit", "abuse", "secondary")))
                if not retryable or attempt == 5:
                    raise APIError(exc.code, path, message) from None
                delay = retry_after_seconds(exc.headers.get("Retry-After"))
                delay = max(delay, min(60 * 2 ** attempt, 900) if exc.code in (403, 429) else min(2 ** attempt, 30))
                LOG.warning("Retrying HTTP %s after %.0fs: %s", exc.code, delay, path.split("?")[0])
                time.sleep(delay)
            except (urllib.error.URLError, TimeoutError, OSError, IncompleteRead) as exc:
                if attempt == 5:
                    raise APIError(0, path, type(exc).__name__) from None
                time.sleep(min(2 ** attempt, 30))
        raise AssertionError("unreachable")

    def get_json(self, path: str, params=None):
        return json.loads(self._request(path, params))


# Resumable search and coverage gaps

# REST code search excludes forks by default unless fork:true or fork:only
# is requested. Repository metadata is checked independently before download.
CODE_QUERY = "filename:design.md"
CODE_MAX_BYTES = 393216
PER_PAGE = 100
SEARCH_LIMIT = 1000
INCOMPLETE_ATTEMPTS = 3
REPOSITORY_TERMS = (
    '"stitch.withgoogle.com/docs/design-md"',
    '"google-labs-code/design.md"',
    '"DESIGN.md" "stitch"',
)
REPOSITORY_START = int(datetime(2008, 1, 1, tzinfo=timezone.utc).timestamp())
JOB_COLUMNS = (
    "kind", "query", "page", "lo", "hi", "state", "total_count",
    "incomplete", "error",
)


class Discovery:
    """Discover repositories and commit progress after every search page."""

    def __init__(self, client, db: sqlite3.Connection):
        self.client = client
        self.db = db
        self._write(self._initialize_schema)

    def _write(self, operation):
        """Commit each search page and its discoveries in one transaction."""
        with self.db:
            self.db.execute("BEGIN IMMEDIATE")
            return operation()

    def _initialize_schema(self):
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS discovery_jobs (
                kind TEXT NOT NULL,
                query TEXT NOT NULL,
                page INTEGER NOT NULL DEFAULT 1,
                lo INTEGER NOT NULL,
                hi INTEGER NOT NULL,
                state TEXT NOT NULL DEFAULT 'pending',
                total_count INTEGER,
                incomplete INTEGER NOT NULL DEFAULT 0,
                error TEXT,
                UNIQUE(kind, query)
            )
        """)
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS discovered_repositories (
                repo_id INTEGER PRIMARY KEY,
                full_name TEXT NOT NULL,
                discovery_sources TEXT NOT NULL,
                is_fork INTEGER
            )
        """)
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS discovered_files (
                repo_id INTEGER NOT NULL,
                path TEXT NOT NULL,
                search_blob_sha TEXT NOT NULL,
                discovery_sources TEXT NOT NULL,
                first_seen_at TEXT NOT NULL,
                last_seen_at TEXT NOT NULL,
                revision INTEGER NOT NULL DEFAULT 1,
                PRIMARY KEY (repo_id, path)
            )
        """)
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS repository_code_scopes (
                repo_id INTEGER NOT NULL,
                full_name TEXT NOT NULL,
                query_base TEXT NOT NULL,
                PRIMARY KEY (repo_id, query_base)
            )
        """)
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS discovery_settings (
                key TEXT PRIMARY KEY, value TEXT NOT NULL
            )
        """)

    def run_code_search(self) -> dict:
        """Search case-insensitive filename candidates, sharded by byte size."""
        self._write(lambda: self._enqueue("code", self._code_query(0, CODE_MAX_BYTES),
                                          0, CODE_MAX_BYTES))
        return self._run("code")

    def run_repository_search(self) -> dict:
        """Supplement code search with README searches and creation shards."""
        def enqueue_roots():
            self.db.execute(
                "INSERT OR IGNORE INTO discovery_settings(key, value) VALUES (?, ?)",
                ("repository_cutoff_utc", str(int(datetime.now(timezone.utc).timestamp()))),
            )
            cutoff = int(self.db.execute(
                "SELECT value FROM discovery_settings WHERE key = ?",
                ("repository_cutoff_utc",),
            ).fetchone()[0])
            for term in REPOSITORY_TERMS:
                for archived in ("false", "true"):
                    base = f"{term} in:readme is:public archived:{archived}"
                    self._enqueue("repository", self._repository_query(
                        base, REPOSITORY_START, cutoff), REPOSITORY_START, cutoff)
        self._write(enqueue_roots)
        return self._run("repository")

    def run_repository_code_search(self, repo_id: int, full_name: str) -> dict:
        """Resume code search within one repository, without scanning its trees."""
        safe_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"
        parts = full_name.split("/") if isinstance(full_name, str) else []
        if (not isinstance(repo_id, int) or isinstance(repo_id, bool) or repo_id <= 0
                or len(parts) != 2
                or any(part in ("", ".", "..") or any(c not in safe_characters for c in part)
                       for part in parts)):
            raise ValueError("Repository search requires a positive ID and safe owner/repository name")
        base = f"{CODE_QUERY} repo:{full_name}"
        def enqueue_scope():
            self.db.execute("""
                INSERT INTO repository_code_scopes(repo_id, full_name, query_base)
                VALUES (?, ?, ?)
                ON CONFLICT(repo_id, query_base) DO UPDATE SET full_name = excluded.full_name
            """, (repo_id, full_name, base))
            self._enqueue("repository_code", self._code_query(0, CODE_MAX_BYTES, base),
                          0, CODE_MAX_BYTES)
        self._write(enqueue_scope)
        return self._run("repository_code", query_base=base)

    def summary(self, kind: str | None = None, query_base: str | None = None) -> dict:
        """Return compact status; exact unresolved queries remain in SQLite."""
        where, args = (" WHERE kind = ?", (kind,)) if kind else ("", ())
        if query_base is not None:
            prefix = query_base + " size:"
            where += (" AND " if where else " WHERE ") + "substr(query, 1, ?) = ?"
            args += (len(prefix), prefix)
        states = {row[0]: row[1] for row in self.db.execute(
            "SELECT state, COUNT(*) FROM discovery_jobs" + where + " GROUP BY state", args
        )}
        result = {"states": states, "repositories": self.db.execute(
            "SELECT COUNT(*) FROM discovered_repositories"
        ).fetchone()[0]}
        if query_base is not None:
            result.update(query_base=query_base,
                          has_pending=any(states.get(state, 0)
                                          for state in ("pending", "running", "error")),
                          has_gaps=any(states.get(state, 0)
                                      for state in ("incomplete", "error")))
        return result

    @staticmethod
    def _code_query(lo: int, hi: int, base: str = CODE_QUERY) -> str:
        return f"{base} size:{lo}..{hi}"

    @staticmethod
    def _timestamp(value: int) -> str:
        return datetime.fromtimestamp(value, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    @classmethod
    def _repository_query(cls, base: str, lo: int, hi: int) -> str:
        return f"{base} created:{cls._timestamp(lo)}..{cls._timestamp(hi)}"

    def _enqueue(self, kind: str, query: str, lo: int, hi: int) -> None:
        self.db.execute("""
            INSERT OR IGNORE INTO discovery_jobs(kind, query, lo, hi)
            VALUES (?, ?, ?, ?)
        """, (kind, query, lo, hi))

    def _run(self, kind: str, query_base: str | None = None) -> dict:
        # An exception leaves an error checkpoint; retry it on an explicit resume.
        # Scoped searches must not replay another repository's failed queries.
        # Match the literal base plus size separator; LIKE would treat valid
        # repository underscores as wildcards and a raw prefix could match a
        # different repository whose name starts with the requested name.
        condition = "kind = ?"
        args: tuple = (kind,)
        if query_base is not None:
            prefix = query_base + " size:"
            condition += " AND substr(query, 1, ?) = ?"
            args += (len(prefix), prefix)
        self._write(lambda: self.db.execute("""
                UPDATE discovery_jobs SET state = 'pending', error = NULL
                WHERE """ + condition + " AND state IN ('running', 'error')", args))
        while True:
            row = self.db.execute(
                "SELECT " + ", ".join(JOB_COLUMNS) +
                " FROM discovery_jobs WHERE " + condition + " AND state = 'pending' ORDER BY rowid LIMIT 1",
                args,
            ).fetchone()
            if row is None:
                break
            job = dict(zip(JOB_COLUMNS, row))
            self._page(job)
        return self.summary(kind, query_base=query_base)

    @staticmethod
    def _empty_incomplete(result: dict) -> bool:
        # Inspect the current raw response, not an earlier page's retained total.
        # Zero hits with an incomplete flag is a timeout, not evidence that
        # narrowing the range will recover hits. Splitting it grows an empty tree.
        return (bool(result.get("incomplete_results"))
                and int(result.get("total_count", 0)) == 0
                and not result["items"])

    def _response(self, job: dict) -> dict:
        path = "/search/code" if job["kind"] in ("code", "repository_code") else "/search/repositories"
        params = {"q": job["query"], "per_page": PER_PAGE, "page": job["page"]}
        # Positive/saturated ranges can be narrowed; all-empty timeout responses
        # must stop after bounded retries rather than create an exponential tree.
        # Every call uses the existing client's limiter/backoff. Keep earlier
        # retry hits separately so final-page pagination still uses the raw page.
        prior_items = []
        prior_total_count = 0
        try:
            for attempt in range(INCOMPLETE_ATTEMPTS):
                result = self.client.get_json(path, params=params)
                if not isinstance(result, dict) or not isinstance(result.get("items"), list):
                    raise ValueError("GitHub search returned an invalid response shape")
                if (not result.get("incomplete_results")
                        or int(result.get("total_count", 0)) > SEARCH_LIMIT
                        or (job["lo"] < job["hi"] and not self._empty_incomplete(result))
                        or attempt + 1 == INCOMPLETE_ATTEMPTS):
                    return dict(result, _prior_items=prior_items,
                                _prior_total_count=prior_total_count)
                prior_items.extend(result["items"])
                prior_total_count = max(prior_total_count, int(result.get("total_count", 0)))
        except Exception as exc:
            self._write(lambda: self.db.execute("""
                    UPDATE discovery_jobs SET state = 'error', error = ?
                    WHERE kind = ? AND query = ?
                """, (f"{type(exc).__name__}: {exc}"[:2000], job["kind"], job["query"])))
            raise

    def _page(self, job: dict) -> None:
        result = self._response(job)
        self._write(lambda: self._save_page(job, result))

    def _save_page(self, job: dict, result: dict) -> None:
        # A later retry may report fewer results after an incomplete response.
        # Retain the largest observed total so a short final page cannot silently
        # erase a coverage gap; a sufficiently complete retry can still recover.
        total = max(int(result.get("total_count", 0)),
                    int(result.get("_prior_total_count", 0)), job["total_count"] or 0)
        incomplete = bool(result.get("incomplete_results")) or bool(job["incomplete"])
        saturated = total > SEARCH_LIMIT
        items = result["items"]
        for item in result.get("_prior_items", []) + items:
            if not isinstance(item, dict):
                continue
            code_search = job["kind"] in ("code", "repository_code")
            if code_search and not self._is_design_path(item.get("path")):
                # Legacy filename search also returns substring/token
                # matches. They must not seed expensive repository work.
                continue
            repo = item.get("repository", {}) if code_search else item
            source = f"{job['kind']}:{job['query']}"
            self._remember_repository(repo, source)
            if code_search:
                self._remember_file(repo, item, source)

        if self._empty_incomplete(result):
            state = "incomplete"
            error = "empty_incomplete_results_after_3_attempts"
        elif (saturated or incomplete) and job["lo"] < job["hi"]:
            mid = (job["lo"] + job["hi"]) // 2
            for lo, hi in ((job["lo"], mid), (mid + 1, job["hi"])):
                if job["kind"] in ("code", "repository_code"):
                    base = job["query"].rsplit(" size:", 1)[0]
                    query = self._code_query(lo, hi, base)
                else:
                    base = job["query"].rsplit(" created:", 1)[0]
                    query = self._repository_query(base, lo, hi)
                self._enqueue(job["kind"], query, lo, hi)
            state = "split"
            error = "result_limit" if saturated else "incomplete_results"
        else:
            max_pages = max(1, math.ceil(min(total, SEARCH_LIMIT) / PER_PAGE))
            expected = min(PER_PAGE, max(0, min(total, SEARCH_LIMIT) - (job["page"] - 1) * PER_PAGE))
            short_page = len(items) < expected
            incomplete = incomplete or saturated or short_page
            if job["page"] < max_pages:
                state = "pending"
            else:
                state = "incomplete" if incomplete else "complete"
            error = job["error"]
            if saturated:
                error = "unsplittable_result_limit"
            elif result.get("incomplete_results"):
                error = "unsplittable_incomplete_results_after_3_attempts"
            elif short_page:
                error = "fewer_items_than_reported_total"
        self.db.execute("""
            UPDATE discovery_jobs
            SET page = ?, state = ?, total_count = ?, incomplete = ?, error = ?
            WHERE kind = ? AND query = ?
        """, (job["page"] + 1, state, total, int(incomplete or saturated),
              error, job["kind"], job["query"]))

    def _remember_repository(self, repo: dict, source: str) -> None:
        # Public must be explicit: a token may also expose private repositories.
        if not isinstance(repo, dict) or repo.get("private") is not False:
            return
        repo_id, full_name = repo.get("id"), repo.get("full_name")
        if not isinstance(repo_id, int) or not isinstance(full_name, str) or full_name.count("/") != 1:
            return
        if repo.get("fork") is True:
            # Refresh a previously discovered repository's eligibility.
            self.db.execute(
                "UPDATE discovered_repositories SET is_fork = 1 WHERE repo_id = ?",
                (repo_id,),
            )
            return
        is_fork = 0 if repo.get("fork") is False else None
        row = self.db.execute(
            "SELECT discovery_sources FROM discovered_repositories WHERE repo_id = ?", (repo_id,)
        ).fetchone()
        sources = json.loads(row[0]) if row else []
        if source not in sources:
            sources.append(source)
        self.db.execute("""
            INSERT INTO discovered_repositories(repo_id, full_name, discovery_sources, is_fork)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(repo_id) DO UPDATE SET
                full_name = excluded.full_name,
                discovery_sources = excluded.discovery_sources,
                is_fork = COALESCE(excluded.is_fork, discovered_repositories.is_fork)
        """, (repo_id, full_name, json.dumps(sources, ensure_ascii=False), is_fork))

    @staticmethod
    def _is_design_path(path) -> bool:
        """Accept only safe Git-relative paths with the exact target basename."""
        if not isinstance(path, str) or not path or "\x00" in path:
            return False
        parts = path.split("/")
        return (all(part not in ("", ".", "..") for part in parts)
                and parts[-1].casefold() == "design.md")

    def _remember_file(self, repo: dict, item: dict, source: str) -> None:
        """Persist searchable file identity in the same transaction as its page."""
        if (not isinstance(repo, dict) or repo.get("private") is not False
                or repo.get("fork") is True):
            return
        repo_id = repo.get("id")
        if not isinstance(repo_id, int) or isinstance(repo_id, bool):
            return
        known = self.db.execute(
            "SELECT is_fork FROM discovered_repositories WHERE repo_id = ?", (repo_id,)
        ).fetchone()
        if known is None or known[0] == 1:
            return
        path, sha = item.get("path"), item.get("sha")
        if not self._is_design_path(path):
            return
        if (not isinstance(sha, str) or len(sha) not in (40, 64)
                or any(c not in "0123456789abcdefABCDEF" for c in sha)):
            return
        sha = sha.lower()
        row = self.db.execute("""
            SELECT discovery_sources FROM discovered_files WHERE repo_id = ? AND path = ?
        """, (repo_id, path)).fetchone()
        sources = json.loads(row[0]) if row else []
        if source not in sources:
            sources.append(source)
        observed_at = datetime.now(timezone.utc).isoformat()
        self.db.execute("""
            INSERT INTO discovered_files
                (repo_id, path, search_blob_sha, discovery_sources, first_seen_at, last_seen_at)
            VALUES (?, ?, ?, ?, ?, ?)
            ON CONFLICT(repo_id, path) DO UPDATE SET
                search_blob_sha = excluded.search_blob_sha,
                discovery_sources = excluded.discovery_sources,
                last_seen_at = excluded.last_seen_at,
                revision = discovered_files.revision +
                    CASE WHEN discovered_files.search_blob_sha != excluded.search_blob_sha
                         THEN 1 ELSE 0 END
        """, (repo_id, path, sha, json.dumps(sources, ensure_ascii=False), observed_at, observed_at))


# Pinned snapshots, original bytes and verification

FORMAT_VERSION = 2


def _now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def _error(exc):
    message = re.sub(r"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+", "[REDACTED]", str(exc))
    return {"type": type(exc).__name__, "message": message[:1000]}


def _safe_parts(value):
    if not isinstance(value, str) or not value or "\x00" in value:
        raise ValueError("Invalid empty or NUL-containing repository path")
    parts = value.split("/")
    if any(part in ("", ".", "..") for part in parts):
        raise ValueError("Unsafe repository-relative path")
    return parts


def _safe_full_name(full_name):
    parts = _safe_parts(full_name)
    if len(parts) != 2:
        raise ValueError("Expected owner/repository name")
    return parts


def _checked_path(base, parts, create_parents=False):
    """Reject symlinks below the configured base, including the final path."""
    base = Path(base)
    if base.is_symlink():
        raise ValueError("Storage base must not be a symbolic link")
    if create_parents:
        base.mkdir(parents=True, exist_ok=True)
    current = base
    for index, part in enumerate(parts):
        current = current / part
        if current.is_symlink():
            raise ValueError("Refusing symbolic link in storage path")
        if create_parents and index < len(parts) - 1:
            current.mkdir(exist_ok=True)
        if index < len(parts) - 1 and current.exists() and not current.is_dir():
            raise ValueError("Non-directory ancestor in storage path")
    return current


def _atomic_bytes(path, content):
    path = Path(path)
    if path.is_symlink():
        raise ValueError("Refusing to replace a symbolic link")
    descriptor, temporary = tempfile.mkstemp(prefix=".designmd-", dir=path.parent)
    try:
        with os.fdopen(descriptor, "wb") as handle:
            handle.write(content)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def _json_bytes(value):
    return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")


def _write_json(path, value):
    _atomic_bytes(path, _json_bytes(value))


def _read_json(path):
    with Path(path).open("r", encoding="utf-8") as handle:
        return json.load(handle)


def _git_blob_sha(content):
    return hashlib.sha1(b"blob " + str(len(content)).encode("ascii") + b"\0" + content).hexdigest()


def _sha256(content):
    return hashlib.sha256(content).hexdigest()


class SnapshotCollector:
    """Collect current default-branch snapshots with a stable resume boundary."""

    def __init__(self, client, root: Path):
        self.client = client
        self.root = Path(root)
        self.metadata_root = self.root / "_metadata"
        self.data_root = self.root / "data"

    def _metadata_file(self, storage_name, name):
        return _checked_path(self.metadata_root, _safe_full_name(storage_name) + [name], True)

    def _index_file(self, repo_id):
        return _checked_path(self.metadata_root, ["_index", str(int(repo_id)) + ".json"], True)

    def _read_records(self, storage_name):
        path = self._metadata_file(storage_name, "files.jsonl")
        records = {}
        if path.exists():
            with path.open("r", encoding="utf-8") as handle:
                for line in handle:
                    if line.strip():
                        record = json.loads(line)
                        if record["path"] in records:
                            raise ValueError("Duplicate path in files.jsonl")
                        records[record["path"]] = record
        return records

    def _write_records(self, storage_name, records):
        content = "".join(json.dumps(records[path], ensure_ascii=False, sort_keys=True) + "\n"
                          for path in sorted(records))
        _atomic_bytes(self._metadata_file(storage_name, "files.jsonl"), content.encode("utf-8"))

    def _save_snapshot(self, snapshot):
        snapshot["updated_at"] = _now()
        _write_json(self._metadata_file(snapshot["storage_full_name"], "snapshot.json"), snapshot)

    def _checkpoint(self, snapshot, records):
        """Publish resolved identities before file records, on every exit path."""
        if records is not None:
            snapshot.update(self._counts(records))
        self._save_snapshot(snapshot)
        if records is not None:
            self._write_records(snapshot["storage_full_name"], records)

    def exclude_fork(self, repo_id):
        """Mark saved files as excluded history without moving or deleting them."""
        index_path = self.metadata_root / "_index" / (str(int(repo_id)) + ".json")
        if not index_path.exists():
            return
        index = _read_json(index_path)
        if index.get("repo_id") != repo_id:
            raise ValueError("Repository index identity mismatch")
        path = _checked_path(self.metadata_root, _safe_full_name(index["storage_full_name"]) + ["snapshot.json"])
        if path.exists():
            snapshot = _read_json(path)
            if snapshot.get("repo_id") != repo_id:
                raise ValueError("Snapshot repository identity mismatch")
            if snapshot.get("format_version") != FORMAT_VERSION:
                raise ValueError("Older checkpoint format is unsupported; use a new collection root")
            if snapshot["status"] == "excluded_fork":
                return
            snapshot.update(status="excluded_fork", fork=True, excluded_reason="fork_repository")
            self._save_snapshot(snapshot)

    def collect(self, repo_id: int, full_name: str, candidate_paths):
        """Fetch discovered paths at a pinned commit without scanning Git trees.

        Candidates may be path strings or dictionaries containing path and
        search_blob_sha. An empty list only rechecks previously saved paths.
        Existing checkpoints are merged, not replaced, when new paths arrive.
        """
        snapshot = None
        records = None
        try:
            repo_id = int(repo_id)
            _safe_full_name(full_name)
            index_path = self._index_file(repo_id)
            if index_path.exists():
                index = _read_json(index_path)
                if index.get("repo_id") != repo_id:
                    raise ValueError("Repository index identity mismatch")
                storage_name = index["storage_full_name"]
                snapshot_path = self._metadata_file(storage_name, "snapshot.json")
                if snapshot_path.exists():
                    saved = _read_json(snapshot_path)
                    if saved.get("format_version") != FORMAT_VERSION:
                        raise ValueError("Older checkpoint format is unsupported; use a new collection root")
                    snapshot = saved
                    if snapshot.get("repo_id") != repo_id:
                        raise ValueError("Snapshot repository identity mismatch")
                    if snapshot["status"] == "excluded_fork":
                        return self._summary(snapshot)
                    records = self._read_records(storage_name)
            repository = self.client.get_json(f"/repositories/{repo_id}")
            if repository.get("id") != repo_id:
                raise ValueError("GitHub returned a different repository identity")
            canonical_name = repository["full_name"]
            _safe_full_name(canonical_name)
            public = repository.get("private") is False and repository.get("visibility", "public") == "public"
            if public and repository.get("fork") is not False:
                if repository.get("fork") is True:
                    self.exclude_fork(repo_id)
                    return {"status": "excluded_fork", "repo_id": repo_id, "full_name": canonical_name,
                            "files_saved": 0, "files_failed": 0, "candidates": 0, "excluded_reason": "fork_repository"}
                raise ValueError("Repository metadata must explicitly report fork=false before downloading content")
            if snapshot is None:
                storage_name = index["storage_full_name"] if index_path.exists() else canonical_name
                snapshot = {
                    "format_version": FORMAT_VERSION,
                    "repo_id": repo_id,
                    "storage_full_name": storage_name,
                    "canonical_full_name": canonical_name,
                    "full_name": canonical_name,
                    "requested_full_names": [full_name],
                    "observed_full_names": [canonical_name],
                    "created_at": _now(),
                    "status": "pending",
                    "history_collected": False,
                    "content_filter": "none",
                    "tree_complete": False,
                    "candidates": [],
                }
                self._save_snapshot(snapshot)
                _write_json(index_path, {"repo_id": repo_id, "storage_full_name": storage_name})
                records = self._read_records(storage_name)
            else:
                if full_name not in snapshot["requested_full_names"]:
                    snapshot["requested_full_names"].append(full_name)
                if canonical_name not in snapshot["observed_full_names"]:
                    snapshot["observed_full_names"].append(canonical_name)
                snapshot["canonical_full_name"] = canonical_name
                snapshot["full_name"] = canonical_name
            snapshot["repository_metadata_fetched_at"] = _now()
            snapshot["public"] = public
            if not snapshot["public"]:
                # A token can grant more access than the corpus intends. Never
                # fetch any Git objects from a non-public repository.
                audit = {key: repository[key] for key in ("id", "full_name", "private", "visibility") if key in repository}
                audit.update({"public": False, "excluded_reason": "non_public"})
                _write_json(self._metadata_file(snapshot["storage_full_name"], "repository.json"), audit)
                snapshot["excluded_reason"] = "non_public"
                snapshot["status"] = "complete"
                self._save_snapshot(snapshot)
                summary = self._summary(snapshot)
                summary.update({"public": False, "excluded_reason": "non_public"})
                return summary
            snapshot["fork"] = False
            snapshot.pop("excluded_reason", None)
            _write_json(self._metadata_file(snapshot["storage_full_name"], "repository.json"), repository)
            endpoint = "/repos/" + "/".join(quote(part, safe="") for part in canonical_name.split("/"))
            languages_path = self._metadata_file(snapshot["storage_full_name"], "languages.json")
            if not languages_path.exists():
                try:
                    languages = self.client.get_json(endpoint + "/languages")
                    _write_json(languages_path, languages)
                    snapshot["languages_fetched_at"] = _now()
                    snapshot.pop("languages_error", None)
                except Exception as exc:
                    snapshot["languages_error"] = _error(exc)
            if not snapshot.get("commit_sha"):
                branch = repository.get("default_branch")
                if not branch:
                    raise ValueError("Repository has no default branch")
                reference = self.client.get_json(endpoint + "/git/ref/heads/" + quote(branch, safe=""))
                snapshot["default_branch"] = branch
                snapshot["commit_sha"] = reference["object"]["sha"]
                snapshot["pinned_at"] = _now()
                self._save_snapshot(snapshot)
            if records is None:
                records = self._read_records(snapshot["storage_full_name"])
            snapshot["status"] = "partial"
            snapshot.pop("completed_at", None)
            snapshot["candidates"] = self._merge_direct_candidates(snapshot, candidate_paths)
            snapshot["inventory_source"] = "code_search_paths"
            snapshot["repository_inventory_complete"] = False
            snapshot["tree_complete"] = False
            self._save_snapshot(snapshot)
            for entry in snapshot["candidates"]:
                path = entry["path"]
                previous = records.get(path)
                try:
                    record = self._collect_direct_file(endpoint, snapshot, entry, previous)
                except Exception as exc:
                    record = dict(previous or {})
                    record.update({"path": path, "status": "failed", "repo_id": repo_id,
                                   "commit_sha": snapshot["commit_sha"], "blob_sha": entry.get("sha"),
                                   "error": _error(exc), "attempted_at": _now()})
                    record["search_blob_shas"] = entry.get("search_blob_shas", [])
                records[path] = record
                self._checkpoint(snapshot, records)
            expected_paths = {entry["path"] for entry in snapshot["candidates"]}
            if set(records) - expected_paths:
                raise ValueError("Metadata contains paths absent from the pinned snapshot")
            counts = self._counts(records)
            snapshot.update(counts)
            final_status = "partial" if counts["files_failed"] or snapshot.get("languages_error") else "complete"
            snapshot.pop("error", None)
            # Publish completion only after both the candidate identities and
            # final records are durable. A crash between those two writes can
            # leave adopted bytes, but must never leave a false complete flag.
            snapshot["status"] = "partial"
            self._checkpoint(snapshot, records)
            snapshot["status"] = final_status
            if final_status == "complete":
                snapshot["completed_at"] = _now()
            self._save_snapshot(snapshot)
            return self._summary(snapshot)
        except (Exception, KeyboardInterrupt) as exc:
            if snapshot is not None:
                snapshot["status"] = "partial" if isinstance(exc, KeyboardInterrupt) else "failed"
                snapshot["error"] = _error(exc)
                try:
                    self._checkpoint(snapshot, records)
                except Exception:
                    pass
                if isinstance(exc, KeyboardInterrupt):
                    raise
                return self._summary(snapshot)
            if isinstance(exc, KeyboardInterrupt):
                raise
            return {"status": "failed", "repo_id": repo_id, "full_name": full_name,
                    "files_saved": 0, "files_failed": 0, "candidates": 0, "error": _error(exc)}

    @staticmethod
    def _merge_direct_candidates(snapshot, candidate_paths):
        if not isinstance(candidate_paths, (list, tuple)):
            raise TypeError("candidate_paths must be a list of paths or path dictionaries")
        merged = {item["path"]: dict(item) for item in snapshot["candidates"]}
        for value in candidate_paths:
            item = {"path": value} if isinstance(value, str) else value
            if not isinstance(item, dict) or not isinstance(item.get("path"), str):
                raise ValueError("Each candidate must contain a string path")
            path = item["path"]
            if path.split("/")[-1].casefold() != "design.md":
                continue
            entry = merged.setdefault(path, {"path": path})
            hashes = set(entry.get("search_blob_shas", []))
            search_sha = item.get("search_blob_sha", item.get("sha"))
            if search_sha is not None:
                if not isinstance(search_sha, str):
                    raise ValueError("search_blob_sha must be a string")
                hashes.add(search_sha)
            entry["search_blob_shas"] = sorted(hashes)
        return sorted(merged.values(), key=lambda item: item["path"])

    def _collect_direct_file(self, endpoint, snapshot, entry, previous):
        path = entry["path"]
        parts = _safe_parts(path)
        if parts[-1].casefold() != "design.md":
            raise ValueError("Candidate basename must be design.md")
        if previous and previous.get("commit_sha") != snapshot["commit_sha"]:
            raise ValueError("File metadata belongs to a different snapshot")
        target = _checked_path(self.data_root, _safe_full_name(snapshot["storage_full_name"]) + parts, True)
        if previous and previous.get("status") == "excluded":
            record = dict(previous)
            record["search_blob_shas"] = entry.get("search_blob_shas", [])
            return record
        if entry.get("sha") and target.exists():
            return self._collect_file(endpoint, snapshot, entry, previous)
        contents_path = endpoint + "/contents/" + quote(path, safe="/")
        try:
            response = self.client.get_json(contents_path, {"ref": snapshot["commit_sha"]})
        except Exception as exc:
            if getattr(exc, "status", getattr(exc, "code", None)) != 404:
                raise
            entry["resolution"] = "missing_at_pinned_commit"
            return self._direct_excluded(snapshot, entry, "missing_at_pinned_commit")
        if isinstance(response, list):
            entry["resolution"] = "not_file_at_pinned_commit"
            return self._direct_excluded(snapshot, entry, "not_file_at_pinned_commit")
        if not isinstance(response, dict) or response.get("path") != path:
            raise ValueError("Contents API returned a different repository path")
        if response.get("type") not in ("file", "symlink") or response.get("submodule_git_url"):
            entry["resolution"] = "not_file_at_pinned_commit"
            return self._direct_excluded(snapshot, entry, "not_file_at_pinned_commit")
        sha = response.get("sha")
        size = response.get("size")
        if not isinstance(sha, str) or not re.fullmatch(r"[a-fA-F0-9]{40}", sha):
            raise ValueError("Contents API returned an invalid Git blob SHA")
        if not isinstance(size, int) or isinstance(size, bool) or size < 0:
            raise ValueError("Contents API returned an invalid blob size")
        entry.update({"sha": sha.lower(), "size": size, "type": "blob",
                      "mode": "120000" if response["type"] == "symlink" else None,
                      "contents_type": response["type"], "resolution": "resolved_at_pinned_commit",
                      "contents_api_url": "https://api.github.com" + contents_path + "?ref=" + snapshot["commit_sha"]})
        # Contents API may follow an in-repository symlink and does not expose
        # ordinary Git modes. Record that uncertainty; never create a symlink.
        prefetched = response if response.get("encoding") == "base64" and response["type"] == "file" else None
        return self._collect_file(endpoint, snapshot, entry, previous, prefetched_blob=prefetched)

    @staticmethod
    def _direct_excluded(snapshot, entry, reason):
        return {"repo_id": snapshot["repo_id"], "full_name": snapshot["canonical_full_name"],
                "storage_full_name": snapshot["storage_full_name"], "path": entry["path"],
                "commit_sha": snapshot["commit_sha"], "status": "excluded", "reason": reason,
                "checked_at": _now(), "search_blob_shas": entry.get("search_blob_shas", [])}

    def _collect_file(self, endpoint, snapshot, entry, previous, prefetched_blob=None):
        path = entry["path"]
        base = {
            "repo_id": snapshot["repo_id"],
            "full_name": snapshot["canonical_full_name"],
            "storage_full_name": snapshot["storage_full_name"],
            "path": path,
            "commit_sha": snapshot["commit_sha"],
            "blob_sha": entry.get("sha"),
            "git_mode": entry.get("mode"),
            "git_type": entry.get("type"),
            "is_symlink": entry.get("mode") == "120000" if entry.get("mode") is not None else None,
            "expected_size": entry.get("size"),
            "content_filter": "none",
        }
        base.update({"contents_type": entry["contents_type"], "contents_api_url": entry["contents_api_url"],
                     "git_mode_known": entry["mode"] is not None,
                     "search_blob_shas": entry.get("search_blob_shas", [])})
        parts = _safe_parts(path)
        target = _checked_path(self.data_root, _safe_full_name(snapshot["storage_full_name"]) + parts, True)
        if previous and previous.get("commit_sha") != snapshot["commit_sha"]:
            raise ValueError("File metadata belongs to a different snapshot")
        if target.exists():
            content = target.read_bytes()
            if _git_blob_sha(content) != entry["sha"]:
                raise ValueError("Existing file differs from the pinned Git blob; refusing overwrite")
            if previous and previous.get("sha256") and _sha256(content) != previous["sha256"]:
                raise ValueError("Existing file differs from its recorded SHA-256; refusing overwrite")
            fetched_at = previous.get("fetched_at", _now()) if previous else _now()
            adopted_existing = not previous
            content_source = previous.get("content_source", "github_git_blob_api") if previous else "existing_verified_bytes"
            source_api_url = previous.get("source_api_url") if previous else None
        else:
            response = prefetched_blob if prefetched_blob is not None else self.client.get_json(endpoint + "/git/blobs/" + entry["sha"])
            if response.get("encoding") != "base64":
                raise ValueError("GitHub blob endpoint did not return base64 content")
            content = base64.b64decode(re.sub(r"\s+", "", response["content"]), validate=True)
            if response.get("sha", entry["sha"]) != entry["sha"]:
                raise ValueError("GitHub blob response SHA does not match requested object")
            if response.get("size", len(content)) != len(content):
                raise ValueError("GitHub blob response size mismatch")
            if _git_blob_sha(content) != entry["sha"]:
                raise ValueError("Downloaded bytes do not match the Git blob SHA")
            if entry.get("size", len(content)) != len(content):
                raise ValueError("Downloaded bytes do not match the recorded blob size")
            content_source = "github_contents_api" if prefetched_blob is not None else "github_git_blob_api"
            _atomic_bytes(target, content)
            fetched_at = _now()
            adopted_existing = False
            source_api_url = entry["contents_api_url"] if prefetched_blob is not None else "https://api.github.com" + endpoint + "/git/blobs/" + entry["sha"]
        if entry.get("size", len(content)) != len(content):
            raise ValueError("Existing bytes do not match the recorded blob size")
        relative_path = "/".join(_safe_full_name(snapshot["storage_full_name"]) + parts)
        return dict(base, status="downloaded", size=len(content), sha256=_sha256(content),
                    data_path="data/" + relative_path, fetched_at=fetched_at, verified_at=_now(),
                    adopted_existing=adopted_existing,
                    content_source=content_source,
                    source_url="https://github.com/" + quote(snapshot["canonical_full_name"], safe="/")
                    + "/blob/" + snapshot["commit_sha"] + "/" + quote(path, safe="/"),
                    source_api_url=source_api_url)

    @staticmethod
    def _counts(records):
        return {
            "files_saved": sum(item["status"] == "downloaded" for item in records.values()),
            "files_failed": sum(item["status"] == "failed" for item in records.values()),
            "files_excluded": sum(item["status"] == "excluded" for item in records.values()),
            "bytes_saved": sum(item.get("size", 0) for item in records.values() if item["status"] == "downloaded"),
        }

    def _summary(self, snapshot):
        summary = {key: snapshot[key] for key in ("status", "repo_id", "files_saved", "files_failed",
                   "files_excluded", "bytes_saved", "commit_sha", "public", "fork", "excluded_reason",
                   "error", "languages_error") if key in snapshot}
        summary.setdefault("files_saved", 0)
        summary.setdefault("files_failed", 0)
        summary["full_name"] = snapshot["canonical_full_name"]
        summary["candidates"] = len(snapshot["candidates"])
        summary["metadata_directory"] = str(self.metadata_root / snapshot["storage_full_name"])
        if snapshot["status"] == "excluded_fork":
            summary.update(files_saved=0, files_failed=0, files_excluded=0, bytes_saved=0, candidates=0)
        return summary

    def verify(self):
        """Verify saved bytes and snapshot consistency without network requests."""
        result = {"repositories": 0, "files": 0, "bytes": 0, "skipped_excluded_snapshots": 0, "problems": []}
        if not self.metadata_root.exists():
            result["ok"] = True
            return result
        for snapshot_path in sorted(self.metadata_root.glob("*/*/snapshot.json")):
            try:
                snapshot = _read_json(snapshot_path)
                if snapshot.get("format_version") != FORMAT_VERSION:
                    raise ValueError("Older checkpoint format is unsupported; use a new collection root")
                storage_name = snapshot["storage_full_name"]
                expected_metadata = _checked_path(self.metadata_root, _safe_full_name(storage_name) + ["snapshot.json"])
                if expected_metadata != snapshot_path:
                    raise ValueError("Snapshot location does not match its storage name")
                if snapshot["status"] == "excluded_fork":
                    result["skipped_excluded_snapshots"] += 1
                    continue
                result["repositories"] += 1
                records = self._read_records(storage_name)
                if snapshot["status"] != "complete":
                    result["problems"].append({"repository": storage_name, "reason": "snapshot_" + snapshot["status"]})
                expected = {item["path"]: item for item in snapshot["candidates"]}
                if set(expected) != set(records):
                    result["problems"].append({"repository": storage_name, "reason": "inventory_metadata_mismatch"})
                for path, record in records.items():
                    if record["status"] != "downloaded":
                        continue
                    try:
                        target = _checked_path(self.data_root, _safe_full_name(storage_name) + _safe_parts(path))
                        content = target.read_bytes()
                        if record["commit_sha"] != snapshot["commit_sha"]:
                            raise ValueError("File snapshot commit mismatch")
                        if record["blob_sha"] != expected[path]["sha"]:
                            raise ValueError("File snapshot blob mismatch")
                        if len(content) != record["size"]:
                            raise ValueError("File size mismatch")
                        if _sha256(content) != record["sha256"]:
                            raise ValueError("File SHA-256 mismatch")
                        if _git_blob_sha(content) != record["blob_sha"]:
                            raise ValueError("File Git blob SHA mismatch")
                        result["files"] += 1
                        result["bytes"] += len(content)
                    except Exception as exc:
                        result["problems"].append({"repository": storage_name, "path": path, "error": _error(exc)})
            except Exception as exc:
                result["problems"].append({"snapshot": str(snapshot_path), "error": _error(exc)})
        result["ok"] = not result["problems"]
        return result


# Two-phase collection and checkpoints

def utc_now():
    return datetime.now(timezone.utc).isoformat()


def atomic_json(path: Path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    _write_json(path, value)

def control_directory(root: Path):
    return root / "_metadata" / "_collector"


def check_root(root: Path):
    """Reject incompatible collections before creating or modifying anything."""
    database = control_directory(root) / "state.sqlite3"
    if database.exists():
        db = sqlite3.connect(database.resolve().as_uri() + "?mode=ro&immutable=1", uri=True)
        try:
            version = db.execute("PRAGMA user_version").fetchone()[0]
        finally:
            db.close()
        if version != 2:
            raise ValueError("Older checkpoint format is unsupported; use a new collection root")
        manifest = control_directory(root) / "manifest.json"
        if manifest.exists() and json.loads(manifest.read_text())["schema_version"] != 2:
            raise ValueError("Older collection manifest is unsupported; use a new collection root")
    elif root.exists() and any(root.iterdir()):
        raise ValueError("Collection root must be empty or contain a current-format checkpoint")


def open_database(root: Path):
    check_root(root)
    control = control_directory(root)
    control.mkdir(parents=True, exist_ok=True)
    db = sqlite3.connect(control / "state.sqlite3")
    db.execute("""CREATE TABLE IF NOT EXISTS collection_tasks (
        repo_id INTEGER PRIMARY KEY, full_name TEXT NOT NULL,
        state TEXT NOT NULL DEFAULT 'pending',
        files_saved INTEGER NOT NULL DEFAULT 0, candidates INTEGER NOT NULL DEFAULT 0,
        files_failed INTEGER NOT NULL DEFAULT 0, error TEXT, updated_at TEXT,
        metadata_directory TEXT, processed_file_revision INTEGER NOT NULL DEFAULT 0)""")
    db.execute("PRAGMA user_version=2")
    db.commit()
    # Store the format marker in the database header before enabling WAL.
    # check_root can then inspect it without creating SQLite sidecar files.
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("PRAGMA synchronous=FULL")
    return db


class CollectorRunner:
    def __init__(self, root: Path, client: GitHubClient, *, max_repositories=None):
        self.root = root
        self.client = client
        self.max_repositories = max_repositories
        self.processed = 0
        self.phase = "initializing"
        self.started_at = utc_now()
        self.db = open_database(root)
        self.discovery = Discovery(client, self.db)
        self.snapshots = SnapshotCollector(client, root)

    def add_repository(self, repo, source):
        with self.db:
            self.discovery._remember_repository(repo, source)

    def _queue_discovered(self):
        self.db.execute("""UPDATE discovered_repositories SET is_fork=1 WHERE repo_id IN
            (SELECT repo_id FROM collection_tasks WHERE state IN ('excluded_fork','excluding_fork'))""")
        self.db.execute("""INSERT OR IGNORE INTO collection_tasks(repo_id, full_name)
            SELECT repo_id, full_name FROM discovered_repositories WHERE is_fork IS NULL OR is_fork=0""")
        self.db.execute("""UPDATE collection_tasks SET state='pending',error=NULL
            WHERE (state IN ('running','failed','partial') OR
                COALESCE((SELECT SUM(revision) FROM discovered_files f
                    WHERE f.repo_id=collection_tasks.repo_id),0)>processed_file_revision)
            AND state NOT IN ('excluded_fork','excluding_fork')
            AND EXISTS (SELECT 1 FROM discovered_files f WHERE f.repo_id=collection_tasks.repo_id)
            AND repo_id IN (SELECT repo_id FROM discovered_repositories WHERE is_fork IS NULL OR is_fork=0)""")
        self.db.commit()
        forks = self.db.execute("""SELECT repo_id FROM collection_tasks
            WHERE state IN ('excluded_fork','excluding_fork') OR repo_id IN
                (SELECT repo_id FROM discovered_repositories WHERE is_fork=1)""").fetchall()
        for (repo_id,) in forks:
            self.snapshots.exclude_fork(repo_id)
            with self.db:
                self.db.execute("""UPDATE collection_tasks SET state='excluded_fork',
                    files_saved=0,candidates=0,files_failed=0,error='fork_repository' WHERE repo_id=?""",
                    (repo_id,))

    def discover(self):
        """Finish all discovery before downloading any repository files."""
        self.phase = "discovery"
        self.write_status("running")
        seed = self.client.get_json("/repos/google-labs-code/design.md")
        self.add_repository(seed, "official-seed")
        self.discovery.run_code_search()
        self.discovery.run_repository_search()

        # Registered scopes may still have unfinished pages even if an earlier
        # run already found files. Also search repositories with no indexed path.
        scopes = set() if seed.get("fork") is True else {(seed["id"], seed["full_name"])}
        scopes.update(self.db.execute("SELECT repo_id,full_name FROM repository_code_scopes"))
        scopes.update(self.db.execute("""SELECT repo_id,full_name FROM discovered_repositories d
            WHERE (is_fork IS NULL OR is_fork=0) AND NOT EXISTS
                (SELECT 1 FROM discovered_files f WHERE f.repo_id=d.repo_id)"""))
        for repo_id, full_name in sorted(scopes):
            excluded = self.db.execute("""SELECT 1 FROM collection_tasks WHERE repo_id=?
                AND state IN ('excluded_fork','excluding_fork') UNION SELECT 1
                FROM discovered_repositories WHERE repo_id=? AND is_fork=1""", (repo_id,repo_id)).fetchone()
            if excluded:
                continue
            try:
                result = self.discovery.run_repository_code_search(repo_id, full_name)
                state = "search_incomplete" if result["has_gaps"] else "no_indexed_files"
            except Exception:
                state = "search_incomplete"
                LOG.exception("File path search failed for %s", full_name)
            has_paths = self.db.execute("SELECT 1 FROM discovered_files WHERE repo_id=? LIMIT 1",
                                        (repo_id,)).fetchone()
            if not has_paths:
                with self.db:
                    self.db.execute("""INSERT INTO collection_tasks(repo_id,full_name,state)
                        VALUES(?,?,?) ON CONFLICT(repo_id) DO UPDATE SET state=excluded.state""",
                        (repo_id, full_name, state))
            self.write_status("running")

    def process_pending(self):
        """Download queued snapshots; return whether a limit left work pending."""
        self._queue_discovered()
        while True:
            row = self.db.execute("""SELECT repo_id, full_name FROM collection_tasks
                WHERE state='pending' AND EXISTS
                    (SELECT 1 FROM discovered_files f WHERE f.repo_id=collection_tasks.repo_id)
                ORDER BY repo_id LIMIT 1""").fetchone()
            if not row:
                return False
            if self.max_repositories is not None and self.processed >= self.max_repositories:
                return True
            repo_id, full_name = row
            entries = self.db.execute("""SELECT path,search_blob_sha,revision FROM discovered_files
                WHERE repo_id=? ORDER BY path""", (repo_id,)).fetchall()
            candidate_paths = [{"path": path, "search_blob_sha": sha} for path, sha, revision in entries]
            inventory_revision = sum(entry[2] for entry in entries)
            self.db.execute("UPDATE collection_tasks SET state='running',updated_at=? WHERE repo_id=?", (utc_now(), repo_id))
            self.db.commit()
            LOG.info("Snapshot %s", full_name)
            try:
                result = self.snapshots.collect(repo_id, full_name, candidate_paths=candidate_paths)
            except Exception as exc:
                result = {"status": "failed", "error": str(exc)}
                LOG.exception("Snapshot failed for %s", full_name)
            status = result.get("status", "failed")
            if status == "excluded_fork":
                self.db.execute("UPDATE discovered_repositories SET is_fork=1 WHERE repo_id=?", (repo_id,))
            if status not in ("complete", "partial", "failed", "skipped", "excluded_fork"):
                status = "failed"
            self.db.execute("""UPDATE collection_tasks SET state=?, files_saved=?, candidates=?,
                files_failed=?, error=?, updated_at=?, metadata_directory=?,processed_file_revision=? WHERE repo_id=?""",
                (status, result.get("files_saved", 0), result.get("candidates", 0),
                 result.get("files_failed", 0), json.dumps(result.get("error") or result.get("languages_error"), ensure_ascii=False) if result.get("error") or result.get("languages_error") else None, utc_now(),
                 str(result.get("metadata_directory", "")), inventory_revision, repo_id))
            self.db.commit()
            self.processed += 1
            LOG.info("Snapshot result %s: %s; files=%s failures=%s", full_name, status,
                     result.get("files_saved", 0), result.get("files_failed", 0))
            self.write_status("running")

    def write_status(self, state, error=None):
        report = database_status(self.db)
        report.update({"state": state, "phase": self.phase, "started_at": self.started_at,
                       "updated_at": utc_now(), "pid": os.getpid(), "requests_this_process": self.client.request_count,
                       "processed_this_process": self.processed, "error": error})
        atomic_json(control_directory(self.root) / "status.json", report)
        return report

    def run(self):
        control = control_directory(self.root)
        with (control / "collector.lock").open("a+") as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                raise RuntimeError("A collector is already running for this destination") from None
            manifest_path = control / "manifest.json"
            if not manifest_path.exists():
                atomic_json(manifest_path, {"schema_version": 2, "created_at": utc_now(),
                    "scope": "public non-fork repositories; pinned current default-branch snapshots",
                    "filename": "basename.casefold() == 'design.md'", "yaml_filter": False,
                    "history": False, "data_layout": "data/<owner>/<repo>/<original-path>",
                    "metadata_layout": "_metadata/<owner>/<repo>/", "fork_repository_policy": "exclude",
                    "collection_method": "code_search_paths_then_contents_at_pinned_commit",
                    "full_repository_tree_scan": False, "repository_inventory_complete": False,
                    "coverage_limits": ["GitHub search is not exhaustive",
                        "Only indexed default-branch paths are searched; no other branches or history",
                        "Saturated or incomplete leaf queries remain recorded as coverage gaps",
                        "Repository snapshots are taken at different times; each pins its own commit"]})
            try:
                self.discover()
                self.phase = "snapshots"
                limited = self.process_pending()
                self.phase = "finished"
                state = "batch_complete" if limited else "complete_with_gaps" if has_gaps(database_status(self.db)) else "complete"
                return self.write_status(state)
            except KeyboardInterrupt:
                return self.write_status("interrupted")
            except BaseException as exc:
                self.write_status("failed", str(exc))
                raise


def database_status(db):
    tables = {row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
    output = {}
    for table, name in (("collection_tasks", "repositories"), ("discovery_jobs", "search_jobs")):
        if table in tables:
            output[name] = dict(db.execute(f"SELECT state,COUNT(*) FROM {table} GROUP BY state"))
    if "collection_tasks" in tables:
        saved, candidates, failures = db.execute("SELECT COALESCE(SUM(files_saved),0),COALESCE(SUM(candidates),0),COALESCE(SUM(files_failed),0) FROM collection_tasks").fetchone()
        output.update(files_saved=saved, candidate_files=candidates, file_failures=failures)
    if "discovered_repositories" in tables:
        output["repositories_discovered"] = db.execute("SELECT COUNT(*) FROM discovered_repositories").fetchone()[0]
    if "discovered_files" in tables:
        output["file_paths_discovered"] = db.execute("SELECT COUNT(*) FROM discovered_files").fetchone()[0]
    return output


def has_gaps(report):
    return any(count for group in ("repositories", "search_jobs")
               for state, count in report.get(group, {}).items() if state not in ("complete", "split", "superseded", "excluded_fork", "no_indexed_files"))


# Command-line interface

def main():
    parser = argparse.ArgumentParser(description="Collect discovered DESIGN.md paths at pinned commits in public, non-fork repositories.")
    parser.add_argument("command", choices=("run", "resume", "status", "verify"))
    parser.add_argument("--root", type=Path, required=True,
                        help="Empty directory or version-2 collection; legacy checkpoint formats require a new root")
    parser.add_argument("--token-file", type=Path, help="GitHub token file; required for run and resume")
    parser.add_argument("--max-repositories", type=int, help="Limit repository downloads after discovery completes; remaining downloads can resume")
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stderr)
    if args.command in ("run", "resume") and args.token_file is None:
        parser.error("--token-file is required for " + args.command)
    if args.max_repositories is not None and args.max_repositories < 1:
        parser.error("--max-repositories must be positive")
    if args.command == "status":
        database = control_directory(args.root) / "state.sqlite3"
        if not database.exists():
            print(json.dumps({"state": "not_started"}))
            return 0
        with closing(sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True)) as db:
            output = database_status(db)
        status_path = control_directory(args.root) / "status.json"
        if status_path.exists():
            output["last_process_report"] = json.loads(status_path.read_text())
        print(json.dumps(output, indent=2))
        return 0
    if args.command == "verify":
        result = SnapshotCollector(None, args.root).verify()
        print(json.dumps(result, indent=2))
        return 1 if result.get("problems") else 0
    check_root(args.root)
    client = GitHubClient(args.token_file)
    def interrupted(signum, frame):
        raise KeyboardInterrupt()
    signal.signal(signal.SIGTERM, interrupted)
    signal.signal(signal.SIGINT, interrupted)
    runner = CollectorRunner(args.root, client, max_repositories=args.max_repositories)
    try:
        report = runner.run()
    finally:
        runner.db.close()
    print(json.dumps(report, indent=2))
    return 1 if report.get("state") == "failed" else 0


if __name__ == "__main__":
    raise SystemExit(main())