# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tainted-context-capability-laundering-across-a-tool-sandbox-boundary-when-a-secret-scoped-tool-s-output-re-enters-the-reasoni.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tainted-context-capability-laundering-across-a-tool-sandbox-boundary-when-a-secret-scoped-tool-s-output-re-enters-the-reasoni.warrant.json
# Markdown SHA-256:   b7f77f2caec821fc665e7826999d5ac1920be0dac603d5b040539f1633916b9f
# Code AST SHA-256:   ade4d3523020725dcba183ab1c501212dc873e7719f32178aa35496bb2c13e45
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a model-generated message derived from SECRET-tainted
    context is about to be used to select an egress-scoped tool without a
    verified declassification proof."""


SECRET = "SECRET"
PUBLIC = "PUBLIC"
_TAINT_RANK = {PUBLIC: 0, SECRET: 1}


def max_taint(labels):
    return max(labels, key=lambda t: _TAINT_RANK[t]) if labels else PUBLIC


def check_egress_allowed(
    context_labels,
    output_message_label,
    egress_tool_scope,
    declassification_proof,
):
    """
    Invariant: a message may drive an egress-scoped tool only if its
    effective taint (max of input-context taint and its own label) is
    PUBLIC, OR a verified declassification proof shows the secret bytes
    are absent from the message.
    """
    effective = max_taint(list(context_labels) + [output_message_label])

    if effective == PUBLIC:
        return True

    if declassification_proof is None:
        raise TaintLaunderingError(
            f"egress tool '{egress_tool_scope}' selected from a message whose "
            f"effective taint is {effective} (input-max propagation); no "
            f"declassification proof supplied. Refusing to launder secret "
            f"content through model paraphrase."
        )

    # Fail-closed: the proof must assert the exact secret bytes are absent.
    if not declassification_proof.get("secret_absent", False):
        raise TaintLaunderingError(
            "declassification proof does not assert secret_absent; "
            "treating message as still SECRET-tainted and blocking egress."
        )

    return True


def guarded_egress(
    agent_context_labels,
    model_output_message,
    egress_tool_scope,
    declassification_proof=None,
):
    # The model's own output inherits the max taint of what it read.
    output_label = max_taint(agent_context_labels)
    check_egress_allowed(
        agent_context_labels,
        output_label,
        egress_tool_scope,
        declassification_proof,
    )
    return f"egress permitted to {egress_tool_scope}"
