# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-rewrite-amnesia-when-a-compaction-pass-silently-drops-the-invariant-it-is-supposed-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-rewrite-amnesia-when-a-compaction-pass-silently-drops-the-invariant-it-is-supposed-to-preserve.warrant.json
# Markdown SHA-256:   9859e99cf9b0286fbf79f04f6cdb2fb72fc083e175b2422beeaa6a40bbfa930c
# Code AST SHA-256:   d725ee4939339ce8edbdc72e60374b6f77c7e4182a7187245b98d6fc63b5142c
# Verified Classes:   CompactionInvariantViolation, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CompactionInvariantViolation(RuntimeError):
    """Raised when a self-rewrite drops an operator-class token that must survive verbatim."""
    pass


@dataclass
class ContextState:
    narrative: list[str] = field(default_factory=list)
    # Operator-class tokens: constraints, scopes, obligations, truncation flags.
    # These are NEVER eligible for summarization.
    operators: list[str] = field(default_factory=list)
    token_budget: int = 150_000

    def token_count(self) -> int:
        return sum(len(s.split()) for s in self.narrative) + sum(
            len(s.split()) for s in self.operators
        )


def digest_operators(operators: list[str]) -> str:
    h = hashlib.sha256()
    for op in sorted(operators):
        h.update(op.encode("utf-8"))
        h.update(b"\x00")
    return h.hexdigest()


def self_compact(state: ContextState, summarizer, target_tokens: int) -> ContextState:
    """
    Rewrite working memory under budget. The invariant: operators survive verbatim
    and are anchored by a digest computed BEFORE the rewrite and verified AFTER.
    """
    anchor = digest_operators(state.operators)
    operator_count = len(state.operators)

    # Summarize ONLY narrative. Operators are carried through untouched.
    summarized_narrative = summarizer(state.narrative, target_tokens)

    new_state = ContextState(
        narrative=summarized_narrative,
        operators=list(state.operators),  # verbatim carry-through
        token_budget=state.token_budget,
    )

    # Post-rewrite gate: budget AND invariant are orthogonal checks.
    if new_state.token_count() > state.token_budget:
        raise CompactionInvariantViolation(
            f"rewrite exceeded budget: {new_state.token_count()} > {state.token_budget}"
        )

    post_anchor = digest_operators(new_state.operators)
    if post_anchor != anchor or len(new_state.operators) != operator_count:
        # This is the silent-amnesia case: the rewrite lost an operator.
        # Must halt and restore from anchor, NOT re-compact.
        raise CompactionInvariantViolation(
            f"operator set mutated during self-compaction: "
            f"anchor={anchor[:12]} post={post_anchor[:12]} "
            f"count {operator_count}->{len(new_state.operators)}; "
            f"restore from anchor and re-plan, do not re-compact"
        )

    return new_state


def guarded_step(state: ContextState, action: str) -> None:
    """A later step that consumes an operator; fails loudly if the operator was elided."""
    if action.startswith("write:/etc") and not any(
        "never modify files under /etc" in op for op in state.operators
    ):
        raise CompactionInvariantViolation(
            "attempted forbidden write: constraint 'never modify files under /etc' "
            "absent from operator set — self-rewrite amnesia detected at consumption time"
        )
