# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-privilege-amplification-when-a-federated-agent-re-derives-delegated-capability-from-a-stale-policy-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-privilege-amplification-when-a-federated-agent-re-derives-delegated-capability-from-a-stale-policy-snapshot.warrant.json
# Markdown SHA-256:   1b0ce20f4714d298839764d38422b76b10f565299f0cee536852308fb2a89095
# Code AST SHA-256:   23f46701ef9137e4f9e80d30ec951b9784697c01744ffe5466ea32a2c9c3073c
# Verified Classes:   DelegationEpochMismatch, DiffClass, Grant, PolicyDiff
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class DelegationEpochMismatch(RuntimeError):
    """Raised when a grant's epoch cannot be reconciled with live policy."""


class DiffClass(Enum):
    NARROWING = "narrowing"
    NEUTRAL = "neutral"
    WIDENING = "widening"
    RECLASSIFICATION = "reclassification"  # treated as widening


@dataclass(frozen=True)
class Grant:
    action: str
    resource_class: str
    delegation_epoch: int
    signed_decision_digest: str


@dataclass(frozen=True)
class PolicyDiff:
    from_epoch: int
    to_epoch: int
    resource_class: str
    classification: DiffClass
    signed: bool


def reconcile(grant: Grant, live_epoch: int, diffs: list[PolicyDiff]) -> None:
    """Enforce monotonic epoch binding for a federated grant.

    Accepts only when the grant epoch equals live policy, or when a signed,
    contiguous chain of diffs proves the change is narrowing-or-neutral for
    the grant's resource class. Absence of proof is denial.
    """
    if grant.delegation_epoch == live_epoch:
        return

    if grant.delegation_epoch > live_epoch:
        raise DelegationEpochMismatch(
            f"grant epoch {grant.delegation_epoch} is ahead of live {live_epoch}; "
            "possible forged epoch or clock skew"
        )

    applicable = sorted(
        (d for d in diffs if d.resource_class == grant.resource_class
         and grant.delegation_epoch < d.to_epoch <= live_epoch),
        key=lambda d: d.to_epoch,
    )

    expected = grant.delegation_epoch
    for d in applicable:
        if d.from_epoch != expected:
            raise DelegationEpochMismatch(
                f"non-contiguous diff chain: expected from_epoch {expected}, "
                f"got {d.from_epoch}"
            )
        if not d.signed:
            raise DelegationEpochMismatch(
                f"unsigned diff {d.from_epoch}->{d.to_epoch} cannot be trusted"
            )
        if d.classification in (DiffClass.WIDENING, DiffClass.RECLASSIFICATION):
            raise DelegationEpochMismatch(
                f"diff {d.from_epoch}->{d.to_epoch} is {d.classification.value}; "
                "grant must be re-derived, not reconciled"
            )
        expected = d.to_epoch

    if expected != live_epoch:
        raise DelegationEpochMismatch(
            f"diff chain ends at {expected}, live policy is {live_epoch}; "
            "no proof of narrowing, deny"
        )


def mint_downstream(broker_cached_epoch: int, live_epoch: int, action: str,
                    resource_class: str) -> Grant:
    """A broker must refresh before minting; minting from a stale epoch is banned."""
    if broker_cached_epoch != live_epoch:
        raise DelegationEpochMismatch(
            f"broker on epoch {broker_cached_epoch} cannot mint against live "
            f"{live_epoch}; refresh required before delegation"
        )
    digest = hashlib.sha256(f"{action}:{resource_class}:{live_epoch}".encode()).hexdigest()
    return Grant(action, resource_class, live_epoch, digest)
