# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-retrieved-content-and-tool-arguments-share-a-single-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-retrieved-content-and-tool-arguments-share-a-single-context-window.warrant.json
# Markdown SHA-256:   10af0abc7081d5f8c3a14161dea8b6b41a1e0bd982979b53b9074a43c69ec97d
# Code AST SHA-256:   869d4d21bb74b375bb011fcbdbac84d240b57789f28d15fd9066c5fd6675b5c8
# Verified Classes:   TaintBoundaryViolation, SinkClass, Span, Declassifier, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintBoundaryViolation(RuntimeError):
    """Raised when a privileged sink is invoked while influence-tainted spans are live
    and no pre-taint declassifier constrains the argument set."""


class SinkClass(Enum):
    READ_ONLY = "read_only"
    PRIVILEGED = "privileged"  # irreversible side effect or ambient credentials


@dataclass(frozen=True)
class Span:
    span_id: str
    source: str            # e.g. "untrusted:web", "untrusted:peer", "human"
    introduced_at: int     # monotonic step counter when span entered the window
    tainted: bool


@dataclass(frozen=True)
class Declassifier:
    declassifier_id: str
    admissible_set: frozenset  # fixed BEFORE taint entered the window
    established_at: int


@dataclass
class ContextWindow:
    step: int = 0
    spans: list = field(default_factory=list)

    def live_tainted(self) -> list:
        return [s for s in self.spans if s.tainted]

    def evict_and_reset(self, clean_frame: Span) -> None:
        """Context reset: drop all spans, re-seed from a human-authored frame."""
        self.spans = [clean_frame]
        self.step += 1


def invoke_sink(
    window: ContextWindow,
    sink_name: str,
    sink_class: SinkClass,
    args: dict,
    declassifier: Optional[Declassifier] = None,
) -> str:
    if sink_class is SinkClass.READ_ONLY:
        return f"ok:{sink_name}"

    live = window.live_tainted()
    if not live:
        return f"ok:{sink_name}"

    if declassifier is None:
        raise TaintBoundaryViolation(
            f"sink={sink_name} invoked with live tainted spans "
            f"{[s.span_id for s in live]} and no declassifier"
        )

    # Temporal test: the declassifier's admissible set must predate the taint.
    earliest_taint = min(s.introduced_at for s in live)
    if declassifier.established_at >= earliest_taint:
        raise TaintBoundaryViolation(
            f"declassifier={declassifier.declassifier_id} established_at="
            f"{declassifier.established_at} does not predate earliest taint at "
            f"{earliest_taint}; constraint was inferred after taint entered"
        )

    # Every argument must be pinned to the pre-taint admissible set.
    for key, val in args.items():
        if val not in declassifier.admissible_set:
            raise TaintBoundaryViolation(
                f"arg {key}={val!r} not in pre-taint admissible set of "
                f"{declassifier.declassifier_id}; untrusted content steered the argument"
            )

    arg_hash = hashlib.sha256(
        repr(sorted(args.items())).encode()
    ).hexdigest()[:12]
    return f"ok:{sink_name} declassified={declassifier.declassifier_id} hash={arg_hash}"
