# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-task-drift-when-auto-compaction-silently-rewrites-the-precondition-of-an-in-flight-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-task-drift-when-auto-compaction-silently-rewrites-the-precondition-of-an-in-flight-plan.warrant.json
# Markdown SHA-256:   7f928ed868baf7b5a2ed14db42a4fc6cd7474691e78c105824595f60d0101d12
# Code AST SHA-256:   24939c2658c4fef200b2cfcd657f7259088e8eb9c34a87d101b2caad557dd606
# Verified Classes:   CompactionDriftError, Phase, Checkpoint, Summary
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CompactionDriftError(RuntimeError):
    """Raised when post-compaction context implies a plan phase that
    contradicts the externally checkpointed control state."""


class Phase(Enum):
    DIAGNOSE = "diagnose"
    VERIFY_SCHEMA = "verify_schema"
    DEPLOY = "deploy"
    SMOKE_TEST = "smoke_test"


# A gate is a predicate over tool output, never prose.
GATES = {
    Phase.DEPLOY: lambda tool_results: tool_results.get("verify_schema", {}).get("status") == "ok",
}


@dataclass
class Checkpoint:
    checkpoint_id: int
    phase: Phase


@dataclass
class Summary:
    source_checkpoint_id: int
    implied_next_phase: Phase
    fidelity_score: float  # referential coverage; NOT operational fidelity


def reconcile(summary: Summary, checkpoint: Checkpoint, tool_results: dict) -> Phase:
    # A high fidelity score is not evidence of operational fidelity.
    if summary.fidelity_score < 0.0 or summary.fidelity_score > 1.0:
        raise CompactionDriftError(f"invalid fidelity score {summary.fidelity_score}")

    if summary.source_checkpoint_id < checkpoint.checkpoint_id:
        # Summary is stale: a phase transition may have occurred after
        # summarization that the summary cannot know about.
        raise CompactionDriftError(
            f"summary derived from checkpoint {summary.source_checkpoint_id} "
            f"predates current checkpoint {checkpoint.checkpoint_id}; "
            f"phase must be re-derived from retained tool results, not the summary"
        )

    if summary.implied_next_phase != checkpoint.phase:
        # The summary has dissolved a gate or reordered the plan.
        raise CompactionDriftError(
            f"summary implies phase {summary.implied_next_phase.value} but "
            f"checkpoint holds {checkpoint.phase.value}; refusing to act on summary"
        )

    # Even with agreement, a gated action must satisfy its predicate.
    gate = GATES.get(checkpoint.phase)
    if gate is not None and not gate(tool_results):
        raise CompactionDriftError(
            f"phase {checkpoint.phase.value} is gated and its precondition "
            f"is unsatisfied by current tool results"
        )

    return checkpoint.phase


def resume_after_compaction(summary: Summary, checkpoint: Checkpoint, tool_results: dict) -> Phase:
    return reconcile(summary, checkpoint, tool_results)
