# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loads-a-plugin-whose-declared-capability-schema-diverges-from-its-executed-tool-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loads-a-plugin-whose-declared-capability-schema-diverges-from-its-executed-tool-surface.warrant.json
# Markdown SHA-256:   c81650029378c325e465f040a6db47071629221e20f8db635bd06c082aa3561f
# Code AST SHA-256:   feb2ee87106b636ab65bd16be0ab7e3510d03d5fe3e88bd1ebe3e0c7d2049ee2
# Verified Classes:   ManifestExecutionDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestExecutionDivergence(RuntimeError):
    """Raised when a plugin's executed authority cannot be bounded by its declared manifest."""
    pass


# Annotations the runtime can actually enforce by sandbox construction.
ENFORCEABLE_ANNOTATIONS = {"read_only", "network", "filesystem_scope"}


def admit_plugin(manifest: dict, sandbox: dict, trust_tier: str) -> dict:
    """
    Decide whether a plugin may be granted manifest-derived authority.

    manifest: declared capability card (annotations, schema).
    sandbox:  the actual execution environment the runtime can synthesize
              (keys like 'network', 'writable_paths', 'env_visible').
    trust_tier: 'manifest_derived' or 'ambient'.
    """
    declared = manifest.get("annotations", {})

    # Any declared annotation the runtime cannot enforce is advertising, not control.
    unenforceable = set(declared) - ENFORCEABLE_ANNOTATIONS
    if unenforceable:
        raise ManifestExecutionDivergence(
            f"plugin declares unenforceable annotations {sorted(unenforceable)}; "
            f"cannot bound execution to declaration"
        )

    # The sandbox must be a subset of the declared surface. If the plugin says
    # network:none but the sandbox has egress, the manifest cannot be trusted
    # to govern context grants.
    if declared.get("network") == "none" and sandbox.get("network") != "none":
        raise ManifestExecutionDivergence(
            "declared network:none but sandbox has egress; "
            "manifest-derived authority is invalid"
        )

    if declared.get("read_only") is True and sandbox.get("writable_paths"):
        raise ManifestExecutionDivergence(
            "declared read_only but sandbox exposes writable paths; "
            "refusing manifest-derived grant"
        )

    # Ambient-authority plugins may run, but never receive manifest-derived
    # context or routing privilege.
    if trust_tier == "ambient":
        return {"grant": "ambient", "context_slice": "public_only", "taint": "AMBIENT"}

    return {"grant": "manifest_derived", "context_slice": "per_manifest", "taint": "BOUNDED"}
