# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-hierarchical-summarization-loss-before-a-lossy-checkpoint-recovery-is-permitted-to-rehydrate-context.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-hierarchical-summarization-loss-before-a-lossy-checkpoint-recovery-is-permitted-to-rehydrate-context.warrant.json
# Markdown SHA-256:   9c583f100087c6423b65813312ee50303ab20efd91e9604082cacee4fe8e2492
# Code AST SHA-256:   3479c5e6ee64119e5e215d7de9b688fbb3608322437149e0246eb75d9c6568fe
# Verified Classes:   ReferentFate, UnrecoverableReferentError, ReferentManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ReferentFate(Enum):
    VERBATIM = "verbatim"
    PARAPHRASED = "paraphrased"
    ABSENT = "absent"


class UnrecoverableReferentError(RuntimeError):
    """Raised when a plan-frontier step dereferences a referent that did not
    survive checkpoint compaction verbatim. Recovery must be refused, not
    attempted, because rehydration would confabulate a plausible literal."""


@dataclass
class ReferentManifest:
    # referent_id -> fate at the persisted checkpoint level
    fates: dict[str, ReferentFate] = field(default_factory=dict)
    # referent_id -> verbatim literal, only for VERBATIM survivors
    literals: dict[str, str] = field(default_factory=dict)

    def resolve(self, referent_id: str, step_name: str) -> str:
        fate = self.fates.get(referent_id)
        if fate is ReferentFate.VERBATIM and referent_id in self.literals:
            return self.literals[referent_id]
        if fate is ReferentFate.PARAPHRASED:
            raise UnrecoverableReferentError(
                f"step '{step_name}' dereferences referent '{referent_id}' "
                f"which was paraphrased during compaction; literal unavailable"
            )
        if fate is ReferentFate.ABSENT or fate is None:
            raise UnrecoverableReferentError(
                f"step '{step_name}' dereferences referent '{referent_id}' "
                f"absent from persisted checkpoint; refusing lossy recovery"
            )
        raise UnrecoverableReferentError(
            f"inconsistent manifest state for referent '{referent_id}'"
        )


def rehydrate_and_execute(
    manifest: ReferentManifest,
    plan_frontier: list[tuple[str, list[str]]],
) -> list[str]:
    """plan_frontier: list of (step_name, [referent_ids the step will emit]).
    Validates dereference closure BEFORE any execution; refuses on first miss."""
    resolved_commands: list[str] = []
    for step_name, referent_ids in plan_frontier:
        args = [manifest.resolve(rid, step_name) for rid in referent_ids]
        resolved_commands.append(f"{step_name}({', '.join(args)})")
    return resolved_commands


# Reproduces the observed auth/billing failure:
manifest = ReferentManifest(
    fates={
        "scope_flag": ReferentFate.PARAPHRASED,  # dropped at S-4, absent at R-1
        "auth_migration_path": ReferentFate.VERBATIM,
    },
    literals={"auth_migration_path": "services/auth/migrations/0007_add_tenant.sql"},
)
frontier = [
    ("modify", ["auth_migration_path"]),
    ("run_tests", ["scope_flag"]),  # triggers refusal
]

try:
    rehydrate_and_execute(manifest, frontier)
except UnrecoverableReferentError as e:
    # Correct behavior: halt and re-derive the scope flag from source/user,
    # rather than silently running the full test tree.
    print(f"RECOVERY REFUSED: {e}")
