#!/usr/bin/env python3
"""ur_verify — offline verifier for UltimateReady evidence packages and log checkpoints.

Checks without trusting UltimateReady's servers or web app:
  * checksum: SHA-256 of the exact contentPreimage, and that the package's context and
    assertions equal what that preimage says;
  * ledger: every entry's proof against the per-tenant Merkle root;
  * signed log: entries already in UltimateReady's transparency log are included (RFC 6962)
    under a checkpoint signed by a PINNED key (c2sp.org signed-note, Ed25519);
  * seal: when present, the exact contentPreimage is an entry in that signed log.

A pass does not show that the assertions are true. No independent witnesses cosign the log
yet, so inclusion and time rest on UltimateReady's key. With --state FILE the tool remembers
the largest checkpoint it verified per log and demands a consistency proof for every new one,
so a log that shows you two different histories fails as a split view.

Usage:
  python3 ur_verify.py package PACKAGE.json [--state FILE] [--api URL]
  python3 ur_verify.py checkpoint [--file NOTE | --api URL] [--state FILE]
Requires Python 3.9+ and the `cryptography` package (pip install cryptography).
Exit status: 0 verified, 1 failed, 2 could not run.
"""

from __future__ import annotations

import argparse
import base64
import binascii
import hashlib
import json
import math
import os
import re
import sys
import unicodedata
import urllib.request
from dataclasses import dataclass

VERSION = "1.0"
# Pinned here, never taken from an API response. Same keys as https://ultimateready.ai/verify;
# rotation adds a new origin and key, so packages signed by earlier keys keep verifying.
PRODUCTION_KEYS = ("log.ultimateready.ai/2026+59d353b8+Ac09p9ZrAK2uViig50xnjSBC09DBxypBZQ+JQa3bD8wm",)
# Public development key: its private half is derivable by anyone. Trusted only with --allow-dev-key.
DEVELOPMENT_KEY = "localhost/ultimateready-dev-log+f3071ab7+AY3KPmZWxkUxnAuZEmuPFKBi+cOYUWjneLwbKuuG10KW"
DEFAULT_API = "https://api.ultimateready.ai"  # serves the production log only
PRODUCTION_ORIGINS = frozenset(key.split("+", 1)[0] for key in PRODUCTION_KEYS)
SCHEMA = "ur-evidence-package/v2"
TLOG_PROOF_HEADER = "c2sp.org/tlog-proof@v1"
SIGNATURE_PREFIX = "\u2014 "
HASH = re.compile(r"sha256:[0-9a-f]{64}")
BARE_HASH = re.compile(r"[0-9a-f]{64}")


class Failed(Exception):
    """A verification check did not pass."""


# ── Encoding ────────────────────────────────────────────────────────────────


def b64encode(data: bytes) -> str:
    return base64.b64encode(data).decode("ascii")


def b64decode(value: str) -> bytes:
    """RFC 4648 with padding; non-canonical encodings are rejected."""
    if not isinstance(value, str):
        raise Failed("expected base64 text")
    try:
        data = base64.b64decode(value, validate=True)
    except (binascii.Error, ValueError):
        raise Failed("invalid base64") from None
    if b64encode(data) != value:
        raise Failed("non-canonical base64")
    return data


def decimal(value: str) -> int:
    if not re.fullmatch(r"0|[1-9][0-9]*", value):
        raise Failed("expected a canonical decimal")
    return int(value)


def sha256(*parts: bytes) -> bytes:
    return hashlib.sha256(b"".join(parts)).digest()
def _varbytes(stream) -> tuple[int, bytes]:
    """OTS wire: a LEB128 varuint length followed by exactly that many bytes."""
    length = 0
    shift = 0
    while True:
        byte = stream.read(1)
        if not byte:
            raise Failed("anchor receipt ended inside a length prefix")
        value = byte[0]
        length |= (value & 0x7F) << shift
        shift += 7
        if shift > 63:
            raise Failed("anchor receipt length prefix too large")
        if not value & 0x80:
            break
    data = stream.read(length)
    if len(data) != length:
        raise Failed("anchor receipt ended inside an operand")
    return length, data


_MAX_ANCHOR_DATA = 4096  # one merkle sibling per op; real paths are ~30 ops


def _varuint(data: bytes) -> int:
    """Strict LEB128: stops at the terminator; trailing bytes or empty fail."""
    if not data:
        raise Failed("anchor receipt carries an empty height field")
    value = 0
    for shift, byte in enumerate(data):
        value |= (byte & 0x7F) << (7 * shift)
        if not byte & 0x80:
            if shift + 1 != len(data):
                raise Failed("anchor receipt height field has trailing bytes")
            return value
    raise Failed("anchor receipt height field is not terminated")


_BTC_TAG = bytes.fromhex("0588960d73d71901")
_PENDING_TAG = bytes.fromhex("83dfe30d2ef90c8e")


def _anchor_attestation(stream) -> int | None:
    """Bitcoin attestations return their block height; pending ones return None."""
    tag = stream.read(8)  # attestation tags are exactly 8 bytes
    if tag == _BTC_TAG:
        _, payload = _varbytes(stream)
        return _varuint(payload)
    if tag == _PENDING_TAG:
        _varbytes(stream)  # calendar URI — informational only
        return None
    raise Failed(f"anchor receipt carries an unknown attestation tag {tag.hex()}")


def _walk_anchor(stream, msg: bytes, depth: int = 0) -> list[tuple[int, bytes]]:
    """Walk one OTS timestamp node, recomputing every message from the note
    digest. Returns (block_height, attested_message) pairs; the caller checks
    each attested message against the real Bitcoin block header's merkle root,
    so a tampered sibling cannot forge a path to a different block."""
    if depth > 64:
        raise Failed("anchor receipt nests too deeply")
    results: list[tuple[int, bytes]] = []
    tag = stream.read(1)
    while tag == b"\xff":
        tag = stream.read(1)
        if not tag:
            raise Failed("anchor receipt ended mid-entry")
        results += _anchor_entry(stream, tag, msg, depth)
        tag = stream.read(1)
    results += _anchor_entry(stream, tag, msg, depth)
    return results


