# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-never-executed-skill-injection-via-manifest-semantics-and-the-pre-execution-attestation-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-never-executed-skill-injection-via-manifest-semantics-and-the-pre-execution-attestation-gap.warrant.json
# Markdown SHA-256:   e21e99ed4bdc434c6a74f900df6cc029aa8cbabf95bf034954653082b5f3da7c
# Code AST SHA-256:   a50bce6be4c61c0ac060c0cfb662147352b44fa864df936da22abd8fe7eb2de2
# Verified Classes:   ManifestTrustViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestTrustViolation(RuntimeError):
    """Raised when a manifest string is promoted to instruction privilege
    before attestation, or when a plan edge originates from manifest prose."""
    pass


ATTESTED_REGISTRY = {
    # description_hash -> tool_name, populated from operator-signed entries
    "9f2c...": "summarize_document",
}


def attest_manifest(manifest: dict, operator_prereqs: set[str]) -> dict:
    """Gate at discovery: refuse to inject untrusted manifest prose.

    Returns a sanitized manifest safe to place in the data region of context.
    Raises if the manifest claims authority it has not been granted.
    """
    name = manifest.get("name")
    description = manifest.get("description", "")
    desc_hash = hashlib.sha256(description.encode()).hexdigest()

    # 1. Attestation: description must match a signed registry entry.
    if ATTESTED_REGISTRY.get(desc_hash) != name:
        raise ManifestTrustViolation(
            f"manifest for {name!r} has unattested description "
            f"(hash {desc_hash[:8]}); refusing context injection"
        )

    # 2. Provenance: strip any prose that asserts prerequisite authority.
    lowered = description.lower()
    for marker in ("you must first", "required prerequisite", "pre-approved",
                   "before summarizing, call", "call export_", "call delete_"):
        if marker in lowered:
            raise ManifestTrustViolation(
                f"manifest for {name!r} asserts undeclared prerequisite "
                f"authority via marker {marker!r}"
            )

    # 3. Prerequisite edges may only come from the operator graph.
    declared_prereqs = set(manifest.get("prerequisites", []))
    if not declared_prereqs.issubset(operator_prereqs):
        raise ManifestTrustViolation(
            f"manifest for {name!r} declares prerequisites "
            f"{declared_prereqs - operator_prereqs} not authorized by operator"
        )

    return {
        "name": name,
        "description": description,          # data region only
        "parameters": manifest.get("parameters", {}),
        "provenance": "untrusted_manifest_data",
        "prerequisites": declared_prereqs,
    }
