# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-memory-poisoning-detector-that-passes-every-per-write-provenance-check-still-fail-to-detect-a-poisoned-memory-at-read-time-a.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-memory-poisoning-detector-that-passes-every-per-write-provenance-check-still-fail-to-detect-a-poisoned-memory-at-read-time-a.warrant.json
# Markdown SHA-256:   a32e9b8be4443d00b8497994ca873a135ad1b97c200b675f953e5243bb70af00
# Code AST SHA-256:   da7dca99c1daf2f4d4ab717709280e0a7f7bc1a6782dab2fede7e222b290c2ff
# Verified Classes:   ReadTimeProvenanceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReadTimeProvenanceError(RuntimeError):
    """Raised when a retrieved memory's trust basis cannot be re-established
    from current session state, even though it passed write-time validation."""
    pass


def admit_memory(memory, current_context):
    """
    Read-time admission gate. A memory that passed the write-time audit is
    NOT automatically admitted: we re-establish its trust basis against the
    *current* context, because the write-time predicate may have decayed.
    """
    proof = memory.get("provenance_proof")

    # No self-contained proof => the write-time audit relied on ephemeral
    # state (delegation id, turn id, sub-agent session). That state may be
    # gone. Treat as unprovenanced at read time.
    if proof is None:
        raise ReadTimeProvenanceError(
            f"memory {memory.get('id')!r} has no self-contained provenance "
            f"proof; write-time trust basis is not re-evaluable at read time"
        )

    # Expiry must be checked against now, not against write time.
    if proof.get("expires_at") is not None and proof["expires_at"] < current_context.now:
        raise ReadTimeProvenanceError(
            f"memory {memory.get('id')!r} provenance proof expired at "
            f"{proof['expires_at']}; trust basis has decayed since write"
        )

    # Delegation liveness: the scope that made this clean at write time
    # must still be live, or the 'scoped' tag is vacuous.
    delegation_id = proof.get("delegation_id")
    if delegation_id is not None:
        if delegation_id not in current_context.live_delegations:
            raise ReadTimeProvenanceError(
                f"memory {memory.get('id')!r} was trusted under delegation "
                f"{delegation_id!r}, which is no longer live; scoped trust "
                f"cannot be inherited across context rollover"
            )

    # Re-verify any signed source against current trust roots, not the
    # roots in effect at write time.
    source = proof.get("source")
    if source not in current_context.trusted_sources:
        raise ReadTimeProvenanceError(
            f"memory {memory.get('id')!r} source {source!r} is not in the "
            f"current trust root set; write-time allowlist membership does "
            f"not persist"
        )

    return True


def retrieve_and_admit(memories, current_context):
    admitted = []
    for m in memories:
        try:
            admit_memory(m, current_context)
            admitted.append(m)
        except ReadTimeProvenanceError:
            # Downgrade to 'asserted, unverified' rather than silently using.
            m["trust"] = "unverified"
            admitted.append(m)
    return admitted
