# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-at-the-write-forget-boundary-in-provenance-tracked-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-at-the-write-forget-boundary-in-provenance-tracked-agent-memory.warrant.json
# Markdown SHA-256:   cfcfd32a095483842dddc28d4af3ecc1924b89e86bc0325cb073b9aca6efb47f
# Code AST SHA-256:   75889d8346624e015e57c37fee75a6572adbb51858eca49355c909d5abf23372
# Verified Classes:   ProvenancePoisoningError, Provenance, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenancePoisoningError(RuntimeError):
    """Raised when a forget/write provenance pattern matches the poisoning triple."""
    pass

@dataclass
class Provenance:
    source: str
    session: str
    trust_tier: int
    corroborating_sessions: list = field(default_factory=list)
    authorizing_entry: Optional[str] = None  # set on forget ops

@dataclass
class MemoryEntry:
    entry_id: str
    provenance: Provenance
    topic_cluster: str

def check_forget_authorization(entry: MemoryEntry, forget: Provenance) -> None:
    if forget.authorizing_entry is None:
        raise ProvenancePoisoningError(
            f"forget on {entry.entry_id} has no authorizing_entry; cannot verify provenance chain"
        )
    # Self-loop: the entry being deleted is its own sole warrant.
    if forget.authorizing_entry == entry.entry_id:
        raise ProvenancePoisoningError(
            f"self-authorized forget: {entry.entry_id} is the sole warrant for its own deletion "
            f"(forget session={forget.session}, tier={forget.trust_tier})"
        )
    # Tier monotonicity: a forget cannot be warranted by a lower tier than the entry.
    if forget.trust_tier < entry.provenance.trust_tier:
        raise ProvenancePoisoningError(
            f"tier downgrade on forget: entry tier={entry.provenance.trust_tier}, "
            f"forget tier={forget.trust_tier} for {entry.entry_id}"
        )

def check_write_corroboration(entry: MemoryEntry, window_sessions: int = 3) -> str:
    p = entry.provenance
    if p.trust_tier <= 2 and not p.corroborating_sessions:
        return "quarantine"  # provisional; force competitor surfacing
    return "accept"

def check_post_delete_rank_shift(
    deleted: MemoryEntry, rank_delta: float, threshold: float = 0.15
) -> None:
    if abs(rank_delta) > threshold:
        raise ProvenancePoisoningError(
            f"post-delete rank shift {rank_delta:+.3f} on cluster {deleted.topic_cluster} "
            f"exceeds {threshold}; poisoning may have propagated into ranker state, "
            f"reindex required (not just undelete)"
        )
