# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-trust-scoring-from-silently-ratifying-a-poisoned-memory-after-cross-session-corroboration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-trust-scoring-from-silently-ratifying-a-poisoned-memory-after-cross-session-corroboration.warrant.json
# Markdown SHA-256:   6f1830c3eb09f73b864ddfa88b6695f52549c2f1ea89a165272ba63c9b64d8ec
# Code AST SHA-256:   749ddec8dedc5ae0640674683448bafce6afa63f6a0a41a2caeeb491434c267c
# Verified Classes:   ProvenanceCycleError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceCycleError(RuntimeError):
    """Raised when a merge would make a record corroborate itself via its own descendants."""
    pass


@dataclass
class MemoryRecord:
    claim: str
    writer_id: str
    session_id: str
    write_time_trust: float
    parent_record_ids: tuple[str, ...] = field(default_factory=tuple)
    record_id: str = ""


def _ancestors(record_id: str, store: dict[str, MemoryRecord], seen: Optional[set] = None) -> set[str]:
    if seen is None:
        seen = set()
    if record_id in seen:
        return seen
    seen.add(record_id)
    rec = store.get(record_id)
    if rec is None:
        return seen
    for pid in rec.parent_record_ids:
        _ancestors(pid, store, seen)
    return seen


def merge_into_cluster(
    incoming: MemoryRecord,
    cluster_member_ids: set[str],
    store: dict[str, MemoryRecord],
) -> float:
    """
    Merge `incoming` into a claim cluster and return the cluster's new
    independent-root provenance floor. Raises if the merge would create
    self-corroboration (incoming is a descendant of a cluster member, or a
    cluster member is a descendant of incoming).
    """
    incoming_ancestors = _ancestors(incoming.record_id, store)

    # Invariant 1: causal independence. Incoming must not be downstream of any
    # cluster member, and no cluster member may be downstream of incoming.
    for member_id in cluster_member_ids:
        if member_id in incoming_ancestors:
            raise ProvenanceCycleError(
                f"merge rejected: incoming record {incoming.record_id} is a "
                f"descendant of cluster member {member_id}; counting it would "
                f"let the cluster corroborate itself"
            )
        member_ancestors = _ancestors(member_id, store)
        if incoming.record_id in member_ancestors:
            raise ProvenanceCycleError(
                f"merge rejected: cluster member {member_id} is a descendant "
                f"of incoming record {incoming.record_id}"
            )

    # Invariant 2: provenance monotonicity. Cluster provenance is the minimum
    # over independent roots, never inherited from the highest-trust member.
    root_trusts = [incoming.write_time_trust]
    for member_id in cluster_member_ids:
        member = store[member_id]
        root_trusts.append(member.write_time_trust)
    return min(root_trusts)


def recompute_trust(
    record: MemoryRecord,
    cluster_member_ids: set[str],
    store: dict[str, MemoryRecord],
    lam: float = 0.15,
    decay: float = 1.0,
    threshold: float = 0.7,
) -> float:
    """
    Recompute trust for `record` given its cluster. Corroboration is counted
    only over members that are NOT descendants of the record; provenance
    floor is the min over independent roots. Returns the score and raises if
    the record would cross the retrieval threshold on self-corroboration.
    """
    record_ancestors = _ancestors(record.record_id, store)
    independent = [
        m for m in cluster_member_ids
        if record.record_id not in _ancestors(m, store)
    ]
    corroboration = len(independent)
    provenance_floor = min(
        [record.write_time_trust] + [store[m].write_time_trust for m in independent]
    )
    score = provenance_floor * decay + lam * corroboration

    if score >= threshold and corroboration > 0 and provenance_floor < 0.5:
        raise ProvenanceCycleError(
            f"trust recomputation for {record.record_id} would cross {threshold} "
            f"on corroboration from a low-provenance source "
            f"(floor={provenance_floor:.2f}); refuse promotion"
        )
    return score
