# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-skill-manifest-that-validates-but-resolves-to-a-different-callable-than-the-one-authorized.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-skill-manifest-that-validates-but-resolves-to-a-different-callable-than-the-one-authorized.warrant.json
# Markdown SHA-256:   db23e3a0d94e798828c047aaf68d5670282363603c839dc22d8408732630be49
# Code AST SHA-256:   98b08407e1e7aece3421db5c9fc12af3007a5ff18a5aabb7a7c40a748adc5665
# Verified Classes:   ResolutionIntegrityError, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResolutionIntegrityError(RuntimeError):
    """Raised when a signed manifest resolves to a callable other than the authorized one."""


@dataclass(frozen=True)
class SignedManifest:
    tool_name: str
    entrypoint: str          # e.g. "skills.summarize:run"
    signed_origin_hash: str | None  # sha256 of resolved module at signing time, if bound
    signature_valid: bool


def resolve_origin_hash(entrypoint: str, import_root: str) -> str:
    # In a real runtime this imports under a pinned root and hashes the module file.
    module_path = f"{import_root}/{entrypoint.split(':')[0].replace('.', '/')}.py"
    with open(module_path, "rb") as fh:
        return hashlib.sha256(fh.read()).hexdigest()


def authorize_and_resolve(
    manifest: SignedManifest,
    import_root: str,
    untrusted_namespace_components: list[str],
) -> str:
    if not manifest.signature_valid:
        raise ResolutionIntegrityError(
            f"manifest for {manifest.tool_name!r} failed signature verification"
        )

    # Signature is valid, but that only attests to the declaration, not resolution.
    if manifest.signed_origin_hash is None:
        raise ResolutionIntegrityError(
            f"manifest for {manifest.tool_name!r} names {manifest.entrypoint!r} "
            "but binds no origin hash; resolution integrity is unproven"
        )

    for component in untrusted_namespace_components:
        if component in import_root:
            raise ResolutionIntegrityError(
                f"resolution for {manifest.tool_name!r} passes through untrusted "
                f"namespace component {component!r}; name may be shadowed"
            )

    actual_hash = resolve_origin_hash(manifest.entrypoint, import_root)
    if actual_hash != manifest.signed_origin_hash:
        raise ResolutionIntegrityError(
            f"manifest for {manifest.tool_name!r} is signed for origin "
            f"{manifest.signed_origin_hash} but resolved to {actual_hash}; "
            "signed name and executing callable diverge"
        )

    return manifest.entrypoint
