#!/usr/bin/env python3
"""Verify a Velerian evidence pack offline. Standard library only — no install.

Usage:  python verify_evidence.py evidence.json [prior_evidence.json] [--check FILE ...]
                                  [--signature]

Recomputes the hashes declared in the supplied pack on YOUR machine:

  bundle_hash = sha256(canonical_json(bundle))          # sort_keys, compact
  chain_hash  = sha256(bundle_hash + prev_pack_hash)    # ASCII hex concat

With a second file, also checks chain continuity: the prior pack's chain_hash
must equal this pack's prev_pack_hash.

A pack sealed since VPLAT-2810 also carries ``chain_seq`` inside its bundle
(so the bundle hash covers it): its number in the workspace's run chain, 1, 2,
3, ... in the order the runs were sealed. It is printed when present. With a
prior file that carries one too, the two numbers must be consecutive (FAIL
otherwise). Among the numbered packs you hold, a missing number is a pack you
do not hold. Packs sealed before numbering carry none and are unaffected.

With --check FILE (repeatable), also checks whether a file you hold is one the
pack fingerprints. The record keeps SHA-256 digests of the run's content, not
the content: the governed input (prompt_sha256), the output as the run recorded
it (output_sha256), and each document that grounded the run, as uploaded
(documents[].sha256) and as extracted text (documents[].extraction_sha256),
plus any policy document the run referenced. The file's bytes are hashed
exactly as they are, so save a text (the output, say) as UTF-8 with nothing
added, not even a final newline. Statuses:

  matches     the file's SHA-256 is one the pack records; the line names which.
  no_match    the pack records no such digest. (FAIL)

Files are checked only when the pack's declared hashes match. A file match
does not independently authenticate the pack or the file's origin.

If the bundle carries a ``descriptor_brief`` section (VPLAT-1471 — the
platform-resolved code-descriptor brief that shaped the run, embedded as a
sha256 digest plus the briefed code identifiers, code-set edition ids,
resolution date and brief-builder version), that section is validated too:
structurally always, and when the ``velerian`` package's code-set data is
importable (a repo checkout or installed wheel) the brief is RE-DERIVED and
its digest checked. Packs without the section are unaffected.

Re-derivation is VERSIONED (VPLAT-1578). The brief's format is platform code
and it changes; a pack sealed under an older brief builder does not re-derive
under today's, and that difference is a platform-version change, NOT evidence
of tampering. So the brief is re-derived under the builder version THE PACK
RECORDS, and when this script cannot build that version it says so instead of
reporting a mismatch it cannot substantiate:

  digest_verified              re-derived under the builder version the pack
                               records; the digest matches. (pass)
  digest_mismatch              re-derived under the builder version the pack
                               records; the digest does NOT match. (FAIL)
  builder_version_unavailable  the pack records a builder version this script
                               cannot build, so the brief was not re-derived.
                               Neither a pass nor a tamper finding.
  builder_version_unrecorded   the pack records no builder version (sealed
                               before VPLAT-1578), so which builder produced
                               the brief is unknown and re-derivation cannot be
                               conclusive either way.
  structure_invalid            the section is malformed. (FAIL)
  structure_ok                 well-formed, but the code-set builder is not
                               importable here, so nothing was re-derived.

Only the two FAIL states affect the exit code. The others report what could
not be re-derived here. Hash checks establish internal consistency. An
independently protected successor can detect a changed predecessor; supplying
the NEXT pack checks that link. Regenerating all supplied records and hashes
can preserve consistency, so a chain link alone does not authenticate history.

If the bundle carries a ``data_provenance`` section (DC-33 §5 — the case's
per-datum data-acquisition record: for each datum the pack's contract
declares, which source satisfied it, when), that section is validated
STRUCTURALLY: statuses and source kinds from their closed vocabularies,
entries ordered by requirement id, satisfied-by exactly on acquired rows and
a failure reason exactly on failed rows, ISO-8601 timestamps. There is no
deep re-derivation for this section — it records server-side ledger state.
The hash seal and audit-chain pointer do not independently prove its truth.
Statuses:

  structure_ok                 well-formed. (pass; not proof of its truth)
  structure_invalid            the section is malformed. (FAIL)

Packs without the section are unaffected — no output line, no verdict change.

If the bundle says how the run ended or what its recorded output is, those
facts are printed in plain words: run_status (the run's recorded status, sealed
when it did not succeed), result_withheld (the run's case was closed before it
finished, so its result was withheld), output_origin (the recorded output is a
platform message, or the model's answer as the platform changed it, rather than
the answer as the model wrote it) and model_output_sha256 (a digest of the
model's original answer, taken before the platform withheld or changed it).
They are part of the sealed bundle, so the hash checks cover them; printing
them changes no verdict. Packs without them print nothing more.

An outcome addendum (``record_type`` ``velerian.outcome_addendum``) is the
sealed record of a run's outcome verdict, written after the run is sealed. It
uses the same envelope, with ``prev_pack_hash`` set to the run record's
``chain_hash``, so pass the run's record as the second file to check the
link. The script prints what it records: the verdict, the run, when it was
scored, the judge model, the run seal it links to and any addendum it
supersedes. ``--check`` matches the output the judge read (output_sha256).

A sign-off record (``record_type`` ``velerian.signoff``) is the sealed record
of a person's sign-off on a journey step, written when the step closed
(ADR-076 Amendment 1). It uses the same envelope, with
``prev_pack_hash`` set to the chain hash of the run the step follows, so pass
that run's record as the second file to check the link. The script prints
the step, when it was signed off, the person's role and the step's required
tier, the basis (single or set), the card's digest and a set's size, and the
run seal it links to. It does not print who the person is: a user id means
something only inside the customer's workspace.

What a "verified" verdict means: the record and chain hashes recompute to
the values declared in this file. This checks internal consistency; it does
not authenticate the issuer, establish when the record was sealed, or prove
historical non-alteration if content and all self-declared hashes are
regenerated. Assessing historical changes requires a previously protected
digest or authenticated chain anchor obtained independently. This script
does not obtain or authenticate that anchor. It does not establish the truth
of recorded facts, the run's compliance, correctness or legality, or the
chain's completeness or uniqueness.

With --signature, also prints the record's ADR-076 signature verdict, checked
against the public keys this script trusts (TRUSTED_KEYS, the published dev,
staging and production keys): a production signature reads
``signed_production``, a dev or staging signature reads
``signed_non_production``, a record with no signature reads ``unsigned``
(which says nothing about when it was sealed), one whose hashes do not
recompute reads ``not_checked``, and one signed with a key not in the set
reads ``unknown_key``. The signature verdict does not change the exit code.

Exit codes: 0 verified (and linked, if a prior file was given, and every
            checked file matched); 1 verification failed, or a checked file
            matched nothing; 2 not verifiable (no integrity envelope).
"""
import base64
import datetime
import hashlib
import hmac
import json
import re
import sys

