# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-trust-score-drop-as-retroactive-invalidation-of-already-retrieved-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-trust-score-drop-as-retroactive-invalidation-of-already-retrieved-memory.warrant.json
# Markdown SHA-256:   7e2653f8be3a5c957042eab7b19b0ef923f8dd1314e05533cb1217bcbde288ee
# Code AST SHA-256:   ff00270168545a359555ed15648fc26f97babecd9ee69353c6c69d619b637ad9
# Verified Classes:   TrustEpochDivergence, TrustSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TrustEpochDivergence(RuntimeError):
    """Raised when a commit's justification set cites a stale trust snapshot."""
    pass


@dataclass(frozen=True)
class TrustSnapshot:
    entry_id: str
    score: float
    epoch: int


def validate_justification_set(
    cited: list[TrustSnapshot],
    store_epochs: dict[str, int],
) -> None:
    """
    Commit-time OCC validation for trust-scored memory.

    `cited` is the read-set: every entry whose trust score justified the
    action about to commit. `store_epochs` must be read as a single
    consistent snapshot from the store, not per-entry.

    Raises TrustEpochDivergence if any cited entry's epoch has advanced
    since retrieval. Caller must abort and replan; do not catch and continue.
    """
    diverged = [
        s for s in cited
        if store_epochs.get(s.entry_id) != s.epoch
    ]
    if diverged:
        details = ", ".join(
            f"{s.entry_id}: cited_epoch={s.epoch} "
            f"current_epoch={store_epochs.get(s.entry_id)} "
            f"cited_score={s.score}"
            for s in diverged
        )
        raise TrustEpochDivergence(
            f"trust snapshot stale at commit; abort and replan: {details}"
        )


def commit_action(
    action: str,
    cited: list[TrustSnapshot],
    store_epochs: dict[str, int],
    score_floor: float = 0.80,
) -> None:
    # Order matters: validate epochs BEFORE checking the floor. A demoted
    # entry may still pass the floor on its stale score; the epoch check
    # is what catches it.
    validate_justification_set(cited, store_epochs)

    for s in cited:
        if s.score < score_floor:
            raise TrustEpochDivergence(
                f"cited entry {s.entry_id} below floor "
                f"({s.score} < {score_floor}) at commit"
            )

    # ... execute action against validated justification set ...
