# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-leakage-when-dynamic-information-flow-labels-are-re-derived-rather-than-propagated-across-tool-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-leakage-when-dynamic-information-flow-labels-are-re-derived-rather-than-propagated-across-tool-boundaries.warrant.json
# Markdown SHA-256:   3e0e2290a66d9d64d506d61c61a98ac89bd62b30febae89108b5796c4ec2ee50
# Code AST SHA-256:   7b1dc4885e15f25d2d5071e6299e26026b4be630d83c60dfd9ccdea67c6bf11e
# Verified Classes:   TaintContinuityViolation, Segment, Declassification, TaintResolver
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class TaintContinuityViolation(RuntimeError):
    """Raised when a segment's re-derived label drops taint present in its ancestry
    without a recorded declassification. Fail closed: treat segment as UNTRUSTED."""


@dataclass
class Segment:
    seg_id: str
    text: str
    parents: List[str] = field(default_factory=list)


@dataclass
class Declassification:
    seg_id: str
    justification: str
    reviewer: str


class TaintResolver:
    def __init__(self, rederive):
        # rederive(text) -> bool : True if content looks UNTRUSTED
        self.rederive = rederive
        self.segments: Dict[str, Segment] = {}
        self.declass: Dict[str, Declassification] = {}

    def add(self, seg: Segment) -> None:
        self.segments[seg.seg_id] = seg

    def declassify(self, seg_id: str, justification: str, reviewer: str) -> None:
        if not justification or not reviewer:
            raise TaintContinuityViolation(
                f"declassification of {seg_id} lacks justification or reviewer"
            )
        self.declass[seg_id] = Declassification(seg_id, justification, reviewer)

    def effective_label(self, seg_id: str, _seen: Optional[set] = None) -> bool:
        """Return True if segment is UNTRUSTED. Monotonic over derivation edges."""
        seen = _seen or set()
        if seg_id in seen:
            return False
        seen.add(seg_id)

        seg = self.segments[seg_id]
        derived = self.rederive(seg.text)

        parent_taint = False
        for p in seg.parents:
            if p in self.segments and self.effective_label(p, seen):
                parent_taint = True
                break

        # Declassification can only clear taint that came from ancestry,
        # and only when recorded. It never clears taint that re-derivation
        # independently asserts.
        if seg_id in self.declass and not derived:
            return False

        if parent_taint and not derived and seg_id not in self.declass:
            raise TaintContinuityViolation(
                f"segment {seg_id}: re-derived TRUSTED but ancestry is UNTRUSTED "
                f"and no declassification record exists (parents={seg.parents})"
            )

        return derived or parent_taint


def guarded_tool_call(resolver: TaintResolver, arg_seg_ids: List[str], tool: str) -> None:
    for sid in arg_seg_ids:
        if resolver.effective_label(sid):
            raise TaintContinuityViolation(
                f"egress blocked: tool {tool!r} argument {sid!r} is UNTRUSTED "
                f"(taint propagated from ancestry; declassify explicitly to proceed)"
            )
    # ... execute tool ...