def _anchor_entry(stream, tag: bytes, msg: bytes, depth: int) -> list[tuple[int, bytes]]:
    if tag == b"\x00":  # attestation marker: tag + payload follows
        height = _anchor_attestation(stream)
        return [(height, msg)] if height is not None else []
    if tag == b"\x08":  # SHA256
        return _walk_anchor(stream, sha256(msg), depth + 1)
    if tag == b"\xf0":  # Append(payload): child message is msg + payload
        length, payload = _varbytes(stream)
        if length > _MAX_ANCHOR_DATA:
            raise Failed("anchor receipt carries an oversized Append operand")
        return _walk_anchor(stream, msg + payload, depth + 1)
    if tag == b"\xf1":  # Prepend(payload): child message is payload + msg
        length, payload = _varbytes(stream)
        if length > _MAX_ANCHOR_DATA:
            raise Failed("anchor receipt carries an oversized Prepend operand")
        return _walk_anchor(stream, payload + msg, depth + 1)
    raise Failed(f"anchor receipt carries an unknown op tag {tag.hex()}")


_OTS_MAGIC = b"\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94"


def _parse_anchor(receipt: bytes, note: str) -> list[tuple[int, bytes]]:
    """Parse an OpenTimestamps receipt for the SHA-256 of `note`.
    Raises Failed unless the file commits to exactly that digest and chains it
    to at least one Bitcoin block attestation. The receipt's own recorded
    operations are the merkle proof; nothing here trusts the calendar.
    """
    if not receipt.startswith(_OTS_MAGIC):
        raise Failed("anchor receipt is not an OpenTimestamps file")
    body = receipt[len(_OTS_MAGIC):]
    import io as _io
    stream = _io.BytesIO(body)
    if stream.read(1) != b"\x01":  # major version
        raise Failed("anchor receipt uses an unknown OpenTimestamps version")
    op_tag = stream.read(1)
    if op_tag != b"\x08":  # the file-digest operation is SHA256
        raise Failed("anchor receipt uses an unexpected file hash operation")
    digest = stream.read(32)
    expected = hashlib.sha256(note.encode("utf-8")).digest()
    if digest != expected:
        raise Failed("anchor receipt commits to a different note than this checkpoint")
    pairs = _walk_anchor(stream, digest)
    if stream.read(1):
        raise Failed("anchor receipt carries trailing bytes after the timestamp tree")
    if not any(height is not None for height, _ in pairs):
        raise Failed("anchor receipt has no Bitcoin attestation yet (still pending)")
    return pairs


def _block_header_time(header: bytes) -> tuple[bytes, int]:
    """(merkle_root, unix_time) from an 80-byte Bitcoin block header."""
    if len(header) != 80:
        raise Failed("block header must be exactly 80 bytes")
    merkle = header[36:68]
    time_value = int.from_bytes(header[68:72], "little")
    return merkle, time_value


# ── RFC 6962 tree, RFC 9162 verification ────────────────────────────────────


def leaf_hash(entry: bytes) -> bytes:
    return sha256(b"\x00", entry)


def node_hash(left: bytes, right: bytes) -> bytes:
    return sha256(b"\x01", left, right)


def verify_inclusion(leaf: bytes, index: int, size: int, proof: list[bytes], root: bytes) -> bool:
    """RFC 9162 section 2.1.3.2."""
    if not 0 <= index < size or any(len(h) != 32 for h in [leaf, root, *proof]):
        return False
    fn, sn, r = index, size - 1, leaf
    for p in proof:
        if sn == 0:
            return False
        if fn % 2 == 1 or fn == sn:
            r = node_hash(p, r)
            while fn != 0 and fn % 2 == 0:
                fn //= 2
                sn //= 2
        else:
            r = node_hash(r, p)
        fn //= 2
        sn //= 2
    return sn == 0 and r == root


def verify_consistency(old_size: int, size: int, old_root: bytes, root: bytes, proof: list[bytes]) -> bool:
    """RFC 9162 section 2.1.4.2."""
    if not 0 <= old_size <= size or any(len(h) != 32 for h in [old_root, root, *proof]):
        return False
    if old_size == size:
        return not proof and old_root == root
    if old_size == 0:
        return not proof
    if not proof:
        return False
    path = [old_root, *proof] if old_size & (old_size - 1) == 0 else list(proof)
    fn, sn = old_size - 1, size - 1
    while fn % 2 == 1:
        fn //= 2
        sn //= 2
    fr = sr = path[0]
    for c in path[1:]:
        if sn == 0:
            return False
        if fn % 2 == 1 or fn == sn:
            fr, sr = node_hash(c, fr), node_hash(c, sr)
            while fn != 0 and fn % 2 == 0:
                fn //= 2
                sn //= 2
        else:
            sr = node_hash(sr, c)
        fn //= 2
        sn //= 2
    return sn == 0 and fr == old_root and sr == root


# ── Checkpoints and signed notes (c2sp.org) ─────────────────────────────────


@dataclass(frozen=True)
class Checkpoint:
    origin: str
    size: int
    root: bytes


def parse_checkpoint(text: str) -> Checkpoint:
    if not text.endswith("\n"):
        raise Failed("checkpoint text must end with a newline")
    lines = text[:-1].split("\n")
    if len(lines) < 3 or "" in lines:
        raise Failed("checkpoint needs origin, size and root lines")
    root = b64decode(lines[2])
    if len(root) != 32:
        raise Failed("checkpoint root must be a SHA-256 hash")
    return Checkpoint(lines[0], decimal(lines[1]), root)


def _key_name(name: str) -> bool:
    return bool(name) and "+" not in name and not any(ch.isspace() for ch in name)


def parse_vkey(value: str):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    # The base64 key may itself contain '+', so only the first two split.
    name, key_id, encoded = (value.split("+", 2) + ["", ""])[:3]
    key = b64decode(encoded)
    expected = sha256(name.encode("utf-8"), b"\n\x01", key[1:])[:4].hex() if len(key) == 33 else ""
    if not _key_name(name) or key[:1] != b"\x01" or len(key) != 33 or key_id != expected:
        raise Failed("malformed verifier key")
    return name, bytes.fromhex(key_id), Ed25519PublicKey.from_public_bytes(key[1:])


