# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-by-decay-what-it-never-re-reads-write-only-salience-and-the-reconsolidation-dead-zone-in-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-by-decay-what-it-never-re-reads-write-only-salience-and-the-reconsolidation-dead-zone-in-memory-tool-apis.warrant.json
# Markdown SHA-256:   e7c2502a84f1220a2072ef7c69474e799579958eda7743d5b023a3d8abdd39d2
# Code AST SHA-256:   531d93707f1fdfac9bd9bdd3ccce952947cae30d91b983a55262520559b4b013
# Verified Classes:   ReconsolidationDeadZone, Entry, MemoryTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ReconsolidationDeadZone(RuntimeError):
    """Raised when a read returns a memory without durably resetting its decay clock."""
    pass


@dataclass
class Entry:
    key: str
    value: str
    salience: float
    last_reinforcement: float
    namespace: str = "default"


class MemoryTool:
    def __init__(self, lam: float = 0.02, theta: float = 0.15):
        self.lam = lam
        self.theta = theta
        self.store: dict[str, Entry] = {}
        self.durable_reinforcements: dict[str, float] = {}

    def remember(self, key: str, value: str, salience: float, ns: str = "default") -> None:
        now = time.time()
        self.store[key] = Entry(key, value, salience, now, ns)
        self.durable_reinforcements[key] = now

    def _salience_at(self, e: Entry, now: float) -> float:
        # Decay is measured from last REINFORCEMENT, not last write.
        return e.salience * pow(2.718281828, -self.lam * (now - e.last_reinforcement) / 60.0)

    def recall(self, key: str) -> tuple[str, float, float]:
        now = time.time()
        e = self.store.get(key)
        if e is None:
            return ("", 0.0, 0.0)
        s = self._salience_at(e, now)
        if s < self.theta:
            del self.store[key]
            return ("", 0.0, 0.0)

        # INVARIANT: persist the reinforcement BEFORE returning the value.
        # If this write does not land, the read is a borrow that will not be repaid.
        self.durable_reinforcements[key] = now
        if self.durable_reinforcements.get(key) != now:
            raise ReconsolidationDeadZone(
                f"reinforcement for {key!r} did not persist; read would return "
                f"a value whose decay clock was never reset"
            )
        e.last_reinforcement = now
        ttl = (self.theta / e.salience) if e.salience > 0 else 0.0
        ttl_seconds = max(0.0, -(60.0 / self.lam) * __import__("math").log(self.theta / e.salience))
        return (e.value, s, ttl_seconds)

    def sweep(self) -> list[str]:
        now = time.time()
        evicted = []
        for key, e in list(self.store.items()):
            if self._salience_at(e, now) < self.theta:
                # Namespace guard: never evict a key whose namespace has a hotter member.
                ns_max = max(
                    (self._salience_at(o, now) for o in self.store.values() if o.namespace == e.namespace),
                    default=0.0,
                )
                if ns_max >= self.theta:
                    raise ReconsolidationDeadZone(
                        f"namespace {e.namespace!r} eviction would drop {key!r} "
                        f"while a hotter sibling is still live; consult last_reinforcement"
                    )
                del self.store[key]
                evicted.append(key)
        return evicted
