# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-scope-widening-across-a-federated-a2a-trust-anchor-after-a-peer-s-key-rotation-rebinds-a-delegated-warrant-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-scope-widening-across-a-federated-a2a-trust-anchor-after-a-peer-s-key-rotation-rebinds-a-delegated-warrant-to.warrant.json
# Markdown SHA-256:   8678df02642ce37bf2e764c84c2a990435a4676799a6f2aae22de175d1460988
# Code AST SHA-256:   2493210776731abf54588a149fac55780c875d975d724fa436ae0c70a3e257a9
# Verified Classes:   ScopeDriftError, AnchorSnapshot, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeDriftError(RuntimeError):
    """Raised when a warrant's effective scope under the current anchor
    epoch is a strict superset of its scope under the issuance epoch."""


@dataclass(frozen=True)
class AnchorSnapshot:
    epoch: int
    default_namespace: str
    normalization_rules: str


@dataclass(frozen=True)
class Warrant:
    scope_selector: str          # may be relative, e.g. "res://shared/*"
    issued_under_anchor_epoch: int
    expires_at: float


def resolve_scope(selector: str, anchor: AnchorSnapshot) -> FrozenSet[str]:
    # Relative selector resolves against anchor-declared namespace.
    if selector.endswith("/*"):
        root = selector[: -len("/*")]
        ns = anchor.default_namespace.rstrip("/")
        return frozenset({f"{root}/{ns}/**"})
    return frozenset({selector})


def effective_scope(
    warrant: Warrant,
    anchor_history: dict[int, AnchorSnapshot],
    current_anchor: AnchorSnapshot,
    now: float,
) -> FrozenSet[str]:
    if now >= warrant.expires_at:
        raise ScopeDriftError("warrant expired; refusing scope computation")

    issue_epoch = warrant.issued_under_anchor_epoch
    if issue_epoch not in anchor_history:
        # Cannot reconstruct issuance-time semantics: fail closed.
        raise ScopeDriftError(
            f"anchor epoch {issue_epoch} not historically addressable; "
            "cannot bound scope, refusing"
        )

    issuance_anchor = anchor_history[issue_epoch]
    issued_scope = resolve_scope(warrant.scope_selector, issuance_anchor)
    current_scope = resolve_scope(warrant.scope_selector, current_anchor)

    if current_scope - issued_scope:
        # Current anchor would widen the grant beyond what was signed.
        raise ScopeDriftError(
            f"scope drift on warrant: issuance={sorted(issued_scope)} "
            f"current={sorted(current_scope)}"
        )

    return issued_scope  # intersection == issued_scope when no widening
