# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-negotiate-capability-delegation-when-a-federated-peer-s-policy-envelope-narrows-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-negotiate-capability-delegation-when-a-federated-peer-s-policy-envelope-narrows-mid-session.warrant.json
# Markdown SHA-256:   54405a2bf34986bc000051af8b5b90b2f3780d9658e03210209c01ecd7fb9f70
# Code AST SHA-256:   5ffd0318f8d6cb68769afdf2b83c46aad6597aeb5495398186e7348217edcc38
# Verified Classes:   EnvelopeStalenessError, CachedEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EnvelopeStalenessError(RuntimeError):
    """Raised when a cached capability envelope can no longer be trusted as current."""


@dataclass(frozen=True)
class CachedEnvelope:
    capability: str
    max_amount: int
    allowed_rails: tuple
    cached_at: float
    stability_horizon: float | None  # absolute epoch seconds, or None if issuer gave no guarantee


def assert_envelope_current(env: CachedEnvelope, now: float | None = None) -> None:
    now = time.time() if now is None else now
    if env.stability_horizon is None:
        # No issuer guarantee: envelope may have narrowed at any instant.
        raise EnvelopeStalenessError(
            f"capability {env.capability!r} has no stability horizon; "
            "cannot certify envelope is current — refresh required before acting"
        )
    if now > env.stability_horizon:
        raise EnvelopeStalenessError(
            f"capability {env.capability!r} stability horizon elapsed at "
            f"{env.stability_horizon:.0f} (now {now:.0f}); cached bounds "
            f"max_amount={env.max_amount}, rails={env.allowed_rails} are unverified"
        )


def classify_policy_denial(error_code: str, deterministic: bool, env: CachedEnvelope) -> str:
    """Return 'retry', 'refetch_warrant', or 'replan'."""
    if error_code in ("capability_revoked", "warrant_expired"):
        return "refetch_warrant"  # capability gone; plan structure may survive
    if error_code == "policy_denied" and deterministic:
        try:
            assert_envelope_current(env)
        except EnvelopeStalenessError:
            return "replan"  # envelope unverifiable + deterministic denial => bounds moved
        # Envelope provably current yet denial persists: issuer-side inconsistency.
        raise EnvelopeStalenessError(
            f"deterministic policy_denied under a provably-current envelope for "
            f"{env.capability!r}; issuer contract violated — escalate"
        )
    return "retry"  # non-deterministic denial treated as transient
