File size: 14,746 Bytes
abf7829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Apply exact-XML-subsection context boundaries to an immutable prior stage."""
from collections import Counter
import argparse
import hashlib
import json
from pathlib import Path
import shutil


def sha(value):
    return hashlib.sha256(value.encode() if isinstance(value, str) else value).hexdigest()


def rows(path):
    return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]


def write_rows(path, records):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("".join(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n" for row in records))


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n")


def patch_context(input_dir, scopes_file, output_dir):
    input_dir, output_dir = input_dir.resolve(), output_dir.resolve()
    if input_dir == output_dir or input_dir in output_dir.parents:
        raise ValueError("Use a separate output directory outside the immutable input stage")
    original_manifest_path = input_dir / "PUBLIC_FILES.json"
    original_manifest = json.loads(original_manifest_path.read_text())
    for item in original_manifest["files"]:
        relative = Path(item["path"])
        if relative.is_absolute() or ".." in relative.parts:
            raise ValueError("Unsafe input allowlist path")
        source = input_dir / relative
        if sha(source.read_bytes()) != item["sha256"]:
            raise ValueError("Immutable input file checksum changed: " + str(relative))
        target = output_dir / relative
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)
    originals = rows(input_dir / "data/licensed_context_packets.jsonl")
    mappings = {row["source_passage_id"]: row for row in rows(scopes_file)}
    if len(mappings) != len(originals):
        raise ValueError("Exact scope mapping must cover every source passage once")
    focal_unchanged = ["id", "source_passage_id", "source_document_id", "source_xpath", "text", "text_sha256",
                       "source_text_start", "source_text_end", "source_text_sha256", "source_xml_sha256"]
    packets, removed = [], []
    original_links = 0
    for original in originals:
        row = dict(original)
        mapping = mappings[row["source_passage_id"]]
        for field in ["source_document_id", "source_xml_sha256", "source_xpath"]:
            if row[field] != mapping[field]:
                raise ValueError("Scope mapping does not identify the exact preserved source")
        for field in ["source_region_xpath", "source_containing_section_xpath", "source_language"]:
            row[field] = mapping[field]
        row["context_scope_revision"] = "doxa-exact-xml-subsection-context-v1"
        row["neighbor_policy"] = "immediate_original_paragraph_in_same_exact_XML_region_and_closest_sec_ancestor_only; no gap or quarantine bridging"
        for side in ["before", "after"]:
            neighbor_id = row["context_" + side + "_passage_id"]
            if not neighbor_id:
                row["context_" + side + "_boundary"] = "no_admitted_immediate_original_neighbor"
                continue
            original_links += 1
            neighbor = mappings[neighbor_id]
            if any(mapping[key] != neighbor[key] for key in ["source_region_xpath", "source_containing_section_xpath", "source_language"]):
                removed.append({"packet_id": row["id"], "side": side, "neighbor_passage_id": neighbor_id,
                                "reason": "different_exact_XML_region_closest_section_or_language",
                                "focal_region_xpath": mapping["source_region_xpath"], "focal_section_xpath": mapping["source_containing_section_xpath"],
                                "neighbor_region_xpath": neighbor["source_region_xpath"], "neighbor_section_xpath": neighbor["source_containing_section_xpath"]})
                row["context_" + side] = ""
                row["context_" + side + "_passage_id"] = None
                row["context_" + side + "_boundary"] = "trimmed_at_exact_XML_subsection_boundary"
                if side == "before":
                    row["context_before_start"] = row["source_text_start"]
                else:
                    row["context_after_end"] = row["source_text_end"]
            else:
                row["context_" + side + "_boundary"] = "same_exact_XML_region_closest_section_and_language"
        row["context_view_sha256"] = sha(json.dumps({key: row[key] for key in ["context_before", "text", "context_after", "source_region_xpath", "source_containing_section_xpath", "context_scope_revision"]}, sort_keys=True, ensure_ascii=False))
        if any(row[key] != original[key] for key in focal_unchanged):
            raise ValueError("A focal source field changed")
        packets.append(row)
    by_id = {row["id"]: row for row in packets}
    old_exercises = rows(input_dir / "data/context_reference_exercises.jsonl")
    exercises, excluded_exercises = [], []
    for exercise in old_exercises:
        focal = by_id[exercise["focal_source_id"]]
        references = [by_id[identifier] for identifier in exercise["reference_source_ids"]]
        if all(focal["context_after_passage_id"] == reference["source_passage_id"]
               and focal["source_region_xpath"] == reference["source_region_xpath"]
               and focal["source_containing_section_xpath"] == reference["source_containing_section_xpath"] for reference in references):
            exercises.append(exercise)
        else:
            excluded_exercises.append({"id": exercise["id"], "reason": "reference_not_within_admitted_exact_XML_subsection_context", "focal_source_id": exercise["focal_source_id"], "reference_source_ids": exercise["reference_source_ids"]})
    write_rows(output_dir / "data/licensed_context_packets.jsonl", packets)
    write_rows(output_dir / "data/context_reference_exercises.jsonl", exercises)
    queue = rows(input_dir / "data/reviewer_queue.jsonl")
    for task in queue:
        task["context_view_sha256"] = by_id[task["source_record_id"]]["context_view_sha256"]
        task["context_scope_revision"] = "doxa-exact-xml-subsection-context-v1"
    write_rows(output_dir / "data/reviewer_queue.jsonl", queue)
    write_rows(output_dir / "audits/context_xml_scopes.jsonl", sorted(mappings.values(), key=lambda row: row["source_passage_id"]))
    write_rows(output_dir / "audits/trimmed_xml_neighbor_relations.jsonl", removed)
    write_rows(output_dir / "audits/excluded_context_reference_exercises.jsonl", excluded_exercises)
    counts = json.loads((input_dir / "audits/licensed_context_counts.json").read_text())
    counts["context_availability"] = {side: sum(bool(row["context_" + side]) for row in packets) for side in ["before", "after"]}
    counts["neighbor_policy"] = packets[0]["neighbor_policy"]
    counts["context_scope_revision"] = "doxa-exact-xml-subsection-context-v1"
    write_json(output_dir / "audits/licensed_context_counts.json", counts)
    matched_counts = json.loads((input_dir / "audits/matched_context_counts.json").read_text())
    matched_counts["context_reference_exercises"] = len(exercises)
    write_json(output_dir / "audits/matched_context_counts.json", matched_counts)
    receipt = {"revision": "doxa-context-exact-XML-subsection-patch-v0.1.1", "input_allowlist_sha256": sha(original_manifest_path.read_bytes()),
               "input_packet_file_sha256": sha((input_dir / "data/licensed_context_packets.jsonl").read_bytes()),
               "exact_scope_mapping_sha256": sha(scopes_file.read_bytes()), "focal_packets": len(packets),
               "focal_text_hash_ID_and_source_locator_changes": 0, "original_neighbor_relations": original_links,
               "trimmed_neighbor_relations": len(removed), "retained_neighbor_relations": original_links - len(removed),
               "original_reference_exercises": len(old_exercises), "admitted_reference_exercises": len(exercises),
               "excluded_reference_exercises": len(excluded_exercises), "new_independent_human_reviews": 0,
               "erratum": "v0.1.0 constrained neighbors to the same broad abstract/body source region and adjacent paragraph ordinal, but did not require the same nearest XML subsection. v0.1.1 stores exact region/closest-section paths and trims crossings. Original focal text and source identities are unchanged.",
               "original_stage_modified": False, "new_model_training": False,
               "limitations": "Exact XML containers define structural context boundaries and do not establish semantic support, political bias or human agreement."}
    write_json(output_dir / "audits/xml_context_patch_receipt.json", receipt)
    schema_path = output_dir / "contracts/context_packet.schema.json"
    schema = json.loads(schema_path.read_text())
    for key in ["source_region_xpath", "source_containing_section_xpath", "context_scope_revision", "context_view_sha256"]:
        if key not in schema["required"]:
            schema["required"].append(key)
        schema["properties"][key] = {"type": "string", "minLength": 1}
    schema["properties"]["context_scope_revision"] = {"const": "doxa-exact-xml-subsection-context-v1"}
    schema["properties"]["context_view_sha256"] = {"type": "string", "pattern": "^[0-9a-f]{64}$"}
    write_json(schema_path, schema)
    for filename in ["README.md", "REVIEW_GUIDE.md"]:
        path = output_dir / filename
        text = path.read_text().replace(str(len(old_exercises)) + " adjacent-reference", str(len(exercises)) + " adjacent-reference").replace("| Adjacent-reference exercises | " + str(len(old_exercises)), "| Adjacent-reference exercises | " + str(len(exercises))).replace("The " + str(len(old_exercises)) + " context-reference exercises", "The " + str(len(exercises)) + " context-reference exercises").replace("within the same source region", "within the same exact XML region and nearest subsection")
        if filename == "README.md":
            text += "\n## v0.1.1 structural-context correction\n\n" + receipt["erratum"] + " This removes **" + str(len(removed)) + " of " + str(original_links) + "** original neighbor relations and keeps **" + str(len(exercises)) + "** same-subsection reference exercises. Each record now exposes `source_region_xpath`, `source_containing_section_xpath`, a boundary outcome per side and an exact `context_view_sha256` for future review provenance. [ERRATUM.md](ERRATUM.md) records the original limitation and preservation checks.\n"
        path.write_text(text)
    (output_dir / "ERRATUM.md").write_text("# Context v0.1.1 erratum\n\n" + receipt["erratum"] + "\n\nAll 11,072 original focal passages, IDs, hashes and source locators remain identical. The earlier machine check established broad source-region adjacency, not nearest-subsection continuity. Of 18,786 original neighbor links, 5,782 crossed a closest XML section boundary; these are now empty context with an explicit boundary outcome rather than silently crossing.\n\nThe new boundary uses the nearest abstract/body ancestor and nearest `sec` ancestor, falling back to that exact region when no section exists. A neighbor must also satisfy the original same-document, original paragraph-ordinal and duplicate-quarantine rules. The section paths resolve to the pinned original XML nodes. Future reviewers can bind their review to the exact context-view hash.\n\nThe original published version is preserved. This patch does not retrain or qualify a model, establish semantic support, label authors biased or create human-reviewed annotations. Reference exercises whose adjacent evidence crosses this boundary are removed from the new view and recorded in an audit.\n")
    (output_dir / "CONTEXT_PATCH.md").write_text("""# Reproduce the structural context patch