def verify_note(note: str, vkeys) -> tuple[str, list[str]]:
    """Return (text, signer names). Unknown keys are ignored; a failing known key rejects."""
    from cryptography.exceptions import InvalidSignature

    if not isinstance(note, str) or not note.endswith("\n") or any(ord(ch) < 0x20 and ch != "\n" for ch in note):
        raise Failed("malformed signed note")
    split = note.rfind("\n\n")
    if split < 0:
        raise Failed("signed note has no signatures")
    text = note[: split + 1]
    known = {(name, key_id): key for name, key_id, key in map(parse_vkey, vkeys)}
    signers = []
    for line in note[split + 2 : -1].split("\n"):
        if not line.startswith(SIGNATURE_PREFIX):
            raise Failed("malformed signature line")
        name, _, encoded = line[len(SIGNATURE_PREFIX):].partition(" ")
        if not _key_name(name):
            raise Failed("malformed signature line")
        raw = b64decode(encoded)
        if len(raw) < 5:
            raise Failed("signature too short")
        key = known.get((name, raw[:4]))
        if key is None:
            continue  # unknown keys (rotation, witness cosignatures) are ignored
        try:
            key.verify(raw[4:], text.encode("utf-8"))
        except InvalidSignature:
            raise Failed(f"signature from pinned key {name} is invalid") from None
        signers.append(name)
    if not signers:
        raise Failed("no pinned log key signed this checkpoint")
    return text, signers


def parse_tlog_proof(value: str) -> tuple[int, list[bytes], str, bytes | None]:
    if not isinstance(value, str):
        raise Failed("not a c2sp.org/tlog-proof@v1 proof")
    head, separator, note = value.partition("\n\n")
    lines = head.split("\n")
    if not separator or not note or lines[0] != TLOG_PROOF_HEADER:
        raise Failed("not a c2sp.org/tlog-proof@v1 proof")
    extra = None
    if len(lines) > 1 and lines[1].startswith("extra "):
        extra = b64decode(lines.pop(1)[len("extra "):])
    if len(lines) < 2 or not lines[1].startswith("index "):
        raise Failed("tlog-proof is missing its index line")
    proof = [b64decode(line) for line in lines[2:]]
    if any(len(h) != 32 for h in proof):
        raise Failed("tlog-proof hashes must be SHA-256")
    return decimal(lines[1][len("index "):]), proof, note, extra


def logged_checkpoint(tlog_proof: str, entry_for, vkeys) -> tuple[Checkpoint, int]:
    """Check that the entry built from the proof's extra line is in a pinned-key checkpoint."""
    index, proof, note, extra = parse_tlog_proof(tlog_proof)
    text, signers = verify_note(note, vkeys)
    checkpoint = parse_checkpoint(text)
    if checkpoint.origin not in signers:
        raise Failed("checkpoint origin is not signed by its own log key")
    if not verify_inclusion(leaf_hash(entry_for(extra)), index, checkpoint.size, proof, checkpoint.root):
        raise Failed("inclusion proof does not match the signed checkpoint")
    return checkpoint, index


def activity_entry(nonce: bytes | None, content_digest: bytes) -> bytes:
    if nonce is None or len(nonce) != 32:
        raise Failed("proof is missing its 32-byte entry nonce")
    commitment = sha256(b"ur-activity/v2\x00", nonce, content_digest)
    return b"urlog/v1\nactivity\n" + b64encode(commitment).encode("ascii") + b"\n"


def artifact_entry(extra: bytes | None, content: bytes) -> bytes:
    if extra is not None:
        raise Failed("artifact seals carry no extra line")
    return b"urlog/v1\nartifact\n" + b64encode(sha256(content)).encode("ascii") + b"\n"


# ── Split-view memory ───────────────────────────────────────────────────────


MAX_RESPONSE = 1 << 20  # checkpoints and consistency proofs are a few KiB


def _fetch(url: str) -> bytes:
    request = urllib.request.Request(url, headers={"User-Agent": f"ur-verify/{VERSION}"})
    with urllib.request.urlopen(request, timeout=15) as response:
        body = response.read(MAX_RESPONSE + 1)
    if len(body) > MAX_RESPONSE:
        raise ValueError("response larger than 1 MiB")
    return body


class Memory:
    """Largest verified checkpoint per origin: for this run and, with a state file, across runs."""

    def __init__(self, path: str | None, api: str | None):
        self.path, self.api, self.changed = path, api.rstrip("/") if api else None, False
        self.state: dict = {}
        if path and os.path.exists(path):  # an unreadable file raises OSError: the caller exits 2
            try:
                with open(path, encoding="utf-8") as handle:
                    loaded = json.load(handle)
            except (ValueError, RecursionError):
                loaded = {}  # corrupt memory: start over from the checkpoints verified now
            self.state = loaded if isinstance(loaded, dict) else {}

    def _remember(self, checkpoint: Checkpoint) -> None:
        self.state[checkpoint.origin] = {"size": checkpoint.size, "root": b64encode(checkpoint.root)}
        self.changed = True

    def _consistency_proof(self, api: str, first: int, second: int) -> list[bytes]:
        body = json.loads(_fetch(f"{api}/api/transparency-log/consistency?first={first}&second={second}"))
        if not isinstance(body, dict) or body.get("first") != first or body.get("second") != second \
                or not isinstance(body.get("proof"), list):
            raise Failed("malformed consistency proof")
        return [b64decode(h) for h in body["proof"]]

    def check(self, checkpoint: Checkpoint) -> str:
        """first_seen | consistent | unchecked | split_view"""
        seen = self.state.get(checkpoint.origin)
        try:
            size, root = seen["size"], b64decode(seen["root"])
            if type(size) is not int or size < 0 or len(root) != 32:
                raise ValueError("unreadable remembered checkpoint")
            seen_cp = Checkpoint(checkpoint.origin, size, root)
        except (Failed, KeyError, TypeError, ValueError):
            self._remember(checkpoint)  # nothing (or nothing readable) remembered yet
            return "first_seen"
        if seen_cp.size == checkpoint.size:
            return "consistent" if seen_cp.root == checkpoint.root else "split_view"
        older, newer = sorted((seen_cp, checkpoint), key=lambda c: c.size)
        # Proofs come from the server of this log; another log's proof would fake a split view.
        api = self.api or (DEFAULT_API if checkpoint.origin in PRODUCTION_ORIGINS else None)
        if api is None:
            return "unchecked"  # no known server for this log's proofs: pass --api
        try:
            proof = self._consistency_proof(api, older.size, newer.size)
        except Exception:
            return "unchecked"
        if not verify_consistency(older.size, newer.size, older.root, newer.root, proof):
            return "split_view"
        if newer is checkpoint:
            self._remember(checkpoint)
        return "consistent"

    def save(self) -> None:
        if self.path and self.changed:
            tmp = f"{self.path}.tmp"
            try:
                with open(tmp, "w", encoding="utf-8") as handle:
                    json.dump(self.state, handle, indent=2, sort_keys=True)
                os.replace(tmp, self.path)
            except OSError as exc:
                print(f"ur_verify: WARNING: could not save {self.path} ({exc.strerror}); "
                      "checkpoints from this run are not remembered", file=sys.stderr)


