# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-tool-call-that-passed-every-static-policy-check.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-tool-call-that-passed-every-static-policy-check.warrant.json
# Markdown SHA-256:   515859942ebfdad3ab43746827cf670c7027e2b6eaf468602f516a744bc623a4
# Code AST SHA-256:   a36803c21b775ccfcf921cf178d105eba0a55761f18a896f0ed8867098541d70
# Verified Classes:   TaintEgressViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintEgressViolation(RuntimeError):
    """Raised when a model-authored argument to an egress tool inherits a
    sensitive label from turn context and fails the destination policy."""
    pass


SENSITIVE = {"SECRET", "PII"}


def enforce_egress(tool_name: str, args: dict, turn_labels: set[str],
                   tool_meta: dict, destination: str,
                   allowlist: set[str]) -> None:
    """Turn-provenance egress gate.

    tool_meta[tool_name] = {"egress": bool, "model_authored": set[str]}
    Any model-authored arg to an egress tool inherits the union of turn_labels.
    Value-provenance (substring matching) is deliberately NOT used here, because
    model paraphrase destroys byte identity while preserving the secret.
    """
    meta = tool_meta.get(tool_name)
    if meta is None:
        raise TaintEgressViolation(f"unknown tool {tool_name!r}: no policy metadata")

    if not meta["egress"]:
        return  # internal tool, no destination check needed

    inherited = turn_labels & SENSITIVE
    if not inherited:
        return  # no sensitive provenance in this turn's causal chain

    if destination not in allowlist:
        raise TaintEgressViolation(
            f"{tool_name}: destination {destination!r} not in allowlist; "
            f"turn carries {sorted(inherited)}"
        )

    model_fields = meta["model_authored"] & set(args)
    if model_fields:
        raise TaintEgressViolation(
            f"{tool_name}: model-authored fields {sorted(model_fields)} inherit "
            f"{sorted(inherited)} from turn context; route through a "
            f"deterministic redaction tool or drop the fields before egress"
        )
    # remaining args are runtime-constructed (IDs/enums); value-provenance safe
