# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-memory-write-when-provenance-chains-become-circular-across-episodic-to-semantic-promotion.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-memory-write-when-provenance-chains-become-circular-across-episodic-to-semantic-promotion.warrant.json
# Markdown SHA-256:   0428de52d1d157139bb2cdc6eb923da0e3b81be87d9996ddb4010df795818c97
# Code AST SHA-256:   27d60e6fb7380db429deec59134fd7da3b041c288082931d1e84cd8ca2e8e144
# Verified Classes:   ProvenanceCycleError, EdgeKind, Record, ProvenanceStore
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class ProvenanceCycleError(RuntimeError):
    """Raised when a memory write, promote, or merge would close a cycle
    in the licensing (derives_from) provenance graph, or when a read
    encounters a record whose closure does not terminate in leaves."""


class EdgeKind(Enum):
    DERIVES_FROM = "derives_from"  # strong: licenses content
    CITES = "cites"                # weak: informational only


@dataclass
class Record:
    rid: str
    kind: str  # "episodic" | "semantic"
    sources: list[tuple[str, EdgeKind]] = field(default_factory=list)


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: dict[str, Record] = {}

    def _licensing_parents(self, rid: str) -> list[str]:
        rec = self._records.get(rid)
        if rec is None:
            return []
        return [src for src, kind in rec.sources if kind is EdgeKind.DERIVES_FROM]

    def _closure(self, rid: str, seen: frozenset[str] = frozenset()) -> set[str]:
        if rid in seen:
            raise ProvenanceCycleError(
                f"cycle detected while traversing provenance of {rid!r}"
            )
        seen = seen | {rid}
        out: set[str] = {rid}
        for parent in self._licensing_parents(rid):
            out |= self._closure(parent, seen)
        return out

    def _leaves(self, rid: str) -> set[str]:
        closure = self._closure(rid)
        return {r for r in closure if not self._licensing_parents(r)}

    def write(self, rec: Record) -> None:
        # Guard: a DERIVES_FROM edge from an episodic record to a semantic
        # record is legal only if the episodic record is already a leaf of
        # that semantic record's closure (i.e., it is a genuine observation).
        for src, kind in rec.sources:
            if kind is not EdgeKind.DERIVES_FROM:
                continue
            if src not in self._records:
                raise ProvenanceCycleError(f"unknown source {src!r}")
            if rec.kind == "episodic" and self._records[src].kind == "semantic":
                if rec.rid not in self._leaves(src):
                    raise ProvenanceCycleError(
                        f"refusing episodic {rec.rid!r} deriving from semantic "
                        f"{src!r}: {rec.rid!r} is not an observation in "
                        f"{src!r}'s leaf set; this edge would launder a "
                        f"semantic claim into an observation"
                    )
        self._records[rec.rid] = rec
        # Post-write invariant check: closure must be acyclic and well-founded.
        if not self._leaves(rec.rid):
            del self._records[rec.rid]
            raise ProvenanceCycleError(
                f"write of {rec.rid!r} produced a closure with no leaves"
            )

    def promote(self, semantic_id: str, episodic_inputs: Iterable[str]) -> Record:
        inputs = list(episodic_inputs)
        leaves: set[str] = set()
        for eid in inputs:
            if self._records.get(eid) is None:
                raise ProvenanceCycleError(f"promote source {eid!r} missing")
            if self._records[eid].kind != "episodic":
                raise ProvenanceCycleError(
                    f"promote source {eid!r} is semantic; promotion must cite "
                    f"episodic leaves, not intermediate semantics"
                )
            leaves |= self._leaves(eid)
        rec = Record(
            rid=semantic_id,
            kind="semantic",
            sources=[(leaf, EdgeKind.DERIVES_FROM) for leaf in sorted(leaves)],
        )
        self.write(rec)
        return rec

    def merge(self, target: str, source: str) -> None:
        # Edge-rewriting: union LEAVES, not immediate parents.
        if target not in self._records or source not in self._records:
            raise ProvenanceCycleError("merge operand missing")
        leaves = self._leaves(target) | self._leaves(source)
        if target in leaves:
            raise ProvenanceCycleError(
                f"merge of {source!r} into {target!r} would make {target!r} "
                f"its own provenance leaf"
            )
        self._records[target] = Record(
            rid=target,
            kind="semantic",
            sources=[(leaf, EdgeKind.DERIVES_FROM) for leaf in sorted(leaves)],
        )
        del self._records[source]

    def read_confidence(self, rid: str) -> float:
        leaves = self._leaves(rid)
        if not leaves:
            raise ProvenanceCycleError(
                f"read of {rid!r} has no well-founded leaf set; refusing to "
                f"return a self-justifying record"
            )
        return 1.0 - 0.5 ** len(leaves)