def _consistency_lines(outcomes: set, persisted: bool) -> list[tuple[str, str]]:
    if not outcomes:
        return []
    if "unchecked" in outcomes:
        lines = [("NOTE", "consistency: a consistency proof was unavailable, so not every checkpoint was compared")]
    elif persisted:
        lines = [("PASS", "consistency: " + ("first checkpoint recorded for this log" if outcomes == {"first_seen"}
                                             else "consistent with the checkpoints this verifier recorded"))]
    else:
        lines = [("PASS", "consistency: this package's checkpoints are consistent with each other")] \
            if "consistent" in outcomes else []
    if not persisted:
        lines.append(("NOTE", "consistency: not compared across runs; use --state FILE to detect split views"))
    return lines


# ── Evidence packages ───────────────────────────────────────────────────────


def _canon(value):
    """JSON value identity: key order ignored, numbers compared as binary64."""
    if value is None:
        return ("null",)
    if isinstance(value, bool):
        return ("bool", value)
    if isinstance(value, (int, float)):
        try:
            number = float(value)  # binary64, as browsers parse JSON numbers
        except OverflowError:
            raise Failed("non-finite number") from None
        if not math.isfinite(number):
            raise Failed("non-finite number")
        return ("number", number)
    if isinstance(value, str):
        return ("string", value)
    if isinstance(value, list):
        return ("array", tuple(_canon(v) for v in value))
    if isinstance(value, dict):
        return ("object", tuple(sorted((k, _canon(v)) for k, v in value.items())))
    raise Failed("not a JSON value")


def _reject_constant(name: str):
    raise Failed(f"non-finite number {name}")


def _ledger_depth(leaf_count: int) -> int:
    depth, width = 0, leaf_count
    while width > 1:
        depth, width = depth + 1, (width + 1) // 2
    return depth


def _tenant_proof_ok(proof: dict, merkle_root: str, leaf_count: int) -> bool:
    path = proof.get("siblingPath")
    if not isinstance(path, list) or len(path) != _ledger_depth(leaf_count) \
            or not all(isinstance(h, str) and BARE_HASH.fullmatch(h) for h in path):
        return False
    current = sha256(proof["leafPreimage"].encode("utf-8"))
    if proof.get("contentHash") != "sha256:" + current.hex():
        return False
    index, width = proof["index"], leaf_count
    for sibling_hex in path:
        if index % 2 == 0 and index + 1 == width and sibling_hex != current.hex():
            return False  # an odd tail must pair with itself
        sibling = bytes.fromhex(sibling_hex)
        current = node_hash(current, sibling) if index % 2 == 0 else node_hash(sibling, current)
        index, width = index // 2, (width + 1) // 2
    return "sha256:" + current.hex() == merkle_root


def _is_index(value, upper: int) -> bool:
    return type(value) is int and 0 <= value < upper


def _number(value) -> bool:
    try:
        return type(value) in (int, float) and math.isfinite(value)
    except OverflowError:
        return False


def _log_status_ok(log) -> bool:
    """As verifyTlog.ts isTransparencyLogProof: tlogProof is non-empty text exactly when included."""
    if not isinstance(log, dict):
        return False
    if log.get("status") == "included":
        return isinstance(log.get("tlogProof"), str) and bool(log["tlogProof"])
    return log.get("status") in ("pending", "unconfigured") and "tlogProof" in log and log["tlogProof"] is None


def _package_shape_ok(pkg: dict) -> bool:
    """The complete package shape, as the browser's normalizeTrustPackageResponse requires it."""
    compliance, banks, proofs, verification, seal = (
        pkg.get(k) for k in ("compliance", "questionnaires", "proofs", "verification", "seal"))
    counts = ("controlCount", "assessedCount", "satisfiedCount", "atRiskCount", "failingCount", "notAssessedCount")
    return (isinstance(compliance, dict) and isinstance(compliance.get("frameworks"), list)
            and all(isinstance(fw, dict) and isinstance(fw.get("id"), str) and isinstance(fw.get("name"), str)
                    and _number(fw.get("score")) and all(_is_index(fw.get(k), 2**53) for k in counts)
                    for fw in compliance["frameworks"])
            and isinstance(banks, list)
            and all(isinstance(b, dict) and isinstance(b.get("bankId"), str) and isinstance(b.get("bankName"), str)
                    and isinstance(b.get("summary"), dict) and isinstance(b.get("answers"), list) for b in banks)
            and isinstance(proofs, list)
            and all(isinstance(p, dict) and isinstance(p.get("contentHash"), str) and isinstance(p.get("siblingPath"), list)
                    and isinstance(p.get("verified"), bool) and _log_status_ok(p.get("transparencyLog")) for p in proofs)
            and isinstance(verification, dict) and isinstance(verification.get("spec"), dict)
            and isinstance(verification.get("instructions"), str)
            and ("seal" not in pkg or (isinstance(seal, dict) and seal.get("status") == "included"
                                       and _is_index(seal.get("logIndex"), 2**53)
                                       and isinstance(seal.get("tlogProof"), str) and bool(seal["tlogProof"]))))


