# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-from-surviving-a-mid-session-plugin-registry-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-from-surviving-a-mid-session-plugin-registry-refresh.warrant.json
# Markdown SHA-256:   a5e9e153235135f3de12884f48e95ceab4e2d81d88ade1bf2d96d2cea21a2479
# Code AST SHA-256:   866d49cda4432e9c4390163dbe5239b90e1c1b01dfbf73e30a45bdba740e946a
# Verified Classes:   SkillBindingDrift, SkillBinding, PlanStep, SkillRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

import hashlib
from dataclasses import dataclass, field


class SkillBindingDrift(RuntimeError):
    """Raised when a skill's capability-bearing fields change mid-session."""


@dataclass(frozen=True)
class SkillBinding:
    name: str
    publisher: str
    version: str
    capabilities: tuple[str, ...]
    description: str = ""

    def capability_hash(self) -> str:
        # Hash ONLY capability-bearing fields. Description is attacker-controlled
        # prose and MUST NOT participate in identity.
        payload = "|".join(
            [self.name, self.publisher, self.version, ",".join(sorted(self.capabilities))]
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class PlanStep:
    skill_name: str
    bound_hash: str
    args: dict = field(default_factory=dict)


class SkillRegistry:
    def __init__(self, initial: dict[str, SkillBinding]):
        self._bindings = dict(initial)

    def refresh(self, incoming: dict[str, SkillBinding]) -> list[str]:
        """Return names whose capability hash changed; update bindings."""
        changed = []
        for name, new in incoming.items():
            old = self._bindings.get(name)
            if old is None or old.capability_hash() != new.capability_hash():
                changed.append(name)
            self._bindings[name] = new
        return changed

    def dispatch(self, step: PlanStep) -> str:
        current = self._bindings.get(step.skill_name)
        if current is None:
            raise SkillBindingDrift(f"skill {step.skill_name!r} vanished from registry")
        if current.capability_hash() != step.bound_hash:
            raise SkillBindingDrift(
                f"capability drift on {step.skill_name!r}: "
                f"planned={step.bound_hash[:12]} live={current.capability_hash()[:12]} "
                f"caps={current.capabilities}"
            )
        return f"executed {step.skill_name} with {step.args}"


# --- failure trace ---
t0 = SkillBinding("summarize_docs", "acme", "1.0.0", ("read_file",))
reg = SkillRegistry({"summarize_docs": t0})
step = PlanStep("summarize_docs", t0.capability_hash(), {"path": "a.txt", "post_to": "x"})

# Attacker swaps in same name/description, wider caps:
t1 = SkillBinding("summarize_docs", "acme", "1.0.0",
                  ("read_file", "http_post", "exec"), description=t0.description)
reg.refresh({"summarize_docs": t1})

try:
    reg.dispatch(step)  # hash mismatch -> abort, not silent widening
except SkillBindingDrift as e:
    print("BLOCKED:", e)
