#!/usr/bin/env python3
"""TES public-projection integrity checker. Python 3.9+, stdlib only.

No exporter/server import, native receipt verification, key, network or writes.
All results concern the supplied unsigned bytes, never authenticated origin.
"""
import base64
import hashlib
import json
import math
import os
import re
import stat
import sys

MAX_WIRE = 4_000_000
MAX_PAYLOAD = 2_999_000
UNITS = "dimensionless cosine-similarity readings"
HEX = re.compile(r"[0-9a-f]{64}")
CARD = re.compile(r"[A-Za-z0-9_-]{16,64}")
TOOL_KEYS = {"receipt_hash", "previous_receipt_hash", "timestamp", "tool_name", "call", "turn", "arg_names", "execution",
             "policy_action", "policy_rule_id", "boundary_rule", "policy_note", "semantic"}
CONFLICT_NOTE = "Conflicting records; this call cannot be matched."
NOTES = {None, "Policy record unavailable.", "Tool reading unavailable.", "Tool outcome unavailable.", "Receipt unavailable.",
         CONFLICT_NOTE}
ARGS = {"read_file": {"path", "offset", "limit"}, "search_files": {"pattern", "target", "path", "file_glob", "limit", "offset", "output_mode", "context", "order"}, "[unlisted tool]": set()}
SEMANTIC = ("The system also measured how closely this tool call fits TES's stated purpose. This score is recorded only. It does not "
            "decide whether the call runs, and it has not yet been tested well enough to use as a decision on this page.")
DISPOSITION_TEXT = {"pending": "The page is still checking this answer.",
                    "screen_refused": "The page held back the reply: its answer check declined it.",
                    "screen_busy": "The page held back the reply: its answer check was busy.",
                    "unavailable": "The page could not read this turn's screen record."}
SCHEMA_V3 = "tes.page.session-bundle/3"
SCHEMA_V1, SCHEMA_V2 = "tes.page.session-bundle/1", "tes.page.session-bundle/2"
# v2 (AT-2). Mirrors of the page's closed tables (server.py _TOOL_SENTENCE, _TOOL_SENTENCE_OTHER, _APPLIER_RULE_IDS; session_bundle
# RECORD_PENDING). Wording: Vale 11-10. A test asserts the mirrors equal the page's tables.
RECORD_PENDING = "record unavailable"
_UNAVAILABLE = ("unreadable", "verification_failed", "no_verdict", "record_unwritable", "internal_error")
APPLIER_ONLY_RULES = frozenset({"semantic_mode:boundaries_clear"} | {"policy_unavailable:" + r for r in _UNAVAILABLE})
TOOL_SENTENCE = {
    ("proceed", "semantic_mode:boundaries_clear"): "The deployer’s policy allowed this call; its execution status is recorded separately.",
    ("decline", "B3_path_allowlist"): "The deployer’s policy declined this request because it asked for a file outside the allowed source paths.",
    (None, None): "The policy result is unavailable here.",          # fix-r1 M1 (ALPHA, DRAFT wording)
    # Vale FROZEN 2026-11-11 (P-a): an unavailable policy check is not a completed policy decision.
    **{("decline", "policy_unavailable:" + r): "The policy check was unavailable; the runtime recorded a decline for this call."
       for r in _UNAVAILABLE}}
TOOL_SENTENCE_OTHER = "See the recorded policy result above, if available."
# Exit 3 names what is incomplete in plain words. Fixed phrases and counts only; nothing from the payload is echoed.
# Gap phrases, singular and plural. Exact wording ruled by Vale (bus RETURN gap-phrases-remaining__ALPHA, 2026-11-11): each
# says what is unavailable in the supplied projection and never why, or whether it existed elsewhere.
_GAP_WORDS = (("record", "{n} turn's record is unavailable in the supplied projection", "{n} turns' records are unavailable in the supplied projection"),
              ("question", "{n} turn's question reading is unavailable in the supplied projection",
               "{n} turns' question readings are unavailable in the supplied projection"),
              ("answer_reading", "{n} turn's answer reading is unavailable in the supplied projection",
               "{n} turns' answer readings are unavailable in the supplied projection"),
              ("no_answer", "{n} turn's answer is unavailable in the supplied projection", "{n} turns' answers are unavailable in the supplied projection"),
              ("held", "{n} answer is not marked allowed in the supplied projection", "{n} answers are not marked allowed in the supplied projection"),
              ("Policy record unavailable.", "{n} tool call's policy record is unavailable in the supplied projection",
               "{n} tool calls' policy records are unavailable in the supplied projection"),
              ("Receipt unavailable.", "{n} tool call's receipt is unavailable in the supplied projection",
               "{n} tool calls' receipts are unavailable in the supplied projection"),
              ("Tool outcome unavailable.", "{n} tool call's outcome is unavailable in the supplied projection",
               "{n} tool calls' outcomes are unavailable in the supplied projection"),
              ("Tool reading unavailable.", "{n} tool call's tool reading is unavailable in the supplied projection",
               "{n} tool calls' tool readings are unavailable in the supplied projection"),
              ("Conflicting records; this call cannot be matched.", "{n} tool call has conflicting records in the supplied projection",
               "{n} tool calls have conflicting records in the supplied projection"))
COVERAGE_COMPLETE = "COVERAGE DECLARED_COMPLETE; SUPPLIED PUBLIC PROJECTION ONLY; COMPLETE EVENT CAPTURE NOT ESTABLISHED"
COVERAGE_INCOMPLETE = "COVERAGE INCOMPLETE; SUPPLIED PUBLIC PROJECTION HAS GAPS: "
GAPS_UNAVAILABLE = "gap details unavailable"
# Wrapper /2 is the attested download, which verify_session_record.py checks. Given one, this checker names that tool and
# parses and validates nothing after the first line (the file is still read, up to the size cap). Wording: Vale ruling 2026-11-12 06:35 (CT-1); it names the header seen, not an attestation.
ATTESTED_HEADER = b"TES-SESSION-BUNDLE/2"
ATTESTED_NOT_CHECKED = "HEADER TES-SESSION-BUNDLE/2: CONTENT NOT CHECKED BY THIS TOOL; USE verify_session_record.py"
ATTESTED_ORIGIN = "ORIGIN NOT CHECKED BY THIS TOOL"   # this branch reads no origin evidence, so it concludes nothing about it


