# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-propagation-across-a-resumed-tool-call-chain-and-why-the-sandbox-boundary-alone-is-insufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-propagation-across-a-resumed-tool-call-chain-and-why-the-sandbox-boundary-alone-is-insufficient.warrant.json
# Markdown SHA-256:   5e9cad5e70845edc5f9b082070ea81acd607eb00355d4b52aad1bbbe6b338e69
# Code AST SHA-256:   f8fdbe1a535de7e831c5aef15ef8984bd89d9b272951df83d36035b2eb9ae8b2
# Verified Classes:   TaintLaunderingError, TaintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when an outbound call's argument is downstream of tainted content
    that the current ledger cannot account for (encoding, paraphrase, or resume gap)."""


@dataclass
class TaintLedger:
    # content-addressed node -> set of upstream tainted node hashes
    nodes: dict[str, frozenset[str]] = field(default_factory=dict)
    tainted: set[str] = field(default_factory=set)

    @staticmethod
    def _h(payload: str) -> str:
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()

    def record(self, payload: str, upstream: list[str] | None = None, tainted: bool = False) -> str:
        h = self._h(payload)
        ups = frozenset(upstream or [])
        self.nodes[h] = ups
        if tainted or any(u in self.tainted for u in ups):
            self.tainted.add(h)
        return h

    def is_tainted(self, payload: str) -> bool:
        return self._h(payload) in self.tainted

    def downstream_tainted(self, payload: str) -> bool:
        h = self._h(payload)
        seen, stack = set(), [h]
        while stack:
            cur = stack.pop()
            if cur in self.tainted:
                return True
            if cur in seen:
                continue
            seen.add(cur)
            stack.extend(self.nodes.get(cur, frozenset()))
        return False


def gate_outbound(ledger: TaintLedger, arg: str, normalized_forms: list[str]) -> None:
    """Fail closed if any normalized form of the outbound argument is downstream
    of tainted content. Called AFTER encoding normalization, BEFORE the call."""
    for form in normalized_forms:
        if ledger.downstream_tainted(form):
            raise TaintLaunderingError(
                f"outbound argument {arg[:32]!r} is downstream of tainted content "
                f"via form {form[:32]!r}; refusing call"
            )


def resume_and_send(checkpoint: dict, ledger: TaintLedger, email_body: str) -> None:
    # On resume, the tainted source may be evicted from context while its
    # paraphrase survives. If the ledger was not serialized with the checkpoint,
    # the resumed instance believes it is clean. Fail closed on that gap.
    if checkpoint.get("taint_ledger") != ledger.nodes:
        raise TaintLaunderingError(
            "resume gap: checkpoint taint ledger does not match live ledger; "
            "refusing to proceed with outbound call"
        )
    # Normalize encodings the model may have applied before checking.
    import base64
    forms = [email_body]
    try:
        forms.append(base64.b64decode(email_body + "==").decode("utf-8", "ignore"))
    except Exception:
        pass
    gate_outbound(ledger, email_body, forms)
