hakua-memory 0.3.3__tar.gz → 0.3.4__tar.gz

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 (60) hide show
  1. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/PKG-INFO +121 -94
  2. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/README.md +115 -92
  3. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/pyproject.toml +9 -8
  4. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/__init__.py +4 -0
  5. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/store.py +1 -2
  6. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/graph.py +5 -2
  7. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/store.py +0 -1
  8. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory.egg-info/PKG-INFO +121 -94
  9. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory.egg-info/SOURCES.txt +8 -1
  10. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory.egg-info/requires.txt +5 -1
  11. hakua_memory-0.3.4/tests/test_acl.py +135 -0
  12. hakua_memory-0.3.4/tests/test_benchmark.py +43 -0
  13. hakua_memory-0.3.4/tests/test_composite.py +171 -0
  14. hakua_memory-0.3.4/tests/test_config.py +112 -0
  15. hakua_memory-0.3.4/tests/test_ebbinghaus.py +28 -0
  16. hakua_memory-0.3.4/tests/test_embedding_backend.py +98 -0
  17. hakua_memory-0.3.4/tests/test_integration.py +120 -0
  18. hakua_memory-0.3.4/tests/test_obsidian.py +90 -0
  19. hakua_memory-0.3.3/tests/test_comprehensive.py +0 -112
  20. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/LICENSE +0 -0
  21. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/setup.cfg +0 -0
  22. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/__init__.py +0 -0
  23. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/composite.py +0 -0
  24. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/config.py +0 -0
  25. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/experience.py +0 -0
  26. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/migrations.py +0 -0
  27. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/models.py +0 -0
  28. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/policies.py +0 -0
  29. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/ebbinghaus/semantic_graph_bridge.py +0 -0
  30. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/obsidian/__init__.py +0 -0
  31. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/obsidian/templates.py +0 -0
  32. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/__init__.py +0 -0
  33. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/chunking.py +0 -0
  34. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/contradiction.py +0 -0
  35. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/ingestion.py +0 -0
  36. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/meeting.py +0 -0
  37. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/models.py +0 -0
  38. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/retrieval.py +0 -0
  39. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/schema.py +0 -0
  40. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/rag/store.py +0 -0
  41. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/__init__.py +0 -0
  42. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/cli.py +0 -0
  43. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/cognitive.py +0 -0
  44. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/config.py +0 -0
  45. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/__init__.py +0 -0
  46. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/base.py +0 -0
  47. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/fake.py +0 -0
  48. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/llama_cpp.py +0 -0
  49. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/serializer.py +0 -0
  50. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/embedding/vectors.py +0 -0
  51. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/exporter.py +0 -0
  52. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/fusion.py +0 -0
  53. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/inference.py +0 -0
  54. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/models.py +0 -0
  55. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/retrieval.py +0 -0
  56. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/runtime.py +0 -0
  57. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/sanitize.py +0 -0
  58. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory/semantic_graph/schemas.py +0 -0
  59. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory.egg-info/dependency_links.txt +0 -0
  60. {hakua_memory-0.3.3 → hakua_memory-0.3.4}/src/hakua_memory.egg-info/top_level.txt +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hakua-memory
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Composite memory library: Ebbinghaus + Semantic Graph + RAG + Obsidian Wiki
5
5
  Author: Hakua
6
- License: Apache-2.0
6
+ License-Expression: Apache-2.0
7
7
  Requires-Python: <3.14,>=3.11
8
8
  Description-Content-Type: text/markdown
9
9
  License-File: LICENSE
@@ -20,7 +20,11 @@ Provides-Extra: dev
20
20
  Requires-Dist: pytest>=8; extra == "dev"
21
21
  Requires-Dist: ruff; extra == "dev"
22
22
  Provides-Extra: all
23
- Requires-Dist: pyyaml>=6; extra == "all"
23
+ Requires-Dist: gitpython<4,>=3; extra == "all"
24
+ Requires-Dist: llama-cpp-python<1,>=0.3; extra == "all"
25
+ Requires-Dist: pypdf<5,>=4; extra == "all"
26
+ Requires-Dist: python-docx<2,>=1; extra == "all"
27
+ Requires-Dist: python-pptx<2,>=1; extra == "all"
24
28
  Dynamic: license-file
25
29
 
26
30
  # hakua-memory
@@ -33,15 +37,8 @@ Dynamic: license-file
33
37
  pip install hakua-memory
34
38
  ```
35
39
 
36
- That's it. Python 3.11–3.13 supported.
37
-
38
- Optional extras:
39
-
40
- ```bash
41
- pip install "hakua-memory[rag]" # PDF/DOCX/PPTX ingestion
42
- pip install "hakua-memory[embedding]" # llama.cpp embeddings
43
- pip install "hakua-memory[obsidian]" # Obsidian helpers
44
- ```
40
+ Python 3.11–3.13 are supported. Optional integrations are listed in the
41
+ Installation section below.
45
42
 
46
43
  ## Overview
47
44
 
@@ -111,15 +108,19 @@ Optional extras:
111
108
  pip install "hakua-memory[rag]" # PDF/DOCX/PPTX ingestion
112
109
  pip install "hakua-memory[embedding]" # llama.cpp embeddings
113
110
  pip install "hakua-memory[obsidian]" # Obsidian helpers
111
+ pip install "hakua-memory[all]" # all optional integrations
114
112
  ```
