File size: 35,958 Bytes
dd5f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build exact-span, unannotated study-context packets from licensed Atlas articles.

No extracted claim, matching context or challenge question is a support judgment.
Run from the repository with .venv/bin/python expansion_release/academic/build_study.py.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
import gzip
from hashlib import sha256
import json
from pathlib import Path
import re
import shutil
import unicodedata
import urllib.request
import xml.etree.ElementTree as ET

import pyarrow as pa
import pyarrow.parquet as pq

HERE = Path(__file__).resolve().parent
REPO = next((path for path in (HERE, *HERE.parents, Path.cwd()) if (path / "research_atlas/work").is_dir()), Path.cwd())
OLD = REPO / "research_atlas/work"
NEW = REPO / "expansion_release/atlas"
RULE_VERSION = "doxa-study-exact-context-0.2.0"
CLAIM = re.compile(r"\b(?:we|our|results?|findings?|found|suggest\w*|show\w*|estimat\w*|effect\w*|associat\w*|causal\w*|correlat\w*|data|samples?|participants?|hypothes\w*|limit\w*|significan\w*|stud(?:y|ies)|experiment\w*|survey\w*|model\w*|measur\w*|evidence|analy[sz]\w*)\b", re.I)
METHOD = re.compile(r"\b(?:methods?|methodology|materials|procedure|participants|data collection|statistical analysis|study design|experimental design)\b", re.I)
RESULT = re.compile(r"\b(?:results?|findings?|empirical analysis)\b", re.I)
LIMIT = re.compile(r"\b(?:limitation\w*|caution\w*|cannot|can not|unable|uncertain\w*|generaliz\w*|generalis\w*|confound\w*|future (?:work|research)|further (?:work|research)|does not (?:imply|establish|prove)|not (?:causal|representative)|cross.sectional)\b", re.I)
CAUSAL = re.compile(r"\b(?:caus\w*|effect\w*|associat\w*|correlat\w*|confound\w*|randomi[sz]\w*|endogen\w*)\b", re.I)
MODAL = re.compile(r"\b(?:must|shall|should|required?|recommends?|recommendation|obligations?|ought)\b", re.I)
NUMBER = re.compile(r"(?<![\w])(?:[−+\-]?[0-9]+(?:[,\.][0-9]+)*(?:\s?%|\s?(?:percent|million|billion|years?|months?|days?))?)(?![\w])", re.I)
TABLE = re.compile(r"\b(?:Table|Tab\.)\s*[A-Z]?\d+[a-z]?\b", re.I)
SENTENCE = re.compile(r".+?(?:[.!?](?=[\s]+[A-Z“\"(\[]|$)|$)", re.S)
BOILER = re.compile(r"creative commons|copyright|all rights reserved|supporting information|data availability|competing interests|reproduced (?:with|by) permission", re.I)
STOP = set("the and for that this with from have has were was are not our their they which than into also been these such we its between can may will more same each other using used study studies results data found analysis".split())
EXCLUDED_ANCESTORS = {"fig", "table-wrap", "boxed-text", "disp-quote", "ref-list", "supplementary-material"}
RAW_XML_INDEX = None
FROZEN_INPUT = None
RAW_OVERRIDE = None
FETCH_MISSING = False
FROZEN_PRIOR = {}
FROZEN_FULLTEXT = {}


def digest(value):
    return sha256(value if isinstance(value, bytes) else value.encode("utf-8")).hexdigest()


def dump(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def read_jsonl(path):
    return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()]


def tokens(text):
    return {x for x in re.findall(r"[\w]+", text.casefold()) if len(x) > 2 and x not in STOP}


def normalized_quote(text):
    return " ".join(re.findall(r"\w+", unicodedata.normalize("NFKC", text).casefold()))


def identity_keys(document):
    values = {"title:" + normalized_quote(document.get("title", ""))}
    if document.get("pmcid"):
        values.add("pmcid:" + document["pmcid"])
    for doi in (document.get("doi"), *(document.get("alternate_dois") or [])):
        if doi:
            values.add("doi:" + re.sub(r"^https?://(?:dx\.)?doi.org/", "", doi.casefold()).rstrip("."))
    values.discard("title:")
    return values


