#!/usr/bin/env python3
"""Offline session-record checker source. Python 3.11+, cryptography 48.0.1.

No server, exporter, signer, key loader or ceremony-kit imports. The companion
verify_bundle.py supplies v1's unchanged closed payload checks. Public-file
pins refer to the immutable ZIP named in the approved r5 packet, not live state.
No key custody, event completeness, trusted time or latest-head claim is made.
"""
import base64
import datetime as dt
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import stat
import sys

# Exact source copy: Vale RETURN d8b8442b050dc5dcddce6e4f88a434dce5a5986d5c4d47a534acf03481750f30.
LABELS = (
    "BUNDLE PAYLOAD MATCHES RECORDED DIGEST",
    "ATTESTATION NAMES THIS BUNDLE",
    "SUPPLIED ATTESTATION CHAIN ROWS RECOMPUTE",
    "CHAIN LINKS TO PUBLISHED ROW 19",
    "WITNESS SIGNATURES VERIFY UNDER ROW-15 KEY",
    "ROW 15 ROOT SIGNATURE VERIFIES UNDER SUPPLIED ROOT KEY",
)
LIMITS = ("A passing attestation check links this bundle's payload digest to the row-15-enrolled Witness key under the supplied root key. "
          "It does not establish trusted signing time, who operated the key, per-row human approval, complete event capture, or the truth "
          "or correctness of the recorded work. Any constitutive fidelity readings are recorded measurements, not proof that the work followed the declared specification.")
UI_ATTESTED = ("This download includes an automated TELOS Witness attestation naming its payload digest, with chain evidence for offline signature checking against the published Record of Trust. "
               "It records no per-row human approval and does not establish trusted signing time, complete event capture, who operated the key, or the correctness of any constitutive fidelity readings.")
UI_UNATTESTED = ("This download has no Witness attestation; the offline checker reports NOT ATTESTED and ORIGIN UNAUTHENTICATED. "
                 "A matching digest checks internal consistency only, not authenticated origin, complete event capture or the correctness of any constitutive fidelity readings.")
# Exact text: Vale RETURN session-checker-lines__ALPHA, 2026-11-11. The coverage line reports what the supplied public
# projection declares; it never infers that events were lost, and an unrecognised value is a failure, never "complete".
COVERAGE_INCOMPLETE = "COVERAGE INCOMPLETE; SUPPLIED PUBLIC PROJECTION HAS GAPS: "
COVERAGE_COMPLETE = "COVERAGE DECLARED_COMPLETE; SUPPLIED PUBLIC PROJECTION ONLY; COMPLETE EVENT CAPTURE NOT ESTABLISHED"
ORIGIN_ATTESTED = "PAYLOAD ORIGIN FIELD: unauthenticated; ATTESTATION: PAYLOAD DIGEST BOUND TO ROW-15 WITNESS KEY UNDER SUPPLIED ROOT KEY"
SCOPE = "SCOPE PUBLIC_PROJECTION_ONLY; NATIVE_RECEIPTS_NOT_VALIDATED"
MAX_WIRE = 4_000_000
MAX_PAYLOAD = 2_999_000
MAX_RESPONSE = 3_000_000
MAX_PUBLIC_FILE = 512_000
COVERS = "this_hash (ASCII bytes of the 64-character hex string)"
FIELDS = frozenset(("schema_version", "event_type", "scope_id", "parent_hash", "row", "timestamp", "bundle_schema",
                    "bundle_sha256", "pa_hash", "purpose_row_hash", "human_approval", "authorization", "signature_envelope", "this_hash"))
PAYLOAD_SCHEMAS = ("tes.page.session-bundle/1", "tes.page.session-bundle/2", "tes.page.session-bundle/3", "tes.page.session-bundle/4")
SESSION_LINES = {
    'complete': 'Session projection coverage: complete through the export cutoff',
    'incomplete': 'Session projection coverage: incomplete; required session records are missing.',
    'unavailable': 'Session projection coverage: unavailable.'}
