# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distinguish-provenance-tracked-memory-from-poisoned-memory-before-recall-and-why-does-confidence-weighted-retrieval-silently-de.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distinguish-provenance-tracked-memory-from-poisoned-memory-before-recall-and-why-does-confidence-weighted-retrieval-silently-de.warrant.json
# Markdown SHA-256:   5a2d46ee80cff596678b9e55d63fbbcf37b709095c71a0fe7c1759616a353dd2
# Code AST SHA-256:   c02ba73c25128c98d023e6af6ea30e879eb9392609baaed31945380eba6ea0e9
# Verified Classes:   ProvenanceViolation, MemoryEntry, SignedProvenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a memory entry's provenance cannot be validated as a hard gate."""
    pass


@dataclass(frozen=True)
class MemoryEntry:
    entry_id: str
    content: str
    writer_id: str
    warrant_token: str
    source_tool_calls: tuple[str, ...]
    parent_episode_id: Optional[str]
    writer_confidence: float  # adversarial: must never enter ranking


@dataclass(frozen=True)
class SignedProvenance:
    entry_id: str
    writer_id: str
    warrant_scope: frozenset[str]
    tool_lineage: tuple[str, ...]
    signature_valid: bool


LOW_TRUST_TOOLS = frozenset({"scrape_summarize", "web_extract_unverified"})


def provenance_valid(
    entry: MemoryEntry,
    signed: SignedProvenance,
    tool_trust: Callable[[str], bool],
) -> bool:
    """Boolean gate. Must be evaluated before any ranking. No fallback."""
    if not signed.signature_valid:
        return False
    if signed.entry_id != entry.entry_id or signed.writer_id != entry.writer_id:
        return False
    if entry.warrant_token not in signed.warrant_scope:
        return False
    if tuple(entry.source_tool_calls) != tuple(signed.tool_lineage):
        return False
    if any(not tool_trust(t) for t in signed.tool_lineage):
        return False
    return True


def recall(
    query: str,
    entries: list[MemoryEntry],
    signed_by_id: dict[str, SignedProvenance],
    embed_score: Callable[[str, str], float],
    tool_trust: Callable[[str], bool],
    k: int = 5,
) -> list[MemoryEntry]:
    gated: list[MemoryEntry] = []
    for e in entries:
        signed = signed_by_id.get(e.entry_id)
        if signed is None:
            # Missing provenance is a violation, not a low score.
            raise ProvenanceViolation(
                f"entry {e.entry_id} has no signed provenance record"
            )
        if provenance_valid(e, signed, tool_trust):
            gated.append(e)
        # else: quarantined, unreachable, never falls back to unfiltered set

    if not gated:
        # Explicit empty, never a fallback to the unfiltered set.
        return []

    # Ranking uses ONLY reader-derived relevance. writer_confidence is ignored.
    ranked = sorted(gated, key=lambda e: embed_score(query, e.content), reverse=True)
    return ranked[:k]


def recall_or_escalate(
    query: str,
    entries: list[MemoryEntry],
    signed_by_id: dict[str, SignedProvenance],
    embed_score: Callable[[str, str], float],
    tool_trust: Callable[[str], bool],
) -> list[MemoryEntry]:
    result = recall(query, entries, signed_by_id, embed_score, tool_trust)
    if not result:
        raise ProvenanceViolation(
            f"no provenance-valid memory for query {query!r}; escalate to tool re-query"
        )
    return result
