# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-controller-has-silently-rewritten-the-wrong-memory-region-under-token-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-controller-has-silently-rewritten-the-wrong-memory-region-under-token-pressure.warrant.json
# Markdown SHA-256:   49cda354c0f11caae791911ab59350833c19f6855bc3b274bffacb77616185aa
# Code AST SHA-256:   97012f0ea1227e0ab166d39de1138429601968d3038437a632e985396edb8d1d
# Verified Classes:   MisattributedRewriteError, Proposition, CompactionResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Polarity = Literal["positive", "negative"]
Source = Literal["user", "tool", "self"]


class MisattributedRewriteError(RuntimeError):
    """Raised when a compaction changes a proposition's epistemic tag or drops a negative constraint."""


@dataclass(frozen=True)
class Proposition:
    text: str
    source: Source
    authority: int          # higher = more binding
    recency: int            # turn index
    mutability: Literal["immutable", "mutable"]
    polarity: Polarity


@dataclass
class CompactionResult:
    retained: list[Proposition] = field(default_factory=list)
    dropped: list[Proposition] = field(default_factory=list)


def structural_diff_gate(
    pre: list[Proposition],
    post: CompactionResult,
) -> None:
    """Reject any rewrite that violates the provenance invariant.

    Two conditions are fatal:
      1. A retained proposition whose (source, authority, mutability, polarity)
         differs from any pre-rewrite proposition with the same normalized text.
      2. A negative, immutable proposition present in `pre` but absent from
         `retained` and absent from `dropped` (i.e. silently folded away).
    """
    pre_by_text = {p.text.strip().lower(): p for p in pre}

    for r in post.retained:
        key = r.text.strip().lower()
        original = pre_by_text.get(key)
        if original is None:
            # A paraphrase: cannot verify tag preservation. Treat as unsafe.
            raise MisattributedRewriteError(
                f"retained proposition has no pre-rewrite provenance: {r.text!r}"
            )
        if (original.source, original.authority, original.mutability, original.polarity) != (
            r.source, r.authority, r.mutability, r.polarity
        ):
            raise MisattributedRewriteError(
                f"epistemic tag drift on {r.text!r}: "
                f"{(original.source, original.authority, original.mutability, original.polarity)} "
                f"-> {(r.source, r.authority, r.mutability, r.polarity)}"
            )

    retained_texts = {p.text.strip().lower() for p in post.retained}
    dropped_texts = {p.text.strip().lower() for p in post.dropped}

    for p in pre:
        if p.polarity == "negative" and p.mutability == "immutable":
            key = p.text.strip().lower()
            if key not in retained_texts and key not in dropped_texts:
                raise MisattributedRewriteError(
                    f"negative immutable constraint silently folded away: {p.text!r} "
                    f"(authority={p.authority}, recency={p.recency})"
                )


def commit_compaction(pre: list[Proposition], post: CompactionResult) -> CompactionResult:
    structural_diff_gate(pre, post)
    return post
