# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-collapse-during-model-driven-context-rewriting.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-collapse-during-model-driven-context-rewriting.warrant.json
# Markdown SHA-256:   116907292eda8fc1f5ecf013b252e0145998eddea62611fccd53a63d96ec8f13
# Code AST SHA-256:   2eadbcad46a19e191f555dca30c721a59c2de2755ca5cb2e0e78cf22e35749f9
# Verified Classes:   ContextInvariantViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextInvariantViolation(RuntimeError):
    """Raised when a self-editing rewrite would drop a pinned invariant."""
    pass


PINNED_INVARIANTS = frozenset({
    'do not mutate records where tenant_id != "acme"',
    'never delete audit rows',
})


def apply_rewrite(window: list[str], proposed: list[str]) -> list[str]:
    """Accept a model-proposed rewrite only if every pinned invariant
    survives verbatim (or is re-injected from the authoritative store)."""
    surviving = set(proposed)
    dropped = PINNED_INVARIANTS - surviving
    if dropped:
        raise ContextInvariantViolation(
            f'rewrite would silently drop invariants: {sorted(dropped)}; '
            f'reinject from store or reject the rewrite'
        )
    return proposed


def prune_with_dereference(window: list[str], span_id: str, store) -> list[str]:
    """Pruning must dereference, never destroy: emit a durable pointer."""
    if span_id not in store:
        raise ContextInvariantViolation(
            f'cannot prune {span_id!r}: no durable backing store entry'
        )
    pointer = f'[pruned:{span_id}]'
    return [t for t in window if t != span_id] + [pointer]
