# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-track-prompt-injection-taint-across-tool-call-boundaries-when-the-taint-label-is-lost-at-the-serialization-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-track-prompt-injection-taint-across-tool-call-boundaries-when-the-taint-label-is-lost-at-the-serialization-seam.warrant.json
# Markdown SHA-256:   51cf51621d3477c0259fb367ce7ccd10fee26cdc53754245152b53c29d86b511
# Code AST SHA-256:   33e1a803051fbcd3bef274307ecd3e31b05f474ca8be8e016a55c757d58405f9
# Verified Classes:   Trust, Span, TaintViolation, SpanTable
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Trust(Enum):
    TRUSTED = 0
    UNTRUSTED = 1


@dataclass(frozen=True)
class Span:
    span_id: str
    start: int
    end: int
    source: Trust
    ancestry: frozenset = field(default_factory=frozenset)


class TaintViolation(RuntimeError):
    """Raised when a tool-call argument derives from an untrusted span
    without a capability warrant, or when a reference cannot be resolved
    (span table desynchronized after context compaction)."""


class SpanTable:
    def __init__(self) -> None:
        self._spans: dict[str, Span] = {}

    def register(self, span: Span) -> None:
        self._spans[span.span_id] = span

    def resolve(self, ref: str) -> Span:
        span = self._spans.get(ref)
        if span is None:
            # Compaction or truncation dropped the anchor: fail closed.
            raise TaintViolation(
                f"unresolvable span ref {ref!r}; span table desynchronized "
                f"(context compaction without re-anchoring)"
            )
        return span

    def join_taint(self, refs: list[str]) -> frozenset:
        """Union of ancestry across all referenced spans."""
        acc: set = set()
        for r in refs:
            s = self.resolve(r)
            acc |= s.ancestry
            if s.source is Trust.UNTRUSTED:
                acc.add(s.span_id)
        return frozenset(acc)


HIGH_BLAST_TOOLS = {"run_shell", "http_post", "write_file_outside_scratch"}


def gate_tool_call(
    table: SpanTable,
    tool: str,
    arg_refs: list[str],
    warrant: Optional[frozenset],
) -> None:
    """Enforce: tainted args require a warrant that untrusted content cannot mint."""
    taint = table.join_taint(arg_refs)
    if not taint:
        return  # fully trusted provenance
    if tool in HIGH_BLAST_TOOLS:
        if warrant is None or taint & warrant:
            # A warrant that shares ancestry with the tainted spans was itself
            # derived from untrusted content -> not a valid capability.
            raise TaintViolation(
                f"tool {tool!r} invoked with tainted args {sorted(taint)} "
                f"and no independent warrant; capability gate failed closed"
            )
    # Low-blast tools: allow but log taint for downstream audit.
    return


# --- demonstration of the laundering seam ---
table = SpanTable()
table.register(Span("T3.body", 0, 200, Trust.UNTRUSTED,
                    ancestry=frozenset({"T3.body"})))
# T4 summary is model-authored but inherits T3 taint via join:
table.register(Span("T4.summary", 200, 260, Trust.UNTRUSTED,
                    ancestry=frozenset({"T3.body", "T4.summary"})))

try:
    gate_tool_call(
        table,
        tool="run_shell",
        arg_refs=["T4.summary"],   # laundered through assistant turn
        warrant=None,
    )
except TaintViolation as e:
    print("blocked:", e)

# Unresolvable ref after compaction must also fail closed:
try:
    gate_tool_call(table, "edit_file", ["T5.arg"], frozenset({"cap:edit"}))
except TaintViolation as e:
    print("blocked:", e)
