# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-a-scoped-memory-write-against-the-retrieval-index-it-will-later-read-from.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-a-scoped-memory-write-against-the-retrieval-index-it-will-later-read-from.warrant.json
# Markdown SHA-256:   c9a97a906187b08f84d266a19153e803cb8dba2f5a82f1224dfd59138a853576
# Code AST SHA-256:   07560ce9b8173d350084d9e6e843d797cd34104a1d7b370a739c17ab620e23fd
# Verified Classes:   StaleRecallError, WriteSet
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleRecallError(RuntimeError):
    """Raised when a recall returns a version older than the agent's acknowledged write,
    or surfaces a key the agent has forgotten in the current task scope."""
    pass


@dataclass
class WriteSet:
    """Task-local ledger of acknowledged writes and forgets, keyed by (scope, key)."""
    written: dict[tuple[str, str], int] = field(default_factory=dict)   # -> acked version
    forgotten: set[tuple[str, str]] = field(default_factory=set)

    def record_write(self, scope: str, key: str, acked_version: int) -> None:
        self.written[(scope, key)] = acked_version
        self.forgotten.discard((scope, key))

    def record_forget(self, scope: str, key: str) -> None:
        self.forgotten.add((scope, key))
        self.written.pop((scope, key), None)


def reconcile_recall(scope: str, results: list[dict], ledger: WriteSet) -> list[dict]:
    """Filter recall results against the task-local write-set.

    - Drop any key the agent has forgotten this task (tombstone not yet propagated).
    - For any key the agent wrote this task, require the returned version to be
      >= the acknowledged version; otherwise the projection is stale.
    """
    reconciled: list[dict] = []
    for hit in results:
        k = (scope, hit["key"])
        if k in ledger.forgotten:
            # Forget acknowledged but index still serves the orphaned embedding.
            continue
        acked: Optional[int] = ledger.written.get(k)
        if acked is not None and hit.get("version", -1) < acked:
            raise StaleRecallError(
                f"recall for {k} returned version {hit.get('version')} "
                f"< acknowledged write version {acked}; projection has not settled"
            )
        reconciled.append(hit)
    return reconciled
