# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-renegotiate-a-capability-warrant-after-a-peer-s-scope-narrowing-handoff-and-why-monotonic-trust-assumptions-silently-break.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-renegotiate-a-capability-warrant-after-a-peer-s-scope-narrowing-handoff-and-why-monotonic-trust-assumptions-silently-break.warrant.json
# Markdown SHA-256:   21e565c15452c179b38f1bfc9d02082865c2226f325c0cec2ef0994e135bb108
# Code AST SHA-256:   dbeaf1d99a6b6ade448caebe80262b7d7edce3f908b9024ee746feea61ab01ab
# Verified Classes:   ChainScopeWideningError, Scope, LedgerEntry, ChainScopeLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from time import monotonic


class ChainScopeWideningError(RuntimeError):
    """Raised when an inbound warrant would grant broader scope than a live
    attenuation recorded for the same chain epoch."""
    pass


@dataclass(frozen=True)
class Scope:
    resources: frozenset[str]
    actions: frozenset[str]

    def intersect(self, other: "Scope") -> "Scope":
        return Scope(self.resources & other.resources, self.actions & other.actions)

    def is_subset_of(self, other: "Scope") -> bool:
        return self.resources <= other.resources and self.actions <= other.actions


@dataclass
class LedgerEntry:
    effective: Scope
    expires_at: float


@dataclass
class ChainScopeLedger:
    # keyed on (originating_root, chain_id) -> most-narrowed live scope
    _entries: dict[tuple[str, str], LedgerEntry] = field(default_factory=dict)

    def record_attenuation(self, root: str, chain: str, narrowed: Scope, ttl: float) -> None:
        key = (root, chain)
        now = monotonic()
        existing = self._entries.get(key)
        if existing and existing.expires_at > now:
            narrowed = existing.effective.intersect(narrowed)
        self._entries[key] = LedgerEntry(effective=narrowed, expires_at=now + ttl)

    def reconcile(self, root: str, chain: str, presented: Scope) -> Scope:
        key = (root, chain)
        now = monotonic()
        entry = self._entries.get(key)
        if entry is None or entry.expires_at <= now:
            # epoch rolled or unseen chain: presented warrant governs
            return presented
        effective = presented.intersect(entry.effective)
        if not effective.is_subset_of(entry.effective):
            # defensive: intersection must never widen
            raise ChainScopeWideningError(
                f"reconciliation produced scope broader than recorded attenuation "
                f"for root={root} chain={chain}"
            )
        return effective


def authorize_inbound(
    ledger: ChainScopeLedger,
    root: str,
    chain: str,
    presented: Scope,
    requested: Scope,
) -> Scope:
    effective = ledger.reconcile(root, chain, presented)
    if not requested.is_subset_of(effective):
        raise ChainScopeWideningError(
            f"requested scope {requested} exceeds effective chain scope {effective} "
            f"for root={root} chain={chain}; an intermediate org attenuated this chain"
        )
    return effective
