# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-compaction-summary-as-a-lossy-index-rather-than-a-faithful-state-image-and-rehydrate-before-acting.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-compaction-summary-as-a-lossy-index-rather-than-a-faithful-state-image-and-rehydrate-before-acting.warrant.json
# Markdown SHA-256:   28ebe76d1be3558860cc7b18c64096bc3c54c71a3809d939f2bf645a344fc2ee
# Code AST SHA-256:   4edb38d1870b0637a09541d83bb94992a46d6799eb289ff5cd3fc066f9ceed72
# Verified Classes:   Preservation, CompactionClassificationError, LossManifest, Digest, Action
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Preservation(Enum):
    VERBATIM = "verbatim"
    SUMMARIZED = "summarized"
    DROPPED = "dropped"


class CompactionClassificationError(RuntimeError):
    """Raised when an agent attempts to act on a lossy digest as if it were a state image."""


@dataclass
class LossManifest:
    span_id: str
    obligations: Preservation
    polarity: Preservation
    scope_qualifiers: Preservation

    def is_state_image(self) -> bool:
        return all(
            p is Preservation.VERBATIM
            for p in (self.obligations, self.polarity, self.scope_qualifiers)
        )


@dataclass
class Digest:
    text: str
    manifest: Optional[LossManifest] = None
    rehydrate_key: Optional[str] = None


@dataclass
class Action:
    name: str
    irreversible: bool
    depends_on: set[str] = field(default_factory=set)


def gate_action(digest: Digest, action: Action) -> str:
    """
    Returns 'proceed' or 'rehydrate'. Raises if the agent tries to bypass the gate
    on an irreversible action backed only by a lossy or unmanifested digest.
    """
    if digest.manifest is None:
        # Fail-closed: absence of a manifest means presumed lossy.
        if action.irreversible:
            raise CompactionClassificationError(
                f"Action {action.name!r} is irreversible but digest carries no loss "
                f"manifest; digest is an unverified index, not a state image."
            )
        return "rehydrate"

    if digest.manifest.is_state_image():
        return "proceed"

    # Digest is a lossy index. Any dependency on a summarized/dropped category
    # forces rehydration before an irreversible action.
    lossy_categories = {
        cat
        for cat, p in (
            ("obligations", digest.manifest.obligations),
            ("polarity", digest.manifest.polarity),
            ("scope_qualifiers", digest.manifest.scope_qualifiers),
        )
        if p is not Preservation.VERBATIM
    }

    if action.irreversible and (action.depends_on & lossy_categories):
        if digest.rehydrate_key is None:
            raise CompactionClassificationError(
                f"Action {action.name!r} depends on lossy categories "
                f"{sorted(action.depends_on & lossy_categories)} but digest has no "
                f"rehydrate_key; span is orphaned and cannot be recovered."
            )
        return f"rehydrate:{digest.rehydrate_key}"

    return "proceed"


# Reproduction of the observed incident:
incident_digest = Digest(
    text="Schema migration for orders was drafted and reviewed; proceed with deployment.",
    manifest=LossManifest(
        span_id="span-0042",
        obligations=Preservation.DROPPED,       # "will revise" lost
        polarity=Preservation.SUMMARIZED,       # REJECTED -> "reviewed"
        scope_qualifiers=Preservation.DROPPED,  # "from my side" lost
    ),
    rehydrate_key="span-0042",
)

deploy = Action(
    name="deploy_orders_migration",
    irreversible=True,
    depends_on={"obligations", "polarity"},
)

verdict = gate_action(incident_digest, deploy)
assert verdict == "rehydrate:span-0042", verdict
print(verdict)  # agent must rehydrate before deploying