def sentence_spans(text):
    """Offset-preserving splitter; does not rewrite abbreviations or source punctuation."""
    for match in SENTENCE.finditer(text):
        start, end = match.span()
        while start < end and text[start].isspace():
            start += 1
        while end > start and text[end - 1].isspace():
            end -= 1
        if end > start:
            yield start, end, text[start:end]


def xml_source(document):
    global RAW_XML_INDEX
    expected = document.get("source_xml_sha256")
    source_url = document.get("fulltext_source_url") or document.get("license", {}).get("source_url", "")
    candidates = [OLD / "raw" / (digest(source_url) + ".xml")]
    raw = RAW_OVERRIDE or NEW / "cache/raw"
    for name in (digest(source_url) + ".xml", document.get("pmcid", "") + ".xml", (expected or "") + ".xml"):
        candidates.append(raw / name)
        candidates.append(raw / (name + ".gz"))
    for path in candidates:
        if path.is_file():
            value = gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
            if digest(value) == expected:
                return ET.fromstring(value), path
    # Collector cache names may be hashes of a different canonical URL; hash match
    # must still succeed, and this fallback only scans XML (never secret/config files).
    if RAW_XML_INDEX is None:
        RAW_XML_INDEX = {}
        for path in (*raw.glob("*.xml"), *raw.glob("*.xml.gz")):
            value = gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
            RAW_XML_INDEX[digest(value)] = path
    if expected in RAW_XML_INDEX:
        path = RAW_XML_INDEX[expected]
        value = gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
        return ET.fromstring(value), path
    if FETCH_MISSING and source_url.startswith("https://www.ebi.ac.uk/europepmc/webservices/rest/") and source_url.endswith("/fullTextXML"):
        request = urllib.request.Request(source_url, headers={"User-Agent": "DOXA-StudyEvidence/0.2 (+https://tacitus.me/doxa/)"})
        with urllib.request.urlopen(request, timeout=45) as response:
            value = response.read()
        if digest(value) != expected:
            raise ValueError("Upstream XML has changed: expected immutable source hash " + expected)
        raw.mkdir(parents=True, exist_ok=True)
        path = raw / (expected + ".xml.gz")
        path.write_bytes(gzip.compress(value, mtime=0))
        RAW_XML_INDEX[expected] = path
        return ET.fromstring(value), path
    raise ValueError("No immutable raw XML matched source_xml_sha256: " + document["id"])


def article_rights(tree):
    """Accept only main-article CC BY / CC0; figure licenses cannot license an article."""
    permissions = tree.find("./front/article-meta/permissions")
    if permissions is None:
        raise ValueError("main-article permissions absent")
    fragment = ET.tostring(permissions, encoding="unicode")
    urls = re.findall(r"https?://creativecommons\.org/(?:licenses/by/[0-9.]+/?|publicdomain/zero/[0-9.]+/?)", fragment, re.I)
    if not urls:
        raise ValueError("main-article license is not explicit CC BY or CC0")
    return {"license_urls": sorted(set(x.rstrip("/") for x in urls)), "permissions_xml_sha256": digest(fragment),
            "permissions_text": "".join(permissions.itertext()).strip(), "license_scope": "main_article_prose_only",
            "figures_tables_supplements_third_party_material": "excluded", "item_check": "main_article_permissions_xml_checked"}