115
113
 
114
+ The `all` extra is the union of the `obsidian`, `embedding`, and `rag` integration
115
+ dependencies. `pyyaml` is installed by the base package.
116
+
116
117
  ## Quick start
117
118
 
118
119
  ```python
119
120
  from pathlib import Path
120
121
  from hakua_memory import CompositeMemory
121
122
 
122
- memory = CompositeMemory(Path(".memory"))
123
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
123
124
 
124
125
  memory.remember(
125
126
  "The user prefers concise, verifiable reports.",
@@ -143,20 +144,13 @@ memory.add_node(
143
144
  }
144
145
  )
145
146
 
146
- # Add edges between nodes
147
- memory.semantic.upsert_edge({
148
- "edge_id": "edge-1",
149
- "source_node_id": "claim-1",
150
- "target_node_id": "claim-2",
151
- "edge_type": "supports",
152
- "label": "支持",
153
- "confidence": 0.8,
154
- "evidence": [],
155
- })
147
+ results = memory.search("Verifiable reporting")
148
+ print(results)
156
149
 
157
150
  print(memory.stats())
158
151
  memory.sleep()
159
- memory.export_wiki(Path("knowledge-base"))
152
+ memory.export_wiki(Path("~/.hakua-memory/wiki").expanduser())
153
+ memory.close()
160
154
  ```
161
155
 
162
156
  ## RAG Quick start
@@ -165,40 +159,28 @@ memory.export_wiki(Path("knowledge-base"))
165
159
  from pathlib import Path
166
160
  from hakua_memory import CompositeMemory
167
161
 
