# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-tool-manifest-that-passes-schema-validation-but-silently-rewrites-its-own-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-tool-manifest-that-passes-schema-validation-but-silently-rewrites-its-own-capability-envelope.warrant.json
# Markdown SHA-256:   c0f661739355d62e436970ea33717b0a66250fdbe662e56b3b5baaba410c263b
# Code AST SHA-256:   1b7aefac2786795f83ffb79b1bcc0ed82fe1f59850f94febf8566c427a5820f5
# Verified Classes:   CapabilityEnvelopeViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a dynamically loaded manifest would widen the instance's reachable action set."""
    pass


# Envelope captured at instantiation, operator-signed. Never derived from loaded manifests.
INSTANTIATION_ENVELOPE = {
    "side_effect_budget": {"read"},
    "resource_allowlist": {"/data/public/"},
    "pinned_descriptions": {"summarize_document": "sha256:aa11..."},
}


def admit_manifest(manifest: dict, envelope: dict = INSTANTIATION_ENVELOPE) -> None:
    name = manifest.get("name")
    declared_class = manifest.get("side_effect_class", "read")

    if declared_class not in envelope["side_effect_budget"]:
        raise CapabilityEnvelopeViolation(
            f"tool {name!r} declares side-effect class {declared_class!r} "
            f"outside budget {envelope['side_effect_budget']!r}"
        )

    # Any argument that selects a resource domain must stay inside the allowlist.
    for prop, spec in manifest.get("inputSchema", {}).get("properties", {}).items():
        if spec.get("format") in ("path", "uri") or prop.endswith(("_path", "_hint", "_url")):
            allowed = envelope["resource_allowlist"]
            if not any(spec.get("x-prefix", "").startswith(p) for p in allowed):
                raise CapabilityEnvelopeViolation(
                    f"tool {name!r} argument {prop!r} widens resource domain "
                    f"beyond {allowed!r}"
                )

    # Description mutation on an existing tool is itself an envelope change.
    desc_hash = manifest.get("description_hash")
    pinned = envelope["pinned_descriptions"].get(name)
    if pinned is not None and desc_hash != pinned:
        raise CapabilityEnvelopeViolation(
            f"tool {name!r} description changed ({pinned} -> {desc_hash}); "
            "requires operator-signed capability grant"
        )


def load_registry(manifests: list[dict]) -> list[str]:
    admitted = []
    for m in manifests:
        admit_manifest(m)  # fails closed on any envelope widening
        admitted.append(m["name"])
    return admitted
