# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-memory-to-semantic-status-when-the-episode-s-tool-call-evidence-is-internally-con.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-memory-to-semantic-status-when-the-episode-s-tool-call-evidence-is-internally-con.warrant.json
# Markdown SHA-256:   3f1822d5c2f052b69f4dd6f136b43456e4720dedf3ddffd6f9643be330b77600
# Code AST SHA-256:   e4131bde274f2e43bb4b318ac6d4ba6ff8568c91782001ec368fa5adb5f1576d
# Verified Classes:   ReferentialStabilityError, Resolution, Episode, Index
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ReferentialStabilityError(RuntimeError):
    """Raised when an episodic record cannot be proven referentially stable
    against the current retrieval index generation."""
    pass


@dataclass
class Resolution:
    identifier: str
    content_hash: str
    generation: str


@dataclass
class Episode:
    episode_id: str
    recorded_generation: str
    resolutions: dict[str, Resolution] = field(default_factory=dict)
    assertion: Optional[str] = None


@dataclass
class Index:
    generation: str
    # identifier -> (content_hash, tombstoned)
    nodes: dict[str, tuple[str, bool]] = field(default_factory=dict)
    # old_generation -> {old_id: new_id}; absent means no mapping
    migrations: dict[str, dict[str, str]] = field(default_factory=dict)

    def resolve(self, identifier: str) -> tuple[str, bool]:
        return self.nodes.get(identifier, ("", True))


def consolidate(episode: Episode, index: Index) -> str:
    """Promote an episode to semantic memory only if referentially stable.
    Returns the promoted assertion. Raises on any unproven binding."""
    if not episode.assertion:
        raise ReferentialStabilityError(
            f"{episode.episode_id}: no assertion to promote"
        )

    # Generation unchanged: epistemic replay already passed upstream.
    if index.generation == episode.recorded_generation:
        return episode.assertion

    # Generation changed. Require a total migration mapping over bound refs.
    mapping = index.migrations.get(episode.recorded_generation)
    if mapping is None:
        raise ReferentialStabilityError(
            f"{episode.episode_id}: index moved {episode.recorded_generation}"
            f"->{index.generation} with no recorded migration; cannot prove"
            f" referential stability, refusing promotion"
        )

    for ident, rec in episode.resolutions.items():
        if ident not in mapping:
            # A tombstoned/unmapped ref is NOT evidence of supersession.
            raise ReferentialStabilityError(
                f"{episode.episode_id}: ref {ident} has no migration entry "
                f"(tombstoned or dropped); partial mapping is a refuse, not "
                f"a promote-what-survives"
            )
        new_id = mapping[ident]
        new_hash, tombstoned = index.resolve(new_id)
        if tombstoned:
            raise ReferentialStabilityError(
                f"{episode.episode_id}: ref {ident} maps to {new_id} which is "
                f"tombstoned in {index.generation}"
            )
        if new_hash != rec.content_hash:
            raise ReferentialStabilityError(
                f"{episode.episode_id}: ref {ident} re-bound to {new_id} with "
                f"content_hash {new_hash} != recorded {rec.content_hash}; "
                f"identifier survived but referent moved"
            )

    return episode.assertion


def _demo() -> None:
    ep = Episode(
        episode_id="e_7741",
        recorded_generation="idx_v12",
        assertion="billing retention default is 90 days in us-east",
    )
    ep.resolutions["doc_8821"] = Resolution("doc_8821", "h_30d", "idx_v12")
    ep.resolutions["doc_8830"] = Resolution("doc_8830", "h_90d", "idx_v12")

    # Post-compaction: 8821 re-pointed to 90-day content, 8830 tombstoned.
    idx = Index(generation="idx_v13")
    idx.nodes["doc_8821"] = ("h_90d", False)
    idx.nodes["doc_8830"] = ("", True)
    idx.migrations["idx_v12"] = {"doc_8821": "doc_8821"}  # 8830 unmapped

    # Replay would PASS here (read(doc_8821) returns h_90d, matching a
    # rationalized reading). Consolidation must still refuse.
    try:
        consolidate(ep, idx)
    except ReferentialStabilityError as e:
        print("REFUSED:", e)
        raise


if __name__ == "__main__":
    _demo()
