# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-of-its-working-memory-buffer-as-a-destructive-non-idempotent-operation-requiring-a-pre-rewrite-w.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-of-its-working-memory-buffer-as-a-destructive-non-idempotent-operation-requiring-a-pre-rewrite-w.warrant.json
# Markdown SHA-256:   c397aae6dc071482d9c23c3827f0f187de652a818c64ff2e08a9d69325a53521
# Code AST SHA-256:   0e4d0c191581a8094e0a4cba54ec37a53b74eb93363339064bea63acec2a8694
# Verified Classes:   SelfEditWitnessViolation, Witness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class SelfEditWitnessViolation(RuntimeError):
    """Raised when a model-generated buffer rewrite drops a decision-critical fact."""
    pass


@dataclass
class Witness:
    literals: list[str] = field(default_factory=list)      # exact tokens: ids, paths, codes
    prohibitions: list[str] = field(default_factory=list)  # negative facts: "do not X"
    provenance: list[str] = field(default_factory=list)    # "user stated", "tool returned", ...


def extract_witness(pre_edit_buffer: str) -> Witness:
    # Deterministic, model-free extraction. Literal tokens and negative clauses
    # are surfaced as exact strings; provenance markers are kept verbatim.
    literals = re.findall(r"\b[A-Za-z]+_[0-9a-f]{4,}\b|\b/[\w./-]+\b", pre_edit_buffer)
    prohibitions = [
        line.strip()
        for line in pre_edit_buffer.splitlines()
        if re.search(r"\b(do not|must not|never|forbidden|denied)\b", line, re.I)
    ]
    provenance = [
        line.strip()
        for line in pre_edit_buffer.splitlines()
        if re.search(r"\b(user stated|tool returned|inferred|assumed)\b", line, re.I)
    ]
    return Witness(literals=literals, prohibitions=prohibitions, provenance=provenance)


def apply_self_edit(pre_edit_buffer: str, post_edit_buffer: str) -> str:
    """Commit a model-generated rewrite only if it preserves the pre-edit witness."""
    witness = extract_witness(pre_edit_buffer)

    missing_literals = [t for t in witness.literals if t not in post_edit_buffer]
    if missing_literals:
        raise SelfEditWitnessViolation(
            f"rewrite dropped literal identifiers {missing_literals!r}; "
            f"refusing destructive commit"
        )

    # Prohibitions must survive as exact clauses, not paraphrases: a summary
    # that turns "do not retry" into "proceeding with alternative" passes any
    # semantic check and fails the agent on the next step.
    missing_prohibitions = [
        p for p in witness.prohibitions
        if not any(tok in post_edit_buffer for tok in p.split()[-3:])
    ]
    if missing_prohibitions:
        raise SelfEditWitnessViolation(
            f"rewrite eroded negative facts {missing_prohibitions!r}; "
            f"retry prune with witness pinned or fall back to truncation"
        )

    if witness.provenance and not any(
        re.search(r"\b(stated|returned|inferred|assumed)\b", post_edit_buffer, re.I)
        for _ in [0]
    ):
        raise SelfEditWitnessViolation(
            "rewrite collapsed provenance; post-edit buffer cannot distinguish "
            "external fact from internal inference"
        )

    return post_edit_buffer
