# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-dynamically-discovered-tool-whose-schema-validates-but-whose-declared-capability-envelope-silently-narrows-the-caller.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-dynamically-discovered-tool-whose-schema-validates-but-whose-declared-capability-envelope-silently-narrows-the-caller.warrant.json
# Markdown SHA-256:   a8e7314192c3837fa825ffb88ad6d8cac3b60ae925516fb52092ff5196470a3a
# Code AST SHA-256:   f53109947c9082aee253944c97f0f96c657c63098e40a0575327a331ff6279d2
# Verified Classes:   CapabilityEnvelopeViolation, CapabilityEnvelope, CallerBudget
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a discovered tool's declared envelope cannot be contained
    within the caller's remaining context budget plus reserved headroom."""


@dataclass(frozen=True)
class CapabilityEnvelope:
    max_input_tokens: int
    max_output_tokens: int

    def cache_key(self, schema_hash: str) -> str:
        # Envelope is part of capability identity: schema alone is insufficient.
        return f"{schema_hash}:{self.max_input_tokens}:{self.max_output_tokens}"


@dataclass(frozen=True)
class CallerBudget:
    remaining_context_budget: int
    reserved_output_headroom: int

    @property
    def admissible(self) -> int:
        return self.remaining_context_budget - self.reserved_output_headroom


def admit_handoff(
    schema_hash: str,
    envelope: CapabilityEnvelope,
    budget: CallerBudget,
    capability_cache: dict[str, CapabilityEnvelope],
) -> CapabilityEnvelope:
    key = envelope.cache_key(schema_hash)
    cached = capability_cache.get(key)
    if cached is not None:
        return cached

    if budget.admissible <= 0:
        raise CapabilityEnvelopeViolation(
            f"Caller has no admissible budget: remaining={budget.remaining_context_budget}, "
            f"headroom={budget.reserved_output_headroom}"
        )

    if envelope.max_output_tokens > budget.admissible:
        raise CapabilityEnvelopeViolation(
            f"Callee max_output_tokens={envelope.max_output_tokens} exceeds "
            f"caller admissible budget={budget.admissible}; result could not be acted upon."
        )

    if envelope.max_input_tokens > budget.admissible:
        raise CapabilityEnvelopeViolation(
            f"Callee max_input_tokens={envelope.max_input_tokens} exceeds "
            f"caller admissible budget={budget.admissible}; input would be silently truncated."
        )

    capability_cache[key] = envelope
    return envelope


def enforce_receipt(
    envelope: CapabilityEnvelope,
    actual_output_tokens: int,
) -> None:
    # Post-receipt guard: callee may violate its own declaration.
    if actual_output_tokens > envelope.max_output_tokens:
        raise CapabilityEnvelopeViolation(
            f"Callee violated declared envelope: declared={envelope.max_output_tokens}, "
            f"actual={actual_output_tokens}; caller must truncate with explicit marker."
        )
