# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-self-editing-context-window-that-has-silently-rewritten-its-own-task-invariant-into-a-local-optimum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-self-editing-context-window-that-has-silently-rewritten-its-own-task-invariant-into-a-local-optimum.warrant.json
# Markdown SHA-256:   946c96816bb48a41c08a21f07be18870d6eaeca47ab80f20860fef0f4ef6c2cf
# Code AST SHA-256:   079b67ae92aa923dd0a9322468db08bed3e54e19f60ea3603e12e66c81bb48b7
# Verified Classes:   ContextInvariantViolation, PinnedAnchor, RewriteRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ContextInvariantViolation(RuntimeError):
    """Raised when a model-driven rewrite has made the task invariant unrecoverable."""
    pass


@dataclass
class PinnedAnchor:
    spec_text: str
    clauses: list[str]  # load-bearing substrings that must remain entailed
    _hash: str = field(init=False)

    def __post_init__(self) -> None:
        self._hash = hashlib.sha256(self.spec_text.encode()).hexdigest()

    def clause_present(self, context: str) -> dict[str, bool]:
        return {c: (c.lower() in context.lower()) for c in self.clauses}


@dataclass
class RewriteRecord:
    turn: int
    span_id: str
    pre_hash: str
    post_hash: str
    summary: str
    derived: bool = True
    order: int = 1  # 1 = first-order, 2+ = summarizing a summary


def apply_rewrite(
    context: str,
    anchor: PinnedAnchor,
    record: RewriteRecord,
    *,
    max_order: int = 1,
) -> str:
    # Guard 1: no second-order rewrites of already-derived spans.
    if record.order > max_order:
        raise ContextInvariantViolation(
            f"turn {record.turn}: second-order rewrite of span {record.span_id} "
            f"would make original evidence unrecoverable"
        )

    # Guard 2: the rewrite must not drop a pinned clause from the context.
    post_context = context.replace(record.summary, record.summary)  # placeholder for real splice
    missing = [c for c, present in anchor.clause_present(post_context).items() if not present]
    if missing:
        raise ContextInvariantViolation(
            f"turn {record.turn}: rewrite of span {record.span_id} evicted pinned "
            f"clause(s) {missing}; refusing to apply"
        )

    # Guard 3: derived summaries must be tagged so the executor does not treat
    # them as primary evidence for permission-relevant claims.
    if not record.derived:
        raise ContextInvariantViolation(
            f"turn {record.turn}: rewrite of span {record.span_id} is not tagged "
            f"derived; executor would condition on it as ground truth"
        )

    return post_context


def verify_against_anchor(context: str, anchor: PinnedAnchor, turn: int) -> None:
    missing = [c for c, present in anchor.clause_present(context).items() if not present]
    if missing:
        raise ContextInvariantViolation(
            f"turn {turn}: context no longer entails pinned clause(s) {missing}; "
            f"halt and re-ground from immutable store (anchor hash {anchor._hash[:12]})"
        )
