# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-invalidated-a-memory-it-still-holds-in-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-invalidated-a-memory-it-still-holds-in-context.warrant.json
# Markdown SHA-256:   4cca7a0ce87dd54f31c1144a54071b53f4ea694e6062eec0b28328b828ae6aaf
# Code AST SHA-256:   3db79880d2d104cd130ef8e15b560bc9e55a752c87fc739f2622d042a1858990
# Verified Classes:   StaleMemoryLeaseError, MemoryLease
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleMemoryLeaseError(RuntimeError):
    """Raised when an instance attempts an irreversible action under an
    in-context memory lease that has not been re-validated against the store."""


class MemoryLease:
    MAX_TURNS = 3          # staleness horizon in agent turns
    MAX_WALL_SECONDS = 120 # staleness horizon in wall time

    def __init__(self, scope: str, version: int, read_turn: int, read_time: float):
        self.scope = scope
        self.version = version
        self.read_turn = read_turn
        self.read_time = read_time

    def is_expired(self, current_turn: int, now: float) -> bool:
        return (
            current_turn - self.read_turn > self.MAX_TURNS
            or now - self.read_time > self.MAX_WALL_SECONDS
        )


def guarded_action(
    lease: MemoryLease,
    current_turn: int,
    now: float,
    memory_tool,
    action_name: str,
    irreversible: bool = True,
) -> None:
    """Validate a memory lease before a dependent action.

    For irreversible actions, an expired lease must be re-validated by a
    fresh read. If the store returns a tombstone (record deleted since the
    read) or a version newer than the lease, the action is refused: the
    in-context content is orphaned and must not steer execution.
    """
    if not irreversible:
        return

    if not lease.is_expired(current_turn, now):
        return  # lease still fresh; proceed under the pinned version

    # Lease expired: re-read to detect tombstone or version advance.
    result = memory_tool.read(scope=lease.scope)

    if result.get("tombstoned"):
        raise StaleMemoryLeaseError(
            f"Action '{action_name}' refused: scope '{lease.scope}' was "
            f"forgotten (tombstone v{result['version']}) after in-context "
            f"read at v{lease.version}. Content is orphaned; escalate."
        )

    if result["version"] > lease.version:
        raise StaleMemoryLeaseError(
            f"Action '{action_name}' refused: scope '{lease.scope}' advanced "
            f"from v{lease.version} to v{result['version']} since read. "
            f"Re-derive rationale from current content before proceeding."
        )

    # Version unchanged and not tombstoned: refresh the lease in place.
    lease.version = result["version"]
    lease.read_turn = current_turn
    lease.read_time = now


def forget_with_cascade(memory_tool, scope: str, reason: str) -> None:
    """Forget a scope and taint any derived writes in sibling scopes.

    Scoped deletion is defeated if the agent persisted inferences drawn from
    the scope elsewhere. This enforces the provenance edge so erasure is
    effective at every scope the erased data reached.
    """
    memory_tool.forget(scope=scope, reason=reason)
    dependents = memory_tool.find_derived_from(scope)
    for dep_scope, dep_key in dependents:
        memory_tool.mark_tainted(
            scope=dep_scope,
            key=dep_key,
            reason=f"derived from forgotten scope '{scope}'",
        )