FIELDS = ("bundle", "bundle_hash", "prev_pack_hash", "chain_hash")
HEX64 = re.compile(r"^[0-9a-f]{64}$")


def verify(body):
    """Structured verdict for one file. Algorithm identical to Velerian's
    internal verifier (velerian.cli.admin.verify_chain_bytes); the only
    addition is the no_envelope refinement for pre-envelope (v1) bundles."""
    try:
        env = json.loads(body)
    except json.JSONDecodeError as exc:
        return {"verdict": "invalid_json", "detail": str(exc)}
    if not isinstance(env, dict) or all(f not in env for f in FIELDS):
        return {"verdict": "no_envelope"}
    missing = sorted(f for f in FIELDS if f not in env)
    if missing:
        return {"verdict": "missing_fields", "detail": ", ".join(missing)}
    canonical = json.dumps(env["bundle"], sort_keys=True, separators=(",", ":")).encode()
    actual_bundle = hashlib.sha256(canonical).hexdigest()
    if actual_bundle != env["bundle_hash"]:
        return {"verdict": "bundle_hash_mismatch",
                "detail": "stated %s / recomputed %s" % (env["bundle_hash"], actual_bundle)}
    actual_chain = hashlib.sha256((env["bundle_hash"] + env["prev_pack_hash"]).encode()).hexdigest()
    if actual_chain != env["chain_hash"]:
        return {"verdict": "chain_hash_mismatch",
                "detail": "stated %s / recomputed %s" % (env["chain_hash"], actual_chain)}
    result = {"verdict": "verified", "chain_hash": env["chain_hash"],
              "prev_pack_hash": env["prev_pack_hash"]}
    seq = chain_seq(env["bundle"])
    if seq is not None:
        result["chain_seq"] = seq
    return result


def chain_seq(bundle):
    """The bundle's run-chain number (VPLAT-2810), or None when it carries none."""
    value = bundle.get("chain_seq") if isinstance(bundle, dict) else None
    if isinstance(value, int) and not isinstance(value, bool) and value >= 1:
        return value
    return None


#: Section statuses that are a substantiated DEFECT (exit 1). Everything else
#: is either a pass or an honest "not proven here" — never both, never blurred.
DESCRIPTOR_FAILURES = ("structure_invalid", "digest_mismatch")

_NOT_TAMPER = ("This is not a tampering finding: the declared hashes were "
               "checked for internal consistency. Passing the NEXT pack in the chain "
               "checks its link; historical non-alteration still requires "
               "an independently protected digest or authenticated anchor.")


