# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-when-its-own-runtime-prompt-rewriting-silently-invalidates-prior-tool-call-contracts.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-when-its-own-runtime-prompt-rewriting-silently-invalidates-prior-tool-call-contracts.warrant.json
# Markdown SHA-256:   9f08fc6b2490d343d111bf3e27cf146f59726349e5869452622818bfa395e079
# Code AST SHA-256:   5671d8adbc667644c8a9afac7f727841a2d6463f2a4f1374574ffc7840ecd851
# Verified Classes:   ContractClausePrunedError, BehavioralDriftError, PreambleClause, ToolContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ContractClausePrunedError(RuntimeError):
    """Raised when a self-rewrite drops a preamble clause that constrains an
    active tool contract, invalidating prior or scheduled tool calls."""
    pass


class BehavioralDriftError(RuntimeError):
    """Raised when post-rewrite tool-call argument distribution shifts in a
    constrained dimension, indicating a silently removed load-bearing clause."""
    pass


@dataclass
class PreambleClause:
    text: str
    constrains: set[str] = field(default_factory=set)  # (tool, arg) keys
    silent_failure: bool = False


@dataclass
class ToolContract:
    tool: str
    arg: str
    invariant: str
    silent_failure: bool = False

    @property
    def key(self) -> str:
        return f"{self.tool}.{self.arg}"


def rewrite_preamble(
    clauses: list[PreambleClause],
    active_contracts: list[ToolContract],
    relevance_scorer: Callable[[PreambleClause], float],
    threshold: float = 0.30,
) -> list[PreambleClause]:
    """Prune low-relevance clauses, but pin any clause constraining an active
    contract. Returns the surviving clause set; raises if a pinned clause would
    have been dropped by the relevance pass alone."""
    active_keys = {c.key for c in active_contracts}
    pinned = {c.text for c in clauses if c.constrains & active_keys}
    silent_pinned = {
        c.text for c in clauses
        if c.silent_failure and c.constrains & active_keys
    }

    survivors: list[PreambleClause] = []
    dropped: list[PreambleClause] = []
    for clause in clauses:
        if clause.text in pinned:
            survivors.append(clause)
            continue
        if relevance_scorer(clause) >= threshold:
            survivors.append(clause)
        else:
            dropped.append(clause)

    # A pinned clause must never appear in the dropped set.
    for clause in dropped:
        if clause.text in pinned:
            raise ContractClausePrunedError(
                f"rewrite would drop pinned clause {clause.text!r} "
                f"constraining active contract(s) {sorted(clause.constrains & active_keys)}"
            )

    # Silent-failure contracts require their governing clause to survive in
    # some form; if all such clauses were dropped, abort.
    surviving_text = {c.text for c in survivors}
    for key in silent_pinned:
        if key not in surviving_text:
            raise ContractClausePrunedError(
                f"silent-failure contract clause {key!r} removed with no replacement"
            )

    return survivors


def check_behavioral_drift(
    pre_rewrite_calls: list[dict],
    post_rewrite_calls: list[dict],
    constrained_arg: str,
    pre_ratio: float,
    tolerance: float = 0.15,
) -> None:
    """Compare the fraction of calls satisfying a constrained argument before
    and after a rewrite. A drop beyond tolerance raises BehavioralDriftError."""
    if not post_rewrite_calls:
        return
    post_ratio = sum(
        1 for c in post_rewrite_calls if c.get(constrained_arg, "").startswith("/")
    ) / len(post_rewrite_calls)
    if pre_ratio - post_ratio > tolerance:
        raise BehavioralDriftError(
            f"argument {constrained_arg!r} constraint satisfaction dropped "
            f"{pre_ratio:.2f} -> {post_ratio:.2f} across rewrite boundary; "
            f"load-bearing clause likely pruned"
        )
