# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-compaction-checkpoints-as-non-invertible-state-transitions-rather-than-reversible-caches.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-compaction-checkpoints-as-non-invertible-state-transitions-rather-than-reversible-caches.warrant.json
# Markdown SHA-256:   1bcf60b0f554f3088095ff52604b4c875c48cd1738b6196ffe9edf8ce6aa276a
# Code AST SHA-256:   7c5d6833bf91782f79d293401eb2a2bca67ebee76f358ff77dd32f40b5d6ffae
# Verified Classes:   CompactionInvariantViolation, ObligationLedger, Checkpoint
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionInvariantViolation(RuntimeError):
    """Raised when a lossy checkpoint is about to be treated as reversible,
    or when a post-rehydration commitment is justified only by summary text."""
    pass


@dataclass
class ObligationLedger:
    pending_subgoals: list[str] = field(default_factory=list)
    verbatim_constraints: list[str] = field(default_factory=list)  # negations/conditionals, token-exact
    live_identifiers: dict[str, str] = field(default_factory=dict)  # role -> exact opaque string


@dataclass
class Checkpoint:
    summary_text: str
    verbatim_tail: list[str]
    ledger: Optional[ObligationLedger]
    projection_depth: int = 1


DESTRUCTIVE_ACTIONS = {"delete", "overwrite", "attach", "deploy", "migrate"}


def pre_projection_audit(ledger: Optional[ObligationLedger],
                         budget_remaining: int) -> ObligationLedger:
    """Must run before compaction fires. Refuses projection if the audit
    cannot externalize obligations, negations, and identifiers."""
    if ledger is None:
        raise CompactionInvariantViolation(
            "no external ledger present at compaction time; "
            "refusing lossy projection rather than swallow open obligations")
    if budget_remaining <= 0:
        raise CompactionInvariantViolation(
            "budget exhausted before audit completed; halt task, do not project")
    if not ledger.verbatim_constraints:
        raise CompactionInvariantViolation(
            "no verbatim constraints captured; negation polarity would be lost")
    return ledger


def rehydrate_and_authorize(checkpoint: Checkpoint,
                            action: str,
                            justification_source: str,
                            target_id: str) -> str:
    """Gate a post-rehydration action. Destructive actions must be justified
    from the external ledger or verbatim tail, never from the summary alone."""
    if checkpoint.projection_depth > 1:
        raise CompactionInvariantViolation(
            "second-order re-projection attempted; force full rehydration from ledger")
    if checkpoint.ledger is None:
        raise CompactionInvariantViolation(
            "rehydration without external ledger; checkpoint is a one-way door")

    if action in DESTRUCTIVE_ACTIONS:
        if justification_source not in ("ledger", "verbatim_tail"):
            raise CompactionInvariantViolation(
                f"destructive action '{action}' justified by '{justification_source}'; "
                "summary body is advisory only and cannot authorize irreversible effect")
        if target_id not in checkpoint.ledger.live_identifiers.values():
            raise CompactionInvariantViolation(
                f"target '{target_id}' is not a pinned identifier; "
                "reconstructed IDs are forbidden for destructive actions")

    return f"authorized:{action}:{target_id}"
