# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-self-pruned-context-has-silently-dropped-the-negative-constraint-that-justified-a-prior-refusal.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-self-pruned-context-has-silently-dropped-the-negative-constraint-that-justified-a-prior-refusal.warrant.json
# Markdown SHA-256:   e4b6e9a5e79d6d99368dde5b4dfdc087d694bf98d4c5881bf107ac75626516d0
# Code AST SHA-256:   fa67d9150e085685021a3e88db136ac092a9f92ee0f7f37676bcb7e09f3aa4ac
# Verified Classes:   ConstraintIntegrityError, EntryKind, ContextEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ConstraintIntegrityError(RuntimeError):
    """Raised when a self-rewrite would drop or depolarize a negative constraint."""


class EntryKind(Enum):
    POSITIVE_STATE = "positive_state"
    NEGATIVE_CONSTRAINT = "negative_constraint"


@dataclass(frozen=True)
class ContextEntry:
    kind: EntryKind
    action_pattern: str      # e.g. "migrate:prod-db-2"
    text: str
    deontic_operator: str | None = None  # "NEVER" for constraints; None for state


def classify(entry: ContextEntry) -> EntryKind:
    # Deontic force is the discriminator, not topical similarity.
    if entry.deontic_operator in {"NEVER", "MUST_NOT", "FORBIDDEN"}:
        return EntryKind.NEGATIVE_CONSTRAINT
    return EntryKind.POSITIVE_STATE


def guard_compaction(
    pre: list[ContextEntry],
    post: list[ContextEntry],
) -> None:
    """
    Invariant: every NEGATIVE_CONSTRAINT present before a rewrite must still be
    represented after it -- same action_pattern, same deontic operator.
    Salience-based eviction is permitted only for POSITIVE_STATE.
    """
    post_index = {
        (e.action_pattern, e.deontic_operator)
        for e in post
        if classify(e) is EntryKind.NEGATIVE_CONSTRAINT
    }
    for entry in pre:
        if classify(entry) is not EntryKind.NEGATIVE_CONSTRAINT:
            continue
        key = (entry.action_pattern, entry.deontic_operator)
        if key not in post_index:
            raise ConstraintIntegrityError(
                f"Compaction dropped or depolarized constraint "
                f"{entry.action_pattern!r} (operator={entry.deontic_operator!r}). "
                f"Rewrite is policy-destroying; reject and re-pin."
            )


def self_edit(pre: list[ContextEntry], proposed_post: list[ContextEntry]) -> list[ContextEntry]:
    # The self-editor may only commit a rewrite that preserves all prohibitions.
    guard_compaction(pre, proposed_post)
    return proposed_post
