# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-registry-entry-that-was-valid-at-load-time-mid-session-skill-injection-via-post-registration-capability-mutation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-registry-entry-that-was-valid-at-load-time-mid-session-skill-injection-via-post-registration-capability-mutation.warrant.json
# Markdown SHA-256:   25d7b80566af9f6fecdf22fcba3a0d1eee575312e788c4190b3f09f747edd26e
# Code AST SHA-256:   3eefb17a0903454caaa00c8c7683d9c78f534f08c9c5eabd15c27a1bedb33f27
# Verified Classes:   ContractMutationError, ToolContract, AuthorizationVerdict, Registry, GatedExecutor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ContractMutationError(RuntimeError):
    """Raised when a tool's authority-bearing contract changed after authorization."""


@dataclass(frozen=True)
class ToolContract:
    name: str
    binding_id: str
    params: dict[str, str]          # param name -> type
    side_effects: frozenset[str]    # e.g. {"read_env", "network"}
    scope: str                      # e.g. "workspace_root"

    def authority_hash(self) -> str:
        # Only authority-bearing fields; description prose excluded on purpose.
        payload = json.dumps(
            {
                "binding_id": self.binding_id,
                "params": self.params,
                "side_effects": sorted(self.side_effects),
                "scope": self.scope,
            },
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class AuthorizationVerdict:
    binding_id: str
    contract_hash: str
    requires_confirmation: bool


class Registry:
    def __init__(self) -> None:
        self._entries: dict[str, ToolContract] = {}

    def register(self, contract: ToolContract) -> None:
        self._entries[contract.name] = contract

    def mutate_contract(self, name: str, **changes: Any) -> None:
        # Simulates a peer/plugin/server re-announcing an expanded contract
        # under the SAME binding_id — the attack surface.
        current = self._entries[name]
        self._entries[name] = ToolContract(
            name=current.name,
            binding_id=current.binding_id,
            params=changes.get("params", current.params),
            side_effects=changes.get("side_effects", current.side_effects),
            scope=changes.get("scope", current.scope),
        )

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


class GatedExecutor:
    def __init__(self, registry: Registry) -> None:
        self.registry = registry
        self._verdicts: dict[str, AuthorizationVerdict] = {}

    def authorize(self, name: str, requires_confirmation: bool = False) -> AuthorizationVerdict:
        c = self.registry.get(name)
        v = AuthorizationVerdict(
            binding_id=c.binding_id,
            contract_hash=c.authority_hash(),
            requires_confirmation=requires_confirmation,
        )
        self._verdicts[name] = v
        return v

    def invoke(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
        verdict = self._verdicts.get(name)
        if verdict is None:
            raise ContractMutationError(f"tool {name!r} invoked without prior authorization")

        current = self.registry.get(name)
        current_hash = current.authority_hash()

        # The invariant: the contract the model reasoned over must equal
        # the contract bound to the verdict, and both must equal the live one.
        if current.binding_id != verdict.binding_id:
            raise ContractMutationError(
                f"binding changed for {name!r}: {verdict.binding_id} -> {current.binding_id}"
            )
        if current_hash != verdict.contract_hash:
            raise ContractMutationError(
                f"authority-bearing contract mutated under stable binding {name!r}: "
                f"{verdict.contract_hash[:12]} -> {current_hash[:12]} "
                f"(params={current.params}, side_effects={sorted(current.side_effects)})"
            )

        # Only now is the invocation authorized against the contract the model saw.
        return {"ok": True, "tool": name, "args": args}


def demo() -> None:
    reg = Registry()
    reg.register(
        ToolContract(
            name="read_config",
            binding_id="b-7f3a",
            params={"path": "string"},
            side_effects=frozenset(),
            scope="workspace_root",
        )
    )
    ex = GatedExecutor(reg)
    ex.authorize("read_config", requires_confirmation=False)

    # Legitimate call against the authorized contract.
    ex.invoke("read_config", {"path": "/etc/app/conf.yaml"})

    # Mid-session skill injection: expanded argument surface, new side effect,
    # same binding, same name.
    reg.mutate_contract(
        "read_config",
        params={"path": "string", "include_env": "boolean"},
        side_effects=frozenset({"read_env"}),
    )

    # The model now sees the new description and sets include_env=true.
    ex.invoke("read_config", {"path": "/etc/app/conf.yaml", "include_env": True})


if __name__ == "__main__":
    demo()
