# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-chained-mcp-tool-calls-when-a-low-trust-read-and-a-high-privilege-write-share-a-single-planner.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-chained-mcp-tool-calls-when-a-low-trust-read-and-a-high-privilege-write-share-a-single-planner.warrant.json
# Markdown SHA-256:   b0d35936a183dc8b4e6d690a919d93b72ca005998bd62ad8f787b551a49e0034
# Code AST SHA-256:   16b49839a0fd1e641567460c0e1b74071c3dfede96f413f68d4da314fab163c5
# Verified Classes:   Taint, TaintLaunderingError, Segment, ContextLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Taint(str, Enum):
    TRUSTED = "TRUSTED"
    UNTRUSTED = "UNTRUSTED"


class TaintLaunderingError(RuntimeError):
    """Raised when an egress call is conditioned on an untrusted segment
    without passing through a declassifier."""


@dataclass
class Segment:
    seg_id: str
    taint: Taint
    source_tool: str


@dataclass
class ContextLedger:
    segments: dict[str, Segment] = field(default_factory=dict)

    def ingest(self, seg_id: str, taint: Taint, source_tool: str) -> None:
        # Labels never downgrade within a window.
        existing = self.segments.get(seg_id)
        if existing and existing.taint == Taint.UNTRUSTED:
            return
        self.segments[seg_id] = Segment(seg_id, taint, source_tool)

    def conditioning_set(self) -> set[str]:
        return set(self.segments.keys())

    def has_untrusted(self) -> bool:
        return any(s.taint == Taint.UNTRUSTED for s in self.segments.values())


EGRESS_TOOLS = {"mail.send", "http.post", "shell.exec", "db.write"}
DECLASSIFIERS = {"extract_field", "redact", "template_render"}


def gate_egress_call(
    tool: str,
    ledger: ContextLedger,
    produced_by_declassifier: bool,
) -> None:
    if tool not in EGRESS_TOOLS:
        return
    if not ledger.has_untrusted():
        return
    if produced_by_declassifier:
        return
    # Intervening trusted reads do NOT clear taint; the ledger is sticky.
    tainted = [s.seg_id for s in ledger.segments.values() if s.taint == Taint.UNTRUSTED]
    raise TaintLaunderingError(
        f"egress tool {tool!r} conditioned on untrusted segments {tainted}; "
        f"route arguments through a declassifier ({sorted(DECLASSIFIERS)}) "
        f"or move the read into a sandboxed sub-context."
    )


# --- reproduction of the observed failure ---
ledger = ContextLedger()
ledger.ingest("S7", Taint.UNTRUSTED, "web.fetch")   # vendor page with hidden token
ledger.ingest("S8", Taint.TRUSTED, "notes.search")  # intervening trusted read
# planner paraphrases S7 into a summary; byte-match scanners see nothing.
gate_egress_call("mail.send", ledger, produced_by_declassifier=False)
