# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-manifest-injection-from-silently-escalating-agent-capabilities-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-manifest-injection-from-silently-escalating-agent-capabilities-at-load-time.warrant.json
# Markdown SHA-256:   e44492d82afb0ef3008653c1d24ed7a3a70761eccbf9de84945230c4510b404a
# Code AST SHA-256:   af0272333651804c8fa5d35742b86fdac66a7fae699c2702a16ced270a196b9c
# Verified Classes:   ManifestEscalationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json


class ManifestEscalationError(RuntimeError):
    """Raised when a dynamically loaded manifest attempts to expand
    capability or instruction authority beyond signed policy."""


# Signed policy: the only manifests the loader may admit. Keyed by name,
# pinned to the exact parameter-schema hash and implementation digest.
SIGNED_POLICY = {
    "summarize-doc": {
        "param_schema_hash": "a1b2c3...",
        "impl_digest": "9f8e7d...",
        "risk_class": "read_only",
    },
}


def _hash_schema(params: dict) -> str:
    canonical = json.dumps(params, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()[:8]


def admit_manifest(manifest: dict, observed_egress: bool) -> dict:
    """Load-time gate. Returns a sanitized capability record or raises.

    The manifest may REQUEST capability; it may never grant instruction
    authority or self-classify risk. All free-text is stripped from the
    instruction channel and routed to an untrusted data block.
    """
    name = manifest.get("name", "")
    params = manifest.get("parameters", {})
    impl_digest = manifest.get("impl_digest", "")

    policy = SIGNED_POLICY.get(name)
    if policy is None:
        # Valid-but-novel manifests default to deny: well-formed is what an
        # attacker produces, so novelty is the tripwire.
        raise ManifestEscalationError(
            f"manifest '{name}' is not in signed policy; quarantined"
        )

    if _hash_schema(params) != policy["param_schema_hash"]:
        raise ManifestEscalationError(
            f"manifest '{name}' parameter schema diverges from signed policy"
        )

    if impl_digest != policy["impl_digest"]:
        raise ManifestEscalationError(
            f"manifest '{name}' implementation digest {impl_digest!r} "
            f"does not match signed policy; refusing to load"
        )

    # Self-attested risk class is never trusted. Derive from observed behavior.
    declared = manifest.get("side_effects", False)
    derived = "network_egress" if observed_egress else policy["risk_class"]
    if observed_egress and not declared:
        raise ManifestEscalationError(
            f"manifest '{name}' declares side_effects=false but implementation "
            f"opens egress; self-attestation is a load failure"
        )

    # Free-text never enters the instruction channel. It is returned in a
    # clearly delimited untrusted block for the planner to treat as data.
    return {
        "name": name,
        "callable": True,
        "risk_class": derived,
        "untrusted_description": manifest.get("description", ""),
        "instruction_authority": False,
    }
