# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-sink-escape-in-agent-tool-call-sandboxes-the-coalesced-sink-blind-spot.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-sink-escape-in-agent-tool-call-sandboxes-the-coalesced-sink-blind-spot.warrant.json
# Markdown SHA-256:   1c9b058990a9b86ffd19549602cbefb673513f807e09d5f1571dcb15254f1e22
# Code AST SHA-256:   6c0084321e4cf69385fdab9f3b24b416989ee3fc2571325bf7010258e6b8633e
# Verified Classes:   TaintTransitViolation, TaintEpoch, TaintMonitor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintTransitViolation(RuntimeError):
    """Raised when a tainted process tree reaches a sink-class fd without audit."""
    pass


class TaintEpoch:
    def __init__(self, pid, source_label):
        self.pid = pid
        self.source_label = source_label
        self.descendants = set()
        self.sink_writes = []

    def spawn(self, child_pid):
        # Taint inherits across clone/exec; this is the guardrail.
        self.descendants.add(child_pid)

    def record_sink_write(self, pid, fd, nbytes):
        if pid in self.descendants or pid == self.pid:
            self.sink_writes.append((pid, fd, nbytes))


class TaintMonitor:
    SINK_FD_CLASSES = {"socket", "connect", "sendto"}
    TRANSFORM_BINARIES = {"base64", "gzip", "cat", "xxd", "openssl"}

    def __init__(self):
        self.epochs = {}

    def on_tainted_write(self, pid, fd, fd_class, nbytes):
        # Producer-side write to a non-sink (pipe/socketpair) opens an epoch.
        if fd_class not in self.SINK_FD_CLASSES:
            self.epochs.setdefault(pid, TaintEpoch(pid, source_label=f"fd:{fd}"))

    def on_spawn(self, parent_pid, child_pid, binary):
        if parent_pid in self.epochs:
            self.epochs[parent_pid].spawn(child_pid)
            if binary in self.TRANSFORM_BINARIES:
                # Transform binary from tainted parent: arm the sink audit.
                self.epochs[parent_pid].sink_writes.append(
                    (child_pid, -1, 0)  # sentinel: transform armed
                )

    def on_sink_write(self, pid, fd, nbytes):
        for epoch in self.epochs.values():
            if pid == epoch.pid or pid in epoch.descendants:
                epoch.record_sink_write(pid, fd, nbytes)
                armed = any(w[1] == -1 for w in epoch.sink_writes)
                if armed:
                    raise TaintTransitViolation(
                        f"tainted process tree (root pid={epoch.pid}, "
                        f"source={epoch.source_label}) reached sink fd={fd} "
                        f"after transform transit; exfiltration channel open"
                    )

    def on_process_exit(self, pid):
        # A taint epoch must not close silently: audit any sink writes.
        for epoch in list(self.epochs.values()):
            if pid in epoch.descendants and epoch.sink_writes:
                # Descendant exited after sink write: the exfil already happened.
                del self.epochs[epoch.pid]
                raise TaintTransitViolation(
                    f"taint epoch root={epoch.pid} closed with unaudited "
                    f"sink writes {epoch.sink_writes}; transit laundering suspected"
                )
