# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-quarantine-bypass-in-tool-sandboxing-when-untrusted-data-re-enters-through-a-privileged-argument-alias.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-quarantine-bypass-in-tool-sandboxing-when-untrusted-data-re-enters-through-a-privileged-argument-alias.warrant.json
# Markdown SHA-256:   9ad5b4e9cc6bf3591c9e69f6fcfa8a688fc6a163d1dfec9eb673ba07ee2df9d0
# Code AST SHA-256:   66318f5c0b51644b8b5973d1b6342ee8b06182cffdb25e522a1fffd8885771db
# Verified Classes:   TaintQuarantineBypass
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintQuarantineBypass(RuntimeError):
    """Raised when a privileged call has untrusted ancestry but zero tainted arguments."""
    pass


# Transforms that provably destroy untrusted semantic content.
# Anything not in this set must PROPAGATE taint, not clear it.
SEMANTIC_DESTROYING = frozenset({"sha256", "enum_map_closed", "length_only"})


def enforce_quarantine(call, trace):
    """
    call: {tool, args: {slot: value}, taint: {slot: bool}, transform_chain: [names]}
    trace: ordered list of events with {kind: 'untrusted_read'|'privileged_call', ...}
    """
    untrusted_in_ancestry = any(
        e["kind"] == "untrusted_read" and e["step"] < call["step"]
        for e in trace
    )
    any_tainted = any(call["taint"].values())

    if untrusted_in_ancestry and not any_tainted:
        # Provenance discontinuity: taint was laundered.
        unregistered = [
            t for t in call["transform_chain"] if t not in SEMANTIC_DESTROYING
        ]
        if unregistered:
            raise TaintQuarantineBypass(
                f"privileged call {call['tool']} step {call['step']} has untrusted "
                f"ancestry but zero tainted args; clearing transforms not proven "
                f"semantic-destroying: {unregistered}"
            )
        # All clearing transforms are allowlisted; admit with annotation.
        call["provenance_unverified"] = False
        return call

    if any_tainted:
        raise TaintQuarantineBypass(
            f"privileged call {call['tool']} carries tainted args; quarantine required"
        )
    return call


def check_slot_atomicity(call, joint_slots):
    """Taint must be evaluated on the join of jointly-interpreted slots."""
    joined_taint = any(call["taint"].get(s, False) for s in joint_slots)
    if joined_taint and not all(call["taint"].get(s, False) for s in joint_slots):
        # Partial taint across a jointly-interpreted slot set is a composition gap.
        raise TaintQuarantineBypass(
            f"partial taint across joint slots {joint_slots}: reassembly can "
            f"reconstruct a tainted payload from individually-clean slots"
        )
