#!/usr/bin/env python3
"""GALENOS offline verification kit verifier.

Python 3 standard library only. It makes no network calls.

Authenticate first, execute second. An altered archive can carry an altered
copy of this script, and an altered download of this script can print any
result. Obtain the release SHA-256 of the archive and of this script from a
source you trust independently of the downloads, check both files with an
operating-system tool before Python starts, and only then run the script:

    printf '%s  galenos-offline-kit.tar\\n%s  verify_offline.py\\n' \\
        '<ARCHIVE_SHA256>' '<VERIFIER_SHA256>' | shasum -a 256 -c - && \\
    python3 -I verify_offline.py --archive galenos-offline-kit.tar \\
        --expect-archive-sha256 '<ARCHIVE_SHA256>'

Add --tamper-self-test to also require that mutated copies are rejected.
"python3 -I" isolates Python imports (no PYTHONPATH, no user site directory,
no script directory on sys.path). It is not an operating-system sandbox.

Input modes (mutually exclusive):

  --archive FILE   Open the file without following a symbolic link and without
                   blocking, require a regular file, read it once into a
                   private size-bounded snapshot, hash that snapshot and check
                   the archive pins. Only then walk the physical 512-byte
                   USTAR records (exactly one leading directory entry and the
                   20 expected regular files in sorted order, no extension
                   headers, links or devices, zero blocks to the end) and
                   extract the same snapshot into a private temporary
                   directory. A pin mismatch stops before tar parsing and
                   extraction.
  --kit-dir DIR    Verify an already extracted directory. The directory is
                   opened once and every listing and file open is anchored to
                   that handle (needs O_DIRECTORY, O_NOFOLLOW and dir_fd, as on
                   Linux and macOS). Entries are counted one at a time and
                   the listing stops past the entry bound. Archive pins (--expect-archive-sha256,
                   --checksum-file) are refused here, because a directory has
                   no archive digest to compare.

What is recomputed from the bytes in the kit:

  1. The exact schema-v2 inventory: 14 named audit receipts, the manifest, the
     dossier, the provenance manifest, README.txt, verify_offline.py and
     SHA256SUMS. A missing, extra, linked or non-regular entry is a mismatch.
  2. Every file listed in SHA256SUMS against its SHA-256.
  3. portfolio-manifest.json header fields (schemaVersion 2, NO_SELF_SCORE,
     no human auditor signature) and the exact receipt and run-digest key sets.
  4. For each of the 14 receipts: the byte SHA-256 of the audit JSON, its
     canonical output SHA-256, its ledgerReceiptId, and audit invariants
     (strict JSON, NO_SELF_SCORE, solver-free flag exactly true, the exact
     per-package identity field and gate names, each gate PASS, HOLD or
     BLOCK, gate counts). Track and core audits carry "package" and gates
     G1 to G4; the CRO bridge audit carries "module" and its four named gates.
  5. portfolioRootSha256 from manifest["receipts"].

Formulas (identical to scripts/build_site.py in the GALENOS repository):

  canonicalOutputSha256 = sha256(ascii(json.dumps(audit, sort_keys=True,
                              separators=(",", ":"), ensure_ascii=True)))
  ledgerReceiptId       = "cohort-" + package + "-" + canonicalOutputSha256[:12]
                          + "-" + sha256(ascii(canonicalOutputSha256 + ":"
                          + runFileSha256[package]))[:12]
  portfolioRootSha256   = sha256(utf8(json.dumps(manifest["receipts"],
                              sort_keys=True, separators=(",", ":"))))

Scope of the result. MATCH means the kit is internally consistent: the archive
member digests (SHA256SUMS), and the manifest receipt, canonical output,
receipt-ID and portfolio root digests were recomputed from the bytes in the
kit and agreed. The per-package run files are not bundled; they enter only as
their published runFileSha256 digests, which are used as given and are not
recomputed here. A kit rewritten end to end with freshly recomputed hashes is
also internally consistent, so the result line is
accompanied by a TRUST_ANCHOR line that states what was pinned from outside:

  RELEASE_ARCHIVE_PINNED  --expect-archive-sha256 matched the whole archive.
                          This is the only anchor that covers every file.
  RECEIPT_SET_PINNED      --expect-root matched portfolioRootSha256. This pins
                          manifest["receipts"] only. README.txt, this script,
                          the dossier, the provenance manifest and the other
                          manifest fields are checked by the local SHA256SUMS
                          only, which a forger can rewrite.
  NONE                    Internal consistency only. The sidecar checksum file
                          travels with the archive and is not an independent pin.

The per-package run files are not in the kit; ledgerReceiptId is recomputed
from their published SHA-256 digests (manifest["runFileSha256"]), which binds
the identifier to those digests without re-reading the run files.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import re
import stat
import sys
import tarfile
import tempfile
from pathlib import Path

KIT_DIR_NAME = "galenos-offline-kit"
ARCHIVE_NAME = "galenos-offline-kit.tar"
CHECKSUM_NAME = "galenos-offline-kit.sha256"
SUMS_NAME = "SHA256SUMS"
MANIFEST_NAME = "portfolio-manifest.json"

# Schema-v2 inventory. The verifier, not the kit, defines which files a kit holds.
EXPECTED_PACKAGES = (
    "aorta11_31", "cro_bridge", "dementia16_3", "dispense18_v2", "drug5_1", "ecg11_36", "fetal13_2",
    "galenos_core", "icu11_61", "omics11_63", "rare19_v2", "surg18_3", "twin11_32", "xray11_12",
)
EXPECTED_RECEIPTS = len(EXPECTED_PACKAGES)
EXPECTED_AUDIT_FILES = frozenset(f"{package}-audit.json" for package in EXPECTED_PACKAGES)
README_NAME = "README.txt"
EXPECTED_ANCILLARY_FILES = frozenset(
    {MANIFEST_NAME, "galenos_core-dossier.json", "public-provenance.json", README_NAME, "verify_offline.py"}
)
# The one audit file the tamper self-test mutates. Fixed here; never taken from a manifest inside the kit.
SELF_TEST_AUDIT_NAME = f"{EXPECTED_PACKAGES[0]}-audit.json"
EXPECTED_SUMS_FILES = EXPECTED_AUDIT_FILES | EXPECTED_ANCILLARY_FILES
EXPECTED_KIT_FILES = EXPECTED_SUMS_FILES | {SUMS_NAME}
RECEIPT_KEYS = frozenset({"artifact", "sha256", "canonicalOutputSha256", "ledgerReceiptId"})
VERIFIER_NAME = "verify_offline.py"
TRACK_GATES = ("G1", "G2", "G3", "G4")
CRO_GATES = (
    "G1_zero_custody_and_novelty",
    "G2_coa_and_plate_qc",
    "G3_raw_4pl_and_pk_recomputation",
    "G4_honest_advancement_and_holds",
)
REQUIRED_GATES = TRACK_GATES
# Exact audit contract per package: (identity field, gate names). The site renderer indexes these names directly,
# so a receipt that carries other names is not a receipt of that package.
PACKAGE_CONTRACTS = {package: ("package", TRACK_GATES) for package in EXPECTED_PACKAGES}
PACKAGE_CONTRACTS["cro_bridge"] = ("module", CRO_GATES)
GATE_STATUSES = frozenset({"PASS", "HOLD", "BLOCK"})

# Every pattern below is applied with fullmatch: "$" alone would accept a trailing newline.
HEX64 = re.compile(r"[0-9a-f]{64}")
ARTIFACT_NAME = re.compile(r"([a-z0-9_]+)-audit\.json")
SUMS_LINE = re.compile(r"([0-9a-f]{64})  ([A-Za-z0-9][A-Za-z0-9._-]*)")
CHECKSUM_LINE = re.compile(r"([0-9a-f]{64})  (" + re.escape(ARCHIVE_NAME) + r"|" + re.escape(VERIFIER_NAME) + r")")

BLOCK = 512
CHUNK = 1024 * 1024
MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
MAX_MEMBER_BYTES = 16 * 1024 * 1024
MAX_TOTAL_EXTRACTED_BYTES = 48 * 1024 * 1024
MAX_CHECKSUM_FILE_BYTES = 4096
MAX_ARCHIVE_MEMBERS = len(EXPECTED_KIT_FILES) + 1  # the files plus the one top-level directory entry
MAX_DIR_ENTRIES = 4 * len(EXPECTED_KIT_FILES)

USTAR_MAGIC = b"ustar\x00"
USTAR_VERSION = b"00"
USTAR_DIRECTORY = b"5"
USTAR_REGULAR = (b"0", b"\x00")
USTAR_EXTENSIONS = frozenset({b"x", b"g", b"L", b"K"})

ANCHOR_ARCHIVE = "TRUST_ANCHOR: RELEASE_ARCHIVE_PINNED (whole-archive SHA-256 verified)"
ANCHOR_RECEIPTS = (
    "TRUST_ANCHOR: RECEIPT_SET_PINNED (portfolioRootSha256 verified; "
    "ancillary kit files checked by local SHA256SUMS only)"
)
ANCHOR_SIDECAR = (
    "TRUST_ANCHOR: NONE (internal consistency only; the sidecar checksum file travels with the archive "
    "and is not an independent pin)"
)
ANCHOR_NONE = "TRUST_ANCHOR: NONE (internal consistency only; no independent release pin was supplied)"


class KitError(Exception):
    """The kit or archive cannot be read as a GALENOS offline kit."""


def sha256_hex(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def canonical_output_sha256(doc: object) -> str:
    payload = json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")
    return sha256_hex(payload)


def ledger_receipt_id(package: str, out_sha: str, run_file_sha: str) -> str:
    pair_sha = sha256_hex(f"{out_sha}:{run_file_sha}".encode("ascii"))
    return f"cohort-{package}-{out_sha[:12]}-{pair_sha[:12]}"


def portfolio_root_sha256(receipts: object) -> str:
    return sha256_hex(json.dumps(receipts, sort_keys=True, separators=(",", ":")).encode("utf-8"))


def _reject_constant(token: str) -> float:
    raise ValueError(f"non-finite JSON constant {token}")


def _finite_float(token: str) -> float:
    value = float(token)
    if not math.isfinite(value):
        raise ValueError(f"number {token[:24]} overflows to a non-finite value")
    return value


def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
    out: dict[str, object] = {}
    for key, value in pairs:
        if key in out:
            raise ValueError(f"duplicate JSON key {key!r}")
        out[key] = value
    return out


def load_strict_json(raw: bytes) -> object:
    """Parse JSON. Duplicate keys, NaN, Infinity and overflowing numbers are rejected while decoding."""
    try:
        return json.loads(
            raw.decode("utf-8"),
            parse_constant=_reject_constant,
            parse_float=_finite_float,
            object_pairs_hook=_unique_object,
        )
    except RecursionError as exc:
        raise KitError("JSON nesting is too deep") from exc
    except ValueError as exc:  # includes UnicodeDecodeError and json.JSONDecodeError
        raise KitError(f"not strict JSON: {exc}") from exc


def strict_open_flags() -> int:
    """Flags for opening one untrusted file: never follow a symbolic link, never block on a FIFO.

    Both O_NOFOLLOW and O_NONBLOCK are required. A host without either is refused; no weaker open is substituted.
    """
    missing = [name for name in ("O_NOFOLLOW", "O_NONBLOCK") if not hasattr(os, name)]
    if missing:
        raise KitError(
            f"this platform lacks {' and '.join(missing)}; nothing was opened "
            "(the verifier needs a POSIX host such as Linux or macOS)"
        )
    return os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_BINARY", 0)


def read_regular_file(path, limit: int, dir_fd: int | None = None) -> bytes:
    """Read one regular file, bounded by limit bytes, without following a symbolic link or blocking on a FIFO.

    With dir_fd the name is resolved inside that already opened directory, so swapping a parent path cannot redirect it.
    """
    label = Path(path).name
    flags = strict_open_flags()
    try:
        fd = os.open(path, flags) if dir_fd is None else os.open(path, flags, dir_fd=dir_fd)
        with os.fdopen(fd, "rb") as handle:
            info = os.fstat(handle.fileno())
            if not stat.S_ISREG(info.st_mode):
                raise KitError(f"{label} is not a regular file")
            if info.st_size > limit:
                raise KitError(f"{label} is larger than {limit} bytes")
            data = handle.read(limit + 1)
    except OSError as exc:
        raise KitError(f"cannot read {label}: {exc.strerror or exc}") from exc
    if len(data) > limit:
        raise KitError(f"{label} is larger than {limit} bytes")
    return data


class Report:
    def __init__(self, quiet: bool = False) -> None:
        self.quiet = quiet
        self.total = 0
        self.failed: list[str] = []
        self.anchors: set[str] = set()

    def check(self, check_id: str, ok: bool, detail: str = "") -> bool:
        self.total += 1
        if ok:
            if not self.quiet:
                print(f"MATCH     {check_id}")
        else:
            self.failed.append(check_id)
            if not self.quiet:
                print(f"MISMATCH  {check_id}: {detail}")
        return ok

    @property
    def ok(self) -> bool:
        return self.total > 0 and not self.failed


def trust_anchor_line(anchors: set[str]) -> str:
    if "archive" in anchors:
        return ANCHOR_ARCHIVE
    if "root" in anchors:
        return ANCHOR_RECEIPTS
    return ANCHOR_SIDECAR if "sidecar" in anchors else ANCHOR_NONE


def parse_sums(raw: bytes) -> dict[str, str]:
    text = raw.decode("utf-8")
    if not text.endswith("\n"):
        raise ValueError("last line is not terminated by a newline")
    listed: dict[str, str] = {}
    for line_no, line in enumerate(text[:-1].split("\n"), start=1):
        m = SUMS_LINE.fullmatch(line)
        if not m:
            raise ValueError(f"line {line_no} is not '<sha256>  <filename>'")
        digest, name = m.group(1), m.group(2)
        if name == SUMS_NAME:
            raise ValueError(f"line {line_no} names the reserved file {name!r}")
        if name in listed:
            raise ValueError(f"line {line_no} repeats {name!r}")
        listed[name] = digest
    return listed


def parse_checksum_file(raw: bytes) -> dict[str, str]:
    """Parse the release checksum file into {filename: sha256}.

    Accepted shapes, one '<sha256>  <filename>' record per line and nothing else:
      galenos-offline-kit.tar                       (archive pin only)
      galenos-offline-kit.tar, then verify_offline.py  (the published release record)
    A repeated, unknown, reordered or malformed record is rejected.
    """
    problem = (
        f"checksum file must hold '<64 lowercase hex>  {ARCHIVE_NAME}', optionally followed by "
        f"'<64 lowercase hex>  {VERIFIER_NAME}', one record per line and nothing else"
    )
    try:
        text = raw.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise KitError("checksum file is not UTF-8 text") from exc
    recorded: dict[str, str] = {}
    for line in (text[:-1] if text.endswith("\n") else text).split("\n"):
        m = CHECKSUM_LINE.fullmatch(line)
        if m is None or m.group(2) in recorded:
            raise KitError(problem)
        recorded[m.group(2)] = m.group(1)
    if list(recorded) not in ([ARCHIVE_NAME], [ARCHIVE_NAME, VERIFIER_NAME]):
        raise KitError(problem)
    return recorded


def _set_diff(actual: set[str], expected: frozenset[str]) -> str:
    missing = sorted(expected - actual)
    extra = sorted(actual - expected)
    return f"missing {missing[:6]}, unexpected {[name[:60] for name in extra[:6]]}"


def open_kit_dir(kit_dir: Path) -> int:
    """Open the kit directory once. Every later listing and file open is anchored to the returned handle."""
    supported = (
        hasattr(os, "O_DIRECTORY")
        and hasattr(os, "O_NOFOLLOW")
        and os.open in os.supports_dir_fd
        and os.stat in os.supports_dir_fd
        and os.scandir in os.supports_fd
    )
    if not supported:
        raise KitError("this platform lacks directory-handle opens (O_DIRECTORY, O_NOFOLLOW, dir_fd, scandir on a handle); the kit directory was not read")
    try:
        dir_fd = os.open(kit_dir, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    except FileNotFoundError as exc:
        raise KitError(f"kit directory not found: {kit_dir}") from exc
    except OSError as exc:
        raise KitError(f"kit directory is a symbolic link, not a directory, or unreadable: {exc.strerror or exc}") from exc
    if not stat.S_ISDIR(os.fstat(dir_fd).st_mode):
        os.close(dir_fd)
        raise KitError("kit directory is a symbolic link or not a directory")
    return dir_fd


def list_kit_dir_bounded(dir_fd: int) -> list[str]:
    """List the opened directory one entry at a time and stop at entry MAX_DIR_ENTRIES + 1.

    The entries are counted as they are read, so a directory with a very large number of entries is refused
    before a full listing of it is ever held in memory.
    """
    names: list[str] = []
    try:
        with os.scandir(dir_fd) as entries:
            for entry in entries:
                if len(names) >= MAX_DIR_ENTRIES:
                    raise KitError(f"more than {MAX_DIR_ENTRIES} directory entries; listing stopped")
                names.append(entry.name)
    except OSError as exc:
        raise KitError(f"cannot list kit directory: {exc.strerror or exc}") from exc
    return names


def inventory_problems_at(dir_fd: int) -> list[str]:
    """Check every entry of the opened directory before any file content is read."""
    names = list_kit_dir_bounded(dir_fd)
    problems: list[str] = []
    for name in sorted(names):
        try:
            mode = os.stat(name, dir_fd=dir_fd, follow_symlinks=False).st_mode
        except OSError:
            problems.append(f"{name[:60]!r} cannot be inspected")
            continue
        if stat.S_ISLNK(mode):
            problems.append(f"{name[:60]!r} is a symbolic link")
        elif not stat.S_ISREG(mode):
            problems.append(f"{name[:60]!r} is not a regular file")
    if set(names) != EXPECTED_KIT_FILES:
        problems.append(_set_diff(set(names), EXPECTED_KIT_FILES))
    return problems


def read_kit_files_at(dir_fd: int) -> dict[str, bytes]:
    """Read each expected regular file exactly once, by name inside the opened directory."""
    blobs: dict[str, bytes] = {}
    total = 0
    for name in sorted(EXPECTED_KIT_FILES):
        blobs[name] = read_regular_file(name, MAX_MEMBER_BYTES, dir_fd=dir_fd)
        total += len(blobs[name])
        if total > MAX_TOTAL_EXTRACTED_BYTES:
            raise KitError(f"kit files exceed {MAX_TOTAL_EXTRACTED_BYTES} bytes in total")
    return blobs


def inventory_problems(kit_dir: Path) -> list[str]:
    """Check the directory itself and every entry before any file content is read."""
    dir_fd = open_kit_dir(kit_dir)
    try:
        return inventory_problems_at(dir_fd)
    finally:
        os.close(dir_fd)


def read_validated_kit(kit_dir: Path) -> dict[str, bytes]:
    """Inventory first, then read each expected regular file exactly once, all through one directory handle."""
    dir_fd = open_kit_dir(kit_dir)
    try:
        problems = inventory_problems_at(dir_fd)
        if problems:
            raise KitError("kit inventory mismatch: " + "; ".join(problems[:6]))
        return read_kit_files_at(dir_fd)
    finally:
        os.close(dir_fd)


def gate_statuses(gates: object, gate_keys: tuple[str, ...] = TRACK_GATES) -> list[str] | None:
    """Return the gate statuses in gate_keys order, or None unless the block holds exactly those gate names."""
    if not isinstance(gates, dict) or set(gates) != set(gate_keys):
        return None
    statuses: list[str] = []
    for key in gate_keys:
        gate = gates[key]
        if not isinstance(gate, dict):
            return None
        status = gate.get("status")
        if not isinstance(status, str) or status not in GATE_STATUSES:
            return None
        statuses.append(status)
    return statuses


def verify_kit(
    kit_dir: Path,
    report: Report,
    expect_root: str | None = None,
    expect_verifier_sha: str | None = None,
    verified_blobs: dict[str, bytes] | None = None,
) -> bool:
    """Run every check against an extracted kit directory. Returns True on full MATCH.

    On full MATCH, verified_blobs (when given) is filled with the exact bytes that were just verified, one entry
    per expected kit file, as read through the anchored directory handle. On any mismatch it is left empty.
    """
    if verified_blobs is not None:
        verified_blobs.clear()
    try:
        dir_fd = open_kit_dir(kit_dir)
    except KitError as exc:
        report.check("kit.inventory", False, str(exc))
        return False
    try:
        try:
            problems = inventory_problems_at(dir_fd)
        except KitError as exc:
            problems = [str(exc)]
        if not report.check("kit.inventory", not problems, "; ".join(problems[:6])):
            return False
        try:
            blobs = read_kit_files_at(dir_fd)
        except KitError as exc:
            report.check("kit.read", False, str(exc))
            return False
    finally:
        os.close(dir_fd)
    ok = verify_blobs(blobs, report, expect_root, expect_verifier_sha)
    if ok and verified_blobs is not None:
        verified_blobs.update({name: blobs[name] for name in sorted(EXPECTED_KIT_FILES)})
    return ok


def verify_blobs(
    blobs: dict[str, bytes], report: Report, expect_root: str | None = None, expect_verifier_sha: str | None = None
) -> bool:
    """Verify kit content that was already read once. No file is opened again past this point."""
    # (a) SHA256SUMS: exact name set, then every digest. Nothing is parsed as JSON until all of this holds.
    try:
        listed = parse_sums(blobs[SUMS_NAME])
    except ValueError as exc:
        report.check("sums.parse", False, str(exc))
        return False
    report.check("sums.parse", True)
    if not report.check("sums.inventory", set(listed) == EXPECTED_SUMS_FILES, _set_diff(set(listed), EXPECTED_SUMS_FILES)):
        return False
    sums_ok = True
    for name in sorted(listed):
        actual = sha256_hex(blobs[name])
        sums_ok = report.check(f"sums.file[{name}]", actual == listed[name], f"expected {listed[name]}, got {actual}") and sums_ok
    if not sums_ok:
        return False
    if expect_verifier_sha is not None:
        # The release checksum file also lists the verifier: the bundled copy must be those same bytes.
        bundled = sha256_hex(blobs[VERIFIER_NAME])
        if not report.check(
            "archive.checksumFile.verifier",
            bundled == expect_verifier_sha,
            f"checksum file records {expect_verifier_sha} for {VERIFIER_NAME}, the archive holds {bundled}",
        ):
            return False

    # (b) manifest header and exact receipt and run-digest inventories
    try:
        manifest = load_strict_json(blobs[MANIFEST_NAME])
    except KitError as exc:
        report.check("manifest.parse", False, str(exc))
        return False
    if not report.check("manifest.parse", isinstance(manifest, dict), "top level is not an object"):
        return False
    schema_version = manifest.get("schemaVersion")
    report.check("manifest.schemaVersion", type(schema_version) is int and schema_version == 2, f"got {schema_version!r}")
    report.check("manifest.scorePolicy", manifest.get("scorePolicy") == "NO_SELF_SCORE", f"got {manifest.get('scorePolicy')!r}")
    report.check(
        "manifest.humanAuditorSignature",
        "humanAuditorSignature" in manifest and manifest["humanAuditorSignature"] is None,
        "must be present and null",
    )
    receipts = manifest.get("receipts")
    receipts_ok = isinstance(receipts, list) and len(receipts) == EXPECTED_RECEIPTS and all(isinstance(r, dict) for r in receipts)
    if not report.check(
        "manifest.receiptCount",
        receipts_ok,
        f"expected {EXPECTED_RECEIPTS} receipt objects, got {len(receipts) if isinstance(receipts, list) else type(receipts).__name__}",
    ):
        return False
    shaped = all(set(r) == RECEIPT_KEYS and all(isinstance(v, str) for v in r.values()) for r in receipts)
    artifacts = {r["artifact"] for r in receipts} if shaped else set()
    if not report.check(
        "manifest.receiptInventory",
        shaped and artifacts == EXPECTED_AUDIT_FILES,
        "receipt fields must be exactly artifact, sha256, canonicalOutputSha256, ledgerReceiptId (strings); "
        + _set_diff(artifacts, EXPECTED_AUDIT_FILES),
    ):
        return False
    run_digests = manifest.get("runFileSha256")
    run_ok = (
        isinstance(run_digests, dict)
        and set(run_digests) == set(EXPECTED_PACKAGES)
        and all(isinstance(v, str) and HEX64.fullmatch(v) is not None for v in run_digests.values())
    )
    if not report.check(
        "manifest.runFileInventory",
        run_ok,
        "runFileSha256 must map exactly the 14 expected packages to 64-hex digests",
    ):
        return False

    # (c) each receipt
    gates_total = 0
    gates_passed = 0
    for entry in receipts:
        artifact = entry["artifact"]
        package = ARTIFACT_NAME.fullmatch(artifact).group(1)
        tag = f"receipt[{package}]"
        raw = blobs[artifact]
        byte_sha = sha256_hex(raw)
        report.check(f"{tag}.sha256", byte_sha == entry["sha256"], f"manifest {entry['sha256']!r}, file {byte_sha}")
        try:
            audit = load_strict_json(raw)
        except KitError as exc:
            report.check(f"{tag}.strictJson", False, str(exc))
            continue
        if not report.check(f"{tag}.strictJson", isinstance(audit, dict), "audit top level is not an object"):
            continue
        out_sha = canonical_output_sha256(audit)
        report.check(
            f"{tag}.canonicalOutputSha256",
            out_sha == entry["canonicalOutputSha256"],
            f"manifest {entry['canonicalOutputSha256']!r}, recomputed {out_sha}",
        )
        expected_id = ledger_receipt_id(package, out_sha, run_digests[package])
        report.check(
            f"{tag}.ledgerReceiptId",
            expected_id == entry["ledgerReceiptId"],
            f"manifest {entry['ledgerReceiptId']!r}, recomputed {expected_id}",
        )
        report.check(f"{tag}.scorePolicy", audit.get("scorePolicy") == "NO_SELF_SCORE", f"got {audit.get('scorePolicy')!r}")
        report.check(
            f"{tag}.humanAuditorSignature",
            "humanAuditorSignature" in audit and audit["humanAuditorSignature"] is None,
            "must be present and null",
        )
        ast_block = audit.get("solverFreeAst")
        report.check(
            f"{tag}.solverFree",
            isinstance(ast_block, dict) and ast_block.get("solverFree") is True,
            "solverFreeAst.solverFree must be present and exactly true",
        )
        # Exact contract per package: no fallback from one identity field to the other, no renamed gates.
        identity_field, gate_keys = PACKAGE_CONTRACTS[package]
        identity = audit.get(identity_field)
        report.check(
            f"{tag}.package",
            isinstance(identity, str) and identity == package,
            f"audit field {identity_field!r} is {identity!r}, receipt file is {artifact}",
        )
        statuses = gate_statuses(audit.get("gates"), gate_keys)
        if report.check(
            f"{tag}.gates",
            statuses is not None,
            f"gates must be exactly {', '.join(gate_keys)}, each an object with status PASS, HOLD or BLOCK",
        ):
            gates_total += len(statuses)
            gates_passed += sum(1 for status in statuses if status == "PASS")

    report.check(
        "manifest.totalGates",
        type(manifest.get("totalGates")) is int and manifest.get("totalGates") == gates_total,
        f"manifest {manifest.get('totalGates')!r}, recounted {gates_total}",
    )
    report.check(
        "manifest.totalGatesPassed",
        type(manifest.get("totalGatesPassed")) is int and manifest.get("totalGatesPassed") == gates_passed,
        f"manifest {manifest.get('totalGatesPassed')!r}, recounted {gates_passed}",
    )

    # (d) portfolio root
    root = portfolio_root_sha256(receipts)
    report.check(
        "manifest.portfolioRootSha256",
        root == manifest.get("portfolioRootSha256"),
        f"manifest {manifest.get('portfolioRootSha256')!r}, recomputed {root}",
    )
    if expect_root is not None:
        if report.check("anchor.expectRoot", root == expect_root.lower(), f"expected {expect_root.lower()}, recomputed {root}"):
            report.anchors.add("root")
    return report.ok


def snapshot_archive(archive: Path, snap) -> tuple[str, int]:
    """Copy the archive once into snap, bounded by MAX_ARCHIVE_BYTES. Returns (sha256, size) of the copy."""
    digest = hashlib.sha256()
    size = 0
    # No symbolic link is followed and a FIFO cannot block the open; the type is checked before any byte is read.
    # O_NOFOLLOW and O_NONBLOCK are both required: a host without them raises KitError here.
    flags = strict_open_flags()
    try:
        fd = os.open(archive, flags)
        with os.fdopen(fd, "rb") as src:
            if not stat.S_ISREG(os.fstat(src.fileno()).st_mode):
                raise KitError(f"archive is not a regular file: {archive}")
            while True:
                chunk = src.read(CHUNK)
                if not chunk:
                    break
                size += len(chunk)
                if size > MAX_ARCHIVE_BYTES:
                    raise KitError(f"archive is larger than {MAX_ARCHIVE_BYTES} bytes")
                digest.update(chunk)
                snap.write(chunk)
        snap.flush()
    except OSError as exc:
        raise KitError(f"cannot read archive {archive}: {exc.strerror or exc}") from exc
    return digest.hexdigest(), size


def _octal_field(field: bytes, what: str) -> int:
    digits = field.rstrip(b" \x00")
    if not digits or digits.strip(b"01234567"):
        raise KitError(f"archive header {what} field is not plain octal")
    return int(digits, 8)


def validate_ustar_framing(data: bytes) -> None:
    """Walk the physical 512-byte records of the release container before any tar library reads it.

    The release shape is fixed: one zero-size galenos-offline-kit/ directory header, then the 20 expected regular
    files in sorted order, each header a plain POSIX USTAR record with a valid checksum, then zero blocks only.
    Extension records (pax x and g, GNU L and K), links, devices and path prefixes are rejected here, so the
    member-count and size limits bound every record and not only the logical members a tar library would yield.
    """
    size = len(data)
    if size == 0 or size % BLOCK != 0:
        raise KitError(f"archive size {size} is not a positive multiple of {BLOCK} bytes")
    if size > MAX_ARCHIVE_BYTES:
        raise KitError(f"archive is larger than {MAX_ARCHIVE_BYTES} bytes")
    order = sorted(EXPECTED_KIT_FILES)
    member_limit = min(MAX_ARCHIVE_MEMBERS, len(order) + 1)
    zero_block = bytes(BLOCK)
    offset = 0
    count = 0
    total = 0
    while offset < size:
        header = data[offset:offset + BLOCK]
        if header == zero_block:
            break
        count += 1
        if count > member_limit:
            raise KitError(f"archive holds more than {member_limit} members")
        if header[257:263] != USTAR_MAGIC or header[263:265] != USTAR_VERSION:
            raise KitError(f"archive record {count} is not a POSIX USTAR header")
        if _octal_field(header[148:156], "checksum") != sum(header[:148]) + 8 * 0x20 + sum(header[156:]):
            raise KitError(f"archive record {count} has a wrong header checksum")
        name = header[0:100].split(b"\x00", 1)[0].decode("latin-1")
        shown = name[:80]
        typeflag = header[156:157]
        if typeflag in USTAR_EXTENSIONS:
            raise KitError(f"archive member {shown!r} carries extended headers")
        if header[157:257].strip(b"\x00") or header[345:500].strip(b"\x00"):
            raise KitError(f"unexpected archive member {shown!r}: link target and path prefix must be empty")
        member_size = _octal_field(header[124:136], "size")
        if count == 1:
            if typeflag != USTAR_DIRECTORY or name not in (KIT_DIR_NAME, KIT_DIR_NAME + "/") or member_size != 0:
                raise KitError(
                    f"unexpected archive member {shown!r}: the first member must be the zero-size {KIT_DIR_NAME}/ directory"
                )
            offset += BLOCK
            continue
        expected = f"{KIT_DIR_NAME}/{order[count - 2]}"
        if typeflag not in USTAR_REGULAR or name != expected:
            raise KitError(f"unexpected archive member {shown!r}: expected the regular file {expected!r}")
        if member_size > MAX_MEMBER_BYTES:
            raise KitError(f"archive member {shown!r} is larger than {MAX_MEMBER_BYTES} bytes")
        total += member_size
        if total > MAX_TOTAL_EXTRACTED_BYTES:
            raise KitError(f"archive members exceed {MAX_TOTAL_EXTRACTED_BYTES} bytes in total")
        offset += BLOCK + ((member_size + BLOCK - 1) // BLOCK) * BLOCK
        if offset > size:
            raise KitError(f"archive member {shown!r} has no complete data")
    if count != len(order) + 1:
        raise KitError(f"archive inventory mismatch: expected 1 directory and {len(order)} files, found {count} members")
    tail = data[offset:]
    if len(tail) < 2 * BLOCK or tail.count(0) != len(tail):
        raise KitError("archive does not end with the USTAR end-of-archive zero blocks, or carries trailing non-zero data")


def _extract_snapshot(snap, size: int, dest: Path) -> Path:
    """Extract an already hashed snapshot into dest. Member paths, types, counts and sizes are not trusted."""
    try:
        snap.seek(0)
        data = snap.read(MAX_ARCHIVE_BYTES + 1)
    except OSError as exc:
        raise KitError(f"cannot read archive snapshot: {exc.strerror or exc}") from exc
    if len(data) != size:
        raise KitError("archive snapshot does not hold the hashed bytes")
    # Physical record walk first. Nothing is created on disk and no tar library runs until the container shape is exact.
    validate_ustar_framing(data)
    del data
    prefix = KIT_DIR_NAME + "/"
    kit_dir = dest / KIT_DIR_NAME
    seen: set[str] = set()
    total = 0
    count = 0
    data_end = 0
    saw_top_dir = False
    try:
        kit_dir.mkdir(parents=True)
        snap.seek(0)
        with tarfile.open(fileobj=snap, mode="r:") as tar:
            for member in tar:
                count += 1
                if count > MAX_ARCHIVE_MEMBERS:
                    raise KitError(f"archive holds more than {MAX_ARCHIVE_MEMBERS} members")
                if member.pax_headers:
                    raise KitError(f"archive member {member.name[:80]!r} carries extended headers")
                if count == 1:
                    if not (member.isdir() and member.name.rstrip("/") == KIT_DIR_NAME and member.size == 0):
                        raise KitError(
                            f"unexpected archive member {member.name[:80]!r}: the first member must be the {KIT_DIR_NAME}/ directory"
                        )
                    saw_top_dir = True
                    data_end = member.offset_data
                    continue
                name = member.name[len(prefix):] if member.name.startswith(prefix) else ""
                if member.type not in (tarfile.REGTYPE, tarfile.AREGTYPE) or name not in EXPECTED_KIT_FILES:
                    raise KitError(f"unexpected archive member {member.name[:80]!r}")
                if name in seen:
                    raise KitError(f"archive repeats member {member.name!r}")
                if member.size > MAX_MEMBER_BYTES:
                    raise KitError(f"archive member {member.name!r} is larger than {MAX_MEMBER_BYTES} bytes")
                total += member.size
                if total > MAX_TOTAL_EXTRACTED_BYTES:
                    raise KitError(f"archive members exceed {MAX_TOTAL_EXTRACTED_BYTES} bytes in total")
                handle = tar.extractfile(member)
                data = handle.read(member.size + 1) if handle is not None else b""
                if handle is None or len(data) != member.size:
                    raise KitError(f"archive member {member.name!r} has no complete data")
                with open(kit_dir / name, "xb") as out:
                    out.write(data)
                seen.add(name)
                data_end = member.offset_data + ((member.size + BLOCK - 1) // BLOCK) * BLOCK
        if saw_top_dir is not True:
            raise KitError(f"archive does not start with the {KIT_DIR_NAME}/ directory entry")
        if seen != EXPECTED_KIT_FILES:
            raise KitError("archive inventory mismatch: " + _set_diff(seen, EXPECTED_KIT_FILES))
        # Canonical USTAR framing: after the last member payload and its padding come only zero blocks, at least two.
        snap.seek(data_end)
        tail = snap.read(MAX_ARCHIVE_BYTES + 1)
    except (tarfile.TarError, OSError) as exc:
        raise KitError(f"cannot read archive: {exc}") from exc
    if len(tail) < 2 * BLOCK or tail.count(0) != len(tail):
        raise KitError("archive does not end with the USTAR end-of-archive zero blocks, or carries trailing non-zero data")
    return kit_dir


def extract_archive(archive: Path, dest: Path) -> Path:
    """Snapshot the archive once and extract that snapshot into dest."""
    with tempfile.TemporaryFile(prefix="galenos-kit-snap-") as snap:
        _sha, size = snapshot_archive(archive, snap)
        return _extract_snapshot(snap, size, dest)


def verify_archive(
    archive: Path,
    report: Report,
    checksum_file: Path | None,
    expect_sha: str | None,
    expect_root: str | None,
    self_test: bool = False,
) -> bool:
    """Hash, pin, extract and verify one private snapshot of the archive. The caller path is opened once."""
    with tempfile.TemporaryFile(prefix="galenos-kit-snap-") as snap:
        archive_sha, size = snapshot_archive(archive, snap)
        if not report.quiet:
            print(f"archive   {archive.name} sha256={archive_sha}")
        if checksum_file is None:
            sibling = archive.with_name(CHECKSUM_NAME)
            checksum_file = sibling if os.path.lexists(sibling) else None
        pins_ok = True
        stop_reasons: list[str] = []
        expect_verifier_sha: str | None = None
        if checksum_file is not None:
            try:
                recorded = parse_checksum_file(read_regular_file(checksum_file, MAX_CHECKSUM_FILE_BYTES))
            except KitError as exc:
                pins_ok = report.check("archive.checksumFile", False, str(exc))
                stop_reasons.append("checksum file not usable")
            else:
                if report.check(
                    "archive.checksumFile",
                    recorded[ARCHIVE_NAME] == archive_sha,
                    f"{checksum_file.name} records {recorded[ARCHIVE_NAME]}, archive is {archive_sha}",
                ):
                    report.anchors.add("sidecar")
                    # Checked after extraction, against the verify_offline.py bytes inside the archive.
                    expect_verifier_sha = recorded.get(VERIFIER_NAME)
                else:
                    pins_ok = False
                    stop_reasons.append("archive hash mismatch")
        if expect_sha is not None:
            if report.check("anchor.expectArchiveSha256", expect_sha.lower() == archive_sha, f"expected {expect_sha.lower()}, archive is {archive_sha}"):
                report.anchors.add("archive")
            else:
                pins_ok = False
                if "archive hash mismatch" not in stop_reasons:
                    stop_reasons.append("archive hash mismatch")
        if not pins_ok:
            # Stop here: an archive that fails its pin was read once for hashing and is never parsed as tar or extracted.
            if not report.quiet:
                print(f"STOPPED   {' and '.join(stop_reasons)}; stopped before tar parsing and extraction")
            return False
        with tempfile.TemporaryDirectory(prefix="galenos-kit-") as tmp:
            kit_dir = _extract_snapshot(snap, size, Path(tmp))
            verified: dict[str, bytes] = {}
            ok = verify_kit(kit_dir, report, expect_root, expect_verifier_sha, verified_blobs=verified)
            if ok and self_test:
                # The self-test works from the bytes just verified; no pathname is opened a second time.
                ok = tamper_self_test(verified)
            return ok


def _flip_hex(ch: str) -> str:
    return "0" if ch != "0" else "1"


def _write_sums(kit_dir: Path) -> None:
    # File names come from the verifier's fixed inventory, never from a directory walk or from the kit's own records.
    names = sorted(n for n in EXPECTED_SUMS_FILES if (kit_dir / n).is_file())
    body = "".join(f"{sha256_hex((kit_dir / n).read_bytes())}  {n}\n" for n in names)
    (kit_dir / SUMS_NAME).write_bytes(body.encode("utf-8"))


def _mutate_audit_digit(kit_dir: Path) -> None:
    path = kit_dir / SELF_TEST_AUDIT_NAME
    text = path.read_text(encoding="utf-8")
    m = re.search(r'"value": (\d)', text) or re.search(r": (\d)", text)
    if m is None:
        raise KitError("no numeric value found to mutate in the first audit JSON")
    pos = m.start(1)
    digit = text[pos]
    path.write_text(text[:pos] + ("7" if digit != "7" else "3") + text[pos + 1:], encoding="utf-8")


def _mutate_manifest_field(kit_dir: Path, pick) -> None:
    path = kit_dir / MANIFEST_NAME
    text = path.read_text(encoding="utf-8")
    old = pick(json.loads(text))
    if text.count(old) != 1:
        raise KitError("mutation target is not unique in portfolio-manifest.json")
    path.write_text(text.replace(old, _flip_hex(old[0]) + old[1:]), encoding="utf-8")


def _reseal_everything(kit_dir: Path) -> None:
    """Recompute every hash after a mutation, as a forger with full write access would."""
    path = kit_dir / MANIFEST_NAME
    manifest = json.loads(path.read_text(encoding="utf-8"))
    by_artifact = {entry["artifact"]: entry for entry in manifest["receipts"]}
    # The files to open are named by the verifier's fixed package list; the manifest only supplies the entry to update.
    for package in EXPECTED_PACKAGES:
        entry = by_artifact[f"{package}-audit.json"]
        raw = (kit_dir / f"{package}-audit.json").read_bytes()
        out_sha = canonical_output_sha256(json.loads(raw.decode("utf-8")))
        entry["sha256"] = sha256_hex(raw)
        entry["canonicalOutputSha256"] = out_sha
        entry["ledgerReceiptId"] = ledger_receipt_id(package, out_sha, manifest["runFileSha256"][package])
    manifest["portfolioRootSha256"] = portfolio_root_sha256(manifest["receipts"])
    path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    _write_sums(kit_dir)


def _add_extra_file(kit_dir: Path) -> None:
    (kit_dir / "unlisted-note.txt").write_bytes(b"not part of the schema-v2 inventory\n")


def _drop_ancillary_file(kit_dir: Path) -> None:
    (kit_dir / README_NAME).unlink()
    _write_sums(kit_dir)


def tamper_self_test(verified_blobs: dict[str, bytes]) -> bool:
    """Write temporary copies from already verified bytes, mutate the copies, and require every mutation to be rejected.

    verified_blobs is the byte set verify_kit filled on a full MATCH. No kit directory pathname is accepted or
    reopened here, so a directory swapped after verification cannot feed the self-test. The pristine copy is
    verified first; if it fails, the self-test stops before any mutation runs.
    """
    if (
        not isinstance(verified_blobs, dict)
        or set(verified_blobs) != EXPECTED_KIT_FILES
        or not all(isinstance(data, bytes) for data in verified_blobs.values())
    ):
        raise KitError("tamper self-test needs the verified bytes of exactly the expected kit files; nothing was mutated")
    blobs = {name: verified_blobs[name] for name in sorted(EXPECTED_KIT_FILES)}
    mutations = [
        ("audit-digit", "one digit changed in an audit JSON", _mutate_audit_digit, "canonicalOutputSha256"),
        (
            "receipt-hash",
            "one receipt sha256 changed in portfolio-manifest.json",
            lambda d: _mutate_manifest_field(d, lambda m: m["receipts"][0]["sha256"]),
            ".sha256",
        ),
        (
            "portfolio-root",
            "portfolioRootSha256 changed in portfolio-manifest.json",
            lambda d: _mutate_manifest_field(d, lambda m: m["portfolioRootSha256"]),
            "manifest.portfolioRootSha256",
        ),
    ]
    outcomes: list[tuple[str, bool, str]] = []
    # Only the verified bytes are written out; nothing is followed, reopened or copied by directory walk.
    with tempfile.TemporaryDirectory(prefix="galenos-kit-tamper-") as tmp:
        base = Path(tmp)

        def fresh(label: str) -> Path:
            target = base / label / KIT_DIR_NAME
            target.mkdir(parents=True)
            for name, data in blobs.items():
                (target / name).write_bytes(data)
            return target

        pristine = Report(quiet=True)
        if not verify_kit(fresh("pristine"), pristine):
            # Abort here. A mutation result means nothing when the unmodified copy does not verify.
            print(
                "MISMATCH  tamper-self-test: pristine copy verifies "
                f"({len(pristine.failed)} of {pristine.total} checks failed; stopped before any mutation)"
            )
            return False
        outcomes.append(("pristine copy verifies", True, ""))
        manifest = load_strict_json(blobs[MANIFEST_NAME])
        original_root = manifest.get("portfolioRootSha256", "") if isinstance(manifest, dict) else ""

        for label, text, mutate, deep_marker in mutations:
            # Mode 1: the mutation alone. SHA256SUMS must reject it.
            plain_dir = fresh(f"{label}-plain")
            mutate(plain_dir)
            plain = Report(quiet=True)
            verify_kit(plain_dir, plain)
            caught = (not plain.ok) and any(c.startswith("sums.file[") for c in plain.failed)
            outcomes.append((f"{text}: rejected by SHA256SUMS", caught, f"failed checks: {plain.failed[:4]}"))
            # Mode 2: the forger also rewrites SHA256SUMS. The deeper hash chain must still reject it.
            sealed_dir = fresh(f"{label}-resealed-sums")
            mutate(sealed_dir)
            _write_sums(sealed_dir)
            sealed = Report(quiet=True)
            verify_kit(sealed_dir, sealed)
            sums_clean = not any(c.startswith("sums.") for c in sealed.failed)
            deep = (not sealed.ok) and sums_clean and any(deep_marker in c for c in sealed.failed)
            outcomes.append((f"{text}: rejected after SHA256SUMS rewrite", deep, f"failed checks: {sealed.failed[:4]}"))

        # Mode 3: the inventory is fixed by the verifier, so an added or removed file is rejected before any read.
        for label, text, mutate in (
            ("extra-file", "one unlisted file added to the kit", _add_extra_file),
            ("missing-file", "README.txt removed and SHA256SUMS rewritten", _drop_ancillary_file),
        ):
            changed_dir = fresh(label)
            mutate(changed_dir)
            changed = Report(quiet=True)
            verify_kit(changed_dir, changed)
            outcomes.append((f"{text}: rejected by the inventory check", changed.failed == ["kit.inventory"], f"failed checks: {changed.failed[:4]}"))

        # Mode 4: every hash in the kit rewritten. Internal checks cannot see this; the out-of-band root does.
        forged_dir = fresh("full-reseal")
        _mutate_audit_digit(forged_dir)
        _reseal_everything(forged_dir)
        anchored = Report(quiet=True)
        verify_kit(forged_dir, anchored, expect_root=original_root)
        outcomes.append((
            "fully re-hashed forgery: rejected by --expect-root",
            anchored.failed == ["anchor.expectRoot"],
            f"failed checks: {anchored.failed[:4]}",
        ))

    all_ok = True
    for text, ok, detail in outcomes:
        all_ok = all_ok and ok
        print(f"{'MATCH    ' if ok else 'MISMATCH '} tamper-self-test: {text}" + ("" if ok else f" ({detail})"))
    return all_ok


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Verify the GALENOS offline verification kit (offline, standard library only).")
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--archive", type=Path, help=f"path to {ARCHIVE_NAME}; verified from one private snapshot")
    mode.add_argument("--kit-dir", type=Path, help="path to an extracted galenos-offline-kit directory (default: the directory of this script)")
    parser.add_argument("--checksum-file", type=Path, help=f"path to {CHECKSUM_NAME} (archive mode only; default: next to --archive when present)")
    parser.add_argument("--expect-archive-sha256", help="release archive SHA-256 obtained from a separate source (archive mode only)")
    parser.add_argument("--expect-root", help="portfolioRootSha256 obtained from a separate source (pins the receipt set only)")
    parser.add_argument("--tamper-self-test", action="store_true", help="mutate temporary copies of the kit and require each mutation to be rejected")
    args = parser.parse_args(argv)

    for label, value in (("--expect-root", args.expect_root), ("--expect-archive-sha256", args.expect_archive_sha256)):
        if value is not None and HEX64.fullmatch(value.lower()) is None:
            print(f"ERROR     {label} must be exactly 64 hexadecimal characters", file=sys.stderr)
            return 2

    script_dir = Path(__file__).resolve().parent
    archive = args.archive
    kit_dir = args.kit_dir
    if archive is None and kit_dir is None:
        if os.path.lexists(script_dir / SUMS_NAME):
            kit_dir = script_dir
        elif (script_dir / ARCHIVE_NAME).is_file():
            archive = script_dir / ARCHIVE_NAME
        else:
            print(
                f"ERROR     no kit found. Pass --archive {ARCHIVE_NAME} (recommended, with --expect-archive-sha256) "
                "or --kit-dir <directory>.",
                file=sys.stderr,
            )
            return 2

    if kit_dir is not None:
        # Fail closed: an archive pin that cannot be checked must never be silently dropped.
        archive_only = [
            flag
            for flag, value in (("--expect-archive-sha256", args.expect_archive_sha256), ("--checksum-file", args.checksum_file))
            if value is not None
        ]
        if archive_only:
            print(
                f"ERROR     {' and '.join(archive_only)} can only be checked in --archive mode. "
                f"Directory mode ({kit_dir}) has no archive digest to compare, so nothing was verified.",
                file=sys.stderr,
            )
            print("RESULT: MISMATCH (archive pin supplied in directory mode; nothing was verified)")
            return 2

    report = Report()
    try:
        if archive is not None:
            ok = verify_archive(
                archive, report, args.checksum_file, args.expect_archive_sha256, args.expect_root, self_test=args.tamper_self_test
            )
        else:
            verified: dict[str, bytes] = {}
            ok = verify_kit(kit_dir, report, args.expect_root, verified_blobs=verified)
            if ok and args.tamper_self_test:
                # The directory is not opened again: the self-test receives the bytes that were just verified.
                ok = tamper_self_test(verified)
    except (KitError, RecursionError) as exc:
        print(f"ERROR     {exc}", file=sys.stderr)
        print("RESULT: MISMATCH (kit unreadable)")
        return 1
    except OSError as exc:
        # Temporary-file creation, self-test writes and similar operating-system failures: report, never a traceback.
        print(f"ERROR     operating-system I/O failure: {exc.strerror or exc}", file=sys.stderr)
        print("RESULT: MISMATCH (I/O failure; verification did not complete)")
        return 1

    if ok:
        suffix = "; tamper self-test rejected every mutation" if args.tamper_self_test else ""
        print(trust_anchor_line(report.anchors))
        print(f"RESULT: MATCH ({report.total} checks{suffix})")
        return 0
    if report.failed:
        print(f"RESULT: MISMATCH ({len(report.failed)} of {report.total} checks failed)")
    else:
        print("RESULT: MISMATCH (tamper self-test: the pristine copy failed or a mutation was not rejected as required)")
    return 1


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