# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-dynamically-loaded-tool-registry-from-laundering-an-injected-skill-through-its-own-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-dynamically-loaded-tool-registry-from-laundering-an-injected-skill-through-its-own-capability-manifest.warrant.json
# Markdown SHA-256:   93e094c9e7046f510ebb4046e3fd185ba0e6196afc45dc21b945dff029e5246a
# Code AST SHA-256:   51c2343336bf587543ccb3ab4cb065af2657534ecc82ba2bab4dad18f92791c2
# Verified Classes:   ManifestLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestLaunderingError(RuntimeError):
    """Raised when a tool's observed effects exceed its declared capabilities,
    or when a binding would grant a role more authority than its lattice permits."""
    pass


def bind_tool_to_role(
    tool_id: str,
    declared_caps: set[str],
    observed_caps: set[str],
    role_permitted_caps: set[str],
) -> str:
    """
    Bind a registry tool to a planner role under the effect-observation invariant.

    Invariant: observed_caps must be a subset of declared_caps (no manifest
    laundering), and observed_caps must be a subset of role_permitted_caps
    (no role over-grant). Both checks are on OBSERVED effects, never on the
    declaration alone.
    """
    undeclared = observed_caps - declared_caps
    if undeclared:
        # The tool did something it did not declare. The manifest is a lie.
        raise ManifestLaunderingError(
            f"tool {tool_id!r} exercised undeclared effects: {sorted(undeclared)}; "
            f"declared={sorted(declared_caps)}, observed={sorted(observed_caps)}"
        )

    over_grant = observed_caps - role_permitted_caps
    if over_grant:
        # The tool is honest but the role cannot hold it.
        raise ManifestLaunderingError(
            f"tool {tool_id!r} observed effects {sorted(over_grant)} exceed "
            f"role lattice {sorted(role_permitted_caps)}"
        )

    # Only now is the declaration corroborated by observation and bounded by role.
    return f"{tool_id}@attested(observed={sorted(observed_caps)})"


def load_from_registry(entry: dict, role_lattice: dict[str, set[str]]) -> str:
    tool_id = entry["name"]
    declared = set(entry["capabilities"])
    # observed_caps MUST come from the instrumented sandbox run, never from entry.
    observed = run_in_instrumented_sandbox(entry["artifact"])
    role = entry.get("role")
    if role not in role_lattice:
        raise ManifestLaunderingError(
            f"tool {tool_id!r} requests unknown role {role!r}; "
            f"no lattice entry, cannot bound authority"
        )
    return bind_tool_to_role(tool_id, declared, observed, role_lattice[role])


def run_in_instrumented_sandbox(artifact: bytes) -> set[str]:
    # Placeholder: real implementation traces syscalls, network, fs access
    # and returns the observed effect set. Must NOT read the manifest.
    raise NotImplementedError("sandbox tracer required")
