File size: 41,452 Bytes
cc4d2ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build a source-faithful, provenance-rich Cayley-Math contribution staging tree.
No model calls, TeX compilation, source code execution, or network access.
"""
import argparse
import collections
import hashlib
import html
import json
import re
import subprocess
from pathlib import Path
from urllib.parse import quote, unquote

LICENSE = 'Apache-2.0'
REPO_URL = 'https://github.com/openai/math'

def dump(path, obj):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + '\n')

def jsonl(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('w') as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False, separators=(',', ':')) + '\n')

def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def uncomment(text):
    # TeX comments begin at an unescaped percent; retain line count for provenance.
    out, verbatim = [], None
    for line in text.splitlines(keepends=True):
        if verbatim:
            out.append(line)
            if '\\end{' + verbatim + '}' in line:
                verbatim = None
            continue
        verbatim_start = re.search(r'\\begin\{(lstlisting|verbatim|Verbatim|minted)\}', line)
        if verbatim_start:
            out.append(line)
            if '\\end{' + verbatim_start.group(1) + '}' not in line[verbatim_start.end():]:
                verbatim = verbatim_start.group(1)
            continue
        literal_ranges = []
        for inline in re.finditer(r'\\(?:verb\*?|lstinline)(?![A-Za-z@])(?:\[[^\]\n]*\])?', line):
            start = inline.end()
            if start >= len(line) or line[start].isspace():
                continue
            delimiter = line[start]
            close = '}' if delimiter == '{' and 'lstinline' in inline.group() else delimiter
            end = line.find(close, start + 1)
            literal_ranges.append((start, len(line) if end < 0 else end + 1))
        for i, ch in enumerate(line):
            if ch == '%':
                if any(a <= i < b for a, b in literal_ranges):
                    continue
                n = 0
                j = i - 1
                while j >= 0 and line[j] == '\\':
                    n += 1
                    j -= 1
                if not n % 2:
                    line = line[:i] + ('\n' if line.endswith('\n') else '')
                    break
        out.append(line)
    return ''.join(out)

def group_at(s, p):
    while p < len(s) and s[p].isspace():
        p += 1
    if p >= len(s) or s[p] != '{':
        raise ValueError('Expected brace group at %d' % p)
    depth, start = 1, p + 1
    p += 1
    while p < len(s):
        if s[p] == '\\':
            p += 2
            continue
        if s[p] == '{':
            depth += 1
        elif s[p] == '}':
            depth -= 1
            if depth == 0:
                return s[start:p], p + 1
        p += 1
    raise ValueError('Unclosed brace group')

def args_at(s, p, n):
    values = []
    for _ in range(n):
        value, p = group_at(s, p)
        values.append(value)
    return values, p

def clean_html(s):
    s = re.sub(r'<[^>]+>', '', s)
    s = html.unescape(s).replace('$`', '$').replace('`$', '$')
    return re.sub(r'\n{3,}', '\n\n', s).strip()

def layout_only(text):
    """Recognize complete fragments containing only pagination/bibliography UI."""
    text = re.sub(r'\\(?:clearpage|newpage|pagebreak|nobreak|small|footnotesize|scriptsize|normalsize|appendix|phantomsection|par|noindent|bigskip|medskip|smallskip|begingroup|endgroup|centering|raggedright)\b(?:\[[^\]]*\])?', '', text)
    text = re.sub(r'\\Needspace\s*\{[^{}]*\}', '', text)
    text = re.sub(r'\\addcontentsline\s*\{toc\}\s*\{section\}\s*\{(?:References|\\refname)\}', '', text)
    text = re.sub(r'\\pdfbookmark(?:\[[^\]]*\])?\s*\{References\}\s*\{references\}', '', text)
    for match in list(re.finditer(r'\\renewcommand\s*', text))[::-1]:
        try:
            a, end = args_at(text, match.end(), 2)
        except ValueError:
            continue
        if a[0] == '\\bibsection':
            text = text[:match.start()] + text[end:]
    return not text.strip(' \t\n{}')

class Corpus:
    def __init__(self, root, output, chunk_chars, preserve_worker_inputs=False):
        self.root = root.resolve()
        self.output = output
        self.chunk_chars = chunk_chars
        self.preserve_worker_inputs = preserve_worker_inputs
        self.commit = subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip()
        self.files = {}
        self.read_cache = {}
        self.extraction = []
        self.macros = []

    def rel(self, p):
        return str(p.resolve().relative_to(self.root))

    def source(self, p):
        p = p.resolve()
        p.relative_to(self.root)
        key = self.rel(p)
        if key not in self.files:
            self.files[key] = {'path': key, 'sha256': digest(p), 'bytes': p.stat().st_size,
                               'source_url': f'{REPO_URL}/blob/{self.commit}/{quote(key, safe="/") }'}
        return self.files[key]

    def read(self, p):
        p = p.resolve()
        if p not in self.read_cache:
            self.read_cache[p] = p.read_text(errors='replace')
        return self.read_cache[p]

    def catalog(self):
        overview = uncomment(self.read(self.root / 'overview.tex')).split('\\begin{document}', 1)[1]
        family_meta, current, subject = {}, {}, None
        for m in re.finditer(r'\\(cataloguesection|resultentry)\b', overview):
            if m.group(1) == 'cataloguesection':
                a, _ = args_at(overview, m.end(), 2)
                subject = a[0]
            else:
                a, _ = args_at(overview, m.end(), 4)
                fid, family_title, family_summary, refs = a
                family_meta[fid] = {'family_id': fid, 'title': family_title, 'source_claim_summary': family_summary, 'discipline': subject}
                for href in re.finditer(r'\\href\b', refs):
                    values, _ = args_at(refs, href.end(), 2)
                    url, title = values
                    if '/preprints/' not in url or not url.endswith('.pdf'):
                        continue
                    pdf_path = 'preprints/' + unquote(url.split('/preprints/', 1)[1])
                    paper_id = Path(pdf_path).parts[1]
                    meta = current.setdefault(paper_id, {'paper_id': paper_id, 'title': title, 'pdf_path': pdf_path, 'family_ids': [], 'disciplines': []})
                    if fid not in meta['family_ids']:
                        meta['family_ids'].append(fid)
                    if subject not in meta['disciplines']:
                        meta['disciplines'].append(subject)
        # CONTENTS paths may contain literal parentheses: delimit at the final .pdf).
        contents = self.read(self.root / 'CONTENTS.md')
        paper_re = re.compile(r'&emsp;\[([^\n]*)\]\((preprints/[^\n]+\.pdf)\)[^\n]*\n(.*?)(?=</td>)', re.S)
        map_paths = set()
        for match in paper_re.finditer(contents):
            title, pdf_path, abstract = match.groups()
            # Title is non-newline; abstract greediness is limited by its first closing cell.
            pdf_path = unquote(pdf_path)
            paper_id = Path(pdf_path).parts[1]
            if paper_id not in current:
                raise ValueError('CONTENTS paper absent from overview: ' + paper_id)
            current[paper_id]['title'] = clean_html(title)
            current[paper_id]['abstract'] = clean_html(abstract)
            current[paper_id]['contents_abstract_source'] = 'CONTENTS.md'
            map_paths.add(pdf_path)
        if len(current) != 721 or len(map_paths) != 721 or len(family_meta) != 373:
            raise ValueError(f'Unexpected catalog coverage current={len(current)}, CONTENTS={len(map_paths)}, families={len(family_meta)}')
        if any(not x.get('abstract') for x in current.values()):
            raise ValueError('Missing abstract')
        previous_to_current = collections.defaultdict(set)
        for d in sorted((self.root / 'preprints').iterdir()):
            if not d.is_dir():
                continue
            md = self.read(d / 'README.md')
            for m in re.finditer(r'\[previous version\]\(([^\n]+?\.pdf)\)', md, re.I):
                target = (d / unquote(m.group(1))).resolve()
                target.relative_to(self.root)
                previous_to_current[target.parent.name].add(d.name)
        # Transitive closure links older versions to the current catalog.
        def successors(pid, seen=None):
            seen = set() if seen is None else set(seen)
            if pid in seen:
                return set()
            if pid in current:
                return {pid}
            seen.add(pid)
            return set().union(*(successors(x, seen) for x in previous_to_current.get(pid, []))) if previous_to_current.get(pid) else set()
        manuscripts = []
        for d in sorted((self.root / 'preprints').iterdir()):
            if not d.is_dir():
                continue
            pdfs = sorted(d.glob('*.pdf'))
            if len(pdfs) != 1:
                raise ValueError('Expected single top-level manuscript PDF: ' + d.name)
            pid = d.name
            readme = self.read(d / 'README.md')
            title_m = re.search(r'^#\s*\[(.*)\]\([^\n]+\.pdf\)', readme, re.M)
            title = title_m.group(1) if title_m else pid
            succ = successors(pid) if pid not in current else {pid}
            status = 'current' if pid in current else ('previous' if pid in previous_to_current else 'withdrawn')
            meta = dict(current.get(pid, {}))
            meta.update(paper_id=pid, title=meta.get('title', title), status=status, pdf_path=self.rel(pdfs[0]),
                        license=LICENSE, creators=['OpenAI'], source_commit=self.commit,
                        verification_status='unverified_source_claim', lean_verified=False,
                        current_versions=sorted(succ), previous_versions=sorted(k for k in previous_to_current if pid in previous_to_current[k]),
                        citation_bibtex=(re.search(r'```bibtex\s*\n(.*?)```', readme, re.S).group(1).strip() if re.search(r'```bibtex\s*\n(.*?)```', readme, re.S) else None),
                        readme_source=self.source(d / 'README.md'), pdf_source=self.source(pdfs[0]))
            if status == 'withdrawn' and 'withdraw' not in readme.lower():
                raise ValueError('Uncatalogued directory is not documented withdrawn: ' + pid)
            if status == 'previous':
                meta['family_ids'] = sorted(set(f for x in succ for f in current[x]['family_ids']))
                meta['disciplines'] = sorted(set(f for x in succ for f in current[x]['disciplines']))
            meta.setdefault('family_ids', [])
            meta.setdefault('disciplines', [])
            meta['family_id'] = meta['family_ids'][0] if meta['family_ids'] else None
            meta['discipline'] = meta['disciplines'][0] if meta['disciplines'] else None
            meta['formalization_artifact_present'] = any((self.root / 'lean' / 'docs' / (f + '.md')).exists() for f in meta['family_ids'])
            meta['formalization_scope_docs'] = [self.rel(self.root / 'lean' / 'docs' / (f + '.md')) for f in meta['family_ids'] if (self.root / 'lean' / 'docs' / (f + '.md')).exists()]
            manuscripts.append(meta)
        # Families shared by a paper must remain in a single split.
        parent = {f: f for f in family_meta}
        def find(f):
            while parent[f] != f:
                parent[f] = parent[parent[f]]
                f = parent[f]
            return f
        for meta in current.values():
            for f in meta['family_ids'][1:]:
                a, b = find(meta['family_ids'][0]), find(f)
                parent[max(a, b)] = min(a, b)
        for meta in manuscripts:
            meta['group'] = 'openai-math:family:' + find(meta['family_ids'][0]) if meta['family_ids'] else 'openai-math:withdrawn:' + meta['paper_id']
        return manuscripts, family_meta

    def select_main(self, paper):
        candidates = []
        roots = []
        for p in sorted(paper.rglob('*.tex')):
            if p.is_symlink() or any(x in {'tools', 'provenance', '.git'} for x in p.relative_to(paper).parts):
                continue
            text = uncomment(self.read(p))
            if '\\begin{document}' not in text:
                continue
            roots.append(p)
            rel = str(p.relative_to(paper))
            score = 100 if p.name == 'main.tex' else (90 if p.name == 'paper.tex' else 50)
            score -= len(p.relative_to(paper).parts) * 2
            if 'figure' in rel.lower():
                score -= 100
            score += min(len(text) / 1000000, 1)
            candidates.append((score, p))
        if not candidates:
            raise ValueError('No main TeX with document body: ' + paper.name)
        candidates.sort(key=lambda x: (-x[0], str(x[1])))
        return candidates[0][1], roots

    def extract(self, meta):
        paper = self.root / 'preprints' / meta['paper_id']
        main, candidates = self.select_main(paper)
        dependencies, unresolved, exclusions, preambles, distribution_dependencies, listings = {}, [], [], [], [], []
        active, expanded = set(), []

        def exclude(path, start, end, reason):
            if end >= start:
                exclusions.append({'source_path': self.rel(path), 'start_line': start, 'end_line': end, 'reason': reason})

        def resolve(name, source, text_attachment=False):
            if any(c in name for c in '\\#{}'):
                return None
            for base in (source.parent, main.parent, paper / 'build', paper):
                p = (base / name).resolve()
                try:
                    p.relative_to(self.root)
                except ValueError:
                    continue
                options = [p] if p.suffix == '.tex' else [p, p.with_name(p.name + '.tex')]
                for opt in options:
                    if opt.is_file() and (text_attachment or opt.suffix in {'.tex', '.tikz'}):
                        return opt
            return None

        include_re = re.compile(r'\\(input|include|subfile)(?![A-Za-z@])\s*(?:\{([^{}]+)\}|([^\s%{}]+))|\\includepdf(?:\[[^\n]*?\])?\s*\{([^{}]+)\}')

        def expand(path, context='body'):
            path = path.resolve()
            path.relative_to(self.root)
            if path in active:
                unresolved.append({'source_path': self.rel(path), 'reason': 'cyclic_include'})
                return []
            active.add(path)
            dependencies[self.rel(path)] = self.source(path)
            original = self.read(path)
            text = uncomment(original)
            lines = text.splitlines(keepends=True)
            begin = next((i for i, line in enumerate(lines) if '\\begin{document}' in line), None)
            if begin is not None:
                raw_pre = ''.join(lines[:begin])
                preambles.append({'source_path': self.rel(path), 'source_sha256': digest(path), 'start_line': 1, 'end_line': begin, 'text': raw_pre})
                exclude(path, 1, begin, 'preamble_preserved_in_macro_context')
                # Expand preamble includes into sidecar, never inject them into body.
                for i, line in enumerate(lines[:begin], 1):
                    for m in include_re.finditer(line):
                        name = m.group(2) or m.group(3)
                        if not name:
                            continue
                        dep = resolve(name, path)
                        if dep is None:
                            (distribution_dependencies if Path(name).name.startswith('glyphtounicode') else unresolved).append({'source_path': self.rel(path), 'line': i, 'target': name, 'reason': 'non_content_tex_distribution_dependency' if Path(name).name.startswith('glyphtounicode') else 'unresolved_preamble_include'})
                        else:
                            preambles.extend(expand(dep, context='preamble'))
                line = lines[begin]
                lines[begin] = line.split('\\begin{document}', 1)[1]
            if context == 'preamble':
                contexts = [{'source_path': self.rel(path), 'source_sha256': digest(path), 'start_line': 1, 'end_line': len(lines), 'text': text}]
                if begin is None:
                    for i, line in enumerate(lines, 1):
                        for m in include_re.finditer(line):
                            name = m.group(2) or m.group(3)
                            if not name:
                                continue
                            dep = resolve(name, path)
                            if dep is None:
                                target = distribution_dependencies if Path(name).name.startswith('glyphtounicode') else unresolved
                                target.append({'source_path': self.rel(path), 'line': i, 'target': name, 'reason': 'non_content_tex_distribution_dependency' if Path(name).name.startswith('glyphtounicode') else 'unresolved_preamble_include'})
                            else:
                                contexts.extend(expand(dep, context='preamble'))
                active.remove(path)
                return contexts
            output = []
            skip_env = None
            skip_start = None
            verbatim = None
            consumed_listing_until = -1
            first = begin or 0
            for i in range(first, len(lines)):
                line, lineno = lines[i], i + 1
                if i <= consumed_listing_until:
                    continue
                if verbatim:
                    output.append((line, self.rel(path), lineno))
                    if '\\end{' + verbatim + '}' in line:
                        verbatim = None
                    continue
                verbatim_start = re.search(r'\\begin\{(lstlisting|verbatim|Verbatim|minted)\}', line)
                if verbatim_start:
                    output.append((line, self.rel(path), lineno))
                    if '\\end{' + verbatim_start.group(1) + '}' not in line[verbatim_start.end():]:
                        verbatim = verbatim_start.group(1)
                    continue
                if '\\end{document}' in line:
                    before = line.split('\\end{document}', 1)[0]
                    if before.strip():
                        output.append((before, self.rel(path), lineno))
                    exclude(path, lineno, len(lines), 'end_document_and_trailing_material')
                    break
                if skip_env:
                    if '\\end{' + skip_env + '}' in line:
                        exclude(path, skip_start, lineno, 'bibliography' if skip_env == 'thebibliography' else 'pure_drawing_code')
                        skip_env = None
                    continue
                env_m = re.search(r'\\begin\{(thebibliography|tikzpicture|axis|asy|pspicture|pgfonlayer)\}', line)
                if env_m:
                    env = env_m.group(1)
                    prefix = line[:env_m.start()]
                    if prefix.strip():
                        output.append((prefix, self.rel(path), lineno))
                    end_token = '\\end{' + env + '}'
                    if end_token in line[env_m.end():]:
                        rest = line.split(end_token, 1)[1]
                        if rest.strip():
                            output.append((rest, self.rel(path), lineno))
                        exclude(path, lineno, lineno, 'bibliography' if env == 'thebibliography' else 'pure_drawing_code')
                    else:
                        skip_env, skip_start = env, lineno
                    continue
                if re.match(r'\s*\\(?:bibliography|bibliographystyle|printbibliography|addbibresource|maketitle|tableofcontents|listoffigures|listoftables)\b', line):
                    exclude(path, lineno, lineno, 'bibliography_or_layout_command')
                    continue
                listing_start = re.search(r'\\(lstinputlisting|verbatiminput|VerbatimInput|inputminted)(?![A-Za-z@])', line)
                if listing_start:
                    # These commands insert literal source/verification data into
                    # the PDF. Read the requested file as data; never execute it.
                    following = ''.join(lines[i:])
                    pos = listing_start.end()
                    while pos < len(following) and following[pos].isspace():
                        pos += 1
                    options = ''
                    if following[pos:pos + 1] == '[':
                        depth, start_option = 1, pos + 1
                        pos += 1
                        while pos < len(following) and depth:
                            if following[pos] == '[':
                                depth += 1
                            elif following[pos] == ']':
                                depth -= 1
                            pos += 1
                        options = following[start_option:pos - 1]
                    try:
                        if listing_start.group(1) == 'inputminted':
                            _, pos = group_at(following, pos)
                        target_name, end = group_at(following, pos)
                    except ValueError:
                        unresolved.append({'source_path': self.rel(path), 'line': lineno, 'reason': 'unparsed_external_code_listing'})
                    else:
                        command_text = following[listing_start.start():end]
                        command_lines = following[:end].count('\n')
                        consumed_listing_until = i + command_lines
                        dep = resolve(target_name, path, text_attachment=True)
                        relocated_by_checksum = False
                        if dep is None:
                            # One release retained an old certificate/ listing
                            # path after moving the file to verification/. Accept
                            # the moved source only when the manuscript itself
                            # prints its exact SHA256, including TeX line wraps.
                            relocated = paper / 'verification' / Path(target_name).name
                            if relocated.is_file():
                                manuscript_checksum_text = re.sub(r'\s+|\\allowbreak', '', self.read(main))
                                if digest(relocated) in manuscript_checksum_text:
                                    dep, relocated_by_checksum = relocated.resolve(), True
                        if line[:listing_start.start()].strip():
                            output.append((line[:listing_start.start()], self.rel(path), lineno))
                        if dep is None:
                            unresolved.append({'source_path': self.rel(path), 'line': lineno, 'target': target_name, 'reason': 'external_code_listing_not_found'})
                            output.append((command_text + '\n', self.rel(path), lineno))
                        else:
                            dependencies[self.rel(dep)] = self.source(dep)
                            literal_lines = self.read(dep).splitlines(keepends=True)
                            first_line = re.search(r'\bfirstline\s*=\s*(\d+)', options)
                            last_line = re.search(r'\blastline\s*=\s*(\d+)', options)
                            a = int(first_line.group(1)) if first_line else 1
                            b = int(last_line.group(1)) if last_line else len(literal_lines)
                            output.append(('\\begin{lstlisting}' + ('[' + options + ']' if options else '') + '\n', self.rel(path), lineno))
                            for n, literal_line in enumerate(literal_lines[a - 1:b], a):
                                output.append((literal_line if literal_line.endswith('\n') else literal_line + '\n', self.rel(dep), n))
                            output.append(('\\end{lstlisting}\n', self.rel(path), lineno + command_lines))
                            listings.append({'from': self.rel(path), 'start_line': lineno, 'end_line': lineno + command_lines,
                                             'target': self.rel(dep), 'target_sha256': self.source(dep)['sha256'],
                                             'declared_target': target_name, 'relocated_by_matching_manuscript_sha256': relocated_by_checksum,
                                             'target_start_line': a, 'target_end_line': b, 'mode': 'literal_read_only_not_executed'})
                        suffix = following[end:].split('\n', 1)[0]
                        if suffix.strip():
                            output.append((suffix + '\n', self.rel(path), lineno + command_lines))
                        continue
                matches = list(include_re.finditer(line))
                if not matches:
                    if line.strip():
                        output.append((line, self.rel(path), lineno))
                    elif output and output[-1][0].strip():
                        output.append(('\n', self.rel(path), lineno))
                    continue
                last = 0
                for m in matches:
                    prefix = line[last:m.start()]
                    if prefix.strip():
                        output.append((prefix, self.rel(path), lineno))
                    name = m.group(2) or m.group(3) or m.group(4)
                    if m.group(4):
                        name = str(Path(name).with_suffix('.tex'))
                    dep = resolve(name, path)
                    if dep is None:
                        unresolved.append({'source_path': self.rel(path), 'line': lineno, 'target': name, 'reason': 'unresolved_pdf_tex' if m.group(4) else 'unresolved_include'})
                        output.append((m.group(0), self.rel(path), lineno))
                    elif dep.suffix == '.tikz':
                        dependencies[self.rel(dep)] = self.source(dep)
                        exclude(dep, 1, len(self.read(dep).splitlines()), 'pure_drawing_include')
                    elif dep.stem.lower() in {'references', 'bibliography'} or dep.parent.name.lower() in {'references', 'bibliography'}:
                        dependencies[self.rel(dep)] = self.source(dep)
                        exclude(dep, 1, len(self.read(dep).splitlines()), 'bibliography_include')
                    else:
                        expanded.append({'from': self.rel(path), 'line': lineno, 'target': self.rel(dep), 'kind': 'includepdf_tex_counterpart' if m.group(4) else m.group(1)})
                        output.extend(expand(dep))
                    last = m.end()
                rest = line[last:]
                if rest.strip():
                    output.append((rest, self.rel(path), lineno))
            if skip_env:
                exclude(path, skip_start, len(lines), 'unterminated_' + skip_env)
                unresolved.append({'source_path': self.rel(path), 'reason': 'unterminated_skipped_environment', 'environment': skip_env})
            active.remove(path)
            return output

        tape = expand(main)
        macro_key = 'macro:' + meta['paper_id']
        macro_context = {'id': macro_key, 'paper_id': meta['paper_id'], 'group': meta['group'], 'license': LICENSE, 'contexts': preambles}
        self.macros.append(macro_context)
        full = ''.join(x[0] for x in tape).strip()
        if len(full) < 500:
            raise ValueError('Implausibly short extracted body: ' + meta['paper_id'])
        section_re = re.compile(r'\\(?:part|chapter|section|subsection)\*?(?:\[[^\]]*\])?\s*\{')
        section_titles = []
        for m in section_re.finditer(full):
            try:
                section_titles.append(group_at(full, m.end() - 1)[0])
            except ValueError:
                pass
        # Split only at paragraph/section boundaries outside mathematical and proof
        # environments, display math and brace groups. The target is soft: retain a
        # long proof as one record rather than truncate its assumptions or argument.
        chunks, chunk, size, section = [], [], 0, 'Front matter and abstract'
        chunk_section, environments = section, []
        display_math, brace_depth, safe_boundary = None, 0, True
        env_re = re.compile(r'\\(begin|end)\{([^}]+)\}')
        for entry in tape:
            text_line = entry[0]
            sm = section_re.search(text_line)
            new_section = None
            if sm:
                try:
                    new_section = group_at(text_line, sm.end() - 1)[0]
                except ValueError:
                    pass
            outside = not environments and display_math is None and brace_depth == 0
            if chunk and outside and ((new_section and size >= 800) or (size >= self.chunk_chars and safe_boundary)):
                chunks.append((chunk_section, chunk))
                chunk, size = [], 0
                chunk_section = new_section or section
            if new_section:
                section = new_section
                if not chunk:
                    chunk_section = section
            chunk.append(entry)
            size += len(text_line)
            if environments and environments[-1] in {'lstlisting', 'verbatim', 'Verbatim', 'minted'}:
                if '\\end{' + environments[-1] + '}' in text_line:
                    environments.pop()
                    safe_boundary = True
                continue
            closed_env = False
            for event in env_re.finditer(text_line):
                kind, env = event.groups()
                if kind == 'begin':
                    environments.append(env)
                elif env in environments:
                    # Retain strict nesting when valid; malformed source is kept.
                    if environments[-1] == env:
                        environments.pop()
                    else:
                        environments.remove(env)
                    closed_env = True
            for event in re.finditer(r'(?<!\\)(?:\\\[|\\\]|\$\$)', text_line):
                marker = event.group()
                if marker == r'\[':
                    display_math = r'\['
                elif marker == r'\]':
                    display_math = None
                else:
                    display_math = None if display_math == '$$' else '$$'
            for event in re.finditer(r'(?<!\\)[{}]', text_line):
                brace_depth += 1 if event.group() == '{' else -1
            safe_boundary = not text_line.strip() or closed_env
        if chunk:
            chunks.append((chunk_section, chunk))
        records = []
        for n, (section, entries) in enumerate(chunks):
            text = ''.join(e[0] for e in entries).strip()
            if not text:
                continue
            if layout_only(text):
                for _, source_path, source_line in entries:
                    exclude(self.root / source_path, source_line, source_line, 'layout_only_fragment')
                continue
            spans = []
            for _, path, line in entries:
                if spans and spans[-1]['path'] == path and line <= spans[-1]['end_line'] + 1:
                    spans[-1]['end_line'] = max(spans[-1]['end_line'], line)
                else:
                    spans.append({'path': path, 'start_line': line, 'end_line': line, 'sha256': self.files[path]['sha256'], 'source_url': self.files[path]['source_url']})
            records.append({'id': f'openai-math:{meta["paper_id"]}:{n:04d}', 'paper_id': meta['paper_id'], 'title': meta['title'],
                            'text': text, 'section': section, 'record_type': 'source_latex', 'group': meta['group'], 'license': LICENSE,
                            'creators': ['OpenAI'], 'family_id': meta['family_id'], 'family_ids': meta['family_ids'], 'discipline': meta['discipline'],
                            'source_commit': self.commit, 'source_path': self.rel(main), 'source_sha256': digest(main),
                            'source_url': self.source(main)['source_url'], 'source_spans': spans, 'macro_context_id': macro_key,
                            'verification_status': 'unverified_source_claim', 'lean_verified': False, 'transform': 'deterministic_latex_body_extraction', 'chunk_index': n,
                            'contains_code_listing': '\\begin{lstlisting}' in text or '\\begin{verbatim}' in text or '\\begin{minted}' in text})
        snippets = []
        statement_re = re.compile(r'\\begin\{(theorem|thm|proposition|prop|lemma|corollary|cor|conjecture)\*?\}')
        for m in statement_re.finditer(full):
            end = re.search(r'\\end\{' + re.escape(m.group(1)) + r'\*?\}', full[m.end():])
            if end:
                snippets.append(full[m.start():m.end() + end.end()][:6000])
            if len(snippets) >= 3:
                break
        flags = sorted(set(x['reason'] for x in unresolved))
        if len(candidates) > 1:
            flags.append('multiple_document_roots_scored')
        worker = {'paper_id': meta['paper_id'], 'title': meta['title'], 'family_id': meta['family_id'], 'family_ids': meta['family_ids'],
                  'discipline': meta['discipline'], 'abstract': meta['abstract'], 'section_titles': section_titles,
                  'source_excerpt': full[:12000], 'main_statement_snippets': snippets, 'extraction_flags': flags,
                  'verification_status': 'unverified_source_claim', 'source_commit': self.commit, 'group': meta['group']}
        meta.update(main_tex_source=self.source(main), source_dependencies=list(dependencies.values()), body_characters=len(full), records=len(records),
                    extraction_flags=flags, excluded_ranges=exclusions, unresolved_includes=unresolved, expanded_includes=expanded,
                    main_tex_candidates=[self.rel(x) for x in candidates], macro_context_id=macro_key, tex_distribution_dependencies=distribution_dependencies,
                    external_listings=listings)
        self.extraction.append({'paper_id': meta['paper_id'], 'main_tex_path': self.rel(main), 'body_characters': len(full),
                                'records': len(records), 'dependency_files': len(dependencies), 'unresolved_includes': unresolved,
                                'excluded_ranges': exclusions, 'extraction_flags': flags, 'tex_distribution_dependencies': distribution_dependencies,
                                'external_listings': listings})
        return records, worker

    def build(self):
        self.output.mkdir(parents=True, exist_ok=True)
        manuscripts, families = self.catalog()
        records, workers = [], []
        for n, meta in enumerate(manuscripts):
            if meta['status'] != 'current':
                continue
            extracted, worker = self.extract(meta)
            records.extend(extracted)
            workers.append(worker)
        counts = collections.Counter(m['status'] for m in manuscripts)
        if dict(counts) != {'current': 721, 'previous': 27, 'withdrawn': 3}:
            raise ValueError('Unexpected status counts: ' + str(counts))
        assert len(workers) == 721 and {r['paper_id'] for r in records} == {w['paper_id'] for w in workers}
        for name in ['README.md', 'CONTENTS.md', 'overview.tex', 'history.md', 'LICENSE', 'lean/formalization.yaml']:
            self.source(self.root / name)
        jsonl(self.output / 'data/source-records.jsonl', records)
        jsonl(self.output / 'data/macro-contexts.jsonl', self.macros)
        worker_path = self.output / 'worker-inputs.jsonl'
        worker_differences = []
        if self.preserve_worker_inputs and worker_path.exists():
            jsonl(self.output / 'worker-inputs-improved.jsonl', workers)
            frozen_workers = {x['paper_id']: x for x in map(json.loads, worker_path.read_text().splitlines())}
            for final in workers:
                before = frozen_workers[final['paper_id']]
                changed_fields = [key for key in sorted(before.keys() | final.keys()) if before.get(key) != final.get(key)]
                if changed_fields:
                    worker_differences.append({'paper_id': final['paper_id'], 'changed_fields': changed_fields,
                                               'before_flags': before['extraction_flags'], 'final_flags': final['extraction_flags'],
                                               'source_excerpt_changed': before['source_excerpt'] != final['source_excerpt'],
                                               'statement_snippets_changed': before['main_statement_snippets'] != final['main_statement_snippets']})
        else:
            jsonl(worker_path, workers)
        jsonl(self.output / 'audit/worker-input-differences.jsonl', worker_differences)
        jsonl(self.output / 'audit/manuscripts.jsonl', manuscripts)
        jsonl(self.output / 'audit/extraction.jsonl', self.extraction)
        jsonl(self.output / 'audit/source-files.jsonl', sorted(self.files.values(), key=lambda x: x['path']))
        dump(self.output / 'audit/families.json', families)
        report = {'source_commit': self.commit, 'manuscript_status_counts': dict(counts), 'family_count': len(families),
                  'disciplines': sorted(set(f['discipline'] for f in families.values())), 'source_records': len(records),
                  'source_papers': len(workers), 'source_body_characters': sum(m.get('body_characters', 0) for m in manuscripts),
                  'source_dependency_files': len(self.files), 'macro_contexts': len(self.macros),
                  'worker_inputs_sha256': digest(worker_path),
                  'worker_inputs_preserved': self.preserve_worker_inputs,
                  'worker_input_snapshot_changed_papers': len(worker_differences),
                  'worker_input_excerpt_changed_papers': sum(x['source_excerpt_changed'] for x in worker_differences),
                  'worker_input_statement_changed_papers': sum(x['statement_snippets_changed'] for x in worker_differences),
                  'worker_input_snapshot_note': 'Workers review the immutable worker-inputs.jsonl snapshot when --preserve-worker-inputs is used. Final extraction differences are recorded in audit/worker-input-differences.jsonl. Worker annotations describe abstracts and supplied excerpts, not a mathematical audit of entire manuscripts.',
                  'tex_distribution_dependency_count': sum(len(x['tex_distribution_dependencies']) for x in self.extraction),
                  'external_literal_listing_count': sum(len(x['external_listings']) for x in self.extraction),
                  'unresolved_includes_count': sum(len(x['unresolved_includes']) for x in self.extraction),
                  'papers_with_unresolved_includes': [x['paper_id'] for x in self.extraction if x['unresolved_includes']],
                  'policies': ['Only current catalog manuscripts enter source-records.', 'Text is source LaTeX, not model-generated proofs.',
                               'Preamble is preserved in macro-contexts.jsonl; comments, bibliography, layout-only commands and drawing environments excluded.',
                               'Local input/include/subfile are read recursively; includepdf uses same-name TeX counterpart when present.',
                               'Root TeX scored by conventional main/paper filename, location and body presence; candidates retained in audit.',
                               'Source line spans are coarse ranges across comment removal; exact source hashes and retained text are recorded.',
                               'No TeX, shell commands, model prompts, or embedded build instructions from source documents are executed.',
                               'No Lean compilation performed; all mathematical claims remain unverified_source_claim.',
                               'Groups join result families sharing a manuscript to prevent split leakage.',
                               'Chunk target is soft: proofs, math environments, display math and brace groups are not cut at arbitrary length.',
                               'External lstinputlisting/verbatiminput/VerbatimInput/inputminted data is read literally, never executed; exact attachment hashes and line ranges are audited.',
                               'Pure layout fragments are excluded and recorded in excluded_ranges.',
                               'worker-inputs.jsonl is an immutable worker-review snapshot when --preserve-worker-inputs is used; worker-inputs-improved.jsonl contains final extraction flags and excerpts.']}
        dump(self.output / 'extraction-report.json', report)
        print(json.dumps(report, ensure_ascii=False))

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--source', type=Path, default=Path('/Users/zxy/math'))
    ap.add_argument('--output', type=Path, default=Path('work/staging/openai-math'))
    ap.add_argument('--chunk-chars', type=int, default=8000)
    ap.add_argument('--preserve-worker-inputs', action='store_true')
    args = ap.parse_args()
    Corpus(args.source, args.output, args.chunk_chars, args.preserve_worker_inputs).build()

if __name__ == '__main__':
    main()