# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-identity-binding-collapse-during-a2a-encrypted-channel-negotiation-when-a-replayed-warrant-envelope-validates-against-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-identity-binding-collapse-during-a2a-encrypted-channel-negotiation-when-a-replayed-warrant-envelope-validates-against-a.warrant.json
# Markdown SHA-256:   2066b38ce33888ee6095163eab952f69a3f88546025757b2b73589c80af920a4
# Code AST SHA-256:   4a14f3a4f9c1ec1689133d4de19801c6bb25f72113e91a8cd6cd1ce5a2957104
# Verified Classes:   EpochBindingCollapse, WarrantRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class EpochBindingCollapse(RuntimeError):
    """Raised when a warrant's minting epoch does not match the envelope's signing epoch,
    or when a counter is presented under an epoch whose base has not been attested."""
    pass


class WarrantRegistry:
    def __init__(self):
        # epoch -> {warrant_id: warrant_body}
        self._by_epoch: dict[str, dict[str, dict]] = {}
        # (peer_id, epoch) -> highest accepted counter
        self._counter_high: dict[tuple[str, str], int] = {}
        # epochs for which a root-signed rebasing attestation has been observed
        self._attested_epochs: set[str] = set()

    def attest_rotation(self, peer_id: str, epoch: str, root_sig_valid: bool) -> None:
        if not root_sig_valid:
            raise EpochBindingCollapse(
                f"rotation attestation for {peer_id}@{epoch} failed root signature"
            )
        self._attested_epochs.add(epoch)

    def register_warrant(self, epoch: str, warrant: dict) -> None:
        self._by_epoch.setdefault(epoch, {})[warrant["id"]] = warrant

    def accept(self, peer_id: str, envelope: dict) -> None:
        epoch = envelope["epoch"]
        warrant = envelope["warrant"]
        counter = envelope["counter"]

        # Condition 1: warrant-epoch equality.
        if warrant.get("epoch") != epoch:
            raise EpochBindingCollapse(
                f"warrant {warrant.get('id')} minted under {warrant.get('epoch')} "
                f"presented under envelope epoch {epoch}"
            )

        # Condition 3: rotation must be root-attested before the new epoch is trusted.
        if epoch not in self._attested_epochs:
            raise EpochBindingCollapse(
                f"epoch {epoch} for peer {peer_id} has no attested rebasing; "
                f"quarantine required, refusing to execute"
            )

        # Condition 2: counter scoped to (peer, epoch), not (peer).
        key = (peer_id, epoch)
        high = self._counter_high.get(key, -1)
        base = warrant.get("counter_base", 0)
        if counter < base:
            raise EpochBindingCollapse(
                f"counter {counter} below epoch-scoped base {base} for {peer_id}@{epoch}"
            )
        if counter <= high:
            raise EpochBindingCollapse(
                f"replay: counter {counter} not ahead of {high} for {peer_id}@{epoch}"
            )

        # Condition 4: warrant must be present in the current epoch's registry.
        if warrant["id"] not in self._by_epoch.get(epoch, {}):
            raise EpochBindingCollapse(
                f"warrant {warrant['id']} not registered under current epoch {epoch}; "
                f"stale warrant re-signed under rotated key"
            )

        self._counter_high[key] = counter
