# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-memory-that-was-verified-before-its-own-context-window-opened.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-memory-that-was-verified-before-its-own-context-window-opened.warrant.json
# Markdown SHA-256:   25646e246832884513bab40d00c61704c12ef7cbef900acaa65149dcd66a4b11
# Code AST SHA-256:   0b6990dd99e71110d8828bc13839311251f16b5d5b71d61495ac1f86f986bd40
# Verified Classes:   StaleAttestationError, Record
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass
from typing import Dict, Set


class StaleAttestationError(RuntimeError):
    """Raised when a signed memory record is genuine but no longer current."""
    pass


@dataclass(frozen=True)
class Record:
    key: str
    value: str
    writer_id: str
    epoch: int
    sig: str


def _expected_sig(secret: bytes, r: Record) -> str:
    msg = f"{r.key}|{r.value}|{r.writer_id}|{r.epoch}".encode()
    return hmac.new(secret, msg, hashlib.sha256).hexdigest()


def verify_and_resolve(
    records: Dict[str, Record],
    secret: bytes,
    current_authority: Dict[str, Set[str]],   # key -> currently authorized writers
    max_epoch: Dict[str, int],                # key -> highest attested epoch seen
) -> Dict[str, str]:
    resolved: Dict[str, str] = {}
    for key, r in records.items():
        # 1. Authorship: signature must verify.
        if not hmac.compare_digest(r.sig, _expected_sig(secret, r)):
            continue  # forged/tampered: drop silently
        # 2. Authority: writer must be authorized for THIS key now.
        if r.writer_id not in current_authority.get(key, set()):
            raise StaleAttestationError(
                f"record for {key!r} signed by {r.writer_id!r} which no longer "
                f"holds authority; genuine attestation is superseded"
            )
        # 3. Currency: epoch must be the max attested for this key.
        if r.epoch < max_epoch.get(key, r.epoch):
            raise StaleAttestationError(
                f"record for {key!r} at epoch {r.epoch} is behind attested "
                f"epoch {max_epoch[key]}; refusing to resurrect retired value"
            )
        resolved[key] = r.value
    return resolved
