# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-collapse-when-a-retrieved-memory-s-source-lineage-is-overwritten-by-a-semantically-similar-synthesis.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-collapse-when-a-retrieved-memory-s-source-lineage-is-overwritten-by-a-semantically-similar-synthesis.warrant.json
# Markdown SHA-256:   298e6a6a8aba9b3666ef656e443dc84049eb718408234730d8057bc7388502de
# Code AST SHA-256:   829b17d2fdc1b5b233209a3102cc14f2c50daa38fbb77733b398d571a16d5176
# Verified Classes:   Leaf, Synthesis, ProvenanceCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Polarity = Literal["assert", "deny", "unknown"]

@dataclass
class Leaf:
    record_id: str
    predicate: str
    polarity: Polarity
    source_tool: str
    run_id: str

@dataclass
class Synthesis:
    record_id: str
    inputs: list[str]
    centroid_text: str
    lineage_depth: int = 1

class ProvenanceCollapseError(RuntimeError):
    """Raised when a synthesis record is asked to act as a terminal citation
    while its leaves disagree on a predicate the downstream action touches,
    or when lineage depth exceeds the auditable budget."""

MAX_LINEAGE_DEPTH = 3

def resolve_to_leaves(
    record_id: str,
    store: dict[str, Leaf | Synthesis],
    depth: int = 0,
) -> list[Leaf]:
    if depth > MAX_LINEAGE_DEPTH:
        raise ProvenanceCollapseError(
            f"lineage depth exceeded {MAX_LINEAGE_DEPTH} at {record_id}; "
            f"record is unattributable — refuse irreversible actions"
        )
    node = store[record_id]
    if isinstance(node, Leaf):
        return [node]
    leaves: list[Leaf] = []
    for parent in node.inputs:
        leaves.extend(resolve_to_leaves(parent, store, depth + 1))
    return leaves

def admit_as_premise(
    record_id: str,
    store: dict[str, Leaf | Synthesis],
    downstream_action: str,
    irreversible: bool,
) -> list[Leaf]:
    """Return the leaves the planner must see. Raise if the summary is
    inadmissible because leaves conflict on a touched predicate."""
    node = store[record_id]
    if isinstance(node, Leaf):
        return [node]

    leaves = resolve_to_leaves(record_id, store)

    # Group leaf polarity by predicate.
    by_pred: dict[str, set[Polarity]] = {}
    for leaf in leaves:
        by_pred.setdefault(leaf.predicate, set()).add(leaf.polarity)

    conflicting = {
        pred: pols for pred, pols in by_pred.items()
        if len(pols - {"unknown"}) > 1
    }

    if conflicting:
        raise ProvenanceCollapseError(
            f"synthesis {record_id} collapses conflicting leaves on "
            f"{sorted(conflicting)}; downstream action '{downstream_action}' "
            f"touches a contested predicate — surface leaves to planner, "
            f"do not use centroid as terminal premise"
        )

    if irreversible:
        # Even without detected conflict, irreversible actions require leaves.
        return leaves

    # Reversible action, no conflict: centroid admissible as terminal.
    return leaves
