# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-attenuated-delegation-warrant-has-silently-outlived-the-parent-scope-it-was-minted-under.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-attenuated-delegation-warrant-has-silently-outlived-the-parent-scope-it-was-minted-under.warrant.json
# Markdown SHA-256:   031d237a9eae79bbcde51562cb320b5140c7ee55a9cd310d1e53a99d0e23ebd0
# Code AST SHA-256:   fadcf1c15238586dc510c3e3f13ad2694ea7dc85289d61d452eed0e8c0c333f1
# Verified Classes:   OrphanedWarrantError, ScopeRecord, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet


class OrphanedWarrantError(RuntimeError):
    """Raised when a child warrant's scope is no longer a valid attenuation
    of its parent's *current* scope (parent narrowed after mint)."""


@dataclass(frozen=True)
class ScopeRecord:
    capabilities: FrozenSet[str]
    epoch: int  # monotonic; bumped on any narrowing


@dataclass(frozen=True)
class Warrant:
    child_scope: FrozenSet[str]
    parent_scope_hash: str
    parent_epoch_at_mint: int
    ttl_seconds: int


def scope_hash(scope: FrozenSet[str]) -> str:
    return hashlib.sha256("|".join(sorted(scope)).encode()).hexdigest()


def authorize_action(
    warrant: Warrant,
    action_capability: str,
    parent_current: ScopeRecord,
    elapsed_seconds: float,
) -> None:
    # 1. TTL check (the easy, always-present check).
    if elapsed_seconds > warrant.ttl_seconds:
        raise OrphanedWarrantError("warrant TTL exceeded")

    # 2. Local claim check: is the action inside the frozen child scope?
    if action_capability not in warrant.child_scope:
        raise OrphanedWarrantError(
            f"action {action_capability!r} not in attenuated child scope"
        )

    # 3. THE BOUNDARY: parent epoch must not have advanced since mint.
    #    An epoch bump means the parent's scope narrowed; the frozen child
    #    claim may now exceed the parent's live scope.
    if parent_current.epoch != warrant.parent_epoch_at_mint:
        # Re-derive superset against the parent's *current* scope.
        if not warrant.child_scope.issubset(parent_current.capabilities):
            raise OrphanedWarrantError(
                f"child scope {sorted(warrant.child_scope)} is no longer a "
                f"subset of parent current scope {sorted(parent_current.capabilities)} "
                f"(parent epoch {warrant.parent_epoch_at_mint} -> {parent_current.epoch})"
            )
        # Epoch advanced but superset still holds; refresh the mint epoch.
        object.__setattr__(warrant, "parent_epoch_at_mint", parent_current.epoch)

    # 4. Chain-freshness: parent scope hash must still match the claim.
    if scope_hash(parent_current.capabilities) != warrant.parent_scope_hash:
        # Hash mismatch without epoch bump indicates a mesh bookkeeping fault.
        raise OrphanedWarrantError(
            "parent scope hash drift without epoch bump; mesh invariant violated"
        )
