# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-intent-drift-after-hierarchical-context-compaction-and-roll-back-to-a-lossy-checkpoint-without-re-triggeri.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-intent-drift-after-hierarchical-context-compaction-and-roll-back-to-a-lossy-checkpoint-without-re-triggeri.warrant.json
# Markdown SHA-256:   cd3886a563ed8e1741d9014e186fa2e6773a8f4429324ce34707267c93b3a4e0
# Code AST SHA-256:   e6d567d892827fa54793c595be9140e8c74446bbe6d28fd428ec3435c9a06cfd
# Verified Classes:   CompactionDriftError, DriftKind, Constraint, Checkpoint, CompactionController
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionDriftError(RuntimeError):
    """Raised when summary-induced intent drift is detected at a compaction boundary."""
    pass


class DriftKind(Enum):
    FAITHFUL = "faithful"
    POLARITY_FLIP = "polarity_flip"   # constraint lost or inverted -> full rollback
    HALLUCINATED = "hallucinated"     # constraint invented -> node discard only


@dataclass(frozen=True)
class Constraint:
    entity: str
    predicate: str
    polarity: bool  # True = must, False = must-not


@dataclass
class Checkpoint:
    epoch_id: int
    constraints: frozenset[Constraint]
    compacted: bool


@dataclass
class CompactionController:
    ledger: frozenset[Constraint]
    checkpoints: list[Checkpoint] = field(default_factory=list)

    def classify_drift(self, rederived: frozenset[Constraint]) -> DriftKind:
        missing = self.ledger - rederived
        invented = rederived - self.ledger
        # A polarity flip shows up as a missing constraint plus an inverted twin.
        for c in missing:
            inverted = Constraint(c.entity, c.predicate, not c.polarity)
            if inverted in invented:
                return DriftKind.POLARITY_FLIP
        if missing:
            return DriftKind.POLARITY_FLIP
        if invented:
            return DriftKind.HALLUCINATED
        return DriftKind.FAITHFUL

    def last_pre_compaction_checkpoint(self) -> Optional[Checkpoint]:
        for cp in reversed(self.checkpoints):
            if not cp.compacted:
                return cp
        return None

    def handle_boundary(self, rederived: frozenset[Constraint]) -> str:
        kind = self.classify_drift(rederived)
        if kind is DriftKind.FAITHFUL:
            return "continue"
        if kind is DriftKind.HALLUCINATED:
            return "discard_summary_node"
        target = self.last_pre_compaction_checkpoint()
        if target is None:
            raise CompactionDriftError(
                "polarity flip detected but no pre-compaction checkpoint exists; "
                "rollback would re-enter the drift deterministically"
            )
        return f"rollback_to_epoch_{target.epoch_id}_with_pinned_ledger"


if __name__ == "__main__":
    ledger = frozenset({
        Constraint("staging-db-02", "ddl", False),      # must NOT issue DDL
        Constraint("staging-db-03", "migration_target", True),
    })
    ctl = CompactionController(ledger=ledger)
    ctl.checkpoints.append(Checkpoint(epoch_id=27, constraints=ledger, compacted=False))
    ctl.checkpoints.append(Checkpoint(epoch_id=28, constraints=frozenset(), compacted=True))

    # Post-compaction the agent re-derives the INVERSE of the DDL prohibition.
    rederived = frozenset({
        Constraint("staging-db-02", "ddl", True),       # flipped polarity
        Constraint("staging-db-03", "migration_target", True),
    })
    action = ctl.handle_boundary(rederived)
    assert action == "rollback_to_epoch_27_with_pinned_ledger", action
    print(action)
