# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-poison-is-consistent-with-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-poison-is-consistent-with-itself.warrant.json
# Markdown SHA-256:   3b768e575dd782a4ffe8c954e15441c1f3670c1451a76ef413e67e40d027c43d
# Code AST SHA-256:   e5727cb0190570b26333aa94a30aecf31b870ade513cdc11abf6dbbfd88fa813
# Verified Classes:   SelfConsistentPoisonError
# Defensive Guards:   3 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

class SelfConsistentPoisonError(RuntimeError):
    """Raised when a memory record's confidence rose without source re-derivation,
    or when consistency checking was retrieval-gated into the poison's own cluster."""
    pass


def promote_confidence(record, rederived_value, source_episodes):
    if record.value != rederived_value:
        raise SelfConsistentPoisonError(
            f"replay divergence on record {record.id}: stored={record.value!r} "
            f"rederived={rederived_value!r}; demote to hypothesis, do not use for tool calls"
        )
    if not source_episodes:
        raise SelfConsistentPoisonError(
            f"record {record.id} has no re-derivable source; confidence may not rise "
            f"(salience={record.salience}, confidence={record.confidence})"
        )
    record.confidence = min(1.0, record.confidence + 0.02)
    return record


def consistency_check(record, store, k=8, min_outside_cluster=2):
    home = record.cluster_id
    neighbors = store.similar(record.embedding, k=k)
    outside = [n for n in neighbors if n.cluster_id != home]
    if len(outside) < min_outside_cluster:
        raise SelfConsistentPoisonError(
            f"retrieval-gated comparison for {record.id}: only {len(outside)} "
            f"cross-cluster candidates; poison may be crowding out its contradiction"
        )
    return [n for n in outside if contradicts(n, record)]
