# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-rewriting-context-window-has-begun-to-prune-its-own-pruning-rationale.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-rewriting-context-window-has-begun-to-prune-its-own-pruning-rationale.warrant.json
# Markdown SHA-256:   2446a49bbc3a8168bed3f82a7800e928f5bb849479e3cb720f0210e2570f35cb
# Code AST SHA-256:   1b29fe056cc6467557b795240406ce55004af314efbc9fa6a943b295240c25d9
# Verified Classes:   ConstraintJustificationSevered, Span, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ConstraintJustificationSevered(RuntimeError):
    """Raised when a self-edit would drop the last rationale for an active constraint."""


@dataclass
class Span:
    span_id: str
    kind: str          # "content" | "constraint" | "rationale"
    references: list[str] = field(default_factory=list)  # rationale -> constraint ids


@dataclass
class ConstraintLedger:
    # Write-once, lives outside the rewritable buffer.
    active: dict[str, str] = field(default_factory=dict)  # constraint_id -> text

    def is_active(self, cid: str) -> bool:
        return cid in self.active


def apply_self_edit(
    spans: list[Span],
    keep_ids: set[str],
    drop_ids: set[str],
    ledger: ConstraintLedger,
) -> list[Span]:
    if keep_ids & drop_ids:
        raise ValueError("keep/drop overlap in rewrite instruction")

    kept = [s for s in spans if s.span_id in keep_ids]
    dropped = [s for s in spans if s.span_id in drop_ids]

    # Invariant: for every active constraint, at least one rationale
    # referencing it must survive the rewrite, OR the constraint must be
    # dropped from the ledger in the same atomic step (logged as removal).
    surviving_rationale_refs = {
        cid
        for s in kept
        if s.kind == "rationale"
        for cid in s.references
    }

    for s in dropped:
        if s.kind != "rationale":
            continue
        for cid in s.references:
            if ledger.is_active(cid) and cid not in surviving_rationale_refs:
                raise ConstraintJustificationSevered(
                    f"rewrite drops rationale {s.span_id!r}, the last "
                    f"justification for active constraint {cid!r}; "
                    f"promote constraint to structural slot or remove it "
                    f"from the ledger atomically before retrying"
                )

    return kept
