# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-silent-semantic-drift-when-an-agent-rewrites-its-own-context-window-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-silent-semantic-drift-when-an-agent-rewrites-its-own-context-window-in-place.warrant.json
# Markdown SHA-256:   4833ada9a05da6280bf7793eaa697765ea1c6e870e6972966b69a9b4554ef949
# Code AST SHA-256:   c298a16ab4fb4fac64274401988cf7926ee6a5097a7a2416e3bb58f34648db03
# Verified Classes:   OrphanedReferenceError, StatusFlatteningError, Token, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class OrphanedReferenceError(RuntimeError):
    """Raised when an in-place rewrite would leave retained tokens
    referring to a span that no longer exists."""


class StatusFlatteningError(RuntimeError):
    """Raised when a lossy transform collapses a non-binary status
    (partial/degraded/retry/unknown) into binary success/failure."""


NON_BINARY_STATUSES = {"partial", "degraded", "retry", "unknown", "stale"}


@dataclass
class Token:
    text: str
    # antecedent: the span id this token refers to, if anchored
    refers_to: str | None = None


@dataclass
class Span:
    span_id: str
    tokens: list[Token] = field(default_factory=list)
    statuses: set[str] = field(default_factory=set)


def commit_in_place_rewrite(
    window: list[Token],
    target: Span,
    replacement: list[Token],
    replacement_statuses: set[str],
) -> list[Token]:
    """Replace `target`'s tokens with `replacement` in place.

    Enforces two invariants:
      1. Referential closure: no retained token may refer into `target`
         unless it is itself part of the rewrite.
      2. Status cardinality: any non-binary status in the source span
         must survive into the replacement.
    """
    target_ids = {t for t in (tok.refers_to for tok in target.tokens) if t}
    retained = [tok for tok in window if tok not in target.tokens]

    orphans = [
        tok for tok in retained
        if tok.refers_to == target.span_id or tok.refers_to in target_ids
    ]
    if orphans:
        raise OrphanedReferenceError(
            f"rewrite of span {target.span_id!r} would orphan "
            f"{len(orphans)} retained token(s): "
            f"{[o.text for o in orphans]!r}. "
            f"Widen the rewrite range to include them or demote to append-only."
        )

    lost = (target.statuses & NON_BINARY_STATUSES) - replacement_statuses
    if lost:
        raise StatusFlatteningError(
            f"rewrite of span {target.span_id!r} drops non-binary status "
            f"{sorted(lost)!r}; replacement carries {sorted(replacement_statuses)!r}. "
            f"Preserve status cardinality or refuse the compaction."
        )

    out: list[Token] = []
    for tok in window:
        if tok in target.tokens:
            if not out or out[-1] is not _SENTINEL:
                out.extend(replacement)
                out.append(_SENTINEL)
        else:
            out.append(tok)
    return [t for t in out if t is not _SENTINEL]


_SENTINEL = Token(text="__rewrite_marker__")


def compact_window(window: list[Token], spans: Iterable[Span]) -> list[Token]:
    """Apply rewrites in order; abort the whole batch on first violation."""
    current = list(window)
    for span in spans:
        summary = [Token(text="<summary>", refers_to=None)]
        try:
            current = commit_in_place_rewrite(
                current, span, summary, replacement_statuses=set()
            )
        except (OrphanedReferenceError, StatusFlatteningError):
            # refuse this rewrite; keep prior state, do not partially commit
            raise
    return current
