# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-right-to-forget-tombstone-has-been-resurrected-by-agent-memory-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-right-to-forget-tombstone-has-been-resurrected-by-agent-memory-consolidation.warrant.json
# Markdown SHA-256:   3f00e5cf8ed582b8546be7db0253d5144a3620a6aa6ac1d822da3632406d9755
# Code AST SHA-256:   43a588ecde917420e4e4157fd16d014c8a218e50560fa311d823a45cfdb9e8d0
# Verified Classes:   TombstoneResurrectionError, Tombstone, SemanticRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TombstoneResurrectionError(RuntimeError):
    """Raised when consolidation emits a record that violates an active right-to-forget tombstone."""


@dataclass(frozen=True)
class Tombstone:
    entity: str
    attribute: str
    t: float
    forbidden_entailment: frozenset[str]  # record ids that may entail the forgotten fact
    complete: bool                         # was reverse-entailment closure computed?


@dataclass
class SemanticRecord:
    record_id: str
    entity: str
    attribute: str
    value: str
    confidence: float
    derived_from: frozenset[str]
    t: float


def gate_consolidation_emit(
    candidate: SemanticRecord,
    tombstones: Iterable[Tombstone],
    scope_frozen: bool,
) -> None:
    """
    Enforce the right-to-forget closure invariant before a consolidation-emitted
    record is committed. Raises if the candidate resurrects a forgotten datum.
    """
    if scope_frozen:
        raise TombstoneResurrectionError(
            f"consolidation attempted in frozen scope while emitting {candidate.record_id}; "
            "tombstone entailment closure was incomplete at forget time"
        )

    for ts in tombstones:
        # Signal 1: write-after-tombstone on the same key with non-user provenance.
        if (
            candidate.entity == ts.entity
            and candidate.attribute == ts.attribute
            and candidate.t > ts.t
        ):
            raise TombstoneResurrectionError(
                f"key resurrection: {candidate.record_id} writes "
                f"({ts.entity},{ts.attribute}) after tombstone t={ts.t}"
            )

        # Signal 3: provenance discontinuity — derivation tree intersects forbidden entailment.
        overlap = candidate.derived_from & ts.forbidden_entailment
        if overlap:
            raise TombstoneResurrectionError(
                f"entailment resurrection: {candidate.record_id} derives from "
                f"forbidden records {sorted(overlap)} for tombstone "
                f"({ts.entity},{ts.attribute})"
            )


def consolidate_batch(
    candidates: list[SemanticRecord],
    tombstones: list[Tombstone],
    scope_frozen: bool,
) -> list[SemanticRecord]:
    committed: list[SemanticRecord] = []
    for c in candidates:
        try:
            gate_consolidation_emit(c, tombstones, scope_frozen)
        except TombstoneResurrectionError:
            # Abort the batch: other candidates may contain undetected resurrections.
            raise
        committed.append(c)
    return committed
