# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-read-a-federated-memory-record-it-is-not-scoped-to-when-the-scope-predicate-is-evaluated-against-a-stale-namespace-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-read-a-federated-memory-record-it-is-not-scoped-to-when-the-scope-predicate-is-evaluated-against-a-stale-namespace-snapshot.warrant.json
# Markdown SHA-256:   445c1de311c50bb193fbe5795cbd39ede17275885da681239858ebf57788ad16
# Code AST SHA-256:   2ead40ca4d7c114de8a7a67b117738996dd9468b97b96c7888e391299eeba9d5
# Verified Classes:   StaleGrantAdmissionError, DerivedRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleGrantAdmissionError(RuntimeError):
    """Raised when derived memory is admitted under a grant epoch that the
    authoritative manifest no longer honors for the reading org."""
    pass


@dataclass(frozen=True)
class DerivedRecord:
    source_namespace: str
    grant_epoch: int
    payload: str


def admit_derived_record(
    record: DerivedRecord,
    reader_org: str,
    authoritative_manifest: dict,
) -> DerivedRecord:
    """Re-validate a derived record against the authoritative manifest before
    re-surfacing it. This is the re-surface guardrail; it is NOT the access
    check and must not be collapsed into it."""
    entry = authoritative_manifest.get(record.source_namespace)
    if entry is None:
        raise StaleGrantAdmissionError(
            f"namespace {record.source_namespace!r} no longer published; "
            f"record admitted under epoch {record.grant_epoch} is orphaned"
        )
    if reader_org not in entry["reader_orgs"]:
        raise StaleGrantAdmissionError(
            f"org {reader_org!r} not in reader_orgs for "
            f"{record.source_namespace!r}; grant revoked after epoch "
            f"{record.grant_epoch}"
        )
    if entry["record_epoch"] > record.grant_epoch:
        raise StaleGrantAdmissionError(
            f"record epoch {record.grant_epoch} predates authoritative "
            f"epoch {entry['record_epoch']} for {record.source_namespace!r}; "
            f"re-validation required"
        )
    return record


def resurface(
    records: list[DerivedRecord],
    reader_org: str,
    authoritative_manifest: dict,
) -> list[DerivedRecord]:
    admitted, quarantined = [], []
    for r in records:
        try:
            admitted.append(admit_derived_record(r, reader_org, authoritative_manifest))
        except StaleGrantAdmissionError:
            quarantined.append(r)
    return admitted
