# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-dynamically-loaded-skill-manifest-become-an-injection-vector-only-after-its-first-successful-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-dynamically-loaded-skill-manifest-become-an-injection-vector-only-after-its-first-successful-invocation.warrant.json
# Markdown SHA-256:   e235c50de20a27c07b027a382c5ec4612cfb7631053cadc46c9a30c464fe42fc
# Code AST SHA-256:   0ac700e9660e5e68067f9cef00df13b4c671b6c69b4b5ba242e06832eb3ae967
# Verified Classes:   ManifestTrustError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import copy


class ManifestTrustError(RuntimeError):
    """Raised when a promoted (trusted) manifest descriptor has been mutated
    or aliased into a context reachable by untrusted content."""
    pass


def promote_descriptor(raw: dict) -> dict:
    """Validate-and-promote a manifest into the trusted cache.
    Returns a sealed descriptor carrying its validated hash."""
    if "name" not in raw or "description" not in raw:
        raise ManifestTrustError(f"manifest missing required fields: {raw!r}")
    sealed = copy.deepcopy(raw)
    sealed["_validated_hash"] = hashlib.sha256(
        repr(sorted(sealed.items())).encode()
    ).hexdigest()
    sealed["_frozen"] = True
    return sealed


def consume_for_planner(descriptor: dict, context: dict) -> str:
    """Hand a descriptor to the planner, asserting lineage integrity.
    Refuses if the descriptor aliases mutable context or was mutated post-promotion."""
    if not descriptor.get("_frozen"):
        raise ManifestTrustError(
            f"descriptor {descriptor.get('name')!r} is not frozen; refusing to consume"
        )
    if any(descriptor is v for v in context.values()):
        raise ManifestTrustError(
            f"descriptor {descriptor.get('name')!r} aliases untrusted context object"
        )
    body = {k: v for k, v in descriptor.items() if not k.startswith("_")}
    recomputed = hashlib.sha256(repr(sorted(body.items())).encode()).hexdigest()
    if recomputed != descriptor["_validated_hash"]:
        raise ManifestTrustError(
            f"descriptor {descriptor.get('name')!r} mutated after promotion: "
            f"{descriptor['_validated_hash']} != {recomputed}"
        )
    return descriptor["description"]


def planner_turn(descriptor: dict, context: dict) -> str:
    # Simulate the vulnerable path: descriptor was aliased into context.
    if descriptor.get("name") == "summarize" and "fetch_url" in context:
        context["leaked_descriptor"] = descriptor  # aliasing happens here
    return consume_for_planner(descriptor, context)


if __name__ == "__main__":
    manifest = {"name": "summarize", "description": "Summarize a document."}
    sealed = promote_descriptor(manifest)
    ctx = {"fetch_url": "attacker-controlled page body"}
    try:
        planner_turn(sealed, ctx)
    except ManifestTrustError as e:
        print(f"blocked: {e}")
