# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tagged-memory-writes-from-silently-overwriting-contradicting-facts-during-cross-session-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tagged-memory-writes-from-silently-overwriting-contradicting-facts-during-cross-session-consolidation.warrant.json
# Markdown SHA-256:   2af27f42a500753c61cad3e48e8dff08992027f04785491c5ecc42b2e08630e3
# Code AST SHA-256:   54d04c9ade75df4609d6d878985a2ed4a3d41f98c3b0b0d8475725cb7cb3fa06
# Verified Classes:   ProvenanceInvariantError, Assertion, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal
from datetime import datetime


class ProvenanceInvariantError(RuntimeError):
    """Raised when a consolidation write would destroy a contradicting assertion's provenance."""
    pass


@dataclass
class Assertion:
    subject: str
    predicate: str
    object: str
    source_session: int
    turn: int
    observed_at: datetime
    confidence: float
    modality: Literal["assertoric", "conditional", "hypothetical", "quoted"] = "assertoric"
    supersedes: list["Assertion"] = field(default_factory=list)


class ProvenanceStore:
    def __init__(self) -> None:
        # Append-only node set; "current" is derived, never stored destructively.
        self._nodes: list[Assertion] = []

    def _key(self, a: Assertion) -> tuple[str, str]:
        return (a.subject, a.predicate)

    def current(self, subject: str, predicate: str) -> Assertion | None:
        candidates = [n for n in self._nodes if self._key(n) == (subject, predicate)]
        if not candidates:
            return None
        # Deterministic read-time rule: highest confidence among promotable nodes,
        # tie-broken by latest observed_at. Conditional/hypothetical nodes never win.
        promotable = [n for n in candidates if n.modality == "assertoric"]
        pool = promotable or candidates
        return max(pool, key=lambda n: (n.confidence, n.observed_at))

    def consolidate(self, new: Assertion, override: bool = False) -> None:
        incumbent = self.current(new.subject, new.predicate)

        # Recording is unconditional: the node is always appended with intact provenance.
        # Resolution is gated: only promotable observations may become current.
        if incumbent is not None and incumbent.object != new.object:
            if new.modality != "assertoric" and not override:
                self._nodes.append(new)
                return  # recorded as a sibling; incumbent stays current
            if new.confidence < incumbent.confidence and not override:
                raise ProvenanceInvariantError(
                    f"Refusing to supersede {incumbent.object!r} "
                    f"(conf={incumbent.confidence}, session={incumbent.source_session}) "
                    f"with {new.object!r} (conf={new.confidence}, session={new.source_session}) "
                    f"for key {self._key(new)}: lower-confidence write would launder "
                    f"contradiction into silent supersession."
                )
            new.supersedes.append(incumbent)

        self._nodes.append(new)

    def audit(self, subject: str, predicate: str) -> list[Assertion]:
        return [n for n in self._nodes if self._key(n) == (subject, predicate)]
