# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-high-similarity-memory-provenance-weighted-recall-scoring-and-the-anchor-poisoning-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-high-similarity-memory-provenance-weighted-recall-scoring-and-the-anchor-poisoning-threshold.warrant.json
# Markdown SHA-256:   f9e01d6cc32fc6a945ec35fb60aa7493b89443c8f55781035dd1d1c1ee055100
# Code AST SHA-256:   dd4cf950803a42616f938d34928eca8e8cb5b8f717ba989e1ecf1bda03f31a16
# Verified Classes:   ProvenanceClass, ProvenanceViolation, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class ProvenanceClass(IntEnum):
    TOOL_UNTRUSTED = 0
    PEER_AGENT = 1
    INTERNAL_DERIVED = 2
    INTERNAL_SIGNED = 3


AUTHORITY_WEIGHT = {
    ProvenanceClass.TOOL_UNTRUSTED: 0.3,
    ProvenanceClass.PEER_AGENT: 0.5,
    ProvenanceClass.INTERNAL_DERIVED: 0.8,
    ProvenanceClass.INTERNAL_SIGNED: 1.0,
}


class ProvenanceViolation(RuntimeError):
    """Raised when recall or derivation would premise an action on an
    unauthorized record, or when a write launders taint above its read-set."""


@dataclass
class MemoryRecord:
    record_id: str
    text: str
    similarity: float
    write_class: ProvenanceClass
    read_set: list[str] = field(default_factory=list)

    def effective_authority(self, store: dict[str, "MemoryRecord"]) -> ProvenanceClass:
        # Taint monotonicity: authority is the minimum over the full derivation chain.
        authority = self.write_class
        for parent_id in self.read_set:
            parent = store.get(parent_id)
            if parent is None:
                raise ProvenanceViolation(
                    f"record {self.record_id} references missing parent {parent_id}; "
                    f"derivation chain unverifiable, authority cannot be established"
                )
            authority = min(authority, parent.effective_authority(store))
        return authority


def weighted_recall(
    query_similarity_floor: float,
    required_authority: ProvenanceClass,
    candidates: list[MemoryRecord],
    store: dict[str, MemoryRecord],
    top_k: int = 5,
) -> list[MemoryRecord]:
    if not candidates:
        raise ProvenanceViolation("empty candidate set; recall coverage not established")

    scored: list[tuple[float, MemoryRecord]] = []
    for rec in candidates:
        if rec.similarity < query_similarity_floor:
            # Coverage floor: admit low-similarity records so high-authority
            # memories are not excluded before provenance weighting runs.
            continue
        authority = rec.effective_authority(store)
        if authority < required_authority:
            # Hard block, not down-weight: an unauthorized record may never
            # enter the premise set for this blast radius, however similar.
            continue
        scored.append((rec.similarity * AUTHORITY_WEIGHT[authority], rec))

    if not scored:
        raise ProvenanceViolation(
            f"no authorized candidate clears coverage floor {query_similarity_floor} "
            f"at required authority {required_authority.name}; refusing to answer"
        )

    scored.sort(key=lambda pair: pair[0], reverse=True)
    return [rec for _, rec in scored[:top_k]]


def derive_summary(
    new_id: str,
    text: str,
    claimed_class: ProvenanceClass,
    read_set: list[str],
    store: dict[str, MemoryRecord],
) -> MemoryRecord:
    # Reject laundering: a derived write may not claim authority above its read-set.
    weakest = claimed_class
    for parent_id in read_set:
        parent = store.get(parent_id)
        if parent is None:
            raise ProvenanceViolation(
                f"cannot derive {new_id}: parent {parent_id} absent from store"
            )
        weakest = min(weakest, parent.effective_authority(store))
    if claimed_class > weakest:
        raise ProvenanceViolation(
            f"taint laundering: {new_id} claimed {claimed_class.name} but read-set "
            f"supports only {weakest.name}"
        )
    record = MemoryRecord(new_id, text, 1.0, weakest, list(read_set))
    store[new_id] = record
    return record