def need(ok):
    if not ok:
        raise ValueError("SCHEMA")


def keys(obj, wanted):
    need(type(obj) is dict and set(obj) == set(wanted))


def hex64(value):
    return type(value) is str and HEX.fullmatch(value) is not None


def integer(value, minimum=0):
    return type(value) is int and minimum <= value <= 10**12


def text(value, maximum=4000):
    return type(value) is str and len(value) <= maximum


def values(obj):
    keys(obj, {"purpose", "scope"})
    need(all(type(v) in (int, float) and -1 <= v <= 1 and round(v, 6) == v for v in obj.values()))


def reading(obj, kind, anchor):
    need(type(obj) is dict)
    if obj.get("availability") == "unavailable":
        keys(obj, {"availability", "card_id"} if kind == "question" else {"availability"})
    else:
        common = {"availability", "pa_hash", "calibration", "units", "precision"}
        extra = {"card_id", "question_commitment", "row_hash", "request_fidelity"} if kind == "question" else {"answer_fidelity", "applied"}
        keys(obj, common | extra)
        need(obj["availability"] == "available" and hex64(obj["pa_hash"]) and obj["pa_hash"] == anchor)
        need(obj["calibration"] == "UNCALIBRATED" and obj["units"] == UNITS and type(obj["precision"]) is int and obj["precision"] == 6)
        if kind == "question":
            need(hex64(obj["question_commitment"]) and hex64(obj["row_hash"]))
            values(obj["request_fidelity"])
        else:
            need(obj["applied"] is False)
            values(obj["answer_fidelity"])
    if kind == "question":
        need(type(obj["card_id"]) is str and CARD.fullmatch(obj["card_id"]) is not None)


def step(obj):
    need(type(obj) is dict and hex64(obj.get("row")) and text(obj.get("text")))
    kind = obj.get("kind")
    if kind == "question":
        keys(obj, {"kind", "commitment", "row", "text", "detail"}); need(hex64(obj["commitment"]) and text(obj["detail"]))
    elif kind == "reading":
        keys(obj, {"kind", "passages", "row", "text"}); need(type(obj["passages"]) is list)
        for p in obj["passages"]:
            keys(p, {"file", "a", "b"}); need(text(p["file"], 600) and integer(p["a"], 1) and integer(p["b"], p["a"]))
    elif kind == "answer":
        keys(obj, {"kind", "citations", "withheld", "text", "row"})
        need(obj["withheld"] in (None, "raw_tool_syntax", "leaked_reasoning", "self_attestation", "other") and type(obj["citations"]) is list)
        for c in obj["citations"]:
            keys(c, {"file", "a", "b", "read", "retrieved", "quote"})
            need(text(c["file"], 600) and (c["a"] is None or integer(c["a"], 1)) and (c["b"] is None or integer(c["b"], 1)))
            need(type(c["read"]) is bool and type(c["retrieved"]) is bool and (c["quote"] is None or type(c["quote"]) is bool))
    elif kind == "claims":
        keys(obj, {"kind", "result", "text", "row"}); need(obj["result"] in ("pass", "no_claims", "error", "withheld"))
    else:
        need(False)


def snapshot(obj, q, v2=False):
    keys(obj, {"id", "revision", "n", "turn", "session", "t", "trial", "steps", "tools"})
    need(hex64(obj["id"]) and hex64(obj["revision"]) and integer(obj["n"], 1))
    need(all(type(obj[k]) is str and re.fullmatch(r"[A-Za-z0-9_:-]{0,8}", obj[k]) is not None for k in ("turn", "session")))
    need(obj["t"] is None or type(obj["t"]) in (int, float) and 1000 <= obj["t"] < 10**10)
    need(obj["trial"] is None or text(obj["trial"], 200))
    need(q["availability"] == "available" and obj["id"] == q["row_hash"])
    need(type(obj["steps"]) is list and obj["steps"])
    order = {"question": 0, "reading": 1, "answer": 2, "claims": 3}
    previous = -1
    for s in obj["steps"]:
        step(s); rank = order[s["kind"]]; need(rank > previous); previous = rank
    need(obj["steps"][0]["kind"] == "question" and obj["steps"][0]["row"] == obj["id"] and obj["steps"][0]["commitment"] == q["question_commitment"])
    need(type(obj["tools"]) is list and len(obj["tools"]) <= 32)
    for i, r in enumerate(obj["tools"], 1):
        keys(r, TOOL_KEYS | {"policy_sentence"} if v2 else TOOL_KEYS)
        need((r["receipt_hash"] is None or hex64(r["receipt_hash"])) and (r["previous_receipt_hash"] in (None, "") or hex64(r["previous_receipt_hash"])))
        need(r["timestamp"] is None or type(r["timestamp"]) is str and re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,6})?\+00:00", r["timestamp"]) is not None)
        need(type(r["tool_name"]) is str and r["tool_name"] in ARGS and type(r["arg_names"]) is list)
        need(all(type(a) is str and (a == "[unlisted argument]" or a in ARGS[r["tool_name"]]) for a in r["arg_names"]))
        need(type(r["call"]) is int and r["call"] == i and type(r["turn"]) is int and r["turn"] == obj["n"])
        need(r["execution"] in ("ran", "did not run", "unknown") and r["policy_action"] in (None, "proceed", "decline", "block"))
        rule = r["policy_rule_id"]
        # Conflicting records choose nothing: no outcome, no decision, no rule (P-25; both schemas).
        need(r["policy_note"] != CONFLICT_NOTE
             or r["execution"] == "unknown" and r["policy_action"] is None and rule is None and r["boundary_rule"] is None)
        if v2:
            # An applier rule that is not one of the anchor's boundaries is published without rule text.
            need((rule is None or rule in APPLIER_ONLY_RULES) and r["boundary_rule"] is None
                 or text(rule, 128) and rule not in APPLIER_ONLY_RULES and text(r["boundary_rule"]))
            need(r["policy_sentence"] == TOOL_SENTENCE.get((r["policy_action"], rule), TOOL_SENTENCE_OTHER))
        else:
            need((rule is None and r["boundary_rule"] is None) or text(rule, 128) and text(r["boundary_rule"]))
        need(r["policy_note"] in NOTES and r["semantic"] == SEMANTIC)


