# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-consistent-memory-semantic-store-confirmation-of-a-poisoned-episodic-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-consistent-memory-semantic-store-confirmation-of-a-poisoned-episodic-fact.warrant.json
# Markdown SHA-256:   8ea854b032fcb55a7fd2ef09880d772928f0b09bc3d450c7e0125fbccdfb1782
# Code AST SHA-256:   dd3e6c732720e7eb51345f0ebd22410d8ba05cdaad6eaaae8f736ae771080595
# Verified Classes:   NonIndependentCorroborationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class NonIndependentCorroborationError(RuntimeError):
    """Raised when a consistency check would confirm a fact using its own provenance."""
    pass


def resolve_root_evidence(record: dict) -> frozenset:
    # Walk provenance to the set of distinct root evidence source ids.
    roots = set()
    stack = [record]
    seen = set()
    while stack:
        node = stack.pop()
        nid = node.get("id")
        if nid in seen:
            continue
        seen.add(nid)
        prov = node.get("provenance")
        if prov is None or prov.get("kind") == "root":
            roots.add(node.get("source_id", nid))
        else:
            for parent in prov.get("parents", []):
                stack.append(parent)
    return frozenset(roots)


def lineage_aware_consistency(episodic: dict, semantic: dict) -> bool:
    ep_roots = resolve_root_evidence(episodic)
    sem_roots = resolve_root_evidence(semantic)

    if ep_roots & sem_roots:
        # Agreement here is tautological: semantic descends from this episode.
        raise NonIndependentCorroborationError(
            f"semantic fact {semantic.get('id')} shares root evidence "
            f"{sorted(ep_roots & sem_roots)} with episodic {episodic.get('id')}; "
            f"agreement is non-independent and cannot confirm the fact"
        )

    # Disjoint roots: agreement is genuine corroboration.
    return episodic.get("value") == semantic.get("value")


def pre_action_gate(episodic: dict, semantic: dict) -> str:
    try:
        if lineage_aware_consistency(episodic, semantic):
            return "trusted"
    except NonIndependentCorroborationError as exc:
        # Do not proceed on non-independent agreement; escalate.
        return f"escalate_independent_verification: {exc}"
    return "unconfirmed"