PUBLIC_TRUST = {
    "files": {
        "entries/commissioning/15.json": "a7a7e81b134cd5828693268e1b41d12f3df6db340f204b605c276077ad2fea70",
        "entries/commissioning/18.json": "1b69e65cb63dd1c0bf7afff11c99ac48b02b7071998f7b7d01d8888a5a424bbe",
        "entries/commissioning/19.json": "dbac091cb491a2df5f6e97283fbcff53d83309ed9b44ba6d718d1086b79fab8a",
        "ROOT-KEY.md": "fe656a4ee96098344fb48b3e1ae125d0af43ce1f8fb98bd450dbe094240450f5",
    },
    "root_fp": "d7fa85af712439c614fb25cdac293b783c0c0240ac79efb57f659c0f60bea8bb",
    "witness_fp": "12f4de3b7a839ce3c665deaff1922916fa39a52bbe239098662d440a283aaddf",
    "head": "1b5f5b48bb9eff758da07c74b69410b894e3d129a30e908ebe9cf9b24b1bd73a",
    "purpose": "a6f569c47cddae4a6306c4d6ee019d80a7bc566e67bf84a4c9df3b2a0ee5bc05",
    "enrollment": "9a16aec02aed9d035b4fedeadd5fa94b112e42051312883919423923f9473e9e",
    # The one human PA amendment row (TLink 020, appended 2026-11-14T00:27:19Z), pinned from outside the chain with
    # values measured from the signed ceremony artifacts. If any digest were None no transition would exist and every
    # supplied row would have to be a session row bound to row 18.
    "transition": {"label": "TLink 020",
                   "predecessor_pa": "7b9c754e778023ebfdd3343d5aacf12845eadbbdc0eb79429ffb129e4dbde3e0",
                   "successor_pa": "2601e2f10ad17d46d0b4f1d6e9991d057c3b005201f8fbecae7b96545280ec70",
                   "body_sha256": "61027dfb18b49e71484d1a2d4e7a36cd3ae95392dc0f6dfc3a9a0c2a65a28a08",
                   "row_hash": "df7d573a7e061763f23e7e6b60c695a53341247a639bcf0b8f2363ee5f22224d"},
}
# The amendment row's closed format (the reviewed ceremony format of the row 18 precedent). The signer keeps its own
# copy of these sets and of the predicate below; a parity test holds the two equal. What the predicate establishes
# from the row alone: the closed key sets and fixed values of the row and of the approval evidence it carries, and
# that row, evidence, receipt and action record name one action digest, one receipt id and one receipt digest. It
# does not verify the approval's passkey assertion, recompute the receipt digest, read the approved action, identify
# the approving credential or check the detached body signature: the row carries digests of those, not the material.
# Which row is the amendment is therefore decided by the external row-hash pin above, never by chain content.
AMENDMENT_FIELDS = frozenset(("action_sha256", "addendum_sha256", "agent_id", "authority_class", "authority_source",
                              "authorization_receipt_id", "authorization_receipt_sha256", "event_type", "maker_evidence",
                              "parent_hash", "public_fingerprint", "role", "signature_envelope", "signature_scope",
                              "signer", "source_candidate_sha256", "status", "this_hash", "timestamp", "tlink_type"))
AMENDMENT_FIXED = {"agent_id": "vale", "authority_class": "Class 4", "role": "Witness", "signer": "Origin Vale",
                   "status": "executed", "tlink_type": "PA_AMENDMENT"}
EVIDENCE_PROFILE = "telos.class4.chamber_authorization_evidence.v1"
EVIDENCE_FIELDS = frozenset(("profile", "action_sha256", "authorization_receipt", "consumer_verify", "suspended_action"))
RECEIPT_FIELDS = frozenset((
    "receipt_profile", "receipt_id", "authorization_receipt_id", "verified", "verifier_result", "authority_class",
    "command_id", "suspended_action_id", "payload_canonical_json_sha256", "payload_display_text_sha256",
    "telegram_context_id", "credential_id_hash", "candidate_credential_id", "public_key_cose_sha256", "assertion_id",
    "challenge_sha256", "authenticator_data_sha256", "client_data_json_sha256", "signature_sha256",
    "assertion_replay_key_sha256", "origin", "rp_id", "cross_origin", "sign_count", "verified_at_utc", "expires_at_utc",
    "decision_slug", "decision_block_sha256", "consumer_acceptance_status", "telegram_authority",
    "not_telegram_authority", "telos_mutated", "chain_appended", "ward_commissioned", "replay_protected",
    "user_presence_verified", "user_verification_verified", "authorization_receipt_emission_external_effect",
    "customer_facing_feature", "governance_runtime_mode", "escalation_type", "policy_verdict", "escalation_reason",
    "semantic_escalation_context", "operator_authority_gate", "receipt_sha256"))
SUSPENDED_FIELDS = frozenset((
    "suspended_action_id", "command_id", "agent_id", "tenant_id", "operator_scope", "tool", "target", "action",
    "payload_canonical_json_sha256", "policy_version", "policy_verdict", "risk_tier", "required_authority_class",
    "required_approval_count", "semantic_escalation_context", "agent_claimed_context", "status", "created_at_utc",
    "expires_at_utc", "nonce_sha256", "authorization_receipt_id", "execution_id", "audit_events", "approved_at_utc"))
