# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-rewrite-starvation-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-rewrite-starvation-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   a135b924a63d94e3ceb314d961ce882ede1aa1583f1da7b819935ef0b6c06ed9
# Code AST SHA-256:   89ce3a1af9bbd9212a5ffabbc94e7557bc26634aa195d650fa07fca3d0a9a96a
# Verified Classes:   ProvenanceClosureError, Chunk, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceClosureError(RuntimeError):
    """Raised when a proposed context rewrite would orphan a justification."""


@dataclass
class Chunk:
    id: str
    body: str
    cites: list[str] = field(default_factory=list)  # ids of chunks used as premises


@dataclass
class Context:
    pinned: dict[str, Chunk]          # immune to pruning
    working: dict[str, Chunk]         # prunable
    decision_log: list[str] = field(default_factory=list)

    def all_chunks(self) -> dict[str, Chunk]:
        return {**self.pinned, **self.working}


def _closure_ok(ctx: Context, retained_ids: set[str]) -> tuple[bool, str]:
    """Every retained chunk's cited premises must also be retained."""
    chunks = ctx.all_chunks()
    for cid in retained_ids:
        chunk = chunks.get(cid)
        if chunk is None:
            return False, f"retained id {cid!r} not present in context"
        for premise in chunk.cites:
            if premise not in retained_ids:
                return False, f"{cid!r} cites {premise!r}, which the rewrite drops"
    return True, ""


def apply_rewrite(ctx: Context, proposed_drop: set[str]) -> Context:
    """Commit a pruning rewrite only if provenance-closure holds.

    The pinned stratum is never droppable. Any drop that orphans a citation
    from a retained chunk is rejected; the caller must re-admit or escalate.
    """
    if proposed_drop & ctx.pinned.keys():
        raise ProvenanceClosureError(
            f"rewrite attempts to drop pinned stratum: {sorted(proposed_drop & ctx.pinned.keys())}"
        )

    retained = set(ctx.all_chunks().keys()) - proposed_drop
    ok, reason = _closure_ok(ctx, retained)
    if not ok:
        raise ProvenanceClosureError(
            f"rewrite violates provenance-closure: {reason}; "
            f"re-admit the orphaned premise or escalate the decision"
        )

    new_working = {k: v for k, v in ctx.working.items() if k not in proposed_drop}
    new_log = ctx.decision_log + [f"dropped {sorted(proposed_drop)}; closure verified"]
    return Context(pinned=dict(ctx.pinned), working=new_working, decision_log=new_log)


def rewrite_loop(ctx: Context, prune_plan: list[set[str]]) -> Context:
    """Iterate rewrites; refuse to shrink unsafely rather than converge to empty."""
    for step, drop in enumerate(prune_plan):
        ctx = apply_rewrite(ctx, drop)  # raises ProvenanceClosureError on starvation path
    return ctx