168
- memory = CompositeMemory(Path(".memory"))
169
-
170
- # Ingest a PDF document
171
- result = memory.ingest_document(
172
- Path("meeting_notes.pdf"),
162
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
163
+ result = memory.ingest_text(
164
+ "Decision: the release schedule is Friday. Task: Alice will confirm the schedule.",
173
165
  title="Q3 Planning Meeting",
174
166
  author="Alice",
175
167
  department="Product",
176
168
  )
177
- print(result) # {'document_id': '...', 'title': '...', 'chunks': 12, ...}
169
+ print(result)
178
170
 
179
- # Search with citation tracking
180
171
  results = memory.search_documents("release schedule", top_k=5)
181
- for r in results:
182
- print(f"[{r['rank']}] {r['document_title']} (p.{r.get('page_number')})")
183
- print(f" {r['content'][:100]}...")
184
-
185
- # Render citation context for RAG answers
186
172
  context = memory.render_citations(results, format="markdown")
187
173
  print(context)
188
174
 
189
- # Extract meeting items (decisions, tasks, action items)
190
- items = memory.extract_meeting_items(results[0]["document_id"])
175
+ items = memory.extract_meeting_items(result["document_id"])
191
176
  for item in items:
192
177
  print(f"[{item['item_type']}] {item['content']}")
193
178
 
194
- # Grant ACL access and search with filtering
195
- memory.grant_access(results[0]["document_id"], "alice", "read")
179
+ memory.grant_access(result["document_id"], "alice", "read")
196
180
  alice_results = memory.search_documents("schedule", principal="alice")
197
-
198
- # Detect contradictions between documents
199
- contradictions = memory.detect_contradictions(min_confidence=0.6)
200
- for c in contradictions:
201
- print(f"[{c['type']}] {c['description']}")
181
+ print(alice_results)
182
+ print(memory.detect_contradictions(min_confidence=0.6))
183
+ memory.close()
202
184
  ```
203
185
 
204
186
  ## Cross-source Contradiction Detection (LLM-as-Judge)
@@ -208,7 +190,7 @@ from pathlib import Path
208
190
  from hakua_memory import CompositeMemory
209
191
  from scripts.contradiction_detector import ContradictionDetector
210
192
 
211
- memory = CompositeMemory(Path(".memory"))
193
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
212
194
  detector = ContradictionDetector(memory)
213
195
 
214
196
  # Detect contradictions across all three memory systems
@@ -269,66 +251,111 @@ results = memory.search("Verifiable reporting", backend=backend)
269
251
 
270
252
  The retrieval layer validates vector dimensions, records the embedding namespace, and combines lexical and dense rankings without silently mixing incompatible representations.
271
253
 
272
- ## Performance Comparison
273
-
274
- ### Internal Benchmarks (hakua-memory v0.3.0)
275
-
276
- | Method | Library | Search Latency | Key Metric | Memory |
277
- |--------|---------|----------------|------------|--------|
278
- | **RAG** | hakua-memory | ~2.5ms/chunk | citation tracking 95% | ~50MB |
279
- | **CoG (Semantic Graph)** | hakua-memory | ~1.0ms/node | 10 edge types, relation extraction | ~30MB |
280
- | **Ebbinghaus** | hakua-memory | ~0.5ms/recall | decay curve, 6 JP vocab | ~10MB |
281
-
282
- *測定条件: Windows 11, RTX 5060 Ti 16GB, Python 3.12, no .venv*
283
- *RAG: chunk_size=100, top_k=5*
284
- *CoG: 1000 nodes, 5000 edges, 10 edge types*
285
- *Ebbinghaus: 100 recall ops avg, Japanese vocabulary*
254
+ ## Performance comparison
286
255
 
287
- ### External Library Comparison (Reference)
256
+ ### Internal reproducible measurements
288
257
 
289
- | Library | Typical Latency | Key Metric | Memory |
290
- |---------|----------------|------------|--------|
291
- | **LangChain (RAG)** | 5-50ms/chunk | vector similarity ~85% | ~100MB |
292
- | **LlamaIndex (RAG)** | 10-100ms/chunk | node similarity ~80% | ~80MB |
293
- | **PyTorch Geometric (CoG)** | 2-5ms/node | GNN convergence ~92% | ~40MB |
294
- | **NetworkX (CoG)** | 10-100ms/node | path finding ~78% | ~20MB |
295
- | **FAISS (Vector Search)** | 0.1-1ms/query | ANN ~90%+ | ~30MB |
258
+ Run the RAG chunking, semantic-graph lexical retrieval, and Ebbinghaus recall
259
+ operations with one deterministic dataset and query configuration:
296
260
 
297
- ### Statistical Summary (v0.3.0)
261
+ ```bash
262
+ python scripts/generate_synthetic_data.py \
263
+ --seed 42 \
264
+ --samples 40 \
265
+ --output synthetic_business_dataset.json
266
+ python scripts/benchmark_cross_validation.py \
267
+ --seed 42 \
268
+ --samples 40 \
269
+ --warmup 5 \
270
+ --repetitions 30 \
271
+ --output benchmark-results.json
272
+ ```
298
273
 
299
- - **Mean processing time**: 1.17ms
300
- - **Median**: 0.99ms
301
- - **Standard deviation**: ~0.9ms
302
- - **Detection power**: Cross-source contradiction detection operational
274
+ The benchmark output is machine-readable JSON containing package version, commit SHA,
275
+ timestamp, operating system, Python version, CPU, dataset id, seed, sample count, warmup
276
+ count, repetition count, and mean, median, standard deviation, p50, p95, and p99 latency
277
+ for every measured operation. No GPU is used by this harness. Generated JSON, SQLite
278
+ state, and temporary benchmark databases are not version-controlled;
279
+ `benchmarks/synthetic_dataset_config.json` records the dataset recipe and expected
280
+ summary.
303
281
 
304
- ### Evaluation Notes
282
+ Only measurements produced by this repository's harness should be described as internal
283
+ results. Values depend on the recorded machine, dataset, seed, warmup, and repetitions.
305
284
 
306
- - Measurements: Windows 11, RTX 5060 Ti 16GB, Python 3.12
307
- - RAG: chunk_size=100, top_k=5
308
- - CoG: 10 edge types (causes, contradicts, supports, requires, enables, prevents, relates_to, part_of, precedes, follows)
309
- - Ebbinghaus: Japanese vocabulary (HERMES_AGENT, OPENCLAW, VRChat_HARNESS, VOICEVOX, MEMORY, POLICY_GUARD, AUDIT_LOG)
285
+ ### Cross-library validation on the same hardware
310
286
 
311
- ## Multi-seed Multi-domain Training
287
+ The optional comparison harness uses the same corpus, query set, warmup count, repetition
288
+ count, and randomized variant order for every paired measurement. It compares RAG
289
+ chunking with LangChain's `RecursiveCharacterTextSplitter` and LlamaIndex's
290
+ `SentenceSplitter`, and compares the Semantic Graph lexical query path with
291
+ `rank-bm25`'s `BM25Okapi`. The comparison is limited to those operations; it is not a
292
+ claim about complete RAG quality, end-to-end agent latency, memory use, or GPU speed.
312
293
 
313
- `hakua-memory` includes tooling for generating and training on synthetic multi-domain datasets:
294
+ Create a separate environment and run the comparison as follows:
314
295
 
315
296
  ```bash
316
- # Generate synthetic datasets (10 seeds × 7 domains × bilingual)
317
- python scripts/generate_synthetic_data.py
318
-
319
- # Run cross-validation benchmarks
320
- python scripts/benchmark_cross_validation.py
321
-
322
- # Run contradiction detection
323
- python scripts/contradiction_detector.py
324
- python scripts/hermes_llm_judge.py
297
+ python -m venv .venv-benchmark
298
+ # Activate .venv-benchmark for your shell, then run:
299
+ python -m pip install -e .
300
+ python -m pip install -r benchmarks/requirements.txt
301
+ python scripts/generate_synthetic_data.py --seed 42 --samples 40 --output synthetic_business_dataset.json
302
+ python scripts/benchmark_external_libraries.py --seed 42 --samples 40 --warmup 5 --repetitions 30 --output benchmark-results-external.json --plot benchmark-errorbars.png
325
303
  ```
326
304
 
327
- **Dataset Coverage (v0.3.0):**
328
- - 10 seeds (42, 123, 456, 789, 999, 111, 222, 333, 444, 555)
329
- - 7 domains: Finance, Technology, Healthcare, Manufacturing, Retail, Legal, HR
330
- - 15 keywords/domain × bilingual (JP/EN) = 11,200 entries
331
- - 10 independent memory instances trained
305
+ The comparison JSON records exact library versions, host metadata, configurations, raw
306
+ paired durations, mean, median, standard deviation, p50, p95, p99, and a 95% confidence
307
+ interval for each variant. It also records the two-sided paired Wilcoxon signed-rank
308
+ test, paired t-test sensitivity result, and Holm-adjusted Wilcoxon p-value across the
309
+ three comparisons. The PNG uses mean latency with 95% confidence-interval error bars.
310
+ The validation section separately records non-empty chunk output and expected top-k hit
311
+ rate, so latency and retrieval-result checks are not conflated.
312
+
313
+ The chunkers use their native length units, which are recorded in the JSON; equal numeric
314
+ chunk-size arguments therefore do not mean equal chunk boundaries. The lexical comparison
315
+ also compares SQLite-backed graph search with an in-memory BM25 index. These scope limits
316
+ are required for an honest cross-library measurement.
317
+
318
+ The following is one recorded run from commit `e2bbb3c8bfd3bbfcd7a5e508a757917919dd5e89`
319
+ on Windows 11 with Python 3.12.13 and an AMD64 Family 23 Model 96 CPU. It used
320
+ `synthetic-business-v1`, seed 42, 40 samples, 40 queries, warmup 5, and 30 paired
321
+ repetitions. Latencies are milliseconds per operation; the confidence interval is 95% CI
322
+ for the mean.
323
+
324
+ | Operation | Variant | Mean | Median | Stdev | P95 | 95% CI |
325
+ |---|---|---:|---:|---:|---:|---:|
326
+ | RAG chunking | hakua-memory | 0.6312 | 0.5901 | 0.1184 | 0.8746 | 0.5870–0.6754 |
327
+ | RAG chunking | LangChain Text Splitters 1.1.2 | 0.0694 | 0.0681 | 0.0144 | 0.0854 | 0.0640–0.0747 |
328
+ | RAG chunking | LlamaIndex Core 0.14.24 | 1.8174 | 1.6806 | 0.3354 | 2.4531 | 1.6921–1.9426 |
329
+ | Lexical retrieval, 40-query batch | hakua-memory | 264.2875 | 155.3723 | 487.9654 | 397.6564 | 82.0782–446.4968 |
330
+ | Lexical retrieval, 40-query batch | rank-bm25 0.2.2 | 2.5974 | 2.4707 | 0.3772 | 3.0580 | 2.4566–2.7382 |
331
+
332
+ The paired two-sided Wilcoxon signed-rank p-values were `1.862645149e-09` for each
333
+ comparison. Holm-adjusted values across the three comparisons were `5.587935448e-09`
334
+ for each comparison. Paired t-test sensitivity p-values were `1.387202830e-21` for
335
+ LangChain, `4.399465113e-19` for LlamaIndex, and `0.006427546` for rank-bm25. These
336
+ p-values describe this paired latency sample only; they are not accuracy claims or proof
337
+ of general library superiority.
338
+
339
+ The dataset-specific validation found non-empty chunk output for all variants. The
340
+ expected exact-record hit rate at top-k=5 was 33/40 (82.5%) for hakua-memory and 38/40
341
+ (95.0%) for rank-bm25. This is a small synthetic query-set check, not a benchmark of
342
+ retrieval quality across domains. The generated JSON and error-bar PNG are intentionally
343
+ kept outside Git; rerun the command above to reproduce them on another machine.
344
+
345
+ ### External references
346
+
347
+ The measured comparison uses [LangChain Text Splitters](https://docs.langchain.com/oss/python/integrations/splitters/recursive_text_splitter),
348
+ [LlamaIndex SentenceSplitter](https://docs.llamaindex.ai/en/stable/module_guides/loading/node_parsers/modules.html),
349
+ and [rank-bm25](https://pypi.org/project/rank-bm25/), with versions pinned in
350
+ `benchmarks/requirements.txt`. NetworkX, PyTorch Geometric, and FAISS remain external
351
+ references only; this repository does not publish direct measurements for them.
352
+
353
+ ## Reproducible synthetic data
354
+
355
+ The generator is deterministic for a given seed and sample count. Its schema version,
356
+ generator version, defaults, and expected summary are recorded in
357
+ `benchmarks/synthetic_dataset_config.json`. Use a different output path when retaining
358
+ multiple datasets; generated files remain ignored by Git.
332
359
 
333
360
  ## Architecture
334
361
 
@@ -8,15 +8,8 @@
8
8
  pip install hakua-memory
9
9
  ```
10
10
 
11
- That's it. Python 3.11–3.13 supported.
12
-
13
- Optional extras:
14
-
15
- ```bash
16
- pip install "hakua-memory[rag]" # PDF/DOCX/PPTX ingestion
17
- pip install "hakua-memory[embedding]" # llama.cpp embeddings
18
- pip install "hakua-memory[obsidian]" # Obsidian helpers
19
- ```
11
+ Python 3.11–3.13 are supported. Optional integrations are listed in the
12
+ Installation section below.
20
13
 
21
14
  ## Overview
22
15
 
@@ -86,15 +79,19 @@ Optional extras:
86
79
  pip install "hakua-memory[rag]" # PDF/DOCX/PPTX ingestion
87
80
  pip install "hakua-memory[embedding]" # llama.cpp embeddings
88
81
  pip install "hakua-memory[obsidian]" # Obsidian helpers
82
+ pip install "hakua-memory[all]" # all optional integrations
89
83
  ```
90
84
 
85
+ The `all` extra is the union of the `obsidian`, `embedding`, and `rag` integration
86
+ dependencies. `pyyaml` is installed by the base package.
87
+
91
88
  ## Quick start
92
89
 
93
90
  ```python
94
91
  from pathlib import Path
95
92
  from hakua_memory import CompositeMemory
96
93
 
97
- memory = CompositeMemory(Path(".memory"))
94
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
98
95
 
99
96
  memory.remember(
100
97
  "The user prefers concise, verifiable reports.",
@@ -118,20 +115,13 @@ memory.add_node(
118
115
  }
119
116
  )
120
117
 
121
- # Add edges between nodes
122
- memory.semantic.upsert_edge({
123
- "edge_id": "edge-1",
124
- "source_node_id": "claim-1",
125
- "target_node_id": "claim-2",
126
- "edge_type": "supports",
127
- "label": "支持",
128
- "confidence": 0.8,
129
- "evidence": [],
130
- })
118
+ results = memory.search("Verifiable reporting")
119
+ print(results)
131
120
 
132
121
  print(memory.stats())
133
122
  memory.sleep()
134
- memory.export_wiki(Path("knowledge-base"))
123
+ memory.export_wiki(Path("~/.hakua-memory/wiki").expanduser())
124
+ memory.close()
135
125
  ```
136
126
 
137
127
  ## RAG Quick start
@@ -140,40 +130,28 @@ memory.export_wiki(Path("knowledge-base"))
140
130
  from pathlib import Path
141
131
  from hakua_memory import CompositeMemory
142
132
 
143
- memory = CompositeMemory(Path(".memory"))
144
-
145
- # Ingest a PDF document
146
- result = memory.ingest_document(
147
- Path("meeting_notes.pdf"),
133
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
134
+ result = memory.ingest_text(
135
+ "Decision: the release schedule is Friday. Task: Alice will confirm the schedule.",
148
136
  title="Q3 Planning Meeting",
149
137
  author="Alice",
150
138
  department="Product",
151
139
  )
152
- print(result) # {'document_id': '...', 'title': '...', 'chunks': 12, ...}
140
+ print(result)
153
141
 
154
- # Search with citation tracking
155
142
  results = memory.search_documents("release schedule", top_k=5)
156
- for r in results:
157
- print(f"[{r['rank']}] {r['document_title']} (p.{r.get('page_number')})")
158
- print(f" {r['content'][:100]}...")
159
-
160
- # Render citation context for RAG answers
161
143
  context = memory.render_citations(results, format="markdown")
162
144
  print(context)
163
145
 
164
- # Extract meeting items (decisions, tasks, action items)
165
- items = memory.extract_meeting_items(results[0]["document_id"])
146
+ items = memory.extract_meeting_items(result["document_id"])
166
147
  for item in items:
167
148
  print(f"[{item['item_type']}] {item['content']}")
168
149
 
169
- # Grant ACL access and search with filtering
170
- memory.grant_access(results[0]["document_id"], "alice", "read")
150
+ memory.grant_access(result["document_id"], "alice", "read")
171
151
  alice_results = memory.search_documents("schedule", principal="alice")
172
-
173
- # Detect contradictions between documents
174
- contradictions = memory.detect_contradictions(min_confidence=0.6)
175
- for c in contradictions:
176
- print(f"[{c['type']}] {c['description']}")
152
+ print(alice_results)
153
+ print(memory.detect_contradictions(min_confidence=0.6))
154
+ memory.close()
177
155
  ```
178
156
 
179
157
  ## Cross-source Contradiction Detection (LLM-as-Judge)
@@ -183,7 +161,7 @@ from pathlib import Path
183
161
  from hakua_memory import CompositeMemory
184
162
  from scripts.contradiction_detector import ContradictionDetector
185
163
 
186
- memory = CompositeMemory(Path(".memory"))
164
+ memory = CompositeMemory(Path("~/.hakua-memory").expanduser())
187
165
  detector = ContradictionDetector(memory)
188
166
 
189
167
  # Detect contradictions across all three memory systems
@@ -244,66 +222,111 @@ results = memory.search("Verifiable reporting", backend=backend)
244
222
 
245
223
  The retrieval layer validates vector dimensions, records the embedding namespace, and combines lexical and dense rankings without silently mixing incompatible representations.
246
224
 
247
- ## Performance Comparison
248
-
249
- ### Internal Benchmarks (hakua-memory v0.3.0)
250
-
251
- | Method | Library | Search Latency | Key Metric | Memory |
252
- |--------|---------|----------------|------------|--------|
253
- | **RAG** | hakua-memory | ~2.5ms/chunk | citation tracking 95% | ~50MB |
254
- | **CoG (Semantic Graph)** | hakua-memory | ~1.0ms/node | 10 edge types, relation extraction | ~30MB |
255
- | **Ebbinghaus** | hakua-memory | ~0.5ms/recall | decay curve, 6 JP vocab | ~10MB |
256
-
257
- *測定条件: Windows 11, RTX 5060 Ti 16GB, Python 3.12, no .venv*
258
- *RAG: chunk_size=100, top_k=5*
259
- *CoG: 1000 nodes, 5000 edges, 10 edge types*
260
- *Ebbinghaus: 100 recall ops avg, Japanese vocabulary*
225
+ ## Performance comparison
261
226
 
262
- ### External Library Comparison (Reference)
227
+ ### Internal reproducible measurements
263
228
 
264
- | Library | Typical Latency | Key Metric | Memory |
265
- |---------|----------------|------------|--------|
266
- | **LangChain (RAG)** | 5-50ms/chunk | vector similarity ~85% | ~100MB |
267
- | **LlamaIndex (RAG)** | 10-100ms/chunk | node similarity ~80% | ~80MB |
268
- | **PyTorch Geometric (CoG)** | 2-5ms/node | GNN convergence ~92% | ~40MB |
269
- | **NetworkX (CoG)** | 10-100ms/node | path finding ~78% | ~20MB |
270
- | **FAISS (Vector Search)** | 0.1-1ms/query | ANN ~90%+ | ~30MB |
229
+ Run the RAG chunking, semantic-graph lexical retrieval, and Ebbinghaus recall
230
+ operations with one deterministic dataset and query configuration:
271
231
 
272
- ### Statistical Summary (v0.3.0)
232
+ ```bash
233
+ python scripts/generate_synthetic_data.py \
234
+ --seed 42 \
235
+ --samples 40 \
236
+ --output synthetic_business_dataset.json
237
+ python scripts/benchmark_cross_validation.py \
238
+ --seed 42 \
239
+ --samples 40 \
240
+ --warmup 5 \
241
+ --repetitions 30 \
242
+ --output benchmark-results.json
243
+ ```
273
244
 
274
- - **Mean processing time**: 1.17ms
275
- - **Median**: 0.99ms
276
- - **Standard deviation**: ~0.9ms
277
- - **Detection power**: Cross-source contradiction detection operational
245
+ The benchmark output is machine-readable JSON containing package version, commit SHA,
246
+ timestamp, operating system, Python version, CPU, dataset id, seed, sample count, warmup
247
+ count, repetition count, and mean, median, standard deviation, p50, p95, and p99 latency
248
+ for every measured operation. No GPU is used by this harness. Generated JSON, SQLite
249
+ state, and temporary benchmark databases are not version-controlled;
250
+ `benchmarks/synthetic_dataset_config.json` records the dataset recipe and expected
251
+ summary.
278
252
 
279
- ### Evaluation Notes
253
+ Only measurements produced by this repository's harness should be described as internal
254
+ results. Values depend on the recorded machine, dataset, seed, warmup, and repetitions.
280
255
 
281
- - Measurements: Windows 11, RTX 5060 Ti 16GB, Python 3.12
282
- - RAG: chunk_size=100, top_k=5
283
- - CoG: 10 edge types (causes, contradicts, supports, requires, enables, prevents, relates_to, part_of, precedes, follows)
284
- - Ebbinghaus: Japanese vocabulary (HERMES_AGENT, OPENCLAW, VRChat_HARNESS, VOICEVOX, MEMORY, POLICY_GUARD, AUDIT_LOG)
256
+ ### Cross-library validation on the same hardware
285
257
 
286
- ## Multi-seed Multi-domain Training
258
+ The optional comparison harness uses the same corpus, query set, warmup count, repetition
259
+ count, and randomized variant order for every paired measurement. It compares RAG
260
+ chunking with LangChain's `RecursiveCharacterTextSplitter` and LlamaIndex's
261
+ `SentenceSplitter`, and compares the Semantic Graph lexical query path with
262
+ `rank-bm25`'s `BM25Okapi`. The comparison is limited to those operations; it is not a
263
+ claim about complete RAG quality, end-to-end agent latency, memory use, or GPU speed.
287
264
 
288
- `hakua-memory` includes tooling for generating and training on synthetic multi-domain datasets:
265
+ Create a separate environment and run the comparison as follows:
289
266
 
290
267
  ```bash
291
- # Generate synthetic datasets (10 seeds × 7 domains × bilingual)
292
- python scripts/generate_synthetic_data.py
293
-
294
- # Run cross-validation benchmarks
295
- python scripts/benchmark_cross_validation.py
296
-
297
- # Run contradiction detection
298
- python scripts/contradiction_detector.py
299
- python scripts/hermes_llm_judge.py
268
+ python -m venv .venv-benchmark
269
+ # Activate .venv-benchmark for your shell, then run:
270
+ python -m pip install -e .
271
+ python -m pip install -r benchmarks/requirements.txt
272
+ python scripts/generate_synthetic_data.py --seed 42 --samples 40 --output synthetic_business_dataset.json
273
+ python scripts/benchmark_external_libraries.py --seed 42 --samples 40 --warmup 5 --repetitions 30 --output benchmark-results-external.json --plot benchmark-errorbars.png
300
274
  ```
301
275
 
302
- **Dataset Coverage (v0.3.0):**
303
- - 10 seeds (42, 123, 456, 789, 999, 111, 222, 333, 444, 555)
304
- - 7 domains: Finance, Technology, Healthcare, Manufacturing, Retail, Legal, HR
305
- - 15 keywords/domain × bilingual (JP/EN) = 11,200 entries
306
- - 10 independent memory instances trained
276
+ The comparison JSON records exact library versions, host metadata, configurations, raw
277
+ paired durations, mean, median, standard deviation, p50, p95, p99, and a 95% confidence
278
+ interval for each variant. It also records the two-sided paired Wilcoxon signed-rank
279
+ test, paired t-test sensitivity result, and Holm-adjusted Wilcoxon p-value across the
280
+ three comparisons. The PNG uses mean latency with 95% confidence-interval error bars.
281
+ The validation section separately records non-empty chunk output and expected top-k hit
282
+ rate, so latency and retrieval-result checks are not conflated.
283
+
284
+ The chunkers use their native length units, which are recorded in the JSON; equal numeric
285
+ chunk-size arguments therefore do not mean equal chunk boundaries. The lexical comparison
286
+ also compares SQLite-backed graph search with an in-memory BM25 index. These scope limits
287
+ are required for an honest cross-library measurement.
288
+
289
+ The following is one recorded run from commit `e2bbb3c8bfd3bbfcd7a5e508a757917919dd5e89`
290
+ on Windows 11 with Python 3.12.13 and an AMD64 Family 23 Model 96 CPU. It used
291
+ `synthetic-business-v1`, seed 42, 40 samples, 40 queries, warmup 5, and 30 paired
292
+ repetitions. Latencies are milliseconds per operation; the confidence interval is 95% CI
293
+ for the mean.
294
+
295
+ | Operation | Variant | Mean | Median | Stdev | P95 | 95% CI |
296
+ |---|---|---:|---:|---:|---:|---:|
297
+ | RAG chunking | hakua-memory | 0.6312 | 0.5901 | 0.1184 | 0.8746 | 0.5870–0.6754 |
298
+ | RAG chunking | LangChain Text Splitters 1.1.2 | 0.0694 | 0.0681 | 0.0144 | 0.0854 | 0.0640–0.0747 |
299
+ | RAG chunking | LlamaIndex Core 0.14.24 | 1.8174 | 1.6806 | 0.3354 | 2.4531 | 1.6921–1.9426 |
300
+ | Lexical retrieval, 40-query batch | hakua-memory | 264.2875 | 155.3723 | 487.9654 | 397.6564 | 82.0782–446.4968 |
301
+ | Lexical retrieval, 40-query batch | rank-bm25 0.2.2 | 2.5974 | 2.4707 | 0.3772 | 3.0580 | 2.4566–2.7382 |
302
+
303
+ The paired two-sided Wilcoxon signed-rank p-values were `1.862645149e-09` for each
304
+ comparison. Holm-adjusted values across the three comparisons were `5.587935448e-09`
305
+ for each comparison. Paired t-test sensitivity p-values were `1.387202830e-21` for
306
+ LangChain, `4.399465113e-19` for LlamaIndex, and `0.006427546` for rank-bm25. These
307
+ p-values describe this paired latency sample only; they are not accuracy claims or proof
308
+ of general library superiority.
309
+
310
+ The dataset-specific validation found non-empty chunk output for all variants. The
311
+ expected exact-record hit rate at top-k=5 was 33/40 (82.5%) for hakua-memory and 38/40
312
+ (95.0%) for rank-bm25. This is a small synthetic query-set check, not a benchmark of
313
+ retrieval quality across domains. The generated JSON and error-bar PNG are intentionally
314
+ kept outside Git; rerun the command above to reproduce them on another machine.
315
+
316
+ ### External references
317
+
318
+ The measured comparison uses [LangChain Text Splitters](https://docs.langchain.com/oss/python/integrations/splitters/recursive_text_splitter),
319
+ [LlamaIndex SentenceSplitter](https://docs.llamaindex.ai/en/stable/module_guides/loading/node_parsers/modules.html),
320
+ and [rank-bm25](https://pypi.org/project/rank-bm25/), with versions pinned in
321
+ `benchmarks/requirements.txt`. NetworkX, PyTorch Geometric, and FAISS remain external
322
+ references only; this repository does not publish direct measurements for them.
323
+
324
+ ## Reproducible synthetic data
325
+
326
+ The generator is deterministic for a given seed and sample count. Its schema version,
327
+ generator version, defaults, and expected summary are recorded in
328
+ `benchmarks/synthetic_dataset_config.json`. Use a different output path when retaining
329
+ multiple datasets; generated files remain ignored by Git.
307
330
 
308
331
  ## Architecture
309
332
 
@@ -360,4 +383,4 @@ The integration path can be exercised with a temporary directory and the determi
360
383
 
361
384
  ## License
362
385
 
363
- Apache License 2.0. See [LICENSE](LICENSE).
386
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "hakua-memory"
7
- version = "0.3.3"
7
+ version = "0.3.4"
8
8
  description = "Composite memory library: Ebbinghaus + Semantic Graph + RAG + Obsidian Wiki"
9
9
  readme = "README.md"
10
- license = {text = "Apache-2.0"}
10
+ license = "Apache-2.0"
11
11
  requires-python = ">=3.11,<3.14"
12
12
  authors = [{name = "Hakua"}]
13
13
  dependencies = ["pyyaml>=6"]
@@ -21,7 +21,13 @@ rag = [
21
21
  "python-pptx>=1,<2",
22
22
  ]
23
23
  dev = ["pytest>=8", "ruff"]
24
- all = ["pyyaml>=6"]
24
+ all = [
25
+ "gitpython>=3,<4",
26
+ "llama-cpp-python>=0.3,<1",
27
+ "pypdf>=4,<5",
28
+ "python-docx>=1,<2",
29
+ "python-pptx>=1,<2",
30
+ ]
25
31
 
26
32
  [tool.setuptools.packages.find]
27
33
  where = ["src"]
@@ -33,8 +39,3 @@ target-version = "py311"
33
39
  [tool.ruff.lint]
34
40
  select = ["E", "F", "W", "I"]
35
41
  ignore = ["E501"]
36
-
37
- [tool.ruff.lint.per-file-ignores]
38
- "scripts/*.py" = ["E402"]
39
- "src/hakua_memory/semantic_graph/**/*.py" = ["F821", "F841", "F401", "E402"]
40
- "src/hakua_memory/ebbinghaus/**/*.py" = ["F821", "F841", "F401", "E402"]
@@ -30,6 +30,10 @@ except ImportError:
30
30
 
31
31
  logger = logging.getLogger(__name__)
32
32
 
33
+
34
+ def tool_error(message: str) -> str:
35
+ return json.dumps({"error": str(message)}, ensure_ascii=False)
36
+
33
37
  __all__ = [
34
38
  "CapacityError",
35
39
  "EbbinghausMemoryProvider",
@@ -22,7 +22,7 @@ from pathlib import Path
22
22
  from typing import Any, Callable, Iterable, Mapping, Sequence
23
23
 
24
24
  from .experience import EbbinghausExperienceLedger, normalize_query_hash
25
- from .models import RecallAttemptResult, RetrievalOutcome
25
+ from .models import RecallAttemptResult, RetrievalOutcome, RevisionResult
26
26
  from .policies import EbbinghausPolicies, is_protected, resolve_prune_mode
27
27
 
28
28
  logger = logging.getLogger(__name__)
@@ -1676,7 +1676,6 @@ class EbbinghausMemoryStore:
1676
1676
  max_negative_sleep_rehearsals: int | None = None,
1677
1677
  ) -> dict:
1678
1678
  sp = self.policies.sleep
1679
- cp = self.policies.capacity
1680
1679
 
1681
1680
  rehearse_threshold = _clamp(
1682
1681
  float(sp.rehearse_threshold if rehearse_threshold is None else rehearse_threshold),