def _action_receipt(preimage: str):
    """Extract only the canonical receipt bound inside a validated ledger preimage."""
    fields = preimage.split("\x1f")
    if len(fields) != 9 or fields[0] != "urlv1":
        return None
    summary = fields[7]
    if not summary.startswith("Action receipt: "):
        return None
    try:
        heading, payload = summary.split("\n\nur-action-receipt/v1 ", 1)
        receipt = json.loads(payload)
        keys = {"tenant_id", "proposal_id", "execution_id", "actor_id", "authorization",
                "consent_hash", "action_type", "affected_resource", "phase", "error"}
        if not isinstance(receipt, dict) or set(receipt) != keys:
            return None
        if any(not isinstance(receipt[k], str) or not receipt[k] for k in keys - {"error"}):
            return None
        if receipt["error"] is not None and not isinstance(receipt["error"], str):
            return None
        events = {"authorized": "proposal.approved", "provider_acknowledged": "proposal.executed",
                  "failed": "proposal.failed", "outcome_unknown": "proposal.outcome_unknown"}
        if (receipt["phase"] not in events or heading != "Action receipt: " + receipt["phase"]
                or fields[3] != events[receipt["phase"]] or fields[4] != "proposal"
                or receipt["tenant_id"] != fields[2] or receipt["proposal_id"] != fields[5]
                or receipt["authorization"] not in ("session", "command")
                or not HASH.fullmatch(receipt["consent_hash"])):
            return None
        for key in ("tenant_id", "proposal_id", "execution_id", "actor_id"):
            if not re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", receipt[key]):
                return None
        if payload != json.dumps(receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=True):
            return None
        return receipt
    except (ValueError, RecursionError):
        return None


_RECEIPT_HEADING = re.compile(r"^Action receipt: ([a-z_]+)\n\nur-action-receipt/v1 ")
_PHASE_KEYS = ("authorized", "provider_acknowledged", "failed", "outcome_unknown")


def _derive_outcomes(proofs: list, tenant: str, section) -> str:
    """Re-derive the package's remediationOutcomes from the proofs' own preimages.

    'absent' for pre-section packages (no section, no receipts); 'match' when
    the section equals the derivation; 'mismatch' otherwise. The section is
    never an input to verification — an asserted rollup the receipts do not
    support is exactly the over-claim this section exists to prevent.
    """
    per_proposal: dict[str, dict] = {}
    for proof in proofs:
        fields = proof["leafPreimage"].split("\x1f")
        if len(fields) != 9 or fields[0] != "urlv1" or fields[4] != "proposal":
            continue
        heading = _RECEIPT_HEADING.match(fields[7])
        if not heading:
            continue
        try:
            receipt = json.loads(fields[7][heading.end():], parse_constant=_reject_constant)
        except (Failed, ValueError):
            return "mismatch"
        if not isinstance(receipt, dict):
            return "mismatch"
        phase = heading.group(1)
        proposal_id = receipt.get("proposal_id")
        if not isinstance(proposal_id, str) or receipt.get("phase") != phase \
                or receipt.get("tenant_id") != tenant:
            return "mismatch"
        entry = per_proposal.get(proposal_id)
        if entry is None:
            entry = per_proposal.setdefault(proposal_id, {
                "proposalId": proposal_id,
                "actionType": receipt["action_type"] if isinstance(receipt.get("action_type"), str) else "",
                "affectedResource": receipt["affected_resource"] if isinstance(receipt.get("affected_resource"), str) else "",
                "actorId": receipt["actor_id"] if isinstance(receipt.get("actor_id"), str) else "",
                "authorization": receipt["authorization"] if isinstance(receipt.get("authorization"), str) else "",
                "consentHash": receipt["consent_hash"] if isinstance(receipt.get("consent_hash"), str) else "",
                "executionId": receipt["execution_id"] if isinstance(receipt.get("execution_id"), str) else "",
                "phases": [],
            })
        if phase not in entry["phases"]:
            entry["phases"].append(phase)
    if not per_proposal:
        return "absent" if section is None else "mismatch"
    if section is None:
        return "mismatch"
    phases = {key: 0 for key in _PHASE_KEYS}
    proposals = [per_proposal[key] for key in sorted(per_proposal)]
    for entry in proposals:
        for phase in entry["phases"]:
            phases[phase] += 1
    return "match" if _canon(section) == _canon({"proposals": proposals, "phases": phases}) else "mismatch"


