# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-summarization-boundary-state-as-a-first-class-continuity-hazard-rather-than-a-recoverable-formatting-concern.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-summarization-boundary-state-as-a-first-class-continuity-hazard-rather-than-a-recoverable-formatting-concern.warrant.json
# Markdown SHA-256:   6627baf78060c13fa99fca8fa9c026d9b44552ecc79b457c2ba89628dcb01b3f
# Code AST SHA-256:   f8a122b8030626cde6a701ffe7772f3fa33dcf2cb6dff2a2cb24cfe48dfb77ce
# Verified Classes:   CompactionContinuityError, LedgerRecord, ContinuityLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionContinuityError(RuntimeError):
    """Raised when a compaction boundary would drop a load-bearing predicate."""
    pass


class LedgerRecord:
    def __init__(self, kind: str, payload: dict, irreversible: bool = False):
        self.kind = kind
        self.payload = payload
        self.irreversible = irreversible


class ContinuityLedger:
    def __init__(self):
        self.records: list[LedgerRecord] = []

    def commit(self, record: LedgerRecord) -> None:
        # Durable write must be confirmed before summarizer runs.
        self.records.append(record)

    def has_pending_gate(self) -> bool:
        return any(r.kind == "approval_pending" for r in self.records)

    def has_consumed_token(self, token_id: str) -> bool:
        return any(
            r.kind == "one_shot_consumed" and r.payload.get("token") == token_id
            for r in self.records
        )


def compact_with_continuity(
    window: list[dict],
    ledger: ContinuityLedger,
    summarizer,
    resume_plan: dict,
) -> str:
    # Phase 1: extract must-preserve predicates BEFORE summarizing.
    for event in window:
        if event.get("type") == "irreversible_side_effect":
            ledger.commit(LedgerRecord("irreversible_effect", event, irreversible=True))
        elif event.get("type") == "one_shot_token_consumed":
            ledger.commit(LedgerRecord("one_shot_consumed", event))
        elif event.get("type") == "approval_requested":
            ledger.commit(LedgerRecord("approval_pending", event))

    # Phase 2: only now may the lossy summarizer run.
    summary = summarizer(window)

    # Phase 3: re-entry reconciliation — refuse to proceed on summary alone.
    if ledger.has_pending_gate() and resume_plan.get("action") == "privileged":
        raise CompactionContinuityError(
            "resume plan issues a privileged action while an approval gate is "
            "pending in the ledger; summary implied approval but ledger forbids it"
        )

    for token in resume_plan.get("tokens_to_use", []):
        if ledger.has_consumed_token(token):
            raise CompactionContinuityError(
                f"resume plan reuses one-shot token {token!r} already consumed "
                f"pre-compaction; summary dropped the consumption record"
            )

    return summary
