# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-self-editing-context-policy-has-silently-rewritten-an-instruction-it-was-supposed-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-self-editing-context-policy-has-silently-rewritten-an-instruction-it-was-supposed-to-preserve.warrant.json
# Markdown SHA-256:   6f242760349ad5c9978aa93a664e4a9987fc9da806890fb14642156a944f5bb9
# Code AST SHA-256:   4be3ca104a3e462551cd1334aacc9ed4622f3df1adddd33d10b1ddf06fa8b11d
# Verified Classes:   InstructionDriftError, InstructionCommitment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field


class InstructionDriftError(RuntimeError):
    """Raised when a context rewrite drops or mutates a pinned instruction."""


_IMPERATIVE = re.compile(
    r"\b(NEVER|MUST|DO NOT|ALWAYS|REQUIRED|FORBIDDEN)\b", re.IGNORECASE
)


def _canonical(clause: str) -> str:
    # Normalize whitespace only. Preserve modality, negation, quantifiers, numbers.
    return " ".join(clause.split())


def _digest(clause: str) -> str:
    return hashlib.sha256(_canonical(clause).encode("utf-8")).hexdigest()


@dataclass
class InstructionCommitment:
    digests: set[str] = field(default_factory=set)
    verbatim: dict[str, str] = field(default_factory=dict)

    def pin(self, context: str) -> None:
        for line in context.splitlines():
            if _IMPERATIVE.search(line):
                d = _digest(line)
                self.digests.add(d)
                self.verbatim[d] = _canonical(line)

    def verify_or_restore(self, rewritten_context: str) -> str:
        present = {_digest(l) for l in rewritten_context.splitlines() if _IMPERATIVE.search(l)}
        missing = self.digests - present
        if missing:
            # Re-inject verbatim originals; do not trust the paraphrase.
            restored = "\n".join(self.verbatim[d] for d in sorted(missing))
            if not restored:
                raise InstructionDriftError(
                    f"{len(missing)} pinned instruction(s) lost and no verbatim copy available"
                )
            return rewritten_context + "\n" + restored
        return rewritten_context


def apply_compaction(commitment: InstructionCommitment, rewritten: str) -> str:
    if not commitment.digests:
        raise InstructionDriftError(
            "compaction attempted with no pinned instructions; classification is unsound"
        )
    return commitment.verify_or_restore(rewritten)
