# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-audit-trail-when-it-rewrites-context-tokens-in-place-instead-of-appending.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-audit-trail-when-it-rewrites-context-tokens-in-place-instead-of-appending.warrant.json
# Markdown SHA-256:   be2a1b77e9bb185057ccece7f3f4a94df9161fbacce6b51400c24bc8a0236c28
# Code AST SHA-256:   86f4e7910d29b80877b5c2a1d546d76aaa4d0a24aef5d9aefada948a78c3d7b7
# Verified Classes:   ProvenanceIntegrityError, Span, Provenance, SelfEditingBuffer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceIntegrityError(RuntimeError):
    """Raised when a provenance record resolves to content it did not originate."""
    pass


@dataclass
class Span:
    source_id: str
    content: str
    content_hash: str = field(init=False)

    def __post_init__(self):
        self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class Provenance:
    span: Span
    offset: int
    length: int


class SelfEditingBuffer:
    """Context buffer that forbids unsafe in-place rewrite of load-bearing spans."""

    def __init__(self):
        self._buffer: list[str] = []
        self._provenance: list[Provenance] = []
        self._load_bearing: set[str] = set()

    def append(self, span: Span, load_bearing: bool = False) -> None:
        offset = sum(len(t) for t in self._buffer)
        self._buffer.append(span.content)
        self._provenance.append(Provenance(span, offset, len(span.content)))
        if load_bearing:
            self._load_bearing.add(span.source_id)

    def read(self, source_id: str) -> str:
        for p in self._provenance:
            if p.span.source_id == source_id:
                start, end = p.offset, p.offset + p.length
                actual = "".join(self._buffer)[start:end]
                # Identity check: content must hash to the recorded span hash.
                if hashlib.sha256(actual.encode()).hexdigest() != p.span.content_hash:
                    raise ProvenanceIntegrityError(
                        f"provenance for {source_id} resolved to mutated content; "
                        f"buffer was rewritten in place without invalidation"
                    )
                return actual
        raise ProvenanceIntegrityError(f"no provenance record for {source_id}")

    def rewrite_in_place(self, source_id: str, new_content: str) -> None:
        """Unsafe operation. Must refuse load-bearing spans and must invalidate."""
        if source_id in self._load_bearing:
            raise ProvenanceIntegrityError(
                f"refusing in-place rewrite of load-bearing span {source_id}; "
                f"use append-and-supersede or externalize to a handle"
            )
        # Even for non-load-bearing spans, invalidate all intersecting/after records.
        target = next(p for p in self._provenance if p.span.source_id == source_id)
        delta = len(new_content) - target.length
        for p in self._provenance:
            if p is target:
                continue
            if p.offset >= target.offset + target.length:
                p.offset += delta  # per-record delta, not a global constant
        target.length = len(new_content)
        target.span = Span(source_id, new_content)


def self_edit_under_budget(buf: SelfEditingBuffer, source_id: str,
                           summary: str, tokens_left: int) -> None:
    """Decision boundary: externalize at budget edge, never rewrite load-bearing."""
    if tokens_left < 0:
        raise ProvenanceIntegrityError(
            f"token budget exhausted before externalizing {source_id}; "
            f"in-place summary would destroy verifiable evidence"
        )
    if source_id in buf._load_bearing:
        raise ProvenanceIntegrityError(
            f"{source_id} is load-bearing; summarization is a lossy transform "
            f"and cannot substitute for verbatim content under verification"
        )
    buf.rewrite_in_place(source_id, summary)