def source_metadata(tree):
    parents = {child: parent for parent in tree.iter() for child in parent}
    mapping = {}
    for section, roots in (("abstract", tree.findall("./front/article-meta/abstract")), ("body", tree.findall("body"))):
        if not roots:
            continue
        elements = [element for root in roots for element in root.findall(".//p")]
        for ordinal, element in enumerate(elements, 1):
            # Existing Atlas locators count the first abstract separately; both
            # variants resolve through section and original ordinal.
            ancestors, node = [], element
            while node in parents:
                node = parents[node]
                ancestors.append(node)
            excluded = any(x.tag in EXCLUDED_ANCESTORS for x in ancestors)
            hierarchy = []
            for item in reversed(ancestors):
                if item.tag == "sec":
                    hierarchy.append({"id": item.attrib.get("id"), "type": item.attrib.get("sec-type"),
                                      "title": "".join(item.find("title").itertext()).strip() if item.find("title") is not None else ""})
            refs = []
            prose = "".join(element.itertext()).strip()
            # itertext preserves xref text exactly; cumulative text offset gives
            # locations without a search that might select an earlier number.
            cursor = 0
            def walk(node):
                nonlocal cursor
                if node.text:
                    cursor += len(node.text)
                for child in node:
                    beginning = cursor
                    walk(child)
                    if child.tag == "xref":
                        refs.append({"ref_type": child.attrib.get("ref-type", ""), "rid": child.attrib.get("rid", ""),
                                     "start": beginning, "end": cursor, "text": "".join(child.itertext())})
                    if child.tail:
                        cursor += len(child.tail)
            walk(element)
            leading = len("".join(element.itertext())) - len("".join(element.itertext()).lstrip())
            for ref in refs:
                ref["xml_text"] = ref["text"]
                ref["start"] = max(0, ref["start"] - leading)
                ref["end"] = min(len(prose), ref["end"] - leading)
                ref["text"] = prose[ref["start"]:ref["end"]]
            mapping[(section, ordinal)] = {"section_path": hierarchy, "references": refs, "excluded": excluded, "text": prose}
    citations = []
    for element in tree.findall(".//ref-list/ref"):
        citations.append({"id": element.attrib.get("id"), "text": "".join(element.itertext()).strip(),
                          "doi": next(("".join(x.itertext()) for x in element.iter("pub-id") if x.attrib.get("pub-id-type") == "doi"), None)})
    citation_ids = Counter(x["id"] for x in citations)
    for paragraph in mapping.values():
        for reference in paragraph["references"]:
            targets = reference["rid"].split()
            if reference["ref_type"] == "bibr":
                reference["bibliography_target_status"] = [
                    {"xml_id": target, "status": "resolved" if citation_ids[target] == 1 else "ambiguous" if citation_ids[target] > 1 else "unresolved"}
                    for target in targets]
                reference["resolution_status"] = "resolved" if targets and all(citation_ids[x] == 1 for x in targets) else "unresolved_or_ambiguous"
            else:
                reference["bibliography_target_status"] = []
                reference["resolution_status"] = "non_bibliography_pointer_content_not_redistributed"
    return mapping, citations


def source_rows():
    if FROZEN_INPUT:
        opener = gzip.open if FROZEN_INPUT.suffix == ".gz" else open
        with opener(FROZEN_INPUT, "rt", encoding="utf-8") as source:
            for line in source:
                value = json.loads(line)
                FROZEN_PRIOR[value["document"]["id"]] = value.get("prior_doxa_source", False)
                FROZEN_FULLTEXT[value["document"]["id"]] = value.get("prior_atlas_fulltext", False)
                yield value["document"], value["passages"], FROZEN_INPUT
        return
    newpaths = sorted((NEW / "work/articles").glob("*.json"))
    if newpaths:
        for path in newpaths:
            value = json.loads(path.read_text(encoding="utf-8"))
            yield value["document"], value["passages"], path
    else:
        passages = defaultdict(list)
        for passage in read_jsonl(OLD / "passages.jsonl"):
            passages[passage["document_id"]].append(passage)
        for document in read_jsonl(OLD / "documents.jsonl"):
            if document.get("text") and passages[document["id"]]:
                yield document, passages[document["id"]], OLD / "documents.jsonl"


def source_locator(passage, start=0, end=None):
    end = len(passage["text"]) if end is None else end
    return {"document_id": passage["document_id"], "paragraph_id": passage["id"],
            "paragraph_start": start, "paragraph_end": end,
            "source_text_start": passage["source_text_start"] + start,
            "source_text_end": passage["source_text_start"] + end,
            "source_xpath": passage["source_xpath"], "section_title": passage["section_title"],
            "paragraph_index": passage["paragraph_index"], "source_section": passage["source_section"],
            "section_path": passage["section_path"], "xml_sha256": passage["source_xml_sha256"],
            "page": None, "page_status": "JATS_XML_has_no_reliable_PDF_page_mapping",
            "offset_unit": "unicode_code_points", "quote": passage["text"][start:end]}


