diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml new file mode 100644 index 000000000..771289d05 --- /dev/null +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -0,0 +1,159 @@ +name: R06 D2 structured runtime compatibility + +on: + push: + branches: + - r06-d2-structured-runtime-compat-0929-sol + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + pull_request: + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-d2-structured-runtime-compat + cancel-in-progress: true + +jobs: + compatibility: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + STRUCTURED_RUNTIME_BASE_SHA: 1d5638f574b697a984fef008e0e16a093f34220e + D2_AUTHORITY_SHA: 6ed0a9e8f390dea7c12c05fb9e991ed6328d1458 + D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 + PYTHONDONTWRITEBYTECODE: "1" + steps: + - name: Resolve expected head + id: head + shell: bash + env: + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EVENT_SHA: ${{ github.sha }} + run: | + set -euo pipefail + expected="${PR_HEAD_SHA:-$EVENT_SHA}" + test -n "$expected" + echo "sha=$expected" >> "$GITHUB_OUTPUT" + + - name: Checkout exact current-package candidate + uses: actions/checkout@v4 + with: + ref: ${{ steps.head.outputs.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Prove package lineage and exact checkout + shell: bash + env: + EXPECTED_HEAD: ${{ steps.head.outputs.sha }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + git merge-base --is-ancestor "$STRUCTURED_RUNTIME_BASE_SHA" HEAD + test "$(git merge-base "$STRUCTURED_RUNTIME_BASE_SHA" HEAD)" = "$STRUCTURED_RUNTIME_BASE_SHA" + test -z "$(git status --porcelain)" + echo "D2_STRUCTURED_RUNTIME_BASE=$STRUCTURED_RUNTIME_BASE_SHA" + echo "D2_RUNTIME_PREINTEGRATION_HEAD=$EXPECTED_HEAD" + + - name: Extract exact D2 authority read-only + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority" + rm -rf "$authority" + mkdir -p "$authority" + git fetch --no-tags origin "$D2_AUTHORITY_SHA" + test "$(git cat-file -t "$D2_AUTHORITY_SHA")" = "commit" + git archive "$D2_AUTHORITY_SHA" "$D2_AUTHORITY_REL" | tar -x -C "$authority" + root="$authority/$D2_AUTHORITY_REL" + test -f "$root/D2_CORRECTED_NODE_HASH_INDEX.json" + test -f "$root/D2_FULL_CORRECTED_AGGREGATION_MANIFEST.json" + test -f "$root/evidence_hash_index.json" + echo "D2_RUNTIME_PREINTEGRATION_AUTHORITY=$D2_AUTHORITY_SHA" + + - name: Run compatibility-tool regressions + shell: bash + run: | + set -euo pipefail + python - <<'PY' + from pathlib import Path + path = Path("tools/validate_dev2_corrected_runtime_compat.py") + compile(path.read_text(encoding="utf-8"), str(path), "exec") + PY + python -m unittest tools/test_validate_dev2_corrected_runtime_compat.py -v + + - name: Run exact D2 through current-package runtime + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority/$D2_AUTHORITY_REL" + pack="$RUNNER_TEMP/R06_D2_PREINTEGRATION_ONLY.zip" + report="$RUNNER_TEMP/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json" + python tools/validate_dev2_corrected_runtime_compat.py --authority-root "$authority" --pack-out "$pack" --report "$report" + python - "$report" <<'PY' + import json + import pathlib + import sys + report = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) + assert report["status"] == "COMPATIBILITY_PASS / PROMOTION_BLOCKED", report + assert report["authority"]["node_count"] == 386, report + assert report["authority"]["evidence_count"] == 184, report + assert report["authority"]["independent_audit"] == "PENDING", report + runtime = report["current_package_runtime"] + assert runtime["repository_nodes"] == 386, runtime + assert runtime["self_grade_correct"] == 386, runtime + assert runtime["runtime_load_pass"] == 386, runtime + assert runtime["structured_witness_count"] == 11, runtime + assert len(runtime["structured_witness_node_ids"]) == 11, runtime + assert runtime["runtime_fallback_count"] == 0, runtime + assert runtime["runtime_fallback_node_ids"] == [], runtime + pack = report["preintegration_content_pack"] + assert pack["node_count"] == 386, pack + assert pack["structured_witness_count"] == 11, pack + assert pack["structured_witness_node_ids"] == runtime["structured_witness_node_ids"], (pack, runtime) + assert pack["runtime_fallback_count"] == 0, pack + assert pack["runtime_fallback_node_ids"] == [], pack + assert report["promotion_allowed"] is False, report + print("D2_STRUCTURED_RUNTIME_COMPAT_PASS nodes=386 self_grade=386 runtime_load=386 structured=11 fallbacks=0") + PY + + - name: Prove worktree stayed immutable + shell: bash + run: | + set -euo pipefail + dirty="$(git status --porcelain)" + if [[ -n "$dirty" ]]; then + echo "D2_RUNTIME_PREINTEGRATION_WORKTREE_DIRTY" >&2 + printf '%s\n' "$dirty" >&2 + exit 1 + fi + echo "D2_RUNTIME_PREINTEGRATION_READ_ONLY_PASS" + + - name: Upload read-only compatibility evidence + uses: actions/upload-artifact@v4 + with: + name: r06-d2-structured-runtime-compat-${{ steps.head.outputs.sha }} + path: | + ${{ runner.temp }}/R06_D2_PREINTEGRATION_ONLY.zip + ${{ runner.temp }}/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json + if-no-files-found: error + retention-days: 30 diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py new file mode 100644 index 000000000..03c0e4b61 --- /dev/null +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import copy +import json +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +for entry in ( + REPO_ROOT / "runtime_engine", + REPO_ROOT / "runtime_engine" / "tests", + REPO_ROOT / "tools", +): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from fixtures import LN01_N03 +from scripture_archive_runtime.content_packs import ContentPackStore, inspect_content_pack +from validate_dev2_corrected_runtime_compat import ( + PACK_ID, + PACK_VERSION, + PARALLEL_WITNESS_FALLBACK_REASON, + CompatibilityError, + _project_nodes_for_current_runtime, + _runtime_compatibility, + write_preintegration_pack, +) + + +class D2CorrectedRuntimeCompatibilityTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_pack_writer_is_deterministic_and_installable(self) -> None: + node = copy.deepcopy(LN01_N03) + first = self.root / "first.zip" + second = self.root / "second.zip" + a = write_preintegration_pack([node], first, expected_node_count=1) + b = write_preintegration_pack([copy.deepcopy(node)], second, expected_node_count=1) + self.assertEqual(first.read_bytes(), second.read_bytes()) + self.assertEqual(a["archive_sha256"], b["archive_sha256"]) + inspected = inspect_content_pack(first) + self.assertEqual(PACK_ID, inspected.manifest.pack_id) + self.assertEqual(PACK_VERSION, inspected.manifest.version) + self.assertEqual(1, inspected.node_count) + + def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self) -> None: + node = copy.deepcopy(LN01_N03) + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["repository_nodes"]) + self.assertEqual(1, runtime["self_grade_correct"]) + self.assertEqual(1, runtime["runtime_load_pass"]) + + archive = self.root / "fixture.zip" + write_preintegration_pack([node], archive, expected_node_count=1) + store = ContentPackStore(self.root / "store") + inspected = store.install(archive) + self.assertEqual(1, inspected.node_count) + store.activate(PACK_ID, PACK_VERSION) + self.assertEqual({PACK_ID: PACK_VERSION}, store.active_versions()) + + def _parallel_witness_fixture(self): + node = copy.deepcopy(LN01_N03) + synthesis = "Witness-safe synthesis for current-runtime compatibility." + witnesses = ["Luke 22:8"] + node["task_type"] = "PARALLEL_WITNESS_COMPARE" + node["response_mode"] = "PARALLEL_WITNESS_COMPARE" + node["task_family"] = "parallel_witness_compare" + node["accepted_answer"] = {"synthesis": synthesis, "witnesses": witnesses} + node["accepted_variants"] = { + "synthesis_aliases": [synthesis], + "witnesses": witnesses, + } + node["grading"] = { + "accepted_propositions": [ + {"id": "P1", "required": True, "aliases": [synthesis]} + ], + "provenance_required": True, + "required_witnesses": witnesses, + } + node["response_contract"] = { + "kind": "witness_compare", + "answer_dto": { + "shape": "object", + "fields": {"synthesis": "string", "witnesses": "array[passage]"}, + }, + } + node["runtime_fallback"] = { + "task_type": "LONG_TEXT", + "accepted_answer": synthesis, + "reason": PARALLEL_WITNESS_FALLBACK_REASON, + } + return node + + def test_parallel_witness_structured_path_is_lossless_and_source_immutable(self) -> None: + node = self._parallel_witness_fixture() + original = copy.deepcopy(node) + projected, structured_ids = _project_nodes_for_current_runtime([node]) + self.assertEqual(original, node) + self.assertEqual([node["node_id"]], structured_ids) + self.assertEqual("PARALLEL_WITNESS_COMPARE", projected[0]["task_type"]) + self.assertEqual(node["accepted_answer"], projected[0]["accepted_answer"]) + + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["structured_witness_count"]) + self.assertEqual([node["node_id"]], runtime["structured_witness_node_ids"]) + self.assertEqual(0, runtime["runtime_fallback_count"]) + self.assertEqual([], runtime["runtime_fallback_node_ids"]) + + def test_parallel_witness_historical_fallback_metadata_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["runtime_fallback"]["accepted_answer"] = "Different synthesis" + with self.assertRaisesRegex(CompatibilityError, "historical runtime_fallback metadata changed"): + _project_nodes_for_current_runtime([node]) + + def test_parallel_witness_truth_binding_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["grading"]["required_witnesses"] = ["Acts 1:1"] + with self.assertRaisesRegex(CompatibilityError, "structured witness truth bindings changed"): + _project_nodes_for_current_runtime([node]) + + def test_conflicting_explicit_grading_truth_fails_closed(self) -> None: + node = copy.deepcopy(LN01_N03) + node["grading"] = {"accepted_choice": "CONTRADICTS CANONICAL ANSWER"} + with self.assertRaisesRegex( + CompatibilityError, + "provenance rejects corrected node", + ): + _runtime_compatibility([node], expected_node_count=1) + + def test_missing_nonvisual_equivalent_fails_before_runtime_promotion(self) -> None: + node = copy.deepcopy(LN01_N03) + node["functional_nonvisual_equivalent"] = "" + with self.assertRaisesRegex( + CompatibilityError, + "current runtime rejected corrected D2 corpus", + ): + _runtime_compatibility([node], expected_node_count=1) + + def test_workflow_requalifies_when_runtime_or_bound_package_changes(self) -> None: + workflow = ( + REPO_ROOT + / ".github" + / "workflows" + / "r06-d2-corrected-runtime-preintegration.yml" + ).read_text(encoding="utf-8") + required_trigger_surfaces = ( + "tools/validate_dev2_corrected_runtime_compat.py", + "tools/test_validate_dev2_corrected_runtime_compat.py", + "tools/validate_dev2_evidence_bundle.py", + "runtime_engine/scripture_archive_runtime/**", + "lanes/dev1/repair_overlay/scripture_archive_platform/**", + "lanes/dev1/repair_overlay/frontend/**", + "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**", + ) + for trigger in required_trigger_surfaces: + self.assertGreaterEqual( + workflow.count(f" - '{trigger}'"), + 2, + f"push and pull_request must both requalify on {trigger}", + ) + self.assertIn('PYTHONDONTWRITEBYTECODE: "1"', workflow) + self.assertIn( + "STRUCTURED_RUNTIME_BASE_SHA: 1d5638f574b697a984fef008e0e16a093f34220e", + workflow, + ) + self.assertNotIn("PACKAGE_BASE_SHA:", workflow) + self.assertNotIn("76176fc3dcd246284366ba88619947ba2626c7d7", workflow) + self.assertNotIn("python -m py_compile tools/validate_dev2_corrected_runtime_compat.py", workflow) + self.assertIn('dirty="$(git status --porcelain)"', workflow) + self.assertIn("D2_RUNTIME_PREINTEGRATION_WORKTREE_DIRTY", workflow) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py new file mode 100644 index 000000000..bd0135d37 --- /dev/null +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,591 @@ +#!/usr/bin/env python3 +"""Read-only compatibility gate for the corrected R06 D2 Paul/Acts authority. + +This gate never promotes the D2 corpus and never mutates the packaged-app content +surface. It consumes an exact external authority snapshot, proves its corrected +hash/index/evidence bindings, then runs all 386 nodes through the current-package +runtime and a deterministic preintegration content-pack round trip. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import stat +import sys +import tempfile +import zipfile +from collections import Counter +from pathlib import Path +from typing import Any, Iterable, Mapping + +REPO_ROOT = Path(__file__).resolve().parents[1] +RUNTIME_ROOT = REPO_ROOT / "runtime_engine" +TOOLS_ROOT = REPO_ROOT / "tools" +for entry in (RUNTIME_ROOT, TOOLS_ROOT): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from scripture_archive_runtime.application import RuntimeApplication +from scripture_archive_runtime.content import ContentRepository +from scripture_archive_runtime.content_packs import ( + CONTENT_PACK_SCHEMA, + CONTENT_SCHEMA_VERSION, + MANIFEST_NAME, + ContentPackStore, + inspect_content_pack, +) +from scripture_archive_runtime.grading import GraderRegistry +from scripture_archive_runtime.models import Correctness +from scripture_archive_runtime.provenance import canonical_answer_dto, classify_provenance +from scripture_archive_runtime.security import ValidationError +from validate_dev2_evidence_bundle import validate_bundle as validate_composed_evidence + +SCHEMA = "R06_D2_CORRECTED_RUNTIME_PREINTEGRATION_v1" +AUTHORITY_SCHEMA = "R06_D2_CORRECTED_NODE_HASH_INDEX_v1" +EXPECTED_NODE_COUNT = 386 +EXPECTED_EVIDENCE_COUNT = 184 +EXPECTED_NODE_AGGREGATE = "ef77ae5d822e105050dedfa9a460325259fe079701ca69f385693aabcad0e661" +EXPECTED_EVIDENCE_AGGREGATE = "88e197fd1c91b7787040e81bdd066d959d42b8ba64ac01acac667ffd8ad346ba" +EXPECTED_STAGING_ZIP = "b681ea26d985eb754bde02a77254d40ab0920061edb9226fae7921a6740a06c0" +EXPECTED_MISSION_COUNTS = { + "PA-03": 53, + "PA-04": 63, + "PA-05": 61, + "PA-06": 43, + "PA-07": 61, + "PA-08": 105, +} +EXPECTED_PARTS = tuple(f"nodes/part_{index:03d}.jsonl" for index in range(1, 27)) +PACKAGE_EVIDENCE_REL = ( + "evidence/part_001.jsonl", + "evidence/part_002.jsonl", + "evidence/part_003.jsonl", + "evidence_hash_index.json", + "mission_metadata.json", +) +PACK_ID = "r06-d2-paul-acts-preintegration" +PACK_VERSION = "0.6.0-d2pre.1" +EXPECTED_STRUCTURED_WITNESS_COUNT = 11 +PARALLEL_WITNESS_FALLBACK_REASON = ( + "DEV5 pre-integration runtime lacks PARALLEL_WITNESS_COMPARE grader; " + "preserve structured canonical comparison and use text fallback only for compatibility testing." +) + + +class CompatibilityError(ValueError): + pass + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _canonical_bytes(value: Any) -> bytes: + return json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + +def _load_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise CompatibilityError(f"cannot load JSON {path}: {exc}") from exc + + +def _require_regular(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_file(): + raise CompatibilityError(f"missing or unsafe regular file: {label}") + + +def _reject_symlinks(root: Path) -> None: + if root.is_symlink() or not root.is_dir(): + raise CompatibilityError(f"missing or unsafe authority root: {root}") + for path in root.rglob("*"): + if path.is_symlink(): + raise CompatibilityError( + f"symlink forbidden in authority snapshot: {path.relative_to(root)}" + ) + + +def _load_evidence_ids(authority_root: Path) -> set[str]: + index = _load_json(authority_root / "evidence_hash_index.json") + if not isinstance(index, Mapping): + raise CompatibilityError("evidence_hash_index.json must be an object") + if index.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence record_count changed") + if index.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("evidence aggregate changed") + records = index.get("records") + if not isinstance(records, list): + raise CompatibilityError("evidence index records must be a list") + ids: set[str] = set() + for row in records: + if not isinstance(row, Mapping): + raise CompatibilityError("evidence index row must be an object") + evidence_id = row.get("id") + digest = row.get("sha256") + if not isinstance(evidence_id, str) or not evidence_id: + raise CompatibilityError("invalid evidence id") + if evidence_id in ids: + raise CompatibilityError(f"duplicate evidence id: {evidence_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid evidence SHA256: {evidence_id}") + ids.add(evidence_id) + if len(ids) != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence ID cardinality changed") + return ids + + +def load_corrected_nodes(authority_root: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]: + _reject_symlinks(authority_root) + index = _load_json(authority_root / "D2_CORRECTED_NODE_HASH_INDEX.json") + if not isinstance(index, Mapping): + raise CompatibilityError("corrected node hash index must be an object") + if index.get("schema") != AUTHORITY_SCHEMA: + raise CompatibilityError("unexpected corrected node hash-index schema") + if index.get("record_count") != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected node record_count changed") + if index.get("aggregate_sha256") != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError("corrected node aggregate changed") + if index.get("historical_staging_zip_sha256") != EXPECTED_STAGING_ZIP: + raise CompatibilityError("historical staging provenance pin changed") + if index.get("source_truth_changed") is not False: + raise CompatibilityError("corrected authority claims source-truth mutation") + if "INDEPENDENT_AUDIT_PENDING" not in str(index.get("status", "")): + raise CompatibilityError("corrected authority improperly promotes audit status") + if index.get("mission_counts") != EXPECTED_MISSION_COUNTS: + raise CompatibilityError( + f"corrected authority mission_counts changed: {index.get('mission_counts')}" + ) + + rows = index.get("records") + if not isinstance(rows, list): + raise CompatibilityError("corrected index records must be a list") + + expected: dict[str, tuple[str, str]] = {} + indexed_parts: set[str] = set() + for row in rows: + if not isinstance(row, Mapping): + raise CompatibilityError("corrected index row must be an object") + node_id = row.get("id") + digest = row.get("sha256") + part = row.get("part") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError("corrected index row has invalid id") + if node_id in expected: + raise CompatibilityError(f"duplicate corrected index node: {node_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid corrected SHA256: {node_id}") + if part not in EXPECTED_PARTS: + raise CompatibilityError(f"unexpected corrected part for {node_id}: {part}") + expected[node_id] = (digest.casefold(), str(part)) + indexed_parts.add(str(part)) + + if len(expected) != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected index unique-node count changed") + if indexed_parts != set(EXPECTED_PARTS): + raise CompatibilityError("corrected index does not cover all 26 canonical parts") + + nodes: dict[str, dict[str, Any]] = {} + mission_counts: Counter[str] = Counter() + for part in EXPECTED_PARTS: + path = authority_root / part + _require_regular(path, part) + for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + try: + node = json.loads(line) + except json.JSONDecodeError as exc: + raise CompatibilityError(f"invalid node JSONL at {part}:{line_number}") from exc + if not isinstance(node, dict): + raise CompatibilityError(f"node at {part}:{line_number} must be an object") + node_id = node.get("node_id") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError(f"node at {part}:{line_number} has invalid node_id") + if node_id in nodes: + raise CompatibilityError(f"duplicate corrected node_id: {node_id}") + indexed = expected.get(node_id) + if indexed is None: + raise CompatibilityError(f"unindexed corrected node: {node_id}") + digest = _sha256_bytes(_canonical_bytes(node)) + if digest != indexed[0]: + raise CompatibilityError(f"corrected record SHA256 mismatch: {node_id}") + if indexed[1] != part: + raise CompatibilityError(f"corrected part mismatch: {node_id}") + mission_id = node.get("mission_id") + if mission_id not in EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"unexpected D2 mission_id: {mission_id}") + mission_counts[str(mission_id)] += 1 + nodes[node_id] = node + + if set(nodes) != set(expected): + missing = sorted(set(expected) - set(nodes)) + extra = sorted(set(nodes) - set(expected)) + raise CompatibilityError( + f"corrected node ID set mismatch missing={missing[:5]} extra={extra[:5]}" + ) + if dict(sorted(mission_counts.items())) != EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"mission node counts changed: {dict(mission_counts)}") + + aggregate = _sha256_bytes( + "".join( + f"{node_id}\t{_sha256_bytes(_canonical_bytes(nodes[node_id]))}\n" + for node_id in sorted(nodes) + ).encode("utf-8") + ) + if aggregate != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError(f"recomputed corrected aggregate mismatch: {aggregate}") + + return [nodes[node_id] for node_id in sorted(nodes)], dict(index) + + +def _verify_evidence_binding( + nodes: Iterable[Mapping[str, Any]], + *, + authority_root: Path, + repo_root: Path, +) -> tuple[int, dict[str, Any]]: + evidence_ids = _load_evidence_ids(authority_root) + missing: list[tuple[str, str]] = [] + for node in nodes: + required = node.get("required_evidence") + if not isinstance(required, list) or not all(isinstance(value, str) for value in required): + raise CompatibilityError(f"{node.get('node_id')}: invalid required_evidence") + for evidence_id in required: + if evidence_id not in evidence_ids: + missing.append((str(node.get("node_id")), evidence_id)) + if missing: + raise CompatibilityError(f"nodes reference unknown evidence IDs: {missing[:10]}") + + package_root = repo_root / "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05" + for rel in PACKAGE_EVIDENCE_REL: + authority_path = authority_root / rel + package_path = package_root / rel + _require_regular(authority_path, f"authority/{rel}") + _require_regular(package_path, f"package/{rel}") + if authority_path.read_bytes() != package_path.read_bytes(): + raise CompatibilityError(f"current-package evidence drift: {rel}") + + evidence_report = validate_composed_evidence(repo_root) + if evidence_report.get("status") != "PASS": + raise CompatibilityError("current-package D2 evidence validator did not PASS") + if evidence_report.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("current-package evidence count changed") + if evidence_report.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("current-package evidence aggregate changed") + if evidence_report.get("independent_audit") != "PENDING": + raise CompatibilityError("current-package evidence audit status was promoted") + return len(evidence_ids), evidence_report + + +def _project_nodes_for_current_runtime( + nodes: Iterable[Mapping[str, Any]], +) -> tuple[list[dict[str, Any]], list[str]]: + """Validate structured D2 truth and return an exact deep-copy runtime view. + + No compatibility downgrade is allowed here. Structured parallel-witness + nodes must remain structured so this gate exercises the actual current + runtime contract introduced by the package candidate. + """ + projected: list[dict[str, Any]] = [] + structured_node_ids: list[str] = [] + expected_fields = {"synthesis": "string", "witnesses": "array[passage]"} + allowed_contract_kinds = {"witness_compare", "parallel_witness_compare"} + + for source in nodes: + node = copy.deepcopy(dict(source)) + if str(node.get("task_type") or "") != "PARALLEL_WITNESS_COMPARE": + projected.append(node) + continue + + node_id = str(node.get("node_id") or "") + accepted = node.get("accepted_answer") + if not isinstance(accepted, Mapping) or set(accepted) != {"synthesis", "witnesses"}: + raise CompatibilityError( + f"{node_id}: PARALLEL_WITNESS_COMPARE requires structured synthesis+witnesses authority" + ) + synthesis = accepted.get("synthesis") + witnesses = accepted.get("witnesses") + if not isinstance(synthesis, str) or not synthesis.strip(): + raise CompatibilityError(f"{node_id}: structured synthesis must be non-empty string") + if ( + not isinstance(witnesses, list) + or not witnesses + or not all(isinstance(value, str) and value.strip() for value in witnesses) + ): + raise CompatibilityError(f"{node_id}: structured witnesses must be a non-empty string list") + + contract = node.get("response_contract") + dto = contract.get("answer_dto") if isinstance(contract, Mapping) else None + if ( + not isinstance(contract, Mapping) + or contract.get("kind") not in allowed_contract_kinds + or not isinstance(dto, Mapping) + or dto.get("shape") != "object" + or dto.get("fields") != expected_fields + ): + raise CompatibilityError(f"{node_id}: structured witness response_contract changed") + + variants = node.get("accepted_variants") + grading = node.get("grading") + if ( + not isinstance(variants, Mapping) + or variants.get("witnesses") != witnesses + or not isinstance(variants.get("synthesis_aliases"), list) + or synthesis not in variants.get("synthesis_aliases", []) + or not isinstance(grading, Mapping) + or grading.get("required_witnesses") != witnesses + ): + raise CompatibilityError(f"{node_id}: structured witness truth bindings changed") + + # The authority still carries historical fallback metadata as provenance + # of the pre-integration period. Verify it exactly, but do not execute it. + fallback = node.get("runtime_fallback") + if ( + not isinstance(fallback, Mapping) + or set(fallback) != {"accepted_answer", "reason", "task_type"} + or fallback.get("task_type") != "LONG_TEXT" + or fallback.get("accepted_answer") != synthesis + or fallback.get("reason") != PARALLEL_WITNESS_FALLBACK_REASON + ): + raise CompatibilityError(f"{node_id}: historical runtime_fallback metadata changed") + + projected.append(node) + structured_node_ids.append(node_id) + + return projected, sorted(structured_node_ids) + + +def _runtime_compatibility( + nodes: list[dict[str, Any]], + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: + runtime_nodes, structured_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(structured_node_ids) != EXPECTED_STRUCTURED_WITNESS_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_STRUCTURED_WITNESS_COUNT} structured parallel-witness nodes, got {len(structured_node_ids)}" + ) + try: + repository = ContentRepository(runtime_nodes, adapt_legacy=True, lane="D2") + except (ValidationError, ValueError, TypeError) as exc: + raise CompatibilityError(f"current runtime rejected corrected D2 corpus: {exc}") from exc + tasks = repository.all() + if len(tasks) != expected_node_count: + raise CompatibilityError("runtime repository did not retain expected nodes") + + grader = GraderRegistry() + app = RuntimeApplication(repository) + provenance_counts: Counter[str] = Counter() + self_grade_failures: list[str] = [] + runtime_load_failures: list[str] = [] + structured_runtime_ids: list[str] = [] + + for node_id in sorted(tasks): + task = tasks[node_id] + decision = classify_provenance(task.raw) + provenance_counts[decision.provenance_class] += 1 + if not decision.release_pass: + raise CompatibilityError( + f"{node_id}: current runtime provenance rejects corrected node: {decision.reason}" + ) + if node_id in structured_node_ids: + if task.task_type != "PARALLEL_WITNESS_SYNTHESIS": + raise CompatibilityError( + f"{node_id}: structured witness authority did not derive PARALLEL_WITNESS_SYNTHESIS" + ) + structured_runtime_ids.append(node_id) + try: + answer = canonical_answer_dto(task.raw) + result = grader.grade(task, answer) + except Exception as exc: + raise CompatibilityError(f"{node_id}: self-grade raised {type(exc).__name__}: {exc}") from exc + if result.correctness is not Correctness.CORRECT or result.score != 1.0: + self_grade_failures.append(node_id) + try: + response = app.load_task(node_id) + rendered = response.get("task", {}) + if rendered.get("node_id") != node_id: + runtime_load_failures.append(node_id) + if not str(rendered.get("functional_nonvisual_equivalent", "")).strip(): + runtime_load_failures.append(node_id) + except Exception as exc: + raise CompatibilityError(f"{node_id}: runtime load raised {type(exc).__name__}: {exc}") from exc + + if self_grade_failures: + raise CompatibilityError(f"runtime self-grade failed: {self_grade_failures[:10]}") + if runtime_load_failures: + raise CompatibilityError(f"runtime task render failed: {runtime_load_failures[:10]}") + if sorted(structured_runtime_ids) != structured_node_ids: + raise CompatibilityError("structured runtime node set drifted") + + return { + "repository_nodes": len(tasks), + "self_grade_correct": expected_node_count, + "runtime_load_pass": expected_node_count, + "provenance_classes": dict(sorted(provenance_counts.items())), + "structured_witness_node_ids": structured_node_ids, + "structured_witness_count": len(structured_node_ids), + "runtime_fallback_node_ids": [], + "runtime_fallback_count": 0, + } + + +def _json_bytes(value: Any) -> bytes: + return ( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + + +def write_preintegration_pack( + nodes: list[dict[str, Any]], + destination: Path, + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: + destination = destination.expanduser().resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + runtime_nodes, structured_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(structured_node_ids) != EXPECTED_STRUCTURED_WITNESS_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_STRUCTURED_WITNESS_COUNT} structured parallel-witness nodes, got {len(structured_node_ids)}" + ) + payload = _json_bytes({"nodes": runtime_nodes}) + payload_name = "content/nodes.json" + manifest = { + "schema": CONTENT_PACK_SCHEMA, + "pack_id": PACK_ID, + "version": PACK_VERSION, + "content_schema_version": CONTENT_SCHEMA_VERSION, + "entry_points": [payload_name], + "files": {payload_name: _sha256_bytes(payload)}, + } + manifest_bytes = _json_bytes(manifest) + with zipfile.ZipFile( + destination, + "w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=9, + ) as archive: + for name, data in ((MANIFEST_NAME, manifest_bytes), (payload_name, payload)): + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = (stat.S_IFREG | 0o644) << 16 + archive.writestr(info, data) + + inspection = inspect_content_pack(destination) + if inspection.node_count != expected_node_count: + raise CompatibilityError("content-pack inspector did not see expected nodes") + if inspection.manifest.pack_id != PACK_ID or inspection.manifest.version != PACK_VERSION: + raise CompatibilityError("content-pack identity drifted") + + with tempfile.TemporaryDirectory() as temp: + store = ContentPackStore(Path(temp) / "store") + installed = store.install(destination) + if installed.node_count != expected_node_count: + raise CompatibilityError("content-pack store install lost expected nodes") + store.activate(PACK_ID, PACK_VERSION) + if store.active_versions().get(PACK_ID) != PACK_VERSION: + raise CompatibilityError("content-pack activation did not select D2 preintegration pack") + installed_payload = ( + Path(temp) + / "store" + / "packs" + / PACK_ID + / PACK_VERSION + / payload_name + ) + roundtrip = ContentRepository.from_json_files( + [installed_payload], + adapt_legacy=True, + lane="D2", + ) + roundtrip_nodes = roundtrip.all() + if len(roundtrip_nodes) != expected_node_count: + raise CompatibilityError("installed content pack runtime reload lost expected nodes") + for node_id in structured_node_ids: + if roundtrip_nodes[node_id].task_type != "PARALLEL_WITNESS_SYNTHESIS": + raise CompatibilityError( + f"{node_id}: installed pack lost structured parallel-witness contract" + ) + + return { + "pack_id": PACK_ID, + "version": PACK_VERSION, + "archive_sha256": _sha256_bytes(destination.read_bytes()), + "payload_sha256": manifest["files"][payload_name], + "node_count": inspection.node_count, + "file_count": inspection.file_count, + "structured_witness_node_ids": structured_node_ids, + "structured_witness_count": len(structured_node_ids), + "runtime_fallback_node_ids": [], + "runtime_fallback_count": 0, + } + + +def run(authority_root: Path, pack_out: Path) -> dict[str, Any]: + authority_root = authority_root.expanduser().resolve() + nodes, index = load_corrected_nodes(authority_root) + evidence_count, evidence_report = _verify_evidence_binding( + nodes, + authority_root=authority_root, + repo_root=REPO_ROOT, + ) + runtime_report = _runtime_compatibility(nodes) + pack_report = write_preintegration_pack(nodes, pack_out) + return { + "schema": SCHEMA, + "status": "COMPATIBILITY_PASS / PROMOTION_BLOCKED", + "authority": { + "node_count": len(nodes), + "corrected_node_aggregate_sha256": index["aggregate_sha256"], + "evidence_count": evidence_count, + "evidence_aggregate_sha256": evidence_report["aggregate_sha256"], + "historical_staging_zip_sha256": EXPECTED_STAGING_ZIP, + "source_truth_changed": False, + "independent_audit": "PENDING", + }, + "current_package_runtime": runtime_report, + "preintegration_content_pack": pack_report, + "promotion_allowed": False, + "promotion_blockers": [ + "final-head D2 hosted qualification must be terminal green", + "independent D2 QA verdict must be recorded", + "current-package composition must occur on its canonical lineage after those gates", + ], + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--authority-root", type=Path, required=True) + parser.add_argument("--pack-out", type=Path, required=True) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + try: + report = run(args.authority_root, args.pack_out) + except (CompatibilityError, ValidationError) as exc: + failure = {"schema": SCHEMA, "status": "FAIL", "error": str(exc)} + payload = json.dumps(failure, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="", file=sys.stderr) + return 1 + payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())