# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-before-a-forget-propagation-wave-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-before-a-forget-propagation-wave-completes.warrant.json
# Markdown SHA-256:   539aff2c978aa61674d69ceefb23dcaecda0c3ef5a54bb587e233d24c1aa6c58
# Code AST SHA-256:   d487a6956c210bceca7ca41d39cd83de89e26dda79abdb2aa4e1b09940b2c372
# Verified Classes:   ForgetPropagationIncomplete, SemanticRule, PeerMemory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ForgetPropagationIncomplete(RuntimeError):
    """Raised when a FORGET wave reports handler success but structural poisoning persists."""
    pass


@dataclass
class SemanticRule:
    rule_id: str
    text_hash: str
    confidence: float
    provenance: str          # source id this rule was distilled from
    citation_count: int = 0


@dataclass
class PeerMemory:
    node_id: str
    rules: Dict[str, SemanticRule] = field(default_factory=dict)
    tombstoned_sources: set = field(default_factory=set)
    sentinel_topk: Dict[str, set] = field(default_factory=dict)


def structural_reconciliation(
    peers: List[PeerMemory],
    sentinel_queries: List[str],
    confidence_divergence_threshold: float = 0.3,
) -> None:
    """
    Phase-two gate. Must run after content-hash FORGET handlers report success.
    Raises if any structural poisoning signal survives the wave.
    """
    orphans: List[str] = []
    ratchets: List[str] = []
    drifts: List[str] = []

    # Signal 1 + 3: provenance-orphans and re-citation ratchets
    for peer in peers:
        for rule in peer.rules.values():
            if rule.provenance in peer.tombstoned_sources:
                orphans.append(f"{peer.node_id}:{rule.rule_id} -> dead {rule.provenance}")
            if rule.citation_count > 0 and rule.confidence >= 0.65:
                # confidence climbing with no fresh-evidence marker
                ratchets.append(f"{peer.node_id}:{rule.rule_id} conf={rule.confidence:.2f}")

    # Signal 2: cross-peer confidence divergence on identical claim hashes
    by_hash: Dict[str, List[tuple]] = {}
    for peer in peers:
        for rule in peer.rules.values():
            by_hash.setdefault(rule.text_hash, []).append((peer.node_id, rule.confidence))
    for h, holders in by_hash.items():
        confs = [c for _, c in holders]
        if len(confs) > 1 and (max(confs) - min(confs)) > confidence_divergence_threshold:
            orphans.append(f"divergent claim {h[:8]}: {holders}")

    # Signal 4: sentinel retrieval drift
    for q in sentinel_queries:
        sets = [p.sentinel_topk.get(q) for p in peers if q in p.sentinel_topk]
        if len(sets) >= 2:
            union = set().union(*sets)
            inter = set.intersection(*sets)
            if union and len(inter) / len(union) < 0.5:
                drifts.append(q)

    if orphans or ratchets or drifts:
        raise ForgetPropagationIncomplete(
            f"FORGET wave incomplete: orphans={orphans} ratchets={ratchets} drift={drifts}"
        )
    # else: wave may be marked COMPLETE
