# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-tool-s-forget-acknowledgment-as-a-tombstone-barrier-rather-than-a-deletion-event-and-why-d.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-tool-s-forget-acknowledgment-as-a-tombstone-barrier-rather-than-a-deletion-event-and-why-d.warrant.json
# Markdown SHA-256:   c0c0b7b67db44bb142f0b0eb0570baf8ef545f4bce9829c91291891c2eed10e3
# Code AST SHA-256:   1b1572bbe4743ec3cb0700e91d8cd5efb9798c05ebdb942e09830258815e5d31
# Verified Classes:   TombstoneBarrierViolation, ForgetLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TombstoneBarrierViolation(RuntimeError):
    """Raised when an agent attempts to act on a read or write that is not
    ordered after the tombstone for a forgotten record, or when a write would
    re-introduce a forgotten content fingerprint under a new id."""
    pass


class ForgetLedger:
    """Local guardrail mirroring forget acknowledgments as tombstone barriers.

    A forget ack is a visibility barrier, not a deletion event. The ledger
    enforces: (1) reads with commit_seq < tombstone.commit_seq are discarded,
    (2) writes whose content fingerprint matches a forgotten fingerprint are
    refused, regardless of target id, when the target retention exceeds the
    forgotten record's remaining TTL.
    """

    def __init__(self, max_secondary_staleness_seq: int):
        self._by_id: dict[str, dict] = {}
        self._by_fingerprint: dict[str, dict] = {}
        self._max_staleness = max_secondary_staleness_seq

    def record_forget(self, record_id: str, commit_seq: int,
                      content_fingerprint: str, remaining_ttl_s: int) -> None:
        if content_fingerprint is None or content_fingerprint == "":
            # Cannot detect re-introduction without a fingerprint. Refuse to
            # pretend the forget is complete.
            raise TombstoneBarrierViolation(
                f"forget({record_id}) lacks a content fingerprint; "
                "re-introduction under a new id would be undetectable"
            )
        entry = {
            "id": record_id,
            "commit_seq": commit_seq,
            "fingerprint": content_fingerprint,
            "remaining_ttl_s": remaining_ttl_s,
        }
        self._by_id[record_id] = entry
        self._by_fingerprint[content_fingerprint] = entry

    def filter_read(self, record_id: str, commit_seq: int,
                    content_fingerprint: str) -> bool:
        """Return True if the read result is admissible (post-tombstone)."""
        tomb = self._by_id.get(record_id)
        if tomb is not None and commit_seq < tomb["commit_seq"]:
            return False  # pre-tombstone read via secondary index
        fp_tomb = self._by_fingerprint.get(content_fingerprint)
        if fp_tomb is not None and commit_seq < fp_tomb["commit_seq"]:
            return False  # same content, different id, stale index
        return True

    def check_write(self, target_id: str, content_fingerprint: str,
                    target_retention_s: int) -> None:
        fp_tomb = self._by_fingerprint.get(content_fingerprint)
        if fp_tomb is None:
            return
        if target_retention_s > fp_tomb["remaining_ttl_s"]:
            raise TombstoneBarrierViolation(
                f"write to {target_id} would re-introduce forgotten content "
                f"under retention {target_retention_s}s, exceeding the "
                f"forgotten record's remaining {fp_tomb['remaining_ttl_s']}s"
            )

    def evict_stale(self, current_seq: int) -> None:
        """Drop ledger entries only after the primary store confirms body
        reclamation AND the longest secondary index has caught up."""
        cutoff = current_seq - self._max_staleness
        for rid, entry in list(self._by_id.items()):
            if entry["commit_seq"] < cutoff:
                del self._by_id[rid]
        for fp, entry in list(self._by_fingerprint.items()):
            if entry["commit_seq"] < cutoff:
                del self._by_fingerprint[fp]


def regenerate_summary(ledger: ForgetLedger, retrieved: list[dict],
                       summary_id: str, retention_s: int) -> str:
    """Regenerate a summary from retrieval results, gated by the ledger.

    Retrieval results carry commit_seq from the secondary index; any result
    ordered before its tombstone is dropped before it can enter context.
    The regenerated summary is then checked against forgotten fingerprints
    before being written back.
    """
    admissible = []
    for rec in retrieved:
        if not ledger.filter_read(rec["id"], rec["commit_seq"],
                                  rec["fingerprint"]):
            continue
        admissible.append(rec)

    joined = " | ".join(r["text"] for r in admissible)
    summary_fp = _fingerprint(joined)

    ledger.check_write(summary_id, summary_fp, retention_s)
    return joined


def _fingerprint(text: str) -> str:
    import hashlib
    return hashlib.sha256(text.encode("utf-8")).hexdigest()
