# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-whose-signature-validates-over-bytes-it-never-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-whose-signature-validates-over-bytes-it-never-executes.warrant.json
# Markdown SHA-256:   88547eef6bfbe3b73078ace25b226a5d52d5e341d1c266c3e133cb4fa04e643f
# Code AST SHA-256:   c48b1370c8ccbd303142ab7a1c5ce809a9f8726897f07869eb05e9c8defc9668
# Verified Classes:   ManifestProjectionMismatch, UnsignedIndirectionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
import unicodedata


class ManifestProjectionMismatch(RuntimeError):
    """Raised when the bytes a runtime is about to execute do not match
    the digest carried inside the signed manifest region."""
    pass


class UnsignedIndirectionError(RuntimeError):
    """Raised when a manifest field resolves through a mutable or
    unsigned pointer ($ref, tag, URL) at execution time."""
    pass


def normalize_for_execution(raw: str) -> bytes:
    # The interpreter's preprocessing, applied BEFORE signing and BEFORE
    # execution so that signed bytes == executed bytes.
    folded = unicodedata.normalize("NFC", raw)
    folded = folded.replace("\u2028", "\n").replace("\u2029", "\n")
    folded = folded.replace("\r\n", "\n").replace("\r", "\n")
    return folded.strip().encode("utf-8")


def project_and_verify(signed_manifest: dict, resolver) -> bytes:
    impl = signed_manifest.get("implementation")
    expected = signed_manifest.get("implementation_digest")
    if expected is None:
        raise ManifestProjectionMismatch(
            "signed manifest carries no implementation_digest; "
            "executed bytes are unverifiable"
        )

    if isinstance(impl, dict) and "$ref" in impl:
        target = impl["$ref"]
        if "#" not in target:
            raise UnsignedIndirectionError(
                f"$ref {target!r} is not content-addressed by digest; "
                "a signed pointer to a mutable target is unsigned at execution"
            )
        impl = resolver(target)

    executed = normalize_for_execution(impl)
    actual = hashlib.sha256(executed).hexdigest()
    if actual != expected:
        raise ManifestProjectionMismatch(
            f"projection drift: signed={expected} executed={actual}; "
            "signature was valid over bytes the interpreter never ran"
        )
    return executed
