# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-self-edit-monotonic-invariant-loss-under-in-place-working-memory-rewrites.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-self-edit-monotonic-invariant-loss-under-in-place-working-memory-rewrites.warrant.json
# Markdown SHA-256:   c5f3791eee5211dd0b265fff4f603d526ce88823d5c72158d73e542abe75aa76
# Code AST SHA-256:   08b15460751b63b398028dda8a34dae52ae60b5542bac4c65cb3ceb72bfebaf9
# Verified Classes:   InvariantState, RewriteRefused, Witness, Memory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class InvariantState(Enum):
    PENDING = "pending"
    ESTABLISHED = "established"
    DISCHARGED = "discharged"


class RewriteRefused(RuntimeError):
    """Raised when an in-place self-edit would sever a live invariant's witness."""


@dataclass
class Witness:
    invariant_id: str
    typed: bool            # machine-checkable record vs. prose
    established_ts: int    # logical clock at witness time
    is_absence_fact: bool  # "X did not occur" style witness


@dataclass
class Memory:
    clock: int = 0
    witnesses: dict = field(default_factory=dict)   # inv_id -> Witness
    states: dict = field(default_factory=dict)      # inv_id -> InvariantState
    last_mutation_ts: dict = field(default_factory=dict)

    def mutate(self, inv_id: str) -> None:
        self.clock += 1
        self.last_mutation_ts[inv_id] = self.clock

    def rewrite_in_place(self, keep_typed: bool) -> None:
        # Simulates a compaction pass that may demote witnesses to prose.
        self.clock += 1
        if not keep_typed:
            for w in self.witnesses.values():
                w.typed = False


def commit_self_edit(mem: Memory, keep_typed: bool) -> None:
    """Refuse the rewrite if any ESTABLISHED invariant would lose its witness."""
    for inv_id, state in mem.states.items():
        if state is not InvariantState.ESTABLISHED:
            continue
        w: Optional[Witness] = mem.witnesses.get(inv_id)
        if w is None:
            raise RewriteRefused(
                f"invariant {inv_id} ESTABLISHED with no witness; refusing rewrite"
            )
        if w.is_absence_fact and not keep_typed:
            raise RewriteRefused(
                f"invariant {inv_id} relies on absence-witness; "
                f"prose demotion would sever witness-to-mutation ordering"
            )
        last_mut = mem.last_mutation_ts.get(inv_id, -1)
        if w.established_ts < last_mut:
            raise RewriteRefused(
                f"invariant {inv_id} witness ts={w.established_ts} predates "
                f"mutation ts={last_mut}; re-verify before rewrite"
            )
    # Safe: rewrite preserves every live witness as a typed record.
    mem.rewrite_in_place(keep_typed=keep_typed)


def guard_check(mem: Memory, inv_id: str) -> bool:
    w = mem.witnesses.get(inv_id)
    if w is None or not w.typed:
        # Default policy: UNKNOWN must block, never pass.
        return False
    return w.established_ts >= mem.last_mutation_ts.get(inv_id, -1)


if __name__ == "__main__":
    m = Memory()
    m.states["INV-NOAUTH"] = InvariantState.ESTABLISHED
    m.witnesses["INV-NOAUTH"] = Witness("INV-NOAUTH", typed=True,
                                        established_ts=0, is_absence_fact=True)
    try:
        commit_self_edit(m, keep_typed=False)   # prose demotion -> refused
    except RewriteRefused as e:
        print("refused:", e)
        assert guard_check(m, "INV-NOAUTH") is True  # witness still typed
    m.mutate("INV-NOAUTH")                       # credential enqueued
    assert guard_check(m, "INV-NOAUTH") is False # stale witness blocks
