# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-deleting-the-only-copy-of-a-live-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-deleting-the-only-copy-of-a-live-constraint.warrant.json
# Markdown SHA-256:   ab3ccb10b7d1787dc47e1f1f5925f3c7b7896dd740ca4bca65c9da5203f2d09d
# Code AST SHA-256:   5918643de7fc5f9ad39e4519afec83282980af14036e984a0ae839bab940efc0
# Verified Classes:   ConstraintLossError, ContextSpan, ContextRewriter
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ConstraintLossError(RuntimeError):
    """Raised when a context rewrite would drop the only copy of a live constraint."""
    pass


@dataclass
class ContextSpan:
    span_id: str
    text: str
    regenerable: bool          # tool outputs / reasoning = True; user constraints = False
    constraints: list = field(default_factory=list)


@dataclass
class ContextRewriter:
    non_editable_constraints: dict = field(default_factory=dict)  # invariant 1 slot

    def ingest(self, span: ContextSpan) -> None:
        # Extract hard constraints into the non-editable slot at ingestion time.
        for c in span.constraints:
            self.non_editable_constraints[c] = hashlib.sha256(
                (span.span_id + c).encode()
            ).hexdigest()

    def rewrite(self, spans: list, summarizer) -> list:
        kept, editable = [], []
        for s in spans:
            if s.regenerable:
                editable.append(s)
            else:
                kept.append(s)  # never compress non-regenerable spans

        candidate_summary = summarizer(editable)

        # Invariant 3: constraint-diff gate — summary must preserve every live constraint.
        for c, digest in self.non_editable_constraints.items():
            if c not in candidate_summary:
                raise ConstraintLossError(
                    f"Rewrite would drop live constraint {c!r} "
                    f"(digest {digest[:12]}). Fall back to evicting tool output "
                    f"or raising context-pressure instead of summarizing."
                )

        return kept + [ContextSpan("summary", candidate_summary, True)]
