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,1488 @@
1
+ """Experiential ledger for Ebbinghaus retrieval misses, events, and later AGIASI flows.
2
+
3
+ This module owns event / retrieval-attempt writes. It does not call the store's
4
+ public ``remember`` / ``recall`` APIs from inside transactions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import logging
12
+ import math
13
+ import sqlite3
14
+ import threading
15
+ import uuid
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from typing import Any
18
+
19
+ from .models import (
20
+ InsightStatus,
21
+ InsightValidationResult,
22
+ RevisionResult,
23
+ )
24
+ from .policies import EbbinghausPolicies
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _MAX_EVENT_FIELD_CHARS = 4000
29
+ _MAX_EVENT_PAYLOAD_CHARS = 32000
30
+ _PREDICTION_ERROR_SOURCES = frozenset(
31
+ {
32
+ "user_correction",
33
+ "explicit_contradiction",
34
+ "tool_result",
35
+ "expected_observed_mismatch",
36
+ "high_surprise_latent_rescue",
37
+ "new_time_qualified_evidence",
38
+ "validation_failure",
39
+ }
40
+ )
41
+ _STABILIZATION_EVIDENCE_TYPES = frozenset(
42
+ {
43
+ "user_confirmation",
44
+ "unit_test",
45
+ "integration_test",
46
+ "trusted_tool_result",
47
+ "external_source_validation",
48
+ "correction_rehearsal_pass",
49
+ "manual_validation",
50
+ }
51
+ )
52
+
53
+
54
+ def normalize_query_hash(query: str) -> str:
55
+ return hashlib.sha256(query.encode("utf-8")).hexdigest()
56
+
57
+
58
+ def _validated_sha256(value: str, *, name: str) -> str:
59
+ digest = str(value or "").strip().lower()
60
+ if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest):
61
+ raise ValueError(f"{name} must be a SHA-256 hex digest")
62
+ return digest
63
+
64
+
65
+ def _safe_json_payload(payload: Mapping[str, Any] | None) -> str:
66
+ data = dict(payload or {})
67
+ # Never persist opaque model scratch / chain-of-thought keys.
68
+ blocked = {
69
+ "chain_of_thought",
70
+ "thinking",
71
+ "reasoning",
72
+ "scratchpad",
73
+ "hidden_state",
74
+ "raw_logits",
75
+ }
76
+ cleaned: dict[str, Any] = {}
77
+ for key, value in data.items():
78
+ key_text = str(key)
79
+ if key_text.lower() in blocked:
80
+ continue
81
+ if isinstance(value, str) and len(value) > _MAX_EVENT_FIELD_CHARS:
82
+ value = value[:_MAX_EVENT_FIELD_CHARS]
83
+ cleaned[key_text] = value
84
+ encoded = json.dumps(cleaned, ensure_ascii=False, default=str)
85
+ if len(encoded) > _MAX_EVENT_PAYLOAD_CHARS:
86
+ encoded = json.dumps(
87
+ {"truncated": True, "keys": sorted(cleaned.keys())[:32]},
88
+ ensure_ascii=False,
89
+ )
90
+ return encoded
91
+
92
+
93
+ class EbbinghausExperienceLedger:
94
+ """Append-only experiential events and retrieval-attempt bookkeeping."""
95
+
96
+ def __init__(
97
+ self,
98
+ conn: sqlite3.Connection,
99
+ *,
100
+ now_fn: Callable[[], float],
101
+ policies: EbbinghausPolicies,
102
+ lock: threading.RLock,
103
+ ) -> None:
104
+ self._conn = conn
105
+ self._now_fn = now_fn
106
+ self.policies = policies
107
+ self._lock = lock
108
+
109
+ def record_event(
110
+ self,
111
+ event_type: str,
112
+ *,
113
+ memory_id: int | None = None,
114
+ related_memory_id: int | None = None,
115
+ belief_id: str = "",
116
+ session_id: str = "",
117
+ payload: Mapping[str, Any] | None = None,
118
+ ) -> int:
119
+ with self._lock:
120
+ cur = self._conn.execute(
121
+ """
122
+ INSERT INTO memory_events(
123
+ event_type, memory_id, related_memory_id, belief_id,
124
+ session_id, payload, created_at
125
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
126
+ """,
127
+ (
128
+ str(event_type),
129
+ memory_id,
130
+ related_memory_id,
131
+ str(belief_id or ""),
132
+ str(session_id or ""),
133
+ _safe_json_payload(payload),
134
+ float(self._now_fn()),
135
+ ),
136
+ )
137
+ self._conn.commit()
138
+ return int(cur.lastrowid)
139
+
140
+ def record_prediction_error(
141
+ self,
142
+ *,
143
+ memory_id: int,
144
+ source: str,
145
+ expected_hash: str,
146
+ observed_hash: str,
147
+ severity: float,
148
+ requires_revision: bool,
149
+ session_id: str = "",
150
+ ) -> dict[str, Any]:
151
+ source_key = str(source or "").strip().lower()
152
+ if source_key not in _PREDICTION_ERROR_SOURCES:
153
+ raise ValueError(
154
+ "prediction error source must be one of "
155
+ f"{sorted(_PREDICTION_ERROR_SOURCES)}"
156
+ )
157
+ expected = _validated_sha256(expected_hash, name="expected_hash")
158
+ observed = _validated_sha256(observed_hash, name="observed_hash")
159
+ if expected == observed:
160
+ raise ValueError("expected_hash and observed_hash must differ")
161
+ severity_value = float(severity)
162
+ if not math.isfinite(severity_value) or not 0.0 <= severity_value <= 1.0:
163
+ raise ValueError("severity must be between 0 and 1")
164
+
165
+ with self._lock:
166
+ self._conn.execute("BEGIN IMMEDIATE")
167
+ try:
168
+ row = self._conn.execute(
169
+ "SELECT memory_id, belief_id, belief_status, state, access_state "
170
+ "FROM memories WHERE memory_id = ?",
171
+ (int(memory_id),),
172
+ ).fetchone()
173
+ if row is None:
174
+ raise ValueError(f"memory_id {memory_id} not found")
175
+ if str(row["belief_status"] or "current") != "current":
176
+ raise ValueError("prediction error requires the current belief version")
177
+ if str(row["state"] or "active") != "active":
178
+ raise ValueError("prediction error requires an active belief")
179
+ now = float(self._now_fn())
180
+ self._conn.execute(
181
+ "UPDATE memories SET access_state = 'labile', updated_at = ? "
182
+ "WHERE memory_id = ?",
183
+ (now, int(memory_id)),
184
+ )
185
+ payload = {
186
+ "source": source_key,
187
+ "expected_hash": expected,
188
+ "observed_hash": observed,
189
+ "severity": severity_value,
190
+ "requires_revision": bool(requires_revision),
191
+ }
192
+ cur = self._conn.execute(
193
+ """
194
+ INSERT INTO memory_events(
195
+ event_type, memory_id, related_memory_id, belief_id,
196
+ session_id, payload, created_at
197
+ ) VALUES ('prediction_error', ?, NULL, ?, ?, ?, ?)
198
+ """,
199
+ (
200
+ int(memory_id),
201
+ str(row["belief_id"] or f"memory-{int(memory_id)}"),
202
+ str(session_id or ""),
203
+ _safe_json_payload(payload),
204
+ now,
205
+ ),
206
+ )
207
+ event_id = int(cur.lastrowid)
208
+ self._conn.execute("COMMIT")
209
+ except Exception:
210
+ self._conn.execute("ROLLBACK")
211
+ raise
212
+ return {
213
+ "status": "labile",
214
+ "event_id": event_id,
215
+ "memory_id": int(memory_id),
216
+ **payload,
217
+ }
218
+
219
+ def stabilize_memory(
220
+ self,
221
+ *,
222
+ memory_id: int,
223
+ evidence_type: str,
224
+ evidence_hash: str,
225
+ session_id: str = "",
226
+ ) -> dict[str, Any]:
227
+ evidence_key = str(evidence_type or "").strip().lower()
228
+ if evidence_key not in _STABILIZATION_EVIDENCE_TYPES:
229
+ raise ValueError(
230
+ "stabilization evidence type must be one of "
231
+ f"{sorted(_STABILIZATION_EVIDENCE_TYPES)}"
232
+ )
233
+ digest = _validated_sha256(evidence_hash, name="evidence_hash")
234
+ with self._lock:
235
+ self._conn.execute("BEGIN IMMEDIATE")
236
+ try:
237
+ row = self._conn.execute(
238
+ "SELECT belief_id, belief_status, state, access_state "
239
+ "FROM memories WHERE memory_id = ?",
240
+ (int(memory_id),),
241
+ ).fetchone()
242
+ if row is None:
243
+ raise ValueError(f"memory_id {memory_id} not found")
244
+ if (
245
+ str(row["belief_status"] or "current") != "current"
246
+ or str(row["state"] or "active") != "active"
247
+ ):
248
+ raise ValueError("only an active current belief can be stabilized")
249
+ if str(row["access_state"] or "accessible") != "labile":
250
+ raise ValueError("memory must be labile before stabilization")
251
+ now = float(self._now_fn())
252
+ self._conn.execute(
253
+ "UPDATE memories SET access_state = 'accessible', updated_at = ? "
254
+ "WHERE memory_id = ?",
255
+ (now, int(memory_id)),
256
+ )
257
+ payload = {
258
+ "evidence_type": evidence_key,
259
+ "evidence_hash": digest,
260
+ }
261
+ cur = self._conn.execute(
262
+ """
263
+ INSERT INTO memory_events(
264
+ event_type, memory_id, related_memory_id, belief_id,
265
+ session_id, payload, created_at
266
+ ) VALUES ('memory_stabilized', ?, NULL, ?, ?, ?, ?)
267
+ """,
268
+ (
269
+ int(memory_id),
270
+ str(row["belief_id"] or f"memory-{int(memory_id)}"),
271
+ str(session_id or ""),
272
+ _safe_json_payload(payload),
273
+ now,
274
+ ),
275
+ )
276
+ event_id = int(cur.lastrowid)
277
+ self._conn.execute("COMMIT")
278
+ except Exception:
279
+ self._conn.execute("ROLLBACK")
280
+ raise
281
+ return {
282
+ "status": "stabilized",
283
+ "event_id": event_id,
284
+ "memory_id": int(memory_id),
285
+ **payload,
286
+ }
287
+
288
+ def record_retrieval_miss(
289
+ self,
290
+ *,
291
+ query_hash: str,
292
+ query_excerpt: str,
293
+ query_cues: Sequence[str],
294
+ direct_best_score: float,
295
+ session_id: str = "",
296
+ ) -> int:
297
+ with self._lock:
298
+ self._trim_unresolved_misses_locked()
299
+ cur = self._conn.execute(
300
+ """
301
+ INSERT INTO retrieval_attempts(
302
+ query_hash, query_excerpt, query_cues, outcome,
303
+ top_memory_id, matched_miss_id, result_memory_ids,
304
+ direct_best_score, rescue_score, surprise,
305
+ resolved_at, created_at
306
+ ) VALUES (?, ?, ?, 'miss', NULL, NULL, '[]', ?, 0.0, 0.0, NULL, ?)
307
+ """,
308
+ (
309
+ str(query_hash),
310
+ str(query_excerpt or ""),
311
+ json.dumps(list(query_cues), ensure_ascii=False),
312
+ float(direct_best_score),
313
+ float(self._now_fn()),
314
+ ),
315
+ )
316
+ attempt_id = int(cur.lastrowid)
317
+ self._conn.execute(
318
+ """
319
+ INSERT INTO memory_events(
320
+ event_type, memory_id, related_memory_id, belief_id,
321
+ session_id, payload, created_at
322
+ ) VALUES ('retrieval_miss', NULL, NULL, '', ?, ?, ?)
323
+ """,
324
+ (
325
+ str(session_id or ""),
326
+ _safe_json_payload(
327
+ {
328
+ "attempt_id": attempt_id,
329
+ "query_hash": query_hash,
330
+ "direct_best_score": float(direct_best_score),
331
+ "cue_count": len(list(query_cues)),
332
+ }
333
+ ),
334
+ float(self._now_fn()),
335
+ ),
336
+ )
337
+ self._conn.commit()
338
+ return attempt_id
339
+
340
+ def resolve_retrieval_miss(
341
+ self,
342
+ *,
343
+ current_query_hash: str,
344
+ current_cues: Sequence[str],
345
+ rescued_memory_id: int,
346
+ rescue_score: float,
347
+ direct_best_score: float,
348
+ session_id: str = "",
349
+ current_attempt_id: int | None = None,
350
+ ) -> dict[str, Any] | None:
351
+ current_cue_set = {str(c).strip().lower() for c in current_cues if str(c).strip()}
352
+ cutoff = float(self._now_fn()) - (
353
+ float(self.policies.experience.miss_resolution_days) * 86400.0
354
+ )
355
+ with self._lock:
356
+ rows = self._conn.execute(
357
+ """
358
+ SELECT attempt_id, query_hash, query_cues, created_at
359
+ FROM retrieval_attempts
360
+ WHERE outcome = 'miss'
361
+ AND resolved_at IS NULL
362
+ AND created_at >= ?
363
+ ORDER BY created_at DESC
364
+ """,
365
+ (cutoff,),
366
+ ).fetchall()
367
+ best: tuple[int, float, float, int] | None = None
368
+ for row in rows:
369
+ attempt_id = int(row["attempt_id"] if isinstance(row, sqlite3.Row) else row[0])
370
+ old_hash = str(row["query_hash"] if isinstance(row, sqlite3.Row) else row[1])
371
+ raw_cues = row["query_cues"] if isinstance(row, sqlite3.Row) else row[2]
372
+ created_at = float(row["created_at"] if isinstance(row, sqlite3.Row) else row[3])
373
+ try:
374
+ old_cues = {str(c).strip().lower() for c in json.loads(raw_cues or "[]")}
375
+ except (TypeError, ValueError, json.JSONDecodeError):
376
+ old_cues = set()
377
+ same_hash = old_hash == str(current_query_hash)
378
+ union = current_cue_set | old_cues
379
+ overlap = (
380
+ len(current_cue_set & old_cues) / max(1, len(union))
381
+ if union
382
+ else 0.0
383
+ )
384
+ if not (same_hash or overlap >= 0.45):
385
+ continue
386
+ prior_context = int(
387
+ current_attempt_id is not None
388
+ and attempt_id != int(current_attempt_id)
389
+ )
390
+ rank = (
391
+ prior_context,
392
+ overlap if not same_hash else 1.0,
393
+ created_at,
394
+ attempt_id,
395
+ )
396
+ if best is None or rank > best:
397
+ best = rank
398
+ if best is None:
399
+ return None
400
+ attempt_id = best[3]
401
+ resolution_gain = max(0.0, float(rescue_score) - float(direct_best_score))
402
+ surprise = max(0.0, min(1.0, resolution_gain))
403
+ now = float(self._now_fn())
404
+ self._conn.execute(
405
+ """
406
+ UPDATE retrieval_attempts
407
+ SET outcome = 'rescued',
408
+ matched_miss_id = attempt_id,
409
+ top_memory_id = ?,
410
+ result_memory_ids = ?,
411
+ rescue_score = ?,
412
+ surprise = ?,
413
+ resolved_at = ?
414
+ WHERE attempt_id = ?
415
+ """,
416
+ (
417
+ int(rescued_memory_id),
418
+ json.dumps([int(rescued_memory_id)], ensure_ascii=False),
419
+ float(rescue_score),
420
+ float(surprise),
421
+ now,
422
+ attempt_id,
423
+ ),
424
+ )
425
+ if (
426
+ current_attempt_id is not None
427
+ and int(current_attempt_id) != attempt_id
428
+ ):
429
+ self._conn.execute(
430
+ """
431
+ UPDATE retrieval_attempts
432
+ SET outcome = 'rescued',
433
+ matched_miss_id = ?,
434
+ top_memory_id = ?,
435
+ result_memory_ids = ?,
436
+ rescue_score = ?,
437
+ surprise = ?,
438
+ resolved_at = ?
439
+ WHERE attempt_id = ?
440
+ """,
441
+ (
442
+ attempt_id,
443
+ int(rescued_memory_id),
444
+ json.dumps([int(rescued_memory_id)], ensure_ascii=False),
445
+ float(rescue_score),
446
+ float(surprise),
447
+ now,
448
+ int(current_attempt_id),
449
+ ),
450
+ )
451
+ self._conn.execute(
452
+ """
453
+ INSERT INTO memory_events(
454
+ event_type, memory_id, related_memory_id, belief_id,
455
+ session_id, payload, created_at
456
+ ) VALUES ('retrieval_rescued', ?, NULL, '', ?, ?, ?)
457
+ """,
458
+ (
459
+ int(rescued_memory_id),
460
+ str(session_id or ""),
461
+ _safe_json_payload(
462
+ {
463
+ "attempt_id": attempt_id,
464
+ "rescue_score": float(rescue_score),
465
+ "surprise": float(surprise),
466
+ }
467
+ ),
468
+ now,
469
+ ),
470
+ )
471
+ self._conn.commit()
472
+ return {
473
+ "attempt_id": attempt_id,
474
+ "matched_miss_id": attempt_id,
475
+ "surprise": surprise,
476
+ }
477
+
478
+ def revise_memory(
479
+ self,
480
+ *,
481
+ memory_id: int,
482
+ normalized_content: str,
483
+ encoded: Mapping[str, Any],
484
+ reason: str,
485
+ evidence: Sequence[Mapping[str, Any]],
486
+ confidence: float,
487
+ test_query: str,
488
+ source: str,
489
+ session_id: str,
490
+ tags: str = "",
491
+ salience: float = 0.65,
492
+ valence: float = 0.0,
493
+ memory_type: str = "episodic",
494
+ ) -> RevisionResult | dict[str, Any]:
495
+ if int(memory_id) < 1:
496
+ raise ValueError("memory_id must be >= 1")
497
+ content = str(normalized_content or "").strip()
498
+ if not content:
499
+ raise ValueError("new_content must not be empty")
500
+ reason_text = str(reason or "").strip()
501
+ if not reason_text:
502
+ raise ValueError("reason must not be empty")
503
+ conf = float(confidence)
504
+ if not 0.0 <= conf <= 1.0:
505
+ raise ValueError("confidence must be between 0 and 1")
506
+
507
+ with self._lock:
508
+ self._conn.execute("BEGIN IMMEDIATE")
509
+ try:
510
+ old = self._conn.execute(
511
+ "SELECT * FROM memories WHERE memory_id = ?",
512
+ (int(memory_id),),
513
+ ).fetchone()
514
+ if old is None:
515
+ raise ValueError(f"memory_id {memory_id} not found")
516
+
517
+ # Resolve superseded pointer to current tip when needed.
518
+ tip = old
519
+ tip_id = int(old["memory_id"])
520
+ if str(old["belief_status"] or "") == "superseded":
521
+ belief_id = str(old["belief_id"] or f"memory-{tip_id}")
522
+ current = self._conn.execute(
523
+ """
524
+ SELECT * FROM memories
525
+ WHERE belief_id = ? AND belief_status = 'current'
526
+ ORDER BY belief_version DESC, memory_id DESC
527
+ LIMIT 1
528
+ """,
529
+ (belief_id,),
530
+ ).fetchone()
531
+ if current is not None:
532
+ tip = current
533
+ tip_id = int(current["memory_id"])
534
+
535
+ if str(tip["content"] or "").strip() == content:
536
+ self._conn.execute("COMMIT")
537
+ return {
538
+ "status": "idempotent",
539
+ "memory_id": tip_id,
540
+ "belief_id": str(tip["belief_id"] or f"memory-{tip_id}"),
541
+ }
542
+
543
+ now = float(self._now_fn())
544
+ belief_id = str(tip["belief_id"] or f"memory-{tip_id}")
545
+ old_version = int(tip["belief_version"] or 1)
546
+ new_version = old_version + 1
547
+ cues = " ".join(list(encoded.get("cues") or [])[:32])
548
+
549
+ self._conn.execute(
550
+ """
551
+ UPDATE memories
552
+ SET access_state = 'labile', updated_at = ?
553
+ WHERE memory_id = ?
554
+ """,
555
+ (now, tip_id),
556
+ )
557
+
558
+ cur = self._conn.execute(
559
+ """
560
+ INSERT INTO memories (
561
+ content, encoded, cues, tags, salience, valence, strength,
562
+ source, session_id, created_at, updated_at,
563
+ last_rehearsed_at, state, last_anchor_at, memory_type,
564
+ belief_id, belief_version, belief_status, access_state,
565
+ confidence, supersedes_memory_id
566
+ ) VALUES (
567
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?,
568
+ ?, ?, 'current', 'accessible', ?, ?
569
+ )
570
+ """,
571
+ (
572
+ content,
573
+ json.dumps(dict(encoded), ensure_ascii=False),
574
+ cues,
575
+ tags or str(tip["tags"] or ""),
576
+ float(salience),
577
+ float(valence),
578
+ 1.0 + float(salience),
579
+ source or "explicit_correction",
580
+ session_id or "",
581
+ now,
582
+ now,
583
+ now,
584
+ now,
585
+ memory_type or str(tip["memory_type"] or "episodic"),
586
+ belief_id,
587
+ new_version,
588
+ conf,
589
+ tip_id,
590
+ ),
591
+ )
592
+ new_id = int(cur.lastrowid)
593
+
594
+ auto_archive = bool(self.policies.revision.auto_archive_superseded)
595
+ self._conn.execute(
596
+ """
597
+ UPDATE memories
598
+ SET belief_status = 'superseded',
599
+ superseded_by_memory_id = ?,
600
+ access_state = 'latent',
601
+ state = CASE WHEN ? THEN 'archived' ELSE state END,
602
+ archived_at = CASE WHEN ? THEN ? ELSE archived_at END,
603
+ archive_reason = CASE WHEN ? THEN 'superseded' ELSE archive_reason END,
604
+ updated_at = ?
605
+ WHERE memory_id = ?
606
+ """,
607
+ (
608
+ new_id,
609
+ 1 if auto_archive else 0,
610
+ 1 if auto_archive else 0,
611
+ now,
612
+ 1 if auto_archive else 0,
613
+ now,
614
+ tip_id,
615
+ ),
616
+ )
617
+
618
+ for relation_type in ("supersedes", "corrected_by"):
619
+ self._conn.execute(
620
+ """
621
+ INSERT OR IGNORE INTO memory_relations(
622
+ source_memory_id, target_memory_id, relation_type,
623
+ metadata, created_at
624
+ ) VALUES (?, ?, ?, ?, ?)
625
+ """,
626
+ (
627
+ new_id if relation_type == "supersedes" else tip_id,
628
+ tip_id if relation_type == "supersedes" else new_id,
629
+ relation_type,
630
+ _safe_json_payload({"reason": reason_text}),
631
+ now,
632
+ ),
633
+ )
634
+
635
+ contested: list[int] = []
636
+ if self.policies.revision.contest_dependents:
637
+ contested = self._contest_dependents_locked(
638
+ source_memory_id=tip_id,
639
+ reason=f"source_revised:{reason_text}",
640
+ visited=set(),
641
+ )
642
+
643
+ query = str(test_query or "").strip()
644
+ if not query:
645
+ query = " ".join(list(encoded.get("cues") or [])[:8])
646
+ rehearsal_id = self._queue_correction_rehearsal_locked(
647
+ belief_id=belief_id,
648
+ old_memory_id=tip_id,
649
+ new_memory_id=new_id,
650
+ test_query=query,
651
+ )
652
+
653
+ self._conn.execute(
654
+ """
655
+ INSERT INTO memory_events(
656
+ event_type, memory_id, related_memory_id, belief_id,
657
+ session_id, payload, created_at
658
+ ) VALUES ('belief_revised', ?, ?, ?, ?, ?, ?)
659
+ """,
660
+ (
661
+ new_id,
662
+ tip_id,
663
+ belief_id,
664
+ session_id or "",
665
+ _safe_json_payload(
666
+ {
667
+ "reason": reason_text,
668
+ "evidence": list(evidence or [])[:20],
669
+ "confidence": conf,
670
+ "old_version": old_version,
671
+ "new_version": new_version,
672
+ }
673
+ ),
674
+ now,
675
+ ),
676
+ )
677
+ self._conn.execute("COMMIT")
678
+ return RevisionResult(
679
+ belief_id=belief_id,
680
+ old_memory_id=tip_id,
681
+ new_memory_id=new_id,
682
+ old_version=old_version,
683
+ new_version=new_version,
684
+ contested_memory_ids=contested,
685
+ queued_rehearsal_id=rehearsal_id,
686
+ )
687
+ except Exception:
688
+ self._conn.execute("ROLLBACK")
689
+ raise
690
+
691
+ def retract_memory(
692
+ self,
693
+ *,
694
+ memory_id: int,
695
+ reason: str,
696
+ session_id: str = "",
697
+ ) -> dict[str, Any]:
698
+ reason_text = str(reason or "").strip()
699
+ if not reason_text:
700
+ raise ValueError("reason must not be empty")
701
+ with self._lock:
702
+ self._conn.execute("BEGIN IMMEDIATE")
703
+ try:
704
+ row = self._conn.execute(
705
+ "SELECT * FROM memories WHERE memory_id = ?",
706
+ (int(memory_id),),
707
+ ).fetchone()
708
+ if row is None:
709
+ raise ValueError(f"memory_id {memory_id} not found")
710
+ now = float(self._now_fn())
711
+ belief_id = str(row["belief_id"] or f"memory-{memory_id}")
712
+ self._conn.execute(
713
+ """
714
+ UPDATE memories
715
+ SET belief_status = 'retracted',
716
+ state = 'archived',
717
+ access_state = 'latent',
718
+ archive_reason = 'retracted',
719
+ archived_at = ?,
720
+ updated_at = ?
721
+ WHERE memory_id = ?
722
+ """,
723
+ (now, now, int(memory_id)),
724
+ )
725
+ contested: list[int] = []
726
+ if self.policies.revision.contest_dependents:
727
+ contested = self._contest_dependents_locked(
728
+ source_memory_id=int(memory_id),
729
+ reason=f"source_retracted:{reason_text}",
730
+ visited=set(),
731
+ )
732
+ self._conn.execute(
733
+ """
734
+ INSERT INTO memory_events(
735
+ event_type, memory_id, related_memory_id, belief_id,
736
+ session_id, payload, created_at
737
+ ) VALUES ('belief_retracted', ?, NULL, ?, ?, ?, ?)
738
+ """,
739
+ (
740
+ int(memory_id),
741
+ belief_id,
742
+ session_id or "",
743
+ _safe_json_payload({"reason": reason_text}),
744
+ now,
745
+ ),
746
+ )
747
+ self._conn.execute("COMMIT")
748
+ return {
749
+ "status": "retracted",
750
+ "memory_id": int(memory_id),
751
+ "belief_id": belief_id,
752
+ "contested_memory_ids": contested,
753
+ }
754
+ except Exception:
755
+ self._conn.execute("ROLLBACK")
756
+ raise
757
+
758
+ def belief_history(
759
+ self,
760
+ *,
761
+ memory_id: int | None = None,
762
+ belief_id: str = "",
763
+ ) -> list[dict[str, Any]]:
764
+ if memory_id is None and not belief_id:
765
+ raise ValueError("memory_id or belief_id is required")
766
+ with self._lock:
767
+ resolved_belief = str(belief_id or "")
768
+ if memory_id is not None:
769
+ row = self._conn.execute(
770
+ "SELECT belief_id FROM memories WHERE memory_id = ?",
771
+ (int(memory_id),),
772
+ ).fetchone()
773
+ if row is None:
774
+ return []
775
+ resolved_belief = str(row["belief_id"] or f"memory-{int(memory_id)}")
776
+ rows = self._conn.execute(
777
+ """
778
+ SELECT memory_id, belief_id, belief_version, belief_status,
779
+ content, confidence, state, access_state,
780
+ supersedes_memory_id, superseded_by_memory_id,
781
+ created_at, updated_at
782
+ FROM memories
783
+ WHERE belief_id = ?
784
+ ORDER BY belief_version ASC, memory_id ASC
785
+ """,
786
+ (resolved_belief,),
787
+ ).fetchall()
788
+ return [
789
+ {
790
+ "memory_id": int(r["memory_id"]),
791
+ "belief_id": str(r["belief_id"] or ""),
792
+ "belief_version": int(r["belief_version"] or 1),
793
+ "belief_status": str(r["belief_status"] or "current"),
794
+ "content": str(r["content"] or ""),
795
+ "confidence": float(r["confidence"] or 0.0),
796
+ "state": str(r["state"] or "active"),
797
+ "access_state": str(r["access_state"] or "accessible"),
798
+ "supersedes_memory_id": r["supersedes_memory_id"],
799
+ "superseded_by_memory_id": r["superseded_by_memory_id"],
800
+ "created_at": float(r["created_at"] or 0.0),
801
+ "updated_at": float(r["updated_at"] or 0.0),
802
+ }
803
+ for r in rows
804
+ ]
805
+
806
+ def queue_correction_rehearsal(
807
+ self,
808
+ *,
809
+ belief_id: str,
810
+ old_memory_id: int,
811
+ new_memory_id: int,
812
+ test_query: str,
813
+ ) -> int:
814
+ with self._lock:
815
+ return self._queue_correction_rehearsal_locked(
816
+ belief_id=belief_id,
817
+ old_memory_id=old_memory_id,
818
+ new_memory_id=new_memory_id,
819
+ test_query=test_query,
820
+ )
821
+
822
+ def run_correction_check(
823
+ self,
824
+ *,
825
+ recall_fn: Callable[..., Any],
826
+ rehearsal_id: int | None = None,
827
+ limit: int = 1,
828
+ ) -> dict[str, Any]:
829
+ """Replay pending correction rehearsals without reinforcing retrieval."""
830
+ with self._lock:
831
+ if rehearsal_id is not None:
832
+ rows = self._conn.execute(
833
+ """
834
+ SELECT * FROM correction_rehearsals
835
+ WHERE rehearsal_id = ?
836
+ """,
837
+ (int(rehearsal_id),),
838
+ ).fetchall()
839
+ else:
840
+ rows = self._conn.execute(
841
+ """
842
+ SELECT * FROM correction_rehearsals
843
+ WHERE status IN ('pending', 'failed')
844
+ ORDER BY created_at ASC, rehearsal_id ASC
845
+ LIMIT ?
846
+ """,
847
+ (max(1, int(limit)),),
848
+ ).fetchall()
849
+
850
+ passed: list[int] = []
851
+ failed: list[int] = []
852
+ details: list[dict[str, Any]] = []
853
+ now = float(self._now_fn())
854
+ for row in rows:
855
+ rid = int(row["rehearsal_id"])
856
+ old_id = int(row["old_memory_id"])
857
+ new_id = int(row["new_memory_id"])
858
+ expected = int(row["expected_memory_id"] or new_id)
859
+ query = str(row["test_query"] or "")
860
+ outcome = recall_fn(
861
+ query,
862
+ limit=5,
863
+ reinforce=False,
864
+ include_archived=False,
865
+ include_history=False,
866
+ allow_rescue=False,
867
+ track=False,
868
+ )
869
+ result_ids = [int(item["memory_id"]) for item in outcome.results]
870
+ top_id = result_ids[0] if result_ids else None
871
+ old_recurred = old_id in result_ids
872
+ ok = (
873
+ top_id == expected
874
+ and expected in result_ids
875
+ and not old_recurred
876
+ )
877
+ status = "passed" if ok else "failed"
878
+ self._conn.execute(
879
+ """
880
+ UPDATE correction_rehearsals
881
+ SET status = ?,
882
+ old_error_recurred = ?,
883
+ actual_memory_ids = ?,
884
+ attempt_count = attempt_count + 1,
885
+ last_run_at = ?
886
+ WHERE rehearsal_id = ?
887
+ """,
888
+ (
889
+ status,
890
+ 1 if old_recurred else 0,
891
+ json.dumps(result_ids, ensure_ascii=False),
892
+ now,
893
+ rid,
894
+ ),
895
+ )
896
+ self._conn.execute(
897
+ """
898
+ INSERT INTO memory_events(
899
+ event_type, memory_id, related_memory_id, belief_id,
900
+ session_id, payload, created_at
901
+ ) VALUES (?, ?, ?, ?, '', ?, ?)
902
+ """,
903
+ (
904
+ "correction_rehearsal_passed"
905
+ if ok
906
+ else "correction_rehearsal_failed",
907
+ new_id,
908
+ old_id,
909
+ str(row["belief_id"] or ""),
910
+ _safe_json_payload(
911
+ {
912
+ "rehearsal_id": rid,
913
+ "result_ids": result_ids,
914
+ "old_error_recurred": old_recurred,
915
+ }
916
+ ),
917
+ now,
918
+ ),
919
+ )
920
+ (passed if ok else failed).append(rid)
921
+ details.append(
922
+ {
923
+ "rehearsal_id": rid,
924
+ "status": status,
925
+ "result_ids": result_ids,
926
+ "old_error_recurred": old_recurred,
927
+ }
928
+ )
929
+ self._conn.commit()
930
+ return {
931
+ "passed": passed,
932
+ "failed": failed,
933
+ "details": details,
934
+ }
935
+
936
+ def contest_dependents(
937
+ self,
938
+ *,
939
+ source_memory_id: int,
940
+ reason: str,
941
+ visited: set[int] | None = None,
942
+ ) -> list[int]:
943
+ with self._lock:
944
+ return self._contest_dependents_locked(
945
+ source_memory_id=source_memory_id,
946
+ reason=reason,
947
+ visited=visited or set(),
948
+ )
949
+
950
+ def _queue_correction_rehearsal_locked(
951
+ self,
952
+ *,
953
+ belief_id: str,
954
+ old_memory_id: int,
955
+ new_memory_id: int,
956
+ test_query: str,
957
+ ) -> int:
958
+ now = float(self._now_fn())
959
+ cur = self._conn.execute(
960
+ """
961
+ INSERT INTO correction_rehearsals(
962
+ belief_id, old_memory_id, new_memory_id, test_query,
963
+ expected_memory_id, status, created_at
964
+ ) VALUES (?, ?, ?, ?, ?, 'pending', ?)
965
+ """,
966
+ (
967
+ str(belief_id),
968
+ int(old_memory_id),
969
+ int(new_memory_id),
970
+ str(test_query or ""),
971
+ int(new_memory_id),
972
+ now,
973
+ ),
974
+ )
975
+ return int(cur.lastrowid)
976
+
977
+ def _contest_dependents_locked(
978
+ self,
979
+ *,
980
+ source_memory_id: int,
981
+ reason: str,
982
+ visited: set[int],
983
+ ) -> list[int]:
984
+ if int(source_memory_id) in visited:
985
+ return []
986
+ visited.add(int(source_memory_id))
987
+ contested: list[int] = []
988
+ now = float(self._now_fn())
989
+
990
+ semantic_rows = self._conn.execute(
991
+ """
992
+ SELECT DISTINCT semantic_memory_id AS memory_id
993
+ FROM memory_provenance
994
+ WHERE source_memory_id = ?
995
+ """,
996
+ (int(source_memory_id),),
997
+ ).fetchall()
998
+ for row in semantic_rows:
999
+ mid = int(row["memory_id"])
1000
+ if mid in visited:
1001
+ continue
1002
+ self._conn.execute(
1003
+ """
1004
+ UPDATE memories
1005
+ SET belief_status = 'contested',
1006
+ state = 'archived',
1007
+ access_state = 'latent',
1008
+ archive_reason = 'source_revised',
1009
+ archived_at = COALESCE(archived_at, ?),
1010
+ updated_at = ?
1011
+ WHERE memory_id = ?
1012
+ """,
1013
+ (now, now, mid),
1014
+ )
1015
+ contested.append(mid)
1016
+ contested.extend(
1017
+ self._contest_dependents_locked(
1018
+ source_memory_id=mid, reason=reason, visited=visited
1019
+ )
1020
+ )
1021
+
1022
+ insight_rows = self._conn.execute(
1023
+ """
1024
+ SELECT DISTINCT candidate_id, promoted_memory_id
1025
+ FROM insight_candidates
1026
+ WHERE candidate_id IN (
1027
+ SELECT candidate_id FROM insight_sources WHERE memory_id = ?
1028
+ )
1029
+ """,
1030
+ (int(source_memory_id),),
1031
+ ).fetchall()
1032
+ for row in insight_rows:
1033
+ candidate_id = str(row["candidate_id"])
1034
+ self._conn.execute(
1035
+ """
1036
+ UPDATE insight_candidates
1037
+ SET status = 'contested', updated_at = ?
1038
+ WHERE candidate_id = ?
1039
+ """,
1040
+ (now, candidate_id),
1041
+ )
1042
+ promoted = row["promoted_memory_id"]
1043
+ if promoted is not None:
1044
+ pmid = int(promoted)
1045
+ self._conn.execute(
1046
+ """
1047
+ UPDATE memories
1048
+ SET belief_status = 'contested',
1049
+ state = 'archived',
1050
+ access_state = 'latent',
1051
+ archive_reason = 'insight_contested',
1052
+ archived_at = COALESCE(archived_at, ?),
1053
+ updated_at = ?
1054
+ WHERE memory_id = ?
1055
+ """,
1056
+ (now, now, pmid),
1057
+ )
1058
+ contested.append(pmid)
1059
+ contested.extend(
1060
+ self._contest_dependents_locked(
1061
+ source_memory_id=pmid, reason=reason, visited=visited
1062
+ )
1063
+ )
1064
+ self._conn.execute(
1065
+ """
1066
+ INSERT INTO memory_events(
1067
+ event_type, memory_id, related_memory_id, belief_id,
1068
+ session_id, payload, created_at
1069
+ ) VALUES ('insight_contested', ?, ?, '', '', ?, ?)
1070
+ """,
1071
+ (
1072
+ int(promoted) if promoted is not None else None,
1073
+ int(source_memory_id),
1074
+ _safe_json_payload(
1075
+ {"candidate_id": candidate_id, "reason": reason}
1076
+ ),
1077
+ now,
1078
+ ),
1079
+ )
1080
+ return contested
1081
+
1082
+ def association_preview(self, *, limit: int) -> dict[str, Any]:
1083
+ """Build cue/tag bridge previews without promoting hypotheses to memory."""
1084
+ ip = self.policies.insight
1085
+ if not ip.enabled:
1086
+ return {"mode": "association_preview", "enabled": False, "associations": []}
1087
+ max_assoc = max(1, min(int(limit), int(ip.association_limit)))
1088
+ now = float(self._now_fn())
1089
+ associations: list[dict[str, Any]] = []
1090
+
1091
+ focus_candidates: list[tuple[str, str, list[str]]] = []
1092
+ miss_rows = self._conn.execute(
1093
+ """
1094
+ SELECT attempt_id, query_cues FROM retrieval_attempts
1095
+ WHERE outcome = 'miss' AND resolved_at IS NULL
1096
+ ORDER BY created_at DESC LIMIT 8
1097
+ """
1098
+ ).fetchall()
1099
+ for row in miss_rows:
1100
+ try:
1101
+ cues = [str(c) for c in json.loads(row["query_cues"] or "[]")]
1102
+ except (TypeError, ValueError, json.JSONDecodeError):
1103
+ cues = []
1104
+ focus_candidates.append(("retrieval_miss", str(row["attempt_id"]), cues))
1105
+
1106
+ contested = self._conn.execute(
1107
+ """
1108
+ SELECT memory_id, cues FROM memories
1109
+ WHERE belief_status = 'contested'
1110
+ ORDER BY updated_at DESC LIMIT 4
1111
+ """
1112
+ ).fetchall()
1113
+ for row in contested:
1114
+ cues = str(row["cues"] or "").split()
1115
+ focus_candidates.append(("contested_belief", str(row["memory_id"]), cues))
1116
+
1117
+ pool = self._conn.execute(
1118
+ """
1119
+ SELECT * FROM memories
1120
+ WHERE belief_status IN ('current', 'context_dependent')
1121
+ AND access_state IN ('accessible', 'reactivated')
1122
+ AND state = 'active'
1123
+ ORDER BY salience DESC, updated_at DESC
1124
+ LIMIT 64
1125
+ """
1126
+ ).fetchall()
1127
+
1128
+ for focus_type, focus_id, focus_cues in focus_candidates:
1129
+ if len(associations) >= max_assoc:
1130
+ break
1131
+ focus_tags: set[str] = set()
1132
+ focus_cue_set = {c.lower() for c in focus_cues if c}
1133
+ scored: list[tuple[float, sqlite3.Row]] = []
1134
+ for row in pool:
1135
+ tags = {
1136
+ t.lower()
1137
+ for t in str(row["tags"] or "").replace(",", " ").split()
1138
+ if t.strip()
1139
+ }
1140
+ cues = {c.lower() for c in str(row["cues"] or "").split() if c}
1141
+ tag_overlap = (
1142
+ len(focus_tags & tags) / max(1, len(focus_tags | tags))
1143
+ if focus_tags or tags
1144
+ else 0.0
1145
+ )
1146
+ cue_overlap = (
1147
+ len(focus_cue_set & cues) / max(1, len(focus_cue_set | cues))
1148
+ if focus_cue_set or cues
1149
+ else 0.0
1150
+ )
1151
+ if tag_overlap == 0.0 and cue_overlap == 0.0:
1152
+ continue
1153
+ bridge = (
1154
+ 0.40 * tag_overlap
1155
+ + 0.25 * cue_overlap
1156
+ + 0.20 * (1.0 - cue_overlap)
1157
+ + 0.15 * float(row["salience"] or 0.0)
1158
+ )
1159
+ scored.append((bridge, row))
1160
+ scored.sort(key=lambda item: item[0], reverse=True)
1161
+ sources = []
1162
+ seen_content: set[str] = set()
1163
+ for _score, row in scored:
1164
+ content = str(row["content"] or "")
1165
+ if content in seen_content:
1166
+ continue
1167
+ seen_content.add(content)
1168
+ sources.append(
1169
+ {
1170
+ "memory_id": int(row["memory_id"]),
1171
+ "content": content,
1172
+ "belief_status": str(row["belief_status"] or "current"),
1173
+ "confidence": float(row["confidence"] or 0.0),
1174
+ }
1175
+ )
1176
+ if len(sources) >= 6:
1177
+ break
1178
+ if len(sources) < 2:
1179
+ continue
1180
+ association_id = f"assoc_{uuid.uuid4().hex}"
1181
+ source_ids = [int(s["memory_id"]) for s in sources]
1182
+ fingerprint = hashlib.sha256(
1183
+ ("|".join(map(str, sorted(source_ids))) + focus_type + focus_id).encode()
1184
+ ).hexdigest()
1185
+ expires_at = now + float(ip.candidate_ttl_days) * 86400.0
1186
+ payload = {
1187
+ "association_id": association_id,
1188
+ "focus": {"type": focus_type, "id": focus_id, "cues": focus_cues[:12]},
1189
+ "source_memories": sources,
1190
+ "instructions": [
1191
+ "Propose one falsifiable hypothesis.",
1192
+ "Do not present it as a fact.",
1193
+ "List a validation method and possible counterexample.",
1194
+ ],
1195
+ "expires_at": expires_at,
1196
+ }
1197
+ try:
1198
+ self._conn.execute(
1199
+ """
1200
+ INSERT INTO association_previews(
1201
+ association_id, focus_type, focus_id, source_memory_ids,
1202
+ source_fingerprint, prompt_payload, status, expires_at, created_at
1203
+ ) VALUES (?, ?, ?, ?, ?, ?, 'previewed', ?, ?)
1204
+ """,
1205
+ (
1206
+ association_id,
1207
+ focus_type,
1208
+ focus_id,
1209
+ json.dumps(source_ids, ensure_ascii=False),
1210
+ fingerprint,
1211
+ json.dumps(payload, ensure_ascii=False),
1212
+ expires_at,
1213
+ now,
1214
+ ),
1215
+ )
1216
+ except sqlite3.IntegrityError:
1217
+ continue
1218
+ associations.append(payload)
1219
+
1220
+ self._conn.commit()
1221
+ return {
1222
+ "mode": "association_preview",
1223
+ "enabled": True,
1224
+ "associations": associations,
1225
+ }
1226
+
1227
+ def propose_insight(
1228
+ self,
1229
+ *,
1230
+ association_id: str,
1231
+ hypothesis: str,
1232
+ source_memory_ids: Sequence[int],
1233
+ initial_confidence: float,
1234
+ ) -> dict[str, Any]:
1235
+ hyp = str(hypothesis or "").strip()
1236
+ if not hyp:
1237
+ raise ValueError("hypothesis must not be empty")
1238
+ conf = float(initial_confidence)
1239
+ if not 0.0 <= conf <= 1.0:
1240
+ raise ValueError("initial_confidence must be between 0 and 1")
1241
+ with self._lock:
1242
+ row = self._conn.execute(
1243
+ "SELECT * FROM association_previews WHERE association_id = ?",
1244
+ (str(association_id),),
1245
+ ).fetchone()
1246
+ if row is None:
1247
+ raise ValueError("association_id not found")
1248
+ now = float(self._now_fn())
1249
+ if float(row["expires_at"] or 0.0) < now:
1250
+ raise ValueError("association preview expired")
1251
+ allowed = set(json.loads(row["source_memory_ids"] or "[]"))
1252
+ sources = [int(x) for x in source_memory_ids]
1253
+ if not sources or not set(sources).issubset(allowed):
1254
+ raise ValueError("source_memory_ids must be a non-empty subset of preview")
1255
+ candidate_id = f"insight_{uuid.uuid4().hex}"
1256
+ self._conn.execute(
1257
+ """
1258
+ INSERT INTO insight_candidates(
1259
+ candidate_id, association_id, hypothesis, status,
1260
+ initial_confidence, evidence, created_at, updated_at
1261
+ ) VALUES (?, ?, ?, 'candidate', ?, '[]', ?, ?)
1262
+ """,
1263
+ (candidate_id, str(association_id), hyp, conf, now, now),
1264
+ )
1265
+ for mid in sources:
1266
+ self._conn.execute(
1267
+ """
1268
+ INSERT OR IGNORE INTO insight_sources(candidate_id, memory_id, source_role)
1269
+ VALUES (?, ?, 'support')
1270
+ """,
1271
+ (candidate_id, int(mid)),
1272
+ )
1273
+ self._conn.execute(
1274
+ """
1275
+ INSERT INTO memory_events(
1276
+ event_type, memory_id, related_memory_id, belief_id,
1277
+ session_id, payload, created_at
1278
+ ) VALUES ('insight_proposed', NULL, NULL, '', '', ?, ?)
1279
+ """,
1280
+ (
1281
+ _safe_json_payload(
1282
+ {
1283
+ "candidate_id": candidate_id,
1284
+ "association_id": association_id,
1285
+ "hypothesis": hyp[:500],
1286
+ }
1287
+ ),
1288
+ now,
1289
+ ),
1290
+ )
1291
+ self._conn.commit()
1292
+ return {
1293
+ "status": "candidate",
1294
+ "candidate_id": candidate_id,
1295
+ "association_id": association_id,
1296
+ "hypothesis": hyp,
1297
+ "initial_confidence": conf,
1298
+ "source_memory_ids": sources,
1299
+ }
1300
+
1301
+ def validate_insight(
1302
+ self,
1303
+ *,
1304
+ candidate_id: str,
1305
+ validation_method: str,
1306
+ evidence: Sequence[Mapping[str, Any]],
1307
+ validated_confidence: float,
1308
+ summary: str,
1309
+ remember_fn: Callable[..., Mapping[str, Any]] | None = None,
1310
+ ) -> InsightValidationResult:
1311
+ from .models import ValidationMethod
1312
+
1313
+ method = str(validation_method or "").strip()
1314
+ if method not in {m.value for m in ValidationMethod}:
1315
+ raise ValueError(f"unsupported validation_method: {method}")
1316
+ if not evidence:
1317
+ raise ValueError("evidence must contain at least one item")
1318
+ conf = float(validated_confidence)
1319
+ ip = self.policies.insight
1320
+ if conf < float(ip.validation_min_confidence):
1321
+ raise ValueError("validated_confidence below validation_min_confidence")
1322
+ with self._lock:
1323
+ row = self._conn.execute(
1324
+ "SELECT * FROM insight_candidates WHERE candidate_id = ?",
1325
+ (str(candidate_id),),
1326
+ ).fetchone()
1327
+ if row is None:
1328
+ raise ValueError("candidate_id not found")
1329
+ if str(row["status"]) not in {"candidate", "validating"}:
1330
+ raise ValueError(f"cannot validate status={row['status']}")
1331
+ sources = self._conn.execute(
1332
+ "SELECT memory_id FROM insight_sources WHERE candidate_id = ?",
1333
+ (str(candidate_id),),
1334
+ ).fetchall()
1335
+ source_ids = [int(r["memory_id"]) for r in sources]
1336
+ for mid in source_ids:
1337
+ belief = self._conn.execute(
1338
+ "SELECT belief_status FROM memories WHERE memory_id = ?",
1339
+ (mid,),
1340
+ ).fetchone()
1341
+ if belief and str(belief["belief_status"]) in {
1342
+ "contested",
1343
+ "superseded",
1344
+ "retracted",
1345
+ }:
1346
+ raise ValueError("source memory is no longer current")
1347
+ now = float(self._now_fn())
1348
+ text = str(summary or row["hypothesis"] or "").strip()
1349
+ promoted_id = None
1350
+ if remember_fn is not None:
1351
+ remembered = remember_fn(
1352
+ text,
1353
+ tags=["insight", "validated", "semantic"],
1354
+ salience=min(1.0, max(0.05, conf)),
1355
+ source="validated_insight",
1356
+ memory_type="semantic",
1357
+ )
1358
+ promoted_id = int(remembered["memory_id"])
1359
+ self._conn.execute(
1360
+ "UPDATE memories SET confidence = ? WHERE memory_id = ?",
1361
+ (conf, promoted_id),
1362
+ )
1363
+ for mid in source_ids:
1364
+ self._conn.execute(
1365
+ """
1366
+ INSERT OR IGNORE INTO memory_provenance(
1367
+ semantic_memory_id, source_memory_id, relation, created_at
1368
+ ) VALUES (?, ?, 'insight-derived', ?)
1369
+ """,
1370
+ (promoted_id, mid, now),
1371
+ )
1372
+ self._conn.execute(
1373
+ """
1374
+ UPDATE insight_candidates
1375
+ SET status = 'validated',
1376
+ validated_confidence = ?,
1377
+ validation_method = ?,
1378
+ evidence = ?,
1379
+ promoted_memory_id = ?,
1380
+ updated_at = ?
1381
+ WHERE candidate_id = ?
1382
+ """,
1383
+ (
1384
+ conf,
1385
+ method,
1386
+ json.dumps(list(evidence), ensure_ascii=False, default=str),
1387
+ promoted_id,
1388
+ now,
1389
+ str(candidate_id),
1390
+ ),
1391
+ )
1392
+ self._conn.execute(
1393
+ """
1394
+ INSERT INTO memory_events(
1395
+ event_type, memory_id, related_memory_id, belief_id,
1396
+ session_id, payload, created_at
1397
+ ) VALUES ('insight_validated', ?, NULL, '', '', ?, ?)
1398
+ """,
1399
+ (
1400
+ promoted_id,
1401
+ _safe_json_payload(
1402
+ {
1403
+ "candidate_id": candidate_id,
1404
+ "validation_method": method,
1405
+ "validated_confidence": conf,
1406
+ }
1407
+ ),
1408
+ now,
1409
+ ),
1410
+ )
1411
+ self._conn.commit()
1412
+ return InsightValidationResult(
1413
+ candidate_id=str(candidate_id),
1414
+ status=InsightStatus.VALIDATED,
1415
+ promoted_memory_id=promoted_id,
1416
+ contested_source_ids=[],
1417
+ )
1418
+
1419
+ def reject_insight(self, *, candidate_id: str, reason: str) -> dict[str, Any]:
1420
+ reason_text = str(reason or "").strip()
1421
+ if not reason_text:
1422
+ raise ValueError("reason must not be empty")
1423
+ with self._lock:
1424
+ row = self._conn.execute(
1425
+ "SELECT * FROM insight_candidates WHERE candidate_id = ?",
1426
+ (str(candidate_id),),
1427
+ ).fetchone()
1428
+ if row is None:
1429
+ raise ValueError("candidate_id not found")
1430
+ now = float(self._now_fn())
1431
+ self._conn.execute(
1432
+ """
1433
+ UPDATE insight_candidates
1434
+ SET status = 'rejected',
1435
+ rejection_reason = ?,
1436
+ updated_at = ?
1437
+ WHERE candidate_id = ?
1438
+ """,
1439
+ (reason_text, now, str(candidate_id)),
1440
+ )
1441
+ self._conn.execute(
1442
+ """
1443
+ INSERT INTO memory_events(
1444
+ event_type, memory_id, related_memory_id, belief_id,
1445
+ session_id, payload, created_at
1446
+ ) VALUES ('false_insight', NULL, NULL, '', '', ?, ?)
1447
+ """,
1448
+ (
1449
+ _safe_json_payload(
1450
+ {"candidate_id": candidate_id, "reason": reason_text}
1451
+ ),
1452
+ now,
1453
+ ),
1454
+ )
1455
+ self._conn.commit()
1456
+ return {
1457
+ "status": "rejected",
1458
+ "candidate_id": str(candidate_id),
1459
+ "reason": reason_text,
1460
+ }
1461
+
1462
+ def _trim_unresolved_misses_locked(self) -> None:
1463
+ limit = int(self.policies.experience.max_unresolved_misses)
1464
+ count_row = self._conn.execute(
1465
+ """
1466
+ SELECT COUNT(*) AS count FROM retrieval_attempts
1467
+ WHERE outcome = 'miss' AND resolved_at IS NULL
1468
+ """
1469
+ ).fetchone()
1470
+ count = int(count_row["count"] if isinstance(count_row, sqlite3.Row) else count_row[0])
1471
+ overflow = count + 1 - limit
1472
+ if overflow <= 0:
1473
+ return
1474
+ old_ids = self._conn.execute(
1475
+ """
1476
+ SELECT attempt_id FROM retrieval_attempts
1477
+ WHERE outcome = 'miss' AND resolved_at IS NULL
1478
+ ORDER BY created_at ASC, attempt_id ASC
1479
+ LIMIT ?
1480
+ """,
1481
+ (overflow,),
1482
+ ).fetchall()
1483
+ for row in old_ids:
1484
+ attempt_id = int(row["attempt_id"] if isinstance(row, sqlite3.Row) else row[0])
1485
+ self._conn.execute(
1486
+ "DELETE FROM retrieval_attempts WHERE attempt_id = ?",
1487
+ (attempt_id,),
1488
+ )