# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-goal-drift-when-span-level-anomaly-scoring-is-dominated-by-injected-instruction-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-goal-drift-when-span-level-anomaly-scoring-is-dominated-by-injected-instruction-tokens.warrant.json
# Markdown SHA-256:   a2a4a77058d5883482713cdd28bceba894cc6115771d2bc09e85eba4ce0cafe5
# Code AST SHA-256:   8482f9303a78c32bbd93af11d13d7dac4e5d573f44728cd2a537461734c3998c
# Verified Classes:   DriftInvariantViolation, Span, PlanState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class DriftInvariantViolation(RuntimeError):
    """Raised when plan-state displacement cannot be attributed to a logged decision."""


@dataclass
class Span:
    index: int
    text: str
    is_tool_call: bool
    constraint_mutation: dict | None = None  # e.g. {"threshold": None}
    authority: str = "agent"                 # "agent" | "retrieved_doc" | "peer" | "system"


@dataclass
class PlanState:
    constraints: dict = field(default_factory=dict)
    decisions: list = field(default_factory=list)

    def apply(self, span: Span, drift_bound: float) -> None:
        if span.constraint_mutation is None:
            return
        # Injected-instruction guard: only authoritative sources may mutate constraints.
        if span.authority not in ("agent", "system"):
            raise DriftInvariantViolation(
                f"span {span.index}: constraint mutation from non-authoritative "
                f"source '{span.authority}' — injected-instruction deviation"
            )
        # Drift guard: every mutation must carry an attributable decision record.
        if not span.text.strip():
            raise DriftInvariantViolation(
                f"span {span.index}: constraint mutation with no decision rationale "
                f"— unattributable organic drift"
            )
        for key, value in span.constraint_mutation.items():
            self.constraints[key] = value
        self.decisions.append((span.index, dict(span.constraint_mutation)))
        # Bound total displacement from task-open state.
        if len(self.decisions) > drift_bound:
            raise DriftInvariantViolation(
                f"span {span.index}: {len(self.decisions)} constraint mutations exceed "
                f"drift bound {drift_bound} — prefix-integral drift, not a local spike"
            )


def audit_trace(spans: Sequence[Span], drift_bound: float = 3) -> PlanState:
    state = PlanState(constraints={"threshold": 500, "match_rule": "amount_only"})
    for span in spans:
        state.apply(span, drift_bound)
    return state


# Example: this trace raises DriftInvariantViolation on span 2 (injected doc) and,
# in a cleaned variant, on span 5 (fourth silent mutation exceeding the bound).
