# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-self-rewrite-its-working-context-the-idempotence-loss-trap-in-budget-driven-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-self-rewrite-its-working-context-the-idempotence-loss-trap-in-budget-driven-context-compaction.warrant.json
# Markdown SHA-256:   2d9f50acebdd7d0320eb9f700cbb09c96ce7b3f666f1e65eeef2dd00067b3858
# Code AST SHA-256:   edec4df5084b60b0f49ecaf6dffe9403431cc6ebaa4f22bba0bf2bd45f7d99c9
# Verified Classes:   ContextRewriteRefused, WorkingContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class ContextRewriteRefused(RuntimeError):
    """Raised when a self-edit would destroy the only copy of its ground truth."""


@dataclass
class WorkingContext:
    turns: list[str]
    digest: Optional[str] = None
    digest_source_hash: Optional[str] = None
    compaction_count: int = 0
    external_store: dict = field(default_factory=dict)  # hash -> raw turns

    def _hash(self, turns: list[str]) -> str:
        return hashlib.sha256(json.dumps(turns, sort_keys=True).encode()).hexdigest()


def compact(ctx: WorkingContext, summarize, *, budget_pressure: bool) -> WorkingContext:
    """Self-edit under budget. Enforces externalization + single-pass invariants."""
    source_hash = ctx._hash(ctx.turns)

    # Invariant 1: source must be externally recoverable before we replace it.
    if source_hash not in ctx.external_store:
        if not budget_pressure:
            raise ContextRewriteRefused(
                "fidelity-repair rewrite attempted without externalized source; "
                "append a correction record instead of rewriting"
            )
        # Spill first, then proceed. The store, not the digest, is the witness.
        ctx.external_store[source_hash] = list(ctx.turns)

    # Invariant 3: no second compaction pass on an already-compacted context.
    if ctx.compaction_count >= 1 and ctx.digest is not None:
        raise ContextRewriteRefused(
            "second compaction pass on already-compacted context: "
            "source is not re-derivable, loss would compound"
        )

    new_digest = summarize(ctx.turns)
    ctx.digest = new_digest
    ctx.digest_source_hash = source_hash
    ctx.turns = [f"[DIGEST src={source_hash}] {new_digest}"]
    ctx.compaction_count += 1
    return ctx


def verify_digest(ctx: WorkingContext, claim: str) -> bool:
    """A digest claim is only actionable if re-derivable from external source."""
    if ctx.digest_source_hash is None:
        raise ContextRewriteRefused("digest has no source hash; claim is unverifiable")
    source = ctx.external_store.get(ctx.digest_source_hash)
    if source is None:
        raise ContextRewriteRefused(
            f"source {ctx.digest_source_hash[:12]} not in external store; "
            f"claim {claim!r} is an orphaned assertion"
        )
    return claim in "\n".join(source)
