# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-in-place-context-edits-when-the-rewrite-policy-has-no-external-diff-oracle.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-in-place-context-edits-when-the-rewrite-policy-has-no-external-diff-oracle.warrant.json
# Markdown SHA-256:   8115b7f469abfa38be207b1a7780610282760636bab976f1d6c4e262743a4d4d
# Code AST SHA-256:   37767df6254bc3a4b1369cbe0ede073f6cba40440ba5836c45e56794d11755a0
# Verified Classes:   RewriteRejected, ObligationStatus, Obligation, ObligationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RewriteRejected(RuntimeError):
    """Raised when an in-place context rewrite fails obligation entailment."""


class ObligationStatus(Enum):
    PRESENT = "present"
    MISSING = "missing"
    AMBIGUOUS = "ambiguous"


@dataclass(frozen=True)
class Obligation:
    key: str                      # stable identity, e.g. "perm:R-4471"
    statement: str                # human/agent-readable commitment
    pinned: bool = False          # non-evictable once quarantined


@dataclass
class ObligationLedger:
    obligations: dict[str, Obligation] = field(default_factory=dict)

    def register(self, ob: Obligation) -> None:
        self.obligations[ob.key] = ob

    def pin(self, key: str) -> None:
        ob = self.obligations[key]
        self.obligations[key] = Obligation(ob.key, ob.statement, pinned=True)


# Independent entailment checker. MUST NOT be the rewriter.
EntailmentChecker = Callable[[str, Obligation], ObligationStatus]


def commit_in_place_rewrite(
    pre_edit_buffer: str,
    proposed_buffer: str,
    ledger: ObligationLedger,
    check: EntailmentChecker,
) -> str:
    """
    Commit a self-rewrite only if every ledger obligation remains entailed
    by the proposed buffer. Fails closed and atomically restores pre-edit
    state on any MISSING or cardinality violation.
    """
    if not ledger.obligations:
        # No typed obligations => no safe basis for in-place rewrite.
        raise RewriteRejected(
            "refusing in-place rewrite: obligation ledger empty; "
            "append-only or spill-to-store required"
        )

    statuses: dict[str, ObligationStatus] = {}
    for key, ob in ledger.obligations.items():
        statuses[key] = check(proposed_buffer, ob)

    missing = [k for k, s in statuses.items() if s is ObligationStatus.MISSING]
    if missing:
        # Atomic rejection: caller keeps pre_edit_buffer untouched.
        raise RewriteRejected(
            f"rewrite dropped obligations {missing}; "
            f"restoring pre-edit buffer ({len(pre_edit_buffer)} chars)"
        )

    ambiguous = [k for k, s in statuses.items() if s is ObligationStatus.AMBIGUOUS]
    if ambiguous:
        # Quarantine: advance buffer but pin the ambiguous obligations.
        for k in ambiguous:
            ledger.pin(k)
        raise RewriteRejected(
            f"rewrite ambiguous on {ambiguous}; buffer quarantined, "
            f"obligations pinned non-evictable pending resolution"
        )

    # Cardinality guard: rewrite must not fabricate new obligations.
    entailed_count = sum(1 for s in statuses.values() if s is ObligationStatus.PRESENT)
    if entailed_count != len(ledger.obligations):
        raise RewriteRejected(
            f"obligation cardinality drift: ledger={len(ledger.obligations)} "
            f"entailed={entailed_count}; rewrite invents or splits commitments"
        )

    return proposed_buffer
