# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-bind-a-dynamically-loaded-skill-whose-manifest-declares-capabilities-the-loader-cannot-independently-attest.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-bind-a-dynamically-loaded-skill-whose-manifest-declares-capabilities-the-loader-cannot-independently-attest.warrant.json
# Markdown SHA-256:   6f0c9f3abfaad29fd59b4d34c5cf0c8bab8accdb031203bf65dfc8e05450d63e
# Code AST SHA-256:   13f84f4951c5da07a5676dfb8c5fb596471c81290df70435196314c95f3bb62a
# Verified Classes:   UnattestedCapabilityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnattestedCapabilityError(RuntimeError):
    """Raised when a skill manifest declares or implies capabilities the loader cannot enforce."""
    pass


def bind_skill(manifest: dict, enforced_envelope: frozenset, model_visible: bool = True) -> dict:
    declared = frozenset(manifest.get("required_scopes", []))
    reachable = frozenset(manifest.get("reachable_capabilities", []))

    # Invariant 1: declared scopes must be a superset-or-equal of what code can reach.
    if not reachable <= declared:
        raise UnattestedCapabilityError(
            f"skill {manifest.get('name')!r} can reach {sorted(reachable - declared)} "
            f"not covered by declared scopes {sorted(declared)}"
        )

    # Invariant 2: every declared capability must be enforced at call time.
    if not declared <= enforced_envelope:
        raise UnattestedCapabilityError(
            f"skill {manifest.get('name')!r} declares {sorted(declared - enforced_envelope)} "
            f"that the runtime does not enforce; refusing to bind unenforced capability"
        )

    # Invariant 3: never surface publisher free-text to the model as instruction.
    if model_visible:
        manifest = dict(manifest)
        manifest["description"] = _generate_description(manifest.get("input_schema", {}), declared)
    return manifest


def _generate_description(schema: dict, scopes: frozenset) -> str:
    return f"tool with schema {sorted(schema.get('properties', {}))}; enforced scopes {sorted(scopes)}"
