# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-capability-grant-when-the-broker-s-attestation-chain-is-valid-but-the-peer-s-declared-capab.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-capability-grant-when-the-broker-s-attestation-chain-is-valid-but-the-peer-s-declared-capab.warrant.json
# Markdown SHA-256:   282f7635dfb70372fdab1aa63cb7e5b98f08061e8b26545187e02ced148d0bf7
# Code AST SHA-256:   9aec71b602e76bf8dbdce0bdb5bf9ab6b91cd11832e76fd641a02f9e4101fb2a
# Verified Classes:   CapabilitySurfaceDivergence, Manifest, Observation, ConformanceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class CapabilitySurfaceDivergence(RuntimeError):
    """Raised when a broker-attested capability's observed invocation surface
    contradicts its declared schema on a hard axis (type or side-effect)."""
    pass


@dataclass
class Manifest:
    peer_id: str
    capability_id: str
    manifest_hash: str
    output_type: str            # e.g. "list[str]"
    side_effect_class: str      # "read_only" | "mutating"
    egress_allowlist: frozenset[str]
    declared_max_tokens: int


@dataclass
class Observation:
    output_type: str
    egress_hosts: frozenset[str]
    observed_max_tokens: int


@dataclass
class ConformanceLedger:
    # key: (peer_id, capability_id, manifest_hash) -> verdict
    entries: dict = field(default_factory=dict)

    def promote_or_revoke(self, m: Manifest, obs: Observation,
                          attestation_valid: bool) -> Literal["USABLE", "PROVISIONAL"]:
        if not attestation_valid:
            return "PROVISIONAL"  # attestation is necessary, not sufficient

        # Hard axis 1: output type divergence
        if obs.output_type != m.output_type:
            self.entries[(m.peer_id, m.capability_id, m.manifest_hash)] = "REVOKED"
            raise CapabilitySurfaceDivergence(
                f"{m.peer_id}/{m.capability_id}: declared output {m.output_type!r} "
                f"but observed {obs.output_type!r}; attestation valid but surface diverges"
            )

        # Hard axis 2: egress outside declared side-effect envelope
        undeclared = obs.egress_hosts - m.egress_allowlist
        if undeclared and m.side_effect_class == "read_only":
            self.entries[(m.peer_id, m.capability_id, m.manifest_hash)] = "REVOKED"
            raise CapabilitySurfaceDivergence(
                f"{m.peer_id}/{m.capability_id}: read_only declared but egress to "
                f"{sorted(undeclared)}; broker attestation does not cover behavior"
            )

        # Soft axis: silent bound clamp -> downgrade, cap budget to observed
        if obs.observed_max_tokens < m.declared_max_tokens:
            self.entries[(m.peer_id, m.capability_id, m.manifest_hash)] = "PROVISIONAL"
            return "PROVISIONAL"

        self.entries[(m.peer_id, m.capability_id, m.manifest_hash)] = "USABLE"
        return "USABLE"

    def effective_budget(self, m: Manifest, obs: Observation) -> int:
        # Never trust a declared bound the peer has been observed to clamp.
        return min(m.declared_max_tokens, obs.observed_max_tokens)
