# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-that-its-own-in-flight-tool-call-is-still-reading-from.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-that-its-own-in-flight-tool-call-is-still-reading-from.warrant.json
# Markdown SHA-256:   a71cfdfbb4d550bdbbb7f4c6cd12b0f5d450a56165fb98149ab1a3ba323e48e7
# Code AST SHA-256:   21bea21e66b150c28cadcadb8b29dd75cf4f8fb049610693107fafa048c690bf
# Verified Classes:   OrphanedReadError, ScopeResurrectionError, Tombstone, ReadResult, TurnMemoryLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class OrphanedReadError(RuntimeError):
    """Raised when a read result is admitted into agent context after the
    scope it read from has been tombstoned by a forget acknowledged in the
    same turn. This is a runtime invariant violation, not a store error."""


class ScopeResurrectionError(RuntimeError):
    """Raised when a write targets a tombstoned scope without an explicit
    generation bump. Silently resurrecting a scope makes the agent's view
    of memory continuity a lie."""


@dataclass
class Tombstone:
    scope: str
    gen: int
    reason: str


@dataclass
class ReadResult:
    scope: str
    gen: int
    value: Any
    status: str  # "ok" | "not_found" | "stale" | "error"


@dataclass
class TurnMemoryLedger:
    """Tracks, within a single assistant turn, which scopes have been
    forgotten and at what generation. The runtime consults this before
    admitting any tool result back into the model's context."""

    tombstones: dict[str, Tombstone] = field(default_factory=dict)

    def record_forget(self, tombstone: Tombstone) -> None:
        prior = self.tombstones.get(tombstone.scope)
        if prior is not None and tombstone.gen <= prior.gen:
            raise ScopeResurrectionError(
                f"forget on {tombstone.scope!r} minted gen {tombstone.gen} "
                f"<= prior tombstone gen {prior.gen}; generation must be monotonic"
            )
        self.tombstones[tombstone.scope] = tombstone

    def admit_read(self, result: ReadResult) -> ReadResult:
        """Gate that must run before a read result enters model context."""
        tomb = self.tombstones.get(result.scope)
        if tomb is None:
            return result
        if result.status == "ok" and result.gen < tomb.gen:
            # The read began before the forget but committed after it.
            # Returning it as "ok" would let the model reason over content
            # the store has already committed to forgetting.
            raise OrphanedReadError(
                f"read of {result.scope!r} at gen {result.gen} admitted after "
                f"tombstone gen {tomb.gen} (reason={tomb.reason!r}); "
                f"runtime must re-issue the read or surface status='stale'"
            )
        if result.status == "ok" and result.gen == tomb.gen:
            # Resurrected scope: value is from a new generation, safe to admit,
            # but the model must be told the scope was recreated.
            result.status = "ok_resurrected"
        return result

    def admit_write(self, scope: str, write_gen: int) -> None:
        tomb = self.tombstones.get(scope)
        if tomb is not None and write_gen <= tomb.gen:
            raise ScopeResurrectionError(
                f"write to {scope!r} at gen {write_gen} targets tombstoned scope "
                f"(tombstone gen {tomb.gen}); write must mint gen > {tomb.gen} "
                f"or fail with ScopeNotFound"
            )


def dispatch_sibling_calls(
    ledger: TurnMemoryLedger,
    calls: list[dict[str, Any]],
    store: Any,
) -> list[Any]:
    """Fan out sibling tool calls from one assistant message, enforcing the
    tombstone/generation invariant on the way back in."""
    raw = store.execute_batch(calls)  # may interleave arbitrarily
    admitted: list[Any] = []
    for call, result in zip(calls, raw):
        op = call["op"]
        if op == "forget_memory":
            ledger.record_forget(
                Tombstone(scope=call["scope"], gen=result["gen"], reason=call.get("reason", ""))
            )
            admitted.append(result)
        elif op == "read_memory":
            admitted.append(
                ledger.admit_read(
                    ReadResult(
                        scope=call["scope"],
                        gen=result["gen"],
                        value=result.get("value"),
                        status=result["status"],
                    )
                )
            )
        elif op == "write_memory":
            ledger.admit_write(call["scope"], result["gen"])
            admitted.append(result)
        else:
            admitted.append(result)
    return admitted