def admitted_neighbor(item, focal):
    here = re.search(r"\)\[(\d+)\]$", focal["source_xpath"])
    there = re.search(r"\)\[(\d+)\]$", item["source_xpath"])
    same_region = item["source_section"] == focal["source_section"]
    xml_gap = abs(int(here[1]) - int(there[1])) - 1 if same_region and here and there else None
    return {**source_locator(item), "relation": "nearest_preceding_admitted" if item["source_text_start"] < focal["source_text_start"] else "nearest_following_admitted",
            "focal_original_paragraph_index": focal["paragraph_index"],
            "source_index_gap": max(0, abs(item["paragraph_index"] - focal["paragraph_index"]) - 1),
            "xml_paragraph_ordinal_gap": xml_gap, "same_abstract_or_body_region": same_region,
            "originally_adjacent": same_region and xml_gap == 0,
            "scope": "nearest_admitted_context_may_skip_quarantined_or_excluded_source_paragraphs"}


def quarantine_duplicates(paragraphs, external=None):
    groups = defaultdict(list)
    for paragraph in paragraphs:
        groups[digest(normalized_quote(paragraph["text"]))].append(paragraph)
    quarantined, receipt = set(), []
    for fingerprint, items in sorted(groups.items()):
        if len({x["document_id"] for x in items}) > 1:
            quarantined.update(x["id"] for x in items)
            receipt.append({"normalized_text_sha256": fingerprint, "reason": "normalized_exact_cross_document_paragraph_all_occurrences_excluded",
                            "paragraphs": [{"id": x["id"], "document_id": x["document_id"], "source_role": x["source_role"]} for x in items]})
    if external:
        for group in external["groups"]:
            matches = [x for x in paragraphs if x["id"] in {p["id"] for p in group["paragraphs"]}]
            if matches:
                assert all(digest(normalized_quote(x["text"])) == group["normalized_text_sha256"] for x in matches)
                quarantined.update(x["id"] for x in matches)
                if group["normalized_text_sha256"] not in {x["normalized_text_sha256"] for x in receipt}:
                    receipt.append(group)
    admitted = [x for x in paragraphs if x["id"] not in quarantined]
    return admitted, {"normalization": "NFKC_unicode_casefold_word_sequence", "groups": receipt,
                      "duplicate_groups": len(receipt), "quarantined_positions_in_this_build": len(quarantined),
                      "quarantined_paragraph_ids": sorted(quarantined), "original_source_text_rewritten": False,
                      "whole_document_training_eligible": False,
                      "policy": "all occurrences removed from admitted paragraph units, claims and every candidate context; original paper text retained solely for anchors"}


def role(paragraph):
    title = " > ".join(x.get("title", "") for x in paragraph["section_path"]) or paragraph["section_title"]
    if METHOD.search(title):
        return "methods"
    if RESULT.search(title):
        return "results"
    if LIMIT.search(title) or LIMIT.search(paragraph["text"]):
        return "limitations_candidate"
    return "abstract" if paragraph["source_section"] == "abstract" else "other"


def context_candidates(claim, paragraph, passages, wanted):
    words = tokens(claim)
    selected = []
    for item in passages:
        # Exact source paragraph exclusion prevents the claim from proving itself.
        if item["id"] == paragraph["id"] or item["semantic_role"] != wanted or normalized_quote(claim) in normalized_quote(item["text"]):
            continue
        score = len(words & tokens(item["text"])) / max(1, len(words))
        selected.append((score, -abs(item["paragraph_index"] - paragraph["paragraph_index"]), item))
    selected.sort(key=lambda x: (x[0], x[1], x[2]["id"]), reverse=True)
    return [{"role": wanted, "selection_method": "fixed_lexical_overlap_then_source_distance_not_entailment",
             "selection_score": round(score, 6), "support_label": None, "anchor": source_locator(item)}
            for score, _, item in selected[:2]]


def span_cues(text, regex, absolute_start):
    return [{"text": match[0], "start": match.start(), "end": match.end(),
             "source_text_start": absolute_start + match.start(), "source_text_end": absolute_start + match.end()}
            for match in regex.finditer(text)]


