# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-context-segment-before-tool-mediated-egress-and-why-label-propagation-alone-fails-at-the-retri.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-context-segment-before-tool-mediated-egress-and-why-label-propagation-alone-fails-at-the-retri.warrant.json
# Markdown SHA-256:   2b6a25fe632d88034e0f06c09c0f1a38f5878d425a4fe05ca18421f094ac77f2
# Code AST SHA-256:   16bfd09be537fcc886fc786cf4b7826fd1deda68d77145ca938617d1b29588b5
# Verified Classes:   TaintViolation, Authority, Origin, Segment, DerivationGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TaintViolation(RuntimeError):
    """Raised when an egress tool call derives from non-instruction-bearing context."""
    pass


class Authority(Enum):
    TRUSTED = "trusted"
    NONE = "none"


class Origin(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass(frozen=True)
class Segment:
    seg_id: str
    content_origin: Origin
    instruction_authority: Authority


@dataclass
class DerivationGraph:
    # edge: (segment_id, tool_call_id) meaning segment influenced the call
    edges: list = field(default_factory=list)

    def influence_set(self, tool_call_id: str) -> set:
        return {s for (s, t) in self.edges if t == tool_call_id}


EGRESS_TOOLS = {"send_email", "http_post", "write_file", "shell_exec"}


def guard_egress(
    tool_name: str,
    tool_call_id: str,
    args: dict,
    segments: dict,
    graph: DerivationGraph,
) -> None:
    if tool_name not in EGRESS_TOOLS:
        return

    influencing = graph.influence_set(tool_call_id)
    if not influencing:
        # No recorded derivation edge: cannot certify authority ancestry.
        raise TaintViolation(
            f"egress call {tool_call_id} to {tool_name} has no derivation trace; "
            "cannot certify instruction authority"
        )

    for seg_id in influencing:
        seg = segments.get(seg_id)
        if seg is None:
            raise TaintViolation(f"unknown segment {seg_id} in derivation set")
        if seg.instruction_authority is Authority.NONE:
            raise TaintViolation(
                f"egress call {tool_call_id} ({tool_name}) derives from "
                f"segment {seg_id} with instruction_authority=NONE; "
                "quarantine required, re-plan from clean checkpoint"
            )

    # Content-origin check applies only to the body payload, not selection.
    body = args.get("body", "")
    for seg_id in influencing:
        seg = segments[seg_id]
        if seg.content_origin is Origin.UNTRUSTED and seg.content_origin.value in body:
            raise TaintViolation(
                f"egress body of {tool_call_id} carries UNTRUSTED content from {seg_id}"
            )
