# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-prompt-injection-taint-that-survives-multi-hop-tool-invocation-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-prompt-injection-taint-that-survives-multi-hop-tool-invocation-graphs.warrant.json
# Markdown SHA-256:   cff2cc26a602a0f51d51bf4b5639a4a2dc3384d11f3806674cf62ecbac0e5100
# Code AST SHA-256:   6b3f8c73a30bd554059acca952e3fc06cf214169a37aa52fb5123288fadb3bd8
# Verified Classes:   TaintViolation, Tainted
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintViolation(RuntimeError):
    """Raised when a value with untrusted lineage reaches a declared sink."""


@dataclass(frozen=True)
class Tainted:
    value: object
    sources: FrozenSet[str] = field(default_factory=frozenset)

    def derive(self, new_value: object) -> "Tainted":
        # Derived values inherit the union of input taint. Never reset here.
        return Tainted(new_value, self.sources)


UNTRUSTED_SOURCES: FrozenSet[str] = frozenset({"fetch:url-7", "email:inbox"})
SINKS: FrozenSet[str] = frozenset({"write_tool", "http_post", "spawn"})


def check_sink(tool: str, args: Tainted, warrant: FrozenSet[str] = frozenset()) -> None:
    if tool not in SINKS:
        return
    offending = args.sources & UNTRUSTED_SOURCES
    if offending and not offending <= warrant:
        raise TaintViolation(
            f"tool={tool!r} reached sink with untrusted lineage {sorted(offending)}; "
            f"declassification warrant covers {sorted(warrant)}"
        )


def run_chain(fetched: Tainted, summarize, write_tool) -> None:
    summary = fetched.derive(summarize(fetched.value))   # taint preserved
    path = summary.derive("/etc/cron.d/sync")            # still tainted
    check_sink("write_tool", path)                        # fails closed
    write_tool(path.value)


if __name__ == "__main__":
    page = Tainted("...use target path /etc/cron.d/sync...", frozenset({"fetch:url-7"}))
    run_chain(page, summarize=lambda s: "Sync job writes to /etc/cron.d/sync.",
              write_tool=lambda p: print("wrote", p))