RECEIPT_FIXED = {"receipt_profile": "telos.remote_class4.authorization.receipt.v1", "authority_class": 4,
                 "verified": True, "verifier_result": "ACCEPT_FOR_EXACT_PAYLOAD",
                 "consumer_acceptance_status": "ACCEPT_FOR_EXACT_PAYLOAD", "cross_origin": False,
                 "telegram_authority": False, "not_telegram_authority": True, "telegram_context_id": "",
                 "replay_protected": True, "user_presence_verified": True, "user_verification_verified": True,
                 "ward_commissioned": False, "authorization_receipt_emission_external_effect": False,
                 "assertion_id": ""}
RECEIPT_DIGESTS = ("payload_canonical_json_sha256", "challenge_sha256", "authenticator_data_sha256",
                   "client_data_json_sha256", "signature_sha256", "assertion_replay_key_sha256", "receipt_sha256")
CONFIRMED_FIELDS = frozenset(("accepted", "verifier_result", "payload_canonical_json_sha256", "authorization_receipt_id"))


class Invalid(ValueError):
    """Fixed public cause code; never carry exception text or record contents."""
    def __init__(self, reason="FORMAT"):
        super().__init__(reason)
        self.reason = reason


class DependencyUnavailable(RuntimeError):
    pass


def need(condition, reason="FORMAT"):
    if not condition:
        raise Invalid(reason)


def hex64(value):
    return type(value) is str and re.fullmatch(r"[0-9a-f]{64}", value) is not None


def _pairs(pairs):
    out = {}
    for key, value in pairs:
        need(key not in out)
        out[key] = value
    return out


def _constant(value):
    raise Invalid()


def parse(raw):
    return json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=_pairs, parse_constant=_constant)


