# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-rewritten-context-as-a-new-epistemic-epoch-rather-than-a-continuation-of-the-current-one.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-rewritten-context-as-a-new-epistemic-epoch-rather-than-a-continuation-of-the-current-one.warrant.json
# Markdown SHA-256:   b39b1bbf7023118890344d5d565b480d206a021a2b09bed8275069ce5329c813
# Code AST SHA-256:   eecbac038a27f2eef82f860238dfb5057ee4f961393b2507254255d07bcb0286
# Verified Classes:   EpochBreakError, Proposition
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class EpochBreakError(RuntimeError):
    """Raised when a self-rewrite launders a scoped/sourced/contested
    proposition into an unconditional one without an explicit epoch boundary."""
    pass


@dataclass(frozen=True)
class Proposition:
    text: str
    source: str                 # "self" or a tool/retrieval id
    scope: Optional[str]        # entity/time/query key, None == global
    contested: bool = False     # was it in tension with another prop?
    rederivable_via: Optional[str] = None  # pointer/query to recover detail


def check_rewrite_is_continuation(
    pre: list[Proposition],
    post: list[Proposition],
) -> None:
    """Enforce the continuation invariant. A rewrite is a valid continuation
    iff every load-bearing (sourced, scoped, or contested) proposition in `pre`
    survives in `post` with the same source, scope, and contestation status,
    or is re-derivable. Otherwise it is an epoch break and must be declared."""
    post_keys = {(p.text, p.source, p.scope, p.contested) for p in post}
    dropped_warrants: list[Proposition] = []

    for p in pre:
        load_bearing = (p.source != "self") or (p.scope is not None) or p.contested
        if not load_bearing:
            continue
        if (p.text, p.source, p.scope, p.contested) in post_keys:
            continue
        if p.rederivable_via is not None:
            # detail compressed to gist, but recoverable: acceptable
            continue
        dropped_warrants.append(p)

    if dropped_warrants:
        raise EpochBreakError(
            "self-rewrite dropped load-bearing warrants without an epoch "
            f"boundary: {[w.text for w in dropped_warrants]}. "
            "Re-summarize preserving source/scope/contestation, or declare "
            "a new epistemic epoch and re-verify these before asserting."
        )


def compact_context(pre: list[Proposition], candidate_post: list[Proposition]) -> list[Proposition]:
    check_rewrite_is_continuation(pre, candidate_post)
    return candidate_post