# /3 is additive: only direct entries use this closed evidence representation.
OUTCOME_KEYS = {"row", "quote_map", "rendered_sha256", "source_set_sha256", "screen_note"}
OUTCOME_ROW_KEYS = set("schema_version kind turn_id session_id n_in_session source_set_sha256 n_sources_given band score floor cited n_sources_cited system_sha256 answer_sha256 rendered_sha256 status withheld_rule regenerated model history_commitment sentence_map quote_gap quote_map checks n_attempts question_reading prev_hash row_hash".split())
QUESTION_ROW_KEYS = set("schema_version record_type timestamp turn_id session_id question_commitment embedder_id pa_hash pa_status pa_external_ratification_verified pa_payload_signed_field calibration surface status error request_fidelity retrieval_forced retrieval_mode retrieval_index_sha256 fact_menu_manifest_sha256 retrieved_passages priority_rules producer previous_row_hash row_hash".split())
DIRECT_RULES = {"bad_disposition", "foreign_source", "quote_not_in_source", "uncited_sentence", "truncated", "empty"}
SCREEN_CODES = {"G-secrets", "G-lexicon", "G-paths", "G-heldip", "GATE_UNAVAILABLE", "INVALID_OUTPUT", "OUTPUT_LIMIT", "EVIDENCE_BINDING", "FAMILY_MISSING", "GATE_ERROR"}


