# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-policy-assertion-has-silently-degraded-to-a-weaker-trust-tier-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-policy-assertion-has-silently-degraded-to-a-weaker-trust-tier-mid-session.warrant.json
# Markdown SHA-256:   c76d4acad7d7a1884f0fb84332cf907c52745605105b1b949179b90ab65ac85c
# Code AST SHA-256:   9894f1707bcdf4febf0f674009bf2a95bd524e0d45dab5427949afa9d57a958f
# Verified Classes:   TierDegradationError, TierAssertion, Action, FederatedSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TierDegradationError(RuntimeError):
    """Raised when an action would be authorized on a cached tier that the
    peer's current policy no longer grants. This is the silent-degradation
    guard: it fires before the action leaves the instance."""
    pass


@dataclass
class TierAssertion:
    tier: str
    max_commit_value: float
    tool_surface: frozenset
    issued_at: float
    ttl: float
    issuer: str

    def is_expired(self, now: float) -> bool:
        return now > self.issued_at + self.ttl


@dataclass
class Action:
    name: str
    value: float
    irreversible: bool


@dataclass
class FederatedSession:
    peer_id: str
    cached_tier: TierAssertion
    degradation_margin: float = 0.1
    _last_verified: float = field(default_factory=time.time)

    def _freshness_budget(self, action: Action) -> float:
        # Unwind cost proxy: irreversible actions demand near-immediate proof.
        return 5.0 if action.irreversible else self.cached_tier.ttl

    def _reverify(self) -> TierAssertion:
        # In production: fetch signed assertion from issuer directory and
        # verify signature *and* that the encoded tier is current.
        # Here we simulate the peer having silently dropped its ceiling.
        now = time.time()
        self._last_verified = now
        return TierAssertion(
            tier=self.cached_tier.tier,
            max_commit_value=5000.0,          # silently degraded from 50000
            tool_surface=frozenset({"catalog_lookup", "draft_quote"}),
            issued_at=now,
            ttl=self.cached_tier.ttl,
            issuer=self.cached_tier.issuer,
        )

    def authorize(self, action: Action) -> None:
        now = time.time()
        needs_reverify = (
            action.irreversible
            or action.value > self.cached_tier.max_commit_value * (1 - self.degradation_margin)
            or self.cached_tier.is_expired(now)
            or (now - self._last_verified) > self._freshness_budget(action)
        )

        effective = self._reverify() if needs_reverify else self.cached_tier

        if action.value > effective.max_commit_value:
            raise TierDegradationError(
                f"action {action.name!r} value={action.value} exceeds peer "
                f"{self.peer_id} current ceiling {effective.max_commit_value} "
                f"(cached tier claimed {self.cached_tier.max_commit_value}); "
                f"tier degraded silently at {effective.issued_at:.0f}"
            )
        if action.name not in effective.tool_surface:
            raise TierDegradationError(
                f"action {action.name!r} not in peer {self.peer_id} current "
                f"tool surface {sorted(effective.tool_surface)}; cached surface "
                f"{sorted(self.cached_tier.tool_surface)} is stale"
            )


def detect_shape_mismatch(response: dict, cached_tier: TierAssertion) -> bool:
    """Fast-path detector: a response carrying a pre-computed artifact where
    the cached tier guarantees a live probe is shape-incompatible with that
    tier and signals a possible degradation. Escalate to re-verification."""
    if response.get("provenance") == "cached_pre_attestation":
        if "price_probe" in cached_tier.tool_surface:
            return True
    return False


if __name__ == "__main__":
    session = FederatedSession(
        peer_id="org-b/supplier-quote",
        cached_tier=TierAssertion(
            tier="quote:negotiate",
            max_commit_value=50000.0,
            tool_surface=frozenset({"catalog_lookup", "price_probe", "draft_quote"}),
            issued_at=time.time() - 5400,
            ttl=21600,
            issuer="org-b/policy-authority",
        ),
    )
    commit = Action(name="commit_quote", value=42000.0, irreversible=True)
    try:
        session.authorize(commit)
    except TierDegradationError as e:
        print(f"BLOCKED before egress: {e}")