def verify_package(pkg, vkeys, memory: Memory) -> tuple[bool, list[tuple[str, str]]]:
    """Return (verified, report lines). Each line is (PASS|FAIL|NOTE, message)."""
    report: list[tuple[str, str]] = []

    def fail(message: str) -> tuple[bool, list[tuple[str, str]]]:
        report.append(("FAIL", message))
        return False, report

    att = pkg.get("attestation") if isinstance(pkg, dict) else None
    if not isinstance(att, dict) or att.get("schema") != SCHEMA:
        return fail(f"not an {SCHEMA} package")
    if not (isinstance(att.get("tenantId"), str) and att["tenantId"]
            and isinstance(att.get("generatedAt"), str) and att["generatedAt"]
            and _is_index(att.get("leafCount"), 2**53) and isinstance(att.get("allProofsVerified"), bool)
            and (att.get("merkleRoot") is None or (isinstance(att["merkleRoot"], str) and HASH.fullmatch(att["merkleRoot"])))
            and isinstance(att.get("contentDigest"), str) and HASH.fullmatch(att["contentDigest"])
            and isinstance(att.get("contentPreimage"), str)):
        return fail("required attestation fields are missing or malformed")
    if not _package_shape_ok(pkg):
        return fail(f"not a complete {SCHEMA} package")

    preimage = att["contentPreimage"]
    if "sha256:" + sha256(preimage.encode("utf-8")).hex() != att["contentDigest"]:
        return fail("checksum: contentDigest is not SHA-256 of the exact contentPreimage")
    shown = {k: v for k, v in att.items() if k not in ("contentDigest", "contentPreimage")}
    try:
        stated = json.loads(preimage, parse_constant=_reject_constant)
        # Presence is decided by the PARSED preimage (the producer's bytes); both
        # sides then use the same key set — a package asserting a section its
        # preimage lacks (or vice versa) is a mismatch, not a tolerated case.
        payload = {"attestation": shown, "compliance": pkg.get("compliance"),
                   "questionnaires": pkg.get("questionnaires")}
        if "remediationOutcomes" in stated:
            payload["remediationOutcomes"] = pkg.get("remediationOutcomes")
        same = _canon(stated) == _canon(payload)
    except (Failed, ValueError):
        same = False
    if not same:
        return fail("checksum: the package's context and assertions differ from its contentPreimage")
    report.append(("PASS", f"checksum: context and assertions match {att['contentDigest']}"))

    leaf_count, merkle_root, tenant = att["leafCount"], att["merkleRoot"], att["tenantId"]
    proofs = pkg.get("proofs")
    if not isinstance(proofs, list) or len(proofs) != leaf_count or (leaf_count == 0) != (merkle_root is None):
        return fail("ledger: the proofs do not match the declared ledger size")
    indices, entry_ids = set(), set()
    for proof in proofs:
        if not isinstance(proof, dict) or not _is_index(proof.get("index"), leaf_count) or proof["index"] in indices \
                or not isinstance(proof.get("entryId"), str) or not proof["entryId"] or proof["entryId"] in entry_ids \
                or not isinstance(proof.get("leafPreimage"), str):
            return fail("ledger: proofs are missing, repeated or out of range")
        fields = proof["leafPreimage"].split("\x1f")
        if fields[:3] != ["urlv1", proof["entryId"], tenant]:
            return fail(f"ledger: entry {proof['entryId']} does not belong to tenant {tenant}")
        indices.add(proof["index"])
        entry_ids.add(proof["entryId"])
    bad = [p["entryId"] for p in proofs if not _tenant_proof_ok(p, merkle_root, leaf_count)]
    if bad:
        return fail(f"ledger: {len(bad)} of {leaf_count} proofs do not recompute to the root ({', '.join(bad[:5])})")
    report.append(("PASS", f"ledger: {leaf_count} of {leaf_count} entries recompute to {merkle_root}"
                   if leaf_count else "ledger: empty (no activity evidence)"))

    checkpoints: list[Checkpoint] = []  # verified; compared for split views once every signature passed
    counts = {"included": 0, "pending": 0, "unconfigured": 0}
    largest = None
    for proof in proofs:
        log = proof["transparencyLog"]
        if log["status"] != "included":
            counts[log["status"]] += 1
            continue
        digest = bytes.fromhex(proof["contentHash"][len("sha256:"):])
        try:
            checkpoint, _ = logged_checkpoint(log["tlogProof"], lambda extra: activity_entry(extra, digest), vkeys)
        except Failed as exc:
            return fail(f"signed log: entry {proof['entryId']}: {exc}")
        checkpoints.append(checkpoint)
        counts["included"] += 1
        largest = checkpoint if largest is None or checkpoint.size > largest.size else largest

    def entries(count: int) -> str:
        return f"{count} entr{'y' if count == 1 else 'ies'}"

    if counts["included"]:
        report.append(("PASS", f"signed log: {entries(counts['included'])} included under {largest.origin} "
                       f"(checkpoint {largest.size})"))
    if counts["pending"]:
        report.append(("NOTE", f"signed log: {entries(counts['pending'])} pending (not yet in a signed checkpoint)"))
    if counts["unconfigured"]:
        report.append(("NOTE", f"signed log: {entries(counts['unconfigured'])} not logged in that environment"))

    if "seal" in pkg:
        seal = pkg["seal"]
        try:
            checkpoint, index = logged_checkpoint(
                seal["tlogProof"], lambda extra: artifact_entry(extra, preimage.encode("utf-8")), vkeys)
        except Failed as exc:
            return fail(f"seal: did NOT verify: {exc}")
        if index != seal["logIndex"]:
            return fail("seal: its log index does not match its proof")
        checkpoints.append(checkpoint)
        report.append(("PASS", f"seal: the exact context and assertions (contentPreimage) are entry {index} of "
                       f"{checkpoint.origin} (checkpoint {checkpoint.size}), unchanged since sealing"))
    else:
        report.append(("NOTE", "seal: none; only the unsigned checksum binds the context and assertions"))

    # Newest first, as the browser checks the seal before the entries: the largest verified
    # checkpoint is remembered even when a consistency proof to an older one is unavailable.
    outcomes = set()
    for checkpoint in sorted(set(checkpoints), key=lambda c: c.size, reverse=True):
        outcome = memory.check(checkpoint)
        if outcome == "split_view":
            return fail(f"SPLIT VIEW — checkpoint {checkpoint.size} of {checkpoint.origin} contradicts another "
                        "checkpoint this verifier verified")
        outcomes.add(outcome)
    report.extend(_consistency_lines(outcomes, memory.path is not None))
    has_receipts = False
    for proof in proofs:
        receipt = _action_receipt(proof["leafPreimage"])
        if receipt is None:
            if "ur-action-receipt/" in proof["leafPreimage"] or "Action receipt: " in proof["leafPreimage"]:
                report.append(("NOTE", f"action receipt {proof['entryId']}: malformed or unsupported binding; "
                               "receipt not verified"))
            continue
        has_receipts = True
        included = proof["transparencyLog"]["status"] == "included"
        status = ("locally checked signed inclusion" if included else
                  "pending/unsigned; no authenticated signed inclusion")
        report.append(("PASS" if included else "NOTE", f"action receipt {proof['entryId']}: {status}; "
                       f"phase={receipt['phase']}; actor={receipt['actor_id']}; "
                       f"authorization={receipt['authorization']}; consent_hash={receipt['consent_hash']}; "
                       f"execution_id={receipt['execution_id']}; action={receipt['action_type']}; "
                       f"target={receipt['affected_resource']}"))
    if has_receipts:
        report.append(("NOTE", "receipts attest an authenticated account and consent hash, not a personal "
                       "digital signature or proof that an action fixed anything"))
    # Last, after every structural check: the section must equal what the
    # receipts in the proofs derive — receipts the section cannot cover (or a
    # section the receipts do not support) fail the package, as in the browser.
    outcomes_derived = _derive_outcomes(proofs, tenant, pkg.get("remediationOutcomes"))
    if outcomes_derived == "mismatch":
        return fail("remediationOutcomes: the section does not match what the receipts in the proofs derive")
    if outcomes_derived == "match":
        report.append(("PASS", "remediationOutcomes: the rollup matches what the ledger receipts derive"))
    else:
        report.append(("NOTE", "remediationOutcomes: absent — package built before the section existed"))
    report.append(("NOTE", "a pass does not prove the assertions true; no independent witnesses cosign this log yet"))
    return True, report


