# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-tagged-memory-writes-have-silently-degraded-into-untagged-overwrites-during-tool-mediated-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-tagged-memory-writes-have-silently-degraded-into-untagged-overwrites-during-tool-mediated-consolidation.warrant.json
# Markdown SHA-256:   95d80029df5e66d61b38d1aa000229f47bcfc67c9f73f50dcf544fb02a2831b2
# Code AST SHA-256:   065bb36e0d4b9c0f99ba2177234414504ac8e5b7527283fd5edd52b955dd0ad4
# Verified Classes:   LineageDecayError, MemoryRecord, ProvenanceGatedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageDecayError(RuntimeError):
    """Raised when a memory write would destroy provenance lineage on a live slot."""


@dataclass
class MemoryRecord:
    cell_id: str
    content: str
    derived_from: list[str] = field(default_factory=list)
    tombstoned: bool = False


class ProvenanceGatedStore:
    def __init__(self) -> None:
        self._slots: dict[str, MemoryRecord] = {}

    def write(
        self,
        cell_id: str,
        content: str,
        derived_from: Optional[list[str]] = None,
        intent: str = "supersede",
    ) -> MemoryRecord:
        derived_from = derived_from or []
        prior = self._slots.get(cell_id)

        # Invariant: a live slot with lineage may not be replaced by a record
        # that drops that lineage, unless the caller explicitly declares an
        # overwrite (which is logged as provenance-destroying and must be
        # accompanied by a tombstone for the prior lineage).
        if (
            prior is not None
            and not prior.tombstoned
            and prior.derived_from
            and not derived_from
            and intent != "overwrite"
        ):
            raise LineageDecayError(
                f"write to live slot {cell_id!r} would drop derived_from="
                f"{prior.derived_from!r} to empty; pass intent='overwrite' "
                f"and tombstone the prior lineage, or supply derived_from "
                f"including {cell_id!r}."
            )

        if intent == "overwrite" and prior is not None and prior.derived_from:
            # Overwrite is only admissible if the prior lineage is tombstoned
            # in the same transaction, preserving an audit edge.
            self._slots[prior.cell_id] = MemoryRecord(
                cell_id=prior.cell_id,
                content=prior.content,
                derived_from=prior.derived_from,
                tombstoned=True,
            )

        record = MemoryRecord(cell_id=cell_id, content=content, derived_from=derived_from)
        self._slots[cell_id] = record
        return record

    def forget(self, cell_id: str) -> None:
        rec = self._slots.get(cell_id)
        if rec is None:
            return
        rec.tombstoned = True  # soft forget preserves the lineage edge

    def read(self, cell_id: str) -> Optional[MemoryRecord]:
        rec = self._slots.get(cell_id)
        if rec is None or rec.tombstoned:
            return None
        return rec


def consolidate_nightly(store: ProvenanceGatedStore, merged: dict[str, dict]) -> None:
    """Simulates the consolidator's write path; must fail loudly on decay."""
    for cell_id, payload in merged.items():
        try:
            store.write(
                cell_id=cell_id,
                content=payload["content"],
                derived_from=payload.get("derived_from", []),
                intent=payload.get("intent", "supersede"),
            )
        except LineageDecayError as exc:
            # Do NOT swallow: a consolidator that treats this as "no predecessor"
            # is exactly the bug this invariant exists to catch.
            raise LineageDecayError(
                f"consolidation aborted at {cell_id!r}: {exc}"
            ) from exc