The v0.1.0 input stage remains immutable. This release includes the exact paragraph-to-XML-region/nearest-section mapping under `audits/context_xml_scopes.jsonl`, with the original paragraph XPath and source XML hash. These paths were independently resolved against the original licensed XML files. The patch consumes this checked map, verifies original source identities/hashes/locators, preserves every focal field and trims context crossings. It does not download new text, request inference or upload anything.

```sh
python tools/apply_xml_subsection_patch.py \\
  --input-dir /path/to/original-v0.1.0-dataset \\
  --scopes audits/context_xml_scopes.jsonl \\
  --output-dir /path/to/new-v0.1.1-dataset
```

The serializer requires PyArrow; it sets one CPU and I/O thread. `audits/xml_context_patch_receipt.json` records the immutable input allowlist and packet hashes, map hash, focal-preservation result and exact trimmed/reference counts. The original source XML can be restored from each record's source URL and checked against `source_xml_sha256` for further independent scope verification. Context is structural reading assistance, not proof of claim support or bias.
""")
    tool_target = output_dir / "tools/apply_xml_subsection_patch.py"
    shutil.copy2(Path(__file__), tool_target)
    test_path = output_dir / "tools/test_context_contracts.py"
    test_text = test_path.read_text().replace("self.assertEqual(len(packets), 180)", "self.assertEqual(len(packets), " + str(len(exercises)) + ")")
    test_path.write_text(test_text)
    import pyarrow as pa
    import pyarrow.parquet as pq
    pa.set_cpu_count(1); pa.set_io_thread_count(1)
    for path in (output_dir / "data").glob("*.parquet"):
        records = rows(path.with_suffix(".jsonl"))
        pq.write_table(pa.Table.from_pylist(records), path, compression="zstd")
        if pq.read_table(path, use_threads=False).to_pylist() != records:
            raise ValueError("Patched public Parquet differs from exact JSONL")
    entries = []
    for path in sorted(output_dir.rglob("*")):
        if path.is_file() and path.name != "PUBLIC_FILES.json":
            if "__pycache__" in path.parts:
                path.unlink(); continue
            entries.append({"path": str(path.relative_to(output_dir)), "bytes": path.stat().st_size, "sha256": sha(path.read_bytes())})
    write_json(output_dir / "PUBLIC_FILES.json", {"revision": "doxa-context-public-allowlist-v0.1.1", "files": entries})
    print(json.dumps(receipt, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input-dir", type=Path, required=True)
    parser.add_argument("--scopes", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    args = parser.parse_args()
    patch_context(args.input_dir, args.scopes, args.output_dir)