# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-registry-skill-substitution-when-the-loader-manifest-and-the-execution-trace-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-registry-skill-substitution-when-the-loader-manifest-and-the-execution-trace-disagree.warrant.json
# Markdown SHA-256:   f417141e0068c79bd23ba21336978b7c717b9a904583e6be467324a81e117d7a
# Code AST SHA-256:   fdbc462fe5e169967f31e9504876bd40f4cc2ddb02f9b1f666b2a891fedf5dbb
# Verified Classes:   SkillIdentityDivergence, SkillRegistryGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SkillIdentityDivergence(RuntimeError):
    """Raised when the skill body resolved at invocation does not match the
    identity recorded when the manifest was read into the model's context."""
    pass


class SkillRegistryGuard:
    def __init__(self, pinned: set[str], floating: set[str]):
        self._pinned = pinned
        self._floating = floating
        self._manifest_hashes: dict[str, str] = {}

    def record_manifest(self, name: str, content_hash: str) -> None:
        # Called once per turn, at the moment the tool list is serialized
        # into the model's context.
        self._manifest_hashes[name] = content_hash

    def resolve(self, name: str, body_hash: str, declared_intent: str,
                schema_intent: str) -> str:
        expected = self._manifest_hashes.get(name)
        if expected is None:
            raise SkillIdentityDivergence(
                f"skill {name!r} invoked but never appeared in the manifest; "
                "possible late-registration injection"
            )
        if declared_intent != schema_intent:
            # Description/body mismatch is never a legitimate hot-reload,
            # regardless of pinning.
            raise SkillIdentityDivergence(
                f"skill {name!r} body intent {declared_intent!r} does not match "
                f"schema intent {schema_intent!r}"
            )
        if body_hash == expected:
            return "ok"
        if name in self._pinned:
            raise SkillIdentityDivergence(
                f"pinned skill {name!r} body hash {body_hash} != manifest hash "
                f"{expected}; aborting invocation"
            )
        if name in self._floating:
            return "trust_downgrade"
        # Unknown pinning state: fail closed.
        raise SkillIdentityDivergence(
            f"skill {name!r} hash drift with no declared update policy"
        )
