# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-window-into-a-state-that-no-longer-contains-the-evidence-for-its-own-pruning-decisions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-window-into-a-state-that-no-longer-contains-the-evidence-for-its-own-pruning-decisions.warrant.json
# Markdown SHA-256:   007058974ab8a339435945a3dc597a7bd74cb2006248e7abbb099edead8da4aa
# Code AST SHA-256:   ab873435e6ec291a857d2832f5764cb5de42c5d2a567b1d9e0f9f12da40fde4b
# Verified Classes:   SpanKind, ProvenanceClosureError, Span, PruneDirective, SelfEditingWindow
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SpanKind(Enum):
    OBSERVATION = "observation"   # raw tool output, file read, API response
    DERIVATION = "derivation"     # model reasoning over observations
    SUMMARY = "summary"           # model-authored compression
    MARKER = "marker"             # quarantine / injection flag / negative result


class ProvenanceClosureError(RuntimeError):
    """Raised when a self-authored prune directive would break provenance closure."""


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    parent_id: Optional[str] = None
    gates_write_action: bool = False


@dataclass
class PruneDirective:
    drop: list[str] = field(default_factory=list)
    summarize: list[str] = field(default_factory=list)
    keep_reason: str = ""


class SelfEditingWindow:
    def __init__(self, spans: dict[str, Span], protected_log: list[str]):
        self.spans = spans
        self.protected_log = protected_log  # harness-side; model cannot prune

    def _terminal_of(self, span_id: str) -> Optional[Span]:
        seen = set()
        cur = self.spans.get(span_id)
        while cur is not None and cur.kind in (SpanKind.SUMMARY, SpanKind.DERIVATION):
            if cur.span_id in seen:
                return None  # cycle: no terminal observation
            seen.add(cur.span_id)
            cur = self.spans.get(cur.parent_id) if cur.parent_id else None
        return cur

    def validate(self, directive: PruneDirective) -> None:
        for sid in directive.drop:
            span = self.spans.get(sid)
            if span is None:
                raise ProvenanceClosureError(f"drop targets unknown span {sid}")
            if span.kind in (SpanKind.OBSERVATION, SpanKind.MARKER):
                raise ProvenanceClosureError(
                    f"refusing to drop {span.kind.value} span {sid}: "
                    f"terminal evidence or quarantine marker is non-droppable"
                )
            if span.gates_write_action:
                raise ProvenanceClosureError(
                    f"refusing to drop {sid}: span gates a pending write action"
                )

        for sid in directive.summarize:
            span = self.spans.get(sid)
            if span is None:
                raise ProvenanceClosureError(f"summarize targets unknown span {sid}")
            terminal = self._terminal_of(sid)
            if terminal is None or terminal.kind is not SpanKind.OBSERVATION:
                raise ProvenanceClosureError(
                    f"refusing to summarize {sid}: justification chain does not "
                    f"terminate in a retained OBSERVATION; summary would become "
                    f"underdetermined ground truth"
                )
            if span.gates_write_action:
                raise ProvenanceClosureError(
                    f"refusing to summarize {sid}: only a raw observation may be "
                    f"terminal justification for a write action"
                )

    def apply(self, directive: PruneDirective) -> None:
        self.validate(directive)
        for sid in directive.drop:
            del self.spans[sid]
        for sid in directive.summarize:
            self.spans[sid] = Span(
                span_id=sid,
                kind=SpanKind.SUMMARY,
                parent_id=self.spans[sid].parent_id,
                gates_write_action=False,
            )
        self.protected_log.append(
            f"prune drop={directive.drop} summarize={directive.summarize} "
            f"reason={directive.keep_reason!r}"
        )
