# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-summarizer-drops-the-constraint-that-justified-the-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-summarizer-drops-the-constraint-that-justified-the-summary.warrant.json
# Markdown SHA-256:   70de2e8610af0397159df677369ee66cecee5d8ec080249f44443320add99dab
# Code AST SHA-256:   3c24c8b650c6136d3b4739b942a5338df168bc5468068526778b9d64d2dc4cd5
# Verified Classes:   ConstraintLossError, ContextSpan, RewriteResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ConstraintLossError(RuntimeError):
    """Raised when a self-rewrite would drop or re-type a binding constraint."""
    pass


# Spans that bind future action. Their presence makes a span un-compressible
# in the sense that the *obligation* must survive, even if its narrative does not.
BINDING_MODALS = (
    "do not", "never", "must not", "only after", "requires",
    "only within", "must be treated as", "without a passing",
)


@dataclass
class ContextSpan:
    text: str
    pinned: bool = False

    def has_binding_modality(self) -> bool:
        low = self.text.lower()
        return any(m in low for m in BINDING_MODALS)


@dataclass
class RewriteResult:
    new_context: str
    removed_binding_spans: list[str] = field(default_factory=list)


def self_rewrite(spans: Iterable[ContextSpan], summarize_fn) -> RewriteResult:
    """
    Model-driven in-place rewrite with a fixed-point guard.

    Invariant: a binding constraint may have its justification compressed,
    but the constraint itself must survive verbatim. Any binding span that
    is not pinned and would be lost by the summarizer is a hard error.
    """
    spans = list(spans)
    compressible = [s for s in spans if not s.pinned and not s.has_binding_modality()]
    pinned = [s for s in spans if s.pinned or s.has_binding_modality()]

    # Summarizer only ever sees narrative, never the binding set.
    digest = summarize_fn([s.text for s in compressible])

    # Detect re-typing: a gate ("requires dry_run") collapsed into a
    # completed assertion ("checks passed") is a loss even if text survived.
    original_gates = {s.text for s in pinned if "requires" in s.text.lower()}
    retyped = [
        g for g in original_gates
        if g.lower().split("requires")[0].strip() and
        g.lower().split("requires")[0].strip() in digest.lower()
        and "requires" not in digest.lower()
    ]

    lost = [s.text for s in pinned if s.text not in digest and s.text not in
            "\n".join(p.text for p in pinned)]

    if retyped:
        raise ConstraintLossError(
            f"rewrite re-typed procedural gate(s) as completed assertion(s): {retyped!r}"
        )
    if lost:
        raise ConstraintLossError(
            f"rewrite dropped binding constraint(s) without authorization: {lost!r}"
        )

    # Constraints re-attached verbatim; only narrative was compressed.
    new_context = digest + "\n" + "\n".join(p.text for p in pinned)
    return RewriteResult(new_context=new_context, removed_binding_spans=lost)


def guarded_rewrite(spans, summarize_fn):
    try:
        return self_rewrite(spans, summarize_fn)
    except ConstraintLossError:
        # Fail closed: keep the pre-rewrite context rather than proceed
        # from a state that looks complete and is not.
        raise ConstraintLossError(
            "self-rewrite rejected; retaining pre-rewrite context. "
            "Constraints must be pinned outside the compressible span."
        )
