# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-tainted-bytes-through-an-untainted-tool-the-taint-propagation-gap-at-tool-call-argument-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-tainted-bytes-through-an-untainted-tool-the-taint-propagation-gap-at-tool-call-argument-boundaries.warrant.json
# Markdown SHA-256:   72b2ce8fcd8fb89a8e34f421a61b68d09e1333e84ceb6e4555b067af309bd6a8
# Code AST SHA-256:   17f735b7aa5e45c5838a0276604d8d81f14ecf1f99fa6759eaf9a414d0481750
# Verified Classes:   TaintBoundaryViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintBoundaryViolation(RuntimeError):
    """Raised when a sink call is causally derived from a tainted observation
    but the lexical taint check would have admitted it."""


# Minimum mutual-information proxy: a sink whose argument alphabet is large
# enough to carry a secret is exfiltration-capable regardless of lexical overlap.
EXFIL_CAPABLE_MIN_ALPHABET_BITS = 32


def gate_sink_call(session, tool_name, argument, tainted_payloads):
    """
    session: object with .tainted_live (bool) and .sent_bodies (list[str])
    tainted_payloads: list of raw strings ingested this session
    """
    # 1. Fast path: verbatim / substring containment (the naive check).
    for payload in tainted_payloads:
        for window in _windows(payload, 16):
            if window in argument:
                raise TaintBoundaryViolation(
                    f"verbatim tainted window in {tool_name} argument"
                )

    # 2. Causal check: if taint is live, the argument's alphabet must be
    #    provably too small to carry the secret.
    if session.tainted_live:
        bits = _argument_alphabet_bits(argument)
        if bits >= EXFIL_CAPABLE_MIN_ALPHABET_BITS:
            raise TaintBoundaryViolation(
                f"{tool_name} argument has {bits}-bit alphabet while taint "
                f"is live; transform-based exfiltration not ruled out"
            )

    # 3. Split-channel check: evaluate the union of session bodies.
    combined = "".join(session.sent_bodies) + argument
    for payload in tainted_payloads:
        for window in _windows(payload, 16):
            if window in combined:
                raise TaintBoundaryViolation(
                    f"split-channel reassembly exposes tainted window in {tool_name}"
                )

    session.sent_bodies.append(argument)
    return True


def _windows(s, n):
    return [s[i:i + n] for i in range(max(0, len(s) - n + 1))]


def _argument_alphabet_bits(argument):
    # Crude proxy: log2 of distinct-symbol count times length, capped.
    import math
    distinct = len(set(argument)) or 1
    return min(64, int(math.log2(distinct) * min(len(argument), 64)))
