diff --git a/.github/workflows/research-architecture.yml b/.github/workflows/research-architecture.yml index aa35e6ef2..4b53e755e 100644 --- a/.github/workflows/research-architecture.yml +++ b/.github/workflows/research-architecture.yml @@ -36,7 +36,8 @@ jobs: graph: name: research-architecture runs-on: ubuntu-24.04 - timeout-minutes: 10 + # Complete stage ceiling: 19 preparation + 11 tests + fourteen 1-minute stages. + timeout-minutes: 44 outputs: checked_commit: ${{ steps.accepted.outputs.checked_commit }} repository: ${{ steps.accepted.outputs.repository }} @@ -48,18 +49,252 @@ jobs: artifact_name: ${{ steps.accepted.outputs.artifact_name }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + timeout-minutes: 1 with: persist-credentials: false + fetch-depth: 0 - name: Parse both workflow sources with the hosted YAML parser + timeout-minutes: 1 run: | set -euo pipefail ruby -rpsych -e 'ARGV.each { |path| Psych.safe_load(File.read(path), aliases: false); puts "Parsed #{path}" }' .github/workflows/research-architecture.yml .github/workflows/workspace-landing.yml + - name: Extract whole-pinned qualified preparation sources + timeout-minutes: 1 + run: | + set -euo pipefail + python3 -I -B -S - "$RUNNER_TEMP" "$GITHUB_WORKSPACE" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" <<'PY' + import hashlib, json, os, pathlib, stat, sys + def require(value, message): + if not value: + raise ValueError(message) + def original(path, size, digest): + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + try: + before = os.fstat(descriptor) + require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and before.st_size == size, + 'qualified whole-source size/type mismatch') + raw = b'' + while len(raw) <= size: + part = os.read(descriptor, min(65536, size + 1 - len(raw))) + if not part: + break + raw += part + after = os.fstat(descriptor) + require((before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) + == (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + and len(raw) == size and hashlib.sha256(raw).hexdigest() == digest, + 'qualified whole-source changed or pin mismatch') + return raw + finally: + os.close(descriptor) + temporary, workspace = map(pathlib.Path, sys.argv[1:3]) + run_id, attempt = sys.argv[3:5] + require(run_id.isdecimal() and attempt.isdecimal(), 'native preparation path context') + workflow = original(workspace / '.github/workflows/architecture-runtime-acquisition.yml', 95714, + '9b33eee757bae53966a151150bc62bc6aec13f9aa8226b4398dfa3362597de65') + original(workspace / 'docs/plans/2026-10-09-public-runtime-acquisition.md', 22516, + '72bdcf2b2374216f415fb6d86b84c2db25e7855caf0699bdfe2473336fb64bb7') + destination = temporary / ('architecture-preparation-source-' + run_id + '-' + attempt) + destination.mkdir(mode=0o700, exist_ok=False) + lines = workflow.decode('ascii').splitlines() + selection = ( + ('write-sources.sh', 'Write fixed trusted preparation sources'), + ('run-preparation.sh', 'Parse the standalone source and run the preparation once'), + ('seal.sh', 'Seal available originals on every conclusion'), + ('cleanup.sh', 'Remove only owned preparation client and control files')) + for filename, name in selection: + starts = [index for index, line in enumerate(lines) if line == ' - name: ' + name] + require(len(starts) == 1, 'ambiguous qualified step marker') + start = starts[0] + end = next((index for index in range(start + 1, len(lines)) + if lines[index].startswith(' - ')), len(lines)) + block = lines[start:end] + markers = [index for index, line in enumerate(block) if line == ' run: |'] + require(len(markers) == 1, 'ambiguous qualified literal run source') + body = block[markers[0] + 1:] + require(body and all(line.startswith(' ') for line in body), + 'qualified literal script indentation') + raw = ('\n'.join(line[10:] for line in body) + '\n').encode('ascii') + descriptor = os.open(destination / filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o444) + with os.fdopen(descriptor, 'wb') as stream: + stream.write(raw) + print(json.dumps({'qualified_sources': 'PIN_MATCH', 'literal_scripts': len(selection)})) + PY + bash "$RUNNER_TEMP/architecture-preparation-source-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/write-sources.sh" + - name: Qualify canonical acquisition and restore daemon before tests + id: preparation + timeout-minutes: 19 + run: | + set -euo pipefail + bash "$RUNNER_TEMP/architecture-preparation-source-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/run-preparation.sh" + - name: Seal separate preparation originals on every conclusion + id: preparation_seal + if: always() + timeout-minutes: 1 + run: | + set -euo pipefail + bash "$RUNNER_TEMP/architecture-preparation-source-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/seal.sh" + - name: Retain separate bounded preparation originals + id: preparation_retained + if: always() + timeout-minutes: 1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: architecture-preparation-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/public-runtime-${{ github.run_id }}-${{ github.run_attempt }}/publish/ + if-no-files-found: error + retention-days: 90 + compression-level: 6 + - name: Remove only owned preparation and extraction files + id: preparation_cleanup + if: always() + timeout-minutes: 1 + run: | + set -euo pipefail + directory="$RUNNER_TEMP/architecture-preparation-source-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + bash "$directory/cleanup.sh" + python3 -I -B -S - "$directory" <<'PY' + import os, pathlib, stat, sys + directory = pathlib.Path(sys.argv[1]) + info = directory.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o700: + raise ValueError('owned extraction directory identity') + names = {'write-sources.sh', 'run-preparation.sh', 'seal.sh', 'cleanup.sh'} + if {path.name for path in directory.iterdir()} != names: + raise ValueError('closed owned extraction inventory') + for name in sorted(names): + path = directory / name + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid() or info.st_size > 1024 * 1024: + raise ValueError('owned extraction file identity/bound') + path.unlink() + directory.rmdir() + PY + - name: Require complete current-run preparation before architecture + timeout-minutes: 1 + env: + PREPARATION_ARTIFACT_ID: ${{ steps.preparation_retained.outputs.artifact-id }} + PREPARATION_ARTIFACT_DIGEST: ${{ steps.preparation_retained.outputs.artifact-digest }} + run: | + set -euo pipefail + python3 -I -B -S - "$RUNNER_TEMP/public-runtime-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/publish" <<'PY' + import hashlib, json, os, pathlib, re, stat, sys + MIB = 2**20 + def require(value, message): + if not value: + raise ValueError(message) + def read(path, limit): + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + try: + before = os.fstat(descriptor) + require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and before.st_size <= limit, + 'sealed preparation regular-file admission') + raw = b'' + while len(raw) <= limit: + part = os.read(descriptor, min(65536, limit + 1 - len(raw))) + if not part: + break + raw += part + after = os.fstat(descriptor) + require((before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) + == (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + and len(raw) == before.st_size <= limit, 'sealed preparation changed during read') + return raw + finally: + os.close(descriptor) + root = pathlib.Path(sys.argv[1]) + info = root.lstat() + require(stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid() + and stat.S_IMODE(info.st_mode) == 0o700, 'owned sealed preparation directory') + native = {key: os.environ[name] for key, name in ( + ('repository', 'GITHUB_REPOSITORY'), ('checked_commit', 'GITHUB_SHA'), + ('run_id', 'GITHUB_RUN_ID'), ('run_attempt', 'GITHUB_RUN_ATTEMPT'))} + require(re.fullmatch(r'[1-9][0-9]*', os.environ['PREPARATION_ARTIFACT_ID']) + and re.fullmatch(r'(?:sha256:)?[0-9a-f]{64}', os.environ['PREPARATION_ARTIFACT_DIGEST']), + 'native preparation upload identity unavailable') + manifest = {} + manifest_raw = read(root / 'ARTIFACT_SHA256SUMS', MIB) + for line in manifest_raw.decode('ascii').splitlines(): + match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line) + require(match is not None and match[2] not in manifest, 'closed preparation hash manifest') + manifest[match[2]] = match[1] + require(0 < len(manifest) <= 256 + and {path.name for path in root.iterdir()} == set(manifest) | {'ARTIFACT_SHA256SUMS'}, + 'exact sealed preparation inventory') + bodies, records, total = {}, {}, len(manifest_raw) + for name, digest in manifest.items(): + limit = 4 * MIB if name in ('pull.stdout', 'pull.stderr') else MIB + raw = read(root / name, limit) + total += len(raw) + require(total <= 36 * MIB and hashlib.sha256(raw).hexdigest() == digest, + 'sealed preparation original hash/aggregate bound') + bodies[name] = raw + records[name] = {'bytes': len(raw), 'sha256': digest} + receipt = json.loads(bodies['receipt.json']) + collection = json.loads(bodies['collection.json']) + result = json.loads(bodies['preparation-result.json']) + observation = json.loads(bodies['preparation-observations.json']) + semantic = json.loads(bodies['semantic-controls.json']) + for record in (receipt, collection): + require(record['status'] == 'ACCEPTED_PREPARATION' and record['native_context'] == native, + 'current-run sealed preparation acceptance required') + require(result['status'] == 'ACCEPTED_PREPARATION' and result['context'] == native + and observation['context'] == native and observation['head'] == native['checked_commit'] + and collection['missing'] == [] and collection['refused'] == [] + and result['preparation_error'] is None and result['recovery_error'] is None + and result['refused_originals'] == [], 'complete current-run preparation required') + rows = receipt['originals'] + joined = {row['path']: {'bytes': row['bytes'], 'sha256': row['sha256']} for row in rows} + require(len(joined) == len(rows) == receipt['original_count'] + and set(joined) == set(records) - {'receipt.json'} + and all(records[name] == record for name, record in joined.items()) + and receipt['original_bytes'] == sum(record['bytes'] for record in joined.values()), + 'receipt original copies/subtotal join') + copied = collection['copied'] + copies = {row['path']: {'bytes': row['bytes'], 'sha256': row['sha256']} for row in copied} + require(len(copies) == len(copied) and set(copies) == set(joined) - {'collection.json'} + and all(records[name] == record for name, record in copies.items()) + and set(copies) == set(result['available_originals']) | {'preparation-result.json'} + and all(copies[name] == record for name, record in result['available_originals'].items()), + 'collection/controller original copies join') + require(records['checked-workflow.yml'] == {'bytes': 95714, 'sha256': + '9b33eee757bae53966a151150bc62bc6aec13f9aa8226b4398dfa3362597de65'} + and records['contract.md'] == {'bytes': 22516, 'sha256': + '72bdcf2b2374216f415fb6d86b84c2db25e7855caf0699bdfe2473336fb64bb7'} + and observation['source_before'] == observation['source_after'], + 'qualified preparation whole sources stable') + negative_ids = ( + 'RP01_stale_run', 'RP01_changed_source', 'RP02_existing_container', 'RP02_cached_image', + 'RP03_missing_actual_mirror', 'RP03_changed_preserved_setting', 'RP04_manifest_substitution', + 'RP04_config_substitution', 'RP05_pull_nonzero', 'RP05_pull_incomplete', + 'RP06_mirror_prefixed_digest', 'RP06_extra_digest', 'RP06_wrong_image_platform', + 'RP07_native_root', 'RP07_missing_OO', 'RP08_wrong_sqlite_all_modes', 'RP08_wrong_OO_flag', + 'RP08_empty_binary_all_modes', 'RP09_wrong_CPU_all_modes', 'RP10_disposal_unconfirmed', + 'RP11_restored_mirror_wrong', 'RP11_restored_bytes_wrong', 'RP12_missing_original', + 'RP03_nested_synthetic_credential', 'RP09_oversized_overlay_lowerdir') + expected = [{'id': 'RP_positive_actual_copy', 'status': 'PASS'}] + expected += [{'id': name, 'status': 'REFUSED'} for name in negative_ids] + require(result['controls'] == semantic['controls'] == expected + and semantic['origin'] == 'TEST_SEMANTIC_MUTATIONS_OF_COPIED_ACTUAL_OBSERVATIONS', + 'all qualified actual-copy controls required') + require(observation['recovery_complete'] is True + and observation['containers_recovery_empty'] is True + and observation['containers_restored_empty'] is True + and observation['restored_mirrors'] == observation['original_mirrors'] + and set(observation['probes']) == {'0', '1', '2'} + and all(item['disposed'] is True for item in observation['probes'].values()) + and result['disposal_confirmed'] == {'0': True, '1': True, '2': True}, + 'owned probe disposal and daemon recovery before architecture') + print(json.dumps({'status': 'ACCEPTED_PREPARATION', 'current_run': native['run_id'], + 'positive': 'PASS', 'negative_refusals': len(negative_ids)})) + PY - name: Prepare fixed runtime and separate output + id: architecture_output + timeout-minutes: 1 env: IMAGE: python:3.11.14-slim-bookworm@sha256:83f339c1be6340ae1096010fdccf6552ac932d8f410d45d206014916bdf37e48 run: | set -euo pipefail - docker pull "$IMAGE" mkdir -p "$RUNNER_TEMP/architecture-evidence" "$RUNNER_TEMP/architecture-publish" chmod 0700 "$RUNNER_TEMP/architecture-publish" truncate -s 64M "$RUNNER_TEMP/architecture-output.img" @@ -75,12 +310,14 @@ jobs: printf '%s\n' "$GITHUB_RUN_ID" > "$RUNNER_TEMP/architecture-publish/run-id.txt" printf '%s\n' "$GITHUB_RUN_ATTEMPT" > "$RUNNER_TEMP/architecture-publish/run-attempt.txt" - name: Run controls and export in ephemeral restricted container + id: architecture_controls + timeout-minutes: 11 env: IMAGE: python:3.11.14-slim-bookworm@sha256:83f339c1be6340ae1096010fdccf6552ac932d8f410d45d206014916bdf37e48 run: | set -euo pipefail set +e - timeout --signal=TERM --kill-after=10s 300s docker run --rm --log-driver none --name architecture-controls \ + timeout --signal=TERM --kill-after=10s 600s docker run --pull=never --rm --log-driver none --name architecture-controls \ --network none --read-only --user 65532:65532 --cpus 2 --memory 1g --pids-limit 128 \ --cap-drop ALL --security-opt no-new-privileges \ --env ARCHITECTURE_SANDBOX=1 \ @@ -102,7 +339,8 @@ jobs: printf '%s\n' "$status" > "$RUNNER_TEMP/architecture-publish/container-exit-status.txt" exit "$status" - name: Dispose container even after timeout - if: always() + timeout-minutes: 1 + if: ${{ always() && (steps.architecture_controls.outcome == 'success' || steps.architecture_controls.outcome == 'failure' || steps.architecture_controls.outcome == 'cancelled') }} run: | set -euo pipefail present="$(docker ps -aq --filter 'name=^/architecture-controls$')" @@ -113,7 +351,8 @@ jobs: exit 1 fi - name: Stage only bounded regular outputs after container disposal - if: always() + timeout-minutes: 1 + if: ${{ always() && (steps.architecture_controls.outcome == 'success' || steps.architecture_controls.outcome == 'failure' || steps.architecture_controls.outcome == 'cancelled') }} run: | set -euo pipefail remaining="$(docker ps -aq --filter 'name=^/architecture-controls$')" @@ -151,6 +390,7 @@ jobs: done printf '::%s::\n' "$marker" - name: Accept current-run controls and exact staged graph before upload + timeout-minutes: 1 run: | set -euo pipefail destination="$RUNNER_TEMP/architecture-publish" @@ -158,8 +398,9 @@ jobs: cd "$destination" sha256sum architecture-run-receipt.json >> ARTIFACT_SHA256SUMS - name: Retain original controls, identities and generated graph + timeout-minutes: 1 id: retained - if: always() + if: ${{ always() && (steps.architecture_output.outcome == 'success' || steps.architecture_output.outcome == 'failure' || steps.architecture_output.outcome == 'cancelled') }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: name: research-architecture-${{ github.run_id }}-${{ github.run_attempt }} @@ -167,9 +408,11 @@ jobs: if-no-files-found: error retention-days: 90 - name: Release bounded output filesystem - if: always() + timeout-minutes: 1 + if: ${{ always() && (steps.architecture_output.outcome == 'success' || steps.architecture_output.outcome == 'failure' || steps.architecture_output.outcome == 'cancelled') }} run: sudo umount "$RUNNER_TEMP/architecture-evidence" - name: Emit accepted identities only after upload and cleanup succeed + timeout-minutes: 1 id: accepted env: NATIVE_ARTIFACT_ID: ${{ steps.retained.outputs.artifact-id }} diff --git a/architecture/evidence_adapter.py b/architecture/evidence_adapter.py new file mode 100644 index 000000000..780b13b8b --- /dev/null +++ b/architecture/evidence_adapter.py @@ -0,0 +1,1427 @@ +"""Validate inert evidence packets without authenticating custody or science. + +All current/stale decisions concern declared records inside the packet. Only the +independently pinned repository graph gate is executable; captures are data. +""" +from __future__ import annotations + +import base64 +import binascii +from dataclasses import dataclass +import hashlib +import json +import math +import os +from pathlib import Path, PurePosixPath +import re +import stat +from types import ModuleType +from typing import Any + + +MAX_PACKET_BYTES = 16 * 1024 * 1024 +MAX_CAPTURE_BYTES = 4 * 1024 * 1024 +MAX_DEPTH = 64 +MAX_GRAPH_NODES = 256 +MAX_GRAPH_EDGES = 2048 +TRUSTED_GATE_SHA256 = "a78f3e25f3b0cfe113e618a4c31a7a25d7f22af638c46dec1ecba221fa333ac8" +ROOT = Path(__file__).resolve().parents[1] +HEX40 = re.compile(r"[0-9a-f]{40}") +HEX64 = re.compile(r"[0-9a-f]{64}") +DECIMAL = re.compile(r"[1-9][0-9]*") +REPOSITORY = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") +NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_.']*") +AXIOM_LINE = re.compile( + r"'([A-Za-z_][A-Za-z0-9_.']*)' " + r"(?:depends on axioms: \[([^\]]*)\]|does not depend on any axioms)" +) +ALLOWED_AXIOMS = frozenset({"propext", "Classical.choice", "Quot.sound"}) +MAIN_TOOLCHAIN = "leanprover/lean4:v4.34.1" +MAIN_VERSION = re.compile(r"\bversion 4\.34\.1(?=[,\s)])") +MAIN_PUBLIC_REPOSITORIES = frozenset({ + "d6g8k5htny-coder/main", "d6g8k5htny-coder/Math-", "d6g8k5htny-coder/query-", + "d6g8k5htny-coder/meta-framework", "d6g8k5htny-coder/Universal-Law-Workspace", +}) +MAIN_EXECUTION_LOG_LABELS = frozenset({"version", "build", "leanchecker", "axioms", "elaborated-types"}) +STATES = frozenset({"recorded", "not_recorded", "unknown", "not_applicable"}) +AXES = ("source", "review", "kernel", "computation", "alignment") +PLACEHOLDERS = frozenset({ + "unknown", "unverified", "not known", "not available", "not provided", "unavailable", "unspecified", + "pending", "tbd", "todo", "none", "null", "n/a", "na", "?", "-", +}) + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=True, allow_nan=False) + + +def keys(value: Any, expected: set[str], label: str) -> dict[str, Any]: + require(type(value) is dict and set(value) == expected, label + ": invalid fields") + return value + + +def text(value: Any, label: str) -> str: + require(type(value) is str and bool(value.strip()), label + ": expected nonempty string") + return value + + +def digest(value: Any, pattern: re.Pattern[str], label: str) -> str: + require(type(value) is str and pattern.fullmatch(value) is not None, + label + ": invalid identity") + return value + + +def repository(value: Any, label: str) -> str: + digest(value, REPOSITORY, label) + require(all(part not in (".", "..") for part in value.split("/")), + label + ": invalid repository") + return value + + +def relative_path(value: Any, label: str) -> str: + text(value, label) + require(not value.startswith("/") and "\\" not in value + and not any(ord(char) < 32 or ord(char) == 127 for char in value), + label + ": unsafe path") + require(all(part not in ("", ".", "..") for part in value.split("/")) + and PurePosixPath(value).as_posix() == value, + label + ": nonnormalized path") + return value + + +def positive_decimal(value: Any, label: str) -> str: + return digest(value, DECIMAL, label) + + +def _git_reference(value: Any, label: str) -> dict[str, Any]: + """Validate a declared closed GitRef without fetching or authenticating it.""" + ref = keys(value, {"repository", "commit", "path", "git_blob", "sha256", "bytes"}, label) + repository(ref["repository"], label + " repository") + digest(ref["commit"], HEX40, label + " commit") + relative_path(ref["path"], label + " path") + digest(ref["git_blob"], HEX40, label + " blob") + digest(ref["sha256"], HEX64, label + " SHA256") + require(type(ref["bytes"]) is int and 0 <= ref["bytes"] <= MAX_CAPTURE_BYTES, + label + ": invalid byte count") + return ref + + +def _depth_and_types(value: Any, depth: int = 0) -> None: + require(depth <= MAX_DEPTH, "JSON nesting exceeds limit") + if type(value) is dict: + require(all(type(key) is str for key in value), "nonstring JSON key") + for child in value.values(): + _depth_and_types(child, depth + 1) + elif type(value) is list: + for child in value: + _depth_and_types(child, depth + 1) + elif type(value) is float: + require(math.isfinite(value), "nonfinite JSON number") + else: + require(value is None or type(value) in (str, int, bool), "non-JSON value") + + +def strict_json(raw: bytes, label: str, *, limit: int = MAX_CAPTURE_BYTES) -> Any: + require(type(raw) is bytes and len(raw) <= limit, label + ": JSON byte limit") + decoded = raw.decode("utf-8") + # Bound nesting before the decoder recurses, accounting for escaped strings. + depth = 0 + quoted = False + escaped = False + for char in decoded: + if quoted: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == '"': + quoted = False + elif char == '"': + quoted = True + elif char in "[{": + depth += 1 + require(depth <= MAX_DEPTH, label + ": JSON nesting exceeds limit") + elif char in "]}": + depth -= 1 + + def unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + require(key not in result, label + ": duplicate JSON key") + result[key] = value + return result + + def constant(value: str) -> Any: + raise ValueError(label + ": nonfinite JSON constant") + + def floating(value: str) -> float: + result = float(value) + require(math.isfinite(result), label + ": nonfinite JSON number") + return result + + result = json.loads(decoded, object_pairs_hook=unique, + parse_constant=constant, parse_float=floating) + _depth_and_types(result) + return result + + +def parse_packet(raw: bytes) -> dict[str, Any]: + result = strict_json(raw, "packet", limit=MAX_PACKET_BYTES) + require(type(result) is dict, "packet must be object") + return result + + +def validate_expected_context(value: dict[str, str]) -> dict[str, str]: + keys(value, {"repository", "commit", "run-id", "run-attempt"}, "expected context") + repository(value["repository"], "expected repository") + digest(value["commit"], HEX40, "expected commit") + positive_decimal(value["run-id"], "expected run id") + positive_decimal(value["run-attempt"], "expected run attempt") + return value + + +@dataclass(frozen=True) +class Capture: + ref: dict[str, Any] + raw: bytes + + def document(self, label: str) -> dict[str, Any]: + result = strict_json(self.raw, label) + require(type(result) is dict, label + ": expected JSON object") + return result + + +class Captures: + """Verified identities shared across every capture role in one packet.""" + + def __init__(self) -> None: + self.git_identities: dict[tuple[str, str, str], Capture] = {} + self.run_identities: dict[tuple[str, ...], Capture] = {} + + @staticmethod + def raw(value: dict[str, Any], label: str) -> bytes: + encoded = value["raw_base64"] + require(type(encoded) is str and len(encoded) <= 4 * ((MAX_CAPTURE_BYTES + 2) // 3), + label + ": encoded capture exceeds limit") + try: + raw = base64.b64decode(encoded.encode("ascii"), validate=True) + except (UnicodeError, binascii.Error, ValueError) as exc: + raise ValueError(label + ": invalid base64") from exc + require(len(raw) <= MAX_CAPTURE_BYTES + and base64.b64encode(raw).decode("ascii") == encoded, + label + ": noncanonical or oversized base64") + return raw + + @staticmethod + def identity_bytes(ref: dict[str, Any], raw: bytes, label: str) -> None: + require(type(ref["bytes"]) is int and 0 <= ref["bytes"] <= MAX_CAPTURE_BYTES, + label + ": invalid byte count") + digest(ref["sha256"], HEX64, label + " SHA256") + require(ref["bytes"] == len(raw) + and ref["sha256"] == hashlib.sha256(raw).hexdigest(), + label + ": raw byte identity mismatch") + + def git(self, value: Any, label: str) -> Capture: + keys(value, {"ref", "raw_base64"}, label) + ref = keys(value["ref"], {"repository", "commit", "path", "git_blob", "sha256", "bytes"}, + label + " GitRef") + repository(ref["repository"], label + " repository") + digest(ref["commit"], HEX40, label + " commit") + relative_path(ref["path"], label + " path") + digest(ref["git_blob"], HEX40, label + " blob") + raw = self.raw(value, label) + self.identity_bytes(ref, raw, label) + blob = hashlib.sha1(b"blob " + str(len(raw)).encode("ascii") + b"\0" + raw, + usedforsecurity=False).hexdigest() + require(ref["git_blob"] == blob, label + ": Git blob identity mismatch") + capture = Capture(ref, raw) + identity = (ref["repository"], ref["commit"], ref["path"]) + previous = self.git_identities.get(identity) + require(previous is None or (previous.raw == raw and canonical(previous.ref) == canonical(ref)), + label + ": conflicting immutable Git capture") + self.git_identities[identity] = capture + return capture + + def run(self, value: Any, native: dict[str, Any], label: str) -> Capture: + keys(value, {"ref", "raw_base64"}, label) + ref = keys(value["ref"], {"repository", "checked_commit", "run_id", "run_attempt", + "artifact_id", "member_path", "sha256", "bytes"}, label + " RunRef") + repository(ref["repository"], label + " repository") + digest(ref["checked_commit"], HEX40, label + " checked commit") + for key in ("run_id", "run_attempt", "artifact_id"): + positive_decimal(ref[key], label + " " + key) + relative_path(ref["member_path"], label + " member path") + require(all(ref[key] == native[key] for key in + ("repository", "checked_commit", "run_id", "run_attempt")), + label + ": native run binding contradiction") + raw = self.raw(value, label) + self.identity_bytes(ref, raw, label) + capture = Capture(ref, raw) + identity = tuple(ref[key] for key in ("repository", "checked_commit", "run_id", "run_attempt", + "artifact_id", "member_path")) + previous = self.run_identities.get(identity) + require(previous is None or (previous.raw == raw and canonical(previous.ref) == canonical(ref)), + label + ": conflicting native artifact member") + self.run_identities[identity] = capture + return capture + + +def _gate() -> ModuleType: + """Read one fixed regular file through anchored no-follow descriptors.""" + descriptor = os.open(ROOT, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for name in ("docs", "site", "dependency-source"): + child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=descriptor) + os.close(descriptor) + descriptor = child + file_descriptor = os.open("hard_gate.py", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, + dir_fd=descriptor) + try: + info = os.fstat(file_descriptor) + require(stat.S_ISREG(info.st_mode) and info.st_size <= MAX_CAPTURE_BYTES, + "trusted gate is not a bounded regular file") + parts = [] + remaining = MAX_CAPTURE_BYTES + 1 + while remaining: + part = os.read(file_descriptor, min(remaining, 65536)) + if not part: + break + parts.append(part) + remaining -= len(part) + raw = b"".join(parts) + require(len(raw) <= MAX_CAPTURE_BYTES and hashlib.sha256(raw).hexdigest() == TRUSTED_GATE_SHA256, + "trusted gate SHA256 pin mismatch") + finally: + os.close(file_descriptor) + finally: + os.close(descriptor) + path = ROOT / "docs/site/dependency-source/hard_gate.py" + module = ModuleType("_verified_architecture_evidence_graph_gate") + module.__file__ = str(path) + exec(compile(raw, str(path), "exec"), module.__dict__) + return module + + +def _slice(value: Any, source: Capture | None, label: str) -> dict[str, Any] | None: + if value is None: + return None + keys(value, {"start_byte", "end_byte", "sha256"}, label) + require(source is not None, label + ": slice without source") + start, end = value["start_byte"], value["end_byte"] + require(type(start) is int and type(end) is int and 0 <= start < end <= len(source.raw), + label + ": invalid byte bounds") + digest(value["sha256"], HEX64, label + " SHA256") + require(hashlib.sha256(source.raw[start:end]).hexdigest() == value["sha256"], + label + ": byte slice hash mismatch") + return value + + +def _snapshot(value: Any, captures: Captures, gate: ModuleType, label: str) -> dict[str, Any]: + keys(value, {"graph", "bindings"}, label) + graph_capture = captures.git(value["graph"], label + " graph") + graph = graph_capture.document(label + " graph") + require(type(graph.get("nodes")) is dict, label + ": graph nodes must be object") + require(len(graph["nodes"]) <= MAX_GRAPH_NODES, label + ": graph node limit exceeded") + require(type(graph.get("edges")) is list, label + ": graph edges must be array") + require(len(graph["edges"]) <= MAX_GRAPH_EDGES, label + ": graph edge limit exceeded") + gate.validate_graph_fail_closed(graph) + require(type(value["bindings"]) is list, label + ": bindings must be array") + bindings = {} + for binding in value["bindings"]: + keys(binding, {"node", "source", "statement_slice", "proof_slice"}, label + " binding") + node = text(binding["node"], label + " node") + require(node in graph["nodes"] and node not in bindings, label + ": unknown or duplicate node binding") + source = None if binding["source"] is None else captures.git(binding["source"], label + " source") + statement = _slice(binding["statement_slice"], source, label + " statement slice") + proof = _slice(binding["proof_slice"], source, label + " proof slice") + bindings[node] = {"source": source, "statement_slice": statement, "proof_slice": proof} + return {"graph": graph, "graph_capture": graph_capture, "bindings": bindings} + + +def _native(value: Any) -> dict[str, Any]: + keys(value, {"repository", "checked_commit", "run_head_sha", "run_id", "run_attempt", + "purpose", "conclusion", "expected_conclusion"}, "native run") + repository(value["repository"], "native repository") + digest(value["checked_commit"], HEX40, "native checked commit") + digest(value["run_head_sha"], HEX40, "native run head") + positive_decimal(value["run_id"], "native run id") + positive_decimal(value["run_attempt"], "native run attempt") + require(value["purpose"] in ("check", "negative_control"), "unknown native run purpose") + conclusions = {"success", "failure", "skipped", "cancelled", "timed_out", "action_required", "neutral", "stale"} + require(type(value["conclusion"]) is str and value["conclusion"] in conclusions, + "unknown native conclusion") + require(type(value["expected_conclusion"]) is str and value["expected_conclusion"] in conclusions, + "unknown expected native conclusion") + return value + + +def _same_context(native: dict[str, Any], expected: dict[str, str]) -> bool: + return (native["repository"] == expected["repository"] + and native["checked_commit"] == expected["commit"] + and native["run_id"] == expected["run-id"] + and native["run_attempt"] == expected["run-attempt"]) + + +def _science(document: dict[str, Any], label: str, *, main: bool) -> None: + require(type(document.get("schema_version")) is int and document["schema_version"] == 1 + and document.get("scientific_effect") == "NONE", label + ": invalid native schema/effect") + if main or "scientific_status_authority" in document: + require(document.get("scientific_status_authority") is False, + label + ": scientific authority must be false") + + +def _axioms(value: Any, targets: set[str], label: str) -> dict[str, list[str]]: + require(type(value) is dict, label + ": expected axiom object") + result = {} + for target, axioms in value.items(): + require(target in targets and type(axioms) is list and all(type(item) is str for item in axioms), + label + ": foreign target or malformed axiom list") + require(len(axioms) == len(set(axioms)) and set(axioms) <= ALLOWED_AXIOMS, + label + ": duplicate or forbidden axiom") + result[target] = sorted(axioms) + return result + + +def _axiom_dump(raw: bytes, targets: set[str]) -> dict[str, list[str]]: + decoded = raw.decode("utf-8") + result = {} + for match in AXIOM_LINE.finditer(decoded): + target, listed = match.groups() + require(target in targets and target not in result, "foreign or duplicate original axiom target") + axioms = [] if listed is None or not listed.strip() else [item.strip() for item in listed.split(",")] + result.update(_axioms({target: axioms}, targets, "original axioms log")) + require(not AXIOM_LINE.sub("", decoded).strip(), "unrecognized original axiom output") + return result + + +def _main_control_rejected(raw: bytes, phase: str) -> bool: + """Match Main's retained rejection test without executing its producer.""" + try: + decoded = raw.decode("utf-8") + except UnicodeError: + return False + if phase == "REJECTED_BY_LEAN": + # Recognize this pinned POSIX producer's native-shaped diagnostics only; + # text shape cannot authenticate custody or a subprocess exit status. + location = re.compile(r"[A-Za-z0-9_./-]+\.lean:[0-9]+:[0-9]+") + tactic_failure = re.compile(r"[Tt]actic (?:'[^'\r\n]+'|`[^`\r\n]+`) failed(?::[^\r\n]*)?") + fence = None + awaiting_proposition = has_proposition = False + for raw_line in decoded.split("\n"): + line = raw_line.removesuffix("\r") + if "\r" in line: + awaiting_proposition = has_proposition = False + continue + stripped = line.lstrip(" \t") + if stripped.startswith(("```", "~~~")): + marker = stripped[0] + width = len(stripped) - len(stripped.lstrip(marker)) + if fence is None: + fence = (marker, width) + elif (marker == fence[0] and width >= fence[1] + and not stripped[width:].strip(" \t")): + fence = None + awaiting_proposition = has_proposition = False + continue + if fence is not None: + continue + if awaiting_proposition: + if line.startswith((" ", "\t")) and stripped: + nested_location, separator, _ = stripped.partition(": ") + if separator and location.fullmatch(nested_location): + awaiting_proposition = has_proposition = False + else: + has_proposition = True + continue + if has_proposition and line.rstrip(" \t") == "is false": + return True + awaiting_proposition = has_proposition = False + source_location, separator, message = line.partition(": error: ") + if not separator or location.fullmatch(source_location) is None: + continue + message = message.rstrip(" \t") + if message in ("unsolved goals", "proposition is false") or tactic_failure.fullmatch(message): + return True + if message == "Tactic `decide` proved that the proposition": + awaiting_proposition = True + return False + matches = list(AXIOM_LINE.finditer(decoded)) + if phase != "REJECTED_BY_AXIOM_GATE" or not matches: + return False + # Main audits only selected reports for its fixed `injected` target; Lean + # warnings around them are legitimate. Mirror that audit's rejection rules, + # including its acceptance of repeated allowed axioms within one report. + seen = set() + for match in matches: + target, listed = match.groups() + if target != "injected" or target in seen: + return True + axioms = [] if listed is None or not listed.strip() else [item.strip() for item in listed.split(",")] + if (any(NAME.fullmatch(axiom) is None for axiom in axioms) + or not set(axioms) <= ALLOWED_AXIOMS): + return True + seen.add(target) + return seen != {"injected"} + + +def _strip_lean_comments(decoded: str) -> str | None: + """Retain layout and quoted markers while removing nested native comments.""" + pieces = [] + start = index = 0 + quoted = escaped = False + while index < len(decoded): + character = decoded[index] + if quoted: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + quoted = False + elif character == '"': + quoted = True + elif decoded.startswith("--", index) or decoded.startswith("/-", index): + pieces.append(decoded[start:index]) + comment_start = index + if decoded.startswith("--", index): + newline = decoded.find("\n", index + 2) + index = len(decoded) if newline < 0 else newline + else: + index += 2 + depth = 1 + while index < len(decoded) and depth: + if decoded.startswith("/-", index): + depth += 1 + index += 2 + elif decoded.startswith("-/", index): + depth -= 1 + index += 2 + else: + index += 1 + if depth: + return None + pieces.append(re.sub(r"[^\r\n]", " ", decoded[comment_start:index])) + start = index + continue + index += 1 + if quoted: + return None + pieces.append(decoded[start:]) + return "".join(pieces) + + +def _elaborated_targets_complete(raw: bytes, targets: set[str]) -> bool: + """Check declared #check coverage, not the truth or custody of type text.""" + try: + decoded = raw.decode("utf-8") + except UnicodeError: + return False + decoded = _strip_lean_comments(decoded) + if decoded is None: + return False + blocks: dict[str, list[str]] = {} + current = None + for line in decoded.splitlines(): + if not line.strip(): + continue + if line[0].isspace(): + if current is None: + return False + blocks[current].append(line) + continue + matched = NAME.match(line) + if matched is None: + return False + current = matched.group() + tail = line[matched.end():] + if (current not in targets or current in blocks + or (tail and not tail[0].isspace() and tail[0] not in ":({[")): + return False + blocks[current] = [tail] + if set(blocks) != targets: + return False + closing = {")": "(", "}": "{", "]": "["} + for lines in blocks.values(): + body = "\n".join(lines) + stack: list[str] = [] + quoted = escaped = False + declaration_colon = None + for offset, character in enumerate(body): + if quoted: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + quoted = False + elif character == '"': + quoted = True + elif character in "({[": + stack.append(character) + elif character in closing: + if not stack or stack.pop() != closing[character]: + return False + elif character == ":" and not stack and declaration_colon is None: + # Parameter/binder colons cannot supply the declaration's type. + declaration_colon = offset + if stack or quoted or declaration_colon is None or not body[declaration_colon + 1:].strip(): + return False + return True + + +def _target_inventory(manifest: dict[str, Any], main: bool) -> tuple[list[str], dict[str, Any], dict[str, Any]]: + targets = manifest.get("targets") + require(type(targets) is list and bool(targets), "empty native target inventory") + rows = {} + sources = {} + if main: + for row in targets: + keys(row, {"name", "module", "title", "source", "informal_anchor", "does_not_claim"}, + "main target") + name = digest(row["name"], NAME, "main target name") + require(name not in rows, "duplicate main target") + for field in ("title", "source", "informal_anchor", "does_not_claim"): + text(row[field], "main target " + field) + relative_path(row["module"], "main target module") + rows[name] = row + source_rows = manifest.get("sources") + require(type(source_rows) is list and bool(source_rows), "missing main source rows") + for row in source_rows: + keys(row, {"id", "repository", "commit", "path", "bytes", "sha256", "local_copy"}, + "main source row") + identity = text(row["id"], "main source id") + require(identity not in sources, "duplicate main source id") + repository(row["repository"], "main origin repository") + digest(row["commit"], HEX40, "main origin commit") + relative_path(row["path"], "main origin path") + relative_path(row["local_copy"], "main local copy") + digest(row["sha256"], HEX64, "main origin SHA256") + require(type(row["bytes"]) is int and 0 < row["bytes"] <= MAX_CAPTURE_BYTES, + "main origin byte count") + sources[identity] = row + require(all(row["source"] in sources for row in rows.values()), "unknown main target source") + else: + for name in targets: + digest(name, NAME, "Math target name") + require(name not in rows, "duplicate Math target") + rows[name] = None + return sorted(rows), rows, sources + + +def _main_native_comments(decoded: str) -> str: + """Mirror Main's non-quote-aware source comment stripping, not elaboration.""" + out, index, depth = [], 0, 0 + while index < len(decoded): + two = decoded[index:index + 2] + if depth: + if two == "/-": + depth, index = depth + 1, index + 2 + elif two == "-/": + depth, index = depth - 1, index + 2 + else: + out.append("\n" if decoded[index] == "\n" else " ") + index += 1 + elif two == "/-": + depth, index = 1, index + 2 + elif two == "--": + end = decoded.find("\n", index) + index = len(decoded) if end < 0 else end + else: + out.append(decoded[index]) + index += 1 + return "".join(out) + + +def _main_captured_source_check(manifest: dict[str, Any], sources: dict[str, Capture], + paths: dict[str, str], package_root: str, + source_rows: dict[str, Any]) -> None: + """Validate Main's finite retained-source predicates without executing Lean.""" + root_module = text(manifest.get("root_module"), "main root module") + root_path = package_root + "/" + root_module + ".lean" + relative_path(root_path, "main root module path") + required = {package_root + "/" + name for name in ( + "lean-toolchain", "lakefile.toml", "lake-manifest.json", root_module + ".lean", + "SCOPE.md", "GLOSSARY.md", "README.md", + )} | {"tools/formal_gate_check.py", "tests/test_formal_gate.py"} + require(required <= set(paths), "main native required-file floor is incomplete") + require(sources[package_root + "/lean-toolchain"].raw.decode("utf-8").strip() == MAIN_TOOLCHAIN, + "main captured toolchain differs from the native toolchain") + lock = sources[package_root + "/lake-manifest.json"].document("main dependency lock") + require(type(lock) is dict, "main dependency lock must be an object") + packages = lock.get("packages", []) + require(type(packages) is list, "main dependency packages must be an array") + actual = {} + for package in packages: + require(type(package) is dict and "name" in package and "rev" in package + and type(package["name"]) is str, "main dependency package is malformed") + name = package["name"] + require(name not in actual, "duplicate main dependency package") + actual[name] = digest(package["rev"], HEX40, "main locked dependency revision") + require(type(manifest.get("dependency_revisions")) is dict + and actual == manifest["dependency_revisions"], "main dependency lock differs from declaration") + modules = manifest["source_modules"] + require(all(module.endswith(".lean") for module in modules), "main registered module must be Lean") + expected_root = "".join("import " + module[:-5].replace("/", ".") + "\n" for module in modules) + root_text = _main_native_comments(sources[root_path].raw.decode("utf-8")) + require("".join(line + "\n" for line in root_text.splitlines() if line.strip()) == expected_root, + "main root imports differ from ordered registered modules") + names = [] + for module in modules: + decoded = _main_native_comments(sources[package_root + "/" + module].raw.decode("utf-8")) + require(re.search(r"\bsorry\b", decoded) is None + and re.search(r"\bnative_decide\b", decoded) is None + and re.search(r"^\s*axiom\b", decoded, re.M) is None, + "main captured module contains a prohibited proof construct") + namespaces = re.findall(r"^namespace\s+(\S+)", decoded, re.M) + require(len(namespaces) == 1, "main module must open exactly one native namespace") + declarations = re.findall(r"^(?:theorem|lemma)\s+([A-Za-z_][A-Za-z0-9_.']*)", decoded, re.M) + names.extend(namespaces[0] + "." + name for name in declarations) + require(names == [row["name"] for row in manifest["targets"]], + "main ordered targets differ from native declarations") + prefix = package_root + "/" + visible_lean = {path[len(prefix):] for path in sources + if path.startswith(prefix) and path.endswith(".lean") + and ".lake" not in PurePosixPath(path[len(prefix):]).parts} + require(visible_lean == set(modules) | {root_module + ".lean"}, + "main visible retained Lean inventory differs from native scope") + for row in source_rows.values(): + require(row["repository"] in MAIN_PUBLIC_REPOSITORIES, + "main pinned origin is outside the native public-repository policy") + sources[row["local_copy"]].raw.decode("utf-8") + registered = manifest.get("negative_controls", {}) + require(type(registered) is dict, "main negative controls must be an object") + for label, spec in registered.items(): + require(type(label) is str and type(spec) is dict + and {"module", "replace", "with"} <= set(spec), "main registered mutation is malformed") + module = relative_path(spec["module"], "main mutation module") + path = package_root + "/" + module + require(path in sources and type(spec["replace"]) is str and type(spec["with"]) is str, + "main registered mutation source or replacement is missing") + require(spec["replace"] in sources[path].raw.decode("utf-8"), + "main registered mutation replacement text is absent") + + +def _lineage(party: Any, *, normalized: bool) -> dict[str, str] | None: + if type(party) is not dict: + return None + result = {} + for field in ("provider", "family", "agent"): + value = party.get(field) + if type(value) is not str or not value.strip(): + return None + normalized_value = " ".join(value.split()).casefold() + if normalized_value in PLACEHOLDERS: + return None + compared = normalized_value if normalized else value.strip().casefold() + result[field] = compared + return result + + +def _alignment_reasons(document: dict[str, Any] | None, manifest: Capture, scope: Capture, + targets: list[str], *, main: bool, source_author: Any = None) -> list[str]: + if document is None: + return ["alignment_not_recorded"] + reasons = [] + for field in ("manifest_sha256", "scope_sha256"): + if field in document: + digest(document[field], HEX64, "alignment " + field) + if document.get("manifest_sha256") != manifest.ref["sha256"]: + reasons.append("manifest_binding_changed") + if document.get("scope_sha256") != scope.ref["sha256"]: + reasons.append("scope_binding_changed") + covered = document.get("targets") + if not (type(covered) is list and all(type(item) is str for item in covered) + and len(covered) == len(set(covered)) and set(covered) == set(targets)): + reasons.append("target_coverage_changed") + if document.get("disposition") != "ACCEPTED": + reasons.append("alignment_not_accepted") + reviewer = _lineage(document.get("reviewer"), normalized=not main) + authors = [_lineage(document.get("author"), normalized=not main)] + if main: + retained_author = _lineage(source_author, normalized=False) + if retained_author is None: + reasons.append("manifest_author_unresolved") + else: + if authors[0] != retained_author: + reasons.append("author_binding_changed") + # A review cannot gain distinct lineage by relabeling its author. + authors.append(retained_author) + else: + proposers = document.get("proposal_authors", []) + if type(proposers) is not list: + reasons.append("lineage_not_distinct") + else: + for proposer in proposers: + authors.append(_lineage(proposer, normalized=True)) + if type(proposer) is dict and "targets" in proposer: + subset = proposer["targets"] + if not (type(subset) is list and bool(subset) + and all(type(item) is str and item in targets for item in subset) + and len(subset) == len(set(subset))): + reasons.append("target_coverage_changed") + if reviewer is None or any(author is None or any(author[field] == reviewer[field] + for field in reviewer) for author in authors): + reasons.append("lineage_not_distinct") + evidence = document.get("evidence") + if type(evidence) is not dict: + reasons.append("alignment_evidence_unresolved") + else: + # These declarations are structurally checked, never fetched or credited as custody. + try: + repository(evidence.get("repository"), "alignment evidence repository") + digest(evidence.get("commit"), HEX40, "alignment evidence commit") + digest(evidence.get("sha256"), HEX64, "alignment evidence SHA256") + relative_path(evidence.get("path"), "alignment evidence path") + except ValueError: + reasons.append("alignment_evidence_unresolved") + return sorted(set(reasons)) + + +def _formal(value: Any, captures: Captures, nodes: set[str], expected: dict[str, str]) -> dict[str, Any]: + keys(value, {"id", "format", "manifest", "scope", "source_files", "receipt", "logs", + "alignment", "native_run", "node_targets"}, "formal record") + identity = text(value["id"], "formal id") + require(value["format"] in ("main-formal-gate/v1", "math-formal-gate/v1"), "unknown native format") + main = value["format"] == "main-formal-gate/v1" + native = _native(value["native_run"]) + manifest_capture = captures.git(value["manifest"], "formal manifest") + scope = captures.git(value["scope"], "formal scope") + manifest = manifest_capture.document("formal manifest") + _science(manifest, "formal manifest", main=main) + require(manifest.get("formalization_status") == "proved" + and manifest.get("alignment_status") == "PENDING_INDEPENDENT_REVIEW", + "native source metadata cannot award execution or review") + if main: + require(manifest_capture.ref["path"] == "formal/manifest.json", + "main manifest must identify the native formal/manifest.json") + text(manifest.get("package"), "main package") + require(manifest.get("lean_toolchain") == MAIN_TOOLCHAIN, + "unsupported main native Lean toolchain") + targets, target_rows, source_rows = _target_inventory(manifest, main) + target_set = set(targets) + require(type(value["source_files"]) is list, "formal source_files must be array") + sources = {} + for original in value["source_files"]: + capture = captures.git(original, "formal source file") + require(capture.ref["path"] not in sources, "duplicate formal source file") + sources[capture.ref["path"]] = capture + for capture in [manifest_capture, scope, *sources.values()]: + require(capture.ref["repository"] == native["repository"] + and capture.ref["commit"] == native["checked_commit"], + "native checked source binding contradiction") + files = manifest.get("files") + require(type(files) is dict and bool(files), "missing native file hashes") + parent = str(PurePosixPath(manifest_capture.ref["path"]).parent) + package_root = relative_path(manifest.get("package_root"), "main package root") if main else None + scope_path = package_root + "/SCOPE.md" if main else "SCOPE.md" if parent == "." else parent + "/SCOPE.md" + require(scope.ref["path"] == scope_path, "native scope must identify the original SCOPE.md") + paths = {} + for name, expected_hash in files.items(): + relative_path(name, "native file key") + digest(expected_hash, HEX64, "native file SHA256") + path = name if main or parent == "." else parent + "/" + name + relative_path(path, "native source lookup") + require(path not in paths, "duplicate native source lookup") + paths[path] = expected_hash + require(path in sources and sources[path].ref["sha256"] == expected_hash, + "native source file missing or contradictory") + require(scope.ref["path"] in paths and paths[scope.ref["path"]] == scope.ref["sha256"], + "native scope is not bound by manifest files") + if main: + prefix = package_root + "/" + for capture in [manifest_capture, scope, *sources.values()]: + path = capture.ref["path"] + if (path.startswith(prefix) and ".lake" not in PurePosixPath(path[len(prefix):]).parts + and path not in paths): + require(path in set(manifest.get("unbound_files", [])), + "main known package member is neither bound nor declared unbound") + for row in source_rows.values(): + local = sources.get(row["local_copy"]) + require(local is not None and row["local_copy"] in paths + and local.ref["bytes"] == row["bytes"] and local.ref["sha256"] == row["sha256"], + "main checked local copy differs from pinned origin bytes") + modules = manifest.get("source_modules") + require(type(modules) is list and bool(modules) and all(type(item) is str for item in modules) + and len(modules) == len(set(modules)), "invalid main source module inventory") + for module in modules: + relative_path(module, "main source module") + require(package_root + "/" + module in paths, "unbound main source module") + require(all(row["module"] in modules for row in target_rows.values()), "target module not registered") + for row in target_rows.values(): + local = sources[source_rows[row["source"]]["local_copy"]] + require(row["informal_anchor"].encode("utf-8") in local.raw, + "main target anchor absent from checked source") + _main_captured_source_check(manifest, sources, paths, package_root, source_rows) + require(type(value["node_targets"]) is list, "node_targets must be array") + mappings = [] + seen = set() + for binding in value["node_targets"]: + keys(binding, {"node", "target"}, "node target binding") + require(type(binding["node"]) is str and binding["node"] in nodes + and type(binding["target"]) is str and binding["target"] in target_set, + "unknown explicit node or native target") + pair = (binding["node"], binding["target"]) + require(pair not in seen, "duplicate explicit node target binding") + seen.add(pair) + mappings.append(binding) + require(type(value["logs"]) is list, "formal logs must be array") + logs = {} + members = [] + for original in value["logs"]: + capture = captures.run(original, native, "formal log") + name = PurePosixPath(capture.ref["member_path"]).name + require(name not in logs, "duplicate native log filename") + logs[name] = capture + members.append(capture) + receipt_capture = None if value["receipt"] is None else captures.run(value["receipt"], native, "formal receipt") + receipt = None if receipt_capture is None else receipt_capture.document("formal receipt") + if receipt_capture is not None: + receipt_member = PurePosixPath(receipt_capture.ref["member_path"]) + require(receipt_member.name == "receipt.json", "native receipt must be named receipt.json") + require(all(PurePosixPath(capture.ref["member_path"]).parent == receipt_member.parent + for capture in logs.values()), "native receipt/log parent contradiction") + members.append(receipt_capture) + require(len({capture.ref["artifact_id"] for capture in members}) <= 1, + "native receipt/log artifact identity contradiction") + complete = False + if receipt is not None: + _science(receipt, "formal receipt", main=main) + require(receipt.get("manifest_sha256") == manifest_capture.ref["sha256"] + and receipt.get("repository") == native["repository"] + and receipt.get("checked_commit") == native["checked_commit"] + and receipt.get("workflow_run_id") == native["run_id"], "native receipt identity contradiction") + require(receipt.get("formalization_status") == "kernel-checked" + and receipt.get("alignment_status") == "PENDING_INDEPENDENT_REVIEW", + "unsupported native receipt status") + if main: + require(type(manifest.get("package")) is str and receipt.get("package") == manifest["package"], + "main receipt package contradiction") + require(type(manifest.get("dependency_revisions")) is dict + and canonical(receipt.get("dependency_revisions")) == canonical(manifest["dependency_revisions"]), + "native dependency receipt contradiction") + for revision in manifest["dependency_revisions"].values(): + digest(revision, HEX40, "native dependency revision") + lean_version = text(receipt.get("lean_version"), "native Lean version record") + if main: + require(MAIN_VERSION.search(lean_version) is not None, + "unsupported main native Lean version") + version_complete = True + if main: + version_capture = logs.get("version.log") + version_text = "" if version_capture is None else version_capture.raw.decode("utf-8").strip() + version_complete = bool(version_text) + if version_complete: + require(version_text == lean_version, "original whole version log contradicts receipt") + recorded_logs = receipt.get("logs") + require(type(recorded_logs) is dict, "missing native receipt log inventory") + for name, expected_hash in recorded_logs.items(): + relative_path(name, "receipt log name") + require("/" not in name, "receipt log key must be native basename") + if main: + require(re.fullmatch(r"[A-Za-z0-9_-]+\.log", name) is not None, + "invalid main native receipt log basename") + digest(expected_hash, HEX64, "receipt log SHA256") + require(name in logs and logs[name].ref["sha256"] == expected_hash, + "original receipt log hash contradiction") + require(set(logs) == set(recorded_logs), "unbound original native log") + receipt_axioms = _axioms(receipt.get("axioms"), target_set, "native receipt axioms") + dumped = None if "axioms.log" not in logs else _axiom_dump(logs["axioms.log"].raw, target_set) + if dumped is not None: + require(canonical(dumped) == canonical(receipt_axioms), "original axiom log contradicts receipt") + complete = (version_complete and dumped is not None and set(dumped) == target_set + and {"build.log", "leanchecker.log", "elaborated-types.log"} <= set(logs) + and _elaborated_targets_complete(logs["elaborated-types.log"].raw, target_set)) + controls = receipt.get("negative_controls") + require(type(controls) is dict and all(type(name) is str and outcome in + ("REJECTED_BY_LEAN", "REJECTED_BY_AXIOM_GATE") for name, outcome in controls.items()), + "invalid native negative-control outcomes") + if main: + registered = manifest.get("negative_controls") + require(type(registered) is dict, "missing main negative-control declarations") + require(not MAIN_EXECUTION_LOG_LABELS.intersection(registered), + "main negative control aliases a positive execution-log basename") + phases = dict.fromkeys(registered, "REJECTED_BY_LEAN") + # The native producer installs these axiom controls after mutations. + phases.update(dict.fromkeys(("sorry", "custom_imported", "native"), "REJECTED_BY_AXIOM_GATE")) + require(set(controls) <= set(phases), + "main native negative-control outcome inventory contradiction") + require(all(name not in controls or controls[name] == phase for name, phase in phases.items()), + "main native negative-control rejection mechanism contradiction") + complete = (complete and set(phases) <= set(controls) + and all(name + ".log" in logs + and _main_control_rejected(logs[name + ".log"].raw, phase) + for name, phase in phases.items())) + alignment_capture = None if value["alignment"] is None else captures.git(value["alignment"], "formal alignment") + alignment = None if alignment_capture is None else alignment_capture.document("formal alignment") + reviewed_graph = (None if alignment is None or "reviewed_graph" not in alignment else + _git_reference(alignment["reviewed_graph"], "alignment reviewed_graph")) + reviewed_bindings = None + if alignment is not None and "reviewed_bindings" in alignment: + reviewed_bindings = keys(alignment["reviewed_bindings"], {"schema_version", "sha256"}, + "alignment reviewed_bindings") + require(type(reviewed_bindings["schema_version"]) is int and reviewed_bindings["schema_version"] == 1, + "alignment reviewed_bindings: unsupported schema") + digest(reviewed_bindings["sha256"], HEX64, "alignment reviewed_bindings SHA256") + alignment_reasons = _alignment_reasons(alignment, manifest_capture, scope, targets, + main=main, source_author=manifest.get("author")) + return { + "id": identity, "main": main, "native": native, "context_current": _same_context(native, expected), + "manifest_capture": manifest_capture, "scope": scope, "manifest": manifest, + "targets": targets, "target_rows": target_rows, "source_rows": source_rows, + "receipt": receipt, "complete": complete, "mappings": mappings, + "alignment": alignment, "alignment_capture": alignment_capture, "alignment_reasons": alignment_reasons, + "reviewed_graph": reviewed_graph, "reviewed_bindings": reviewed_bindings, + "summary": {"id": identity, "format": value["format"], "manifest_targets": targets, + "node_targets": value["node_targets"], "retained_manifest": manifest, + "retained_receipt": receipt, "retained_alignment": alignment}, + } + + +RETROFIT_BASELINE = {"Math-": "08f86862f859ac4804b4fd6c6477a7ed0421e37f", + "main": "cddbb7f6cf3f57f3b495277f7da148287e027b19"} +RETROFIT_AXES = frozenset({"source_review", "provider_distinct_review", "blind_reconstruction", + "adversarial_attack", "formal_evidence", "numerical_reproduction", + "novelty", "human_reading", "custody", "observable_statement"}) +RETROFIT_REPOSITORIES = frozenset({"Math-", "main", "Universal-Law-Workspace", "d6g8k5htny-coder", + "google-drive", "governance-", "meta-framework", "query-", "sandbox", "trial"}) +RETROFIT_EVIDENCE_KEYS = { + "file": {"kind", "repository", "commit", "path", "blob"}, + "github_comment": {"kind", "repository", "ref"}, + "github_review": {"kind", "repository", "ref", "commit"}, + "workflow_run": {"kind", "repository", "ref", "attempt", "job", "run_head_sha", + "checked_commit", "purpose", "conclusion", "expected_conclusion"}, +} +RETROFIT_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}") +RETROFIT_DECIMAL = re.compile(r"[1-9][0-9]{0,19}") + + +def _retrofit_person(value: Any) -> None: + keys(value, {"provider", "model_or_agent", "session"}, "retrofit performer") + for field in value: + text(value[field], "retrofit performer " + field) + + +def _retrofit_evidence(item: Any) -> None: + require(type(item) is dict and type(item.get("kind")) is str + and item["kind"] in RETROFIT_EVIDENCE_KEYS, "unknown retrofit evidence kind") + kind = item["kind"] + keys(item, RETROFIT_EVIDENCE_KEYS[kind], "retrofit evidence") + require(type(item["repository"]) is str and item["repository"] in RETROFIT_REPOSITORIES, + "unknown retrofit evidence repository") + if kind == "file": + relative_path(item["path"], "retrofit evidence file") + digest(item["commit"], HEX40, "retrofit file commit") + digest(item["blob"], HEX40, "retrofit file blob") + else: + digest(item["ref"], RETROFIT_DECIMAL, "retrofit native id") + if kind == "github_review": + digest(item["commit"], HEX40, "retrofit native review commit") + if kind == "workflow_run": + require(type(item["attempt"]) is int and item["attempt"] > 0, + "retrofit run attempt must be positive integer") + if item["job"] is not None: + digest(item["job"], RETROFIT_DECIMAL, "retrofit native job") + digest(item["run_head_sha"], HEX40, "retrofit run head") + if item["checked_commit"] is not None: + digest(item["checked_commit"], HEX40, "retrofit checked commit") + require(item["purpose"] in ("check", "negative_control"), "unknown retrofit purpose") + require(item["conclusion"] in ("success", "failure", "cancelled", "skipped", "timed_out", + "neutral", "action_required", "stale", "startup_failure"), + "unknown retrofit native conclusion") + require(item["expected_conclusion"] in ("success", "failure"), "unknown retrofit expected conclusion") + + +def _retrofit(value: Any, captures: Captures, nodes: set[str]) -> dict[str, Any]: + keys(value, {"id", "record", "node_records"}, "retrofit wrapper") + identity = text(value["id"], "retrofit id") + capture = captures.git(value["record"], "retrofit original record") + document = capture.document("retrofit original record") + keys(document, {"schema", "shard", "baseline", "author", "scientific_effect", "status_authority", "records"}, + "retrofit native document") + require(document["schema"] == "retrofit-records/v0.1" and document["scientific_effect"] == "NONE" + and document["status_authority"] is False, "invalid retrofit schema or authority") + digest(document["shard"], re.compile(r"[A-Z][A-Za-z0-9_]{0,39}"), "retrofit shard") + require(canonical(document["baseline"]) == canonical(RETROFIT_BASELINE), "retrofit baseline contradiction") + _retrofit_person(document["author"]) + require(type(document["records"]) is list and bool(document["records"]), "empty retrofit native records") + records = {} + for record in document["records"]: + keys(record, {"id", "subject", "delta", "axis", "state", "evidence", "performer", "exposure", + "independence_credit", "alias_of", "notes"}, "retrofit native record") + record_id = digest(record["id"], RETROFIT_ID, "retrofit record id") + require(record_id not in records, "duplicate retrofit record id") + subject = keys(record["subject"], {"repository", "commit", "path", "blob"}, "retrofit subject") + require(type(subject["repository"]) is str and subject["repository"] in RETROFIT_REPOSITORIES, + "unknown retrofit subject repository") + digest(subject["commit"], HEX40, "retrofit subject commit") + digest(subject["blob"], HEX40, "retrofit subject blob") + relative_path(subject["path"], "retrofit subject path") + require(type(record["delta"]) is bool, "retrofit delta must be exact boolean") + require(record["delta"] or RETROFIT_BASELINE.get(subject["repository"]) == subject["commit"], + "nonbaseline retrofit subject requires delta") + require(type(record["axis"]) is str and record["axis"] in RETROFIT_AXES, "unknown retrofit axis") + require(type(record["state"]) is str and record["state"] in STATES, "unknown retrofit availability") + require(type(record["evidence"]) is list, "retrofit evidence must be array") + require(record["state"] != "recorded" or bool(record["evidence"]), "recorded retrofit lacks evidence") + require(record["state"] not in ("not_recorded", "not_applicable") or not record["evidence"], + "absent retrofit availability cannot carry evidence") + for item in record["evidence"]: + _retrofit_evidence(item) + _retrofit_person(record["performer"]) + text(record["exposure"], "retrofit exposure") + require(type(record["independence_credit"]) is int and record["independence_credit"] == 0, + "retrofit independence credit must be integer zero") + require(record["alias_of"] is None or type(record["alias_of"]) is str, "invalid retrofit alias id") + require(type(record["notes"]) is str, "retrofit notes must be text") + records[record_id] = record + for record in records.values(): + if record["alias_of"] is not None: + original = records.get(record["alias_of"]) + require(original is not None and original is not record and original["alias_of"] is None, + "dangling or chained retrofit alias") + require(original["axis"] == record["axis"] and original["state"] == record["state"] + and sorted(canonical(item) for item in original["evidence"]) + == sorted(canonical(item) for item in record["evidence"]), "retrofit alias differs from original") + require(type(value["node_records"]) is list, "retrofit node_records must be array") + bindings = [] + seen = set() + for binding in value["node_records"]: + keys(binding, {"node", "record_id"}, "retrofit node record") + require(type(binding["node"]) is str and binding["node"] in nodes + and type(binding["record_id"]) is str and binding["record_id"] in records, + "unknown retrofit node or record") + pair = (binding["node"], binding["record_id"]) + require(pair not in seen, "duplicate retrofit node record binding") + seen.add(pair) + bindings.append((binding["node"], records[binding["record_id"]])) + return {"id": identity, "capture": capture, "document": document, "bindings": bindings} + + +def _fingerprint(binding: dict[str, Any] | None) -> Any: + if binding is None: + return None + source = binding["source"] + return {"source": None if source is None else {key: source.ref[key] for key in + ("repository", "commit", "path", "bytes", "sha256")}, + "statement_slice": binding["statement_slice"], "proof_slice": binding["proof_slice"]} + + +def _regression(old: dict[str, Any], new: dict[str, Any], gate: ModuleType) -> dict[str, Any]: + old_graph, new_graph = old["graph"], new["graph"] + old_sources = {node: _fingerprint(old["bindings"].get(node)) for node in old_graph["nodes"]} + new_sources = {node: _fingerprint(new["bindings"].get(node)) for node in new_graph["nodes"]} + # Snapshot-relative source commits normally advance with the graph commit. + # Ignore that paired revision change while preserving fixed-origin changes. + for node in set(old_sources) & set(new_sources): + before, after = old_sources[node], new_sources[node] + if before is None or after is None or before["source"] is None or after["source"] is None: + continue + if all(fingerprint["source"]["repository"] == snapshot["graph_capture"].ref["repository"] + and fingerprint["source"]["commit"] == snapshot["graph_capture"].ref["commit"] + for fingerprint, snapshot in ((before, old), (after, new))): + before["source"]["commit"] = after["source"]["commit"] = None + impact = gate.reverse_impact_between(old_graph, new_graph, old_sources=old_sources, new_sources=new_sources) + reasons: dict[str, set[str]] = {node: set() for node in impact["changed_nodes"]} + statement_changed = [] + proof_changed = [] + unscoped = [] + for node in impact["changed_nodes"]: + if node not in old_graph["nodes"] or node not in new_graph["nodes"]: + reasons[node].add("node_record_changed") + elif canonical(old_graph["nodes"][node]) != canonical(new_graph["nodes"][node]): + reasons[node].add("node_record_changed") + old_edges = sorted(canonical(edge) for edge in old_graph["edges"] if edge["from"] == node) + new_edges = sorted(canonical(edge) for edge in new_graph["edges"] if edge["from"] == node) + if old_edges != new_edges: + reasons[node].add("dependency_edges_changed") + if impact["context_changed"]: + reasons[node].add("graph_context_changed") + if node in old_sources and node in new_sources and canonical(old_sources[node]) != canonical(new_sources[node]): + before, after = old["bindings"].get(node), new["bindings"].get(node) + scoped = False + if before is not None and after is not None and before["source"] is not None and after["source"] is not None: + for field, code, changed in (("statement_slice", "statement_changed", statement_changed), + ("proof_slice", "proof_body_changed", proof_changed)): + first, last = before[field], after[field] + if first is not None and last is not None and first["sha256"] != last["sha256"]: + changed.append(node) + reasons[node].add(code) + scoped = True + if not scoped: + unscoped.append(node) + reasons[node].add("source_changed_unscoped") + proposals = [] + for node in impact["impacted"]: + codes = reasons.get(node, {"dependency_changed"}) + proposals.append({"node": node, "reasons": sorted(codes or {"dependency_changed"})}) + return {"changed_nodes": impact["changed_nodes"], "impacted_nodes": impact["impacted"], + "statement_changed": sorted(statement_changed), "proof_changed": sorted(proof_changed), + "unscoped_source_changed": sorted(unscoped), "traversal_edges": impact["traversal_edges"], + "revalidation_required": proposals, "affected_alignment_records": []} + + +def _axis(state: str = "unknown", applicability: str = "unknown", *, reasons: list[str] | None = None, + evidence: list[str] | None = None) -> dict[str, Any]: + return {"record_state": state, "applicability": applicability, "reasons": sorted(set(reasons or [])), + "evidence_ids": sorted(set(evidence or [])), "custody": "unknown"} + + +def _merge_axis(records: list[dict[str, Any]]) -> dict[str, Any]: + if not records: + return _axis() + states = {record["record_state"] for record in records} + state = "recorded" if "recorded" in states else next(iter(states)) if len(states) == 1 else "unknown" + applications = {record["applicability"] for record in records} + applicability = "stale" if "stale" in applications else next(iter(applications)) if len(applications) == 1 else "unknown" + return _axis(state, applicability, + reasons=[code for record in records for code in record["reasons"]], + evidence=[identity for record in records for identity in record["evidence_ids"]]) + + +def _main_join(formal: dict[str, Any], node: str, target: str, bindings: dict[str, Any]) -> tuple[bool, list[str]]: + binding = bindings.get(node) + if not formal["main"] or binding is None or binding["source"] is None: + return False, ["missing_target_source_binding"] + row = formal["target_rows"][target] + origin = formal["source_rows"][row["source"]] + capture = binding["source"] + if any(capture.ref[key] != origin[key] for key in ("repository", "commit", "path", "bytes", "sha256")): + return False, ["missing_target_source_binding"] + statement = binding["statement_slice"] + if statement is None: + return False, ["missing_statement_slice"] + portion = capture.raw[statement["start_byte"]:statement["end_byte"]] + if row["informal_anchor"].encode("utf-8") not in portion: + return False, ["missing_statement_slice"] + return True, ["declared_byte_slice_only"] + + +def _kernel(formal: dict[str, Any], joined: bool, join_reasons: list[str]) -> dict[str, Any]: + reasons = list(join_reasons) + native = formal["native"] + if not formal["context_current"]: + reasons.append("native_context_changed") + if native["purpose"] != "check": + reasons.append("native_run_negative_control") + if native["conclusion"] != "success": + reasons.append("native_run_not_success") + if not formal["complete"]: + reasons.append("target_inventory_incomplete") + current = (joined and formal["context_current"] and formal["complete"] + and native["purpose"] == "check" and native["conclusion"] == "success") + applicability = "current" if current else "stale" if not formal["context_current"] else "unknown" + return _axis("recorded" if formal["receipt"] is not None else "unknown", applicability, + reasons=reasons, evidence=[formal["id"]]) + + +def _retrofit_projection(record: dict[str, Any], binding: dict[str, Any] | None) -> dict[str, Any]: + reasons = ["retrofit_availability_only", "native_custody_unknown"] + source = None if binding is None else binding["source"] + subject = record["subject"] + # This is the native contract's explicit repository alias, not a fuzzy join. + qualified = "d6g8k5htny-coder/" + subject["repository"] + matching = (source is not None and source.ref["repository"] == qualified + and source.ref["commit"] == subject["commit"] and source.ref["path"] == subject["path"] + and source.ref["git_blob"] == subject["blob"]) + if not matching: + reasons.append("source_binding_changed") + for evidence in record["evidence"]: + if evidence["kind"] == "workflow_run": + if evidence["purpose"] != "check": + reasons.append("native_run_negative_control") + if evidence["conclusion"] != "success": + reasons.append("native_run_not_success") + applicability = "not_applicable" if record["state"] == "not_applicable" else "unknown" if matching else "stale" + return _axis(record["state"], applicability, reasons=reasons, evidence=[record["id"]]) + + +def _proof_binding_context_sha256(new: dict[str, Any]) -> str: + """Bind the exact graph and every declared binding; no semantic or custody claim.""" + rows = [] + for node in sorted(new["graph"]["nodes"]): + original = new["bindings"].get(node) + binding = None if original is None else { + "source": None if original["source"] is None else original["source"].ref, + "statement_slice": original["statement_slice"], "proof_slice": original["proof_slice"], + } + rows.append({"node": node, "binding": binding}) + payload = {"domain": "architecture-proof-binding-context/v1", + "graph": new["graph_capture"].ref, "bindings": rows} + return hashlib.sha256(canonical(payload).encode("ascii")).hexdigest() + + +def _proof_binding_context_nodes(old: dict[str, Any], new: dict[str, Any], + regression: dict[str, Any]) -> set[str]: + """Require selector coverage for affected whole records, including downstream uses.""" + affected = set() + for node in set(old["graph"]["nodes"]) | set(new["graph"]["nodes"]): + before, after = old["bindings"].get(node), new["bindings"].get(node) + first = None if before is None else before["proof_slice"] + last = None if after is None else after["proof_slice"] + if first is not None and (after is None or after["source"] is None or last is None): + affected.add(node) + elif (before is not None and after is not None + and before["source"] is not None and after["source"] is not None + and all(before["source"].ref[key] == after["source"].ref[key] for key in + ("repository", "path", "git_blob", "sha256", "bytes")) + and canonical(first) != canonical(last)): + affected.add(node) + reverse: dict[str, set[str]] = {} + for child, dependency in regression["traversal_edges"]: + reverse.setdefault(dependency, set()).add(child) + queue = list(affected) + while queue: + for child in reverse.get(queue.pop(), ()): + if child not in affected: + affected.add(child) + queue.append(child) + return affected + + +def _alignment_holds(old: dict[str, Any], new: dict[str, Any], formals: list[dict[str, Any]], + regression: dict[str, Any]) -> dict[str, set[str]]: + regression_reasons = {proposal["node"]: proposal["reasons"] + for proposal in regression["revalidation_required"]} + changed = set(regression["changed_nodes"]) + groups: dict[str, list[dict[str, Any]]] = {} + for formal in formals: + capture = formal["alignment_capture"] + if capture is not None: + groups.setdefault(canonical(capture.ref), []).append(formal) + graph_ref = canonical(new["graph_capture"].ref) + context_nodes = _proof_binding_context_nodes(old, new, regression) + binding_digest = _proof_binding_context_sha256(new) if context_nodes else None + holds = {} + for identity, records in groups.items(): + reasons = {code for formal in records for mapping in formal["mappings"] + for code in regression_reasons.get(mapping["node"], + ["node_record_changed"] if mapping["node"] in changed else [])} + context_reasons = set() + if any(mapping["node"] in context_nodes for formal in records for mapping in formal["mappings"]): + for formal in records: + claim = formal["reviewed_bindings"] + if claim is None: + context_reasons.add("proof_binding_context_missing") + elif claim["sha256"] != binding_digest: + context_reasons.add("proof_binding_context_changed") + reasons.update(context_reasons) + # A newer alignment commit alone is not graph-context revalidation. + # Every formal use of the original whole record must remain bound and + # explicitly review the same verified full new graph identity. + revalidated = not context_reasons and all( + not formal["alignment_reasons"] and formal["reviewed_graph"] is not None + and canonical(formal["reviewed_graph"]) == graph_ref + and (not formal["main"] or all( + mapping["node"] in new["graph"]["nodes"] + and _main_join(formal, mapping["node"], mapping["target"], new["bindings"])[0] + for mapping in formal["mappings"])) for formal in records) + if reasons and not revalidated: + holds[identity] = reasons + return holds + + +def _dimensions(new: dict[str, Any], formals: list[dict[str, Any]], retrofits: list[dict[str, Any]], + regression: dict[str, Any], alignment_holds: dict[str, set[str]]) -> dict[str, Any]: + projected = {node: {axis: [] for axis in AXES} for node in new["graph"]["nodes"]} + for node, original in new["graph"]["nodes"].items(): + binding = new["bindings"].get(node) + source = None if binding is None else binding["source"] + if source is not None: + ref = source.ref + source_id = ref["repository"] + "@" + ref["commit"] + ":" + ref["path"] + "#" + ref["git_blob"] + reasons = ["declared_byte_slice_only"] + if binding["statement_slice"] is None: + reasons.append("missing_statement_slice") + projected[node]["source"].append(_axis("recorded", "current", reasons=reasons, evidence=[source_id])) + else: + projected[node]["source"].append(_axis(reasons=["source_not_captured"])) + review_fields = {key: value for key, value in original.items() if key.startswith("review_")} + if review_fields: + review_reasons = ["graph_review_record_only"] + application = "unknown" + if source is not None and node in regression["statement_changed"] + regression["proof_changed"]: + review_reasons.extend(code for code, changed in + (("statement_changed", regression["statement_changed"]), + ("proof_body_changed", regression["proof_changed"])) if node in changed) + application = "stale" + # No independent native review ID is supplied by graph review text. + projected[node]["review"].append(_axis("recorded", application, reasons=review_reasons)) + for formal in formals: + capture = formal["alignment_capture"] + held_reasons = set() if capture is None else alignment_holds.get(canonical(capture.ref), set()) + for mapping in formal["mappings"]: + node, target = mapping["node"], mapping["target"] + if node not in projected: + # Historical explicit mappings remain in the original record, + # but removed nodes have no new-snapshot dimensions. + continue + joined, join_reasons = _main_join(formal, node, target, new["bindings"]) + projected[node]["kernel"].append(_kernel(formal, joined, join_reasons)) + reasons = list(formal["alignment_reasons"]) + if held_reasons: + # The hold covers every explicit mapping of this original whole record. + reasons.extend(sorted(held_reasons)) + reasons.append("alignment_record_revalidation_required") + unresolved_join = formal["main"] and not joined + if unresolved_join: + reasons.extend(join_reasons) + if formal["alignment"] is None: + alignment = _axis(reasons=reasons, evidence=[formal["id"]]) + else: + contract_stale = bool(formal["alignment_reasons"]) or bool(held_reasons) + application = "stale" if contract_stale else "unknown" if unresolved_join else "current" + alignment = _axis("recorded", application, + reasons=reasons, evidence=[formal["id"]]) + projected[node]["alignment"].append(alignment) + retrofit_mapping = {"source_review": "review", "provider_distinct_review": "review", + "formal_evidence": "kernel", "numerical_reproduction": "computation"} + for retrofit in retrofits: + for node, record in retrofit["bindings"]: + axis = retrofit_mapping.get(record["axis"]) + if axis is not None: + projected[node][axis].append(_retrofit_projection(record, new["bindings"].get(node))) + return {node: {axis: _merge_axis(projected[node][axis]) for axis in AXES} for node in sorted(projected)} + + +def adapt_packet(packet: dict, expected_context: dict[str, str]) -> dict: + """Produce a loss-only derived report; never modify packet or source records.""" + _depth_and_types(packet) + require(len(canonical(packet).encode("utf-8")) <= MAX_PACKET_BYTES, "packet byte limit") + expected = validate_expected_context(expected_context) + keys(packet, {"schema_version", "old", "new", "formal_records", "retrofit_records"}, "packet") + require(type(packet["schema_version"]) is int and packet["schema_version"] == 1, + "unsupported packet schema") + captures = Captures() + gate = _gate() + old = _snapshot(packet["old"], captures, gate, "old") + new = _snapshot(packet["new"], captures, gate, "new") + nodes = set(new["graph"]["nodes"]) + require(type(packet["formal_records"]) is list and type(packet["retrofit_records"]) is list, + "native record collections must be arrays") + formal_nodes = nodes | set(old["graph"]["nodes"]) + formals = [_formal(value, captures, formal_nodes, expected) for value in packet["formal_records"]] + retrofits = [_retrofit(value, captures, nodes) for value in packet["retrofit_records"]] + identities = [record["id"] for record in formals + retrofits] + require(len(identities) == len(set(identities)), "duplicate packet record id") + regression = _regression(old, new, gate) + alignment_holds = _alignment_holds(old, new, formals, regression) + affected = {} + for formal in formals: + capture = formal["alignment_capture"] + if capture is None: + continue + identity = canonical(capture.ref) + if identity in alignment_holds or formal["alignment_reasons"]: + affected[canonical(capture.ref)] = capture.ref + regression["affected_alignment_records"] = [affected[identity] for identity in sorted(affected)] + return {"schema_version": 1, "scientific_effect": "NONE", "scientific_status_authority": False, + "custody": "unknown", "original_packet": packet, + "dimensions": _dimensions(new, formals, retrofits, regression, alignment_holds), + "formal_summary": [formal["summary"] for formal in formals], "regression": regression} diff --git a/docs/plans/2026-10-08-architecture-evidence-adapter.md b/docs/plans/2026-10-08-architecture-evidence-adapter.md new file mode 100644 index 000000000..c82b9b5cb --- /dev/null +++ b/docs/plans/2026-10-08-architecture-evidence-adapter.md @@ -0,0 +1,341 @@ +# Architecture Evidence Adapter Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Validate inert evidence packets, preserve their original records, and report independent evidence dimensions and loss-only downstream revalidation without authenticating packet custody or promoting science. + +**Architecture:** A stdlib CLI consumes one closed-schema packet on stdin and emits one deterministic report on stdout. Separate adapters retain the main and Math formal formats and existing retrofit records; the independently pinned graph gate supplies graph validation and old/new union reverse-impact semantics. Actual Git capture, native artifact readback, and formal producer custody remain a separately claimed follow-up. + +**Tech Stack:** Python stdlib, JSON/base64/SHA-256/Git blob identities, unittest subprocess controls, existing pinned `hard_gate.py`, hosted ephemeral testing in both normal and optimized interpreter modes. + +**Spec:** [Research architecture design, sections 1/4 and 8](../superpowers/specs/2026-10-08-research-architecture-design.md); [original Task 2](../superpowers/plans/2026-10-08-research-architecture-plan.md). This bounded plan replaces that task's proposed module layout and internal four-argument interface with the agreed packet/CLI ABI below. + +## Global Constraints + +- Starting checkout: main `ad4509d58aea5b1b1ac32dbea7f2be3b591a1345`; worktree `project-evidence-adapter`; coordination pickup main307/6069575569. +- This increment owns new adapter, CLI, tests, and this plan only. Formal workflows, manifests, Lean sources, existing reviews, site assets, and other owners' branches are outside the edit scope. +- Drive/R17 governs research records; GitHub executes and reviews. Scientific effect is always `NONE`; scientific status authority is always exact boolean `false`. +- Source availability, kernel verification, computation, alignment, and review remain independent. Missing evidence is not a pass. Profiles are derived reports, not another scientific-status register. +- Preserve complete original node/edge/review/receipt records. Report holds separately; never rewrite classifications, controlling flags, review verdicts, or original receipts to match the report. +- Input hashes establish internal byte consistency only. No input `authenticated`, capture flag, signature-looking string, or self-consistent native metadata can authorize external custody. Global and every axis custody remain `unknown`. +- Execute no packet-supplied Python, gate, Lean, shell, or test code; fetch no packet-selected URL/path. Trusted gate bytes must match `a78f3e25f3b0cfe113e618a4c31a7a25d7f22af638c46dec1ecba221fa333ac8` before loading their verified buffer. +- No project Python execution on the owner laptop. Observe genuine hosted missing-CLI RED before implementation; retain exact source, normal/optimized logs, failures, and artifacts. Standing owner authorization requires no new permission checkpoint. +- The corrected external suite is frozen at 35 methods in `tests/test_architecture_evidence_adapter.py`, SHA-256 `397581308cc517545b5e0e8a1716ce696a14aa7e9f885f61cd07dd46dcb7de63`. Its native-contract corrections below are the current test authority; the earlier 32-method draft is superseded. The implementation owner creates only the two new adapter/CLI files after the integration owner records genuine hosted absent-CLI RED for these corrected bytes. + +## Review Focus + +- Self-consistent forged Git/run identities remain internally checkable but externally unverified; Task 1 pins this distinction. +- Deep, oversized, duplicate-key, nonfinite, type-coerced, or contradictory captures fail without success JSON; Task 1 pins parser limits and exact types. +- A proof-body edit cannot become a statement edit; absent or incomplete declared slices yield unresolved coverage; Task 3 pins both cases. +- Partial alignment, same-provider lineage, and negative-control runs cannot become whole-manifest alignment or positive kernel execution; Task 2 pins the distinctions. +- Removed dependencies, deleted nodes, context edges, and multiple original alignment identities remain visible in union impact; Task 3 pins exact traversal and affected-record identities. + +--- + +## Agreed v1 ABI + +Create `architecture/evidence_adapter.py`, `tools/architecture_evidence_adapter.py`, and `tests/test_architecture_evidence_adapter.py`. Synthetic fixtures live inside the test module; no separate fixture files are required. The CLI requires each of `--expected-repository`, `--expected-commit`, `--expected-run-id`, and `--expected-run-attempt` exactly once. They compare declared native metadata; they do not attest capture. The module exposes `adapt_packet(packet: dict, expected_context: dict[str, str]) -> dict`; the CLI exposes `main(argv: list[str] | None = None) -> int`. + +Stdin is one UTF-8 JSON document, at most 16 MiB, maximum nesting 64. Every decoded capture is at most 4 MiB. Reject duplicate keys, nonfinite numbers including exponent overflow, trailing documents, unsupported wrapper keys, invalid base64, and nonexact identity/slice types. The tests define the original native document fields supported by each format; no invented merged native schema is accepted. + +The exact packet is `{schema_version: 1, old: Snapshot, new: Snapshot, formal_records: [Formal], retrofit_records: [Retrofit]}`: + +| Type | Exact wrapper fields | +|---|---| +| `Snapshot` | `graph: GitCapture`, `bindings: [Binding]` | +| `Binding` | `node`, `source: GitCapture or null`, `statement_slice: Slice or null`, `proof_slice: Slice or null` | +| `Slice` | `start_byte`, `end_byte`, `sha256` | +| `GitCapture` | `ref: GitRef`, `raw_base64` | +| `GitRef` | `repository`, `commit`, `path`, `git_blob`, `sha256`, `bytes` | +| `RunCapture` | `ref: RunRef`, `raw_base64` | +| `RunRef` | `repository`, `checked_commit`, `run_id`, `run_attempt`, `artifact_id`, `member_path`, `sha256`, `bytes` | +| `Formal` | `id`, `format`, `manifest: GitCapture`, `scope: GitCapture`, `source_files: [GitCapture]`, `receipt: RunCapture or null`, `logs: [RunCapture]`, `alignment: GitCapture or null`, `native_run`, `node_targets: [{node, target}]` | +| `native_run` | `repository`, `checked_commit`, `run_head_sha`, `run_id`, `run_attempt`, `purpose`, `conclusion`, `expected_conclusion` | +| `Retrofit` | `id`, `record: GitCapture`, `node_records: [{node, record_id}]` | + +`format` is exactly `main-formal-gate/v1` or `math-formal-gate/v1`. SHA-256 is lowercase 64 hex; Git commit/blob is lowercase 40 hex; counts and offsets are exact integers; native run/attempt/artifact IDs are positive ASCII decimals without leading zeros. Paths are normalized safe relative paths. Verify raw byte count, SHA-256, and Git blob framing/hash against each capture before parsing embedded documents. Slices bind byte offsets and hashes in their explicit source capture and are **declared byte slices only**, not a semantic Lean parser or coverage certificate. + +### Resolved native contracts + +All Git captures share one packet-wide immutable-identity registry keyed by `(repository, commit, path)`. Repeated captures of that identity must have identical verified raw bytes, byte count, SHA-256, and Git blob identity. Conflicts are a refusal even when the captures occur in different graphs, bindings, scopes, source lists, alignment records, or retrofit records. Consistency within each wrapper alone is insufficient. + +Main's manifest `sources` rows identify the original informal source separately from the checked main repository's `local_copy`. The origin can be an older Math commit and path while the local copy lives at a current main path such as `formal/sources/...`. Compare the node's explicit source binding to the complete origin identity, then independently verify the local copy against the native `files` hash and checked main repository/commit. Keep both roles and their original fields; never demand that the origin use main's checked commit, or join the node by the local-copy path. A mismatch in the origin join leaves kernel applicability unknown; contradictory capture or file identities are a refusal. + +Math's native `files` keys are relative to the captured manifest's parent directory. Derive a safe root-relative Git lookup path by joining that parent with each native key, and match the resulting path to `source_files`. For example, a manifest at `TEST/formal/manifest.json` with key `SCOPE.md` binds the capture at `TEST/formal/SCOPE.md`. The retained manifest still contains its original `SCOPE.md` key. This lookup rule does not add main-only source rows, receipt fields, or a node-to-target bridge to Math. + +Math alignment keeps its source-native `author`, `reviewer`, `proposal_authors`, and target declarations. Normalize lineage comparison values with split-whitespace joining and case folding; compare the reviewer with the primary author and every declared proposal author for provider, family, and agent. Empty or placeholder lineage, a matching normalized lineage component, and invalid proposer target scope cannot become current alignment. Each proposer target declaration must be a valid unique subset of the complete native target inventory. Valid partial coverage and unresolved lineage stay preserved as stale/unknown evidence, with no new accepted-review marker or organizational-independence credit. Preserve all original native annotations, including main's meaning, coordination, author, unbound-file, and negative-control fields, rather than rewriting either format into a merged schema. + +The exact report has `schema_version`, `scientific_effect`, `scientific_status_authority`, `custody`, `original_packet`, `dimensions`, `formal_summary`, and `regression`. `original_packet` preserves the complete typed input, including original base64 bytes. Sort only derived lists/maps; do not reorder retained native arrays or alter retained native fields. + +- `dimensions` covers exactly surviving new graph nodes. Each has `source`, `review`, `kernel`, `computation`, and `alignment`, each exactly `{record_state, applicability, reasons, evidence_ids, custody}`. `record_state` uses `recorded`, `not_recorded`, `unknown`, `not_applicable`; applicability uses `current`, `stale`, `unknown`, `not_applicable`. Applicability describes packet-internal consistency only; custody always remains `unknown`. +- Every `formal_summary` row has exactly `{id, format, manifest_targets, node_targets, retained_manifest, retained_receipt, retained_alignment}`. Preserve the original decoded documents and original node-target bindings; `manifest_targets` is the complete sorted native inventory. Null receipts/alignment stay null. +- `regression` has exactly `{changed_nodes, impacted_nodes, statement_changed, proof_changed, unscoped_source_changed, traversal_edges, revalidation_required, affected_alignment_records}`. `revalidation_required` is sorted `[{node, reasons}]` for affected surviving new nodes. `affected_alignment_records` contains exact original alignment `GitRef` objects, deduplicated by full identity and sorted by canonical JSON. Select them only from explicit mapped impacted nodes or stale whole-manifest/scope contracts; unknown mappings never invent an affected record. +- Malformed or contradictory packets exit nonzero, write refusal detail to stderr, and emit no success report. Valid unknown/stale/negative evidence produces a report with exit zero. Output is deterministic and cannot mutate retained records. + +## Task 1: Bounded packet integrity and preservation + +**Files:** Create the adapter module, CLI, and external CLI test module listed above. Tests launch the CLI as a subprocess, propagate `-O`/`-OO`, and use `-B -S`; they do not import implementation code. + +**Interfaces:** Consume the complete v1 packet and expected context. Produce exact typed captures and a deterministic report envelope, preserving all originals with custody `unknown`. + +- [ ] Write subprocess controls for valid deterministic output, preservation, every required CLI argument, matching/changed declared native context, and refusal of any invented capture-auth override. Fixtures are labeled synthetic `TEST.A/B/C` with `TEST.Formal.alpha/beta`; they make no actual capture or execution claim. +- [ ] Add controls for duplicate/nonfinite/deep/oversized stdin, malformed base64, decoded capture limit, byte/SHA/blob mismatch, unsafe paths, offset/hash/type errors, unknown wrapper keys, and multiple documents. A bool must not pass an integer check. +- [ ] Pin packet-wide immutable Git identity consistency, including conflicts crossing graph/source/formal capture roles; do not limit collision checks to a single record or list. +- [ ] Publish the tests-only candidate and run `python -B -S -m unittest discover -s tests -p test_architecture_evidence_adapter.py -v` and the same command with `-O` in the hosted restricted lane. RED must explicitly identify the absent CLI; an import crash, zero discovery, or unrelated failure does not satisfy this step. Root records exact candidate/run/artifact identities and original logs. +- [ ] After observed RED, implement bounded strict parsing, inert capture verification, `adapt_packet`, and the stdout-only CLI. Load only independently pinned repository gate bytes; never a gate supplied in the packet. +- [ ] Repeat those hosted commands on the exact candidate. Require all controls executed, no skipped tests, and identical discovery in both modes. Freeze and commit this independently reviewable packet boundary through the integration owner. + +## Task 2: Native evidence adapters and independent dimensions + +**Files:** Extend `architecture/evidence_adapter.py` and `tests/test_architecture_evidence_adapter.py`; CLI ABI remains unchanged. + +**Interfaces:** Consume verified captures, native documents, explicit target bindings, and expected context from Task 1. Produce all five axes and retained native formal summaries without new authority fields. + +- [ ] Pin main's dict-target inventory, source rows, file hashes, original receipt/log bindings, and Math's distinct list-target inventory in external controls. Source files must cover manifest file hashes; original receipt/log axiom inventories must name only native targets and preserve permitted axioms. Incomplete positive inventories remain unresolved and cannot produce current kernel applicability. +- [ ] Verify main origin and checked local-copy identities separately, including a Math origin at a historical commit with a current main local copy. Rebase Math native relative file keys only for safe source-file lookup and retain all native key spellings and annotations unchanged. +- [ ] Add valid failed-build controls with null receipt and retain failed/skipped/cancelled/negative records. Positive kernel applicability requires `purpose == "check"` and actual `conclusion == "success"`; matching caller-declared `expected_conclusion == "failure"` cannot make a negative control positive. +- [ ] Pin explicit main target joins: node target, node statement slice, exact manifest source identity `(repository, commit, path, bytes, SHA-256)`, and exact informal-anchor bytes within the declared slice. Unknown mappings stay unresolved. Math's native format lacks this main source-row bridge; preserve its inventory/receipt without fabricating an equivalent join. +- [ ] Add whole-manifest alignment controls: exact manifest and scope hash bindings, unique full target coverage, accepted disposition, and distinct declared author/reviewer provider/family/agent. Partial/nonaccepted/stale records remain preserved with stale/unknown applicability; lineage strings establish no authenticated review or organizational independence. +- [ ] For Math, validate every proposal author's normalized lineage and unique native-target subset, including a conflict in a nonfirst proposer, whitespace/case collisions, placeholder agent values, and foreign target scope. This extends native contract checking without authenticating any declared lineage. +- [ ] Add independent source/review/computation controls against original retrofit records. Changing one axis must not award another; graph classification, review text, matching hash, or green native metadata cannot manufacture kernel, computation, alignment, or scientific acceptance. +- [ ] Observe the corresponding hosted RED controls before implementing the two native adapters and retrofit projection. Rerun the complete adapter suite in both modes, retain originals and review this unit before committing through the integration owner. + +## Task 3: Loss-only union impact and exact alignment identities + +**Files:** Extend the same adapter and external CLI tests. Existing gate/source/review files remain unchanged. + +**Interfaces:** Consume both validated graphs, their explicit source/slice bindings, and Task 2 dimensions/native identities. Produce separate regression lists and exact original affected alignment refs; preserve original graphs unchanged. + +- [ ] Write changed-statement, proof-body-only, missing-slice, unscoped-source change, availability-loss, failed/skipped/missing receipt, stale alignment, removed-edge, deleted-node, added-node, context-edge, and unknown-mapping controls. Include full-record nested type changes that ordinary Python equality can hide. +- [ ] Write the original alignment-identity control: old/new union impacts a downstream node, and `affected_alignment_records` names its original repository/commit/path/blob/SHA/bytes exactly; canonical sorting/dedup cannot merge different original identities. Unmapped nodes yield no guessed review ref. +- [ ] Observe hosted RED, then implement canonical full-record comparisons and pinned union reverse impact. The gate uses **all** old/new `(from, to)` edges, including deleted/context edges; required-edge cycle validation remains a separate rule. Only surviving new nodes appear in revalidation proposals. +- [ ] Keep stable reason codes: `node_record_changed`, `dependency_edges_changed`, `graph_context_changed`, `statement_changed`, `proof_body_changed`, `source_changed_unscoped`, `dependency_changed`; axis reasons include `manifest_binding_changed`, `scope_binding_changed`, `target_coverage_changed`, `alignment_not_accepted`, `lineage_not_distinct`, `native_run_not_success`, `native_run_negative_control`, `native_context_changed`, `missing_statement_slice`, `missing_target_source_binding`. +- [ ] On a proof-only edit, invalidate affected kernel evidence and explicitly byte-bound reviews. Whole-manifest alignment can stale when manifest bytes change; report that binding change without adding `statement_changed` if its declared statement slice is unchanged. A fresh successful kernel record cannot automatically refresh alignment. +- [ ] Run the complete hosted suite in normal and optimized modes on frozen bytes, obtain fresh nonauthor source review, reconcile findings, and preserve the exact report/artifact. Root verifies required current-candidate checks and performs protected integration; this plan author runs no code or Git writes. + +## Completion boundary and follow-ups + +This increment is complete only when the exact CLI ABI and every substantive control pass in hosted execution with original records preserved and reviewed. That establishes packet validation and regression reporting, not authentic Git capture, native artifact custody, actual semantic alignment, or all-eight architecture completion. + +The current dated 49-node graph has no explicit node-to-Lean mapping. A shared informal-source hash does not make the full graph claim kernel checked; main's SIDE24 targets explicitly retain narrower scopes. Synthetic fixtures cannot fill that gap. + +## Observed execution and native-contract correction + +The corrected 35-method tests-only candidate `cb39e820828be33628258e18663645be002eec02` produced genuine missing-CLI RED in hosted run37851327382 at checked merge `70c0eb3e7615636435e50b28c887f34030329380`: both modes ran124 methods, with89 prior controls passing and all35 adapter methods failing93 assertions including subtests. Original artifact11582351325 raw ZIP SHA256 `5293a37af057d4302f2a61de945f7e85265cae615c6bb34581b952f827f71a50` and its eight retained member hashes were verified. Earlier fixture corrections and the initial32-method attempt remain historical evidence. + +Implementation candidate `8212d488182f8dba0723c075a30bf356bc4004d7` produced historical35-control GREEN in run37853081951, checked merge `f740b78f13d680eb500a481b775eb246a9052fae`: both modes ran124 distinct methods and OK. Original artifact11583381174 raw ZIP SHA256 `ac0b327ed7cc2ea690d222619519fa5f733efa4976c4da521da1e84549c152c5` was downloaded; a distinct data reader verified all12 fixed manifest member hashes, all eight receipt input hashes, both exact124-method inventories and the native identity files. That success did not close later source findings. + +Nonauthor source review5463623676 requested changes for substitution of the actual native SCOPE.md, swapped negative-control rejection mechanisms, and unsupported Main producer toolchains/Lean versions. Three external methods were added without changing the original35 methods, freezing38 tests at SHA256 `3180ae17437a457bf003165cde168207e1e912cfc4f68b40f07e94c33cac1b04`. Tests-only head `04b17cb807a3f55c017c1dd5b50bdfe3914cb91c` produced genuine contradiction RED in run37853766162, job113572914457, checked merge `f6c7e68aef566c031a6c5964e3c9178f1e359c4a`: both modes ran127 methods; the prior124 passed and three methods failed eight assertions because the CLI returned0 for two scope substitutions, four phase substitutions and two incompatible version substitutions. Original artifact11583044083 raw ZIP SHA256 `4a20e625316ac661133cc7094003204efba3d66d2c305daad2111c4d9c74650a` and all eight retained member hashes were verified. Architecture failed, landing skipped and verify failed despite native formal success; disposal, failure retention and strict release succeeded. + +The corrected adapter must identify Main scope by `package_root/SCOPE.md` and Math scope by the captured manifest parent's `SCOPE.md`. A different manifest-bound module is a contradiction. Main manifests must use native `leanprover/lean4:v4.34.1`, and Main receipts must contain the exact4.34.1 version token. Registered mutation controls must have `REJECTED_BY_LEAN`; the producer's special `sorry`, `custom_imported` and `native` controls must have `REJECTED_BY_AXIOM_GATE`, including its overwrite order. Supplied contradictory outcomes refuse; missing outcomes retain incomplete evidence. Native annotations and original packet stay unchanged. + +The author amended only `architecture/evidence_adapter.py`, frozen SHA256 `dd36165bf21fb595c6179169af13b468dbd1af76b08b3068da69abf11598a101`. CLI and38 tests remain unchanged. Fresh127-method hosted GREEN, original archive custody, exact corrected-source nonauthor review and integration remain pending. All evidence here is delegated AI/source-exposed with organization-independence credit0 and scientific effect NONE. + +## Corrected38-control GREEN and source review + +The pending sentence above is the preserved pre-GREEN checkpoint. Corrected candidate `2a1e82e823d6eb254ebef8b2091310947f4f570f`, tree `d2cbe928e316573c70786a5ff0bb8a10e0078087`, ran in [run37854584089](https://github.com/d6g8k5htny-coder/main/actions/runs/37854584089), architecture job113575593781, checked merge `9f6f9e5a7df83d6e2f7e577197fbee777f23c5c0` with that same tree and parents879fb4f5/2a1e82e8. Both normal and optimized modes ran127 methods and OK, with89 prior controls and38 adapter methods; each receipt inventory contains127 unique full IDs and the inventories match. All eight head checks succeeded. + +Original artifact11582819796, name `research-architecture-37854584089-1`, is22823 bytes with raw ZIP SHA256 `ddd0ef974f512af0a10dad6660e398b955d372bc2731a5355daf63af58a22449`. Root downloaded and verified all12 manifest members and eight receipt-input hashes. Receipt SHA256 `871954a355f5891acc28b444b0088dd79fa7b1e5e004b48097be2ff470e5abfe` binds the original native checked commit/run/attempt/repository; caller job113576932166 emitted the exact same eight native binding values including archive and receipt identities. Generated graph SHA256 remains `30cdcedabbdd3d9906a6cf13c838a23424ca065225d179c112db3ed7f5b3aa7f`. Container disposal, bounded collection, strict release and accepted native emission succeeded. These are original identities, not substituted integration identities. + +Fresh nonauthor [review5463745559](https://github.com/d6g8k5htny-coder/main/pull/325#pullrequestreview-5463745559), actual OpenAI/Codex `/root/repo_inventory`, accepted this exact corrected adapter and independently compared the Main native producer's scope/toolchain/version/negative-control ordering. It closes all three findings in review5463623676. Null, partial, failed, negative or stale evidence cannot award positive kernel applicability. The CLI `ad759f3f…` and38-test file `3180ae17…` remain unchanged. Organization-independence credit0, custody unknown, scientific effect NONE and authority false remain explicit. + +PR325 was marked ready on8October22:47UTC; native readiness review completed at2a1e82e8 without findings. Its merge remains held behind the coordinated317→324→325 integration queue. Main advanced through math PR326 and site PR317; these historical GREEN identities therefore do not establish current-base integration. Root will reconcile exactly the four adapter paths onto the actual integrated source-isolation main, preserve the three reviewed executable/test byte identities, and obtain fresh127 required controls plus the separate ten casefold controls and original native archive readback before an expected-head normal merge. + +PR324 subsequently landed through a guarded normal merge at actual main `f08dfdf9ec4dbf62553766a7d6b6a758f1f99f9a`, tree `f0a4db84c978edef586eb93b7ff03d0ff7b8270e`, parents00bcd986/f6e90d2d. Native main/tree/parents readback matches its tested tree. Root now reconciles exactly these four adapter paths onto that source, preserving all source-isolation/site/brand/math content. Module `dd36165b…`, CLI `ad759f3f…` and38 tests `3180ae17…` remain byte-identical to review5463745559. Fresh hosted127 required controls and ten separate casefold controls, native original archive readback and current-head readiness review remain pending for this new revision. + +Separately claimed work must acquire exact Git `commit:path` bytes and original native run artifacts, verify archive digests with a fail-closed readback, bind producer identities/current native context, and retain original manifests/receipts/logs. The existing formal upload lacks artifact ID/digest/name outputs and its name omits attempt; the original receipt lacks attempt. Do not edit those producers here or invent authenticated capture from this packet. Base/candidate real-input collection, every-PR required enforcement of this new adapter, SSG artifact consumption, and actual Math transition integration remain unimplemented until separately tested and reconciled with their current owners. + +## Current-base evidence and author-lineage review + +Reconciled head `60aa00e9cc85b548c5c2f93181dda294f2599737` produced fresh required run37857698366/attempt1, checked merge `5d73e7900d2524d1131ab0698c1eb51213c389cb`, tree `a9411c6649b6a584db39c3a27ccab8aae5295217`, parentsf08dfdf9/60aa00e9. Both restricted modes passed127 unique identical methods, normal90.137s and optimized87.243s. Original artifact11585146326 is22815 bytes, raw/native SHA256 `946d63d15605ea65f6f1ffeeac45d5fbed62c11293b5c90b83c1ed0ea996c41f`; all12 manifest hashes and eight receipt inputs match. Receipt `c576661ca269678871cb4ceee164f18c326069ac65e26f0e70353fc959383cae` binds original four native context fields; caller113586792384 accepts all eight exact bindings. Graph30cdceda is unchanged. + +An actual workflow_dispatch casefold probe37858013139/attempt1 at the same checked5d73e790/treea941 passed2x10, with native ext4 F precondition and durations1.379s/1.392s. Original artifact11585096776 is4767 bytes, raw/native SHA256 `bbb01359f530e24e116a45bda09a5ad2605b121274a85357217dcaf5930a4fee`; all ten member hashes match. This was a dispatch at the checked revision, not a rerun or rebinding of historical evidence. Root verified both original ZIPs with data-only reads. These passing controls do not close later source findings. + +Automatic review on60aa00e9 raised two P1 suggestions. Independent receiving-review assessment by actual `/root/required_binding_tests` and root rejects mandatory Math proposer target lists (thread4225066097): native Math formal/gate.py88-99 preserves historical optional targets, while100-103 still compares every declared proposer lineage against the reviewer. An absent subset is an unscoped whole-manifest proposer under that v1 format. A focused positive omitted-target control and negative unscoped/nonfirst lineage conflict controls will preserve it; no native Math format is changed. + +The Main author consistency finding4225066106 is accepted. The retained manifest declares source author provider/family/agent, but the adapter currently compares only parties claimed inside alignment. Relabeling that author can make a reviewer equal to the real source author look independent. Main manifest18-22, SCOPE54-55 and REVIEW_LANE74-75 preserve that source lineage. Freeze focused external controls against the unchanged module `dd36165b...`: each field mismatch, relabeled author plus actual-author reviewer, and coherently rehashed missing/invalid manifest author. Include strip/casefold-equivalent valid lineage as a positive. Such packets retain their original records and independently applicable kernel axis, while alignment is noncurrent and its exact original reference requires revalidation. Math has no manifest author requirement and keeps its original format. + +At this checkpoint no merge has been attempted. New author-binding controls, genuine hosted RED, Main-only correction, exact corrected-source nonauthor review, fresh full GREEN and original archive readback remain pending. Owner authorization already exists; this hold is for substantive technical validation. Packet custody remains unknown, scientific effect NONE and authority false. + +The pending RED checkpoint above is now superseded operationally by actual run37859224871/attempt1, architecture job113590723075. Tests-only head `ebc12a64609beb8ef368c911af220fe27c693a4e`, tree `0818b162de0f9bdfd40822aa4e114e02d29fde67`, checked merge `c333ab76dccfaa982e07a9ef3b63d1328d2a6c9c` with the same tree/parentsf08dfdf9+ebc12a64 preserves implementation dd36165b and CLIad759f3f. Both modes ran129 methods: prior127 and the Math optional-scope method pass; the Main author-binding method fails12 coherent cases because alignment remains current. Normal89.026s and optimized88.843s. Native formal succeeded, architecture failed, landing skipped and verify failed; disposal, failure archive and strict release succeeded. Accepted identity emission skipped. + +Original artifact11586085043 is19357 bytes, raw/native SHA256 `e207a2cb103e0ea8a613b1c5ce86e76fdd9172210f360763e3a3f26a155569c2`; all eight retained member hashes match. Root read both full original failure inventories. Frozen40-test SHA256 `7de370ea659d289edf0560a93daba6e0eb1d2edaa67a0ae6d4c1ae45983ab710` adds only lines825-922; deleting those98 inserted lines recovers original38-test SHA3180ae17 exactly. The author is now correcting only the Main lineage consistency check. Source review, fresh129 GREEN and integration remain pending; the real failure is retained without rewriting earlier successful scope. + +The Main-only correction is SOURCE_PREPARED at module SHA256 `49fc152b6f8b2df099677469db510a56942c7df81f03890a95bad940b23cf310`. Root's source comparison against retained dd36165b confirms exactly three edits: optional source_author input to alignment analysis, Main-only retained-lineage comparison/reviewer distinctness, and the callsite supplying manifest.get(author). Existing Main strip/casefold semantics derive `manifest_author_unresolved` for missing/malformed source lineage and `author_binding_changed` for a different claimed author. Existing stale-contract handling names the exact original alignment reference. Kernel calculation, original packet/records and the Math branch are byte-identical. CLIad759f3f and40tests7de370ea remain unchanged. This is a source acceptance by a distinct implementation nonauthor, source-exposed organization-independence0; fresh129-mode execution, exact original archive custody, current automatic review and integration remain pending. + +## Placeholder lineage and shared alignment regression follow-up + +The prior pending129-mode checkpoint is superseded by genuine GREEN run37859841587/attempt1 at exact head98608a1ee4e54467d0df95106baa461768250233, checked merge4d5c40335adf4e1487269491a97412fde69ac962, tree762dac9575d24a4167603c91b9f44d79290bdb81, parentsf08dfdf9/98608a1. Both restricted modes report129 unique identical methods/OK, normal112.380s and optimized113.214s. Original artifact11586071017 is23036 bytes, native/raw SHA2564f97d252e8dc9e80ff935bd131d233ed8427a0c8d52907d424461332d31ed79e; all12 manifest members and eight receipt inputs match. Original receiptb284d9037046894ead0f59bcdc785017750c17d7a9f8cba4213b94e3b854fd3f matches the native context and caller113593860702's eight bound outputs. All eight head checks succeeded. Fresh actual root nonauthor source review5464070754 accepts the Main-only author-binding source49fc152b; organization-independence0 and scientific effect NONE remain. + +Automatic review6070628711 completed on98608a1 at23:38:27UTC and raised two NEW findings4225219972 and4225219976. Root and actual original implementation author /root/architecture_design_review independently confirm both source paths. Main's strip/casefold comparison must remain native-compatible, but recognized unresolved words must be rejected independently of comparison mode. This is a conservative adapter guard: the native Main gate itself checks nonempty lineage, rather than already providing this placeholder guarantee. Graph/dependency/context regression must also make impacted explicitly mapped alignment noncurrent. A whole-manifest original alignment record held for revalidation must not be simultaneously projected current through another explicit mapping of that same record. Its other mappings need an explicit shared-record reason, without inventing graph impact or erasing independently current kernel evidence. A separate unimpacted original alignment identity can remain current; no fuzzy target join is permitted. + +Root-authored external controls add only111 lines924-1033 to the original40-method file:42 methods, SHA256a761861bce9b35e2d5ad0be7655b8e9bf1ed0fc675735b26ee9b8ad61bb90792. The first method covers16 literal reserved words with decorated case/whitespace for a reviewer and a coherently rebound manifest/alignment author, plus each single unresolved lineage component (38 cases). The second retains a source-bound unchanged positive, shared B/D whole-manifest alignment and a separate E review identity, then challenges upstream statement, proof, source loss, node record, removed dependency, relation and whole-graph context changes. Original records and kernel applicability remain independent, and unmapped C retains unknown alignment. Source review and actual hosted RED are pending; implementation49fc152b and CLIad759f3f remain unchanged. There is no local Python/Node/test execution or merge attempt. Earlier GREEN scopes and genuine failures remain retained, without claiming these new cases already passed. +Fresh actual /root/graph_tests_review nonauthor source assessment ACCEPT_SCOPED_SOURCE covers the exact new a761861b tests and their native capture/mutation helpers. Data-only deletion of111 added lines924-1034 reproduces original40 SHA7de370ea exactly. The independent review confirms38 coherent placeholder cases, admitted positive source joins, seven union-regression cases and shared-record versus separate-ref controls, without a kernel or organizational-independence claim. Source runtime remains NOT_RUN; publish tests-only against unchanged49fc152b before any implementation correction. +Actual new two-method RED is now retained: run37861392790/attempt1, architecture job113597709898, tests-onlyfd8fe0f5, checked1ab7c8d7635772c81b6cbad0208baf2ed867dd0d/tree4cc75004ea8bd4099a5c70c15791b0b7019d6207/parentsf08dfdf9+fd8fe0f5. Both original full logs ran131 methods with45 assertion failures:38 placeholder cases and seven upstream/dependency/context cases, while129 prior unique methods pass identically. Normal73.181s and optimized73.349s. The shared-record D assertions occur after the first failing B assertion and remain to be exercised after correction. Native formal succeeded, architecture/verify failed and landing skipped; failure archive/disposal/strict release succeeded, accepted identity emission skipped. Original artifact11585544866 is22614 bytes, native/raw SHA256be9d35e25261c74cf1ef8680084c0c36cbe8c0e941e8e093b19c3fc6af02d9a4, and all eight original ARTIFACT_SHA256SUMS payload hashes match. Root read both complete failure inventories. An initial data lookup requested nonexistent SHA256SUMS.txt; original member listing established ARTIFACT_SHA256SUMS and its readback succeeded, with no archive transfer retry or product execution. Distinct implementation author /root/graph_tests_review is now assigned a bounded module-only correction after this actual RED; frozen42 tests and CLI are unchanged. Fresh source review, full131 GREEN, original custody and current automatic review remain pending. +Fresh actual root implementation-nonauthor source assessment accepts exact module08adf2661a3ee490f1f9f12bf58f0a97bd5237b6f078bad1127988428757746e after reading both changed functions and comparing the complete source against retained49fc152b. Exactly five bounded replacements add1059 characters: placeholder recognition independent of lineage comparison mode; a canonical-full-GitRef hold map derived only from existing explicitly mapped revalidation proposals; and whole-record stale projection with actual regression codes plus alignment_record_revalidation_required. The entire regression/main-source-join/kernel/adapt_packet functions, original records and affected-ref selection are byte-identical. Root authored the two new external tests and is distinct from this correction author /root/graph_tests_review; exposure is source/test-exposed and organization-independence0.42tests a761861b and CLIad759f3f are unchanged. Fresh hosted131-mode GREEN, original archive/native readback, current automatic findings and later-current-main integration are still pending; no local execution or merge attempt. + +The last pending checkpoint is superseded by genuine required GREEN run37862438657/attempt1, architecture job113601103968, headf756883c22ee54ef0f3b6b2889fc3ef428ebcc50 and checked merge8dbcea659f971511cbd4c902165d664368176199. Native commit readback establishes tree3e25c79164a24a8a87caefddc0325eebe21cd864 and parents0be54aa227d7015b0abda00feb5e847a3fbdbcdb+f756883c. This run therefore already executed against actual integrated PR329 main, rather than the older base shown in the earlier PR snapshot. Both restricted modes ran131 unique identical methods and OK, normal78.450s/optimized78.286s. The new placeholder and shared-whole-record assertions all pass; the genuine45-failure RED above remains retained. + +Original artifact11586009565 is23226 bytes, raw/native SHA25633a126dc59eb8cf6c79877039b6f5374fcce400099ac039686c914ef645160ae. Data-only readback verifies all12 ARTIFACT_SHA256SUMS payload hashes and all eight receipt inputs; original receiptf94e324b132c51026e886b07e202348be64f843e2506f52170b10928228e9ea7 retains native repository/checked commit/run/attempt. Caller113601946828 emits the same eight bindings, including artifact ID/name/raw hash and receipt hash. Formal/architecture/landing/verify all succeed; disposal, bounded collection, strict release and accepted identity emission succeed. No local project execution occurred. + +Actual PR329 main is0be54aa227d7015b0abda00feb5e847a3fbdbcdb/treeef353151f01ebe3db7c79595d21d401b5cd194e9, parentsf08dfdf9+1966a746. Root now composes exactly the four adapter paths over that main, preserving all seven mathematical Markdown changes and all other peer content. Executable08adf266, CLIad759f3f and42tests a761861b stay byte-identical; only this evidence history is appended. Fresh exact-final hosted131 controls, ten casefold controls at the final checked revision, original native archive readback and current automatic review remain the integration gates. Root's implementation-nonauthor source review5464256529 is source/test-exposed with organizational independence0; custody remains unknown, scientific effect NONE and authority false. No merge is claimed here. + +The exact-final historical checkpoint is now genuine GREEN at head890824aea56b82c4f43df12edeeceadb80d28eae/tree7ba11102e002fb00215e7bbad765ec2ba7b221b6, checkedaaef6e3629733f55a901b822b2e0ab43521ba2a9 with nativeparents0be54aa227d7015b0abda00feb5e847a3fbdbcdb+890824ae. Required37863413817/architecture113604310327 ran131 unique identical methods in normal120.448s and optimized120.626s, all8headchecksSUCCESS. Original11587267910 is23226B/native-and-rawSHA256fd92df6f097b1f809835781c17983f5348f27a0ae6a471e2bbeca3c3e2277a44; all12payloadhashes and all8receiptinputs match, receiptf18204fb85655a1d0060a225c7df71685f76e51e9f0261c8bfae30148e29857f, accepted caller113605523117. Casefold workflow was dispatched once at that exactcheckedrevision as37864769784, job113608763418SUCCESS, normal10/1.407s and optimized10/1.414s identicalPASS. Original11587524002 is4761B/raw-and-nativeSHA256a75d2cd62604d77320083671c0cec5b72931050d29b9d78f2a8c5d244672baab; all10payloadhashes match. This checkpoint is bounded to those controls, not a merge or comprehensive acceptance. + +Current automatic review5464349566 on890 raised four additionalP1 findings4225427323/333/337/342. Root and actual /root/graph_tests_review independently assessed them against full adapter source and actual original native formal producer bytes. Caller expected repository/commit/run/attempt belongs to kernel applicability and must not alone stale unchanged statement alignment or its affected-record list. Historical formal node mappings must be admitted against old/new node union, retained even for a deleted node, selected for affected alignment from changed_nodes union impacted_nodes, and projected into dimensions only for survivors. Outside-both mappings remain a contradiction; no fuzzy node/target join is added. + +An exact successor review needs an explicit new graph review context to discharge a graph/dependency hold. A newer commit or bound source/manifest alone does not establish review of changed dependencies. The optional original alignment document field `reviewed_graph` is a complete closed GitRef with the same six exact fields and syntax/type limits as the table above; its canonical identity must equal the already verified new snapshot graph capture ref. It is internally declared review context, with custody still unknown. Malformed supplied refs refuse; absent, valid old or valid mismatched refs preserve a regression hold. Clear a held original alignment identity only when its full manifest/scope/target/lineage applicability is current and every formal use of that same canonical original alignment ref satisfies this reviewed context. Preserve the original old/new comparison, review bytes, graph impact and independently current kernel evidence. This additive original-document annotation does not change any closed packet wrapper or authenticate a review. + +The empty-log suggestion requires native compatibility care. Actual successful original formal artifact11586807198 from37863465487 contains a legitimately zero-byte receipt/leanchecker.log,237Bbuild.log and25152Belaborated-types.log. Main execute257-264 checks successful command exits without requiring checker output. Its silent success remains valid. Missing/empty/whitespace/partial/duplicate/foreign elaborated target coverage cannot supply complete current kernel evidence; record all original logs and derive unknown applicability. Validate each expected native target exactly once with substantive type evidence, accepting actual multiline and parameterized headers rather than requiring a colon on the first line. This is log-coverage consistency, not Lean type parsing, theorem execution or source-to-meaning proof. + +Root-authored four external methods add95lines1035-1129 to the frozen42 controls:46methods,1131L73897B,SHA256897701ff6d981b59c1ec5679f578c083e69143e8ad45c3898d323ac00a5bf056. Deleting only those95lines reproduces original42SHAa761861bce9b35e2d5ad0be7655b8e9bf1ed0fc675735b26ee9b8ad61bb90792. New controls cover proof-body/added-context-dependency/whole-graph successor reviews with exact, old, mismatched and malformed reviewed refs; four independent expected-native mismatches; deleted and shared surviving formal mappings plus outside-union refusal; silent-checker positive and seven incomplete elaborated-log variants plus multiline positive. Both implementation08adf266 and CLIad759f3f stay unchanged. Fresh nonauthor source review and genuine135-method hosted RED remain pending before implementation correction. The old131GREEN and casefold evidence remain retained. Temporary PR335 peer integration may proceed under its own concrete evidence; root will compose successors over actual resulting main. No local Python/Node/tests or merge attempt occurred. + +Fresh actual /root/graph_tests_review source assessment now ACCEPT_SCOPED_SOURCE for exact46testSHA897701ff after reading all95new lines and full capture/formal/replace_log/assertion helpers. The reviewer confirms coherent immutable captures, native logs/receipt updates, legacy held and exact successor contexts, independent evidence axes, deleted/surviving union behavior, silent-checker and substantive multiline elaboration controls, and exact42-source recovery. This is source/test-exposed nonauthor review with organization-independence0. Actual135-method hosted RED remains NOT_RUN; implementation and CLI stay unchanged until that observed failure. + +The pending RED is now actual retained failure: head0fdfe616e9ef49848a49e02179dc81650d90b170, required run37865603185/architecture113611466558, checked4c3dbce50bb360a089e598832499e7079259cada/treecfe416ed77c459c3410b05e7d41727ad67e93350/native parents0be54aa2+0fdfe616. Both restricted modes discovered135 methods, normal130.363s/optimized130.706s, and each preserved15 failed assertions: deleted formal mapping1, incomplete elaborated coverage7, exact successor graph revalidation3 and native-only context isolation4. Prior131methods pass. Original artifact11588311835 is21214B/raw-and-nativeSHA256023ceebbbe4eb08086d3d6b10e578e3a4f259369ddf08c15925819aee2be0baa; root verified all8 retained payload hashes and read complete original normal/optimized logs. Formal native success did not override failed architecture/verify or skipped landing. Original failure remains part of the record. + +Following owner token-restoration6085820307 and root scope-resume6085859861, actual /root/graph_tests_review authored only the module correction SHA2565fb28b0b64054163b6fd529951802c78bdfbb0de19d74ed285161803a68e9fad (1106L59210B;109insertions20deletions). It validates optional reviewed_graph closed6-field refs, groups full original alignment identities consistently for dimensions and affected records, clears a regression hold only with every formal use's full current bindings and exact verified new graph context, isolates expected native context to kernel, admits old/new formal-node union while projecting only survivors, and checks exact substantive multiline elaborated target coverage without rejecting silent checker success. CLIad759f3f and46tests897701ff remain byte-identical. Root fresh source review read the complete1106-line module and frozen tests, inspected all changed helpers and source preservation, and accepts this scoped candidate for hosted validation. Root is a nonauthor of this implementation, author of the four new methods and previously source-exposed; organizational independence0. This is source acceptance, not corrected runtime GREEN, authentic custody, scientific alignment acceptance or integration. + +Actual main on resumed reconciliation is032267c259162728229e3ddd14d08fe1c3f9a392/treea32a3a7c6dc4fe6715e8c912f31181637fb8b7fe after337. Publication composes only these four adapter paths over that main and preserves every intervening peer change. Exact135-method hosted GREEN, original archive readback, current automatic review, exact checked-revision casefold controls and review-thread closure remain required before ordinary protected merge. The full eight-item objective remains active. + +## Retained135-method GREEN and three-regression resource amendment + +The last pending135-method checkpoint now has actual hosted GREEN: head5b0d2a3248ee6f67518c7f89fe4060870caf43af, run37967019742/attempt1, checked7fc8e2c8fbb67980ffa203b0d34c084811d5bda4/tree6352cd67f69112fd1294c0fa49470f52e84148b4, ordered parents032267c259162728229e3ddd14d08fe1c3f9a392+5b0d2a3248ee6f67518c7f89fe4060870caf43af. Both restricted modes ran135 identical unique methods/OK, normal133.599s/optimized131.179s. Original artifact11634551473 is23577B/raw-and-nativeSHA2568ec0a27b7132d086f54de6c273ba63ac08832d6a87714581fcc652f7647fd2eb; root verified all12payload hashes and eight receipt input bytes/hashes, original receipt54bf2991327556180fe3d81cc0ed0e96078a416abea0056b9136f6d4a5e57f1f, and native accepted caller113945671475's eight output bindings. This remains its bounded historical scope, not final acceptance or a merge. + +Actual automatic review5473413944 on5b0d2a32 raised three new findings4232898480/8492/8497. Root and distinct test author operations_contract_review assessed the unchanged implementation5fb28b0b against these source paths. A comment-only text following a declared target's colon cannot establish a substantive elaborated type, while quoted comment markers, trailing/nested comments attached to substantive types and legitimate multiline native headers remain compatible. An exact new reviewed_graph identity cannot clear a whole original alignment record if any Main use lacks the complete node-to-origin-source/statement/target-anchor join; independently current kernel evidence and a separate original review remain independent. The pinned gate repeatedly scans outgoing edges, so the adapter needs a bounded graph cardinality admission before invoking that independently pinned gate; this source assessment is not a measured runtime estimate or evidence that the full every-PR graph product is complete. + +This additive v1 resource ABI admits at most256 nodes and2048 edges in each old and new captured graph, including aliased immutable captures. Verify capture byte/blob/hash integrity and parse the original graph, then refuse excessive cardinality before any pinned graph-gate classification/traversal. A refused packet exits1 with empty stdout and a deterministic stderr prefixed `architecture evidence adapter refused: ` containing `graph node limit` or `graph edge limit` respectively. Cardinality admission precedes gate classification even if an oversized original graph also contains an unsupported classification. Exact256/2048 boundaries remain admitted when otherwise lawful. The dated49-node/55-edge graph is within this scope. Existing16MiB packet/4MiB capture/depth64 and inert-code/custody/scientific boundaries remain unchanged. This is a deliberately bounded adapter contract, not a25,000-node performance benchmark, optimized gate replacement or full architecture completion. + +Exactly three additive external methods are SOURCE_PREPARED at49methods/1285L/85510B/SHA256ed65e2ae0a4d2f52436ccfd6a5c4774bf5b2f3fbf0cfdd33f3caa9ec231707be. The154-line block1130–1283 has zero deletions; passive deletion recovers original46SHA897701ff6d981b59c1ec5679f578c083e69143e8ad45c3898d323ac00a5bf056. The comment-only method covers four compatible substantive positive logs and nine missing-target comment-only negatives with a silent checker. The shared-alignment method retains unchanged/exact-successor complete-join positives and three coherent Main join-loss cases, holding the shared original record once while the joined survivor's kernel and disjoint review remain current. The cardinality method has four lawful exact-boundary positives and twelve old/new/alias oversized or classification-order negatives, each with two deterministic CLI calls; all graphs remain at most257nodes/2049 unique shallow context edges, raw graph below512KiB and packet below2MiB, without timing probes or gate mutation. + +Actual source author operations_contract_review; fresh distinct graph_reader_design_review ACCEPT_SCOPED_SOURCE reads the entire154-line delta and all constructors/helpers1–307, confirms exact46 recovery and unchanged module5fb28b0b/CLIad759f3f/trustedgatea78f3e25. Source/test-exposed, organizational independence0 and scienceNONE. Root owns this contract amendment and publication; neither test author nor reviewer edited implementation or ran local project code. Publish these tests and this additive history against unchanged implementation before any correction. Genuine138-method hosted RED, original logs/native/archive readback, distinct implementation correction, fresh full138GREEN, current auto review, exact-final checked-revision casefold and all thread closure remain pending. Source-only static mismatches are not the required hosted failure. Main integration remains queued328 then325 under root's current coordination window; source publication does not merge or seize a peer scope. + +## Actual138-method RED and distinct module correction after PR328 integration + +The49-method tests-only head2601c2cc97d51c2f324653d01107b084ace6ff46 produced actual restricted hosted RED at required37973350254/attempt1 architecture113965305742. Checked a1c149daceb652002099ae0050bc80a85edaf3fb/tree70ee4bc61beb90138fa4cfcdd96a0c2fdaa96a27, nativeorderedparentsd52c6fdc1dc4e66fd26290a9a01fc9739edcc50b+2601c2cc97d51c2f324653d01107b084ace6ff46, independentlyverified. Both modes ran138identicalunique methods: prior135PASS,30failedassertions (9comment-onlycoverage,9wholealignmentjoinloss,12cardinality/classification-order), normal141.161s/optimized140.481s. Original11638147575/25385B/rawSHA9885fdbfc084c0e8114512caece7c176fec1fb1076f6f1dfed03f0e6ff20fa23/all8originalpayloadhashesMATCH; completebothterminalinventories/statusesreadbackMATCH. NativeformalSUCCESS,architecture/verifyFAILURE,landingSKIPPED;disposal/staging/originalupload/strictunmountSUCCESS. No import/setup/timeout substitution or positive receipt. Publicnativefullbody325/6086949806 matches. Separate navigation host execution37973349934 reports578methods/30failures/8skips; it is retained but is not credited as restricted product execution or goal6 closure. + +Distinct implementation author graph_reader_design_review then froze only the correctedmodule1165L/61612B/SHA2560cae76aab14440185e540d94edb6517e132ff9049a815e04c941a2ca0f19edce, exactlyfourhunks/+60/-1lines/+2402B from previous5fb28b0b. After verifiedcapturebytes/strictJSONparsing, exactcontainer/node/edge bounds now precede the independentlypinned gate. A linear scanner masks line/nestedblockcomments while retaininglayout/CRLF/escapedquotedstrings; incompleteblock/string refuses typecoverage, lawfulEOFlinecomment remainscompatible. Wholeoriginal alignment revalidation additionally requires everygrouped Main mapping to survive and pass the existing exact source/statement/target-anchor join; Math uses its preserved separatecontract. This predicate does not collapse kernel execution into alignment. Frozen49tests ed65e2ae/CLIad759f3f/gatea78f3e25 remainunchanged. + +Actualroot, a distinct module nonauthor, read the entire1165lines and checked the exactfour-hunk reconstruction against freshly fetched native2601preimage; ACCEPT_SCOPED_SOURCE, source/test-exposed/org0/NONEfalse/custodyunknown. This source review does not establish corrected runtime. No localprojectcode/tests/Python/Node/YAML/database/model execution occurred. + +PR328 actually integrated by one expected-head normal merge at2026-10-09T18:57:31Z, merge36eed0e9e2c7d4d1ad26bc2c2ae8499d31e78563/tree4451d3d3156df6c339b4cd19019da1e449779459, orderedparentsd52c6fdc1dc4e66fd26290a9a01fc9739edcc50b+7afae61f50bbc2baa98b7a58ba0af72ffb90a2b4; allfourmergedsources literalMATCH reviewedhead. FullC225executionreview5474060811 and canonical compactDrivecarrier1AIRSrtj3B0aRFJ0Twhvfpg94J3E2BqPd/850432B/SHA7063b4c9829ed0495a0a91b53cbc8d0007e09d0efc26a8dbd2c9bf9d7ffd389f arepublished/nativebyteverified;85R17cells/formatsmatch. The carrier explicitly excludes three external originalGitHubZIPs, locallyverified; firstlargeTARupload remainscreationUNKNOWN afterMCPtimeout, and overwrittenearlierfirst-runLeanlogbytes remainNOT_RETAINED. No scientific promotion. Nativecoordination307/6087325748 explicitlyreleases328integration andadvances onlyroot's retainedwindowto325. + +Publish the corrected four adapter paths over actualmain36eed0e9, with old2601head andactualmain asorderedparents, preservingallpeer/main/runtime sources. Freshfull138normal/optimizedGREEN/originalnativearchivecustody/currentautomaticreview/exactfinalchecked-revisioncasefold/allthreadclosure remainrequired beforeordinaryexpected-headmerge325. All eightgoals remainACTIVE. + +## Negative-control original-log coverage amendment + +Automatic finding4233374415 at head8aedd7a6ef0ba0c2d71f13d9978400327f780035 is accepted as a source defect: a self-consistent Main packet can remove every required negative-control log from both original-log and receipt inventories while retaining all outcome labels, and the current module still regards its formal record as complete. The preceding required138-method run37977491475 is an earlier-control checkpoint; these new cases were absent. Its original archive/native binding review remains root-owned. Preserve that execution and all earlier RED/GREEN history without claiming it covers this amendment. + +Fresh native Main producer `tools/formal_gate_check.py` at36eed0e9e2c7d4d1ad26bc2c2ae8499d31e78563 is literal byte-equal to the local23282B/SHA25621c355e02ac6e01337d10465a3105b34b93f832586ee60aa2430f662a90cd8b7 source. It writes each `