# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-across-vendor-trust-domain-boundaries-when-agent-warrants-carry-non-monotonic-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-across-vendor-trust-domain-boundaries-when-agent-warrants-carry-non-monotonic-scope.warrant.json
# Markdown SHA-256:   0e3fc72e8e49f91f5a6341d82e7cb4838e28e2012af5e367a5985343b9d37b29
# Code AST SHA-256:   24791974e02d67087a6c2db2fb02aa81c68651bea79e69f0633d737403c1b08e
# Verified Classes:   NonMonotonicScopeReplay, Warrant, ReplayCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet


class NonMonotonicScopeReplay(RuntimeError):
    """Raised when a warrant presentation violates the attenuation invariant
    and cannot be safely keyed by scope-hash alone."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    parent_chain_hash: str  # hash of all ancestor signatures, or "" for root
    signature: str

    def chain_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.parent_chain_hash.encode())
        h.update(self.signature.encode())
        return h.hexdigest()

    def scope_hash(self) -> str:
        return hashlib.sha256(
            "|".join(sorted(self.scope)).encode()
        ).hexdigest()


class ReplayCache:
    def __init__(self) -> None:
        # key: (subject, chain_hash) -> set of consumed scope hashes
        self._seen: dict[tuple[str, str], set[str]] = {}

    def check_and_record(self, w: Warrant, cached_scope: FrozenSet[str] | None) -> None:
        key = (w.subject, w.chain_hash())
        consumed = self._seen.setdefault(key, set())

        if w.scope_hash() in consumed:
            raise NonMonotonicScopeReplay(
                f"replay: warrant for {w.subject} under chain {w.chain_hash()[:12]} "
                f"already consumed scope {w.scope_hash()[:12]}"
            )

        # The attenuation invariant: a re-presented warrant under the same
        # chain must have scope that is a SUBSET of the previously cached scope.
        # If it is not a subset, the derivation was non-monotonic and the
        # scope-hash key is unsound — refuse rather than extend trust.
        if cached_scope is not None and not w.scope.issubset(cached_scope):
            raise NonMonotonicScopeReplay(
                f"non-monotonic scope expansion for {w.subject}: "
                f"{sorted(w.scope - cached_scope)} not present in cached scope; "
                f"replay cache key is unsound across this trust boundary"
            )

        consumed.add(w.scope_hash())


def verify_presentation(
    w: Warrant,
    cache: ReplayCache,
    cached_scope: FrozenSet[str] | None,
) -> None:
    if not w.parent_chain_hash and w.issuer not in {"vendor-a.example"}:
        # Root warrants may only be minted by configured trust anchors.
        raise NonMonotonicScopeReplay(
            f"root warrant minted by non-anchor issuer {w.issuer}"
        )
    cache.check_and_record(w, cached_scope)
