# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-provenance-check-itself-is-retrieved-from-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-provenance-check-itself-is-retrieved-from-memory.warrant.json
# Markdown SHA-256:   ce7bce6aec637cca0ce89233daf2d905a64f547b4209eabeced1d584294b9109
# Code AST SHA-256:   4805bdfee64211413017c84161e6919b2910a9e107e3478ba403c265941a3bd9
# Verified Classes:   ProvenanceGateError, Warrant, Candidate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceGateError(RuntimeError):
    """Raised when a write's provenance cannot be verified against a trust root
    that is independent of the mutable store being written to."""


@dataclass(frozen=True)
class Warrant:
    source: str
    content_hash: str          # binds to a specific fact, not a label
    tier: int
    signature: bytes           # verified against an out-of-band key, not a bool


@dataclass(frozen=True)
class Candidate:
    source: str
    payload: str
    required_tier: int
    claims_warrant: bool = False


def content_hash(payload: str) -> str:
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def admit_write(
    candidate: Candidate,
    resolve_warrant,           # callable: source -> Warrant | None
    trust_root,                # immutable, session-scoped signed manifest
    verify_signature,          # callable: (Warrant, key) -> bool
) -> None:
    # Invariant 0: a write that installs trust metadata must never be
    # adjudicated by the gate it would modify.
    if candidate.claims_warrant:
        raise ProvenanceGateError(
            f"candidate from {candidate.source!r} attempts to install warrant "
            f"metadata; route to external approver, not the write gate"
        )

    w = resolve_warrant(candidate.source)
    if w is None:
        raise ProvenanceGateError(
            f"no warrant for source {candidate.source!r}; refusing write"
        )

    # Invariant 1: the warrant must be reachable from the immutable root, not
    # merely present in the mutable store.
    if w.source not in trust_root.sources:
        raise ProvenanceGateError(
            f"warrant for {candidate.source!r} is not anchored in the trust "
            f"root; it may have been minted by the store itself"
        )

    # Invariant 2: content-binding. A label-only warrant authorizes nothing.
    if w.content_hash != content_hash(candidate.payload):
        raise ProvenanceGateError(
            f"warrant for {candidate.source!r} does not bind to this payload "
            f"(expected {w.content_hash[:12]}..., got "
            f"{content_hash(candidate.payload)[:12]}...)"
        )

    # Invariant 3: cryptographic validity recomputed against the root key.
    if not verify_signature(w, trust_root.key_for(w.source)):
        raise ProvenanceGateError(
            f"warrant signature for {candidate.source!r} failed verification "
            f"against trust root"
        )

    # Invariant 4: transitive tier is the min over the provenance chain.
    effective_tier = trust_root.tier_of(w.source)
    if effective_tier < candidate.required_tier:
        raise ProvenanceGateError(
            f"effective tier {effective_tier} < required {candidate.required_tier} "
            f"for source {candidate.source!r}"
        )
    # ... commit to store only after all four invariants hold
