""" Shelly AI - Memory Trace Manager Tracks memory reinforcement and activation strength. """ from __future__ import annotations import math import time from typing import Any, Dict class MemoryTraceManager: def __init__(self): self.traces = {} def create_trace( self, memory_id: str, novelty: float = 0.5, attention: float = 0.5, emotional_intensity: float = 0.0, ) -> Dict[str, Any]: now = time.time() novelty = max(0.0, min(1.0, novelty)) attention = max(0.0, min(1.0, attention)) emotional_intensity = max( 0.0, min(1.0, emotional_intensity), ) initial_strength = ( 0.30 + novelty * 0.25 + attention * 0.25 + emotional_intensity * 0.20 ) trace = { "memory_id": memory_id, "strength": min(1.0, initial_strength), "created_at": now, "last_reinforced": now, "reinforcement_count": 0, "retrieval_count": 0, } self.traces[memory_id] = trace return dict(trace) def reinforce( self, memory_id: str, amount: float = 0.1, reason: str = "retrieval", ) -> Optional[Dict[str, Any]]: trace = self.traces.get(memory_id) if trace is None: return None amount = max(0.0, min(1.0, amount)) trace["strength"] = min( 1.0, trace["strength"] + amount, ) trace["last_reinforced"] = time.time() trace["reinforcement_count"] += 1 trace["last_reason"] = reason return dict(trace) def record_retrieval( self, memory_id: str, ) -> Optional[Dict[str, Any]]: trace = self.traces.get(memory_id) if trace is None: return None trace["retrieval_count"] += 1 self.reinforce( memory_id, amount=0.025, reason="retrieval", ) return dict(trace) def get_strength(self, memory_id: str) -> float: trace = self.traces.get(memory_id) if trace is None: return 0.0 return float(trace["strength"]) def calculate_decay( self, memory_id: str, decay_rate: float = 0.01, ) -> float: """ Calculate time-based memory decay. This returns a calculated strength without deleting or permanently modifying the trace. """ trace = self.traces.get(memory_id) if trace is None: return 0.0 elapsed = max( 0.0, time.time() - trace["last_reinforced"], ) days = elapsed / 86400.0 rate = max(0.0, decay_rate) strength = trace["strength"] * math.exp( -rate * days ) return max(0.0, min(1.0, strength)) def remove_trace(self, memory_id: str) -> bool: return self.traces.pop(memory_id, None) is not None def export_state(self) -> Dict[str, Any]: return { memory_id: dict(trace) for memory_id, trace in self.traces.items() } def import_state(self, state: Dict[str, Any]) -> None: if not isinstance(state, dict): raise TypeError("Trace state must be a dictionary.") self.traces = { memory_id: dict(trace) for memory_id, trace in state.items() }