# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-semantic-anchors-when-it-prunes-its-own-context-window-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-semantic-anchors-when-it-prunes-its-own-context-window-mid-task.warrant.json
# Markdown SHA-256:   25274e77dd3a9fa7b25f83d3fb440bc338ab67adab90b941b3e5af0004a50390
# Code AST SHA-256:   6bd25a39b210c6ffa2f26cace96b4a58047abfbb72da94cb17a51eb70c6a8c3f
# Verified Classes:   ContextDriftError, Trust, Span, Anchor, SelfPruningBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ContextDriftError(RuntimeError):
    """Raised when a self-pruned context buffer would launder a pinned anchor."""
    pass


class Trust(Enum):
    PRIMARY = 1      # verbatim tool output / system constraint
    SURROGATE = 2    # model-written summary of PRIMARY or SURROGATE


@dataclass
class Span:
    text: str
    trust: Trust
    generation: int = 0
    pinned_facts: list = field(default_factory=list)


@dataclass
class Anchor:
    kind: str          # "path" | "relation" | "negation" | "threshold"
    payload: dict


MAX_SURROGATE_GENERATION = 1


class SelfPruningBuffer:
    def __init__(self, budget: int):
        self.budget = budget
        self.spans: list[Span] = []
        self.anchors: list[Anchor] = []   # never pruned, never summarized

    def ingest_primary(self, text: str, facts: list[Anchor]) -> None:
        self.spans.append(Span(text, Trust.PRIMARY, 0, facts))
        self.anchors.extend(facts)

    def _anchors_in(self, span: Span) -> list[Anchor]:
        return [a for a in self.anchors if a in span.pinned_facts]

    def rewrite(self, start: int, end: int, surrogate_text: str) -> None:
        """Model-driven prune: replace spans[start:end] with a summary."""
        target = self.spans[start:end]
        max_gen = max((s.generation for s in target), default=0)
        new_gen = max_gen + 1

        # Invariant 1: generation cap prevents geometric drift.
        if new_gen > MAX_SURROGATE_GENERATION:
            raise ContextDriftError(
                f"rewrite would create generation-{new_gen} surrogate; "
                f"cap is {MAX_SURROGATE_GENERATION}. Pin anchors instead of "
                f"re-summarizing a summary."
            )

        # Invariant 2: any span carrying a pinned anchor may not be prose-rewritten.
        for s in target:
            if self._anchors_in(s):
                raise ContextDriftError(
                    f"span at generation {s.generation} carries pinned anchors "
                    f"{[a.payload for a in self._anchors_in(s)]}; it must be "
                    f"retained verbatim or replaced by a typed record, not prose."
                )

        self.spans[start:end] = [Span(surrogate_text, Trust.SURROGATE, new_gen)]

    def audit(self, claim: str) -> bool:
        """Self-audit MUST consult primary anchors, not surrogate prose."""
        for a in self.anchors:
            if a.kind == "negation" and a.payload.get("path_glob") in claim:
                return False
        return True


def migrate_edit(buf: SelfPruningBuffer, path: str) -> None:
    if not buf.audit(path):
        raise ContextDriftError(
            f"edit to {path} blocked: matches pinned negation anchor. "
            f"Agent's working model may be reading a laundered surrogate; "
            f"re-derive from PRIMARY tool output before proceeding."
        )
