# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-capability-after-a-cross-organizational-reputation-fork.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-capability-after-a-cross-organizational-reputation-fork.warrant.json
# Markdown SHA-256:   3609be0293cab2ac54e4d0a64133889439ae2c3bef66bc7a94687f786c694633
# Code AST SHA-256:   d314c16394a2f0dc21caef1f24998f9d9027b93c8fd0785cde3b86be14a0cf9d
# Verified Classes:   RevocationForkError, Grant, ReputationAttestation, Executor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional


class RevocationForkError(RuntimeError):
    """Raised when a capability grant is shadowed by a stale reputation attestation
    that masks an authoritative revocation at a higher epoch."""


@dataclass
class Grant:
    issuer: str
    agent: str
    capability: str
    epoch: int
    signature_ok: bool


@dataclass
class ReputationAttestation:
    scorer: str
    agent: str
    score: float
    observed_epoch: int


@dataclass
class Executor:
    # Monotone high-water mark per (issuer, agent, capability).
    rhwm: Dict[tuple, int] = field(default_factory=dict)
    synced_issuers: set = field(default_factory=set)
    reputation_threshold: float = 0.7

    def observe_revocation(self, issuer: str, agent: str, capability: str, epoch: int) -> None:
        key = (issuer, agent, capability)
        self.rhwm[key] = max(self.rhwm.get(key, -1), epoch)

    def mark_synced(self, issuer: str) -> None:
        self.synced_issuers.add(issuer)

    def validate(self, grant: Grant, rep: Optional[ReputationAttestation]) -> bool:
        if not grant.signature_ok:
            raise RevocationForkError(f"unsigned grant from {grant.issuer}")

        if grant.issuer not in self.synced_issuers:
            # Fail-closed during cold start: no epoch floor yet.
            raise RevocationForkError(
                f"executor not synced with issuer {grant.issuer}; refusing grant"
            )

        key = (grant.issuer, grant.agent, grant.capability)
        floor = self.rhwm.get(key, -1)

        if grant.epoch <= floor:
            # Authoritative revocation at or above this epoch exists.
            raise RevocationForkError(
                f"grant epoch {grant.epoch} <= revocation high-water mark {floor} "
                f"for {key}"
            )

        if rep is not None:
            if rep.observed_epoch < floor:
                # The scorer is blind to the revocation; its score cannot
                # legitimize the grant's epoch. Treat as stale, not as valid.
                raise RevocationForkError(
                    f"reputation from {rep.scorer} observed epoch {rep.observed_epoch} "
                    f"< RHWM {floor}; score is stale and cannot gate capability"
                )
            if rep.score < self.reputation_threshold:
                return False

        return True