def packets_for(document, passages, max_claims):
    candidates = []
    for paragraph in passages:
        for start, end, text in sentence_spans(paragraph["text"]):
            if not 90 <= len(text) <= 1500 or not CLAIM.search(text) or BOILER.search(text):
                continue
            score = (4 * bool(re.search(r"\b(?:we|our)\b", text, re.I))
                     + 3 * bool(RESULT.search(text)) + 2 * bool(NUMBER.search(text))
                     + 2 * (paragraph["semantic_role"] in {"results", "methods"}) + bool(CAUSAL.search(text)))
            candidates.append((score, digest(normalized_quote(text)), paragraph, start, end, text))
    # Different section-role queues stop all packets coming from the abstract or
    # longest results section. No repeated claim copies are used to hit a target.
    pools = defaultdict(list)
    for item in sorted(candidates, key=lambda x: (-x[0], x[1])):
        pools[item[2]["semantic_role"]].append(item)
    selected, seen = [], set()
    while any(pools.values()) and len(selected) < max_claims:
        for name in ("results", "methods", "abstract", "limitations_candidate", "other"):
            while pools[name]:
                candidate = pools[name].pop(0)
                if candidate[1] not in seen:
                    selected.append(candidate)
                    seen.add(candidate[1])
                    break
            if len(selected) == max_claims:
                break
    byid = {p["id"]: i for i, p in enumerate(passages)}
    for _, _, paragraph, start, end, claim in selected:
        anchor = source_locator(paragraph, start, end)
        claimid = "doxa-study-" + digest(document["id"] + ":" + str(anchor["source_text_start"]) + ":" + claim)[:24]
        contexts = {wanted: context_candidates(claim, paragraph, passages, wanted)
                    for wanted in ("methods", "results", "limitations_candidate")}
        index = byid[paragraph["id"]]
        adjacent = [admitted_neighbor(passages[x], paragraph) for x in (index - 1, index + 1)
                    if 0 <= x < len(passages) and passages[x]["source_section"] == paragraph["source_section"]]
        quantities = span_cues(claim, NUMBER, anchor["source_text_start"])
        table_refs = span_cues(claim, TABLE, anchor["source_text_start"])
        challenges = []
        for condition, kind, question in (
            (quantities, "numerical_scope", "What population, denominator, time period, outcome, uncertainty and table/estimate support each quantity? Are these available or unresolved?"),
            (CAUSAL.search(claim), "causal_scope", "Is the wording associational or causal? Identify the design, comparison, assumptions and limitations before deciding whether the causal strength is justified."),
            (MODAL.search(claim), "requirement_vs_event", "Does this span describe a requirement, recommendation, hypothesis or observed event? Locate evidence of actual occurrence before treating an obligation as an event."),
        ):
            if condition:
                challenges.append({"kind": kind, "question": question, "authoring": "doxa_rule_authored_review_prompt",
                                   "source_anchor": anchor, "gold_answer": None, "annotation_status": "unannotated"})
        refs = [{**ref, "start": ref["start"] - start, "end": ref["end"] - start}
                for ref in paragraph["reference_spans"] if start <= ref["start"] and ref["end"] <= end]
        yield {"record_type": "unannotated_study_claim_context", "id": claimid, "document_id": document["id"],
               "document_group": document["document_group"], "source_role": document["source_role"],
               "prior_doxa_source": document["prior_doxa_source"], "title": document["title"], "pmcid": document.get("pmcid"),
               "source_url": document["url"], "license": document["license"], "claim": claim, "claim_sha256": digest(claim),
               "claim_anchor": anchor, "claim_role_candidate": paragraph["semantic_role"],
               "claim_extraction_method": RULE_VERSION + ":verbatim_sentence_scientific_cue_selection",
               "focal_paragraph": source_locator(paragraph), "adjacent_context": adjacent,
               "methods_candidates": contexts["methods"], "results_candidates": contexts["results"],
               "limitations_candidates": contexts["limitations_candidate"],
               "context_coverage": {name: "candidate_found_not_verified" if items else "not_detected_or_claim_self_match_excluded"
                                    for name, items in contexts.items()},
               "citation_and_cross_reference_spans": refs, "numeric_mentions": quantities, "table_references": table_refs,
               "challenge_prompts": challenges,
               "counterevidence_retrieval": {"query": claim + " limitations alternative explanation robustness sensitivity null effect confounding",
                                            "method": "heuristic_query_expansion_not_counterevidence_label",
                                            "candidates": contexts["limitations_candidate"], "reference_judgment": None},
               "gold_label": None, "annotation_status": "unannotated", "annotation_origin": "deterministic_extraction_not_annotation",
               "human_review_count": 0, "supervised_training_eligible": False, "gold_evaluation_eligible": False,
               "retrieval_candidate_corpus_eligible": True,
               "retrieval_unsupervised_eligible": document["source_role"] == "train_candidate",
               "unsupervised_training_role": "candidate_training_source_only" if document["source_role"] == "train_candidate" else "reserved_development_or_test_do_not_fit",
               "limitations": ["Article authors' claims are not independently verified facts.",
                               "Lexical context candidates do not establish support, contradiction, omission or political bias.",
                               "No paper author ideology or demographic identity is inferred."]}