def check_descriptor_brief(body):
    """Validate the bundle's descriptor_brief section, when present.

    Returns None when the file carries no section (nothing to check), else a
    (status, detail) pair; see the module docstring for the status vocabulary.

    The deep check re-derives the exact brief text from the embedded code
    identifiers + resolution date against the published code-set editions,
    USING THE BUILDER VERSION THE SECTION RECORDS (VPLAT-1578). Three things
    are therefore needed before a digest comparison means anything: the
    velerian package importable, the recorded builder version implemented in
    it, and the named code-set editions in force. Each missing input gets its
    own honest status — none of them is reported as a mismatch, because a
    check that could not run has found nothing.
    """
    try:
        env = json.loads(body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        return None
    if not isinstance(env, dict):
        return None
    bundle = env["bundle"] if isinstance(env.get("bundle"), dict) else env
    section = bundle.get("descriptor_brief")
    if section is None:
        return None
    if not isinstance(section, dict):
        return ("structure_invalid", "descriptor_brief is not an object")
    digest = section.get("brief_sha256")
    codes = section.get("briefed_codes")
    editions = section.get("code_set_editions")
    as_of = section.get("as_of")
    if not (isinstance(digest, str) and HEX64.match(digest)):
        return ("structure_invalid", "brief_sha256 is not a sha256 hex digest")
    if not (isinstance(codes, list) and codes
            and all(isinstance(c, str) and c for c in codes)):
        return ("structure_invalid", "briefed_codes is not a non-empty list of codes")
    if not (isinstance(editions, list)
            and all(isinstance(e, str) and e for e in editions)):
        return ("structure_invalid", "code_set_editions is not a list of edition ids")
    try:
        parsed_as_of = datetime.date.fromisoformat(as_of)
    except (TypeError, ValueError):
        return ("structure_invalid", "as_of is not an ISO date (YYYY-MM-DD)")
    # An ABSENT key = sealed before VPLAT-1578. A PRESENT key must be a real
    # version — a null/negative/float/string stamp is a malformed section, not
    # a quiet fall-through to the unversioned path.
    stamped = "brief_builder_version" in section
    sealed_version = section.get("brief_builder_version")
    if stamped and not (isinstance(sealed_version, int)
                        and not isinstance(sealed_version, bool)
                        and sealed_version > 0):
        return ("structure_invalid",
                "brief_builder_version is present but is not a positive integer")
    try:
        from velerian.products.agenticx.code_sets.render import (
            DESCRIPTOR_BRIEF_BUILDER_VERSION,
            DESCRIPTOR_BRIEF_BUILDER_VERSIONS,
            build_descriptor_brief_at_version,
        )
    except ImportError:
        return ("structure_ok",
                "section is well-formed; the velerian code-set brief builder is "
                "not importable here (package absent, or older than brief-builder "
                "versioning), so the digest was not re-derived -- check out or "
                "install the velerian package to re-derive")
    buildable = ", ".join("v%d" % v for v in DESCRIPTOR_BRIEF_BUILDER_VERSIONS)

    if not stamped:
        # Pre-VPLAT-1578 pack. Which builder wrote this brief is not recorded,
        # so re-derivation cannot be conclusive: reporting what the CURRENT
        # builder produces is evidence, never a verdict.
        current = build_descriptor_brief_at_version(
            DESCRIPTOR_BRIEF_BUILDER_VERSION, codes, as_of=parsed_as_of)
        agrees = (current is not None
                  and hashlib.sha256(current.encode("utf-8")).hexdigest() == digest)
        if agrees:
            return ("builder_version_unrecorded",
                    "this pack was sealed before the brief-builder version was "
                    "recorded (VPLAT-1578), so which builder produced the brief "
                    "is unknown. This script's current builder (v%d) does "
                    "reproduce the sealed digest exactly, which is consistent "
                    "with an unaltered section -- but the pack does not name a "
                    "builder, so that is corroboration, not a re-derivation "
                    "under the sealed version." % DESCRIPTOR_BRIEF_BUILDER_VERSION)
        return ("builder_version_unrecorded",
                "this pack was sealed before the brief-builder version was "
                "recorded (VPLAT-1578), and this script's current builder (v%d) "
                "does not reproduce the sealed digest. An older brief builder "
                "and an altered section produce exactly the same result here, "
                "and this script cannot tell them apart -- so it claims "
                "neither. %s" % (DESCRIPTOR_BRIEF_BUILDER_VERSION, _NOT_TAMPER))

    text = build_descriptor_brief_at_version(sealed_version, codes, as_of=parsed_as_of)
    if text is None:
        return ("builder_version_unavailable",
                "this pack was sealed under brief builder v%d; this script can "
                "build %s, so the brief was NOT re-derived. A brief built by a "
                "superseded builder legitimately differs from today's, so no "
                "conclusion is drawn in either direction. %s"
                % (sealed_version, buildable or "no builder version", _NOT_TAMPER))
    actual = hashlib.sha256(text.encode("utf-8")).hexdigest()
    if actual != digest:
        return ("digest_mismatch",
                "re-derived under the pack's own brief builder v%d: stated %s / "
                "re-derived %s -- the section does not match the brief these "
                "codes + editions derive under the version this pack names "
                "(altered section, or different code-set data than the editions "
                "named)" % (sealed_version, digest, actual))
    return ("digest_verified",
            "re-derived under the pack's own brief builder v%d from the embedded "
            "code identifiers: the result matches the embedded digest exactly"
            % sealed_version)


# ─── VPLAT-1655: the data_provenance section check (DC-33 §5) ───────────────
#
# Structural contract mirrored verbatim from the internal ground truth
# (velerian.cli.admin.validate_data_provenance_section); the parity suite pins
# both — and the browser lib — to the same fixtures. Only structure_invalid
# affects the exit code; structure_ok is a pass whose proof is the hash seal.

PROVENANCE_FAILURES = ("structure_invalid",)

PROVENANCE_STATUSES = ("pending", "acquiring", "acquired", "failed")
PROVENANCE_SOURCE_KINDS = ("connector", "tenant_store", "upload", "manual")
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
ISO_TS_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")


def _nonempty_str(value):
    return isinstance(value, str) and bool(value)


def _check_provenance_version(version, where):
    """One satisfied_by.version block (VPLAT-1755). Detail string, or None.

    Mirrors velerian.cli.admin._validate_provenance_version verbatim. The
    block names WHICH VERSION of a tenant reference-data record satisfied the
    entity: tenant reference data stays deletable (the CTO ruling on
    VPLAT-1684), so a sealed pack names the version instead of dangling a
    pointer at a record that may since have been purged. The identity is
    required whole; effective_to must be PRESENT and may be null, because for
    a range "no end" is a value. payload_sha256 is checked for SHAPE only --
    the payload is deliberately not in the pack, so it cannot be re-derived
    here; the digest's proof is the hash seal above it.
    """
    if not isinstance(version, dict):
        return "%s is not an object" % where
    version_id = version.get("version_id")
    if not (isinstance(version_id, str) and UUID_RE.match(version_id)):
        return "%s.version_id is not a lowercase UUID string" % where
    version_no = version.get("version_no")
    if isinstance(version_no, bool) or not isinstance(version_no, int) or version_no < 1:
        return "%s.version_no is not a positive integer" % where
    effective_from = version.get("effective_from")
    if not (isinstance(effective_from, str) and ISO_DATE_RE.match(effective_from)):
        return "%s.effective_from is not an ISO-8601 date" % where
    if "effective_to" not in version:
        return "%s.effective_to is absent (null is the open-ended value)" % where
    effective_to = version["effective_to"]
    if effective_to is not None:
        if not (isinstance(effective_to, str) and ISO_DATE_RE.match(effective_to)):
            return "%s.effective_to is neither null nor an ISO-8601 date" % where
        if effective_to < effective_from:
            return "%s.effective_to precedes effective_from" % where
    digest = version.get("payload_sha256")
    if not (isinstance(digest, str) and SHA256_RE.match(digest)):
        return "%s.payload_sha256 is not a lowercase SHA-256 hex digest" % where
    return None


def check_data_provenance(body):
    """Validate the bundle's data_provenance section, when present.

    Returns None when the file carries no section (nothing to check), else a
    (status, detail) pair. The section is the case's per-datum acquisition
    record sealed inside the bundle: requirement id, status, the satisfying
    source (kind + reference + label), and the ledger timestamp. The check is
    structural only — the section records server-side ledger state. The
    hash seal and audit-chain pointer do not independently establish truth,
    both independent of this check.
    """
    try:
        env = json.loads(body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        return None
    if not isinstance(env, dict):
        return None
    bundle = env["bundle"] if isinstance(env.get("bundle"), dict) else env
    section = bundle.get("data_provenance")
    if section is None:
        return None
    if not isinstance(section, dict):
        return ("structure_invalid", "data_provenance is not an object")
    case_id = section.get("case_id")
    if not (isinstance(case_id, str) and UUID_RE.match(case_id)):
        return ("structure_invalid", "case_id is not a lowercase UUID string")
    requirements = section.get("requirements")
    if not isinstance(requirements, list):
        return ("structure_invalid", "requirements is not a list")
    prev_id = None
    for index, entry in enumerate(requirements):
        where = "requirements[%d]" % index
        if not isinstance(entry, dict):
            return ("structure_invalid", "%s is not an object" % where)
        req_id = entry.get("requirement_id")
        if not _nonempty_str(req_id):
            return ("structure_invalid",
                    "%s.requirement_id is not a non-empty string" % where)
        if prev_id is not None and not (prev_id < req_id):
            return ("structure_invalid",
                    "%s is not strictly ordered by requirement_id (%r after %r)"
                    % (where, req_id, prev_id))
        prev_id = req_id
        status = entry.get("status")
        if status not in PROVENANCE_STATUSES:
            return ("structure_invalid",
                    "%s.status is not one of %r" % (where, PROVENANCE_STATUSES))
        stamp = entry.get("status_changed_at")
        if not (isinstance(stamp, str) and ISO_TS_RE.match(stamp)):
            return ("structure_invalid",
                    "%s.status_changed_at is not an ISO-8601 timestamp" % where)
        satisfied = entry.get("satisfied_by")
        if (status == "acquired") != (satisfied is not None):
            return ("structure_invalid",
                    "%s: satisfied_by must be present exactly when status is acquired" % where)
        if satisfied is not None:
            if not isinstance(satisfied, dict):
                return ("structure_invalid", "%s.satisfied_by is not an object" % where)
            if satisfied.get("kind") not in PROVENANCE_SOURCE_KINDS:
                return ("structure_invalid",
                        "%s.satisfied_by.kind is not one of %r"
                        % (where, PROVENANCE_SOURCE_KINDS))
            for optional in ("reference", "label"):
                if optional in satisfied and not _nonempty_str(satisfied[optional]):
                    return ("structure_invalid",
                            "%s.satisfied_by.%s is present but not a non-empty string"
                            % (where, optional))
            if "version" in satisfied:
                problem = _check_provenance_version(
                    satisfied["version"], "%s.satisfied_by.version" % where)
                if problem is not None:
                    return ("structure_invalid", problem)
        reason = entry.get("failure_reason")
        reason_digest = entry.get("failure_reason_sha256")
        if (status == "failed") != (reason is not None or reason_digest is not None):
            return ("structure_invalid",
                    f"{where}: failure_reason or its digest must be present exactly when status is failed")
        if reason is not None and not _nonempty_str(reason):
            return ("structure_invalid", "%s.failure_reason is not a non-empty string" % where)
        if reason_digest is not None and not (
                isinstance(reason_digest, str) and SHA256_RE.fullmatch(reason_digest)):
            return ("structure_invalid",
                    f"{where}.failure_reason_sha256 is not a lowercase SHA-256 hex digest")
        for optional in ("entity_kind", "cardinality"):
            if optional in entry and not _nonempty_str(entry[optional]):
                return ("structure_invalid",
                        "%s.%s is present but not a non-empty string" % (where, optional))
    return ("structure_ok",
            "section is well-formed (%d requirement(s)); the hash seal and "
            "audit_chain_pointer do not independently establish its truth"
            % len(requirements))


# ─── How the run ended and what its output is (VPLAT-2811) ──────────────────

OUTPUT_ORIGINS = {
    "governance_block_message": "the platform's notice that governance withheld the "
                                "model's answer, not the answer itself",
    "input_block_message": "the platform's notice that a workspace input rule stopped "
                           "the run before the model was called",
    "approval_pending_message": "the platform's notice that the run is waiting for a "
                                "sign-off; the model was not called",
    "provider_refusal_message": "the platform's notice that the model provider declined "
                                "to finish the answer",
    "model_output_transformed": "the model's answer as the platform changed it (masked, "
                                "normalised, or with codes rendered)",
}


def run_outcome(body):
    """Output lines for what the bundle says about how the run ended and what its
    recorded output is. Empty when it says none of it, so older packs print
    exactly as before."""
    try:
        env = json.loads(body)
    except json.JSONDecodeError:
        return []
    if not isinstance(env, dict):
        return []
    bundle = env["bundle"] if isinstance(env.get("bundle"), dict) else env
    lines = []
    status = bundle.get("run_status")
    if isinstance(status, str):
        lines.append("run_status: %s" % status)
        lines.append("  meaning: the platform recorded this run as %s" % status)
    if bundle.get("result_withheld") is True:
        lines.append("result_withheld: yes")
        lines.append("  meaning: this step's result was withheld because its case was "
                     "closed before the run finished. The result was not added to the "
                     "case or returned to the caller")
    origin = bundle.get("output_origin")
    if isinstance(origin, str):
        lines.append("output_origin: %s" % origin)
        lines.append("  meaning: the recorded output (output_sha256) is %s"
                     % OUTPUT_ORIGINS.get(origin, "not the model's answer as the model wrote it"))
    model_digest = bundle.get("model_output_sha256")
    if isinstance(model_digest, str):
        lines.append("model_output_sha256: %s" % model_digest)
        if HEX64.match(model_digest):
            lines.append("  meaning: digest of the model's original answer, taken before "
                         "the platform withheld or changed it. The record keeps only this "
                         "digest, never the answer")
        else:
            lines.append("  this value is not a SHA-256 digest")
    return lines


# ─── Check a file against the pack's digests (ADR-072) ──────────────────────
#
# Mirrors velerian.core.governance.sealed_record.sealed_digest_targets
# verbatim; the parity suite pins both to the same fixtures.

TARGET_LABELS = {
    "input": "the run's governed input",
    "output": "the run's output",
    "document": "document %s, as uploaded",
    "document_text": "document %s, as extracted text",
    "policy_document": "policy document %s",
}


def digest_targets(bundle):
    """Every whole-payload digest the bundle records, as {kind, sha256[, attachment_id]}."""
    if not isinstance(bundle, dict):
        return []
    targets = []
    for kind, key in (("input", "prompt_sha256"), ("output", "output_sha256")):
        value = bundle.get(key)
        if isinstance(value, str) and HEX64.match(value):
            targets.append({"kind": kind, "sha256": value})
    documents = bundle.get("documents")
    if isinstance(documents, list):
        for entry in documents:
            if not isinstance(entry, dict) or not isinstance(entry.get("attachment_id"), str):
                continue
            for kind, key in (("document", "sha256"), ("document_text", "extraction_sha256")):
                value = entry.get(key)
                if isinstance(value, str) and HEX64.match(value):
                    targets.append({"kind": kind, "attachment_id": entry["attachment_id"],
                                    "sha256": value})
    sources = bundle.get("tenant_policy_sources")
    if isinstance(sources, list):
        for entry in sources:
            if (isinstance(entry, dict) and isinstance(entry.get("attachment_id"), str)
                    and isinstance(entry.get("sha256"), str) and HEX64.match(entry["sha256"])):
                targets.append({"kind": "policy_document",
                                "attachment_id": entry["attachment_id"],
                                "sha256": entry["sha256"]})
    return targets


OUTCOME_ADDENDUM = "velerian.outcome_addendum"
SIGNOFF = "velerian.signoff"


def describe_outcome_addendum(body):
    """The lines a holder sees for an outcome addendum, or None for any other record."""
    env = json.loads(body)
    bundle = env.get("bundle") if isinstance(env, dict) else None
    if not isinstance(bundle, dict) or bundle.get("record_type") != OUTCOME_ADDENDUM:
        return None

    def shown(key):
        value = bundle.get(key)
        return "none" if value is None else str(value)

    lines = [
        "outcome_addendum: verdict %s" % shown("verdict"),
        "  run %s, addendum %s, scored at %s (%s)"
        % (shown("run_id"), shown("sequence"), shown("scored_at"), shown("source")),
        "  judge model: %s; scorer: %s" % (shown("judge_model_id"), shown("scorer_version")),
        "  links to the run seal: %s" % shown("run_evidence_chain_hash"),
    ]
    supersedes = bundle.get("supersedes")
    if isinstance(supersedes, dict):
        lines.append("  supersedes addendum %s (sha256 %s)"
                     % (supersedes.get("sequence"), supersedes.get("content_sha256")))
    backfill = bundle.get("backfill")
    if isinstance(backfill, dict):
        lines.append("  written by an operator backfill (%s); prior verdict %s"
                     % (backfill.get("mode"), backfill.get("prior_verdict")))
    lines.append("  meaning: the sealed record of this run's outcome verdict. Pass the "
                 "run's record as the second file to check that it links to that seal.")
    return lines


def describe_signoff(body):
    """The lines a holder sees for a sign-off record, or None for any other record."""
    env = json.loads(body)
    bundle = env.get("bundle") if isinstance(env, dict) else None
    if not isinstance(bundle, dict) or bundle.get("record_type") != SIGNOFF:
        return None

    def shown(key, source=bundle):
        value = source.get(key) if isinstance(source, dict) else None
        return "none" if value is None else str(value)

    signer = bundle.get("signer")
    lines = [
        "signoff: step %s (step %s) signed off at %s"
        % (shown("stage_key"), shown("stage_index"), shown("signed_at")),
        "  by a person with the role %s; the step requires %s"
        % (shown("role", signer), shown("required_tier")),
        "  basis %s; card digest %s" % (shown("basis"), shown("card_digest")),
    ]
    if bundle.get("basis") == "set":
        lines.append("  one of a set of %s steps (set %s)" % (shown("set_size"), shown("set_id")))
    lines.append("  links to the run seal: %s" % shown("run_evidence_chain_hash"))
    lines.append("  meaning: the sealed record of a person's sign-off on this journey step. "
                 "It names the person only by their workspace user id, which the workspace "
                 "resolves, and carries no name or email. It does not say whether anything "
                 "was sent. Pass the record of the run the step follows as the second file to "
                 "check that it links to that seal.")
    return lines


def check_file(body, data):
    """(status, detail) for one held file's bytes against the pack in ``body``."""
    env = json.loads(body)
    bundle = env["bundle"] if isinstance(env.get("bundle"), dict) else env
    digest = hashlib.sha256(data).hexdigest()
    matches = [t for t in digest_targets(bundle) if t["sha256"] == digest]
    if not matches:
        return ("no_match", "sha256 %s is not a digest this pack records" % digest)
    names = []
    for target in matches:
        label = TARGET_LABELS[target["kind"]]
        names.append(label % target["attachment_id"] if "%s" in label else label)
    return ("matches", "sha256 %s is %s" % (digest, "; ".join(names)))


# --- ADR-076 signature check (--signature) ---------------------------------
#
# The same verdicts as velerian/core/evidence/seal_verifier.py and the browser
# verifier on /trust/verify (frontend/lib/evidence/signed-record.ts), over the
# same shared corpus (tests/fixtures/evidence_signing/signed_records.json).
# TRUSTED_KEYS is the key set this script trusts: the published set at
# /.well-known/velerian-evidence-signing-keys.json: the dev, staging and
# production keys. A dev or staging signature reads signed_non_production,
# never signed_production. A signature verdict is printed only with
# --signature and never changes the exit code.

#: The evidence-signing public keys this script trusts (ADR-076 step 6). Each
#: entry: kid, env (dev/staging/prod), modulus_hex, exponent, status.
TRUSTED_KEYS = (
    {
        "kid": "velerian-dev-2026-11",
        "env": "dev",
        "modulus_hex": (
            "e025fd661dc3b7b6a140c48db6bd27ce1517df87243b3e26e1f380ec8fcbb4aa"
            "7df79fe5cc87b92198eb3e1091c2f750d2023c03efa5100cf07218e3e85b08ec"
            "171b18559927cbd9a693a20713ffc7751b090214308394802cc35c61749004ec"
            "c4ac47af565107ec67051bcfa0dab2cdd2b83989f2e35baba7a0c0dbd761cd5a"
            "74fec8c40162a2d0a071496655438d29d47c25c277f8f0a6036a18b66107fc7b"
            "fc69a9ee0d3784e4e7d5a51a0fa80995ded9c787f53c41beadaa44a69708dbc5"
            "c79c37ed7dbabdc37f30fd8af202645efec56ad2ea3b3d5cb101ef2f67fc47e4"
            "538c3971ea091813a41fc5bef3b23b9a212087abf30b63ff5e5ef38fb6a9bf8b"
            "41312c5b1d63a701d9dafd3bc0ecb638785d35d134a680db62e9181c653cf19f"
            "4f0c921b326934251e726172064076129edd34652fbb78c947d8e92645173408"
            "37652d474e9b01a59b17922f91c6934dfba6eeed7b52ce9b1b23d9a1e003860d"
            "f52422dcd7ac5935a839e82af5c4dd7d01460121bb1b1fb5c5e22a04aca6e72b"
        ),
        "exponent": 65537,
        "status": "active",
    },
    {
        "kid": "velerian-staging-2026-11",
        "env": "staging",
        "modulus_hex": (
            "cc0b22fceb8b030a165763a74c63fc25f6dc9db54ee61f1697d37094b20529c2"
            "4cbf9d14f92b3cdc5ac256baa04cb65d0b61f7907fdc25c0474f52174a4bfacd"
            "d9bce574f0af6dcc793dffeebc8d32e873cc8a575c65e0b6b93f184ce9bef158"
            "f5381d76ea51cef5716090401b8d2386f3d97c7c3fd415a719ba431496904862"
            "53c672890cf68b3015c8767f2c0e594d208f6d26f79c5061e58f2b2507eb6150"
            "07569770d482183e12c07ee8cd11505babcec2e4c04a933a077ec888b3055f2b"
            "f5fa688bf23a97b542fd2ef836421b21938a2d5f272d3f633946b929b938edeb"
            "c0005bc4f7b405ce0ff06d76a33dfa50dbb61c2af75124b4f27f40ed3f3cc83d"
            "53d416dae2a3e6189caa34bd61836dbc066586c3eb5e3a07a48729d1e30af88f"
            "3929fa7ded79df96fb41d037008d4eeb9aa456b0c0747c12cdc9a3d4f93c838d"
            "f4d425dfccac3dcf94605fc3b9dc5e20c4dfe65da998eba1f5675a6a4145445b"
            "493ea4d25cc7f1d3f351178f828fc3187f50048e8c9e608ff105fa9ebf7e0835"
        ),
        "exponent": 65537,
        "status": "active",
    },
    {
        "kid": "velerian-prod-2026-11",
        "env": "prod",
        "modulus_hex": (
            "b2d9752de1144d48e2df7a2988358695020467600c10fe8451e51d34412f711a"
            "bbe7d1c47224861e95da444b10ced5a4e019103ac9d28f10dd0271c6953d7818"
            "f909751eb4fb4c8d4b8284c251860a8d382f90479365a29b582a5b4792cfa338"
            "eba513632c8752ef61e922874e5471a0309fbb77d27ab6581f591fcb5aeed6ff"
            "5af9c92d05e8864b19e7a06d3f787b21793993a8eb5c41bbf5cd5ddc6b153291"
            "ad5b279b9212468108e9943310a17450de8ab3ade547133ce2c770e5c8eb737e"
            "76e0de735cfbaec1ba54c1bdcce1f867f3903890d5bb1b050edcb7d2a0d20ac6"
            "16568b31d084d0e2b7bfc4203245af4f2da10776924e4bee8355b1218cbacb13"
            "368fcc6d29ec91ca416e0a4ecf2fb6bc2d6f73c216ae228fbd9db2d65d84877a"
            "786489a89a5282a21432d55e4da029a64f691e042cdf1200becf73d2a439d67a"
            "31629be95b76368fda7600231163cfdefdd15357a6027a568c1b28c63c13dfbe"
            "ac79b47d53261ebb94661ce33a1cdc0b6df3b3a33248c4a66411aae4d32ee531"
        ),
        "exponent": 65537,
        "status": "active",
    },
)

SIGNATURE_ALGORITHM = "RSASSA_PKCS1_V1_5_SHA_256"
STATEMENT_LIMIT = 2048
SIGNATURE_BLOCK_LIMIT = 4096
KEY_LIMIT = 64
RECORD_LIMIT = 16 * 1024 * 1024
SIGNING_ENVIRONMENTS = ("dev", "staging", "prod")
STATEMENT_FIELDS = frozenset(("v", "kid", "env", "kind", "pack_id", "tenant_id",
                              "bundle_hash", "prev_pack_hash", "chain_hash", "sealed_at"))
_KID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}", re.ASCII)
_SIG_UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
_SIG_HASH_RE = re.compile(r"[0-9a-f]{64}")
_SIG_TIME_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
                          r"(?:\.[0-9]{1,6})?(?:Z|\+00:00)")
