# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-of-its-own-working-context-and-what-invariant-does-an-unguarded-rewrite-violate.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-of-its-own-working-context-and-what-invariant-does-an-unguarded-rewrite-violate.warrant.json
# Markdown SHA-256:   d30cf6cb811f4bfaa62dccb85fd591eb56c25bea044e4317c580a201a391158d
# Code AST SHA-256:   f2a7f4511f43a7400ab8f732e4eb83bf7d9ee829b8f25bc684164afa93fe206a
# Verified Classes:   UnguardedContextRewrite, Obligation, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnguardedContextRewrite(RuntimeError):
    """Raised when a self-rewrite would drop or reinterpret a load-bearing obligation."""
    pass


@dataclass
class Obligation:
    oid: str
    verbatim: str          # the exact clause, never paraphrased
    kind: str              # "prohibition" | "criterion" | "authority" | "definition"
    pointers: list = field(default_factory=list)  # live refs in episodic channel


@dataclass
class ContextWindow:
    episodic_turns: list
    ledger: dict            # oid -> Obligation ; append-only, rewrite-immune
    occupancy: float        # 0.0 - 1.0
    rewrite_threshold: float = 0.70


def self_rewrite(ctx: ContextWindow, summarize_fn, target_span: tuple) -> ContextWindow:
    """Replace target_span of episodic turns with a summary, guarding the obligation ledger."""

    # 1. Semantic trigger check: occupancy alone is never sufficient.
    if ctx.occupancy < ctx.rewrite_threshold:
        return ctx
    if not _at_phase_boundary(ctx, target_span):
        raise UnguardedContextRewrite(
            f"rewrite fired mid-phase at span {target_span}; "
            "volumetric pressure is not grounds to reinterpret obligations"
        )

    # 2. Identify obligations whose defining turns fall inside the target span.
    at_risk = [
        ob for ob in ctx.ledger.values()
        if _defined_within(ob, target_span)
    ]

    # 3. Refuse if any at-risk obligation is a prohibition or definition
    #    that the summary would paraphrase rather than quote.
    summary = summarize_fn(ctx.episodic_turns[target_span[0]:target_span[1]])
    for ob in at_risk:
        if ob.kind in ("prohibition", "definition") and ob.verbatim not in summary:
            raise UnguardedContextRewrite(
                f"obligation {ob.oid!r} ({ob.kind}) would be reinterpreted: "
                f"verbatim clause {ob.verbatim!r} absent from replacement summary"
            )

    # 4. Apply the rewrite to the episodic channel only.
    new_episodic = (
        ctx.episodic_turns[:target_span[0]]
        + [summary]
        + ctx.episodic_turns[target_span[1]:]
    )
    new_ctx = ContextWindow(
        episodic_turns=new_episodic,
        ledger=dict(ctx.ledger),       # untouched
        occupancy=_estimate_occupancy(new_episodic),
    )

    # 5. Post-rewrite re-derivation check: every ledger entry must still
    #    have a live pointer in the new episodic channel.
    for ob in new_ctx.ledger.values():
        if not _has_live_pointer(ob, new_episodic):
            raise UnguardedContextRewrite(
                f"dangling obligation {ob.oid!r} after rewrite; "
                "refusing to proceed on an unrepresented constraint"
            )
    return new_ctx


def _at_phase_boundary(ctx, span) -> bool:
    return _is_boundary_marker(ctx.episodic_turns[span[1] - 1])


def _defined_within(ob, span) -> bool:
    return any(span[0] <= p < span[1] for p in ob.pointers)


def _has_live_pointer(ob, episodic) -> bool:
    return any(_references(ob, turn) for turn in episodic)


def _estimate_occupancy(turns) -> float:
    return min(1.0, sum(len(str(t)) for t in turns) / 200_000)


# --- stubs for the surrounding harness ---
def _is_boundary_marker(turn) -> bool: ...
def _references(ob, turn) -> bool: ...
