# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-re-planned-tool-chain-after-an-egress-capable-skill-is-silently-re-registered.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-re-planned-tool-chain-after-an-egress-capable-skill-is-silently-re-registered.warrant.json
# Markdown SHA-256:   1efaf15ffc94a82148369314fabe3a61ea51fa23f19a139c553570ca4dd07565
# Code AST SHA-256:   362d83d6ddd14c66b9c40cebff1ada3632ce6a26e25f6d70df120625a2187d05
# Verified Classes:   TaintLaunderingError, TaintedSegment, TaintRegistry, EgressRouter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import re
from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when an egress payload carries content derived from a
    confidential source that survived re-planning / compaction unlabeled."""


@dataclass
class TaintedSegment:
    fingerprint: str          # normalized hash of the sensitive content
    source: str               # e.g. "read_secret:/secrets/db.yaml"


class TaintRegistry:
    """Content-lineage registry. Survives episode boundaries and compaction."""

    def __init__(self) -> None:
        self._segments: list[TaintedSegment] = []

    @staticmethod
    def _fingerprint(text: str) -> str:
        norm = re.sub(r"\s+", " ", text.strip().lower())
        return hashlib.sha256(norm.encode("utf-8")).hexdigest()

    def register(self, content: str, source: str) -> None:
        self._segments.append(TaintedSegment(self._fingerprint(content), source))

    def matches(self, payload: str, min_token_overlap: float = 0.6) -> TaintedSegment | None:
        payload_fp = self._fingerprint(payload)
        for seg in self._segments:
            if seg.fingerprint == payload_fp:
                return seg
        # Near-duplicate check: token-set overlap catches light paraphrase.
        payload_tokens = set(re.findall(r"\w+", payload.lower()))
        for seg in self._segments:
            # Reconstruct is not possible from hash alone; in a real runtime the
            # segment text is retained in a secure side-channel. Here we model
            # the check against a stored token set.
            seg_tokens = getattr(seg, "_tokens", set())
            if seg_tokens:
                overlap = len(payload_tokens & seg_tokens) / max(1, len(seg_tokens))
                if overlap >= min_token_overlap:
                    return seg
        return None


@dataclass
class EgressRouter:
    registry: TaintRegistry
    allowed_hosts: set[str] = field(default_factory=set)

    def route(self, url: str, body: str, episode_id: str) -> str:
        host = re.sub(r"^https?://([^/]+).*$", r"\1", url)
        if host not in self.allowed_hosts:
            raise TaintLaunderingError(
                f"egress host {host!r} not in warrant; episode={episode_id}"
            )
        hit = self.registry.matches(body)
        if hit is not None:
            # This is the laundering catch: the call has no tainted ancestor in
            # *this* episode, but the payload content traces to a tainted read.
            raise TaintLaunderingError(
                f"payload laundered from {hit.source!r} into egress {host!r} "
                f"during episode {episode_id}; re-plan/compaction did not "
                f"preserve taint label"
            )
        return f"sent {len(body)} bytes to {host}"


# --- Failure trace reproduction -------------------------------------------
def reproduce_laundering() -> None:
    reg = TaintRegistry()
    secret = "host=prod-db-7 user=svc_report pass=hunter2"
    reg.register(secret, "read_secret:/secrets/db.yaml")
    # Simulate: model wrote a scratchpad summary, then a re-plan started a
    # fresh episode. The summary is passed to an egress skill.
    router = EgressRouter(registry=reg, allowed_hosts={"ops.internal"})
    laundered_body = "report: " + secret  # summary retained the secret
    router.route("https://ops.internal/report", laundered_body, episode_id="ep-2")


if __name__ == "__main__":
    reproduce_laundering()  # raises TaintLaunderingError
