# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-description-shadowing-from-silently-widening-a-dynamically-loaded-agent-s-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-description-shadowing-from-silently-widening-a-dynamically-loaded-agent-s-capability-envelope.warrant.json
# Markdown SHA-256:   8708892db951d2eff6e3f601444e4df6193735684d1a7ffbc98fa6c7dadee8d0
# Code AST SHA-256:   e61f0b917fa9e230c8cada9caf3ef3c1575bd155863a50bc0974a57cc576371b
# Verified Classes:   ToolContractViolation, PlanAuthorityViolation, ToolEntry, ToolRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ToolContractViolation(RuntimeError):
    """Raised when a re-registration mutates the model-facing contract of an
    existing tool name without a version bump or explicit re-consent."""
    pass


class PlanAuthorityViolation(RuntimeError):
    """Raised when an assembled tool plan touches tools outside the warrant
    that authorized the originating task."""
    pass


@dataclass(frozen=True)
class ToolEntry:
    name: str
    description: str
    schema: dict
    side_effect_class: str  # "read" | "write" | "egress"

    def contract_fingerprint(self) -> tuple:
        # Description is included verbatim: you cannot safely diff "meaning",
        # so any description change is a contract change.
        return (self.description, repr(self.schema), self.side_effect_class)


@dataclass
class ToolRegistry:
    _entries: dict = field(default_factory=dict)

    def register(self, entry: ToolEntry, *, allow_contract_change: bool = False) -> None:
        existing = self._entries.get(entry.name)
        if existing is not None:
            if existing.contract_fingerprint() != entry.contract_fingerprint() and not allow_contract_change:
                raise ToolContractViolation(
                    f"re-registration of '{entry.name}' mutates its model-facing "
                    f"contract (description/schema/side-effect) without a version "
                    f"bump or re-consent; fork the name instead"
                )
        self._entries[entry.name] = entry

    def get(self, name: str) -> ToolEntry:
        return self._entries[name]


def validate_plan_authority(plan: list, warrant_tools: set) -> None:
    """Plan-level check: the sequence the model assembled must stay inside the
    warrant's declared tool set, not merely pass per-call checks."""
    for step in plan:
        if step not in warrant_tools:
            raise PlanAuthorityViolation(
                f"plan step '{step}' is outside the task warrant's tool set "
                f"{sorted(warrant_tools)}; description-driven composition rejected"
            )


def refresh_and_execute(registry: ToolRegistry, manifest_entry: ToolEntry,
                        plan: list, warrant_tools: set) -> None:
    registry.register(manifest_entry)  # raises on contract shadowing
    validate_plan_authority(plan, warrant_tools)  # raises on composition escape
    for step in plan:
        registry.get(step)  # execution would follow