def write_rows(name, rows, work, stage):
    destination = work / (name + ".jsonl")
    with destination.open("w", encoding="utf-8") as output:
        for row in rows:
            output.write(json.dumps(row, ensure_ascii=False) + "\n")
    folder = stage / "data" / name
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / "corpus.parquet"
    pq.write_table(pa.Table.from_pylist(rows), path, compression="zstd")
    return {"rows": len(rows), "parquet_sha256": digest(path.read_bytes()), "parquet_bytes": path.stat().st_size,
            "jsonl_sha256": digest(destination.read_bytes())}


def main():
    global FROZEN_INPUT, RAW_OVERRIDE, FETCH_MISSING
    parser = argparse.ArgumentParser()
    parser.add_argument("--max-papers", type=int, default=320)
    parser.add_argument("--max-claims-per-paper", type=int, default=28)
    parser.add_argument("--work", type=Path, default=HERE / "work")
    parser.add_argument("--stage", type=Path, default=HERE / "stage")
    parser.add_argument("--input-articles", type=Path, help="Frozen sources/articles.jsonl.gz from a published dataset")
    parser.add_argument("--raw-xml-dir", type=Path, help="Local immutable raw XML cache (not redistributed)")
    parser.add_argument("--fetch-missing-xml", action="store_true", help="Fetch public original XML only when its exact SHA256 still matches")
    parser.add_argument("--quarantine-manifest", type=Path, help="Apply the complete frozen duplicate receipt when reproducing a source subset")
    args = parser.parse_args()
    FROZEN_INPUT, RAW_OVERRIDE, FETCH_MISSING = args.input_articles, args.raw_xml_dir, args.fetch_missing_xml
    args.work.mkdir(parents=True, exist_ok=True)
    args.stage.mkdir(parents=True, exist_ok=True)
    prior_path = OLD / "documents.jsonl"
    prior = read_jsonl(prior_path) if prior_path.exists() else []
    prior_keys = set().union(*(identity_keys(x) for x in prior)) if prior else set()
    fulltext_keys = set().union(*(identity_keys(x) for x in prior if x.get("text"))) if any(x.get("text") for x in prior) else set()
    papers, paragraphs, packets, failures, seen_sources, frozen_sources = [], [], [], [], set(), []
    sources = sorted(source_rows(), key=lambda x: (digest(x[0].get("pmcid") or x[0]["id"]), x[0]["id"]))
    for document, passages, source_path in sources:
        if len(papers) >= args.max_papers:
            break
        try:
            if document.get("text") is None:
                continue
            identity = (document.get("doi") or document.get("pmcid") or document["id"]).casefold()
            if identity in seen_sources:
                continue
            tree, raw_path = xml_source(document)
            rights = article_rights(tree)
            metadata, citations = source_metadata(tree)
            group = "study-source-" + digest(identity)[:24]
            prior_seen = bool(FROZEN_PRIOR.get(document["id"], False) or identity_keys(document) & prior_keys)
            prior_fulltext = bool(FROZEN_FULLTEXT.get(document["id"], False) or identity_keys(document) & fulltext_keys)
            bucket = int(digest(group)[:8], 16) % 100
            source_role = "train_candidate" if bucket < 70 else "development_candidate" if bucket < 85 else "frozen_test_candidate"
            d = {**document, "document_group": group, "prior_doxa_source": prior_seen, "source_role": source_role,
                 "prior_atlas_metadata": prior_seen, "prior_atlas_fulltext": prior_fulltext,
                 "prior_model_use": "not_established_by_catalogue_or_fulltext_membership_consult_source_use_ledger",
                 "source_dataset": "Giuliocc/doxa-research-atlas", "rights_receipt": rights,
                 "raw_xml_local_path": str(raw_path.relative_to(REPO)) if raw_path.is_relative_to(REPO) else str(raw_path), "input_record_sha256": digest(json.dumps(document, sort_keys=True, ensure_ascii=False)),
                 "paper_citations": citations, "supervised_training_eligible": False, "gold_evaluation_eligible": False,
                 "whole_document_training_eligible": False,
                 "training_unit_policy": "original_source_text_is_anchor_archive_only_use_admitted_role_eligible_paragraph_units"}
            clean = []
            for passage in sorted(passages, key=lambda x: x["source_text_start"]):
                text = passage["text"]
                assert document["text"][passage["source_text_start"]:passage["source_text_end"]] == text, passage["id"]
                ordinal = re.search(r"\)\[(\d+)\]$", passage["source_xpath"])
                key = (passage["source_section"], int(ordinal[1])) if ordinal else None
                meta = metadata.get(key)
                if meta is None or meta["text"] != text:
                    raise ValueError("original XML paragraph locator mismatch: " + passage["id"])
                if meta["excluded"] or BOILER.search(text):
                    continue
                p = {**passage, "document_group": group, "source_role": source_role, "prior_doxa_source": prior_seen,
                     "source_xml_sha256": document["source_xml_sha256"], "section_path": meta["section_path"],
                     "reference_spans": meta["references"], "gold_label": None,
                     "third_party_figures_tables_supplements": "excluded", "annotation_status": "unannotated",
                     "retrieval_candidate_corpus_eligible": True,
                     "unsupervised_training_eligible": source_role == "train_candidate",
                     "supervised_training_eligible": False, "gold_evaluation_eligible": False}
                p["semantic_role"] = role(p)
                for ref in p["reference_spans"]:
                    assert text[ref["start"]:ref["end"]] == ref["text"], passage["id"]
                clean.append(p)
            has_claim = any(90 <= len(text) <= 1500 and CLAIM.search(text) and not BOILER.search(text)
                            for p in clean for _, _, text in sentence_spans(p["text"]))
            if not has_claim:
                failures.append({"document_id": document["id"], "reason": "no_eligible_verbatim_scientific_claim_sentences"})
                continue
            d["packet_count"] = 0
            d["admitted_paragraph_count"] = len(clean)
            papers.append(d)
            paragraphs.extend(clean)
            frozen_sources.append({"document": document, "passages": passages, "prior_doxa_source": prior_seen,
                                   "prior_atlas_fulltext": prior_fulltext, "whole_document_training_eligible": False})
            seen_sources.add(identity)
        except (ValueError, AssertionError, ET.ParseError) as exc:
            failures.append({"document_id": document["id"], "reason": str(exc)})
    external = json.loads(args.quarantine_manifest.read_text(encoding="utf-8")) if args.quarantine_manifest else None
    paragraphs, duplicate_receipt = quarantine_duplicates(paragraphs, external)
    grouped = defaultdict(list)
    for paragraph in paragraphs:
        grouped[paragraph["document_id"]].append(paragraph)
    for admitted in grouped.values():
        for index, paragraph in enumerate(admitted):
            # Replace inherited Atlas neighbor material with eligible pointers.
            # The immutable original context is still available in sources/.
            for name, neighbor in (("context_before", index - 1), ("context_after", index + 1)):
                paragraph[name] = (admitted_neighbor(admitted[neighbor], paragraph)
                                   if 0 <= neighbor < len(admitted) and admitted[neighbor]["source_section"] == paragraph["source_section"] else None)
    packets = []
    for document in papers:
        study_packets = list(packets_for(document, grouped[document["id"]], args.max_claims_per_paper))
        document["packet_count"] = len(study_packets)
        document["admitted_paragraph_count"] = len(grouped[document["id"]])
        packets.extend(study_packets)
    assert len({p["id"] for p in packets}) == len(packets)
    by_doc = {d["id"]: d for d in papers}
    for packet in packets:
        claim = packet["claim_anchor"]
        assert by_doc[packet["document_id"]]["text"][claim["source_text_start"]:claim["source_text_end"]] == packet["claim"]
        for key in ("methods_candidates", "results_candidates", "limitations_candidates"):
            assert all(x["anchor"]["paragraph_id"] != claim["paragraph_id"] for x in packet[key])
    manifests = {name: write_rows(name, rows, args.work, args.stage)
                 for name, rows in (("papers", papers), ("paragraphs", paragraphs), ("claim_packets", packets))}
    split = [{"document_id": d["id"], "pmcid": d.get("pmcid"), "doi": d.get("doi"),
              "document_group": d["document_group"], "source_role": d["source_role"],
              "prior_doxa_source": d["prior_doxa_source"], "source_text_sha256": d["source_text_sha256"],
              "prior_atlas_metadata": d["prior_atlas_metadata"], "prior_atlas_fulltext": d["prior_atlas_fulltext"],
              "whole_document_training_eligible": False,
              "source_xml_sha256": d["source_xml_sha256"], "packet_count": d["packet_count"],
              "gold_label": None, "supervised_training_eligible": False, "gold_evaluation_eligible": False}
             for d in papers]
    dump(args.work / "source_split_manifest.json", {"rule_version": RULE_VERSION, "split_usage": "candidate_source_roles_only_not_a_labeled_benchmark",
                                                   "seed_rule": "sha256(canonical DOI or PMCID), 70/15/15 buckets", "sources": split})
    counts = {"papers": len(papers), "paragraphs": len(paragraphs), "claim_packets": len(packets),
              "targets": {"papers_approximate": 300, "claim_packets_minimum": 5000},
              "targets_met": len(papers) >= 300 and len(packets) >= 5000,
              "new_to_prior_atlas_sources": sum(not d["prior_doxa_source"] for d in papers),
              "prior_atlas_metadata_papers": sum(d["prior_atlas_metadata"] for d in papers),
              "prior_atlas_fulltext_papers": sum(d["prior_atlas_fulltext"] for d in papers),
              "human_reviewed_political_claims": 0, "supervised_training_eligible_packets": 0, "gold_evaluation_eligible_packets": 0,
              "packet_roles": dict(Counter(x["claim_role_candidate"] for x in packets)),
              "challenge_kinds": dict(Counter(c["kind"] for p in packets for c in p["challenge_prompts"])),
              "context_coverage": {k: sum(bool(x[k]) for x in packets) for k in ("methods_candidates", "results_candidates", "limitations_candidates")},
              "licenses": dict(Counter(x["license"]["identifier"] for x in papers)),
              "rule_version": RULE_VERSION, "tables": manifests,
              "rejected_or_missing": len(failures), "spent_usd": 0,
              "source_input_files": len(sources), "third_party_figures_tables_supplements_included": False}
    counts["quarantined_cross_document_duplicate_groups"] = duplicate_receipt["duplicate_groups"]
    counts["quarantined_paragraph_positions"] = duplicate_receipt["quarantined_positions_in_this_build"]
    dump(args.work / "counts.json", counts)
    dump(args.work / "exclusions.json", failures)
    dump(args.work / "duplicate_quarantine.json", duplicate_receipt)
    for name in ("counts.json", "source_split_manifest.json", "exclusions.json", "duplicate_quarantine.json"):
        shutil.copy2(args.work / name, args.stage / name)
    sourcefolder = args.stage / "sources"
    sourcefolder.mkdir(exist_ok=True)
    sourcebytes = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in frozen_sources).encode("utf-8")
    (sourcefolder / "articles.jsonl.gz").write_bytes(gzip.compress(sourcebytes, mtime=0))
    dump(sourcefolder / "raw_xml_fetch_receipts.json", [{"pmcid": d.get("pmcid"), "url": d["fulltext_source_url"],
                                                        "expected_decompressed_sha256": d["source_xml_sha256"],
                                                        "raw_xml_not_redistributed": "may_contain_third_party_figures_tables_supplements"} for d in papers])
    tools = args.stage / "tools"
    tools.mkdir(exist_ok=True)
    if Path(__file__).resolve() != (tools / "build_study.py").resolve():
        shutil.copy2(__file__, tools / "build_study.py")
    print(json.dumps(counts, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()