hakua-memory 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. hakua_memory/__init__.py +21 -0
  2. hakua_memory/composite.py +257 -0
  3. hakua_memory/config.py +168 -0
  4. hakua_memory/ebbinghaus/__init__.py +862 -0
  5. hakua_memory/ebbinghaus/experience.py +1488 -0
  6. hakua_memory/ebbinghaus/migrations.py +362 -0
  7. hakua_memory/ebbinghaus/models.py +85 -0
  8. hakua_memory/ebbinghaus/policies.py +529 -0
  9. hakua_memory/ebbinghaus/semantic_graph_bridge.py +764 -0
  10. hakua_memory/ebbinghaus/store.py +2736 -0
  11. hakua_memory/obsidian/__init__.py +32 -0
  12. hakua_memory/obsidian/templates.py +212 -0
  13. hakua_memory/rag/__init__.py +36 -0
  14. hakua_memory/rag/chunking.py +150 -0
  15. hakua_memory/rag/contradiction.py +228 -0
  16. hakua_memory/rag/ingestion.py +260 -0
  17. hakua_memory/rag/meeting.py +150 -0
  18. hakua_memory/rag/models.py +156 -0
  19. hakua_memory/rag/retrieval.py +235 -0
  20. hakua_memory/rag/schema.py +159 -0
  21. hakua_memory/rag/store.py +539 -0
  22. hakua_memory/semantic_graph/__init__.py +23 -0
  23. hakua_memory/semantic_graph/cli.py +161 -0
  24. hakua_memory/semantic_graph/cognitive.py +174 -0
  25. hakua_memory/semantic_graph/config.py +273 -0
  26. hakua_memory/semantic_graph/embedding/__init__.py +45 -0
  27. hakua_memory/semantic_graph/embedding/base.py +57 -0
  28. hakua_memory/semantic_graph/embedding/fake.py +78 -0
  29. hakua_memory/semantic_graph/embedding/llama_cpp.py +221 -0
  30. hakua_memory/semantic_graph/embedding/serializer.py +65 -0
  31. hakua_memory/semantic_graph/embedding/vectors.py +144 -0
  32. hakua_memory/semantic_graph/exporter.py +132 -0
  33. hakua_memory/semantic_graph/fusion.py +85 -0
  34. hakua_memory/semantic_graph/graph.py +480 -0
  35. hakua_memory/semantic_graph/inference.py +103 -0
  36. hakua_memory/semantic_graph/models.py +156 -0
  37. hakua_memory/semantic_graph/retrieval.py +235 -0
  38. hakua_memory/semantic_graph/runtime.py +1185 -0
  39. hakua_memory/semantic_graph/sanitize.py +164 -0
  40. hakua_memory/semantic_graph/schemas.py +462 -0
  41. hakua_memory/semantic_graph/store.py +1533 -0
  42. hakua_memory-0.2.0.dist-info/METADATA +238 -0
  43. hakua_memory-0.2.0.dist-info/RECORD +46 -0
  44. hakua_memory-0.2.0.dist-info/WHEEL +5 -0
  45. hakua_memory-0.2.0.dist-info/licenses/LICENSE +201 -0
  46. hakua_memory-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2736 @@