# ── Command line ────────────────────────────────────────────────────────────


def _keys(args) -> list[str]:
    return list(PRODUCTION_KEYS) + ([DEVELOPMENT_KEY] if args.allow_dev_key else [])


def _safe(text: str) -> str:
    """Package fields are untrusted: never let control characters reach the terminal."""
    return "".join("?" if unicodedata.category(ch)[0] == "C" else ch for ch in text)


def _print(verified: bool, report, dev: bool) -> int:
    if dev:
        print("NOTE  the public development key is trusted: this result does not apply to production")
    for status, message in report:
        print(f"{status:<5} {_safe(message)}")
    print("RESULT: VERIFIED" if verified else "RESULT: FAILED")
    return 0 if verified else 1


def _cmd_package(args) -> int:
    try:
        memory = Memory(args.state, args.api)
        with open(args.file, encoding="utf-8") as handle:
            pkg = json.load(handle, parse_constant=_reject_constant)  # NaN is not JSON, as in browsers
    except OSError as exc:
        print(f"ur_verify: cannot read {exc.filename}: {exc.strerror}", file=sys.stderr)
        return 2
    except (ValueError, RecursionError, Failed):
        return _print(False, [("FAIL", f"{args.file} is not JSON")], args.allow_dev_key)
    try:
        verified, report = verify_package(pkg, _keys(args), memory)
    except Failed as exc:
        verified, report = False, [("FAIL", str(exc))]
    except Exception as exc:  # hostile input fails closed: never a pass, never a traceback
        verified, report = False, [("FAIL", f"malformed package ({type(exc).__name__})")]
    memory.save()
    return _print(verified, report, args.allow_dev_key)


REGISTER_WORKFLOW = "ai-governance-register"
_REGISTER_CONTENT_KEYS = ("workflow", "inputs", "assessment", "sections", "authors", "agentPolicy")
CARD_SCHEMA = "ur-posture-card/v1"
_CARD_CONTENT_KEYS = ("schema", "subject", "generatedAt", "claims", "aiGovernance")


