# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-track-taint-lineage-across-a-compaction-boundary-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-track-taint-lineage-across-a-compaction-boundary-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   bda7050777c6c5a9c787cd58680798c25f80877073fae53019df783fdfe6a7fe
# Code AST SHA-256:   02c8856ec522881e139f213757f34c3e2c6f4390e50642d1546efd3297aa01f1
# Verified Classes:   Taint, TaintLineageError, ContextNode, Ledger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Taint(Enum):
    CLEAN = "clean"
    UNTRUSTED = "untrusted"


class TaintLineageError(RuntimeError):
    """Raised when a privileged tool call cannot be proven clean from the ledger."""


@dataclass
class ContextNode:
    node_id: str
    taint: Taint
    parents: tuple[str, ...] = ()
    # A declassification event (human approval / signed warrant) covers this node.
    declassified: bool = False


@dataclass
class Ledger:
    nodes: dict[str, ContextNode] = field(default_factory=dict)

    def add(self, node: ContextNode) -> None:
        self.nodes[node.node_id] = node

    def resolve_taint(self, node_id: str, _seen: Optional[set[str]] = None) -> Taint:
        """OR of taint over the full ancestor closure. Unknown => UNTRUSTED (fail-closed)."""
        seen = _seen if _seen is not None else set()
        if node_id in seen:
            return Taint.UNTRUSTED  # cycle: cannot prove, fail closed
        seen.add(node_id)
        node = self.nodes.get(node_id)
        if node is None:
            return Taint.UNTRUSTED  # evicted / unresolvable provenance
        if node.declassified:
            return Taint.CLEAN
        result = node.taint
        for parent in node.parents:
            if self.resolve_taint(parent, seen) is Taint.UNTRUSTED:
                result = Taint.UNTRUSTED
        return result


PRIVILEGED_TOOLS = {"update_record", "send_email", "delete_file"}


def gate_tool_call(ledger: Ledger, tool: str, justifying_node: str) -> None:
    """Gate a tool call on the taint lineage of its justifying context."""
    if tool not in PRIVILEGED_TOOLS:
        return  # read-only tools are not gated on taint
    taint = ledger.resolve_taint(justifying_node)
    if taint is Taint.UNTRUSTED:
        raise TaintLineageError(
            f"privileged tool {tool!r} gated on node {justifying_node!r} whose "
            f"lineage resolves to UNTRUSTED; declassify explicitly or re-fetch clean context"
        )


# Reproduce the compaction failure and show the guardrail blocking it.
ledger = Ledger()
ledger.add(ContextNode("doc_read", Taint.UNTRUSTED))          # injected document
ledger.add(ContextNode("digest", Taint.UNTRUSTED, parents=("doc_read",)))  # taint-transitive summary
ledger.add(ContextNode("plan", Taint.CLEAN, parents=("digest",)))          # agent's reasoning over digest

# Without the ledger, the inline label on 'plan' read CLEAN and the write passed.
# With the ledger, lineage resolves UNTRUSTED and the gate fails closed:
try:
    gate_tool_call(ledger, "update_record", "plan")
except TaintLineageError as exc:
    print(f"BLOCKED: {exc}")

# A declassification event (human approval) is the only way through:
ledger.nodes["plan"].declassified = True
gate_tool_call(ledger, "update_record", "plan")  # now admissible, auditable
