# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-drops-taint-labels-across-a-checkpoint-resume-boundary-in-a-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-drops-taint-labels-across-a-checkpoint-resume-boundary-in-a-tool-sandbox.warrant.json
# Markdown SHA-256:   c872dcea8bb7b78507fd818aa2679f550b489290314e7cb7bdfe0984c0d4b402
# Code AST SHA-256:   de4b42c928d63c0e651b9d948f98c9c35e971f2082f3019286892281fbd4486e
# Verified Classes:   TaintRestoreError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintRestoreError(RuntimeError):
    """Raised when a resumed instance cannot prove its taint set was preserved."""
    pass


TAINT_SCHEMA_V1 = 1


def resume_sandbox_state(checkpoint: dict) -> set[str]:
    """
    Restore the taint set for a resumed instance.

    Invariant: a checkpoint that cannot prove taint conservation resumes
    in the UNKNOWN state, which blocks all sinks. Absence of taint metadata
    is NOT evidence of cleanliness.
    """
    schema_version = checkpoint.get("schema_version")
    taint = checkpoint.get("taint_set")

    if schema_version is None or schema_version < TAINT_SCHEMA_V1:
        # Legacy or malformed checkpoint: cannot prove conservation.
        return {"UNKNOWN:resumed"}

    if taint is None:
        # Schema claims support but field is missing: corruption.
        raise TaintRestoreError(
            f"checkpoint schema_version={schema_version} declares taint_set "
            f"but field is absent; refusing to resume as clean"
        )

    if not isinstance(taint, (set, list, tuple)):
        raise TaintRestoreError(
            f"taint_set has unexpected type {type(taint).__name__}; "
            f"refusing to resume"
        )

    return set(taint)


def dispatch_sink_tool(checkpoint: dict, tool_name: str, args: dict) -> dict:
    """
    Dispatch a sink tool only if the restored taint set is empty.
    UNKNOWN:resumed blocks all sinks until an audited clear.
    """
    SINK_TOOLS = {"http_post", "send_email", "shell_exec"}
    if tool_name not in SINK_TOOLS:
        return {"status": "dispatched", "tool": tool_name}

    taint = resume_sandbox_state(checkpoint)

    if taint:
        raise TaintRestoreError(
            f"sink tool {tool_name!r} blocked: taint set non-empty after resume "
            f"({sorted(taint)}); requires audited de-taint before egress"
        )

    return {"status": "dispatched", "tool": tool_name, "args": args}
