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,21 @@
1
+ """Composite memory library: Ebbinghaus + Semantic Graph + Obsidian Wiki."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from hakua_memory.composite import CompositeMemory
6
+ from hakua_memory.ebbinghaus.store import (
7
+ _encode_memory,
8
+ forgetting_retention,
9
+ )
10
+ from hakua_memory.semantic_graph.store import (
11
+ DB_SCHEMA_VERSION,
12
+ GRAPH_SCHEMA_VERSION,
13
+ )
14
+
15
+ __all__ = [
16
+ "forgetting_retention",
17
+ "_encode_memory",
18
+ "DB_SCHEMA_VERSION",
19
+ "GRAPH_SCHEMA_VERSION",
20
+ "CompositeMemory",
21
+ ]
@@ -0,0 +1,257 @@
1
+ """High-level composite memory API tying Ebbinghaus, Semantic Graph, Embedding, and RAG."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+ from pathlib import Path
7
+ from typing import Any, Optional
8
+
9
+ from hakua_memory.ebbinghaus.store import EbbinghausMemoryStore
10
+ from hakua_memory.obsidian import write_diary
11
+ from hakua_memory.rag import (
12
+ AclEntry,
13
+ DocumentStore,
14
+ RagResult,
15
+ detect_contradictions,
16
+ extract_meeting_items,
17
+ ingest_document,
18
+ ingest_markdown_string,
19
+ ingest_text_string,
20
+ render_citation_context,
21
+ search_chunks,
22
+ )
23
+ from hakua_memory.semantic_graph.embedding.base import EmbeddingBackend
24
+ from hakua_memory.semantic_graph.retrieval import hybrid_search_and_rank
25
+ from hakua_memory.semantic_graph.store import SemanticGraphStore
26
+
27
+
28
+ class CompositeMemory:
29
+ """Single entrypoint for local composite memory."""
30
+
31
+ def __init__(self, root: Path) -> None:
32
+ self.root = Path(root)
33
+ self.root.mkdir(parents=True, exist_ok=True)
34
+ self.ebbinghaus = EbbinghausMemoryStore(self.root / "ebbinghaus.db")
35
+ self.semantic = SemanticGraphStore(self.root / "semantic.db")
36
+ self.documents = DocumentStore(self.root / "rag.db")
37
+
38
+ def remember(self, content: str, tags: Optional[list[str]] = None) -> dict[str, Any]:
39
+ return self.ebbinghaus.remember(content=content, tags=tags or [])
40
+
41
+ def recall(self, query: str, top_k: int = 5) -> list[dict[str, Any]]:
42
+ return self.ebbinghaus.recall(query, limit=top_k)
43
+
44
+ def sleep(self) -> dict[str, Any]:
45
+ return self.ebbinghaus.sleep_cycle()
46
+
47
+ def add_node(self, node: dict[str, Any]) -> dict[str, Any]:
48
+ self.semantic.ensure_ready()
49
+ return self.semantic.upsert_node(node)
50
+
51
+ def search(
52
+ self,
53
+ query: str,
54
+ *,
55
+ top_k: int = 8,
56
+ backend: Optional[EmbeddingBackend] = None,
57
+ ) -> list[dict[str, Any]]:
58
+ return hybrid_search_and_rank(
59
+ self.semantic,
60
+ query,
61
+ backend=backend,
62
+ top_k=top_k,
63
+ )
64
+
65
+ # ── RAG methods ─────────────────────────────────────────────────
66
+
67
+ def ingest_document(self, path: Path, **kwargs: Any) -> dict[str, Any]:
68
+ """Ingest a document file and store it with chunks."""
69
+ doc, chunks = ingest_document(path, **kwargs)
70
+ self.documents.insert_document(doc)
71
+ chunk_ids = self.documents.insert_chunks(chunks)
72
+ return {
73
+ "document_id": doc.document_id,
74
+ "title": doc.title,
75
+ "chunks": len(chunk_ids),
76
+ "document_type": doc.document_type,
77
+ }
78
+
79
+ def ingest_markdown(self, text: str, **kwargs: Any) -> dict[str, Any]:
80
+ """Ingest a markdown string."""
81
+ doc, chunks = ingest_markdown_string(text, **kwargs)
82
+ self.documents.insert_document(doc)
83
+ chunk_ids = self.documents.insert_chunks(chunks)
84
+ return {
85
+ "document_id": doc.document_id,
86
+ "title": doc.title,
87
+ "chunks": len(chunk_ids),
88
+ }
89
+
90
+ def ingest_text(self, text: str, **kwargs: Any) -> dict[str, Any]:
91
+ """Ingest a plain text string."""
92
+ doc, chunks = ingest_text_string(text, **kwargs)
93
+ self.documents.insert_document(doc)
94
+ chunk_ids = self.documents.insert_chunks(chunks)
95
+ return {
96
+ "document_id": doc.document_id,
97
+ "title": doc.title,
98
+ "chunks": len(chunk_ids),
99
+ }
100
+
101
+ def search_documents(
102
+ self,
103
+ query: str,
104
+ *,
105
+ top_k: int = 8,
106
+ principal: str = "",
107
+ document_type: str = "",
108
+ department: str = "",
109
+ ) -> list[dict[str, Any]]:
110
+ """Search ingested documents with full-text search."""
111
+ results = search_chunks(
112
+ self.documents,
113
+ query,
114
+ top_k=top_k,
115
+ principal=principal,
116
+ document_type=document_type,
117
+ department=department,
118
+ )
119
+ return [r.to_dict() for r in results]
120
+
121
+ def render_citations(
122
+ self,
123
+ results: list[dict[str, Any]],
124
+ *,
125
+ max_chars: int = 4000,
126
+ format: str = "markdown",
127
+ ) -> str:
128
+ """Render citation context from search results."""
129
+ # Rebuild RagResult objects from dicts
130
+ rag_results = []
131
+ for r in results:
132
+ chunk = self.documents.get_chunk(r["chunk_id"])
133
+ doc = self.documents.get_document(r["document_id"])
134
+ if chunk and doc:
135
+ rag_results.append(
136
+ RagResult(
137
+ chunk=chunk,
138
+ document=doc,
139
+ score=r.get("score", 0.0),
140
+ rank=r.get("rank", 0),
141
+ )
142
+ )
143
+ return render_citation_context(rag_results, max_chars=max_chars, format=format)
144
+
145
+ def extract_meeting_items(
146
+ self, document_id: str, *, auto_store: bool = True
147
+ ) -> list[dict[str, Any]]:
148
+ """Extract meeting items (decisions, tasks, action items) from a document."""
149
+ chunks = self._get_chunks(document_id)
150
+ items = extract_meeting_items(
151
+ document_id, chunks, store=self.documents, auto_store=auto_store
152
+ )
153
+ return [
154
+ {
155
+ "item_id": i.item_id,
156
+ "item_type": i.item_type,
157
+ "content": i.content,
158
+ "assignee": i.assignee,
159
+ "due_date": i.due_date,
160
+ "page_number": i.page_number,
161
+ "slide_number": i.slide_number,
162
+ }
163
+ for i in items
164
+ ]
165
+
166
+ def detect_contradictions(
167
+ self,
168
+ document_ids: Optional[list[str]] = None,
169
+ min_confidence: float = 0.6,
170
+ ) -> list[dict[str, Any]]:
171
+ """Detect contradictions between documents."""
172
+ contradictions = detect_contradictions(
173
+ self.documents,
174
+ document_ids=document_ids,
175
+ min_confidence=min_confidence,
176
+ )
177
+ return [
178
+ {
179
+ "contradiction_id": c.contradiction_id,
180
+ "type": c.contradiction_type,
181
+ "description": c.description,
182
+ "document_a": c.document_a_title,
183
+ "document_b": c.document_b_title,
184
+ "confidence": c.confidence,
185
+ "page_a": c.page_a,
186
+ "page_b": c.page_b,
187
+ }
188
+ for c in contradictions
189
+ ]
190
+
191
+ def grant_access(
192
+ self, document_id: str, principal: str, permission: str, *, department: str = ""
193
+ ) -> dict[str, Any]:
194
+ """Grant ACL permission on a document.
195
+ Args:
196
+ document_id: The document ID.
197
+ principal: The user, group, or role.
198
+ permission: "read", "write", or "delete".
199
+ department: Optional department scope.
200
+ """
201
+ entry = AclEntry(
202
+ document_id=document_id,
203
+ principal=principal,
204
+ permission=permission,
205
+ department=department,
206
+ )
207
+ key = self.documents.grant_acl(entry)
208
+ return {"acl_key": key, "permission": entry.permission}
209
+
210
+ def revoke_access(self, document_id: str, principal: str, permission: str) -> dict[str, Any]:
211
+ """Revoke ACL permission on a document."""
212
+ success = self.documents.revoke_acl(document_id, principal, permission)
213
+ return {"revoked": success}
214
+
215
+ def check_access(self, document_id: str, principal: str) -> dict[str, Any]:
216
+ """Check ACL permissions for a principal on a document.
217
+ Returns a dict with boolean flags and the permissions list.
218
+ """
219
+ result = self.documents.check_acl_detailed(document_id, principal)
220
+ return {
221
+ "document_id": result.document_id,
222
+ "principal": result.principal,
223
+ "can_read": result.can_read,
224
+ "can_write": result.can_write,
225
+ "can_delete": result.can_delete,
226
+ "permissions": result.permissions,
227
+ }
228
+
229
+ def check_access_department(self, document_id: str, department: str) -> list[str]:
230
+ """Check ACL permissions for a department on a document."""
231
+ return self.documents.check_acl_department(document_id, department)
232
+
233
+ def _get_chunks(self, document_id: str) -> list:
234
+ """Get all chunks for a document."""
235
+ with self.documents._conn() as conn:
236
+ conn.row_factory = sqlite3.Row
237
+ rows = conn.execute(
238
+ "SELECT * FROM chunks WHERE document_id = ? ORDER BY chunk_index",
239
+ (document_id,),
240
+ ).fetchall()
241
+ from hakua_memory.rag.store import _row_to_chunk
242
+ return [_row_to_chunk(row) for row in rows]
243
+
244
+ def close(self) -> None:
245
+ """Close all underlying stores."""
246
+ self.ebbinghaus.close()
247
+
248
+ def export_wiki(self, wiki_root: Path) -> dict[str, Any]:
249
+ path = write_diary(wiki_root, "composite-export", "# CompositeMemory export\n")
250
+ return {"diary": str(path)}
251
+
252
+ def stats(self) -> dict[str, Any]:
253
+ return {
254
+ "ebbinghaus": self.ebbinghaus.stats(),
255
+ "semantic_graph": self.semantic.get_status_counts(),
256
+ "rag": self.documents.stats(),
257
+ }
hakua_memory/config.py ADDED
@@ -0,0 +1,168 @@
1
+ """Configuration management for hakua-memory.
2
+
3
+ Independent from Hermes Agent - manages its own config.yaml."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any, Optional
10
+
11
+ import yaml
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class EmbeddingConfig:
16
+ """Embedding backend configuration.
17
+
18
+ Supports:
19
+ - "fake": Deterministic fake backend (default, for tests)
20
+ - "llama-cpp": llama.cpp backend (requires model file)
21
+ - "openai": OpenAI-compatible API
22
+ """
23
+
24
+ backend: str = "fake" # "fake" | "llama-cpp" | "openai"
25
+ dimensions: int = 1024
26
+ serializer_version: int = 1
27
+ timeout_seconds: float = 5.0
28
+
29
+ # llama-cpp specific
30
+ model_path: str = ""
31
+ n_ctx: int = 512
32
+ n_gpu_layers: int = -1
33
+
34
+ # OpenAI-compatible specific
35
+ api_base: str = "https://api.openai.com/v1"
36
+ api_key: str = ""
37
+ model: str = "text-embedding-3-small"
38
+
39
+ def __post_init__(self) -> None:
40
+ if self.backend not in {"fake", "llama-cpp", "openai"}:
41
+ raise ValueError(f"Unknown embedding backend: {self.backend}")
42
+ if self.dimensions <= 0:
43
+ raise ValueError("embedding.dimensions must be positive")
44
+ if self.backend == "llama-cpp" and not self.model_path:
45
+ raise ValueError("embedding.model_path required for llama-cpp backend")
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ObsidianConfig:
50
+ """Obsidian export configuration."""
51
+
52
+ vault_path: str = ""
53
+ diary_template: str = ""
54
+ dream_template: str = ""
55
+ sleep_log_template: str = ""
56
+ export_diary: bool = True
57
+ export_dream: bool = True
58
+ export_graph: bool = True
59
+ export_forgetting_curve: bool = True
60
+
61
+ def __post_init__(self) -> None:
62
+ if self.vault_path and not Path(self.vault_path).exists():
63
+ # Don't raise - vault may be created later
64
+ pass
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class RagConfig:
69
+ """RAG module configuration."""
70
+
71
+ chunk_size: int = 1000
72
+ chunk_overlap: int = 200
73
+ top_k: int = 8
74
+ acl_enabled: bool = True
75
+ citation_format: str = "markdown" # "markdown" | "xml"
76
+
77
+ def __post_init__(self) -> None:
78
+ if self.chunk_size <= 0:
79
+ raise ValueError("rag.chunk_size must be positive")
80
+ if self.chunk_overlap < 0:
81
+ raise ValueError("rag.chunk_overlap must be non-negative")
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class HakuaMemoryConfig:
86
+ """Top-level configuration for hakua-memory."""
87
+
88
+ embedding: EmbeddingConfig = field(default_factory=EmbeddingConfig)
89
+ obsidian: ObsidianConfig = field(default_factory=ObsidianConfig)
90
+ rag: RagConfig = field(default_factory=RagConfig)
91
+
92
+ @classmethod
93
+ def from_yaml(cls, path: Path | str) -> HakuaMemoryConfig:
94
+ """Load configuration from YAML file."""
95
+ path = Path(path)
96
+ if not path.exists():
97
+ raise FileNotFoundError(f"Config file not found: {path}")
98
+ with open(path, "r", encoding="utf-8") as f:
99
+ data = yaml.safe_load(f) or {}
100
+ return cls.from_dict(data)
101
+
102
+ @classmethod
103
+ def from_dict(cls, data: dict[str, Any]) -> HakuaMemoryConfig:
104
+ """Create config from dictionary."""
105
+ embedding_data = data.get("embedding", {})
106
+ obsidian_data = data.get("obsidian", {})
107
+ rag_data = data.get("rag", {})
108
+
109
+ return cls(
110
+ embedding=EmbeddingConfig(**{k: v for k, v in embedding_data.items() if v is not None}),
111
+ obsidian=ObsidianConfig(**{k: v for k, v in obsidian_data.items() if v is not None}),
112
+ rag=RagConfig(**{k: v for k, v in rag_data.items() if v is not None}),
113
+ )
114
+
115
+ def to_dict(self) -> dict[str, Any]:
116
+ """Convert config to dictionary."""
117
+ return {
118
+ "embedding": {
119
+ "backend": self.embedding.backend,
120
+ "dimensions": self.embedding.dimensions,
121
+ "serializer_version": self.embedding.serializer_version,
122
+ "timeout_seconds": self.embedding.timeout_seconds,
123
+ "model_path": self.embedding.model_path,
124
+ "n_ctx": self.embedding.n_ctx,
125
+ "n_gpu_layers": self.embedding.n_gpu_layers,
126
+ "api_base": self.embedding.api_base,
127
+ "api_key": self.embedding.api_key,
128
+ "model": self.embedding.model,
129
+ },
130
+ "obsidian": {
131
+ "vault_path": self.obsidian.vault_path,
132
+ "diary_template": self.obsidian.diary_template,
133
+ "dream_template": self.obsidian.dream_template,
134
+ "sleep_log_template": self.obsidian.sleep_log_template,
135
+ "export_diary": self.obsidian.export_diary,
136
+ "export_dream": self.obsidian.export_dream,
137
+ "export_graph": self.obsidian.export_graph,
138
+ "export_forgetting_curve": self.obsidian.export_forgetting_curve,
139
+ },
140
+ "rag": {
141
+ "chunk_size": self.rag.chunk_size,
142
+ "chunk_overlap": self.rag.chunk_overlap,
143
+ "top_k": self.rag.top_k,
144
+ "acl_enabled": self.rag.acl_enabled,
145
+ "citation_format": self.rag.citation_format,
146
+ },
147
+ }
148
+
149
+ def to_yaml(self, path: Path | str) -> None:
150
+ """Save configuration to YAML file."""
151
+ path = Path(path)
152
+ path.parent.mkdir(parents=True, exist_ok=True)
153
+ with open(path, "w", encoding="utf-8") as f:
154
+ yaml.dump(self.to_dict(), f, default_flow_style=False, allow_unicode=True)
155
+
156
+
157
+ def get_default_config_path() -> Path:
158
+ """Get default config file path."""
159
+ return Path.home() / ".hakua-memory" / "config.yaml"
160
+
161
+
162
+ def load_config(path: Optional[Path] = None) -> HakuaMemoryConfig:
163
+ """Load configuration from file, or return defaults."""
164
+ if path is None:
165
+ path = get_default_config_path()
166
+ if path.exists():
167
+ return HakuaMemoryConfig.from_yaml(path)
168
+ return HakuaMemoryConfig()