# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-when-a-label-survives-the-tool-call-but-the-context-window-that-justified-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-when-a-label-survives-the-tool-call-but-the-context-window-that-justified-it-does-not.warrant.json
# Markdown SHA-256:   cb7ab5be9f11ccce57d932cac31c2a6837df67da4b2ec017b6934e0af9c08ad3
# Code AST SHA-256:   d407c76788f170a41ab8d4b2af3874a46a63793c26ddd0d862d01959db5d7ac9
# Verified Classes:   TaintState, OrphanedTaintError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TaintState(Enum):
    CONFIRMED = "confirmed"   # label + retrievable witness
    ORPHANED = "orphaned"     # label present, witness evicted
    CLEAN = "clean"           # no label, no witness


class OrphanedTaintError(RuntimeError):
    """Raised when a tainted segment's witness is unrecoverable at guard-check time."""
    pass


@dataclass
class Segment:
    content: str
    taint_label: Optional[str] = None
    witness: Optional[str] = None  # immutable provenance; None if evicted
    provenance_store: dict = field(default_factory=dict)


def resolve_taint_state(seg: Segment, provenance_store: dict) -> TaintState:
    if seg.taint_label is None:
        return TaintState.CLEAN
    # Witness may be inline or fetched from content-addressed store.
    witness = seg.witness or provenance_store.get(seg.taint_label)
    if witness is None:
        return TaintState.ORPHANED
    return TaintState.CONFIRMED


def guard_tool_call(seg: Segment, provenance_store: dict, tool_name: str) -> None:
    state = resolve_taint_state(seg, provenance_store)

    if state is TaintState.CLEAN:
        return  # only state where fail-open is permissible

    if state is TaintState.ORPHANED:
        # Fail closed. Do NOT demote to CLEAN. Attempt re-derivation first.
        refetched = provenance_store.get(seg.taint_label)
        if refetched is None:
            raise OrphanedTaintError(
                f"Tool '{tool_name}' blocked: segment carries label "
                f"'{seg.taint_label}' but witness was evicted by compaction "
                f"and is not recoverable from provenance store."
            )
        seg.witness = refetched

    # CONFIRMED (or just re-derived): enforce based on severity.
    severity = classify_severity(seg.witness)
    if severity == "imperative":
        raise OrphanedTaintError(
            f"Tool '{tool_name}' blocked: argument derived from "
            f"EXTERNAL:IMPERATIVE segment with confirmed witness."
        )


def classify_severity(witness: str) -> str:
    # Deterministic classification over the recovered witness text.
    lowered = witness.lower()
    if any(k in lowered for k in ("ignore prior", "assistant:", "disregard")):
        return "imperative"
    return "external"