def digest_object(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")).hexdigest()


def quote_evidence(note, row, answer):
    """Check the recorded placement and bytes against the outcome's citation hashes.

    The pinned source documents themselves are outside this offline file.
    """
    entries = note["quote_exemptions"]
    need(note["status"] == "allowed" and type(entries) is list and 0 < len(entries) <= 2 * len(row["cited"]))
    quote_prefix = "From the reviewed sources:\n\n"
    prefix = ""
    if answer is not None and row.get("rendering", "quotes.v1") == "lead.v1":
        lead_end = row["lead_spans"][-1][1]
        prefix = answer[:lead_end] + "\n\n"
        need(answer.startswith(prefix + quote_prefix))
    first_quote = len((prefix + quote_prefix).encode())
    seen = set()
    for e in entries:
        keys(e, {"citation", "family", "answer_start", "answer_end", "leading", "trailing"})
        i, family = e["citation"], e["family"]
        need(integer(i) and i < len(row["cited"]) and family in ("claims", "enforcement") and (i, family) not in seen)
        seen.add((i, family))
        start, end = e["answer_start"], e["answer_end"]
        need(integer(start) and integer(end, start + 1))
        need(all(type(e[k]) is str and not e[k].strip() for k in ("leading", "trailing")))
        if answer is None:
            continue  # The projection expired. No quotation can be displayed.
        data = answer.encode()
        need(first_quote <= start < end <= len(data))
        quote = data[start:end].decode("utf-8")
        c = row["cited"][i]
        source_slice = e["leading"] + quote + e["trailing"]
        need(quote == quote.strip() and c["end"] - c["start"] == len(source_slice))
        need(hashlib.sha256(source_slice.encode()).hexdigest() == c["quote_sha256"])
        before, after = data[:start].decode(), data[end:].decode()
        if i == 0:
            need(before == prefix + quote_prefix)
        else:
            need(before.endswith(" [" + row["cited"][i-1]["sid"] + "]\n\n"))
        heading = after.split("\n", 2)
        need(len(heading) >= 2 and heading[0] == "" and heading[1].endswith(" [" + c["sid"] + "]"))


class BundleVerification(int):
    """Completeness with optional lead verification depth."""
    def __new__(cls, complete, depth):
        result = int.__new__(cls, bool(complete))
        result.verification_depth = depth
        return result


def direct_outcome(outcome, q, anchor, view=None):
    """Internal consistency only; no source bytes, chain completeness or producer authentication."""
    depth = "structure_only"
    keys(outcome, OUTCOME_KEYS)  # RX-R8: the one outer outcome key-set guard
    r = outcome["row"]
    need(type(r) is dict)
    mode = r.get("rendering", "quotes.v1")
    need(type(mode) is str and mode in ("quotes.v1", "lead.v1"))
    keys(r, OUTCOME_ROW_KEYS | ({"rendering"} if "rendering" in r else set())
         | ({"lead_sentence_sha256", "lead_spans"} if mode == "lead.v1" else set()))
    need(r["schema_version"] == "telos.tes.cited_turn.v1" and r["kind"] == "outcome")
    need(r["row_hash"] == digest_object({k: v for k, v in r.items() if k != "row_hash"}))
    need(all(hex64(r[k]) for k in ("row_hash", "source_set_sha256", "system_sha256", "answer_sha256", "rendered_sha256")))
    need(r["prev_hash"] is None or hex64(r["prev_hash"]))
    need(r["history_commitment"] is None or hex64(r["history_commitment"]))
    need(all(text(r[k], 128) and r[k] for k in ("turn_id", "session_id")))
    need(r["model"] is None or text(r["model"], 128))
    need(integer(r["n_in_session"], 1) and integer(r["n_attempts"]) and integer(r["n_sources_given"]))
    need(r["band"] in ("in_scope", "out_of_scope", "not_gated"))
    need(all(type(r[k]) in (int, float) and -1 <= r[k] <= 1 for k in ("score", "floor")))
    need(r["status"] in ("answered", "abstained", "withheld", "out_of_scope", "too_long", "turn_cap", "provider_failed", "reading_unavailable"))
    need(r["withheld_rule"] is None or r["withheld_rule"] in DIRECT_RULES | ({"lead_render_invalid","bad_lead_count"} if mode == "lead.v1" else set()) | {"reading_unavailable", "quote_offset_unavailable"})
    need(type(r["regenerated"]) is bool and type(r["quote_gap"]) is bool)
    keys(r["checks"], DIRECT_RULES | ({"bad_lead_count","lead_render_invalid"} if mode == "lead.v1" else set()))
    need(all(v in ("pass", "fail", "not_evaluated", "advisory_fail") for v in r["checks"].values()))
    need(type(r["cited"]) is list and len(r["cited"]) <= 10000)
    for c in r["cited"]:
        keys(c, {"sid", "text_sha256", "quote_sha256", "start", "end"})
        need(text(c["sid"], 128) and c["sid"] and hex64(c["text_sha256"]) and hex64(c["quote_sha256"]))
        need(integer(c["start"]) and integer(c["end"], c["start"] + 1))
    need(type(r["n_sources_cited"]) is int and r["n_sources_cited"] == len({c["sid"] for c in r["cited"]}))
    need(r["status"] != "answered" or bool(r["cited"]))
    expected = [{"index": i, "sid": c["sid"], "cited_text_sha256": c["quote_sha256"]} for i, c in enumerate(r["cited"])]
    need(type(r["quote_map"]) is list and r["quote_map"] == expected)
    for m in r["quote_map"]:
        keys(m, {"index", "sid", "cited_text_sha256"}); need(type(m["index"]) is int)
    need(digest_object(outcome["quote_map"]) == digest_object(r["quote_map"]))  # RX-R3b
    need(outcome["source_set_sha256"] == r["source_set_sha256"])  # RX-R3c
    need(outcome["rendered_sha256"] == r["rendered_sha256"])
    need(type(r["sentence_map"]) is list and all(type(xs) is list and all(type(i) is int and 0 <= i < len(r["cited"]) for i in xs) for xs in r["sentence_map"]))
    depth = "structure_only"
    if mode == "lead.v1":
        depth = lead_commitments(r)
    qr = r["question_reading"]
    need(type(qr) is dict)
    keys(qr, QUESTION_ROW_KEYS | ({"not_measured_reason"} if "not_measured_reason" in qr else set()))
    need(qr["schema_version"] == "telos.tes.request_observation.v1" and qr["record_type"] == "request_observation" and qr["producer"] == "page_direct_call")
    need(qr["pa_hash"] == anchor and qr["session_id"] == r["turn_id"] == qr["turn_id"])
    need(qr["row_hash"] == digest_object({k: v for k, v in qr.items() if k != "row_hash"}))
    need(hex64(qr["row_hash"]) and (qr["question_commitment"] is None or hex64(qr["question_commitment"])))
    need(qr["status"] in ("measured", "not_measured", "error") and qr["error"] in (None, "measure_error"))
    need(qr.get("not_measured_reason") in (None, "secret_cue", "other"))
    need(qr["request_fidelity"] is None or type(qr["request_fidelity"]) is dict)
    if qr["request_fidelity"] is not None: values(qr["request_fidelity"])
    need(qr["pa_status"] == "RATIFICATION_UNVERIFIED" and qr["pa_external_ratification_verified"] is False and qr["pa_payload_signed_field"] is False)
    need(qr["calibration"] == "UNCALIBRATED" and qr["surface"] == "vale_public_demo_surface")
    need(type(qr["timestamp"]) in (int, float) and 1000 <= qr["timestamp"] < 10**10)
    need(qr["embedder_id"] is None or type(qr["embedder_id"]) is str and re.fullmatch(r"sentence-transformers/all-MiniLM-L6-v2@sha256:[0-9a-f]{64}", qr["embedder_id"]))
    need(qr["retrieval_forced"] is False and qr["retrieval_mode"] == "none" and qr["retrieval_index_sha256"] is None and qr["fact_menu_manifest_sha256"] is None and qr["retrieved_passages"] == [] and qr["priority_rules"] is None and qr["previous_row_hash"] == "")
    if q["availability"] == "available":
        need(q["row_hash"] == qr["row_hash"] and q["question_commitment"] == qr["question_commitment"] and q["request_fidelity"] == qr["request_fidelity"])
    note = outcome["screen_note"]
    if note is not None:
        extended = note.get("schema") == "telos.tes.page_screen.v2"
        keys(note, {"schema", "session_id", "pa_hash", "pointer_row_hash", "rendered_answer_sha256", "status", "reasons", "producer"}
             | ({"quote_exemptions"} if extended else set()))
        need((extended or note["schema"] == "telos.tes.page_screen.v1") and note["producer"] == "page_direct_call")
        if extended:
            answer = next((step["text"] for step in (view or {}).get("steps", []) if step["kind"] == "answer"), None)
            quote_evidence(note, r, answer)
        need(note["session_id"] == r["turn_id"] and note["pa_hash"] == anchor and note["pointer_row_hash"] == r["row_hash"] and note["rendered_answer_sha256"] == r["rendered_sha256"])
        need(note["status"] in ("allowed", "screen_refused", "screen_busy") and type(note["reasons"]) is list and all(type(v) is str and v in SCREEN_CODES for v in note["reasons"]))
        need(bool(note["reasons"]) == (note["status"] == "screen_refused"))
    answered = False
    if view is not None:
        keys(view, {"id", "revision", "n", "turn", "session", "t", "trial", "steps", "tools"})
        need(view["id"] == qr["row_hash"] and hex64(view["revision"]) and integer(view["n"], 1))
        need(all(type(view[k]) is str and re.fullmatch(r"[A-Za-z0-9_:-]{0,8}", view[k]) is not None for k in ("turn", "session")))
        need(view["t"] == qr["timestamp"] and (view["trial"] is None or text(view["trial"], 200)))
        need(view["tools"] == [] and type(view["steps"]) is list and 1 <= len(view["steps"]) <= 2)
        first = view["steps"][0]
        keys(first, {"kind", "commitment", "row", "text", "detail"})
        need(first["kind"] == "question" and first["row"] == qr["row_hash"] and first["commitment"] == qr["question_commitment"] and text(first["text"]) and text(first["detail"]))
        for st in view["steps"]:
            need(st["kind"] in ("question", "answer"))
            if st["kind"] == "answer":
                step(st)
                need(st["row"] == r["row_hash"])  # RX-R3d: independent served turn commitment
                need(hashlib.sha256(st["text"].encode("utf-8")).hexdigest() == r["rendered_sha256"])  # RX-R3a
                if mode == "lead.v1":
                    depth = lead_commitments(r, st["text"])
                    if r["status"] == "answered":
                        lead_quote_block(r, st["text"])
                need(note is not None and note["status"] == "allowed" and st["citations"] == [] and st["withheld"] is None)
                answered = True
    return BundleVerification(answered and q["availability"] == "available" and note is not None and note["status"] == "allowed",depth)


def lead_commitments(row, answer=None):
    """Structure-only absent answer bytes; exact hashes/spans/join when supplied.

    Kept standalone with this offline checker; no exporter/runtime import.
    """
    hashes, spans, mapping = (row[k] for k in ('lead_sentence_sha256','lead_spans','sentence_map'))
    need(all(type(x) is list for x in (hashes,spans,mapping)))
    if row['status'] != 'answered':
        need(hashes == spans == mapping == [])
        return "structure_only"
    need(1 <= len(hashes) <= 5 and len(spans) == len(mapping) == len(hashes))
    need(all(hex64(h) for h in hashes))
    need(row['answer_sha256'] == row['rendered_sha256'])
    end = -1
    for span, refs in zip(spans,mapping):
        need(type(span) is list and len(span) == 2 and all(type(x) is int for x in span))
        need(span[0] == end+1 and span[1] > span[0]);end=span[1]
        need(type(refs) is list and bool(refs) and all(type(x) is int and 0 <= x < len(row['quote_map']) for x in refs))
        need(len(set(refs)) == len(refs))
    if len(hashes) == 1 and row.get('quote_gap') is not True:
        need(any(type(row['quote_map'][i]) is dict and row['quote_map'][i].get('cited_text_sha256') == hashes[0]
                 for i in mapping[0]))
    if answer is not None:
        need(type(answer) is str and len(answer) > end)
        sentences=[answer[start:end] for start,end in spans]
        need(all(s and s == s.strip() for s in sentences) and ' '.join(sentences) == answer[:end])
        # Same frozen segmentation as the publication layer; conservative on abbreviations.
        boundary=re.compile(r'''[.!?]+["')\]]*(?=\s)|\n\s*\n''')
        need(all(not boundary.search(s) for s in sentences))
        need([hashlib.sha256(s.encode('utf-8')).hexdigest() for s in sentences] == hashes)
        need(hashlib.sha256(answer.encode('utf-8')).hexdigest() == row['rendered_sha256'])

    return "structure_only" if answer is None else "text_bound"

# /4 retains legacy validators but derives membership from a separate journal prefix.
SCHEMA_V4 = 'tes.page.session-bundle/4'
SESSION_LINES = {
    'complete': 'Session projection coverage: complete through the export cutoff',
    'incomplete': 'Session projection coverage: incomplete; required session records are missing.',
    'unavailable': 'Session projection coverage: unavailable.'}
TERMINAL_STATES = {'served', 'screen_refused', 'screen_busy', 'screen_record_unavailable', 'error'}


def lead_quote_block(row, answer):
    """Check that every recorded citation has a visible passage and section trail."""
    start = row["lead_spans"][-1][1]
    prefix = "\n\nFrom the reviewed sources:\n\n"
    need(answer.startswith(prefix, start))
    start += len(prefix)
    for i, citation in enumerate(row["cited"]):
        marker = " [" + citation["sid"] + "]"
        trail = re.compile(r"\n[^\n]+" + re.escape(marker) + r"(?=\n\n|$)")
        match = trail.search(answer, start)
        need(match is not None)
        quote = answer[start:match.start()]
        need(bool(quote) and quote == quote.strip())
        original_length = citation["end"] - citation["start"]
        need(len(quote) <= original_length)
        if len(quote) == original_length:
            need(hashlib.sha256(quote.encode()).hexdigest() == citation["quote_sha256"])
        start = match.end()
        if i < len(row["cited"]) - 1:
            need(answer.startswith("\n\n", start))
            start += 2
    need(bool(answer[start + 2:].strip()) and answer.startswith("\n\n", start)
         if row["quote_gap"] else start == len(answer))


def session_manifest(manifest):
    keys(manifest, {'session_id', 'events', 'digest'})
    sid = manifest['session_id']
    need(type(sid) is str and re.fullmatch('[0-9a-f]{32}', sid) is not None)
    need(manifest['digest'] == digest_object({k: v for k, v in manifest.items() if k != 'digest'}))
    events = manifest['events']
    need(type(events) is list and events and len(events) <= 20000)
    members, previous, generation, capped = {}, None, None, False
    for i, row in enumerate(events, 1):
        keys(row, {'schema', 'generation', 'session_id', 'seq', 'event', 'previous_event_sha256', 'event_sha256', 'data'})
        need(row['schema'] == 'tes.page.session-index/1' and row['session_id'] == sid)
        need(type(row['seq']) is int and row['seq'] == i and row['previous_event_sha256'] == previous)
        need(row['event_sha256'] == digest_object({k: v for k, v in row.items() if k != 'event_sha256'}))
        need(text(row['generation'], 64) and row['generation'])
        generation = row['generation'] if i == 1 else generation
        need(row['generation'] == generation)
        event, d = row['event'], row['data']
        need(type(d) is dict)
        if i == 1:
            need(event == 'START' and d == {'provenance': 'first_admitted_owned_ask'})
        elif event == 'RESERVE':
            keys(d, {'id', 'path', 'pa_hash', 'config_sha256'})
            need(not capped and type(d['id']) is str and re.fullmatch('[0-9a-f]{32}', d['id']) is not None)
            need(d['id'] not in members and len(members) < 2000 and d['path'] in ('direct', 'native'))
            need(hex64(d['pa_hash']) and hex64(d['config_sha256']))
            members[d['id']] = {**d, 'terminal': None, 'references': []}
        elif event == 'TERMINAL':
            keys(d, {'id', 'terminal', 'references'})
            need(not capped and d['id'] in members and members[d['id']]['terminal'] is None)
            need(d['terminal'] in TERMINAL_STATES and type(d['references']) is list)
            seen = set()
            for ref in d['references']:
                keys(ref, {'kind', 'sha256'})
                need(ref['kind'] in ('reading', 'outcome', 'pointer', 'screen', 'tool_policy', 'projection', 'attempt') and hex64(ref['sha256']))
                pair = (ref['kind'], ref['sha256'])
                need(pair not in seen); seen.add(pair)
            members[d['id']].update(terminal=d['terminal'], references=d['references'])
        elif event == 'CAP':
            need(not capped and d == {'reason': 'journal_cap'})
            capped = True
        elif event == 'CUTOFF':
            keys(d, {'streams'})
            need(type(d['streams']) is dict and (capped or all(m['terminal'] is not None for m in members.values())))
            for name, stream in d['streams'].items():
                need(name in ('request_observations.jsonl', 'pointer_observations.jsonl', 'policy_actions.jsonl', 'tool_calls.jsonl', 'cited_turns.jsonl', 'screen_notes', 'projection'))
                keys(stream, {'size', 'sha256'})
                need(integer(stream['size']) and hex64(stream['sha256']))
        else:
            need(False)
        previous = row['event_sha256']
    need(events[-1]['event'] == 'CUTOFF' or capped and events[-1]['event'] == 'CAP')
    return members, capped


def session_result(obj, *, declaration=True):
    keys(obj, {'schema', 'scope', 'anchor', 'total', 'page_window_complete', 'turns', 'tool_reading', 'session_manifest', 'coverage', 'origin'})
    need(obj['schema'] == SCHEMA_V4 and obj['scope'] == 'retained served projections')
    need(obj['origin'] == 'unauthenticated' and obj['tool_reading'] == 'reading not recorded')
    need(obj['anchor'] is None or hex64(obj['anchor']))
    need(obj['total'] is None or integer(obj['total']))
    need(obj['page_window_complete'] is None or type(obj['page_window_complete']) is bool)
    need(type(obj['turns']) is list and len(obj['turns']) <= 500)
    manifest = obj['session_manifest']
    if manifest is not None and type(manifest) is dict and type(manifest.get('events')) is list and manifest['events']:
        last = manifest['events'][-1]
        if type(last) is dict and last.get('event') == 'CUTOFF':
            streams = last.get('data', {}).get('streams', {})
            for name, value in [('projection', obj['turns']), ('screen_notes', {
                    t['screen_note']['pointer_row_hash']: t['screen_note'] for t in obj['turns']
                    if type(t) is dict and t.get('screen_note') is not None})]:
                raw = json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode()
                need(streams.get(name) == {'size': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()})
    members, capped = ({}, False) if manifest is None else session_manifest(manifest)
    gaps_found = []
    def gap(reason, member=None, kind=None):
        detail = {'reason': reason}
        if member is not None: detail['turn'] = member
        if kind is not None: detail['kind'] = kind
        if detail not in gaps_found: gaps_found.append(detail)
    if manifest is None: gap('index_unavailable')
    if capped: gap('journal_cap')
    supplied, cards = {}, set()
    for t in obj['turns']:
        keys(t, {'member_id', 'question_reading', 'answer_reading', 'snapshot', 'disposition', 'record', 'attempts', 'outcome', 'pointer', 'screen_note'})
        mid = t['member_id']
        need(type(mid) is str and re.fullmatch('[0-9a-f]{32}', mid) is not None and mid not in supplied)
        need(manifest is None or mid in members)
        member = members.get(mid)
        anchor = member['pa_hash'] if member is not None else obj['anchor']
        q, a, s = t['question_reading'], t['answer_reading'], t['snapshot']
        reading(q, 'question', anchor); reading(a, 'answer', anchor)
        need(q['card_id'] not in cards); cards.add(q['card_id'])
        need(t['record'] in (None, RECORD_PENDING) and type(t['attempts']) is list)
        supplied[mid] = t
        if t['disposition'] is not None:
            keys(t['disposition'], {'status'}); need(t['disposition']['status'] == 'allowed')
        path, terminal = (member['path'], member['terminal']) if member is not None else ('direct' if t['outcome'] is not None else 'native', None)
        note, outcome, pointer = t['screen_note'], t['outcome'], t['pointer']
        actual = set()
        if q['availability'] == 'available': actual.add(('reading', q['row_hash']))
        if path == 'direct':
            need(pointer is None and a == {'availability': 'unavailable'})
            if outcome is not None:
                direct_outcome(outcome, q, anchor, s)
                need(note == outcome['screen_note'])
                row = outcome['row']
                if member is not None: need(row['system_sha256'] == member['config_sha256'])
                actual.add(('outcome', row['row_hash']))
                need(len(t['attempts']) <= row['n_attempts'])
                previous = None
                for index, attempt in enumerate(t['attempts']):
                    keys(attempt, {'schema_version', 'kind', 'turn_id', 'session_id', 'n_in_session', 'attempt_index', 'source_set_sha256', 'model', 'system_sha256', 'history_commitment', 'candidate_sha256', 'rule', 'stop_reason', 'checks', 'prev_hash', 'row_hash'})
                    need(attempt['kind'] == 'attempt' and attempt['schema_version'] == 'telos.tes.cited_turn.v1')
                    need(attempt['row_hash'] == digest_object({k: v for k, v in attempt.items() if k != 'row_hash'}))
                    need(all(attempt[k] == row[k] for k in ('turn_id', 'session_id', 'n_in_session', 'source_set_sha256', 'system_sha256', 'model')))
                    need(type(attempt['attempt_index']) is int and attempt['attempt_index'] == index)
                    need(index == 0 or attempt['prev_hash'] == previous)
                    previous = attempt['row_hash']; actual.add(('attempt', previous))
                if t['attempts']: need(row['prev_hash'] == previous)
                if len(t['attempts']) != row['n_attempts']: gap('record_missing', mid, 'outcome')
            else:
                need(s is None and not t['attempts'])
        else:
            need(outcome is None and not t['attempts'])
            if s is not None:
                snapshot(s, q, True)
                need(obj['total'] is not None and s['n'] <= obj['total'])
                for tool in s['tools']:
                    if tool['policy_note'] is None: actual.add(('tool_policy', digest_object(tool)))
                    else: gap('record_missing', mid, 'tool_policy')
            if pointer is not None:
                keys(pointer, {'row_hash', 'rendered_answer_sha256'})
                need(hex64(pointer['row_hash']) and hex64(pointer['rendered_answer_sha256']))
                actual.add(('pointer', pointer['row_hash']))
        has_answer = s is not None and any(step['kind'] == 'answer' for step in s['steps'])
        if has_answer:
            rendered = next(step for step in s['steps'] if step['kind'] == 'answer')
            actual.add(('projection', hashlib.sha256(rendered['text'].encode()).hexdigest()))
        if note is not None:
            extended = outcome is not None and note['schema'] == 'telos.tes.page_screen.v2'
            keys(note, {'schema', 'session_id', 'pa_hash', 'pointer_row_hash', 'rendered_answer_sha256', 'status', 'reasons'}
                 | ({'producer'} if path == 'direct' else set()) | ({'quote_exemptions'} if extended else set()))
            need((extended or note['schema'] == 'telos.tes.page_screen.v1') and note['pa_hash'] == anchor and text(note['session_id'], 128))
            need(hex64(note['pointer_row_hash']) and hex64(note['rendered_answer_sha256']))
            need(note['status'] in ('allowed', 'screen_refused', 'screen_busy') and type(note['reasons']) is list)
            need(all(type(code) is str and code in SCREEN_CODES for code in note['reasons']))
            need(bool(note['reasons']) == (note['status'] == 'screen_refused'))
            if member is not None and terminal != 'error':
                need(note['status'] == {'served': 'allowed', 'screen_refused': 'screen_refused', 'screen_busy': 'screen_busy'}.get(terminal))
            if pointer is not None:
                need(note['pointer_row_hash'] == pointer['row_hash'] and note['rendered_answer_sha256'] == pointer['rendered_answer_sha256'])
            if has_answer:
                answer = next(step for step in s['steps'] if step['kind'] == 'answer')
                need(note['status'] == 'allowed' and answer['row'] == note['pointer_row_hash'])
                if path == 'direct':
                    need(hashlib.sha256(answer['text'].encode()).hexdigest() == note['rendered_answer_sha256'])
                # Native snapshot text describes the answer; the pointer/note
                # bind its original rendering, and projection refs bind the summary.
            actual.add(('screen', digest_object(note)))
        if member is None: continue
        need(terminal == 'served' or not has_answer)
        need(t['disposition'] is None or terminal == 'served')
        if terminal == 'served':
            if s is None or not has_answer: gap('projection_expired', mid)
            if path == 'native' and a['availability'] != 'available': gap('record_missing', mid, 'reading')
        if q['availability'] != 'available': gap('record_missing', mid, 'reading')
        if terminal != 'error' and note is None: gap('record_missing', mid, 'screen')
        if terminal != 'error' and (outcome if path == 'direct' else pointer) is None:
            gap('record_missing', mid, 'outcome' if path == 'direct' else 'pointer')
        if member['pa_hash'] != obj['anchor']: gap('prior_pa_evidence', mid)
        expected_refs = {(ref['kind'], ref['sha256']) for ref in member['references']}
        need(all(pair in expected_refs for pair in actual))
        for ref in member['references']:
            pair = (ref['kind'], ref['sha256'])
            if pair not in actual:
                kind = ref['kind']
                if kind == 'projection': gap('projection_expired', mid)
                elif kind == 'attempt': gap('record_missing', mid, 'outcome')
                else:
                    # A different supplied immutable record is invalid; an absent record is a gap.
                    need(not any(k == kind for k, h in actual) or kind == 'tool_policy' and any(x.get('kind') == 'tool_policy' for x in gaps_found))
                    gap('record_missing', mid, kind)
    if manifest is not None:
        need(list(supplied) == [mid for mid in members if mid in supplied])
    for mid, member in members.items():
        if member['pa_hash'] != obj['anchor']: gap('prior_pa_evidence', mid)
        if member['terminal'] is None: gap('pending_at_cutoff', mid)
        if mid not in supplied:
            gap('record_missing', mid, 'reading')
            if member['terminal'] == 'served': gap('projection_expired', mid)
            if member['terminal'] in ('served', 'screen_refused', 'screen_busy', 'screen_record_unavailable'): gap('record_missing', mid, 'screen')
    status = 'unavailable' if any(g['reason'] in ('index_unavailable', 'journal_cap') for g in gaps_found) else 'incomplete' if gaps_found else 'complete'
    if declaration: need(obj['coverage'] == status)
    return status, gaps_found


def validate_payload(obj):
    if type(obj) is dict and obj.get("schema") == SCHEMA_V4:
        complete = session_result(obj)[0] == "complete"
        lead_turns = [t for t in obj["turns"]
                      if (t.get("outcome") or {}).get("row", {}).get("rendering") == "lead.v1"]
        bound = lead_turns and all(t["outcome"]["row"]["status"] == "answered"
                                  and any(st["kind"] == "answer" for st in (t["snapshot"] or {}).get("steps", []))
                                  for t in lead_turns)
        return BundleVerification(complete, "text_bound" if bound else "structure_only")
    keys(obj, {"schema", "scope", "anchor", "total", "window_complete", "turns", "tool_reading", "coverage", "origin"})
    need(obj["schema"] in (SCHEMA_V1, SCHEMA_V2, SCHEMA_V3) and obj["scope"] == "retained served projections")
    v2 = obj["schema"] in (SCHEMA_V2, SCHEMA_V3)
    need(obj["origin"] == "unauthenticated" and obj["tool_reading"] == "reading not recorded")
    need(obj["anchor"] is None or hex64(obj["anchor"]))
    need(obj["total"] is None or integer(obj["total"]))
    need(obj["window_complete"] is None or type(obj["window_complete"]) is bool)
    need(type(obj["turns"]) is list and 1 <= len(obj["turns"]) <= 500)
    complete = obj["window_complete"] is True
    cards, ids = set(), set()
    depths = []
    for t in obj["turns"]:
        keys(t, {"question_reading", "answer_reading", "snapshot", "disposition"} | ({"record"} if v2 else set()) | ({"outcome"} if obj["schema"] == SCHEMA_V3 and "outcome" in t else set()))
        q, a, s = t["question_reading"], t["answer_reading"], t["snapshot"]
        reading(q, "question", obj["anchor"]); reading(a, "answer", obj["anchor"])
        need(q["card_id"] not in cards); cards.add(q["card_id"])
        if obj["schema"] == SCHEMA_V3 and "outcome" in t:
            ready = direct_outcome(t["outcome"], q, obj["anchor"], s)
            depths.append(ready.verification_depth)
            need(t["record"] is None)
            if s is not None:
                need(s["id"] not in ids); ids.add(s["id"])
                need(obj["total"] is not None and s["n"] <= obj["total"])
            has_direct_answer = s is not None and any(st["kind"] == "answer" for st in s["steps"])
            expected_note = {"status": "allowed"} if has_direct_answer else None
            need(t["disposition"] == expected_note)
            complete = complete and ready and s is not None
            continue
        if s is not None:
            snapshot(s, q, v2); need(s["id"] not in ids); ids.add(s["id"])
            need(obj["total"] is not None and s["n"] <= obj["total"])
        if v2:
            need(t["record"] == (None if s is not None else RECORD_PENDING))   # a missing record is stated, never silent
        note = t["disposition"]
        has_answer = s is not None and any(step["kind"] == "answer" for step in s["steps"])
        if note is None:
            need(not has_answer)
        else:
            need(type(note) is dict and s is not None)
            if note.get("status") == "allowed":
                keys(note, {"status"}); need(has_answer)
            else:
                keys(note, {"status", "text"})
                need(type(note["status"]) is str and note["status"] in DISPOSITION_TEXT
                     and note["text"] == DISPOSITION_TEXT[note["status"]])
                need(not has_answer and a == {"availability": "unavailable"})
        complete = complete and q["availability"] == "available" and a["availability"] == "available" and s is not None and note == {"status": "allowed"} and all(r["policy_note"] is None for r in s["tools"])
    need(obj["schema"] != SCHEMA_V3 or any("outcome" in t for t in obj["turns"]))
    need(obj["coverage"] == ("declared_complete" if complete else "incomplete"))
    return BundleVerification(complete,"text_bound" if depths and all(x == "text_bound" for x in depths) else "structure_only")


def gaps(obj):
    """Plain words for an already validated payload whose coverage is incomplete."""
    count = dict.fromkeys((g[0] for g in _GAP_WORDS), 0)
    for t in obj["turns"]:
        s, note = t["snapshot"], t["disposition"]
        count["record"] += s is None
        count["question"] += t["question_reading"]["availability"] != "available"
        count["answer_reading"] += t["answer_reading"]["availability"] != "available"
        count["no_answer"] += s is not None and note is None
        count["held"] += note is not None and note["status"] != "allowed"
        for r in s["tools"] if s is not None else ():
            if r["policy_note"] is not None:
                count[r["policy_note"]] += 1
    words = [] if obj["window_complete"] is True else [
        "the served record window was marked incomplete" if obj["window_complete"] is False
        else "the served record window was not stated"]
    words += [(one if count[k] == 1 else many).format(n=count[k]) for k, one, many in _GAP_WORDS if count[k]]
    return "; ".join(words)


def _pairs(pairs):
    out = {}
    for k, v in pairs:
        if k in out: raise ValueError("duplicate")
        out[k] = v
    return out


def quote_attribution(sid):
    page, section = sid.split("#", 1)
    return f"Quoted from the TELOS site: {page}, {section or 'Introduction'}."


def quote_lines(obj):
    lines = []
    for turn in obj["turns"]:
        outcome = turn.get("outcome") or {}
        note = outcome.get("screen_note") or {}
        entries = note.get("quote_exemptions", [])
        if not entries or turn["snapshot"] is None:
            continue
        answer = next((s["text"] for s in turn["snapshot"]["steps"] if s["kind"] == "answer"), None)
        if answer is None:
            continue
        data = answer.encode()
        for i in sorted({e["citation"] for e in entries}):
            e = next(e for e in entries if e["citation"] == i)
            quote = data[e["answer_start"]:e["answer_end"]].decode()
            lines.extend([quote_attribution(outcome["row"]["cited"][i]["sid"]), json.dumps(quote, ensure_ascii=True)])
    return ["Quote evidence checked for internal integrity only.", *lines] if lines else []


def verify_bytes(wire):
    origin = "ORIGIN UNAUTHENTICATED"
    if type(wire) is bytes and wire.split(b"\n", 1)[0] == ATTESTED_HEADER:   # the first line, exactly; nothing after it is parsed
        return 2, [ATTESTED_NOT_CHECKED, ATTESTED_ORIGIN]                             # exit 2: not checked here, so never 0 and never INVALID
    if type(wire) is not bytes or len(wire) > MAX_WIRE:
        return 2, ["TES SESSION BUNDLE UNAVAILABLE: TOO_LARGE", origin]
    try:
        lines = wire.split(b"\n")
        if len(lines) != 4 or lines[0] != b"TES-SESSION-BUNDLE/1" or lines[-1] != b"" or not re.fullmatch(b"sha256:[0-9a-f]{64}", lines[1]):
            raise ValueError("FORMAT")
        raw = base64.b64decode(lines[2], validate=True)
        if len(raw) > MAX_PAYLOAD:
            return 2, ["TES SESSION BUNDLE UNAVAILABLE: TOO_LARGE", origin]
        if base64.b64encode(raw) != lines[2]: raise ValueError("FORMAT")
        if hashlib.sha256(raw).hexdigest().encode() != lines[1][7:]:
            return 1, ["TES SESSION BUNDLE INVALID: HASH_MISMATCH", origin]
        obj = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=_pairs,
                         parse_constant=lambda value: (_ for _ in ()).throw(ValueError("constant")))
        complete = validate_payload(obj)
        coverage = (SESSION_LINES[obj["coverage"]] if obj["schema"] == SCHEMA_V4 else
                    COVERAGE_COMPLETE if complete else COVERAGE_INCOMPLETE + (gaps(obj) or GAPS_UNAVAILABLE))
        details = (["GAPS " + json.dumps(session_result(obj)[1], sort_keys=True)] if obj["schema"] == SCHEMA_V4 else [])
        if obj['schema'] == SCHEMA_V4 and obj['session_manifest'] is not None:
            details += ['MEMBER ' + m['id'] + ' ' + str(m['terminal']) for m in session_manifest(obj['session_manifest'])[0].values()]
        lines = ["TES SESSION BUNDLE INTERNALLY CONSISTENT", coverage, origin, *details, *quote_lines(obj),
                 "SCOPE PUBLIC_PROJECTION_ONLY; NATIVE_RECEIPTS_NOT_VALIDATED"]
        if any((turn.get("outcome") or {}).get("row", {}).get("rendering") == "lead.v1" for turn in obj["turns"]):
            lines.append("VERIFICATION_DEPTH " + complete.verification_depth)
        return (0 if complete else 3), lines
    except Exception:
        return 1, ["TES SESSION BUNDLE INVALID: FORMAT_OR_SCHEMA", origin]


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


def main(argv=None, read=None, out=None):
    argv = sys.argv[1:] if argv is None else argv
    out = sys.stdout if out is None else out
    if len(argv) != 1:
        rc, lines = 2, ["TES SESSION BUNDLE UNAVAILABLE: USAGE", "ORIGIN UNAUTHENTICATED"]
    else:
        try: rc, lines = verify_bytes((read or read_file)(argv[0]))
        except Exception: rc, lines = 2, ["TES SESSION BUNDLE UNAVAILABLE: IO", "ORIGIN UNAUTHENTICATED"]
    out.write("\n".join(lines) + "\n")
    return rc


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