# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-buffers-from-silently-rewriting-the-evidence-they-depend-on.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-buffers-from-silently-rewriting-the-evidence-they-depend-on.warrant.json
# Markdown SHA-256:   fbb822354778f33274d7eed9a9cb82d7d5b553ac551e7b33c5beb3f6599fc85b
# Code AST SHA-256:   a0465250e4a446b5bef0b458432d1f5277fedd54eae2282aa2f575ad70079215
# Verified Classes:   RewriteIntegrityError, Polarity, ProvenanceSpan, RetainedClaim, SelfEditedBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class RewriteIntegrityError(RuntimeError):
    """Raised when a self-edited buffer cannot substantiate a claim it asserts."""


class Polarity(Enum):
    SUCCESS = "success"
    FAILURE = "failure"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class ProvenanceSpan:
    source_id: str          # content-addressed id of the pre-rewrite artifact
    span: tuple[int, int]   # byte range within that artifact
    polarity: Polarity      # polarity of the claim as recorded in the source


@dataclass
class RetainedClaim:
    text: str
    provenance: Optional[ProvenanceSpan] = None


@dataclass
class SelfEditedBuffer:
    claims: list[RetainedClaim] = field(default_factory=list)
    # immutable sources are stored OUTSIDE the rewriting model's reach
    sources: dict[str, str] = field(default_factory=dict)

    def add_source(self, source_id: str, raw: str) -> None:
        self.sources[source_id] = raw

    def verify_claim(self, claim: RetainedClaim) -> Polarity:
        """Resolve a claim against its source. Refuse circular verification."""
        if claim.provenance is None:
            # No pointer => testimony, not evidence. Do not trust the rewrite.
            return Polarity.UNKNOWN
        src = self.sources.get(claim.provenance.source_id)
        if src is None:
            # Source evicted: the rewrite is now the only copy. This is the
            # exact condition under which silent corruption becomes undetectable.
            raise RewriteIntegrityError(
                f"claim {claim.text!r} cites source {claim.provenance.source_id!r} "
                "which is no longer retained; buffer is a reconstruction, not evidence"
            )
        start, end = claim.provenance.span
        observed = src[start:end]
        recorded = claim.provenance.polarity
        # Detect polarity flip: the highest-severity rewrite error.
        if recorded is Polarity.FAILURE and "returncode=0" in observed:
            raise RewriteIntegrityError(
                f"polarity conflict on {claim.text!r}: source span {observed!r} "
                "contradicts recorded failure; halt and re-execute"
            )
        return recorded


def gate_fallback_skip(buf: SelfEditedBuffer, claim: RetainedClaim) -> bool:
    """A verifier may only skip a fallback if the claim is substantiated by source."""
    polarity = buf.verify_claim(claim)
    if polarity is Polarity.UNKNOWN:
        # Downgrade to re-execute; never accept the summary as warrant.
        raise RewriteIntegrityError(
            f"cannot skip fallback: claim {claim.text!r} is UNVERIFIED "
            "(no provenance); re-run the probe instead of trusting the rewrite"
        )
    if polarity is Polarity.FAILURE:
        return False
    return True
