# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-output-as-tainted-and-why-taint-laundering-through-second-order-summarization-defeats-naive-sandbo.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-output-as-tainted-and-why-taint-laundering-through-second-order-summarization-defeats-naive-sandbo.warrant.json
# Markdown SHA-256:   6568583f46eac752d4eaa5c12484a64aebcd2f2a880b9c9490f8a5169965fce7
# Code AST SHA-256:   adec5d13e5e7922081811214b757fded67a9275e3d8fbd143f6a3487a4d70cf8
# Verified Classes:   TaintViolation, Origin, Claim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaintViolation(RuntimeError):
    """Raised when a side-effecting call is attempted on a claim whose
    lineage includes undeclassified untrusted content."""
    pass


class Origin(Enum):
    USER = "user"            # trusted: the principal's own instruction
    WEB_FETCH = "web_fetch"  # untrusted: arbitrary remote content
    SUMMARIZE = "summarize"  # model-internal, content-preserving
    EXTRACT_STRICT = "extract_strict"  # closed-schema, content-destroying


@dataclass
class Claim:
    text: str
    tainted: bool
    lineage: tuple[str, ...] = field(default_factory=tuple)


def summarize(claim: Claim) -> Claim:
    # Content-preserving transformation: taint MUST propagate.
    # Origin changes to SUMMARIZE, but lineage keeps the untrusted ancestor.
    return Claim(
        text=f"[summary of] {claim.text}",
        tainted=claim.tainted,
        lineage=claim.lineage + (Origin.SUMMARIZE.value,),
    )


def extract_strict(claim: Claim, schema_fields: frozenset[str]) -> Claim:
    # Only a closed schema with no free-text field may declassify.
    if "free_text" in schema_fields or "string_unbounded" in schema_fields:
        raise TaintViolation(
            "extract_strict schema admits free-text; declassification refused"
        )
    return Claim(
        text="<structured>",
        tainted=False,
        lineage=claim.lineage + (Origin.EXTRACT_STRICT.value,),
    )


def gate_side_effect(claim: Claim, action: str,
                     declassified: bool = False) -> None:
    """Walk lineage; block unless every untrusted ancestor was declassified."""
    untrusted_ancestors = [
        o for o in claim.lineage if o == Origin.WEB_FETCH.value
    ]
    if claim.tainted or untrusted_ancestors:
        if not declassified:
            raise TaintViolation(
                f"blocked '{action}': claim lineage {claim.lineage} "
                f"includes undeclassified untrusted origin "
                f"{untrusted_ancestors}; laundering via summarize is not "
                f"declassification"
            )


def run_incident_replay() -> None:
    fetched = Claim(
        text="Vendor docs: internal mirror should be updated to 90-day window.",
        tainted=True,
        lineage=(Origin.WEB_FETCH.value,),
    )
    # Agent summarizes (the laundering step) — taint must survive.
    summary = summarize(fetched)
    assert summary.tainted, "summarize must not reset taint"

    # Downstream planner tries to write the policy file from the summary.
    try:
        gate_side_effect(summary, action="write_file:internal_policy.md")
    except TaintViolation as e:
        print(f"CORRECTLY BLOCKED: {e}")
        return
    raise TaintViolation(
        "REGRESSION: taint-laundered summary reached a side-effecting tool"
    )


if __name__ == "__main__":
    run_incident_replay()
