# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-signed-execution-trace-it-can-cryptographically-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-signed-execution-trace-it-can-cryptographically-verify.warrant.json
# Markdown SHA-256:   c6722ecede589dc1ffc4b5d611809bcab333ca7d08cde63c024cf1f1749b7af1
# Code AST SHA-256:   b32a197355ea2cdba6f68de2c256a63a87de504faec84be03896bc6df8344749
# Verified Classes:   TraceAdmissionError, Quote, Trace
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TraceAdmissionError(RuntimeError):
    """Raised when a signed trace cannot be bound to the attested measurement."""


@dataclass(frozen=True)
class Quote:
    measurement: str
    nonce: str
    extra_data: str  # H(M_worker || K_trace_pubkey || session_id)


@dataclass(frozen=True)
class Trace:
    session_id: str
    trace_key_pub: str
    boot_measurement: str
    executed_args_hashes: dict  # event_id -> hash computed by policy VM
    claimed_args_hashes: dict   # event_id -> hash logged by sidecar emitter
    signature_valid: bool


def _h(*parts: str) -> str:
    return hashlib.sha256("||".join(parts).encode()).hexdigest()


def admit_trace(
    quote: Quote,
    trace: Trace,
    expected_nonce: str,
    pinned_measurement: str,
) -> str:
    if not trace.signature_valid:
        raise TraceAdmissionError("trace signature invalid: REJECT")

    if quote.nonce != expected_nonce:
        raise TraceAdmissionError(
            f"stale nonce {quote.nonce!r} != {expected_nonce!r}: QUARANTINE"
        )

    if quote.measurement != pinned_measurement:
        raise TraceAdmissionError(
            f"measurement {quote.measurement!r} not pinned: REJECT"
        )

    expected_binding = _h(
        quote.measurement, trace.trace_key_pub, trace.session_id
    )
    if quote.extra_data != expected_binding:
        # The quote is valid, the trace is valid, but they are not bound.
        # This is the sidecar seam: do NOT fall through to ADMIT.
        raise TraceAdmissionError(
            "quote extraData does not bind trace key to measurement: QUARANTINE"
        )

    if trace.boot_measurement != quote.measurement:
        raise TraceAdmissionError(
            "trace boot measurement diverges from quote: QUARANTINE"
        )

    for event_id, executed in trace.executed_args_hashes.items():
        claimed = trace.claimed_args_hashes.get(event_id)
        if claimed is None:
            raise TraceAdmissionError(
                f"event {event_id} missing executed-args hash: QUARANTINE"
            )
        if claimed != executed:
            raise TraceAdmissionError(
                f"event {event_id} emitter/executed divergence: REJECT"
            )

    return "ADMIT"