_MODULUS_RE = re.compile(r"[0-9a-f]{768}")
_DIGEST_INFO = bytes.fromhex("3031300d060960864801650304020105000420")

SIGNATURE_VERDICTS = ("signed_production", "signed_non_production", "signature_mismatch",
                      "unknown_key", "revoked_key", "pending", "unsigned", "not_checked")


def _full(pattern, value):
    return isinstance(value, str) and pattern.fullmatch(value) is not None


def _sig_json(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()


def canonical_statement(statement):
    """The exact signing bytes of a closed v1 statement; ValueError otherwise."""
    if not isinstance(statement, dict) or set(statement) != STATEMENT_FIELDS:
        raise ValueError("statement_fields")
    if type(statement["v"]) is not int or statement["v"] != 1:
        raise ValueError("statement_version")
    if not _full(_KID_RE, statement["kid"]):
        raise ValueError("statement_kid")
    if statement["env"] not in SIGNING_ENVIRONMENTS:
        raise ValueError("statement_environment")
    if statement["kind"] not in ("evidence_pack", "outcome_addendum", "chain_checkpoint",
                                 "signoff"):
        raise ValueError("statement_kind")
    if any(not _full(_SIG_UUID_RE, statement[f]) for f in ("pack_id", "tenant_id")):
        raise ValueError("statement_identity")
    if any(not _full(_SIG_HASH_RE, statement[f]) for f in ("bundle_hash", "chain_hash")):
        raise ValueError("statement_hash")
    if statement["prev_pack_hash"] != "" and not _full(_SIG_HASH_RE, statement["prev_pack_hash"]):
        raise ValueError("statement_predecessor")
    timestamp = statement["sealed_at"]
    if not _full(_SIG_TIME_RE, timestamp):
        raise ValueError("statement_timestamp")
    datetime.datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
    encoded = _sig_json(statement)
    if len(encoded) > STATEMENT_LIMIT:
        raise ValueError("statement_size")
    return encoded


def _read_signature_block(encoded):
    if not isinstance(encoded, bytes) or len(encoded) > SIGNATURE_BLOCK_LIMIT:
        raise ValueError("signature_size")
    value = json.loads(encoded.decode("utf-8"))
    if not isinstance(value, dict) or set(value) != {"alg", "kid", "statement", "value"}:
        raise ValueError("signature_fields")
    if value["alg"] != SIGNATURE_ALGORITHM or not _full(_KID_RE, value["kid"]):
        raise ValueError("signature_algorithm_or_kid")
    statement_bytes = canonical_statement(value["statement"])
    if not isinstance(value["value"], str):
        raise ValueError("signature_base64")
    raw = base64.b64decode(value["value"], validate=True)
    if len(raw) != 384 or base64.b64encode(raw).decode("ascii") != value["value"]:
        raise ValueError("signature_base64")
    if _sig_json(value) != encoded:
        raise ValueError("noncanonical_signature")
    return value, statement_bytes, raw


def _key_registry(keys):
    if not isinstance(keys, (list, tuple)) or len(keys) > KEY_LIMIT:
        raise ValueError("key_registry")
    result = {}
    for key in keys:
        if not isinstance(key, dict) or set(key) != {"kid", "env", "modulus_hex",
                                                     "exponent", "status"}:
            raise ValueError("key_fields")
        if not _full(_KID_RE, key["kid"]) or key["kid"] in result:
            raise ValueError("key_kid")
        if key["env"] not in SIGNING_ENVIRONMENTS:
            raise ValueError("key_environment")
        if key["status"] not in ("active", "retired", "revoked"):
            raise ValueError("key_status")
        if type(key["exponent"]) is not int or key["exponent"] != 65537:
            raise ValueError("key_exponent")
        if not _full(_MODULUS_RE, key["modulus_hex"]):
            raise ValueError("key_modulus")
        modulus = int(key["modulus_hex"], 16)
        if modulus.bit_length() != 3072 or modulus % 2 != 1:
            raise ValueError("key_modulus")
        result[key["kid"]] = dict(key)
    return result


def verify_signature(signature, expected_statement, trusted_keys=(), expected_env=None):
    """{"status": valid|unsigned|invalid, "reason": ...} for one signature block.

    Strict RSA-3072 PKCS#1 v1.5 / SHA-256 over the exact expected statement,
    against keys the caller trusts, never keys read from the record.
    """
    try:
        expected = canonical_statement(expected_statement)
    except (ValueError, TypeError, RecursionError):
        return {"status": "invalid", "reason": "invalid_expected"}
    if expected_env not in SIGNING_ENVIRONMENTS or expected_statement["env"] != expected_env:
        return {"status": "invalid", "reason": "invalid_environment"}
    if signature is None:
        return {"status": "unsigned", "reason": "unsigned"}
    try:
        block, actual, raw = _read_signature_block(signature)
    except (ValueError, TypeError, UnicodeError, RecursionError):
        return {"status": "invalid", "reason": "invalid_signature_block"}
    if actual != expected or block["kid"] != expected_statement["kid"]:
        return {"status": "invalid", "reason": "statement_mismatch"}
    try:
        keys = _key_registry(trusted_keys)
    except (ValueError, TypeError):
        return {"status": "invalid", "reason": "invalid_key"}
    key = keys.get(block["kid"])
    if key is None:
        return {"status": "invalid", "reason": "unknown_key"}
    if key["env"] != expected_env:
        return {"status": "invalid", "reason": "invalid_key"}
    if key["status"] == "revoked":
        return {"status": "invalid", "reason": "revoked_key"}
    modulus = int(key["modulus_hex"], 16)
    representative = int.from_bytes(raw, "big")
    if representative >= modulus:
        return {"status": "invalid", "reason": "invalid_signature"}
    digest_info = _DIGEST_INFO + hashlib.sha256(expected).digest()
    expected_em = b"\x00\x01" + b"\xff" * (384 - len(digest_info) - 3) + b"\x00" + digest_info
    actual_em = pow(representative, 65537, modulus).to_bytes(384, "big")
    if not hmac.compare_digest(actual_em, expected_em):
        return {"status": "invalid", "reason": "invalid_signature"}
    return {"status": "valid", "reason": "valid"}


def _sig_result(verdict, reason, kid=None, env=None):
    return {"verdict": verdict, "reason": reason, "kid": kid, "env": env}


def _hashes_recompute(envelope):
    bundle_hash = envelope.get("bundle_hash")
    prev_pack_hash = envelope.get("prev_pack_hash")
    chain_hash = envelope.get("chain_hash")
    if not all(isinstance(v, str) for v in (bundle_hash, prev_pack_hash, chain_hash)):
        return False
    try:
        actual_bundle = hashlib.sha256(_sig_json(envelope["bundle"])).hexdigest()
        actual_chain = hashlib.sha256((bundle_hash + prev_pack_hash).encode("ascii")).hexdigest()
    except (ValueError, TypeError, UnicodeError, RecursionError):
        return False
    return (hmac.compare_digest(actual_bundle, bundle_hash)
            and hmac.compare_digest(actual_chain, chain_hash))


def expected_statement(envelope, kid, env):
    """The statement a genuine signature over ``envelope`` must carry."""
    record_type = envelope.get("record_type")
    kind = ("outcome_addendum" if record_type == OUTCOME_ADDENDUM
            else "signoff" if record_type == SIGNOFF
            else "evidence_pack")
    return {
        "v": 1, "kid": kid, "env": env, "kind": kind,
        "pack_id": envelope.get("id"), "tenant_id": envelope.get("tenant_id"),
        "bundle_hash": envelope.get("bundle_hash"),
        "prev_pack_hash": envelope.get("prev_pack_hash"),
        "chain_hash": envelope.get("chain_hash"),
        "sealed_at": envelope.get("rendered_at"),
    }


def check_record_signature(record, trusted_keys=TRUSTED_KEYS, signature_status=None):
    """The ADR-076 signature verdict for one record's exact bytes.

    The hashes must recompute first; the expected statement comes from the
    record's checked hashes and identities, and its environment from the
    trusted key set, never from the signature. ``signature_status`` is a
    platform caller's own outbox state; a file alone never yields ``pending``.
    """
    if not isinstance(record, bytes) or not record or len(record) > RECORD_LIMIT:
        return _sig_result("not_checked", "record_size")
    try:
        envelope = json.loads(record.decode("utf-8"))
    except (ValueError, UnicodeError, RecursionError):
        return _sig_result("not_checked", "invalid_json")
    if not isinstance(envelope, dict) or any(f not in envelope for f in FIELDS):
        return _sig_result("not_checked", "no_envelope")
    if not _hashes_recompute(envelope):
        return _sig_result("not_checked", "hash_mismatch")
    if "signature" not in envelope:
        if signature_status == "pending":
            return _sig_result("pending", "pending")
        return _sig_result("unsigned", "unsigned")
    signature = envelope["signature"]
    if not isinstance(signature, dict) or not isinstance(signature.get("kid"), str):
        return _sig_result("signature_mismatch", "invalid_signature_block")
    kid = signature["kid"]
    entry = None
    for key in trusted_keys:
        if isinstance(key, dict) and key.get("kid") == kid:
            entry = key
            break
    if entry is None:
        return _sig_result("unknown_key", "unknown_key", kid=kid)
    env = entry.get("env")
    if not isinstance(env, str):
        return _sig_result("signature_mismatch", "invalid_key", kid=kid)
    try:
        block = _sig_json(signature)
    except (ValueError, TypeError, RecursionError):
        return _sig_result("signature_mismatch", "invalid_signature_block", kid=kid)
    checked = verify_signature(block, expected_statement(envelope, kid, env), trusted_keys,
                               expected_env=env)
    if checked["status"] == "valid":
        verdict = "signed_production" if env == "prod" else "signed_non_production"
        return _sig_result(verdict, "valid", kid=kid, env=env)
    if checked["reason"] == "revoked_key":
        return _sig_result("revoked_key", "revoked_key", kid=kid, env=env)
    if checked["reason"] == "unknown_key":
        return _sig_result("unknown_key", "unknown_key", kid=kid)
    return _sig_result("signature_mismatch", checked["reason"], kid=kid, env=env)


#: The same words the /trust/verify signature row uses for each verdict.
SIGNATURE_EXPLAIN = {
    "signed_production": "signed by Velerian's production key, and unchanged since it was "
                         "signed. The signature does not prove when the record was "
                         "signed, or that its contents are true.",
    "signed_non_production": "signed by a non-production key. It is never accepted as "
                             "production evidence.",
    "signature_mismatch": "the signature does not match this record. The record was "
                          "changed after it was signed, or the signature is malformed.",
    "unknown_key": "signed with a key this script does not know, so the signature "
                   "could not be checked.",
    "revoked_key": "signed with a key Velerian has revoked. Its signatures are not to "
                   "be trusted.",
    "pending": "signature pending. This record is not yet signed.",
    "unsigned": "this file carries no signature.",
    "not_checked": "not checked -- the record's hashes must recompute before its "
                   "signature means anything.",
}


def parse_args(argv):
    """(positional files, files to check, --signature) — or None on wrong usage."""
    positional, checks, signature = [], [], False
    args = list(argv[1:])
    while args:
        arg = args.pop(0)
        if arg == "--signature":
            signature = True
        elif arg == "--check":
            if not args:
                return None
            checks.append(args.pop(0))
        else:
            positional.append(arg)
    if not 1 <= len(positional) <= 2:
        return None
    return positional, checks, signature


EXPLAIN = {
    "verified": "the record and chain hashes recompute to the values declared "
                "in this file. This checks internal consistency; it does not "
                "authenticate the issuer or prove historical non-alteration "
                "without a previously protected independent digest or chain anchor.",
    "invalid_json": "this file is not readable JSON, so nothing can be verified",
    "no_envelope": "this record predates the integrity envelope -- "
                   "it cannot be independently verified yet (not proof of tampering)",
    "missing_fields": "the integrity envelope is incomplete, so the seal cannot be recomputed",
    "bundle_hash_mismatch": "the recomputed record hash differs from the value "
                            "declared in this file. The record is internally "
                            "inconsistent; the verifier cannot determine when "
                            "or why it became inconsistent.",
    "chain_hash_mismatch": "the recomputed chain hash differs from the value "
                           "declared in this file. The verifier cannot determine "
                           "when or why it became inconsistent.",
}


def main(argv):
    parsed = parse_args(argv)
    if parsed is None:
        print(__doc__.strip())
        return 1
    positional, checks, signature = parsed
    body = open(positional[0], "rb").read()
    result = verify(body)
    print("verdict: %s" % result["verdict"])
    if "detail" in result:
        print("  %s" % result["detail"])
    print("  meaning: %s" % EXPLAIN[result["verdict"]])
    if signature:
        signature_check = check_record_signature(body)
        print("signature: %s" % signature_check["verdict"])
        print("  meaning: %s" % SIGNATURE_EXPLAIN[signature_check["verdict"]])
    if "chain_seq" in result:
        print("chain_seq: %d" % result["chain_seq"])
        print("  meaning: this pack is number %d in its workspace's run chain, "
              "numbered in the order runs were sealed" % result["chain_seq"])
    descriptor_failed = False
    provenance_failed = False
    if result["verdict"] in ("verified", "no_envelope"):
        brief_check = check_descriptor_brief(body)
        if brief_check is not None:
            status, detail = brief_check
            print("descriptor_brief: %s" % status)
            print("  %s" % detail)
            descriptor_failed = status in DESCRIPTOR_FAILURES
        provenance_check = check_data_provenance(body)
        if provenance_check is not None:
            status, detail = provenance_check
            print("data_provenance: %s" % status)
            print("  %s" % detail)
            provenance_failed = status in PROVENANCE_FAILURES
        for line in run_outcome(body):
            print(line)
    section_failed = descriptor_failed or provenance_failed
    if checks and (result["verdict"] != "verified" or section_failed):
        print("check: not_checked")
        print("  the pack's checks failed, so its fingerprints were not compared")
    if result["verdict"] == "no_envelope":
        return 1 if section_failed else 2
    if result["verdict"] != "verified" or section_failed:
        return 1
    for line in describe_outcome_addendum(body) or describe_signoff(body) or ():
        print(line)
    if len(positional) == 2:
        prior = verify(open(positional[1], "rb").read())
        if prior["verdict"] != "verified":
            print("continuity: prior_unverifiable (prior file: %s)" % prior["verdict"])
            print("  the prior file's checks failed, so its chain link was not compared")
            return 1
        if prior["chain_hash"] == result["prev_pack_hash"]:
            print("continuity: linked")
            print("  meaning: the prior pack's chain seal is exactly what this "
                  "pack points back to")
            if "chain_seq" in result and "chain_seq" in prior:
                if result["chain_seq"] == prior["chain_seq"] + 1:
                    print("sequence: consecutive (%d -> %d)"
                          % (prior["chain_seq"], result["chain_seq"]))
                else:
                    print("sequence: not_consecutive (%d -> %d)"
                          % (prior["chain_seq"], result["chain_seq"]))
                    print("  the two packs are linked but their numbers are not "
                          "consecutive, so the records are internally inconsistent")
                    return 1
        else:
            print("continuity: not_linked")
            print("  this pack does not point back to that prior pack's seal")
            return 1
    unmatched = False
    for path in checks:
        status, detail = check_file(body, open(path, "rb").read())
        print("check %s: %s" % (path, status))
        print("  %s" % detail)
        unmatched = unmatched or status == "no_match"
    return 1 if unmatched else 0


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