def packed(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode("utf-8")


def digest_row(row):
    # Adapted exclusion rule: shared/contract.py:43-52, SHA256
    # 0e48ea08ce0220a9ce0df8e26a72481c83b715268cc82e625e714d63e4298eef.
    # R5's explicit ASCII rule overrides the historical conditional escaping.
    return hashlib.sha256(packed({k: v for k, v in row.items() if k not in {"signature_envelope", "this_hash"}})).hexdigest()


def unbase64(line):
    raw = base64.b64decode(line, validate=True)
    need(base64.b64encode(raw) == line)
    return raw


def envelope_signature(env, fingerprint):
    # Root-envelope branch adapted from check_public.py:89-106, SHA256
    # d413a6e091b8975542af971f761febf2eff2abc2b79b373902fbd44ecba81dbe,
    # and shared/contract.py:78-86. R5 uses this envelope with a Witness key id.
    need(type(env) is dict and set(env) == {"algorithm", "covers", "signer_key_id", "value"})
    need(env["algorithm"] == "ed25519" and env["covers"] == COVERS)
    need(env["signer_key_id"] == "sha256:" + fingerprint, "KEY_MISMATCH")
    need(type(env["value"]) is str)
    raw = unbase64(env["value"].encode("ascii"))
    need(len(raw) == 64)
    return raw


def transition_of(trust):
    """The pinned amendment identity, or None while it is absent or any digest pin is unset. Filled pins must be well formed."""
    pins = trust.get("transition")
    if pins is None:
        return None
    need(type(pins) is dict and set(pins) == {"label", "predecessor_pa", "successor_pa", "body_sha256", "row_hash"})
    digests = [pins[key] for key in ("predecessor_pa", "successor_pa", "body_sha256", "row_hash")]
    if any(value is None for value in digests):
        return None
    found = re.fullmatch(r"TLink (0[0-9]{2})", pins["label"]) if type(pins["label"]) is str else None
    need(found is not None and all(hex64(value) for value in digests) and pins["predecessor_pa"] != pins["successor_pa"])
    number = found.group(1)
    body_field, signature_field = "tlink_" + number + "_final_body_sha256", "tlink_" + number + "_signature_sha256"
    return {**pins, "event_type": "vale_tlink_" + number + "_pa_amendment", "body_field": body_field,
            "signature_field": signature_field, "fields": AMENDMENT_FIELDS | {body_field, signature_field}}


def is_amendment(entry, transition):
    return transition is not None and type(entry) is dict and entry.get("event_type") == transition["event_type"]


def amendment_packed(value):
    # The ceremony format's canonical bytes: UTF-8, not ASCII-escaped. Session rows use packed() instead.
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")


def digest_amendment(row):
    return hashlib.sha256(amendment_packed({k: v for k, v in row.items() if k not in {"signature_envelope", "this_hash"}})).hexdigest()


def amendment_moment(value):
    need(type(value) is str and re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", value) is not None)
    return dt.datetime.fromisoformat(value[:-1] + "+00:00")


def amendment_signature(env, witness_fp):
    need(type(env) is dict and set(env) == {"alg", "public_key_raw_hex", "signature_hex", "signed_message"})
    need(env["alg"] == "Ed25519" and env["signed_message"] == "this_hash_ascii" and hex64(env["public_key_raw_hex"]))
    need(hashlib.sha256(bytes.fromhex(env["public_key_raw_hex"])).hexdigest() == witness_fp, "KEY_MISMATCH")
    need(type(env["signature_hex"]) is str and re.fullmatch(r"[0-9a-f]{128}", env["signature_hex"]) is not None)
    return bytes.fromhex(env["signature_hex"])


def _same(left, right):
    return amendment_packed(left) == amendment_packed(right)   # equal in value and JSON type: true is not 1


def _text(value):
    return type(value) is str and bool(value.strip()) and len(value) <= 4096



def _receipt_export_matches(raw_value, exported):
    """Check the chamber's payload export without importing signer or chamber code."""
    if type(exported) is not dict or set(exported) != {"sha256", "keys", "redacted"}:
        return False
    if exported["redacted"] is not True:
        return False
    encoded = json.dumps(raw_value, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
    expected_keys = sorted(raw_value) if isinstance(raw_value, dict) else None
    return _same(exported["sha256"], hashlib.sha256(encoded).hexdigest()) and _same(exported["keys"], expected_keys)


def amendment_shape(row, transition, trust):
    """Structure/binding only, like row_shape: no hash, signature or row-pin check. See the note above the field sets."""
    need(type(row) is dict and set(row) == transition["fields"])
    need(_same(row["event_type"], transition["event_type"]) and all(_same(row[k], v) for k, v in AMENDMENT_FIXED.items()))
    need(all(hex64(row[k]) for k in ("action_sha256", "addendum_sha256", "authorization_receipt_sha256", "parent_hash",
                                     "public_fingerprint", "source_candidate_sha256", "this_hash",
                                     transition["body_field"], transition["signature_field"])))
    need(all(_text(row[k]) for k in ("authority_source", "signature_scope", "authorization_receipt_id")))
    need(row["addendum_sha256"] == transition["successor_pa"]
         and row["source_candidate_sha256"] == row[transition["body_field"]] == transition["body_sha256"], "HEAD_MISMATCH")
    need(row["public_fingerprint"] == trust["witness_fp"], "KEY_MISMATCH")
    stamp = amendment_moment(row["timestamp"])
    amendment_signature(row["signature_envelope"], trust["witness_fp"])
    evidence = row["maker_evidence"]
    need(type(evidence) is dict and set(evidence) == EVIDENCE_FIELDS)
    receipt, action, confirmed = evidence["authorization_receipt"], evidence["suspended_action"], evidence["consumer_verify"]
    need(type(receipt) is dict and set(receipt) == RECEIPT_FIELDS and type(action) is dict
         and set(action) == SUSPENDED_FIELDS and type(confirmed) is dict)
    need(_same(evidence["profile"], EVIDENCE_PROFILE) and all(_same(receipt[k], v) for k, v in RECEIPT_FIXED.items()))
    need(all(hex64(receipt[k]) for k in RECEIPT_DIGESTS) and hex64(evidence["action_sha256"])
         and hex64(action["payload_canonical_json_sha256"]) and hex64(action["nonce_sha256"])
         and type(receipt["sign_count"]) is int and 0 <= receipt["sign_count"] < 2 ** 32
         and all(_text(receipt[k]) for k in ("receipt_id", "authorization_receipt_id", "command_id", "suspended_action_id")))
    events = action["audit_events"]
    need(row["action_sha256"] == evidence["action_sha256"] == receipt["payload_canonical_json_sha256"]
         == action["payload_canonical_json_sha256"]
         and row["authorization_receipt_id"] == receipt["authorization_receipt_id"] == receipt["receipt_id"]
         and _same(action["authorization_receipt_id"], receipt["authorization_receipt_id"])
         and row["authorization_receipt_sha256"] == receipt["receipt_sha256"]
         and _same(action["status"], "approved") and action["execution_id"] is None
         and _same(action["suspended_action_id"], receipt["suspended_action_id"])
         and _same(action["command_id"], receipt["command_id"])
         and _same(action["approved_at_utc"], receipt["verified_at_utc"])
         and _same(action["expires_at_utc"], receipt["expires_at_utc"])
         and type(events) is list and len(events) == 1 and type(events[0]) is dict
         and set(events[0]) == {"at_utc", "status", "updates"} and _same(events[0]["status"], "approved")
         and _same(events[0]["updates"], {"authorization_receipt_id": receipt["authorization_receipt_id"],
                                          "approved_at_utc": receipt["verified_at_utc"]})
         and CONFIRMED_FIELDS <= set(confirmed) and confirmed["accepted"] is True
         and all(k in receipt and (_receipt_export_matches(v, receipt[k])
                                 if k in ("action", "agent_claimed_context", "semantic_escalation_context", "escalation_reason")
                                 else _same(v, receipt[k])) for k, v in confirmed.items() if k != "accepted"))
    need(moment(receipt["verified_at_utc"]) <= stamp)


PURPOSE_ROW_MAX = 16 * 1024
_PURPOSE_ROW_PARENT = "6d8d36c59aae9c14558abe7e3572b2980ea6ede7935d58796d02eceb2c834e3b"


def verify_purpose_approval(raw, mounted_sha):
    """Accept only the published trust pins' TLink 020 row for this mounted PA."""
    transition = transition_of(PUBLIC_TRUST)
    need(transition is not None and mounted_sha == transition["successor_pa"], "MOUNT_MISMATCH")
    need(len(raw) <= PURPOSE_ROW_MAX, "ROW_SIZE")
    row = parse(raw)
    amendment_shape(row, transition, PUBLIC_TRUST)
    need(row["parent_hash"] == _PURPOSE_ROW_PARENT, "PARENT_MISMATCH")
    need(digest_amendment(row) == row["this_hash"], "ROW_DIGEST_MISMATCH")
    need(row["this_hash"] == transition["row_hash"], "ROW_PIN_MISMATCH")
    envelope = row["signature_envelope"]  # amendment_shape already checked its format and Witness pin
    verify = crypto_backend()
    need(verify(envelope["public_key_raw_hex"], bytes.fromhex(envelope["signature_hex"]),
                row["this_hash"].encode("ascii")), "SIGNATURE_INVALID")


def row_shape(row, trust, purposes=None):
    """A session row. `purposes` are the purpose rows it may bind; by default the published row 18 only."""
    need(type(row) is dict and set(row) == FIELDS)
    need(row["schema_version"] == "telos.lineage.session_attestation/0.1"
         and row["event_type"] == "session_bundle_attestation" and row["scope_id"] == "scope:telos-commissioning-chain"
         and row["bundle_schema"] in PAYLOAD_SCHEMAS and row["human_approval"] is None
         and row["authorization"] == "automated_witness_attestation")
    need(type(row["row"]) is int and row["row"] >= 20)
    need(all(hex64(row[k]) for k in ("parent_hash", "bundle_sha256", "pa_hash", "purpose_row_hash", "this_hash")))
    need(row["purpose_row_hash"] in ((trust["purpose"],) if purposes is None else purposes))
    moment(row["timestamp"])
    envelope_signature(row["signature_envelope"], trust["witness_fp"])


def coverage_line(rc, v1_lines, schema=None):
    """The companion checker's own coverage line, repeated only when it agrees with its exit code. Unknown is never complete."""
    need(type(v1_lines) is list and all(type(line) is str for line in v1_lines))   # a short list is an IndexError, refused as FORMAT below
    line = v1_lines[1]
    if schema == 'tes.page.session-bundle/4':
        need(line == SESSION_LINES['complete'] if rc == 0 else line in (SESSION_LINES['incomplete'], SESSION_LINES['unavailable']))
        return line
    if rc == 0:
        need(line == COVERAGE_COMPLETE)
    else:
        need(line.startswith(COVERAGE_INCOMPLETE) and len(line) > len(COVERAGE_INCOMPLETE))   # rc is 3 here: the caller admits only 0 and 3
    return line


def moment(value):
    need(type(value) is str and re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z", value) is not None)
    return dt.datetime.fromisoformat(value[:-1] + "+00:00")


def validate_attestation_response(proof, digest, anchor, *, trust=None):
    """Page-only structure/binding predicate. NO hash or signature verification.

    Passing this predicate is not verification. The page must additionally run
    the ruled offline-verifier adapter before installing or labelling v2. The
    caller retains exact frozen v1 if either stage refuses or is unavailable.
    """
    trust = PUBLIC_TRUST if trust is None else trust
    transition = transition_of(trust)
    need(type(proof) is dict and set(proof) == {"row", "chain"})
    need(len(packed(proof)) <= MAX_RESPONSE and hex64(digest) and hex64(anchor))
    row, extension = proof["row"], proof["chain"]
    # The named row is always a session row. Under a pinned transition it may bind row 18 or the pinned amendment;
    # the walk below then holds every row to the purpose and PA of its own side of the amendment.
    row_shape(row, trust, None if transition is None else (trust["purpose"], transition["row_hash"]))
    need(row["bundle_sha256"] == digest and row["pa_hash"] == anchor)
    need(type(extension) is list and bool(extension) and extension[-1] == row)
    parent, purpose, amended = trust["head"], trust["purpose"], False
    pa = None if transition is None else transition["predecessor_pa"]
    for number, entry in enumerate(extension, 20):
        if is_amendment(entry, transition):
            # This path recomputes no hash, so a repeated row could claim the pinned hash: refuse a second amendment here.
            need(not amended)
            amendment_shape(entry, transition, trust)
            need(entry["this_hash"] == transition["row_hash"] and entry["parent_hash"] == parent)
            purpose, pa, amended = transition["row_hash"], transition["successor_pa"], True
        else:
            row_shape(entry, trust, (purpose,))
            need(pa is None or entry["pa_hash"] == pa)
            need(entry["row"] == number and entry["parent_hash"] == parent)
        parent = entry["this_hash"]
    return proof


def pinned_file(read, name, trust):
    try:
        raw = read(name)
    except (KeyError, OSError) as exc:
        raise OSError() from exc
    need(type(raw) is bytes and len(raw) <= MAX_PUBLIC_FILE)
    need(hashlib.sha256(raw).hexdigest() == trust["files"][name], "ROW_EDITED")
    return raw


def published_row(read, number, trust):
    # Published rows are declared/redacted: never native-recompute their visible
    # canonical object. Exact approved file pins bind their displayed contents.
    obj = parse(pinned_file(read, "entries/commissioning/" + str(number) + ".json", trust))
    need(type(obj) is dict and type(obj.get("canonical")) is dict)
    need(obj["canonical"]["this_hash"] == obj["row_hash"])
    return obj["canonical"]


def crypto_backend():
    try:
        import cryptography
        if cryptography.__version__ != "48.0.1":
            raise DependencyUnavailable()
        from cryptography.exceptions import InvalidSignature
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    except ImportError:
        raise DependencyUnavailable() from None

    def verify(public_hex, signature, message):
        # Ported public-only predicate: shared/contract.py:64-71, same SHA above;
        # check_public.py:57-59 verifies the same message with the same primitive.
        try:
            if type(signature) is not bytes or len(signature) != 64 or type(message) is not bytes:
                return False
            public = bytes.fromhex(public_hex)
            if len(public) != 32:
                return False
            Ed25519PublicKey.from_public_bytes(public).verify(signature, message)
            return True
        except (InvalidSignature, ValueError, TypeError):
            return False
    return verify


def v1_backend():
    # Only the fixed companion checker is loaded, never a file from the bundle
    # or public-record directory, server code, exporter or signer.
    path = Path(__file__).with_name("verify_bundle.py")
    spec = importlib.util.spec_from_file_location("tes_session_v1_checker", path)
    if spec is None or spec.loader is None:
        raise DependencyUnavailable()
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module.verify_bytes


def verify_bytes(wire, *, read_public=None, verify_signature=None, verify_v1=None, dependency=None, trust=None):
    """Check supplied bytes; injectable pure boundaries support synthetic oracles.

    CLI always uses pinned production trust and dependency version enforcement.
    No successful label is emitted for an unperformed dependent check.
    """
    trust = PUBLIC_TRUST if trust is None else trust
    lines, step = [], 0
    finish = lambda rc: (rc, lines + [LIMITS])
    try:
        if type(wire) is not bytes or len(wire) > MAX_WIRE:
            lines.append("UNAVAILABLE: INPUT SIZE")
            return finish(2)
        parts = wire.split(b"\n")
        need(parts[0] in (b"TES-SESSION-BUNDLE/1", b"TES-SESSION-BUNDLE/2"))
        attested = parts[0] == b"TES-SESSION-BUNDLE/2"
        need(parts[-1] == b"", "TRUNCATED")
        expected = 6 if attested else 4
        need(len(parts) >= expected, "TRUNCATED")
        need(len(parts) == expected)
        need(re.fullmatch(b"sha256:[0-9a-f]{64}", parts[1]) is not None)
        raw = unbase64(parts[2]); need(len(raw) <= MAX_PAYLOAD)
        need(hashlib.sha256(raw).hexdigest().encode("ascii") == parts[1][7:], "ROW_EDITED")
        v1 = b"TES-SESSION-BUNDLE/1\n" + parts[1] + b"\n" + parts[2] + b"\n"
        verify_v1 = v1_backend() if verify_v1 is None else verify_v1
        rc, v1_lines = verify_v1(v1)
        need(type(rc) is int and rc in (0, 3))
        payload = parse(raw)
        coverage = coverage_line(rc, v1_lines, payload.get('schema'))
        lines.extend(("PASS: " + LABELS[0], coverage))
        if payload.get('schema') == 'tes.page.session-bundle/4':
            lines.extend(line for line in v1_lines if line.startswith(('MEMBER ', 'GAPS ')))
        if not attested:
            lines.extend(("NOT ATTESTED", "ORIGIN UNAUTHENTICATED", SCOPE))
            return finish(3)

        step = 1
        row_raw, extension_raw = unbase64(parts[3]), unbase64(parts[4])
        need(len(row_raw) + len(extension_raw) <= MAX_RESPONSE)
        row, extension, payload = parse(row_raw), parse(extension_raw), parse(raw)
        need(packed(row) == row_raw and packed(extension) == extension_raw)
        transition = transition_of(trust)
        row_shape(row, trust, None if transition is None else (trust["purpose"], transition["row_hash"]))
        need(row["bundle_sha256"] == parts[1][7:].decode("ascii") and row["pa_hash"] == payload["anchor"]
             and row["bundle_schema"] == payload["schema"], "HEAD_MISMATCH")
        need(type(extension) is list)
        need(bool(extension), "TRUNCATED")
        # A missing terminal suffix differs from an inconsistent supplied head.
        if type(extension[-1]) is dict and type(extension[-1].get("row")) is int:
            need(extension[-1]["row"] >= row["row"], "TRUNCATED")
        need(extension[-1] == row, "HEAD_MISMATCH")
        lines.append("PASS: " + LABELS[1])

        step = 2
        seen, seen_numbers = set(), set()
        # At most one row may be the amendment, and only the externally pinned one. Session rows before it bind
        # row 18; session rows after it bind the amendment row's hash.
        amendment, purpose = None, trust["purpose"]
        for entry in extension:
            if is_amendment(entry, transition):
                # A second amendment whose bytes differ from the pinned row fails the pin below. An exact copy of
                # the pinned row passes the pin; step 3 then walks the earlier copy as a session row and refuses it
                # (FORMAT: an amendment carries no `row`). The structure-only predicate has its own one-amendment rule.
                amendment_shape(entry, transition, trust)
                need(digest_amendment(entry) == entry["this_hash"], "ROW_EDITED")
                need(entry["this_hash"] == transition["row_hash"], "HEAD_MISMATCH")
                amendment, purpose = entry, transition["row_hash"]
                continue
            row_shape(entry, trust, (purpose,))
            need(digest_row(entry) == entry["this_hash"], "ROW_EDITED")
            # Recomputed equal hashes with different bodies require a SHA-256
            # collision, already outside this record's hash/signature guarantee.
            # Equal bodies repeat the bundle digest, so no separate hash set.
            need(entry["bundle_sha256"] not in seen and entry["row"] not in seen_numbers, "DUPLICATE_ROW")
            seen.add(entry["bundle_sha256"])
            seen_numbers.add(entry["row"])
        lines.append("PASS: " + LABELS[2])

        step = 3
        if read_public is None:
            raise OSError()
        r18, r19 = published_row(read_public, 18, trust), published_row(read_public, 19, trust)
        need(r18["this_hash"] == trust["purpose"] and r19["this_hash"] == trust["head"], "HEAD_MISMATCH")
        need(r19["parent_hash"] == r18["this_hash"] and r19["purpose_row_hash"] == r18["this_hash"], "HEAD_MISMATCH")
        # The PA in force: row 19's published PA until the amendment, the pinned successor PA after it. The pinned
        # predecessor must be row 19's PA, and under a pinned transition every session row names its side's PA.
        need(transition is None or transition["predecessor_pa"] == r19["purpose_sha256"], "HEAD_MISMATCH")
        need(row["pa_hash"] == (r19["purpose_sha256"] if amendment is None else transition["successor_pa"]), "HEAD_MISMATCH")
        parent, last, pa = trust["head"], None, r19["purpose_sha256"]
        for number, entry in enumerate(extension, 20):
            # Row numbers are physical positions. The amendment carries no number of its own; it takes one position.
            if entry is amendment:
                stamp, pa = amendment_moment(entry["timestamp"]), transition["successor_pa"]
            else:
                need(entry["row"] == number, "ROW_MISSING_OR_REORDERED")
                need(transition is None or entry["pa_hash"] == pa, "HEAD_MISMATCH")
                stamp = moment(entry["timestamp"])
            need(entry["parent_hash"] == parent, "HEAD_MISMATCH" if number == 20 else "ROW_MISSING_OR_REORDERED")
            need(last is None or stamp >= last, "TIMESTAMP_ROLLBACK")
            parent, last = entry["this_hash"], stamp
        lines.append("PASS: " + LABELS[3])

        step = 4
        r15 = published_row(read_public, 15, trust)
        witness = r19["signature_envelope"]["public_key_raw_hex"]
        need(hex64(witness) and hashlib.sha256(bytes.fromhex(witness)).hexdigest() == r15["child_public_key_sha256"] == trust["witness_fp"], "KEY_MISMATCH")
        # Enrollment predicate adapted from check_public.py:152-153; scope is
        # additionally required by this r5 contract. Exact public pins bind it.
        need(r15["this_hash"] == trust["enrollment"] and r15["status"] == "active" and r15["purpose"] == "witness_signing"
             and r15["key_role"] == "witness" and r15["scope_id"] == "scope:telos-commissioning-chain")
        if verify_signature is None:
            verify_signature = (dependency or crypto_backend)()
        for entry in extension:
            if entry is amendment:
                # The Witness key attests the amendment row. This is not the Maker approval, which the row records
                # as evidence and which this checker does not verify.
                signature = amendment_signature(entry["signature_envelope"], trust["witness_fp"])
                need(entry["signature_envelope"]["public_key_raw_hex"] == witness, "KEY_MISMATCH")
            else:
                signature = envelope_signature(entry["signature_envelope"], trust["witness_fp"])
            need(verify_signature(witness, signature, entry["this_hash"].encode("ascii")) is True, "SIGNATURE_INVALID")
        lines.append("PASS: " + LABELS[4])

        step = 5
        root_text = pinned_file(read_public, "ROOT-KEY.md", trust).decode("utf-8", "strict")
        matches = re.findall(r"Public key \(raw, hex\): ([0-9a-f]{64})", root_text)
        need(len(matches) == 1)
        root = matches[0]; need(hashlib.sha256(bytes.fromhex(root)).hexdigest() == trust["root_fp"], "KEY_MISMATCH")
        signature = envelope_signature(r15["signature_envelope"], trust["root_fp"])
        need(verify_signature(root, signature, r15["this_hash"].encode("ascii")) is True, "SIGNATURE_INVALID")
        lines.append("PASS: " + LABELS[5])
        lines.extend((ORIGIN_ATTESTED, SCOPE))   # only after all six checks pass
        return finish(3 if payload['schema'] == 'tes.page.session-bundle/4' and rc == 3 else 0)
    except DependencyUnavailable:
        lines.append("UNAVAILABLE: DEPENDENCY")
        return finish(2)
    except OSError:
        lines.append("UNAVAILABLE: IO")
        return finish(2)
    except Invalid as exc:
        lines.extend(("REASON: " + exc.reason, "FAIL: " + LABELS[step]))
        return finish(1)
    except (ValueError, TypeError, KeyError, IndexError, UnicodeError, OverflowError, RecursionError):
        lines.append("REASON: FORMAT")
        lines.append("FAIL: " + LABELS[step])
        return finish(1)


def read_file(path, maximum):
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
    fd = os.open(path, flags)
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            raise OSError()
        with os.fdopen(fd, "rb", closefd=False) as stream:
            return stream.read(maximum + 1)
    finally:
        os.close(fd)


def main(argv=None, out=None):
    argv = sys.argv[1:] if argv is None else argv
    out = sys.stdout if out is None else out
    if len(argv) != 2 or sys.version_info < (3, 11):
        rc, lines = 2, ["UNAVAILABLE: USAGE OR PYTHON VERSION", LIMITS]
    else:
        try:
            wire = read_file(argv[0], MAX_WIRE)
            directory = Path(argv[1])
            rc, lines = verify_bytes(wire, read_public=lambda name: read_file(directory / name, MAX_PUBLIC_FILE))
        except OSError:
            rc, lines = 2, ["UNAVAILABLE: IO", LIMITS]
    out.write("\n".join(lines) + "\n")
    return rc


if __name__ == "__main__":
    raise SystemExit(main())
