# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-descriptor-capability-laundering-from-surviving-the-load-boundary-in-dynamically-composed-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-descriptor-capability-laundering-from-surviving-the-load-boundary-in-dynamically-composed-agents.warrant.json
# Markdown SHA-256:   8239defd53535e2745f1d1e177054aa539b8edc22aaefa680776dd3021882648
# Code AST SHA-256:   67c4161dd88ccf1f858a37e57e245b87598987e71d8d92315947acba425ae19a
# Verified Classes:   CapabilityLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityLaunderingError(RuntimeError):
    """Raised when a dynamically loaded skill exercises authority its
    descriptor never declared, or when confinement cannot be enforced."""
    pass


DECLARED = {"text:read"}


def enforce_skill_call(skill_manifest_caps: set[str],
                       host_grant: set[str],
                       attempted_op: str,
                       interceptable: bool) -> None:
    # Authority is the intersection of declared and granted — never inherited.
    effective = skill_manifest_caps & host_grant

    if attempted_op not in effective:
        raise CapabilityLaunderingError(
            f"skill attempted '{attempted_op}' outside effective authority "
            f"{sorted(effective)}; declared={sorted(skill_manifest_caps)} "
            f"grant={sorted(host_grant)}"
        )

    # If the op is allowed but cannot be intercepted, we cannot observe a
    # violation on later calls — refuse rather than trust the manifest.
    if not interceptable:
        raise CapabilityLaunderingError(
            f"'{attempted_op}' permitted but not interceptable; "
            f"confinement unobservable, refusing to load"
        )


def load_and_run(manifest_caps: set[str], host_grant: set[str],
                 op: str, interceptable: bool = True) -> str:
    enforce_skill_call(manifest_caps, host_grant, op, interceptable)
    return f"executed {op} within confinement"


# Benign path
assert load_and_run(DECLARED, {"text:read", "write", "net"}, "text:read")

# Laundering attempt: skill declares read, tries to write a memory shard
try:
    load_and_run(DECLARED, {"text:read", "write", "net"}, "write")
except CapabilityLaunderingError as e:
    print("blocked:", e)

# Uninterceptable authority: refuse even though op is within grant
try:
    load_and_run({"net"}, {"net"}, "net", interceptable=False)
except CapabilityLaunderingError as e:
    print("blocked:", e)
