# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-against-the-loss-of-load-bearing-negative-constraints.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-against-the-loss-of-load-bearing-negative-constraints.warrant.json
# Markdown SHA-256:   7973c9417bd7adb7f66d6d56a4db68417ee001fe04bca09da689414eaaff3993
# Code AST SHA-256:   a38583605924e6568dd9fe8381c3e8df3a4266a6d0feb7279a30797cf6228f91
# Verified Classes:   ConstraintLedgerViolation, SpanClass, Span, ContextWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ConstraintLedgerViolation(RuntimeError):
    """Raised when a self-editing context rewrite would strip or summarize a live constraint."""
    pass


class SpanClass(Enum):
    NARRATIVE = "narrative"          # safe to summarize/drop
    CONSTRAINT = "constraint"        # prohibition / precondition / scope boundary
    DISCHARGED = "discharged"        # constraint with a recorded discharge event


@dataclass
class Span:
    span_id: str
    text: str
    cls: SpanClass
    discharge_event: str | None = None

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class ContextWindow:
    budget_tokens: int
    pinned: dict[str, Span] = field(default_factory=dict)   # immutable ledger
    mutable: list[Span] = field(default_factory=list)

    def tokens(self) -> int:
        # crude proxy: 1 token ~= 4 chars for pinned + mutable
        return sum(len(s.text) // 4 for s in self.pinned.values()) + \
               sum(len(s.text) // 4 for s in self.mutable)


def rewrite(window: ContextWindow, pruner, classifier) -> ContextWindow:
    """
    Model-driven compaction. Invariant: a CONSTRAINT span may never be
    summarized or dropped; only DISCHARGED spans with an event may leave.
    """
    new_mutable: list[Span] = []
    for span in window.mutable:
        cls = classifier(span)
        if cls is SpanClass.CONSTRAINT:
            # promote to pinned ledger verbatim; never hand to pruner
            window.pinned[span.span_id] = span
            continue
        if cls is SpanClass.DISCHARGED:
            if span.discharge_event is None:
                raise ConstraintLedgerViolation(
                    f"span {span.span_id} marked DISCHARGED without a discharge event; "
                    "refusing to drop an undischarged constraint"
                )
            continue  # safe to remove
        new_mutable.append(pruner(span))

    window.mutable = new_mutable

    # post-condition: every pinned span must survive byte-identical
    for sid, span in window.pinned.items():
        if span.digest() != hashlib.sha256(span.text.encode()).hexdigest():
            raise ConstraintLedgerViolation(f"pinned constraint {sid} mutated during rewrite")

    if window.tokens() > window.budget_tokens:
        # budget pressure may only be resolved by compressing NARRATIVE further,
        # never by touching the ledger
        raise ConstraintLedgerViolation(
            f"window over budget ({window.tokens()} > {window.budget_tokens}) "
            "with ledger intact; compress narrative, do not evict constraints"
        )
    return window


def pre_write_check(window: ContextWindow, target_path: str) -> None:
    """Re-read the ledger verbatim (not its summary) before any write-class call."""
    for span in window.pinned.values():
        if span.cls is SpanClass.CONSTRAINT and "frozen" in span.text.lower():
            if "billing/legacy" in target_path:
                raise ConstraintLedgerViolation(
                    f"write to {target_path} blocked by pinned constraint {span.span_id}: "
                    f"{span.text!r}"
                )
