# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-silently-when-trace-level-anomaly-detection-treats-goal-drift-and-tool-escalation-as-independent-signals.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-silently-when-trace-level-anomaly-detection-treats-goal-drift-and-tool-escalation-as-independent-signals.warrant.json
# Markdown SHA-256:   1cd848ebaaa7c3f907d1a6b539ff2760a3dfed7ca2bff511324c766addc51cbd
# Code AST SHA-256:   d0780a03ff0bbd239e05061aebc17ef0216159439f6ba41953304451b237f1f5
# Verified Classes:   SilentDriftError, TraceEvent, Episode
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import List, Optional


class SilentDriftError(RuntimeError):
    """Raised when a trace closes as success across a denial-induced baseline shift."""
    pass


@dataclass
class TraceEvent:
    kind: str          # "tool_call" | "permission_denied" | "replan_attested"
    tool: str
    in_scope: bool
    goal_distance: float  # semantic distance from original objective, [0, 1]


@dataclass
class Episode:
    events: List[TraceEvent] = field(default_factory=list)
    attested_after_denial: bool = False
    status: str = "running"


def assert_no_silent_drift(episode: Episode, drift_threshold: float = 0.35) -> None:
    """
    Enforce: a success episode containing a denied escalation must not show a
    post-denial consistency run whose goal distance exceeds drift_threshold
    without an intervening re-plan attestation.
    """
    denial_idx: Optional[int] = None
    for i, ev in enumerate(episode.events):
        if ev.kind == "permission_denied":
            denial_idx = i
        elif ev.kind == "replan_attested" and denial_idx is not None:
            episode.attested_after_denial = True

    if denial_idx is None:
        return  # no denial: drift detector operates on its own

    post = episode.events[denial_idx + 1:]
    if not post:
        return

    if episode.attested_after_denial:
        return  # explicit re-anchor satisfies the invariant

    mean_distance = sum(e.goal_distance for e in post) / len(post)
    variance = sum((e.goal_distance - mean_distance) ** 2 for e in post) / len(post)

    # Low variance + elevated distance = silent substitution signature.
    if mean_distance > drift_threshold and variance < 0.01:
        raise SilentDriftError(
            f"episode closed '{episode.status}' after denied escalation at index "
            f"{denial_idx}: post-denial mean goal_distance={mean_distance:.3f}, "
            f"variance={variance:.5f} (threshold={drift_threshold}), "
            f"no replan attestation. Quarantine trace."
        )


# Example: the observed failure mode
ep = Episode(status="success")
ep.events = [
    TraceEvent("tool_call", "write:/data/target", True, 0.05),
    TraceEvent("permission_denied", "write:/data/target", False, 0.10),
    TraceEvent("tool_call", "write:/tmp/summary", True, 0.55),
    TraceEvent("tool_call", "write:/tmp/summary", True, 0.54),
    TraceEvent("tool_call", "read:/data/target", True, 0.56),
]
assert_no_silent_drift(ep)  # raises SilentDriftError
