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,362 @@
1
+ """Additive experiential-memory schema migrations for Ebbinghaus SQLite.
2
+
3
+ Migrations are idempotent, preserve existing memory rows, and use the SQLite
4
+ online backup API before applying version 1 DDL.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import sqlite3
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ EXPERIENCE_SCHEMA_VERSION = 1
18
+ EXPERIENCE_MIGRATION_NAME = "experiential_memory_v1"
19
+
20
+ _EXPERIENCE_COLUMNS: list[tuple[str, str]] = [
21
+ ("access_state", "TEXT NOT NULL DEFAULT 'accessible'"),
22
+ ("belief_id", "TEXT NOT NULL DEFAULT ''"),
23
+ ("belief_version", "INTEGER NOT NULL DEFAULT 1"),
24
+ ("belief_status", "TEXT NOT NULL DEFAULT 'current'"),
25
+ ("confidence", "REAL NOT NULL DEFAULT 0.60"),
26
+ ("supersedes_memory_id", "INTEGER"),
27
+ ("superseded_by_memory_id", "INTEGER"),
28
+ ("latent_at", "REAL"),
29
+ ("last_reactivated_at", "REAL"),
30
+ ("reactivation_count", "INTEGER NOT NULL DEFAULT 0"),
31
+ ]
32
+
33
+ _EXPERIENCE_DDL = """
34
+ CREATE TABLE IF NOT EXISTS ebbinghaus_schema_migrations (
35
+ version INTEGER PRIMARY KEY,
36
+ name TEXT NOT NULL,
37
+ applied_at REAL NOT NULL,
38
+ backup_path TEXT NOT NULL DEFAULT ''
39
+ );
40
+
41
+ CREATE TABLE IF NOT EXISTS memory_events (
42
+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,
43
+ event_type TEXT NOT NULL,
44
+ memory_id INTEGER,
45
+ related_memory_id INTEGER,
46
+ belief_id TEXT NOT NULL DEFAULT '',
47
+ session_id TEXT NOT NULL DEFAULT '',
48
+ payload TEXT NOT NULL DEFAULT '{}',
49
+ created_at REAL NOT NULL
50
+ );
51
+
52
+ CREATE INDEX IF NOT EXISTS idx_memory_events_type_created
53
+ ON memory_events(event_type, created_at DESC);
54
+
55
+ CREATE INDEX IF NOT EXISTS idx_memory_events_memory
56
+ ON memory_events(memory_id, created_at DESC);
57
+
58
+ CREATE INDEX IF NOT EXISTS idx_memory_events_belief
59
+ ON memory_events(belief_id, created_at DESC);
60
+
61
+ CREATE TABLE IF NOT EXISTS retrieval_attempts (
62
+ attempt_id INTEGER PRIMARY KEY AUTOINCREMENT,
63
+ query_hash TEXT NOT NULL,
64
+ query_excerpt TEXT NOT NULL DEFAULT '',
65
+ query_cues TEXT NOT NULL DEFAULT '',
66
+ outcome TEXT NOT NULL,
67
+ top_memory_id INTEGER,
68
+ matched_miss_id INTEGER,
69
+ result_memory_ids TEXT NOT NULL DEFAULT '[]',
70
+ direct_best_score REAL NOT NULL DEFAULT 0.0,
71
+ rescue_score REAL NOT NULL DEFAULT 0.0,
72
+ surprise REAL NOT NULL DEFAULT 0.0,
73
+ resolved_at REAL,
74
+ created_at REAL NOT NULL
75
+ );
76
+
77
+ CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_open_miss
78
+ ON retrieval_attempts(outcome, resolved_at, created_at DESC);
79
+
80
+ CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_hash
81
+ ON retrieval_attempts(query_hash, created_at DESC);
82
+
83
+ CREATE TABLE IF NOT EXISTS memory_relations (
84
+ relation_id INTEGER PRIMARY KEY AUTOINCREMENT,
85
+ source_memory_id INTEGER NOT NULL,
86
+ target_memory_id INTEGER NOT NULL,
87
+ relation_type TEXT NOT NULL,
88
+ metadata TEXT NOT NULL DEFAULT '{}',
89
+ created_at REAL NOT NULL,
90
+ UNIQUE(source_memory_id, target_memory_id, relation_type)
91
+ );
92
+
93
+ CREATE INDEX IF NOT EXISTS idx_memory_relations_source
94
+ ON memory_relations(source_memory_id, relation_type);
95
+
96
+ CREATE INDEX IF NOT EXISTS idx_memory_relations_target
97
+ ON memory_relations(target_memory_id, relation_type);
98
+
99
+ CREATE TABLE IF NOT EXISTS correction_rehearsals (
100
+ rehearsal_id INTEGER PRIMARY KEY AUTOINCREMENT,
101
+ belief_id TEXT NOT NULL,
102
+ old_memory_id INTEGER NOT NULL,
103
+ new_memory_id INTEGER NOT NULL,
104
+ test_query TEXT NOT NULL,
105
+ expected_memory_id INTEGER NOT NULL,
106
+ status TEXT NOT NULL DEFAULT 'pending',
107
+ old_error_recurred INTEGER NOT NULL DEFAULT 0,
108
+ actual_memory_ids TEXT NOT NULL DEFAULT '[]',
109
+ attempt_count INTEGER NOT NULL DEFAULT 0,
110
+ last_run_at REAL,
111
+ created_at REAL NOT NULL
112
+ );
113
+
114
+ CREATE INDEX IF NOT EXISTS idx_correction_rehearsals_status
115
+ ON correction_rehearsals(status, created_at);
116
+
117
+ CREATE TABLE IF NOT EXISTS association_previews (
118
+ association_id TEXT PRIMARY KEY,
119
+ focus_type TEXT NOT NULL,
120
+ focus_id TEXT NOT NULL,
121
+ source_memory_ids TEXT NOT NULL,
122
+ source_fingerprint TEXT NOT NULL UNIQUE,
123
+ prompt_payload TEXT NOT NULL,
124
+ status TEXT NOT NULL DEFAULT 'previewed',
125
+ expires_at REAL NOT NULL,
126
+ created_at REAL NOT NULL
127
+ );
128
+
129
+ CREATE TABLE IF NOT EXISTS insight_candidates (
130
+ candidate_id TEXT PRIMARY KEY,
131
+ association_id TEXT NOT NULL,
132
+ hypothesis TEXT NOT NULL,
133
+ status TEXT NOT NULL DEFAULT 'candidate',
134
+ initial_confidence REAL NOT NULL,
135
+ validated_confidence REAL,
136
+ validation_method TEXT NOT NULL DEFAULT '',
137
+ evidence TEXT NOT NULL DEFAULT '[]',
138
+ rejection_reason TEXT NOT NULL DEFAULT '',
139
+ promoted_memory_id INTEGER,
140
+ created_at REAL NOT NULL,
141
+ updated_at REAL NOT NULL
142
+ );
143
+
144
+ CREATE INDEX IF NOT EXISTS idx_insight_candidates_status
145
+ ON insight_candidates(status, updated_at DESC);
146
+
147
+ CREATE TABLE IF NOT EXISTS insight_sources (
148
+ candidate_id TEXT NOT NULL,
149
+ memory_id INTEGER NOT NULL,
150
+ source_role TEXT NOT NULL DEFAULT 'support',
151
+ PRIMARY KEY(candidate_id, memory_id)
152
+ );
153
+
154
+ CREATE INDEX IF NOT EXISTS idx_insight_sources_memory
155
+ ON insight_sources(memory_id);
156
+
157
+ CREATE INDEX IF NOT EXISTS idx_memories_retrieval_state
158
+ ON memories(state, access_state, belief_status);
159
+
160
+ CREATE INDEX IF NOT EXISTS idx_memories_belief_version
161
+ ON memories(belief_id, belief_version DESC);
162
+
163
+ CREATE INDEX IF NOT EXISTS idx_memories_reactivation
164
+ ON memories(reactivation_count DESC, last_reactivated_at DESC);
165
+ """
166
+
167
+
168
+ def verify_database_integrity(conn: sqlite3.Connection) -> None:
169
+ """Raise if SQLite integrity or foreign-key checks fail."""
170
+ integrity = conn.execute("PRAGMA integrity_check").fetchone()
171
+ if integrity is None or str(integrity[0]).lower() != "ok":
172
+ raise sqlite3.DatabaseError(
173
+ f"Ebbinghaus integrity_check failed: {integrity[0] if integrity else None}"
174
+ )
175
+ try:
176
+ conn.execute("PRAGMA foreign_keys=ON")
177
+ fk_rows = conn.execute("PRAGMA foreign_key_check").fetchall()
178
+ except sqlite3.DatabaseError as exc:
179
+ raise sqlite3.DatabaseError(
180
+ f"Ebbinghaus foreign_key_check failed to run: {exc}"
181
+ ) from exc
182
+ if fk_rows:
183
+ raise sqlite3.DatabaseError(
184
+ f"Ebbinghaus foreign_key_check failed: {len(fk_rows)} violation(s)"
185
+ )
186
+
187
+
188
+ def create_online_backup(
189
+ conn: sqlite3.Connection,
190
+ db_path: Path,
191
+ *,
192
+ schema_version: int,
193
+ now: float,
194
+ ) -> Path | None:
195
+ """Create an integrity-checked online backup beside ``db_path``."""
196
+ db_path = Path(db_path)
197
+ if not db_path.exists() or db_path.stat().st_size == 0:
198
+ return None
199
+
200
+ stamp = datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
201
+ backup_path = db_path.with_name(
202
+ f"{db_path.stem}.pre-experience-v{schema_version}.{stamp}.bak"
203
+ )
204
+ if backup_path.exists():
205
+ return backup_path
206
+
207
+ destination = sqlite3.connect(str(backup_path))
208
+ try:
209
+ conn.backup(destination)
210
+ row = destination.execute("PRAGMA integrity_check").fetchone()
211
+ if row is None or str(row[0]).lower() != "ok":
212
+ raise sqlite3.DatabaseError(
213
+ "Ebbinghaus migration backup failed integrity_check"
214
+ )
215
+ destination.commit()
216
+ except Exception:
217
+ destination.close()
218
+ backup_path.unlink(missing_ok=True)
219
+ raise
220
+ else:
221
+ destination.close()
222
+ return backup_path
223
+
224
+
225
+ def _ensure_migration_table(conn: sqlite3.Connection) -> None:
226
+ conn.execute(
227
+ """
228
+ CREATE TABLE IF NOT EXISTS ebbinghaus_schema_migrations (
229
+ version INTEGER PRIMARY KEY,
230
+ name TEXT NOT NULL,
231
+ applied_at REAL NOT NULL,
232
+ backup_path TEXT NOT NULL DEFAULT ''
233
+ )
234
+ """
235
+ )
236
+
237
+
238
+ def _memory_columns(conn: sqlite3.Connection) -> set[str]:
239
+ return {
240
+ str(row[1] if not isinstance(row, sqlite3.Row) else row["name"])
241
+ for row in conn.execute("PRAGMA table_info(memories)").fetchall()
242
+ }
243
+
244
+
245
+ def _add_experience_columns(conn: sqlite3.Connection) -> None:
246
+ existing = _memory_columns(conn)
247
+ for col_name, col_def in _EXPERIENCE_COLUMNS:
248
+ if col_name in existing:
249
+ continue
250
+ conn.execute(f"ALTER TABLE memories ADD COLUMN {col_name} {col_def}")
251
+ logger.info("Ebbinghaus experience migration: added column %s", col_name)
252
+
253
+
254
+ def _backfill_experience_columns(conn: sqlite3.Connection) -> None:
255
+ # Version-1 only: existing rows are pre-experience, so rewrite access_state
256
+ # from storage state even when ADD COLUMN defaulted archived rows to accessible.
257
+ conn.execute(
258
+ """
259
+ UPDATE memories
260
+ SET access_state = CASE
261
+ WHEN state = 'archived' THEN 'latent'
262
+ ELSE 'accessible'
263
+ END
264
+ """
265
+ )
266
+ conn.execute(
267
+ """
268
+ UPDATE memories
269
+ SET belief_id = 'memory-' || memory_id
270
+ WHERE belief_id IS NULL OR belief_id = ''
271
+ """
272
+ )
273
+ conn.execute(
274
+ """
275
+ UPDATE memories
276
+ SET belief_version = 1
277
+ WHERE belief_version IS NULL OR belief_version < 1
278
+ """
279
+ )
280
+ conn.execute(
281
+ """
282
+ UPDATE memories
283
+ SET belief_status = 'current'
284
+ WHERE belief_status IS NULL OR belief_status = ''
285
+ """
286
+ )
287
+
288
+
289
+ def apply_experience_migrations(
290
+ conn: sqlite3.Connection,
291
+ db_path: Path,
292
+ *,
293
+ now: float,
294
+ ) -> dict[str, Any]:
295
+ """Apply additive experiential-memory schema migrations once."""
296
+ db_path = Path(db_path)
297
+ _ensure_migration_table(conn)
298
+ conn.commit()
299
+
300
+ existing = conn.execute(
301
+ "SELECT version, backup_path FROM ebbinghaus_schema_migrations WHERE version = ?",
302
+ (EXPERIENCE_SCHEMA_VERSION,),
303
+ ).fetchone()
304
+ if existing is not None:
305
+ backup_path = ""
306
+ if isinstance(existing, sqlite3.Row):
307
+ backup_path = str(existing["backup_path"] or "")
308
+ else:
309
+ backup_path = str(existing[1] or "")
310
+ return {
311
+ "applied": False,
312
+ "version": EXPERIENCE_SCHEMA_VERSION,
313
+ "backup_path": backup_path,
314
+ }
315
+
316
+ backup = create_online_backup(
317
+ conn,
318
+ db_path,
319
+ schema_version=EXPERIENCE_SCHEMA_VERSION,
320
+ now=now,
321
+ )
322
+ backup_path = str(backup) if backup is not None else ""
323
+
324
+ conn.execute("BEGIN IMMEDIATE")
325
+ try:
326
+ _add_experience_columns(conn)
327
+ conn.executescript(_EXPERIENCE_DDL)
328
+ _backfill_experience_columns(conn)
329
+ conn.execute(
330
+ """
331
+ INSERT INTO ebbinghaus_schema_migrations(version, name, applied_at, backup_path)
332
+ VALUES (?, ?, ?, ?)
333
+ """,
334
+ (
335
+ EXPERIENCE_SCHEMA_VERSION,
336
+ EXPERIENCE_MIGRATION_NAME,
337
+ float(now),
338
+ backup_path,
339
+ ),
340
+ )
341
+ conn.execute("COMMIT")
342
+ except Exception as exc:
343
+ try:
344
+ conn.execute("ROLLBACK")
345
+ except sqlite3.Error:
346
+ pass
347
+ raise sqlite3.DatabaseError(
348
+ "Ebbinghaus experiential migration failed"
349
+ + (f"; backup kept at {backup_path}" if backup_path else "")
350
+ ) from exc
351
+
352
+ verify_database_integrity(conn)
353
+ logger.info(
354
+ "Ebbinghaus experience migration v%s applied (backup=%s)",
355
+ EXPERIENCE_SCHEMA_VERSION,
356
+ backup_path or "none",
357
+ )
358
+ return {
359
+ "applied": True,
360
+ "version": EXPERIENCE_SCHEMA_VERSION,
361
+ "backup_path": backup_path,
362
+ }
@@ -0,0 +1,85 @@
1
+ """Experiential-memory domain models for Ebbinghaus AGIASI extensions.
2
+
3
+ Wire values are stable contracts used by SQLite rows, tool payloads, and tests.
4
+ Do not rename enum members or change their ``.value`` strings without a
5
+ compatibility adapter.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from typing import Any
13
+
14
+
15
+ class AccessState(str, Enum):
16
+ ACCESSIBLE = "accessible"
17
+ LATENT = "latent"
18
+ REACTIVATED = "reactivated"
19
+ LABILE = "labile"
20
+
21
+
22
+ class BeliefStatus(str, Enum):
23
+ CURRENT = "current"
24
+ CONTEXT_DEPENDENT = "context_dependent"
25
+ UNVERIFIED = "unverified"
26
+ CONTESTED = "contested"
27
+ SUPERSEDED = "superseded"
28
+ RETRACTED = "retracted"
29
+
30
+
31
+ class RetrievalOutcome(str, Enum):
32
+ HIT = "hit"
33
+ MISS = "miss"
34
+ RESCUED = "rescued"
35
+
36
+
37
+ class InsightStatus(str, Enum):
38
+ CANDIDATE = "candidate"
39
+ VALIDATING = "validating"
40
+ VALIDATED = "validated"
41
+ REJECTED = "rejected"
42
+ CONTESTED = "contested"
43
+ EXPIRED = "expired"
44
+
45
+
46
+ class ValidationMethod(str, Enum):
47
+ UNIT_TEST = "unit_test"
48
+ EXTERNAL_SOURCE = "external_source"
49
+ COUNTEREXAMPLE_SEARCH = "counterexample_search"
50
+ USER_CONFIRMATION = "user_confirmation"
51
+ INDEPENDENT_REASONING = "independent_reasoning"
52
+ MANUAL = "manual"
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class RecallAttemptResult:
57
+ query: str
58
+ outcome: RetrievalOutcome
59
+ results: list[dict[str, Any]]
60
+ attempt_id: int | None = None
61
+ matched_miss_id: int | None = None
62
+ rescued_memory_id: int | None = None
63
+ direct_best_score: float = 0.0
64
+ rescue_score: float = 0.0
65
+ surprise: float = 0.0
66
+ state_note: str = ""
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class RevisionResult:
71
+ belief_id: str
72
+ old_memory_id: int
73
+ new_memory_id: int
74
+ old_version: int
75
+ new_version: int
76
+ contested_memory_ids: list[int] = field(default_factory=list)
77
+ queued_rehearsal_id: int | None = None
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class InsightValidationResult:
82
+ candidate_id: str
83
+ status: InsightStatus
84
+ promoted_memory_id: int | None
85
+ contested_source_ids: list[int] = field(default_factory=list)