def _canonical_document(payload, content_keys: tuple[str, ...]) -> bytes:
    content = {key: payload[key] for key in content_keys if key in payload}
    return json.dumps(content, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _verify_sealed_document(payload, vkeys, memory: Memory, *, label: str, kind_check, content_keys: tuple[str, ...],
                            attestation_note) -> tuple[bool, list[tuple[str, str]]]:
    """Shared chain for sealed documents: content digest, seal, split-view memory."""
    report: list[tuple[str, str]] = []

    def fail(message: str):
        report.append(("FAIL", message))
        return False, report

    kind_error = kind_check(payload)
    if kind_error:
        return fail(kind_error)
    proof = payload.get("proof") or {}
    seal = payload.get("seal") or {}
    snapshot_hash = proof.get("snapshotHash") or payload.get("contentDigest")
    if not (isinstance(snapshot_hash, str) and HASH.fullmatch(snapshot_hash)):
        return fail(f"the {label} has no content digest to verify")
    if seal.get("status") != "included" or not isinstance(seal.get("tlogProof"), str):
        return fail(f"the {label} is not sealed (no included tlog proof) — nothing binds it to the log")

    computed = "sha256:" + sha256(_canonical_document(payload, content_keys)).hex()
    if computed != snapshot_hash:
        return fail(f"content: the {label}'s content does not match its content digest "
                    f"({snapshot_hash}) — it changed after sealing or was edited")
    report.append(("PASS", f"content: the {label}'s content matches its content digest {snapshot_hash}"))

    try:
        digest = bytes.fromhex(snapshot_hash[len("sha256:"):])
        checkpoint, index = logged_checkpoint(
            seal["tlogProof"], lambda extra: artifact_entry(extra, digest), vkeys)
    except Failed as exc:
        return fail(f"seal: did NOT verify: {exc}")
    except ValueError as exc:
        return fail(f"seal: malformed digest ({type(exc).__name__})")
    if seal.get("logIndex") != index:
        return fail("seal: its log index does not match its proof")
    outcome = memory.check(checkpoint)
    if outcome == "split_view":
        return fail(f"SPLIT VIEW — checkpoint {checkpoint.size} of {checkpoint.origin} contradicts "
                    "another checkpoint this verifier verified")
    report.append(("PASS", f"seal: the exact {label} content (digest {snapshot_hash}) was entry {index} of "
                   f"{checkpoint.origin} (checkpoint {checkpoint.size}), unchanged since sealing"))
    report.extend(_consistency_lines({outcome}, memory.path is not None))
    attestation_note(payload, report)
    report.append(("NOTE", f"a pass proves the {label} is unchanged since sealing and internally consistent; "
                   "it does not prove its claims true"))
    return True, report


def _register_kind(payload):
    workflow = payload.get("workflow") if isinstance(payload, dict) else None
    if not isinstance(workflow, dict) or workflow.get("id") != REGISTER_WORKFLOW:
        return f"not an {REGISTER_WORKFLOW} register"
    return None


def _register_attestation_note(payload, report):
    attestation = payload.get("agentPolicy") or {}
    report.append(("NOTE", f"agent policy attestation: {attestation.get('drift', 'unknown')} "
                   f"(policy {attestation.get('policyHash', 'unknown')})"))
    report.append(("NOTE", "app identification is a name match, never vendor proof"))


def verify_register(payload, vkeys, memory: Memory) -> tuple[bool, list[tuple[str, str]]]:
    """Verify a sealed AI & agent register: content digest, seal, policy attestation."""
    return _verify_sealed_document(payload, vkeys, memory, label="register",
                                   kind_check=_register_kind, content_keys=_REGISTER_CONTENT_KEYS,
                                   attestation_note=_register_attestation_note)


def _card_kind(payload):
    if not isinstance(payload, dict) or payload.get("schema") != CARD_SCHEMA:
        return f"not a {CARD_SCHEMA} card"
    return None


def _card_attestation_note(payload, report):
    governance = payload.get("aiGovernance") or {}
    report.append(("NOTE", f"AI governance: agent policy {governance.get('policyHash', 'not attested by a register')}"))
    report.append(("NOTE", "the card carries counts and digests only — selective disclosure"))


def verify_card(payload, vkeys, memory: Memory) -> tuple[bool, list[tuple[str, str]]]:
    """Verify a sealed posture card: content digest, seal, AI-governance echo."""
    return _verify_sealed_document(payload, vkeys, memory, label="card",
                                   kind_check=_card_kind, content_keys=_CARD_CONTENT_KEYS,
                                   attestation_note=_card_attestation_note)


def _cmd_checkpoint(args) -> int:
    try:
        memory = Memory(args.state, args.api)
        if args.file:
            with open(args.file, encoding="utf-8") as handle:
                note = handle.read()
        else:
            api = (args.api or DEFAULT_API).rstrip("/")
            note = _fetch(f"{api}/api/transparency-log/checkpoint").decode("utf-8")
    except (OSError, ValueError) as exc:
        print(f"ur_verify: cannot read the checkpoint: {exc}", file=sys.stderr)
        return 2
    try:
        text, signers = verify_note(note, _keys(args))
        checkpoint = parse_checkpoint(text)
        if checkpoint.origin not in signers:
            raise Failed("checkpoint origin is not signed by its own log key")
        report = [("PASS", f"checkpoint: {checkpoint.origin} size {checkpoint.size} root {b64encode(checkpoint.root)}, "
                   f"signed by {', '.join(signers)}")]
        outcome = memory.check(checkpoint)
        if outcome == "split_view":
            raise Failed(f"SPLIT VIEW — checkpoint {checkpoint.size} contradicts one this verifier recorded before")
        report.extend(_consistency_lines({outcome}, memory.path is not None))
        if args.anchor:
            with open(args.anchor, "rb") as handle:
                receipt = handle.read()
            pairs = _parse_anchor(receipt, note)
            for height, attested in pairs:
                if args.block_header:
                    try:
                        header = bytes.fromhex(args.block_header)
                    except ValueError as exc:
                        raise Failed(f"anchor: --block-header is not hex ({exc})") from exc
                else:
                    # Two network fetches (Esplora): height -> hash -> 80-byte
                    # hex header. Pass --block-header for a fully offline check.
                    try:
                        block_hash = _fetch(f"https://blockstream.info/api/block-height/{height}").decode("ascii").strip()
                        header = bytes.fromhex(_fetch(f"https://blockstream.info/api/block/{block_hash}/header").decode("ascii").strip())
                    except (OSError, ValueError) as exc:
                        raise Failed(f"anchor: could not fetch block {height}'s header ({exc})") from exc
                merkle, block_time = _block_header_time(header)
                if merkle != attested:
                    raise Failed(f"anchor: attested message does not match block {height}'s merkle root")
                report.append(("PASS", f"anchor: bitcoin block {height} observed this checkpoint "
                                f"no later than {block_time} unix time"))
        verified = True
    except Failed as exc:
        verified, report = False, [("FAIL", f"checkpoint: {exc}")]
    memory.save()
    return _print(verified, report, args.allow_dev_key)


def _cmd_document(args, verify_fn, kind_name: str) -> int:
    try:
        memory = Memory(args.state, args.api)
        with open(args.file, encoding="utf-8") as handle:
            payload = json.load(handle, parse_constant=_reject_constant)
    except OSError as exc:
        print(f"ur_verify: cannot read {exc.filename}: {exc.strerror}", file=sys.stderr)
        return 2
    except (ValueError, RecursionError, Failed):
        return _print(False, [("FAIL", f"{args.file} is not JSON")], args.allow_dev_key)
    try:
        verified, report = verify_fn(payload, _keys(args), memory)
    except Failed as exc:
        verified, report = False, [("FAIL", str(exc))]
    except Exception as exc:  # hostile input fails closed: never a pass, never a traceback
        verified, report = False, [("FAIL", f"malformed {kind_name} ({type(exc).__name__})")]
    memory.save()
    return _print(verified, report, args.allow_dev_key)


def _cmd_register(args) -> int:
    return _cmd_document(args, verify_register, "register")


def _cmd_card(args) -> int:
    return _cmd_document(args, verify_card, "posture card")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="ur_verify", description=__doc__.split("\n\n")[0])
    parser.add_argument("--version", action="version", version=f"ur_verify {VERSION}")
    sub = parser.add_subparsers(dest="command", required=True)
    for name, helptext in (("package", "verify an evidence package JSON file"),
                           ("register", "verify a sealed AI & agent register JSON file"),
                           ("card", "verify a sealed posture card JSON file"),
                           ("checkpoint", "verify the log's current signed checkpoint")):
        cmd = sub.add_parser(name, help=helptext)
        if name == "checkpoint":
            cmd.add_argument("--file", help="read the checkpoint note from a file instead of the API")
            cmd.add_argument("--anchor", help="OpenTimestamps receipt (.ots) anchoring the checkpoint note in Bitcoin")
            cmd.add_argument("--block-header", help="80-byte block header (hex) for the attested height; "
                                                    "fetched from blockstream.info when omitted")
        else:
            cmd.add_argument("file", help="the downloaded document (JSON)")
        cmd.add_argument("--state", help="JSON file remembering checkpoints, to detect split views across runs")
        cmd.add_argument("--api", help=f"API serving the log's checkpoints and consistency proofs "
                                       f"(default {DEFAULT_API}, for UltimateReady's production log)")
        cmd.add_argument("--allow-dev-key", action="store_true",
                         help="also trust the public development key (local testing only)")
    args = parser.parse_args(argv)
    try:
        import cryptography  # noqa: F401
    except ImportError:
        print("ur_verify: the 'cryptography' package is required (pip install cryptography)", file=sys.stderr)
        return 2
    command = {"package": _cmd_package, "register": _cmd_register, "card": _cmd_card,
               "checkpoint": _cmd_checkpoint}
    return command[args.command](args)


if __name__ == "__main__":
    sys.exit(main())
