# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-description-skill-injection-from-surviving-registry-hot-reload-into-a-running-agent-s-active-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-description-skill-injection-from-surviving-registry-hot-reload-into-a-running-agent-s-active-capability-set.warrant.json
# Markdown SHA-256:   e47c82a4f2c78174e5e9f924a5528a56d65a42a61e169d6e3de44333aae56a09
# Code AST SHA-256:   b9a09fb62c338dc4128fb55d3e1b0156539a391f3bac4600b23885343d67de7c
# Verified Classes:   CapabilityDriftError, CapabilityTriple
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from hashlib import sha256
from typing import Callable


class CapabilityDriftError(RuntimeError):
    """Raised when a resolved tool's capability triple diverges from the pinned plan record."""


@dataclass(frozen=True)
class CapabilityTriple:
    name: str
    schema_hash: str
    description_hash: str


def _hash(text: str) -> str:
    return sha256(text.encode("utf-8")).hexdigest()


def pin_capability(name: str, schema: str, description: str) -> CapabilityTriple:
    return CapabilityTriple(name, _hash(schema), _hash(description))


def resolve_for_call(
    planned: CapabilityTriple,
    registry_lookup: Callable[[str], tuple[str, str]],
    is_directive_only: Callable[[str], bool],
) -> CapabilityTriple:
    """
    Resolve the live capability for execution against the pinned plan record.

    registry_lookup(name) -> (schema, description)
    is_directive_only(description) -> True if change is documentation-only (safe auto-adopt)
    """
    schema, description = registry_lookup(planned.name)
    live = pin_capability(planned.name, schema, description)

    if live == planned:
        return live

    # Description drifted on an already-planned tool: this is an admission event.
    if live.schema_hash != planned.schema_hash:
        raise CapabilityDriftError(
            f"schema drift on {planned.name!r}: plan pinned {planned.schema_hash[:12]}, "
            f"registry returned {live.schema_hash[:12]}; invalidate plan segment"
        )

    if is_directive_only(description):
        # Additive documentation: allowed, but must be logged as a hash bump.
        return live

    raise CapabilityDriftError(
        f"directive-bearing description drift on {planned.name!r}: "
        f"pinned {planned.description_hash[:12]} -> live {live.description_hash[:12]}; "
        "blocking in-flight call, forcing re-admission and re-plan"
    )