1
+ """SQLite store for Ebbinghaus memory with sleep/dream/capacity lifecycle.
2
+
3
+ Implements the full Ebbinghaus forgetting curve, sleep-cycle consolidation,
4
+ dream-based semantic clustering, and policy-driven capacity enforcement.
5
+ All state lives in a single SQLite database.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import logging
13
+ import math
14
+ import re
15
+ import sqlite3
16
+ import threading
17
+ import time
18
+ import unicodedata
19
+ from collections import Counter, defaultdict
20
+ from datetime import datetime, timezone
21
+ from pathlib import Path
22
+ from typing import Any, Callable, Iterable, Mapping, Sequence
23
+
24
+ from .experience import EbbinghausExperienceLedger, normalize_query_hash
25
+ from .models import RecallAttemptResult, RetrievalOutcome
26
+ from .policies import EbbinghausPolicies, is_protected, resolve_prune_mode
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Constants
32
+ # ---------------------------------------------------------------------------
33
+
34
+ _MAX_STRENGTH: float = 6.0
35
+
36
+ _TOKEN_RE = re.compile(r"[\w][\w.+#:/-]{1,}", re.UNICODE)
37
+ _CJK_RE = re.compile(r"[\u3040-\u30ff\u3400-\u9fff]+")
38
+ _SPACE_RE = re.compile(r"\s+")
39
+
40
+ _STOPWORDS: frozenset[str] = frozenset({
41
+ "about", "after", "also", "and", "are", "because", "been", "but",
42
+ "can", "could", "for", "from", "has", "have", "into", "not", "of",
43
+ "our", "the", "that", "this", "use", "was", "were", "with", "you",
44
+ "your", "です", "ます", "して", "した", "こと", "これ", "それ",
45
+ })
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Pure helpers
49
+ # ---------------------------------------------------------------------------
50
+
51
+
52
+ def _clamp(value: float, low: float, high: float) -> float:
53
+ return max(low, min(high, value))
54
+
55
+
56
+ def forgetting_retention(elapsed_days: float, stability_days: float) -> float:
57
+ """Return retention in [0, 1] for the Ebbinghaus exponential curve."""
58
+ if elapsed_days <= 0:
59
+ return 1.0
60
+ stability = max(0.01, float(stability_days))
61
+ return _clamp(math.exp(-float(elapsed_days) / stability), 0.0, 1.0)
62
+
63
+
64
+ def _dream_idempotency_key(source_ids: Sequence[int]) -> str:
65
+ canonical = ",".join(str(value) for value in sorted({int(x) for x in source_ids}))
66
+ return f"dream:{canonical}"
67
+
68
+
69
+ def _normalize_text(text: str) -> str:
70
+ text = unicodedata.normalize("NFKC", text or "")
71
+ return _SPACE_RE.sub(" ", text).strip()
72
+
73
+
74
+ def _tokenize(text: str) -> list[str]:
75
+ """Encode text into retrieval cues (latin terms + CJK n-grams)."""
76
+ normalized = _normalize_text(text).lower()
77
+ tokens: list[str] = []
78
+ for match in _TOKEN_RE.finditer(normalized):
79
+ token = match.group(0).strip("._-/#:")
80
+ if len(token) >= 2 and token not in _STOPWORDS:
81
+ tokens.append(token)
82
+ for chunk in _CJK_RE.findall(normalized):
83
+ if len(chunk) < 2:
84
+ continue
85
+ tokens.extend(chunk[i : i + 2] for i in range(0, len(chunk) - 1))
86
+ if len(chunk) >= 3:
87
+ tokens.extend(chunk[i : i + 3] for i in range(0, len(chunk) - 2))
88
+ return tokens
89
+
90
+
91
+ def _cue_counts(text: str | Iterable[str]) -> Counter:
92
+ if isinstance(text, str):
93
+ return Counter(_tokenize(text))
94
+ counts: Counter = Counter()
95
+ for item in text:
96
+ counts.update(_tokenize(str(item)))
97
+ return counts
98
+
99
+
100
+ def _top_cues(counts: Counter, limit: int = 64) -> list[str]:
101
+ return [
102
+ token
103
+ for token, _count in sorted(
104
+ counts.items(), key=lambda item: (-item[1], item[0])
105
+ )[:limit]
106
+ ]
107
+
108
+
109
+ def _cosine(a: Counter, b: Counter) -> float:
110
+ if not a or not b:
111
+ return 0.0
112
+ overlap = set(a) & set(b)
113
+ numerator = sum(a[token] * b[token] for token in overlap)
114
+ if numerator <= 0:
115
+ return 0.0
116
+ left = math.sqrt(sum(v * v for v in a.values()))
117
+ right = math.sqrt(sum(v * v for v in b.values()))
118
+ if left == 0 or right == 0:
119
+ return 0.0
120
+ return float(numerator / (left * right))
121
+
122
+
123
+ def _split_tags(tags: Any) -> list[str]:
124
+ if tags is None:
125
+ return []
126
+ if isinstance(tags, str):
127
+ raw = re.split(r"[,;\n]", tags)
128
+ elif isinstance(tags, Iterable):
129
+ raw = [str(item) for item in tags]
130
+ else:
131
+ raw = [str(tags)]
132
+ cleaned: list[str] = []
133
+ seen: set[str] = set()
134
+ for tag in raw:
135
+ value = _normalize_text(tag).lower()
136
+ if not value or value in seen:
137
+ continue
138
+ seen.add(value)
139
+ cleaned.append(value)
140
+ return cleaned
141
+
142
+
143
+ def _join_tags(tags: Iterable[str]) -> str:
144
+ return ",".join(_split_tags(list(tags)))
145
+
146
+
147
+ def _timestamp_value(value: Any, *, default: float = 0.0) -> float:
148
+ """Return a Unix timestamp for legacy REAL or ISO-8601 values."""
149
+ if value is None or value == "":
150
+ return float(default)
151
+ if isinstance(value, (int, float)):
152
+ return float(value)
153
+ text = str(value).strip()
154
+ if not text:
155
+ return float(default)
156
+ try:
157
+ return float(text)
158
+ except ValueError:
159
+ pass
160
+ try:
161
+ normalized = text[:-1] + "+00:00" if text.endswith("Z") else text
162
+ parsed = datetime.fromisoformat(normalized)
163
+ if parsed.tzinfo is None:
164
+ parsed = parsed.replace(tzinfo=timezone.utc)
165
+ return float(parsed.timestamp())
166
+ except ValueError:
167
+ logger.debug("Invalid Ebbinghaus timestamp value %r; using default", value)
168
+ return float(default)
169
+
170
+
171
+ def _encode_memory(content: str, tags: Iterable[str]) -> dict:
172
+ counts = _cue_counts([content, *list(tags)])
173
+ cues = _top_cues(counts)
174
+ return {
175
+ "version": 1,
176
+ "kind": "cue_encoding",
177
+ "summary": _normalize_text(content)[:280],
178
+ "cue_vector": {token: counts[token] for token in cues},
179
+ "cues": cues,
180
+ "length": len(content),
181
+ }
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # Schema
186
+ # ---------------------------------------------------------------------------
187
+
188
+ _BASE_SCHEMA = """
189
+ CREATE TABLE IF NOT EXISTS memories (
190
+ memory_id INTEGER PRIMARY KEY AUTOINCREMENT,
191
+ content TEXT NOT NULL UNIQUE,
192
+ encoded TEXT NOT NULL,
193
+ cues TEXT DEFAULT '',
194
+ tags TEXT DEFAULT '',
195
+ salience REAL DEFAULT 0.6,
196
+ valence REAL DEFAULT 0.0,
197
+ strength REAL DEFAULT 1.0,
198
+ rehearsal_count INTEGER DEFAULT 0,
199
+ retrieval_count INTEGER DEFAULT 0,
200
+ source TEXT DEFAULT '',
201
+ session_id TEXT DEFAULT '',
202
+ created_at REAL NOT NULL,
203
+ updated_at REAL NOT NULL,
204
+ last_rehearsed_at REAL,
205
+ last_retrieved_at REAL,
206
+ state TEXT NOT NULL DEFAULT 'active',
207
+ last_anchor_at REAL,
208
+ sleep_rehearsal_count INTEGER NOT NULL DEFAULT 0,
209
+ last_sleep_at REAL,
210
+ archived_at REAL,
211
+ archive_reason TEXT DEFAULT '',
212
+ memory_type TEXT NOT NULL DEFAULT 'episodic',
213
+ dream_candidate INTEGER NOT NULL DEFAULT 0
214
+ );
215
+
216
+ CREATE INDEX IF NOT EXISTS idx_ebbinghaus_tags ON memories(tags);
217
+ CREATE INDEX IF NOT EXISTS idx_ebbinghaus_updated ON memories(updated_at DESC);
218
+ CREATE INDEX IF NOT EXISTS idx_ebbinghaus_salience ON memories(salience DESC);
219
+
220
+ CREATE TABLE IF NOT EXISTS memory_provenance (
221
+ semantic_memory_id INTEGER NOT NULL,
222
+ source_memory_id INTEGER NOT NULL,
223
+ relation TEXT NOT NULL DEFAULT 'dream-derived',
224
+ created_at REAL NOT NULL,
225
+ PRIMARY KEY (semantic_memory_id, source_memory_id)
226
+ );
227
+
228
+ CREATE TABLE IF NOT EXISTS dream_previews (
229
+ cluster_id TEXT PRIMARY KEY,
230
+ payload TEXT NOT NULL,
231
+ created_at REAL NOT NULL
232
+ );
233
+ """
234
+
235
+ _MIGRATION_COLUMNS: list[tuple[str, str]] = [
236
+ ("state", "TEXT NOT NULL DEFAULT 'active'"),
237
+ ("last_anchor_at", "REAL"),
238
+ ("sleep_rehearsal_count", "INTEGER NOT NULL DEFAULT 0"),
239
+ ("last_sleep_at", "REAL"),
240
+ ("archived_at", "REAL"),
241
+ ("archive_reason", "TEXT DEFAULT ''"),
242
+ ("memory_type", "TEXT NOT NULL DEFAULT 'episodic'"),
243
+ ("dream_candidate", "INTEGER NOT NULL DEFAULT 0"),
244
+ ]
245
+
246
+ # Whitelist for DDL identifiers — never interpolate untrusted strings into SQL.
247
+ _MIGRATION_COLUMN_DEFS: dict[str, str] = dict(_MIGRATION_COLUMNS)
248
+ _IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
249
+ _ALLOWED_MEMORY_STATES = frozenset({"active", "archived"})
250
+ _MAX_IN_CLAUSE = 2048
251
+
252
+
253
+ def _assert_safe_identifier(name: str) -> str:
254
+ if name not in _MIGRATION_COLUMN_DEFS or not _IDENTIFIER_RE.fullmatch(name):
255
+ raise ValueError(f"refusing unsafe SQL identifier: {name!r}")
256
+ return name
257
+
258
+
259
+ def _placeholders(count: int) -> str:
260
+ n = int(count)
261
+ if n < 1 or n > _MAX_IN_CLAUSE:
262
+ raise ValueError(f"IN-clause size out of bounds: {n}")
263
+ return ",".join("?" * n)
264
+
265
+
266
+ def _as_positive_int_ids(raw: Sequence[Any]) -> list[int]:
267
+ ids: list[int] = []
268
+ for item in raw:
269
+ value = int(item)
270
+ if value < 1:
271
+ raise ValueError(f"memory_id must be >= 1, got {value}")
272
+ ids.append(value)
273
+ return ids
274
+
275
+
276
+ # ---------------------------------------------------------------------------
277
+ # Exceptions
278
+ # ---------------------------------------------------------------------------
279
+
280
+
281
+ class CapacityError(RuntimeError):
282
+ """Raised when capacity is full and no non-protected memory can be archived."""
283
+
284
+ def __init__(self, message: str, *, details: dict[str, Any] | None = None) -> None:
285
+ super().__init__(message)
286
+ self.details = details or {}
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Store
291
+ # ---------------------------------------------------------------------------
292
+
293
+
294
+ class EbbinghausMemoryStore:
295
+ """SQLite store for encoded memory traces with lifecycle policies."""
296
+
297
+ def __init__(
298
+ self,
299
+ db_path: str | Path,
300
+ *,
301
+ base_stability_days: float = 3.0,
302
+ decay_threshold: float = 0.10,
303
+ time_fn: Callable[[], float] | None = None,
304
+ policies: EbbinghausPolicies | None = None,
305
+ ) -> None:
306
+ self.db_path = Path(db_path).expanduser()
307
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
308
+
309
+ if policies is not None:
310
+ self.policies = policies
311
+ self.base_stability_days = max(0.05, policies.base_stability_days)
312
+ self.decay_threshold = _clamp(policies.decay_threshold, 0.0, 1.0)
313
+ else:
314
+ self.base_stability_days = max(0.05, float(base_stability_days))
315
+ self.decay_threshold = _clamp(float(decay_threshold), 0.0, 1.0)
316
+ self.policies = EbbinghausPolicies(
317
+ base_stability_days=self.base_stability_days,
318
+ decay_threshold=self.decay_threshold,
319
+ )
320
+
321
+ self._time_fn = time_fn or time.time
322
+ # In-process cache of dream previews; durable copy lives in dream_previews.
323
+ self._preview_registry: dict[str, dict[str, Any]] = {}
324
+ self._negative_prefetch_suppressed_count = 0
325
+ self._lock = threading.RLock()
326
+ self._conn = sqlite3.connect(
327
+ str(self.db_path), check_same_thread=False, timeout=10.0
328
+ )
329
+ self._conn.row_factory = sqlite3.Row
330
+ self._init_db()
331
+ self.experience = EbbinghausExperienceLedger(
332
+ self._conn,
333
+ now_fn=self._now,
334
+ policies=self.policies,
335
+ lock=self._lock,
336
+ )
337
+ self._hydrate_preview_registry()
338
+
339
+ # ------------------------------------------------------------------
340
+ # DB initialisation & migration
341
+ # ------------------------------------------------------------------
342
+
343
+ def _init_db(self) -> None:
344
+ try:
345
+ from hermes_state import apply_wal_with_fallback
346
+
347
+ apply_wal_with_fallback(self._conn, db_label="ebbinghaus_memory.db")
348
+ except Exception:
349
+ try:
350
+ self._conn.execute("PRAGMA journal_mode=WAL")
351
+ except sqlite3.DatabaseError:
352
+ pass
353
+
354
+ self._conn.executescript(_BASE_SCHEMA)
355
+ self._migrate()
356
+ self._conn.commit()
357
+ from .migrations import apply_experience_migrations
358
+
359
+ apply_experience_migrations(self._conn, self.db_path, now=self._now())
360
+
361
+ def _migrate(self) -> None:
362
+ self._conn.execute("BEGIN")
363
+ try:
364
+ existing = {
365
+ row[1]
366
+ for row in self._conn.execute("PRAGMA table_info(memories)").fetchall()
367
+ }
368
+ for col_name, col_def in _MIGRATION_COLUMNS:
369
+ safe_name = _assert_safe_identifier(col_name)
370
+ safe_def = _MIGRATION_COLUMN_DEFS[safe_name]
371
+ if safe_def != col_def:
372
+ raise ValueError(f"migration definition mismatch for {safe_name}")
373
+ if safe_name not in existing:
374
+ # Identifiers come only from the hardcoded whitelist above.
375
+ self._conn.execute(
376
+ f"ALTER TABLE memories ADD COLUMN {safe_name} {safe_def}"
377
+ )
378
+ logger.info("Ebbinghaus migration: added column %s", safe_name)
379
+
380
+ self._conn.execute(
381
+ """
382
+ UPDATE memories
383
+ SET last_anchor_at = MAX(
384
+ COALESCE(created_at, 0),
385
+ COALESCE(last_rehearsed_at, 0),
386
+ COALESCE(last_retrieved_at, 0)
387
+ )
388
+ WHERE last_anchor_at IS NULL
389
+ """
390
+ )
391
+
392
+ for idx_sql in (
393
+ "CREATE INDEX IF NOT EXISTS idx_ebbinghaus_state_anchor "
394
+ "ON memories(state, last_anchor_at ASC)",
395
+ "CREATE INDEX IF NOT EXISTS idx_ebbinghaus_state_salience "
396
+ "ON memories(state, salience ASC)",
397
+ ):
398
+ try:
399
+ self._conn.execute(idx_sql)
400
+ except sqlite3.OperationalError:
401
+ pass
402
+ self._conn.execute("COMMIT")
403
+ except Exception:
404
+ self._conn.execute("ROLLBACK")
405
+ raise
406
+
407
+ def close(self) -> None:
408
+ self._conn.close()
409
+
410
+ def _hydrate_preview_registry(self) -> None:
411
+ """Load durable dream preview payloads after reopen (best-effort)."""
412
+ try:
413
+ rows = self._conn.execute(
414
+ "SELECT cluster_id, payload FROM dream_previews"
415
+ ).fetchall()
416
+ except sqlite3.Error:
417
+ return
418
+ for row in rows:
419
+ cluster_id = str(row["cluster_id"] or "")
420
+ if not cluster_id or "\x00" in cluster_id:
421
+ continue
422
+ try:
423
+ payload = json.loads(row["payload"])
424
+ except (TypeError, ValueError, json.JSONDecodeError):
425
+ continue
426
+ if isinstance(payload, dict):
427
+ self._preview_registry[cluster_id] = payload
428
+
429
+ def _persist_preview(self, cluster_id: str, payload: dict[str, Any], *, now: float) -> None:
430
+ """Write preview ledger to SQLite so apply survives process restart."""
431
+ if not cluster_id or "\x00" in cluster_id or len(cluster_id) > 128:
432
+ raise ValueError(f"invalid dream cluster_id: {cluster_id!r}")
433
+ encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True)
434
+ if "\x00" in encoded:
435
+ raise ValueError("dream preview payload must not contain NUL bytes")
436
+ self._conn.execute(
437
+ """
438
+ INSERT INTO dream_previews (cluster_id, payload, created_at)
439
+ VALUES (?, ?, ?)
440
+ ON CONFLICT(cluster_id) DO UPDATE SET
441
+ payload = excluded.payload,
442
+ created_at = excluded.created_at
443
+ """,
444
+ (cluster_id, encoded, now),
445
+ )
446
+ self._preview_registry[cluster_id] = payload
447
+
448
+ def _load_preview(self, cluster_id: str) -> dict[str, Any] | None:
449
+ cached = self._preview_registry.get(cluster_id)
450
+ if isinstance(cached, dict):
451
+ return cached
452
+ row = self._conn.execute(
453
+ "SELECT payload FROM dream_previews WHERE cluster_id = ?",
454
+ (cluster_id,),
455
+ ).fetchone()
456
+ if row is None:
457
+ return None
458
+ try:
459
+ payload = json.loads(row["payload"])
460
+ except (TypeError, ValueError, json.JSONDecodeError):
461
+ return None
462
+ if not isinstance(payload, dict):
463
+ return None
464
+ self._preview_registry[cluster_id] = payload
465
+ return payload
466
+
467
+ def _drop_preview(self, cluster_id: str) -> None:
468
+ self._preview_registry.pop(cluster_id, None)
469
+ self._conn.execute(
470
+ "DELETE FROM dream_previews WHERE cluster_id = ?",
471
+ (cluster_id,),
472
+ )
473
+
474
+ def _now(self) -> float:
475
+ return float(self._time_fn())
476
+
477
+ # ------------------------------------------------------------------
478
+ # Internal helpers
479
+ # ------------------------------------------------------------------
480
+
481
+ @staticmethod
482
+ def _decode(value: str) -> dict:
483
+ try:
484
+ decoded = json.loads(value or "{}")
485
+ return decoded if isinstance(decoded, dict) else {}
486
+ except json.JSONDecodeError:
487
+ return {}
488
+
489
+ def _stability_days(self, row: sqlite3.Row) -> float:
490
+ salience = float(row["salience"] or 0.0)
491
+ strength = float(row["strength"] or 1.0)
492
+ rehearsals = int(row["rehearsal_count"] or 0)
493
+ retrievals = int(row["retrieval_count"] or 0)
494
+ multiplier = (
495
+ 0.45
496
+ + (1.35 * salience)
497
+ + (0.65 * math.log1p(rehearsals))
498
+ + (0.25 * math.log1p(retrievals))
499
+ )
500
+ return max(0.05, self.base_stability_days * strength * multiplier)
501
+
502
+ def _select_replay_budgets(
503
+ self,
504
+ candidates: Sequence[sqlite3.Row],
505
+ ) -> dict[str, dict[str, Any]]:
506
+ """Select recent and remote replay independently with fixed work caps."""
507
+ policy = self.policies.sleep
508
+ provenance_counts: dict[int, int] = {}
509
+ candidate_ids = [int(row["memory_id"]) for row in candidates]
510
+ for offset in range(0, len(candidate_ids), _MAX_IN_CLAUSE):
511
+ chunk = candidate_ids[offset : offset + _MAX_IN_CLAUSE]
512
+ if not chunk:
513
+ continue
514
+ placeholders = _placeholders(len(chunk))
515
+ provenance_rows = self._conn.execute(
516
+ f"""
517
+ SELECT memory_id, SUM(link_count) AS link_count
518
+ FROM (
519
+ SELECT source_memory_id AS memory_id, COUNT(*) AS link_count
520
+ FROM memory_provenance
521
+ WHERE source_memory_id IN ({placeholders})
522
+ GROUP BY source_memory_id
523
+ UNION ALL
524
+ SELECT semantic_memory_id AS memory_id, COUNT(*) AS link_count
525
+ FROM memory_provenance
526
+ WHERE semantic_memory_id IN ({placeholders})
527
+ GROUP BY semantic_memory_id
528
+ )
529
+ GROUP BY memory_id
530
+ """,
531
+ [*chunk, *chunk],
532
+ ).fetchall()
533
+ for row in provenance_rows:
534
+ memory_id = int(row["memory_id"])
535
+ provenance_counts[memory_id] = (
536
+ provenance_counts.get(memory_id, 0)
537
+ + int(row["link_count"] or 0)
538
+ )
539
+ now = self._now()
540
+ weak_stability_ceiling = max(2.0, self.base_stability_days * 4.0)
541
+ recent_ranked: list[tuple[tuple[float, ...], sqlite3.Row]] = []
542
+ remote_ranked: list[tuple[tuple[float, ...], sqlite3.Row]] = []
543
+ for row in candidates:
544
+ memory_id = int(row["memory_id"])
545
+ created_at = _timestamp_value(row["created_at"], default=now)
546
+ age_days = max(0.0, (now - created_at) / 86_400.0)
547
+ salience = float(row["salience"] or 0.0)
548
+ retrievals = int(row["retrieval_count"] or 0)
549
+ stability = self._stability_days(row)
550
+ if (
551
+ age_days <= 7.0
552
+ and stability <= weak_stability_ceiling
553
+ and (
554
+ salience >= policy.salience_keep_threshold
555
+ or retrievals > 0
556
+ )
557
+ ):
558
+ utility = float(retrievals) + salience
559
+ recent_ranked.append(
560
+ ((-utility, stability, -salience, float(memory_id)), row)
561
+ )
562
+ provenance_count = provenance_counts.get(memory_id, 0)
563
+ if age_days >= 30.0 and retrievals >= 2 and provenance_count >= 1:
564
+ remote_ranked.append(
565
+ (
566
+ (
567
+ -float(provenance_count),
568
+ -float(retrievals),
569
+ -salience,
570
+ float(memory_id),
571
+ ),
572
+ row,
573
+ )
574
+ )
575
+
576
+ def select(
577
+ ranked: list[tuple[tuple[float, ...], sqlite3.Row]],
578
+ limit: int,
579
+ ) -> dict[str, Any]:
580
+ selected: list[sqlite3.Row] = []
581
+ negative_suppressed: list[int] = []
582
+ if limit <= 0:
583
+ return {
584
+ "budget": 0,
585
+ "rows": selected,
586
+ "selected": [],
587
+ "negative_suppressed": negative_suppressed,
588
+ }
589
+ negative_count = 0
590
+ for _rank, row in sorted(ranked, key=lambda item: item[0]):
591
+ strongly_negative = (
592
+ float(row["valence"] or 0.0)
593
+ <= policy.negative_valence_threshold
594
+ )
595
+ if strongly_negative:
596
+ if negative_count >= policy.max_negative_replay_per_budget:
597
+ negative_suppressed.append(int(row["memory_id"]))
598
+ continue
599
+ negative_count += 1
600
+ selected.append(row)
601
+ if len(selected) >= limit:
602
+ break
603
+ return {
604
+ "budget": limit,
605
+ "rows": selected,
606
+ "selected": [int(row["memory_id"]) for row in selected],
607
+ "negative_suppressed": negative_suppressed,
608
+ }
609
+
610
+ return {
611
+ "recent_replay": select(
612
+ recent_ranked,
613
+ policy.recent_replay_limit,
614
+ ),
615
+ "remote_integration": select(
616
+ remote_ranked,
617
+ policy.remote_integration_limit,
618
+ ),
619
+ }
620
+
621
+ def _apply_replay_rows(
622
+ self,
623
+ rows: Sequence[sqlite3.Row],
624
+ *,
625
+ now: float,
626
+ max_sleep_rehearsals: int,
627
+ max_negative_sleep_rehearsals: int,
628
+ ) -> tuple[list[int], list[int]]:
629
+ replayed: list[int] = []
630
+ cap_suppressed: list[int] = []
631
+ negative_threshold = self.policies.sleep.negative_valence_threshold
632
+ for row in rows:
633
+ memory_id = int(row["memory_id"])
634
+ strongly_negative = float(row["valence"] or 0.0) <= negative_threshold
635
+ cap = (
636
+ max_negative_sleep_rehearsals
637
+ if strongly_negative
638
+ else max_sleep_rehearsals
639
+ )
640
+ if int(row["sleep_rehearsal_count"] or 0) >= cap:
641
+ cap_suppressed.append(memory_id)
642
+ continue
643
+ gain = self._reinforcement_gain(row, kind="rehearsal")
644
+ self._conn.execute(
645
+ """
646
+ UPDATE memories
647
+ SET rehearsal_count = rehearsal_count + 1,
648
+ strength = MIN(?, strength + ?),
649
+ last_rehearsed_at = ?, updated_at = ?,
650
+ last_anchor_at = ?,
651
+ sleep_rehearsal_count = sleep_rehearsal_count + 1
652
+ WHERE memory_id = ?
653
+ """,
654
+ (_MAX_STRENGTH, gain, now, now, now, memory_id),
655
+ )
656
+ replayed.append(memory_id)
657
+ return replayed, cap_suppressed
658
+
659
+ def _retention(self, row: sqlite3.Row) -> float:
660
+ now = self._now()
661
+ anchor = _timestamp_value(row["last_anchor_at"])
662
+ if anchor <= 0:
663
+ anchor = max(
664
+ _timestamp_value(row["created_at"], default=now),
665
+ _timestamp_value(row["last_rehearsed_at"]),
666
+ _timestamp_value(row["last_retrieved_at"]),
667
+ )
668
+ elapsed_days = max(0.0, (now - anchor) / 86400.0)
669
+ return forgetting_retention(elapsed_days, self._stability_days(row))
670
+
671
+ def _compute_anchor(self, row: sqlite3.Row) -> float:
672
+ return max(
673
+ _timestamp_value(row["created_at"], default=0.0),
674
+ _timestamp_value(row["last_rehearsed_at"]),
675
+ _timestamp_value(row["last_retrieved_at"]),
676
+ )
677
+
678
+ def _update_anchor(self, memory_id: int, anchor: float) -> None:
679
+ self._conn.execute(
680
+ "UPDATE memories SET last_anchor_at = ? WHERE memory_id = ?",
681
+ (anchor, memory_id),
682
+ )
683
+
684
+ def _reinforcement_gain(
685
+ self, row: sqlite3.Row, *, kind: str
686
+ ) -> float:
687
+ bases = {"duplicate": 0.15, "retrieval": 0.08, "rehearsal": 0.25}
688
+ base = bases.get(kind, 0.08)
689
+ valence = float(row["valence"] or 0.0)
690
+ threshold = self.policies.sleep.negative_valence_threshold
691
+ multiplier = self.policies.sleep.negative_reinforcement_multiplier
692
+ if valence <= threshold:
693
+ return base * multiplier
694
+ return base
695
+
696
+ def _row_to_result(
697
+ self,
698
+ row: sqlite3.Row,
699
+ *,
700
+ query_score: float | None,
701
+ retention: float | None = None,
702
+ ) -> dict:
703
+ retention = self._retention(row) if retention is None else retention
704
+ encoded = self._decode(row["encoded"])
705
+ now = self._now()
706
+ anchor = _timestamp_value(row["last_anchor_at"])
707
+ if anchor <= 0:
708
+ anchor = self._compute_anchor(row)
709
+ created = _timestamp_value(row["created_at"], default=now)
710
+
711
+ result: dict[str, Any] = {
712
+ "memory_id": int(row["memory_id"]),
713
+ "content": row["content"],
714
+ "tags": _split_tags(row["tags"]),
715
+ "cues": encoded.get("cues", [])[:12],
716
+ "salience": round(float(row["salience"] or 0.0), 3),
717
+ "valence": round(float(row["valence"] or 0.0), 3),
718
+ "retention": round(float(retention), 4),
719
+ "stability_days": round(self._stability_days(row), 3),
720
+ "age_days": round(max(0.0, (now - created) / 86400.0), 3),
721
+ "days_since_reinforcement": round(
722
+ max(0.0, (now - anchor) / 86400.0), 3
723
+ ),
724
+ "rehearsal_count": int(row["rehearsal_count"] or 0),
725
+ "retrieval_count": int(row["retrieval_count"] or 0),
726
+ "source": row["source"] or "",
727
+ "session_id": row["session_id"] or "",
728
+ "state": row["state"] or "active",
729
+ "memory_type": row["memory_type"] or "episodic",
730
+ "sleep_rehearsal_count": int(row["sleep_rehearsal_count"] or 0),
731
+ "dream_candidate": bool(row["dream_candidate"]),
732
+ "access_state": str(row["access_state"] or "accessible"),
733
+ "belief_status": str(row["belief_status"] or "current"),
734
+ "belief_id": str(row["belief_id"] or ""),
735
+ "reactivation_count": int(row["reactivation_count"] or 0),
736
+ "confidence": round(float(row["confidence"] or 0.0), 3),
737
+ }
738
+ if query_score is not None:
739
+ result["score"] = round(float(query_score), 4)
740
+ return result
741
+
742
+ def _is_row_protected(self, row: sqlite3.Row) -> bool:
743
+ return is_protected(
744
+ _split_tags(row["tags"]),
745
+ self.policies.capacity.protected_tags,
746
+ )
747
+
748
+ def _has_live_semantic_dependents(self, memory_id: int) -> bool:
749
+ """True if memory_id is the sole provenance source for a live semantic."""
750
+ row = self._conn.execute(
751
+ """
752
+ SELECT 1 FROM memory_provenance p
753
+ WHERE p.source_memory_id = ?
754
+ AND NOT EXISTS (
755
+ SELECT 1 FROM memory_provenance p2
756
+ WHERE p2.semantic_memory_id = p.semantic_memory_id
757
+ AND p2.source_memory_id != ?
758
+ )
759
+ AND EXISTS (
760
+ SELECT 1 FROM memories m
761
+ WHERE m.memory_id = p.semantic_memory_id
762
+ )
763
+ LIMIT 1
764
+ """,
765
+ (memory_id, memory_id),
766
+ ).fetchone()
767
+ return row is not None
768
+
769
+ # ------------------------------------------------------------------
770
+ # remember
771
+ # ------------------------------------------------------------------
772
+
773
+ def remember(
774
+ self,
775
+ content: str,
776
+ *,
777
+ tags: Any = None,
778
+ salience: float = 0.65,
779
+ valence: float = 0.0,
780
+ source: str = "",
781
+ session_id: str = "",
782
+ memory_type: str = "episodic",
783
+ ) -> dict:
784
+ content = _normalize_text(content)
785
+ if not content:
786
+ raise ValueError("content must not be empty")
787
+ if "\x00" in content:
788
+ raise ValueError("content must not contain NUL bytes")
789
+
790
+ tag_list = _split_tags(tags)
791
+ encoded = _encode_memory(content, tag_list)
792
+ cues = " ".join(encoded["cues"])
793
+ now = self._now()
794
+ salience = _clamp(float(salience), 0.05, 1.0)
795
+ valence = _clamp(float(valence), -1.0, 1.0)
796
+ tag_text = _join_tags(tag_list)
797
+
798
+ self._enforce_capacity_headroom()
799
+
800
+ try:
801
+ cur = self._conn.execute(
802
+ """
803
+ INSERT INTO memories (
804
+ content, encoded, cues, tags, salience, valence, strength,
805
+ source, session_id, created_at, updated_at,
806
+ last_rehearsed_at, state, last_anchor_at, memory_type
807
+ )
808
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
809
+ """,
810
+ (
811
+ content,
812
+ json.dumps(encoded, ensure_ascii=False),
813
+ cues,
814
+ tag_text,
815
+ salience,
816
+ valence,
817
+ 1.0 + salience,
818
+ source,
819
+ session_id,
820
+ now,
821
+ now,
822
+ now,
823
+ now,
824
+ memory_type,
825
+ ),
826
+ )
827
+ self._conn.commit()
828
+ memory_id = int(cur.lastrowid)
829
+ self._conn.execute(
830
+ """
831
+ UPDATE memories
832
+ SET belief_id = ?,
833
+ belief_version = 1,
834
+ belief_status = 'current',
835
+ access_state = 'accessible'
836
+ WHERE memory_id = ?
837
+ AND (belief_id IS NULL OR belief_id = '')
838
+ """,
839
+ (f"memory-{memory_id}", memory_id),
840
+ )
841
+ self._conn.commit()
842
+ return {"memory_id": memory_id, "status": "remembered", **self.get(memory_id)}
843
+ except sqlite3.IntegrityError:
844
+ row = self._conn.execute(
845
+ "SELECT * FROM memories WHERE content = ?", (content,)
846
+ ).fetchone()
847
+ if not row:
848
+ raise
849
+ belief_status = str(row["belief_status"] or "current")
850
+ if belief_status == "superseded":
851
+ belief_id = str(row["belief_id"] or f"memory-{row['memory_id']}")
852
+ current = self._conn.execute(
853
+ """
854
+ SELECT memory_id FROM memories
855
+ WHERE belief_id = ? AND belief_status = 'current'
856
+ ORDER BY belief_version DESC, memory_id DESC
857
+ LIMIT 1
858
+ """,
859
+ (belief_id,),
860
+ ).fetchone()
861
+ return {
862
+ "status": "historical_duplicate",
863
+ "historical_memory_id": int(row["memory_id"]),
864
+ "current_memory_id": (
865
+ int(current["memory_id"]) if current else None
866
+ ),
867
+ "belief_id": belief_id,
868
+ }
869
+ if belief_status == "retracted":
870
+ return {
871
+ "status": "retracted_duplicate",
872
+ "historical_memory_id": int(row["memory_id"]),
873
+ "belief_id": str(row["belief_id"] or ""),
874
+ }
875
+ gain = self._reinforcement_gain(row, kind="duplicate")
876
+ merged_tags = sorted(set(_split_tags(row["tags"])) | set(tag_list))
877
+ self._conn.execute(
878
+ """
879
+ UPDATE memories
880
+ SET tags = ?, salience = MAX(salience, ?),
881
+ rehearsal_count = rehearsal_count + 1,
882
+ strength = MIN(?, strength + ?),
883
+ last_rehearsed_at = ?, updated_at = ?,
884
+ last_anchor_at = ?,
885
+ state = CASE WHEN state = 'archived' THEN 'active' ELSE state END,
886
+ archived_at = CASE WHEN state = 'archived' THEN NULL ELSE archived_at END,
887
+ archive_reason = CASE WHEN state = 'archived' THEN '' ELSE archive_reason END,
888
+ access_state = CASE
889
+ WHEN state = 'archived' THEN 'reactivated'
890
+ ELSE COALESCE(access_state, 'accessible')
891
+ END
892
+ WHERE memory_id = ?
893
+ """,
894
+ (
895
+ _join_tags(merged_tags),
896
+ salience,
897
+ _MAX_STRENGTH,
898
+ gain,
899
+ now,
900
+ now,
901
+ now,
902
+ row["memory_id"],
903
+ ),
904
+ )
905
+ self._conn.commit()
906
+ memory_id = int(row["memory_id"])
907
+ return {"memory_id": memory_id, "status": "reinforced", **self.get(memory_id)}
908
+
909
+ def revise_memory(
910
+ self,
911
+ memory_id: int,
912
+ new_content: str,
913
+ *,
914
+ reason: str,
915
+ evidence: list[dict[str, Any]] | None = None,
916
+ confidence: float = 0.95,
917
+ test_query: str = "",
918
+ source: str = "explicit_correction",
919
+ session_id: str = "",
920
+ ) -> dict[str, Any]:
921
+ content = _normalize_text(new_content)
922
+ if not content:
923
+ raise ValueError("new_content must not be empty")
924
+ old = self.get(int(memory_id))
925
+ tags = old.get("tags") or []
926
+ encoded = _encode_memory(content, tags)
927
+ result = self.experience.revise_memory(
928
+ memory_id=int(memory_id),
929
+ normalized_content=content,
930
+ encoded=encoded,
931
+ reason=reason,
932
+ evidence=evidence or [],
933
+ confidence=float(confidence),
934
+ test_query=test_query,
935
+ source=source,
936
+ session_id=session_id,
937
+ tags=_join_tags(tags),
938
+ salience=float(old.get("salience") or 0.65),
939
+ valence=float(old.get("valence") or 0.0),
940
+ memory_type=str(old.get("memory_type") or "episodic"),
941
+ )
942
+ if isinstance(result, RevisionResult):
943
+ return {
944
+ "status": "revised",
945
+ "belief_id": result.belief_id,
946
+ "old_memory_id": result.old_memory_id,
947
+ "new_memory_id": result.new_memory_id,
948
+ "old_version": result.old_version,
949
+ "new_version": result.new_version,
950
+ "contested_memory_ids": list(result.contested_memory_ids),
951
+ "queued_rehearsal_id": result.queued_rehearsal_id,
952
+ **self.get(result.new_memory_id),
953
+ }
954
+ return dict(result)
955
+
956
+ def record_prediction_error(
957
+ self,
958
+ memory_id: int,
959
+ *,
960
+ source: str,
961
+ expected_hash: str,
962
+ observed_hash: str,
963
+ severity: float,
964
+ requires_revision: bool,
965
+ new_content: str = "",
966
+ reason: str = "",
967
+ confidence: float | None = None,
968
+ test_query: str = "",
969
+ session_id: str = "",
970
+ ) -> dict[str, Any]:
971
+ current = self.get(int(memory_id))
972
+ event = self.experience.record_prediction_error(
973
+ memory_id=int(memory_id),
974
+ source=source,
975
+ expected_hash=expected_hash,
976
+ observed_hash=observed_hash,
977
+ severity=float(severity),
978
+ requires_revision=bool(requires_revision),
979
+ session_id=session_id,
980
+ )
981
+ if not requires_revision:
982
+ return event
983
+
984
+ content = _normalize_text(new_content)
985
+ if not content:
986
+ return {**event, "status": "revision_required"}
987
+ revision = self.revise_memory(
988
+ int(memory_id),
989
+ content,
990
+ reason=str(reason or f"prediction error from {event['source']}"),
991
+ evidence=[
992
+ {
993
+ "event_id": event["event_id"],
994
+ "expected_hash": event["expected_hash"],
995
+ "observed_hash": event["observed_hash"],
996
+ "severity": event["severity"],
997
+ }
998
+ ],
999
+ confidence=(
1000
+ float(current.get("confidence") or 0.0)
1001
+ if confidence is None
1002
+ else float(confidence)
1003
+ ),
1004
+ test_query=test_query,
1005
+ source=event["source"],
1006
+ session_id=session_id,
1007
+ )
1008
+ return {
1009
+ "status": "revised",
1010
+ "prediction_error": event,
1011
+ "revision": revision,
1012
+ }
1013
+
1014
+ def stabilize_memory(
1015
+ self,
1016
+ memory_id: int,
1017
+ *,
1018
+ evidence_type: str,
1019
+ evidence_hash: str,
1020
+ session_id: str = "",
1021
+ ) -> dict[str, Any]:
1022
+ return self.experience.stabilize_memory(
1023
+ memory_id=int(memory_id),
1024
+ evidence_type=evidence_type,
1025
+ evidence_hash=evidence_hash,
1026
+ session_id=session_id,
1027
+ )
1028
+
1029
+ def retract_memory(
1030
+ self,
1031
+ memory_id: int,
1032
+ *,
1033
+ reason: str,
1034
+ session_id: str = "",
1035
+ ) -> dict[str, Any]:
1036
+ return self.experience.retract_memory(
1037
+ memory_id=int(memory_id),
1038
+ reason=reason,
1039
+ session_id=session_id,
1040
+ )
1041
+
1042
+ def belief_history(
1043
+ self,
1044
+ *,
1045
+ memory_id: int | None = None,
1046
+ belief_id: str = "",
1047
+ ) -> list[dict[str, Any]]:
1048
+ return self.experience.belief_history(
1049
+ memory_id=memory_id,
1050
+ belief_id=belief_id,
1051
+ )
1052
+
1053
+ def run_correction_check(
1054
+ self,
1055
+ *,
1056
+ rehearsal_id: int | None = None,
1057
+ limit: int = 1,
1058
+ ) -> dict[str, Any]:
1059
+ return self.experience.run_correction_check(
1060
+ recall_fn=self.recall_with_experience,
1061
+ rehearsal_id=rehearsal_id,
1062
+ limit=limit,
1063
+ )
1064
+
1065
+ def association_preview(self, *, limit: int | None = None) -> dict[str, Any]:
1066
+ lim = (
1067
+ int(self.policies.insight.association_limit)
1068
+ if limit is None
1069
+ else int(limit)
1070
+ )
1071
+ return self.experience.association_preview(limit=lim)
1072
+
1073
+ def propose_insight(
1074
+ self,
1075
+ *,
1076
+ association_id: str,
1077
+ hypothesis: str,
1078
+ source_memory_ids: Sequence[int],
1079
+ initial_confidence: float = 0.55,
1080
+ ) -> dict[str, Any]:
1081
+ return self.experience.propose_insight(
1082
+ association_id=association_id,
1083
+ hypothesis=hypothesis,
1084
+ source_memory_ids=source_memory_ids,
1085
+ initial_confidence=initial_confidence,
1086
+ )
1087
+
1088
+ def validate_insight(
1089
+ self,
1090
+ *,
1091
+ candidate_id: str,
1092
+ validation_method: str,
1093
+ evidence: Sequence[Mapping[str, Any]],
1094
+ validated_confidence: float,
1095
+ summary: str = "",
1096
+ ) -> dict[str, Any]:
1097
+ result = self.experience.validate_insight(
1098
+ candidate_id=candidate_id,
1099
+ validation_method=validation_method,
1100
+ evidence=evidence,
1101
+ validated_confidence=validated_confidence,
1102
+ summary=summary,
1103
+ remember_fn=lambda content, **kwargs: self.remember(content, **kwargs),
1104
+ )
1105
+ return {
1106
+ "status": result.status.value,
1107
+ "candidate_id": result.candidate_id,
1108
+ "promoted_memory_id": result.promoted_memory_id,
1109
+ "contested_source_ids": list(result.contested_source_ids),
1110
+ }
1111
+
1112
+ def reject_insight(self, *, candidate_id: str, reason: str) -> dict[str, Any]:
1113
+ return self.experience.reject_insight(
1114
+ candidate_id=candidate_id, reason=reason
1115
+ )
1116
+
1117
+ def _protected_category_breakdown(self) -> dict[str, int]:
1118
+ breakdown: dict[str, int] = {}
1119
+ rows = self._conn.execute(
1120
+ "SELECT tags FROM memories WHERE state = 'active'"
1121
+ ).fetchall()
1122
+ protected = {
1123
+ str(tag).strip().lower() for tag in self.policies.capacity.protected_tags
1124
+ }
1125
+ for row in rows:
1126
+ tags = {t.lower() for t in _split_tags(row["tags"])}
1127
+ for tag in tags & protected:
1128
+ breakdown[tag] = breakdown.get(tag, 0) + 1
1129
+ return breakdown
1130
+
1131
+ def _eviction_rank(self, row: sqlite3.Row) -> tuple:
1132
+ """Lower tuple sorts first = better eviction candidate."""
1133
+ access = str(row["access_state"] or "accessible")
1134
+ belief = str(row["belief_status"] or "current")
1135
+ if belief in {"contested", "superseded", "retracted"}:
1136
+ tier = -1
1137
+ elif access == "latent":
1138
+ tier = 0
1139
+ elif access == "accessible":
1140
+ tier = 1
1141
+ else:
1142
+ tier = 2
1143
+ retention = self._retention(row)
1144
+ reactivated_at = _timestamp_value(
1145
+ row["last_reactivated_at"],
1146
+ default=_timestamp_value(row["created_at"]),
1147
+ )
1148
+ anchor = _timestamp_value(
1149
+ row["last_anchor_at"], default=_timestamp_value(row["created_at"])
1150
+ )
1151
+ return (
1152
+ tier,
1153
+ retention,
1154
+ float(row["salience"] or 0.0),
1155
+ int(row["retrieval_count"] or 0),
1156
+ int(row["rehearsal_count"] or 0),
1157
+ reactivated_at if access == "reactivated" else anchor,
1158
+ int(row["memory_id"]),
1159
+ )
1160
+
1161
+ def _enforce_capacity_headroom(self) -> None:
1162
+ cap = self.policies.capacity
1163
+ active_count = self._count_active()
1164
+ if active_count < cap.max_active_memories:
1165
+ return
1166
+ rows = self._conn.execute(
1167
+ "SELECT * FROM memories WHERE state = 'active'"
1168
+ ).fetchall()
1169
+ candidates = [
1170
+ r for r in rows if not is_protected(_split_tags(r["tags"]), cap.protected_tags)
1171
+ ]
1172
+ candidates.sort(key=self._eviction_rank)
1173
+ archived = 0
1174
+ now = self._now()
1175
+ for r in candidates:
1176
+ self._archive_memory(r["memory_id"], reason="capacity", now=now)
1177
+ archived += 1
1178
+ if active_count - archived < cap.max_active_memories:
1179
+ self._conn.commit()
1180
+ return
1181
+ protected_categories = self._protected_category_breakdown()
1182
+ raise CapacityError(
1183
+ f"Memory capacity full ({cap.max_active_memories} active) "
1184
+ "and no non-protected memory can be archived.",
1185
+ details={
1186
+ "capacity_blocked": True,
1187
+ "active_count": active_count,
1188
+ "max_active_memories": cap.max_active_memories,
1189
+ "protected_count": active_count - archived,
1190
+ "protected_categories": protected_categories,
1191
+ },
1192
+ )
1193
+
1194
+ # ------------------------------------------------------------------
1195
+ # get
1196
+ # ------------------------------------------------------------------
1197
+
1198
+ def get(self, memory_id: int) -> dict:
1199
+ row = self._conn.execute(
1200
+ "SELECT * FROM memories WHERE memory_id = ?", (int(memory_id),)
1201
+ ).fetchone()
1202
+ if not row:
1203
+ raise KeyError(f"memory_id not found: {memory_id}")
1204
+ return self._row_to_result(row, query_score=None)
1205
+
1206
+ # ------------------------------------------------------------------
1207
+ # recall
1208
+ # ------------------------------------------------------------------
1209
+
1210
+ def recall(
1211
+ self,
1212
+ query: str,
1213
+ *,
1214
+ limit: int = 5,
1215
+ min_score: float = 0.12,
1216
+ reinforce: bool = False,
1217
+ include_archived: bool = False,
1218
+ ) -> list[dict]:
1219
+ result = self.recall_with_experience(
1220
+ query,
1221
+ limit=limit,
1222
+ min_score=min_score,
1223
+ reinforce=reinforce,
1224
+ include_archived=include_archived,
1225
+ include_history=False,
1226
+ allow_rescue=None,
1227
+ track=True,
1228
+ )
1229
+ return result.results
1230
+
1231
+ def recall_with_experience(
1232
+ self,
1233
+ query: str,
1234
+ *,
1235
+ limit: int = 5,
1236
+ min_score: float = 0.12,
1237
+ reinforce: bool = False,
1238
+ include_archived: bool = False,
1239
+ include_history: bool = False,
1240
+ allow_rescue: bool | None = None,
1241
+ track: bool = True,
1242
+ ) -> RecallAttemptResult:
1243
+ """Cue recall with optional miss tracking, rescue, and historical access."""
1244
+ query = _normalize_text(query)
1245
+ if not query:
1246
+ return RecallAttemptResult(
1247
+ query=query,
1248
+ outcome=RetrievalOutcome.MISS,
1249
+ results=[],
1250
+ )
1251
+
1252
+ query_counts = _cue_counts(query)
1253
+ query_lower = query.lower()
1254
+ query_cues = _top_cues(query_counts, limit=32)
1255
+ query_hash = normalize_query_hash(query)
1256
+ excerpt = (
1257
+ query[:240]
1258
+ if self.policies.experience.record_query_excerpt
1259
+ else ""
1260
+ )
1261
+ xp = self.policies.experience
1262
+ rescue_allowed = (
1263
+ bool(xp.rescue_enabled)
1264
+ if allow_rescue is None
1265
+ else bool(allow_rescue)
1266
+ )
1267
+
1268
+ rows = self._conn.execute("SELECT * FROM memories").fetchall()
1269
+ scored: list[dict] = []
1270
+ best_score = 0.0
1271
+ for row in rows:
1272
+ state = str(row["state"] or "active")
1273
+ access_state = str(row["access_state"] or "accessible")
1274
+ belief_status = str(row["belief_status"] or "current")
1275
+
1276
+ historical = False
1277
+ if include_history and belief_status in {
1278
+ "superseded",
1279
+ "retracted",
1280
+ "contested",
1281
+ "unverified",
1282
+ }:
1283
+ historical = True
1284
+ else:
1285
+ if state != "active" and not include_archived:
1286
+ continue
1287
+ if include_archived and state not in {"active", "archived"}:
1288
+ continue
1289
+ if state == "active" and access_state not in {"accessible", "reactivated"}:
1290
+ continue
1291
+ if (
1292
+ state == "archived"
1293
+ and access_state not in {"accessible", "reactivated", "latent"}
1294
+ ):
1295
+ continue
1296
+ if belief_status not in {"current", "context_dependent"}:
1297
+ continue
1298
+
1299
+ score = self._score_row_against_query(
1300
+ row, query_counts=query_counts, query_lower=query_lower, query=query
1301
+ )
1302
+ if score is None:
1303
+ continue
1304
+ best_score = max(best_score, float(score))
1305
+ if score < min_score:
1306
+ continue
1307
+ retention = self._retention(row)
1308
+ item = self._row_to_result(row, query_score=score, retention=retention)
1309
+ if historical:
1310
+ item["historical"] = True
1311
+ scored.append(item)
1312
+
1313
+ scored.sort(
1314
+ key=lambda item: (item["score"], item["retention"], item["salience"]),
1315
+ reverse=True,
1316
+ )
1317
+ results = scored[: max(1, int(limit))] if scored else []
1318
+
1319
+ if results and reinforce and not any(r.get("historical") for r in results):
1320
+ for result in results:
1321
+ self._reinforce_retrieval(result["memory_id"])
1322
+ results = [
1323
+ self.get(r["memory_id"]) | {"score": r["score"]}
1324
+ for r in results
1325
+ ]
1326
+
1327
+ if results:
1328
+ if (
1329
+ track
1330
+ and xp.enabled
1331
+ and xp.record_hits
1332
+ ):
1333
+ self.experience.record_event(
1334
+ "retrieval_hit",
1335
+ memory_id=int(results[0]["memory_id"]),
1336
+ payload={
1337
+ "query_hash": query_hash,
1338
+ "direct_best_score": best_score,
1339
+ "result_count": len(results),
1340
+ },
1341
+ )
1342
+ return RecallAttemptResult(
1343
+ query=query,
1344
+ outcome=RetrievalOutcome.HIT,
1345
+ results=results,
1346
+ direct_best_score=best_score,
1347
+ )
1348
+
1349
+ attempt_id = None
1350
+ if track and xp.enabled:
1351
+ attempt_id = self.experience.record_retrieval_miss(
1352
+ query_hash=query_hash,
1353
+ query_excerpt=excerpt,
1354
+ query_cues=query_cues,
1355
+ direct_best_score=best_score,
1356
+ )
1357
+
1358
+ if xp.enabled and rescue_allowed:
1359
+ rescued = self._attempt_rescue(
1360
+ query=query,
1361
+ query_counts=query_counts,
1362
+ query_lower=query_lower,
1363
+ query_cues=query_cues,
1364
+ query_hash=query_hash,
1365
+ direct_best_score=best_score,
1366
+ reinforce=reinforce,
1367
+ attempt_id=attempt_id,
1368
+ )
1369
+ if rescued is not None:
1370
+ return rescued
1371
+
1372
+ return RecallAttemptResult(
1373
+ query=query,
1374
+ outcome=RetrievalOutcome.MISS,
1375
+ results=[],
1376
+ attempt_id=attempt_id,
1377
+ direct_best_score=best_score,
1378
+ )
1379
+
1380
+ def _score_row_against_query(
1381
+ self,
1382
+ row: sqlite3.Row,
1383
+ *,
1384
+ query_counts: Counter,
1385
+ query_lower: str,
1386
+ query: str,
1387
+ ) -> float | None:
1388
+ encoded = self._decode(row["encoded"])
1389
+ memory_counts = Counter(encoded.get("cue_vector") or {})
1390
+ tags = _split_tags(row["tags"])
1391
+ tag_counts = _cue_counts(tags)
1392
+ lexical = _cosine(query_counts, memory_counts + tag_counts)
1393
+ substring = 0.35 if query_lower in str(row["content"]).lower() else 0.0
1394
+ tag_bonus = 0.12 if set(_split_tags(query)) & set(tags) else 0.0
1395
+ if lexical <= 0 and substring <= 0 and tag_bonus <= 0:
1396
+ return None
1397
+ retention = self._retention(row)
1398
+ salience = float(row["salience"] or 0.0)
1399
+ rehearsal_bonus = min(
1400
+ 0.08, math.log1p(int(row["rehearsal_count"] or 0)) * 0.025
1401
+ )
1402
+ return (
1403
+ max(lexical, substring) * 0.68
1404
+ + retention * 0.18
1405
+ + salience * 0.08
1406
+ + tag_bonus
1407
+ + rehearsal_bonus
1408
+ )
1409
+
1410
+ def _attempt_rescue(
1411
+ self,
1412
+ *,
1413
+ query: str,
1414
+ query_counts: Counter,
1415
+ query_lower: str,
1416
+ query_cues: Sequence[str],
1417
+ query_hash: str,
1418
+ direct_best_score: float,
1419
+ reinforce: bool,
1420
+ attempt_id: int | None,
1421
+ ) -> RecallAttemptResult | None:
1422
+ xp = self.policies.experience
1423
+ candidates: list[tuple[float, sqlite3.Row]] = []
1424
+ for state_filter in ("active", "archived"):
1425
+ rows = self._conn.execute(
1426
+ """
1427
+ SELECT * FROM memories
1428
+ WHERE state = ?
1429
+ AND access_state = 'latent'
1430
+ AND belief_status IN ('current', 'context_dependent')
1431
+ """,
1432
+ (state_filter,),
1433
+ ).fetchall()
1434
+ for row in rows:
1435
+ score = self._score_row_against_query(
1436
+ row,
1437
+ query_counts=query_counts,
1438
+ query_lower=query_lower,
1439
+ query=query,
1440
+ )
1441
+ if score is None or score < float(xp.rescue_min_score):
1442
+ continue
1443
+ candidates.append((float(score), row))
1444
+ if candidates:
1445
+ break
1446
+
1447
+ if not candidates:
1448
+ return None
1449
+
1450
+ candidates.sort(key=lambda item: item[0], reverse=True)
1451
+ rescue_score, row = candidates[0]
1452
+ memory_id = int(row["memory_id"])
1453
+ now = self._now()
1454
+ created = _timestamp_value(row["created_at"], default=now)
1455
+ age_days = max(0.0, (now - created) / 86400.0)
1456
+ resolution_gain = max(0.0, float(rescue_score) - float(direct_best_score))
1457
+ surprise = _clamp(
1458
+ 0.50 * (1.0 - float(direct_best_score))
1459
+ + 0.30 * resolution_gain
1460
+ + 0.20 * min(1.0, age_days / 90.0),
1461
+ 0.0,
1462
+ 1.0,
1463
+ )
1464
+
1465
+ with self._lock:
1466
+ self._conn.execute(
1467
+ """
1468
+ UPDATE memories
1469
+ SET state = 'active',
1470
+ access_state = 'reactivated',
1471
+ archived_at = NULL,
1472
+ archive_reason = '',
1473
+ reactivation_count = COALESCE(reactivation_count, 0) + 1,
1474
+ last_reactivated_at = ?,
1475
+ last_retrieved_at = ?,
1476
+ retrieval_count = retrieval_count + ?,
1477
+ updated_at = ?,
1478
+ last_anchor_at = CASE WHEN ? > 0 THEN ? ELSE last_anchor_at END
1479
+ WHERE memory_id = ?
1480
+ """,
1481
+ (
1482
+ now,
1483
+ now,
1484
+ 1 if reinforce else 0,
1485
+ now,
1486
+ 1 if reinforce else 0,
1487
+ now,
1488
+ memory_id,
1489
+ ),
1490
+ )
1491
+ self._conn.execute(
1492
+ """
1493
+ INSERT OR IGNORE INTO memory_relations(
1494
+ source_memory_id, target_memory_id, relation_type, metadata, created_at
1495
+ ) VALUES (?, ?, 'triggered_recall', ?, ?)
1496
+ """,
1497
+ (
1498
+ memory_id,
1499
+ memory_id,
1500
+ json.dumps({"query_hash": query_hash}, ensure_ascii=False),
1501
+ now,
1502
+ ),
1503
+ )
1504
+ self._conn.commit()
1505
+
1506
+ self.experience.record_event(
1507
+ "memory_reactivated",
1508
+ memory_id=memory_id,
1509
+ belief_id=str(row["belief_id"] or ""),
1510
+ payload={
1511
+ "rescue_score": rescue_score,
1512
+ "direct_best_score": direct_best_score,
1513
+ "surprise": surprise,
1514
+ "query_hash": query_hash,
1515
+ },
1516
+ )
1517
+ resolved = self.experience.resolve_retrieval_miss(
1518
+ current_query_hash=query_hash,
1519
+ current_cues=query_cues,
1520
+ rescued_memory_id=memory_id,
1521
+ rescue_score=rescue_score,
1522
+ direct_best_score=direct_best_score,
1523
+ current_attempt_id=attempt_id,
1524
+ )
1525
+ matched_miss_id = None
1526
+ if resolved:
1527
+ matched_miss_id = int(resolved.get("matched_miss_id") or resolved.get("attempt_id") or 0) or None
1528
+ if "surprise" in resolved:
1529
+ surprise = float(resolved["surprise"])
1530
+ if (
1531
+ attempt_id is not None
1532
+ and matched_miss_id is not None
1533
+ and matched_miss_id != attempt_id
1534
+ and resolution_gain > 0.0
1535
+ ):
1536
+ self.experience.record_event(
1537
+ "forgotten_then_recalled",
1538
+ memory_id=memory_id,
1539
+ belief_id=str(row["belief_id"] or ""),
1540
+ payload={
1541
+ "prior_attempt_id": matched_miss_id,
1542
+ "current_attempt_id": attempt_id,
1543
+ "current_query_hash": query_hash,
1544
+ "resolution_gain": resolution_gain,
1545
+ "surprise": surprise,
1546
+ },
1547
+ )
1548
+
1549
+ result = self.get(memory_id) | {"score": round(float(rescue_score), 4)}
1550
+ state_note = (
1551
+ "[Memory state]\n"
1552
+ "A previously inaccessible memory was recovered from a latent or archived trace.\n"
1553
+ "Treat it as recalled context, not verified truth.\n"
1554
+ "Outcome: forgotten_then_recalled\n"
1555
+ f"Surprise: {surprise:.2f}"
1556
+ )
1557
+ return RecallAttemptResult(
1558
+ query=query,
1559
+ outcome=RetrievalOutcome.RESCUED,
1560
+ results=[result],
1561
+ attempt_id=attempt_id,
1562
+ matched_miss_id=matched_miss_id,
1563
+ rescued_memory_id=memory_id,
1564
+ direct_best_score=direct_best_score,
1565
+ rescue_score=float(rescue_score),
1566
+ surprise=float(surprise),
1567
+ state_note=state_note,
1568
+ )
1569
+
1570
+ # ------------------------------------------------------------------
1571
+ # rehearse
1572
+ # ------------------------------------------------------------------
1573
+
1574
+ def rehearse(
1575
+ self,
1576
+ *,
1577
+ memory_id: int | None = None,
1578
+ query: str = "",
1579
+ limit: int = 1,
1580
+ ) -> list[dict]:
1581
+ targets: list[int] = []
1582
+ if memory_id is not None:
1583
+ targets.append(int(memory_id))
1584
+ elif query:
1585
+ targets.extend(
1586
+ item["memory_id"]
1587
+ for item in self.recall(query, limit=limit, reinforce=False)
1588
+ )
1589
+ else:
1590
+ raise ValueError("memory_id or query is required")
1591
+
1592
+ now = self._now()
1593
+ for target in targets:
1594
+ row = self._conn.execute(
1595
+ "SELECT * FROM memories WHERE memory_id = ?", (target,)
1596
+ ).fetchone()
1597
+ gain = self._reinforcement_gain(row, kind="rehearsal") if row else 0.25
1598
+ self._conn.execute(
1599
+ """
1600
+ UPDATE memories
1601
+ SET rehearsal_count = rehearsal_count + 1,
1602
+ strength = MIN(?, strength + ?),
1603
+ last_rehearsed_at = ?, updated_at = ?,
1604
+ last_anchor_at = ?
1605
+ WHERE memory_id = ?
1606
+ """,
1607
+ (_MAX_STRENGTH, gain, now, now, now, target),
1608
+ )
1609
+ self._conn.commit()
1610
+ return [self.get(t) for t in targets]
1611
+
1612
+ # ------------------------------------------------------------------
1613
+ # forget (exact delete)
1614
+ # ------------------------------------------------------------------
1615
+
1616
+ def forget(self, memory_id: int) -> bool:
1617
+ mid = int(memory_id)
1618
+ if mid < 1:
1619
+ raise ValueError(f"memory_id must be >= 1, got {mid}")
1620
+ cur = self._conn.execute(
1621
+ "DELETE FROM memories WHERE memory_id = ?", (mid,)
1622
+ )
1623
+ self._conn.commit()
1624
+ return cur.rowcount > 0
1625
+
1626
+ # ------------------------------------------------------------------
1627
+ # decay (legacy)
1628
+ # ------------------------------------------------------------------
1629
+
1630
+ def decay(
1631
+ self,
1632
+ *,
1633
+ threshold: float | None = None,
1634
+ prune: bool = False,
1635
+ limit: int = 50,
1636
+ ) -> dict:
1637
+ threshold = (
1638
+ self.decay_threshold
1639
+ if threshold is None
1640
+ else _clamp(float(threshold), 0.0, 1.0)
1641
+ )
1642
+ rows = self._conn.execute(
1643
+ "SELECT * FROM memories WHERE state = 'active'"
1644
+ ).fetchall()
1645
+ decayed = [
1646
+ self._row_to_result(row, query_score=None)
1647
+ for row in rows
1648
+ if self._retention(row) <= threshold
1649
+ ]
1650
+ decayed.sort(key=lambda item: item["retention"])
1651
+ decayed = decayed[: max(1, int(limit))]
1652
+ pruned: list[int] = []
1653
+ if prune and decayed:
1654
+ pruned = [int(item["memory_id"]) for item in decayed]
1655
+ self._conn.executemany(
1656
+ "DELETE FROM memories WHERE memory_id = ?",
1657
+ [(mid,) for mid in pruned],
1658
+ )
1659
+ self._conn.commit()
1660
+ return {"threshold": threshold, "decayed": decayed, "pruned": pruned}
1661
+
1662
+ # ------------------------------------------------------------------
1663
+ # sleep_cycle
1664
+ # ------------------------------------------------------------------
1665
+
1666
+ def sleep_cycle(
1667
+ self,
1668
+ *,
1669
+ rehearse_threshold: float | None = None,
1670
+ forget_threshold: float | None = None,
1671
+ salience_keep_threshold: float | None = None,
1672
+ prune: bool | None = None,
1673
+ limit: int | None = None,
1674
+ prune_mode: str | None = None,
1675
+ max_sleep_rehearsals: int | None = None,
1676
+ max_negative_sleep_rehearsals: int | None = None,
1677
+ ) -> dict:
1678
+ sp = self.policies.sleep
1679
+ cp = self.policies.capacity
1680
+
1681
+ rehearse_threshold = _clamp(
1682
+ float(sp.rehearse_threshold if rehearse_threshold is None else rehearse_threshold),
1683
+ 0.0,
1684
+ 1.0,
1685
+ )
1686
+ forget_threshold = _clamp(
1687
+ float(sp.forget_threshold if forget_threshold is None else forget_threshold),
1688
+ 0.0,
1689
+ 1.0,
1690
+ )
1691
+ salience_keep_threshold = _clamp(
1692
+ float(
1693
+ sp.salience_keep_threshold
1694
+ if salience_keep_threshold is None
1695
+ else salience_keep_threshold
1696
+ ),
1697
+ 0.0,
1698
+ 1.0,
1699
+ )
1700
+ limit = max(1, int(sp.limit if limit is None else limit))
1701
+
1702
+ resolved_prune = resolve_prune_mode(
1703
+ prune=prune,
1704
+ prune_mode=prune_mode,
1705
+ default=sp.prune_mode,
1706
+ )
1707
+ max_sr = (
1708
+ sp.max_sleep_rehearsals
1709
+ if max_sleep_rehearsals is None
1710
+ else int(max_sleep_rehearsals)
1711
+ )
1712
+ max_neg_sr = (
1713
+ sp.max_negative_sleep_rehearsals
1714
+ if max_negative_sleep_rehearsals is None
1715
+ else int(max_negative_sleep_rehearsals)
1716
+ )
1717
+
1718
+ candidate_window = max(limit * 3, limit + 256)
1719
+ # Prefer never-slept / oldest-slept first so prune_mode=none still advances.
1720
+ candidates = self._conn.execute(
1721
+ """
1722
+ SELECT * FROM memories
1723
+ WHERE state = 'active'
1724
+ ORDER BY COALESCE(last_sleep_at, 0) ASC,
1725
+ COALESCE(last_anchor_at, created_at) ASC,
1726
+ memory_id ASC
1727
+ LIMIT ?
1728
+ """,
1729
+ (candidate_window,),
1730
+ ).fetchall()
1731
+
1732
+ scored: list[tuple[float, float, sqlite3.Row]] = []
1733
+ for row in candidates:
1734
+ retention = self._retention(row)
1735
+ salience = float(row["salience"] or 0.0)
1736
+ scored.append((retention, salience, row))
1737
+ scored.sort(key=lambda t: (t[0], -t[1]))
1738
+
1739
+ now = self._now()
1740
+ replay_budgets = self._select_replay_budgets(candidates)
1741
+ recent_replayed, recent_cap_suppressed = self._apply_replay_rows(
1742
+ replay_budgets["recent_replay"]["rows"],
1743
+ now=now,
1744
+ max_sleep_rehearsals=max_sr,
1745
+ max_negative_sleep_rehearsals=max_neg_sr,
1746
+ )
1747
+ remote_replayed, remote_cap_suppressed = self._apply_replay_rows(
1748
+ replay_budgets["remote_integration"]["rows"],
1749
+ now=now,
1750
+ max_sleep_rehearsals=max_sr,
1751
+ max_negative_sleep_rehearsals=max_neg_sr,
1752
+ )
1753
+ replayed_ids = set(recent_replayed) | set(remote_replayed)
1754
+ rehearsed: list[int] = [*recent_replayed, *remote_replayed]
1755
+ forgotten_ids: list[int] = []
1756
+ latent_ids: list[int] = []
1757
+ archived_ids: list[int] = []
1758
+ dream_candidate_ids: list[int] = []
1759
+ negative_rehearsal_suppressed: list[int] = list(
1760
+ dict.fromkeys(
1761
+ [
1762
+ *replay_budgets["recent_replay"]["negative_suppressed"],
1763
+ *replay_budgets["remote_integration"]["negative_suppressed"],
1764
+ ]
1765
+ )
1766
+ )
1767
+ protected_skipped: list[int] = []
1768
+ reviewed_ids: list[int] = list(
1769
+ dict.fromkeys([*recent_replayed, *remote_replayed])
1770
+ )
1771
+ reviewed_id_set = set(reviewed_ids)
1772
+ processed = 0
1773
+
1774
+ xp = self.policies.experience
1775
+ functional = bool(xp.enabled and xp.functional_forgetting)
1776
+ latent_threshold = (
1777
+ float(xp.latent_retention_threshold) if functional else forget_threshold
1778
+ )
1779
+
1780
+ for retention, salience, row in scored:
1781
+ if processed >= limit:
1782
+ break
1783
+ processed += 1
1784
+ mid = int(row["memory_id"])
1785
+ if mid not in reviewed_id_set:
1786
+ reviewed_ids.append(mid)
1787
+ reviewed_id_set.add(mid)
1788
+ valence = float(row["valence"] or 0.0)
1789
+ prot = self._is_row_protected(row)
1790
+ src = int(row["sleep_rehearsal_count"] or 0)
1791
+ access_state = str(row["access_state"] or "accessible")
1792
+
1793
+ if mid in replayed_ids:
1794
+ continue
1795
+
1796
+ if prot:
1797
+ if (
1798
+ src < max_sr
1799
+ and retention <= rehearse_threshold
1800
+ and salience >= salience_keep_threshold
1801
+ ):
1802
+ gain = self._reinforcement_gain(row, kind="rehearsal")
1803
+ self._conn.execute(
1804
+ """
1805
+ UPDATE memories
1806
+ SET rehearsal_count = rehearsal_count + 1,
1807
+ strength = MIN(?, strength + ?),
1808
+ last_rehearsed_at = ?, updated_at = ?,
1809
+ last_anchor_at = ?,
1810
+ sleep_rehearsal_count = sleep_rehearsal_count + 1
1811
+ WHERE memory_id = ?
1812
+ """,
1813
+ (_MAX_STRENGTH, gain, now, now, now, mid),
1814
+ )
1815
+ rehearsed.append(mid)
1816
+ else:
1817
+ protected_skipped.append(mid)
1818
+ continue
1819
+
1820
+ strongly_negative = valence <= sp.negative_valence_threshold
1821
+
1822
+ if strongly_negative:
1823
+ # Forget/archive first when retention is exhausted; otherwise
1824
+ # allow a small number of attenuated sleep rehearsals.
1825
+ if retention <= latent_threshold and salience < salience_keep_threshold:
1826
+ forgotten_ids.append(mid)
1827
+ if functional and access_state in {"accessible", "reactivated"}:
1828
+ self._mark_memory_latent(mid, now=now)
1829
+ latent_ids.append(mid)
1830
+ self._conn.execute(
1831
+ "UPDATE memories SET dream_candidate = 1 WHERE memory_id = ?",
1832
+ (mid,),
1833
+ )
1834
+ dream_candidate_ids.append(mid)
1835
+ elif src < max_neg_sr and retention <= rehearse_threshold:
1836
+ gain = self._reinforcement_gain(row, kind="rehearsal")
1837
+ self._conn.execute(
1838
+ """
1839
+ UPDATE memories
1840
+ SET rehearsal_count = rehearsal_count + 1,
1841
+ strength = MIN(?, strength + ?),
1842
+ last_rehearsed_at = ?, updated_at = ?,
1843
+ last_anchor_at = ?,
1844
+ sleep_rehearsal_count = sleep_rehearsal_count + 1
1845
+ WHERE memory_id = ?
1846
+ """,
1847
+ (_MAX_STRENGTH, gain, now, now, now, mid),
1848
+ )
1849
+ rehearsed.append(mid)
1850
+ else:
1851
+ negative_rehearsal_suppressed.append(mid)
1852
+ self._conn.execute(
1853
+ "UPDATE memories SET dream_candidate = 1 WHERE memory_id = ?",
1854
+ (mid,),
1855
+ )
1856
+ dream_candidate_ids.append(mid)
1857
+ continue
1858
+
1859
+ # Instruction §8.6: forget before rehearse so capped high-salience
1860
+ # traces can leave the active set once retention collapses.
1861
+ if retention <= latent_threshold and salience < salience_keep_threshold:
1862
+ forgotten_ids.append(mid)
1863
+ if functional and access_state in {"accessible", "reactivated"}:
1864
+ self._mark_memory_latent(mid, now=now)
1865
+ latent_ids.append(mid)
1866
+ elif (
1867
+ retention <= rehearse_threshold
1868
+ and salience >= salience_keep_threshold
1869
+ and src < max_sr
1870
+ ):
1871
+ gain = self._reinforcement_gain(row, kind="rehearsal")
1872
+ self._conn.execute(
1873
+ """
1874
+ UPDATE memories
1875
+ SET rehearsal_count = rehearsal_count + 1,
1876
+ strength = MIN(?, strength + ?),
1877
+ last_rehearsed_at = ?, updated_at = ?,
1878
+ last_anchor_at = ?,
1879
+ sleep_rehearsal_count = sleep_rehearsal_count + 1
1880
+ WHERE memory_id = ?
1881
+ """,
1882
+ (_MAX_STRENGTH, gain, now, now, now, mid),
1883
+ )
1884
+ rehearsed.append(mid)
1885
+ elif (
1886
+ retention <= rehearse_threshold
1887
+ and salience >= salience_keep_threshold
1888
+ and src >= max_sr
1889
+ ):
1890
+ self._conn.execute(
1891
+ "UPDATE memories SET dream_candidate = 1 WHERE memory_id = ?",
1892
+ (mid,),
1893
+ )
1894
+ dream_candidate_ids.append(mid)
1895
+
1896
+ pruned_ids: list[int] = []
1897
+ if forgotten_ids and not functional:
1898
+ if resolved_prune == "archive":
1899
+ for mid in forgotten_ids:
1900
+ self._archive_memory(mid, reason="sleep-forget", now=now)
1901
+ archived_ids.extend(forgotten_ids)
1902
+ elif resolved_prune == "delete":
1903
+ self._conn.executemany(
1904
+ "DELETE FROM memories WHERE memory_id = ?",
1905
+ [(mid,) for mid in forgotten_ids],
1906
+ )
1907
+ pruned_ids.extend(forgotten_ids)
1908
+ elif functional:
1909
+ archived_from_latent = self._archive_exhausted_latent(
1910
+ now, skip_ids=set(latent_ids)
1911
+ )
1912
+ for mid in archived_from_latent:
1913
+ if mid not in forgotten_ids:
1914
+ forgotten_ids.append(mid)
1915
+ archived_ids.append(mid)
1916
+
1917
+ self._archive_noncurrent_beliefs(now)
1918
+
1919
+ correction_report = {"passed": [], "failed": []}
1920
+ if xp.enabled and int(xp.correction_rehearsals_per_sleep) > 0:
1921
+ correction_report = self.run_correction_check(
1922
+ rehearsal_id=None,
1923
+ limit=int(xp.correction_rehearsals_per_sleep),
1924
+ )
1925
+
1926
+ capacity_archived = self._enforce_capacity_ceiling(now)
1927
+
1928
+ purged = self._purge_old_archives(now)
1929
+
1930
+ if reviewed_ids:
1931
+ self._conn.executemany(
1932
+ "UPDATE memories SET last_sleep_at = ? WHERE memory_id = ?",
1933
+ [(now, mid) for mid in reviewed_ids],
1934
+ )
1935
+
1936
+ self._conn.commit()
1937
+
1938
+ return {
1939
+ "mode": "sleep_cycle",
1940
+ "reviewed": processed,
1941
+ "candidate_window": candidate_window,
1942
+ "rehearse_threshold": rehearse_threshold,
1943
+ "forget_threshold": forget_threshold,
1944
+ "salience_keep_threshold": salience_keep_threshold,
1945
+ "prune_mode": resolved_prune,
1946
+ "rehearsed": rehearsed,
1947
+ "forgotten": forgotten_ids,
1948
+ "latent": latent_ids,
1949
+ "archived": archived_ids,
1950
+ "pruned": pruned_ids,
1951
+ "correction_rehearsals": {
1952
+ "passed": list(correction_report.get("passed") or []),
1953
+ "failed": list(correction_report.get("failed") or []),
1954
+ },
1955
+ "negative_rehearsal_suppressed": negative_rehearsal_suppressed,
1956
+ "recent_replay": {
1957
+ "budget": replay_budgets["recent_replay"]["budget"],
1958
+ "selected": replay_budgets["recent_replay"]["selected"],
1959
+ "replayed": recent_replayed,
1960
+ "negative_suppressed": replay_budgets["recent_replay"][
1961
+ "negative_suppressed"
1962
+ ],
1963
+ "cap_suppressed": recent_cap_suppressed,
1964
+ },
1965
+ "remote_integration": {
1966
+ "budget": replay_budgets["remote_integration"]["budget"],
1967
+ "selected": replay_budgets["remote_integration"]["selected"],
1968
+ "replayed": remote_replayed,
1969
+ "negative_suppressed": replay_budgets["remote_integration"][
1970
+ "negative_suppressed"
1971
+ ],
1972
+ "cap_suppressed": remote_cap_suppressed,
1973
+ },
1974
+ "dream_candidates": dream_candidate_ids,
1975
+ "capacity_archived": capacity_archived,
1976
+ "purged": purged,
1977
+ "protected_skipped": protected_skipped,
1978
+ "active_count": self._count_active(),
1979
+ "archived_count": self._count_archived(),
1980
+ }
1981
+
1982
+ # ------------------------------------------------------------------
1983
+ # archive / capacity helpers
1984
+ # ------------------------------------------------------------------
1985
+
1986
+ def _archive_memory(self, memory_id: int, *, reason: str, now: float) -> None:
1987
+ self._conn.execute(
1988
+ """
1989
+ UPDATE memories
1990
+ SET state = 'archived', archived_at = ?, archive_reason = ?,
1991
+ updated_at = ?,
1992
+ access_state = CASE
1993
+ WHEN COALESCE(access_state, 'accessible') = 'accessible'
1994
+ THEN 'latent'
1995
+ ELSE access_state
1996
+ END
1997
+ WHERE memory_id = ? AND state = 'active'
1998
+ """,
1999
+ (now, reason, now, memory_id),
2000
+ )
2001
+
2002
+ def _mark_memory_latent(self, memory_id: int, *, now: float) -> None:
2003
+ self._conn.execute(
2004
+ """
2005
+ UPDATE memories
2006
+ SET access_state = 'latent',
2007
+ latent_at = COALESCE(latent_at, ?),
2008
+ updated_at = ?
2009
+ WHERE memory_id = ?
2010
+ AND COALESCE(access_state, 'accessible') IN ('accessible', 'reactivated')
2011
+ """,
2012
+ (now, now, memory_id),
2013
+ )
2014
+ belief = self._conn.execute(
2015
+ "SELECT belief_id FROM memories WHERE memory_id = ?",
2016
+ (memory_id,),
2017
+ ).fetchone()
2018
+ self.experience.record_event(
2019
+ "memory_became_latent",
2020
+ memory_id=int(memory_id),
2021
+ belief_id=str(belief["belief_id"] if belief else "") or "",
2022
+ payload={"reason": "sleep-functional-forgetting"},
2023
+ )
2024
+
2025
+ def _archive_exhausted_latent(
2026
+ self, now: float, *, skip_ids: set[int] | None = None
2027
+ ) -> list[int]:
2028
+ xp = self.policies.experience
2029
+ skip = skip_ids or set()
2030
+ archived: list[int] = []
2031
+ rows = self._conn.execute(
2032
+ """
2033
+ SELECT * FROM memories
2034
+ WHERE state = 'active' AND access_state = 'latent'
2035
+ """
2036
+ ).fetchall()
2037
+ max_latent_age = float(xp.latent_archive_after_days) * 86400.0
2038
+ for row in rows:
2039
+ mid = int(row["memory_id"])
2040
+ if mid in skip or self._is_row_protected(row):
2041
+ continue
2042
+ retention = self._retention(row)
2043
+ latent_at = _timestamp_value(row["latent_at"], default=now)
2044
+ aged = (now - latent_at) >= max_latent_age
2045
+ if retention <= float(xp.archive_retention_threshold) or aged:
2046
+ self._archive_memory(mid, reason="latent-exhausted", now=now)
2047
+ self._conn.execute(
2048
+ "UPDATE memories SET access_state = 'latent' WHERE memory_id = ?",
2049
+ (mid,),
2050
+ )
2051
+ archived.append(mid)
2052
+ return archived
2053
+
2054
+ def _archive_noncurrent_beliefs(self, now: float) -> list[int]:
2055
+ archived: list[int] = []
2056
+ rows = self._conn.execute(
2057
+ """
2058
+ SELECT memory_id, tags FROM memories
2059
+ WHERE state = 'active'
2060
+ AND belief_status IN ('contested', 'superseded', 'retracted')
2061
+ """
2062
+ ).fetchall()
2063
+ for row in rows:
2064
+ if self._is_row_protected(row):
2065
+ continue
2066
+ mid = int(row["memory_id"])
2067
+ self._archive_memory(mid, reason="noncurrent-belief", now=now)
2068
+ self._conn.execute(
2069
+ "UPDATE memories SET access_state = 'latent' WHERE memory_id = ?",
2070
+ (mid,),
2071
+ )
2072
+ archived.append(mid)
2073
+ return archived
2074
+
2075
+ def _enforce_capacity_ceiling(self, now: float) -> list[int]:
2076
+ cp = self.policies.capacity
2077
+ active = self._count_active()
2078
+ if active <= cp.max_active_memories:
2079
+ return []
2080
+ overflow = active - cp.max_active_memories
2081
+ rows = self._conn.execute(
2082
+ "SELECT * FROM memories WHERE state = 'active'"
2083
+ ).fetchall()
2084
+ candidates = [
2085
+ r for r in rows if not is_protected(_split_tags(r["tags"]), cp.protected_tags)
2086
+ ]
2087
+ candidates.sort(key=self._eviction_rank)
2088
+ archived: list[int] = []
2089
+ for r in candidates:
2090
+ if len(archived) >= overflow:
2091
+ break
2092
+ self._archive_memory(r["memory_id"], reason="capacity", now=now)
2093
+ archived.append(int(r["memory_id"]))
2094
+ return archived
2095
+
2096
+ def _purge_old_archives(self, now: float) -> list[int]:
2097
+ cp = self.policies.capacity
2098
+ purged: list[int] = []
2099
+ protected = {str(tag).strip().lower() for tag in cp.protected_tags}
2100
+
2101
+ cutoff = now - (cp.archive_retention_days * 86400.0)
2102
+ old_rows = self._conn.execute(
2103
+ """
2104
+ SELECT memory_id, tags FROM memories
2105
+ WHERE state = 'archived' AND archived_at IS NOT NULL AND archived_at < ?
2106
+ ORDER BY archived_at ASC
2107
+ """,
2108
+ (cutoff,),
2109
+ ).fetchall()
2110
+ for r in old_rows:
2111
+ mid = int(r["memory_id"])
2112
+ tags = {t.lower() for t in _split_tags(r["tags"])}
2113
+ if tags & protected:
2114
+ continue
2115
+ if not self._has_live_semantic_dependents(mid):
2116
+ self._conn.execute(
2117
+ "DELETE FROM memories WHERE memory_id = ?", (mid,)
2118
+ )
2119
+ purged.append(mid)
2120
+
2121
+ archived_count = self._count_archived()
2122
+ if archived_count > cp.max_archived_memories:
2123
+ excess = archived_count - cp.max_archived_memories
2124
+ excess_rows = self._conn.execute(
2125
+ """
2126
+ SELECT memory_id, tags FROM memories
2127
+ WHERE state = 'archived'
2128
+ ORDER BY COALESCE(archived_at, updated_at) ASC
2129
+ LIMIT ?
2130
+ """,
2131
+ (excess + 50,),
2132
+ ).fetchall()
2133
+ removed = 0
2134
+ for r in excess_rows:
2135
+ if removed >= excess:
2136
+ break
2137
+ mid = int(r["memory_id"])
2138
+ if mid in purged:
2139
+ continue
2140
+ tags = {t.lower() for t in _split_tags(r["tags"])}
2141
+ if tags & protected:
2142
+ continue
2143
+ if not self._has_live_semantic_dependents(mid):
2144
+ self._conn.execute(
2145
+ "DELETE FROM memories WHERE memory_id = ?", (mid,)
2146
+ )
2147
+ purged.append(mid)
2148
+ removed += 1
2149
+
2150
+ return purged
2151
+
2152
+ def _count_active(self) -> int:
2153
+ row = self._conn.execute(
2154
+ "SELECT COUNT(*) AS c FROM memories WHERE state = 'active'"
2155
+ ).fetchone()
2156
+ return int(row["c"])
2157
+
2158
+ def _count_archived(self) -> int:
2159
+ row = self._conn.execute(
2160
+ "SELECT COUNT(*) AS c FROM memories WHERE state = 'archived'"
2161
+ ).fetchone()
2162
+ return int(row["c"])
2163
+
2164
+ # ------------------------------------------------------------------
2165
+ # reinforcement
2166
+ # ------------------------------------------------------------------
2167
+
2168
+ def _reinforce_retrieval(self, memory_id: int) -> None:
2169
+ row = self._conn.execute(
2170
+ "SELECT * FROM memories WHERE memory_id = ?", (int(memory_id),)
2171
+ ).fetchone()
2172
+ gain = self._reinforcement_gain(row, kind="retrieval") if row else 0.08
2173
+ now = self._now()
2174
+ self._conn.execute(
2175
+ """
2176
+ UPDATE memories
2177
+ SET retrieval_count = retrieval_count + 1,
2178
+ strength = MIN(?, strength + ?),
2179
+ last_retrieved_at = ?, updated_at = ?,
2180
+ last_anchor_at = ?
2181
+ WHERE memory_id = ?
2182
+ """,
2183
+ (_MAX_STRENGTH, gain, now, now, now, int(memory_id)),
2184
+ )
2185
+ self._conn.commit()
2186
+
2187
+ # ------------------------------------------------------------------
2188
+ # dream_preview
2189
+ # ------------------------------------------------------------------
2190
+
2191
+ def dream_preview(self) -> dict:
2192
+ dp = self.policies.dreaming
2193
+ if not dp.enabled:
2194
+ return {"mode": "dream_preview", "enabled": False, "clusters": []}
2195
+
2196
+ candidates = self._conn.execute(
2197
+ """
2198
+ SELECT * FROM memories
2199
+ WHERE state = 'active' AND dream_candidate = 1
2200
+ ORDER BY COALESCE(last_anchor_at, created_at) ASC
2201
+ LIMIT ?
2202
+ """,
2203
+ (dp.candidate_limit,),
2204
+ ).fetchall()
2205
+
2206
+ if len(candidates) < dp.min_source_count:
2207
+ return {"mode": "dream_preview", "enabled": True, "clusters": []}
2208
+
2209
+ groups: dict[str, list[sqlite3.Row]] = defaultdict(list)
2210
+ for row in candidates:
2211
+ tag_list = _split_tags(row["tags"])
2212
+ source = row["source"] or ""
2213
+ session = row["session_id"] or ""
2214
+ key_parts = sorted(set(tag_list)) + [source, session]
2215
+ group_key = hashlib.sha256(
2216
+ "|".join(key_parts).encode()
2217
+ ).hexdigest()[:16]
2218
+ groups[group_key].append(row)
2219
+
2220
+ encoded_groups: dict[str, list[sqlite3.Row]] = {}
2221
+ for key, rows in groups.items():
2222
+ if len(rows) < dp.min_source_count:
2223
+ for r in rows:
2224
+ cue_set = frozenset(
2225
+ self._decode(r["encoded"]).get("cues", [])[:8]
2226
+ )
2227
+ placed = False
2228
+ for ekey, erows in encoded_groups.items():
2229
+ sample_cues = frozenset(
2230
+ self._decode(erows[0]["encoded"]).get("cues", [])[:8]
2231
+ )
2232
+ if len(cue_set & sample_cues) >= 2:
2233
+ erows.append(r)
2234
+ placed = True
2235
+ break
2236
+ if not placed:
2237
+ encoded_groups.setdefault(key, []).append(r)
2238
+ else:
2239
+ encoded_groups[key] = rows
2240
+
2241
+ clusters: list[dict] = []
2242
+ now = self._now()
2243
+ stamp = datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y%m%d")
2244
+ for _key, rows in sorted(
2245
+ encoded_groups.items(), key=lambda t: -len(t[1])
2246
+ ):
2247
+ if len(rows) < dp.min_source_count:
2248
+ continue
2249
+ if len(clusters) >= dp.max_clusters:
2250
+ break
2251
+ # Skip forced merge of strongly conflicting valence polarities.
2252
+ valences = [float(r["valence"] or 0.0) for r in rows]
2253
+ if max(valences) - min(valences) > 1.2:
2254
+ continue
2255
+ cluster_id = f"dream_{stamp}_{len(clusters) + 1:03d}"
2256
+ source_ids = [int(r["memory_id"]) for r in rows]
2257
+ themes = sorted({tag for r in rows for tag in _split_tags(r["tags"])})[:10]
2258
+ contains_neg = any(
2259
+ float(r["valence"] or 0.0) <= self.policies.sleep.negative_valence_threshold
2260
+ for r in rows
2261
+ )
2262
+ payload = {
2263
+ "cluster_id": cluster_id,
2264
+ "source_memory_ids": source_ids,
2265
+ "source_ids": source_ids,
2266
+ "themes": themes,
2267
+ "suggested_kind": "semantic_lesson",
2268
+ "contains_strong_negative_valence": contains_neg,
2269
+ "llm_output_schema": {
2270
+ "cluster_id": cluster_id,
2271
+ "source_memory_ids": source_ids,
2272
+ "summary": "reusable lesson only",
2273
+ "tags": ["dream-summary", "semantic"],
2274
+ "salience": 0.7,
2275
+ "valence": 0.0,
2276
+ },
2277
+ }
2278
+ # Persist preview ledger so apply works after process restart.
2279
+ # Memories table itself remains unchanged by preview.
2280
+ self._persist_preview(cluster_id, payload, now=now)
2281
+ clusters.append(payload)
2282
+
2283
+ if clusters:
2284
+ self._conn.commit()
2285
+ return {"mode": "dream_preview", "enabled": True, "clusters": clusters}
2286
+
2287
+ def _find_semantic_by_source_set(self, source_ids: Sequence[int]) -> int | None:
2288
+ wanted = sorted({int(x) for x in source_ids})
2289
+ if not wanted:
2290
+ return None
2291
+ rows = self._conn.execute(
2292
+ """
2293
+ SELECT semantic_memory_id, GROUP_CONCAT(source_memory_id) AS sources
2294
+ FROM memory_provenance
2295
+ GROUP BY semantic_memory_id
2296
+ """
2297
+ ).fetchall()
2298
+ for row in rows:
2299
+ raw = str(row["sources"] or "")
2300
+ have = sorted(int(part) for part in raw.split(",") if part.strip())
2301
+ if have == wanted:
2302
+ return int(row["semantic_memory_id"])
2303
+ return None
2304
+
2305
+ def dream_apply(self, dreams: list[dict] | None) -> dict:
2306
+ dp = self.policies.dreaming
2307
+ if not dp.enabled:
2308
+ return {"mode": "dream_apply", "enabled": False, "applied": []}
2309
+ if not dreams:
2310
+ raise ValueError("dreams array is required for apply")
2311
+
2312
+ results: list[dict] = []
2313
+ now = self._now()
2314
+ self._conn.execute("BEGIN")
2315
+ try:
2316
+ for dream in dreams:
2317
+ cluster_id = str(dream.get("cluster_id", ""))
2318
+ if not cluster_id or len(cluster_id) > 128 or "\x00" in cluster_id:
2319
+ raise ValueError("invalid dream cluster_id")
2320
+ content = _normalize_text(
2321
+ str(dream.get("summary") or dream.get("content") or "")
2322
+ )
2323
+ if "\x00" in content:
2324
+ raise ValueError("dream summary must not contain NUL bytes")
2325
+ tags = _split_tags(dream.get("tags") or ["dream-summary", "semantic"])
2326
+ if "dream-summary" not in tags:
2327
+ tags.append("dream-summary")
2328
+ if "semantic" not in tags:
2329
+ tags.append("semantic")
2330
+ salience = _clamp(float(dream.get("salience", 0.6)), 0.05, 1.0)
2331
+ valence = _clamp(float(dream.get("valence", 0.0)), -1.0, 1.0)
2332
+
2333
+ if not content or len(content) < 8:
2334
+ raise ValueError(f"invalid dream summary for cluster {cluster_id!r}")
2335
+
2336
+ preview = self._load_preview(cluster_id)
2337
+ provided_raw = dream.get("source_memory_ids") or dream.get("source_ids") or []
2338
+
2339
+ # Idempotency first: same content OR same source-set already consolidated.
2340
+ # This path stays valid even after the durable preview row is dropped.
2341
+ early_source_ids = (
2342
+ _as_positive_int_ids(provided_raw) if provided_raw else []
2343
+ )
2344
+ existing = self._conn.execute(
2345
+ """
2346
+ SELECT memory_id FROM memories
2347
+ WHERE content = ? AND memory_type = 'semantic'
2348
+ """,
2349
+ (content,),
2350
+ ).fetchone()
2351
+ by_sources = (
2352
+ self._find_semantic_by_source_set(early_source_ids)
2353
+ if early_source_ids
2354
+ else None
2355
+ )
2356
+ if existing or by_sources is not None:
2357
+ semantic_id = int(
2358
+ existing["memory_id"] if existing else by_sources # type: ignore[index]
2359
+ )
2360
+ provenance_rows = self._conn.execute(
2361
+ "SELECT source_memory_id, relation, created_at "
2362
+ "FROM memory_provenance WHERE semantic_memory_id = ? "
2363
+ "ORDER BY source_memory_id",
2364
+ (semantic_id,),
2365
+ ).fetchall()
2366
+ source_ids = [
2367
+ int(row["source_memory_id"]) for row in provenance_rows
2368
+ ]
2369
+ applied_at = max(
2370
+ (float(row["created_at"]) for row in provenance_rows),
2371
+ default=now,
2372
+ )
2373
+ results.append({
2374
+ "cluster_id": cluster_id,
2375
+ "status": "idempotent",
2376
+ "semantic_memory_id": semantic_id,
2377
+ "archived_sources": [],
2378
+ "source_memory_ids": source_ids,
2379
+ "provenance": [
2380
+ {
2381
+ "source_memory_id": int(row["source_memory_id"]),
2382
+ "relation": str(row["relation"]),
2383
+ }
2384
+ for row in provenance_rows
2385
+ ],
2386
+ "applied_at": applied_at,
2387
+ "validation_state": "apply_validated",
2388
+ "idempotency_key": _dream_idempotency_key(source_ids),
2389
+ })
2390
+ continue
2391
+
2392
+ if preview is None:
2393
+ raise ValueError(f"unknown dream preview cluster_id: {cluster_id}")
2394
+
2395
+ expected_ids = _as_positive_int_ids(
2396
+ preview.get("source_memory_ids")
2397
+ or preview.get("source_ids")
2398
+ or []
2399
+ )
2400
+ provided_ids = (
2401
+ _as_positive_int_ids(provided_raw) if provided_raw else list(expected_ids)
2402
+ )
2403
+ if sorted(provided_ids) != sorted(expected_ids):
2404
+ raise ValueError(f"source_memory_ids do not match preview for {cluster_id}")
2405
+
2406
+ source_ids = expected_ids
2407
+ source_rows = self._conn.execute(
2408
+ f"SELECT * FROM memories WHERE memory_id IN ({_placeholders(len(source_ids))})",
2409
+ source_ids,
2410
+ ).fetchall()
2411
+ if len(source_rows) != len(source_ids):
2412
+ raise ValueError(f"missing source memories for {cluster_id}")
2413
+
2414
+ max_source_salience = max(
2415
+ (float(r["salience"] or 0.0) for r in source_rows),
2416
+ default=0.5,
2417
+ )
2418
+ if salience > max_source_salience + 0.15:
2419
+ raise ValueError(
2420
+ f"salience {salience} exceeds source max {max_source_salience} + 0.15"
2421
+ )
2422
+
2423
+ if preview.get("contains_strong_negative_valence") and valence < dp.negative_summary_max_valence:
2424
+ valence = dp.negative_summary_max_valence
2425
+
2426
+ encoded = _encode_memory(content, tags)
2427
+ cur = self._conn.execute(
2428
+ """
2429
+ INSERT INTO memories (
2430
+ content, encoded, cues, tags, salience, valence,
2431
+ strength, source, session_id, created_at, updated_at,
2432
+ last_rehearsed_at, state, last_anchor_at, memory_type
2433
+ )
2434
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, 'semantic')
2435
+ """,
2436
+ (
2437
+ content,
2438
+ json.dumps(encoded, ensure_ascii=False),
2439
+ " ".join(encoded["cues"]),
2440
+ _join_tags(tags),
2441
+ salience,
2442
+ valence,
2443
+ 1.0 + salience,
2444
+ f"dream:{cluster_id}",
2445
+ "",
2446
+ now,
2447
+ now,
2448
+ now,
2449
+ now,
2450
+ ),
2451
+ )
2452
+ semantic_id = int(cur.lastrowid)
2453
+ for sid in source_ids:
2454
+ self._conn.execute(
2455
+ """
2456
+ INSERT OR IGNORE INTO memory_provenance
2457
+ (semantic_memory_id, source_memory_id, relation, created_at)
2458
+ VALUES (?, ?, 'dream-derived', ?)
2459
+ """,
2460
+ (semantic_id, sid, now),
2461
+ )
2462
+ archived_sources: list[int] = []
2463
+ if dp.archive_sources_after_apply:
2464
+ for sid in source_ids:
2465
+ self._archive_memory(sid, reason="dream-consolidated", now=now)
2466
+ archived_sources.append(sid)
2467
+ results.append({
2468
+ "cluster_id": cluster_id,
2469
+ "status": "applied",
2470
+ "semantic_memory_id": semantic_id,
2471
+ "archived_sources": archived_sources,
2472
+ "source_memory_ids": source_ids,
2473
+ "provenance": [
2474
+ {
2475
+ "source_memory_id": sid,
2476
+ "relation": "dream-derived",
2477
+ }
2478
+ for sid in source_ids
2479
+ ],
2480
+ "applied_at": now,
2481
+ "validation_state": "apply_validated",
2482
+ "idempotency_key": _dream_idempotency_key(source_ids),
2483
+ })
2484
+ # Drop durable preview after successful apply (idempotent re-apply
2485
+ # still works via content / source-set provenance checks).
2486
+ self._drop_preview(cluster_id)
2487
+ self._conn.execute("COMMIT")
2488
+ except Exception:
2489
+ self._conn.execute("ROLLBACK")
2490
+ raise
2491
+ return {"mode": "dream_apply", "enabled": True, "applied": results}
2492
+
2493
+ def list_memories(
2494
+ self,
2495
+ *,
2496
+ limit: int = 20,
2497
+ state: str | None = None,
2498
+ include_archived: bool = False,
2499
+ ) -> list[dict]:
2500
+ if state:
2501
+ state_key = str(state).strip().lower()
2502
+ if state_key not in _ALLOWED_MEMORY_STATES:
2503
+ raise ValueError(
2504
+ f"state must be one of {sorted(_ALLOWED_MEMORY_STATES)}, got {state!r}"
2505
+ )
2506
+ rows = self._conn.execute(
2507
+ "SELECT * FROM memories WHERE state = ? ORDER BY updated_at DESC LIMIT ?",
2508
+ (state_key, max(1, int(limit))),
2509
+ ).fetchall()
2510
+ elif include_archived:
2511
+ rows = self._conn.execute(
2512
+ "SELECT * FROM memories ORDER BY updated_at DESC LIMIT ?",
2513
+ (max(1, int(limit)),),
2514
+ ).fetchall()
2515
+ else:
2516
+ rows = self._conn.execute(
2517
+ """
2518
+ SELECT * FROM memories WHERE state = 'active'
2519
+ ORDER BY updated_at DESC LIMIT ?
2520
+ """,
2521
+ (max(1, int(limit)),),
2522
+ ).fetchall()
2523
+ return [self._row_to_result(row, query_score=None) for row in rows]
2524
+
2525
+ def list_events(
2526
+ self,
2527
+ *,
2528
+ event_type: str = "",
2529
+ memory_id: int | None = None,
2530
+ limit: int = 20,
2531
+ ) -> list[dict[str, Any]]:
2532
+ clauses: list[str] = []
2533
+ params: list[Any] = []
2534
+ if event_type:
2535
+ clauses.append("event_type = ?")
2536
+ params.append(str(event_type))
2537
+ if memory_id is not None:
2538
+ clauses.append("memory_id = ?")
2539
+ params.append(int(memory_id))
2540
+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
2541
+ rows = self._conn.execute(
2542
+ f"""
2543
+ SELECT event_id, event_type, memory_id, related_memory_id, belief_id,
2544
+ session_id, payload, created_at
2545
+ FROM memory_events
2546
+ {where}
2547
+ ORDER BY created_at DESC, event_id DESC
2548
+ LIMIT ?
2549
+ """,
2550
+ (*params, max(1, int(limit))),
2551
+ ).fetchall()
2552
+ out: list[dict[str, Any]] = []
2553
+ for row in rows:
2554
+ try:
2555
+ payload = json.loads(row["payload"] or "{}")
2556
+ except (TypeError, ValueError, json.JSONDecodeError):
2557
+ payload = {}
2558
+ out.append(
2559
+ {
2560
+ "event_id": int(row["event_id"]),
2561
+ "event_type": str(row["event_type"] or ""),
2562
+ "memory_id": row["memory_id"],
2563
+ "related_memory_id": row["related_memory_id"],
2564
+ "belief_id": str(row["belief_id"] or ""),
2565
+ "session_id": str(row["session_id"] or ""),
2566
+ "payload": payload,
2567
+ "created_at": float(row["created_at"] or 0.0),
2568
+ }
2569
+ )
2570
+ return out
2571
+
2572
+ def stats(self) -> dict:
2573
+ active_row = self._conn.execute(
2574
+ """
2575
+ SELECT COUNT(*) AS count,
2576
+ COALESCE(AVG(salience), 0) AS avg_salience,
2577
+ COALESCE(AVG(valence), 0) AS avg_valence,
2578
+ COALESCE(SUM(rehearsal_count), 0) AS rehearsals,
2579
+ COALESCE(SUM(retrieval_count), 0) AS retrievals,
2580
+ COALESCE(SUM(sleep_rehearsal_count), 0) AS sleep_rehearsals
2581
+ FROM memories WHERE state = 'active'
2582
+ """
2583
+ ).fetchone()
2584
+
2585
+ archived_row = self._conn.execute(
2586
+ "SELECT COUNT(*) AS count FROM memories WHERE state = 'archived'"
2587
+ ).fetchone()
2588
+ total_row = self._conn.execute(
2589
+ "SELECT COUNT(*) AS count FROM memories"
2590
+ ).fetchone()
2591
+ episodic_row = self._conn.execute(
2592
+ "SELECT COUNT(*) AS count FROM memories WHERE memory_type = 'episodic'"
2593
+ ).fetchone()
2594
+ semantic_row = self._conn.execute(
2595
+ "SELECT COUNT(*) AS count FROM memories WHERE memory_type = 'semantic'"
2596
+ ).fetchone()
2597
+ dream_row = self._conn.execute(
2598
+ "SELECT COUNT(*) AS count FROM memories WHERE dream_candidate = 1 AND state = 'active'"
2599
+ ).fetchone()
2600
+
2601
+ active_rows = self._conn.execute(
2602
+ "SELECT * FROM memories WHERE state = 'active'"
2603
+ ).fetchall()
2604
+ retained = sum(
2605
+ 1 for row in active_rows if self._retention(row) > self.decay_threshold
2606
+ )
2607
+ protected_count = sum(1 for row in active_rows if self._is_row_protected(row))
2608
+ negative_active = sum(
2609
+ 1
2610
+ for row in active_rows
2611
+ if float(row["valence"] or 0.0) <= self.policies.sleep.negative_valence_threshold
2612
+ )
2613
+ active_count = int(active_row["count"])
2614
+ capacity_blocked = (
2615
+ active_count >= self.policies.capacity.max_active_memories
2616
+ and protected_count >= self.policies.capacity.max_active_memories
2617
+ )
2618
+ warning = None
2619
+ if active_count and protected_count / max(1, active_count) > 0.10:
2620
+ warning = "protected memories exceed 10% of active store"
2621
+
2622
+ now = self._now()
2623
+ oldest_active_age_days = 0.0
2624
+ if active_rows:
2625
+ oldest_created = min(
2626
+ _timestamp_value(row["created_at"], default=now) for row in active_rows
2627
+ )
2628
+ oldest_active_age_days = max(0.0, (now - oldest_created) / 86400.0)
2629
+ archived_rows = self._conn.execute(
2630
+ "SELECT archived_at, created_at FROM memories WHERE state = 'archived'"
2631
+ ).fetchall()
2632
+ oldest_archived_age_days = 0.0
2633
+ if archived_rows:
2634
+ oldest_arch = min(
2635
+ _timestamp_value(row["archived_at"])
2636
+ or _timestamp_value(row["created_at"], default=now)
2637
+ for row in archived_rows
2638
+ )
2639
+ oldest_archived_age_days = max(0.0, (now - oldest_arch) / 86400.0)
2640
+
2641
+ sleep_rehearsals = int(active_row["sleep_rehearsals"])
2642
+ negative_rehearsal_ratio = (
2643
+ round(negative_active / max(1, active_count), 4) if active_count else 0.0
2644
+ )
2645
+ return {
2646
+ "count": int(total_row["count"]),
2647
+ "active_count": active_count,
2648
+ "archived_count": int(archived_row["count"]),
2649
+ "episodic_count": int(episodic_row["count"]),
2650
+ "semantic_count": int(semantic_row["count"]),
2651
+ "protected_count": protected_count,
2652
+ "negative_active_count": negative_active,
2653
+ "dream_candidate_count": int(dream_row["count"]),
2654
+ "retained_count": retained,
2655
+ "avg_salience": round(float(active_row["avg_salience"]), 3),
2656
+ "avg_valence": round(float(active_row["avg_valence"]), 3),
2657
+ "rehearsal_count": int(active_row["rehearsals"]),
2658
+ "retrieval_count": int(active_row["retrievals"]),
2659
+ "sleep_rehearsal_count": sleep_rehearsals,
2660
+ "negative_rehearsal_ratio": negative_rehearsal_ratio,
2661
+ "negative_prefetch_suppressed_count": int(
2662
+ self._negative_prefetch_suppressed_count
2663
+ ),
2664
+ "oldest_active_age_days": round(oldest_active_age_days, 3),
2665
+ "oldest_archived_age_days": round(oldest_archived_age_days, 3),
2666
+ "decay_threshold": self.decay_threshold,
2667
+ "base_stability_days": self.base_stability_days,
2668
+ "max_active_memories": self.policies.capacity.max_active_memories,
2669
+ "max_archived_memories": self.policies.capacity.max_archived_memories,
2670
+ "capacity_blocked": capacity_blocked,
2671
+ "warning": warning,
2672
+ "db_path": str(self.db_path),
2673
+ "dreaming_enabled": self.policies.dreaming.enabled,
2674
+ **self._experience_stats(),
2675
+ }
2676
+
2677
+ def _experience_stats(self) -> dict[str, Any]:
2678
+ if not self.policies.experience.enabled:
2679
+ return {"experience_enabled": False}
2680
+ latent = self._conn.execute(
2681
+ "SELECT COUNT(*) AS c FROM memories WHERE access_state = 'latent'"
2682
+ ).fetchone()["c"]
2683
+ reactivated = self._conn.execute(
2684
+ "SELECT COUNT(*) AS c FROM memories WHERE access_state = 'reactivated'"
2685
+ ).fetchone()["c"]
2686
+ unresolved_miss = self._conn.execute(
2687
+ """
2688
+ SELECT COUNT(*) AS c FROM retrieval_attempts
2689
+ WHERE outcome = 'miss' AND resolved_at IS NULL
2690
+ """
2691
+ ).fetchone()["c"]
2692
+ completed = self._conn.execute(
2693
+ """
2694
+ SELECT COUNT(*) AS c FROM correction_rehearsals
2695
+ WHERE status IN ('passed', 'failed')
2696
+ """
2697
+ ).fetchone()["c"]
2698
+ failed = self._conn.execute(
2699
+ "SELECT COUNT(*) AS c FROM correction_rehearsals WHERE status = 'failed'"
2700
+ ).fetchone()["c"]
2701
+ candidates = self._conn.execute(
2702
+ "SELECT COUNT(*) AS c FROM insight_candidates WHERE status = 'candidate'"
2703
+ ).fetchone()["c"]
2704
+ validated = self._conn.execute(
2705
+ "SELECT COUNT(*) AS c FROM insight_candidates WHERE status = 'validated'"
2706
+ ).fetchone()["c"]
2707
+ rejected = self._conn.execute(
2708
+ "SELECT COUNT(*) AS c FROM insight_candidates WHERE status = 'rejected'"
2709
+ ).fetchone()["c"]
2710
+ return {
2711
+ "experience_enabled": True,
2712
+ "latent_count": int(latent),
2713
+ "reactivated_count": int(reactivated),
2714
+ "unresolved_miss_count": int(unresolved_miss),
2715
+ "correction_rehearsal_completed_count": int(completed),
2716
+ "correction_rehearsal_failed_count": int(failed),
2717
+ "corrected_error_recurrence_rate": round(
2718
+ float(failed) / max(1, int(completed)), 4
2719
+ ),
2720
+ "insight_candidate_count": int(candidates),
2721
+ "insight_validated_count": int(validated),
2722
+ "insight_rejected_count": int(rejected),
2723
+ }
2724
+
2725
+
2726
+ # ---------------------------------------------------------------------------
2727
+ # Public exports
2728
+ # ---------------------------------------------------------------------------
2729
+
2730
+ __all__ = [
2731
+ "forgetting_retention",
2732
+ "EbbinghausMemoryStore",
2733
+ "CapacityError",
2734
+ "_assert_safe_identifier",
2735
+ "_placeholders",
2736
+ ]