# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-context-compaction-summary-as-a-lossy-projection-with-an-explicit-fidelity-budget-rather-than-a-faithful-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-context-compaction-summary-as-a-lossy-projection-with-an-explicit-fidelity-budget-rather-than-a-faithful-transcript.warrant.json
# Markdown SHA-256:   dbbd5b71bdc10b7d9091fc23ee754845f74b3f95bf2ffe7dc900de352b346c54
# Code AST SHA-256:   594ed806e47e5f5266fe1dfbad0fb131115b0ceebefec12afdc529b778f15fa1
# Verified Classes:   CompactionFidelityError, CompactedContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionFidelityError(RuntimeError):
    """Raised when a continuation step would act on a lossy summary alone."""
    pass


@dataclass
class CompactedContext:
    summary: str
    pinned_store: dict[str, str] = field(default_factory=dict)  # verbatim, never summarized
    irreversible: bool = False


def guarded_continue(ctx: CompactedContext, required_invariants: list[str], next_action: str) -> str:
    """
    Enforce: irreversible actions may not be taken from a lossy summary alone.
    Every operative constraint must survive verbatim in the pinned store.
    """
    if not ctx.irreversible:
        # Reversible/exploratory: gist is sufficient.
        return f"proceed-with-summary: {next_action}"

    missing = [k for k in required_invariants if k not in ctx.pinned_store]
    if missing:
        # Do NOT reconstruct the constraint from residual summary tokens.
        raise CompactionFidelityError(
            f"refusing irreversible action '{next_action}': "
            f"pinned invariants lost to compaction: {missing}. "
            f"Re-ground from authoritative state before proceeding."
        )

    # Re-derive referents from the pinned store, not the summary.
    grounded = {k: ctx.pinned_store[k] for k in required_invariants}
    return f"proceed-grounded: {next_action} with {grounded}"


if __name__ == "__main__":
    ctx = CompactedContext(
        summary="Migrating auth service; migration in progress on prod-primary.",
        pinned_store={"no_prod_writes": "use db-replica-07, never prod-primary"},
        irreversible=True,
    )
    # The summary says prod-primary; the pinned store forbids it.
    print(guarded_continue(ctx, ["no_prod_writes"], "run-migration"))
