# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-consent-chain-has-silently-forked-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-consent-chain-has-silently-forked-mid-execution.warrant.json
# Markdown SHA-256:   7b00ddf543e56083749e3b233cca4c6d765559b44ab4911e955d3e0b238654bc
# Code AST SHA-256:   a593aa1d40fbeea8ea9597461520ad5bc558bef8a619dbd8c794c1032861421d
# Verified Classes:   ConsentChainForkError, ConsentHighWaterLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ConsentChainForkError(RuntimeError):
    """Raised when a delegated capability token's consent chain has forked:
    the presented consent_id is not the monotonic high-water mark for its
    (principal, scope) pair, implying a sibling branch exists."""
    pass


class ConsentHighWaterLedger:
    """Local, monotonic record of the highest consent counter seen per
    (principal, scope). Cheap fork detector that does not require an
    issuer round-trip."""

    def __init__(self):
        self._marks = {}

    def admit(self, token) -> None:
        key = (token.principal, token.scope)
        seen = self._marks.get(key, -1)

        if token.chain_counter < seen:
            raise ConsentChainForkError(
                f"consent fork: token consent_id={token.consent_id} "
                f"counter={token.chain_counter} is behind high-water "
                f"{seen} for principal={token.principal} scope={token.scope}; "
                f"a sibling delegation branch is live. Refusing to execute."
            )

        if token.chain_counter == seen and token.consent_id != self._marks.get(key + ("id",)):
            raise ConsentChainForkError(
                f"consent fork at equal counter: consent_id={token.consent_id} "
                f"conflicts with admitted id for {key}. Ambiguous authority."
            )

        self._marks[key] = token.chain_counter
        self._marks[key + ("id",)] = token.consent_id


def verify_and_admit(token, ledger: ConsentHighWaterLedger) -> None:
    if not token.signature_valid():
        raise ConsentChainForkError(f"bad signature on {token.consent_id}")
    if token.depth_remaining < 0:
        raise ConsentChainForkError(f"depth exhausted on {token.consent_id}")
    ledger.admit(token)  # raises ConsentChainForkError on divergence
