kausamemory 2.1.0__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 (33) hide show
  1. kausamemory-2.1.0/LICENSE +201 -0
  2. kausamemory-2.1.0/PKG-INFO +29 -0
  3. kausamemory-2.1.0/README.md +304 -0
  4. kausamemory-2.1.0/kausamemory/__init__.py +0 -0
  5. kausamemory-2.1.0/kausamemory/config.py +31 -0
  6. kausamemory-2.1.0/kausamemory/crypto/__init__.py +0 -0
  7. kausamemory-2.1.0/kausamemory/crypto/encryption.py +36 -0
  8. kausamemory-2.1.0/kausamemory/crypto/sync.py +181 -0
  9. kausamemory-2.1.0/kausamemory/engine/__init__.py +0 -0
  10. kausamemory-2.1.0/kausamemory/engine/classifier.py +37 -0
  11. kausamemory-2.1.0/kausamemory/engine/core.py +509 -0
  12. kausamemory-2.1.0/kausamemory/engine/extractor.py +188 -0
  13. kausamemory-2.1.0/kausamemory/engine/retriever.py +200 -0
  14. kausamemory-2.1.0/kausamemory/interfaces/__init__.py +0 -0
  15. kausamemory-2.1.0/kausamemory/interfaces/mcp_server.py +107 -0
  16. kausamemory-2.1.0/kausamemory/providers/__init__.py +0 -0
  17. kausamemory-2.1.0/kausamemory/providers/embedder.py +18 -0
  18. kausamemory-2.1.0/kausamemory/providers/llm.py +82 -0
  19. kausamemory-2.1.0/kausamemory/stores/__init__.py +0 -0
  20. kausamemory-2.1.0/kausamemory/stores/database.py +240 -0
  21. kausamemory-2.1.0/kausamemory/stores/decisions.py +46 -0
  22. kausamemory-2.1.0/kausamemory/stores/episodes.py +77 -0
  23. kausamemory-2.1.0/kausamemory/stores/graph.py +135 -0
  24. kausamemory-2.1.0/kausamemory/stores/profile.py +86 -0
  25. kausamemory-2.1.0/kausamemory/stores/vectors.py +115 -0
  26. kausamemory-2.1.0/kausamemory.egg-info/PKG-INFO +29 -0
  27. kausamemory-2.1.0/kausamemory.egg-info/SOURCES.txt +31 -0
  28. kausamemory-2.1.0/kausamemory.egg-info/dependency_links.txt +1 -0
  29. kausamemory-2.1.0/kausamemory.egg-info/entry_points.txt +2 -0
  30. kausamemory-2.1.0/kausamemory.egg-info/requires.txt +12 -0
  31. kausamemory-2.1.0/kausamemory.egg-info/top_level.txt +1 -0
  32. kausamemory-2.1.0/pyproject.toml +44 -0
  33. kausamemory-2.1.0/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: kausamemory
3
+ Version: 2.1.0
4
+ Summary: Persistent encrypted memory for AI agents. Knowledge graph, vector search, decision tracking, encrypted IPFS backup.
5
+ Author-email: KausaLayer <kausalayer@proton.me>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://kausalayer.com
8
+ Project-URL: Repository, https://github.com/fasqua/kausamemory-v2
9
+ Keywords: ai,agent,memory,mcp,knowledge-graph,solana,encryption,ipfs
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ License-File: LICENSE
19
+ Requires-Dist: fastembed>=0.4.0
20
+ Requires-Dist: numpy>=1.24.0
21
+ Requires-Dist: httpx>=0.27.0
22
+ Requires-Dist: cryptography>=43.0.0
23
+ Requires-Dist: mcp>=1.0.0
24
+ Requires-Dist: pydantic>=2.0.0
25
+ Provides-Extra: openai
26
+ Requires-Dist: openai>=1.0.0; extra == "openai"
27
+ Provides-Extra: anthropic
28
+ Requires-Dist: anthropic>=0.30.0; extra == "anthropic"
29
+ Dynamic: license-file
@@ -0,0 +1,304 @@
1
+ # KausaMemory v2
2
+
3
+ Persistent encrypted memory for AI agents. Knowledge graph, vector search, decision tracking, user profiling, and encrypted IPFS backup — in a single SQLite file.
4
+
5
+ Built by [KausaLayer](https://kausalayer.com) — privacy infrastructure for Solana.
6
+
7
+ ![Architecture](./kausamemory-v2-architecture.png)
8
+
9
+ ## Why KausaMemory
10
+
11
+ Your AI agent forgets everything between sessions. KausaMemory fixes that.
12
+
13
+ Every conversation is automatically broken down into entities, relationships, decisions, and user traits — stored in a local knowledge graph, encrypted with your passphrase, and backed up to IPFS. Switch devices, delete your database, reinstall — your agent's memory comes back.
14
+
15
+ No cloud vendor holds your data. No one can read it. Just you and your passphrase.
16
+
17
+ ## Features
18
+
19
+ **Knowledge Graph** — entities with typed properties, relationships with temporal validity, recursive CTE traversal, upsert with dedup, contradiction detection against existing entities
20
+
21
+ **Decision Tracking** — decision ledger with reason and topic, supersede chain when decisions change, active/inactive filtering
22
+
23
+ **User Profiling** — auto-extracted from conversations across 5 categories (identity, preferences, expertise, workflow, personality) with confidence scoring and boost-on-confirm
24
+
25
+ **Vector Search** — numpy vectorized batch cosine similarity, pre-normalized matrix cache, lazy rebuild, configurable min_similarity threshold (default 0.3)
26
+
27
+ **Full-Text Search** — 4 FTS5 virtual tables (episodes, entities, decisions, user_profile) with sanitized queries and LIKE fallback
28
+
29
+ **Tiered Retrieval** — brief (~100 tokens, top 3), summary (~500 tokens, top 5), or full (unlimited, top 10) per query
30
+
31
+ **4-Strategy Classification** — temporal (time keywords), reasoning (why/because), summary (everything/overview), hybrid (default: vector + graph + FTS)
32
+
33
+ **Multi-Agent Namespaces** — each namespace gets its own SQLite database, optional cross-agent shared read (read-only)
34
+
35
+ **Encrypted IPFS Backup** — AES-256-GCM with passphrase-derived key, 12-byte random nonce, Pinata IPFS pinning, CID persisted to local file before unpinning old snapshot
36
+
37
+ **Safety Checks** — refuses to sync empty databases (prevents overwriting good IPFS snapshots), auto-sync every 5 stores, background sync loop every 120s
38
+
39
+ ## Current Status
40
+
41
+ KausaMemory v2 is functional and tested with Hermes Agent. It is not yet published on PyPI. To use it, clone this repo and install in editable mode.
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ git clone https://github.com/fasqua/kausamemory-v2.git
47
+ cd kausamemory-v2
48
+ pip install -e .
49
+ ```
50
+
51
+ Required environment variables:
52
+
53
+ ```bash
54
+ export MEMORY_PASSPHRASE="your-secret-passphrase"
55
+ export PINATA_API_KEY="your-pinata-key"
56
+ ```
57
+
58
+ Optional (enables LLM extraction of entities, decisions, traits):
59
+
60
+ ```bash
61
+ export LLM_API_KEY="your-api-key"
62
+ export LLM_PROVIDER="openrouter" # or "openai" or "anthropic"
63
+ export LLM_MODEL="anthropic/claude-sonnet-4"
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ### As MCP Server
69
+
70
+ The MCP server provides 6 tools to any compatible client (Claude Desktop, Cursor, VS Code, Cline).
71
+
72
+ Add to your MCP client config:
73
+
74
+ ```json
75
+ {
76
+ "kausamemory": {
77
+ "command": "kausamemory-mcp",
78
+ "env": {
79
+ "MEMORY_PASSPHRASE": "your-secret-passphrase",
80
+ "PINATA_API_KEY": "your-pinata-key"
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ **MCP Tools:**
87
+
88
+ | Tool | Description |
89
+ |------|-------------|
90
+ | `memory_retrieve` | Retrieve context before responding. Supports depth: brief, summary, full |
91
+ | `memory_store` | Store conversation with auto-extraction of entities, decisions, traits |
92
+ | `memory_search` | Search by type: all (semantic), facts (graph), timeline (episodes), decisions, text (FTS5), profile |
93
+ | `memory_forget` | Remove entities, decisions, or profile entries by name/topic/key |
94
+ | `memory_status` | Memory health: entity count, relationships, episodes, decisions, embeddings, profile entries |
95
+ | `memory_sync` | Force encrypted backup to IPFS |
96
+
97
+ ### As Hermes Agent Plugin
98
+
99
+ KausaMemory integrates as a native Hermes memory provider with full ABC implementation. The plugin auto-prefetches context before each turn, auto-stores after each turn, injects memory stats into the system prompt, and syncs to IPFS on session end.
100
+
101
+ ```yaml
102
+ # ~/.hermes/config.yaml
103
+ memory:
104
+ provider: kausamemory
105
+ ```
106
+
107
+ ```bash
108
+ # ~/.hermes/.env
109
+ MEMORY_PASSPHRASE=your-secret-passphrase
110
+ PINATA_API_KEY=your-pinata-key
111
+ LLM_API_KEY=your-llm-key
112
+ LLM_PROVIDER=openrouter
113
+ LLM_MODEL=anthropic/claude-sonnet-4
114
+ ```
115
+
116
+ The Hermes plugin exposes 7 tools (the 6 MCP tools plus `kausamemory_reconnect` for refreshing the DB connection after external restores).
117
+
118
+ ### As Python Library
119
+
120
+ ```python
121
+ import asyncio
122
+ from kausamemory.engine.core import MemoryEngine
123
+
124
+ # Initialize — all config from environment variables
125
+ engine = MemoryEngine(namespace="my-agent")
126
+
127
+ # Store a conversation (async — triggers LLM extraction if LLM_API_KEY set)
128
+ result = asyncio.run(engine.store(
129
+ "I prefer using Rust for backend development",
130
+ "Noted, Rust is great for performance-critical systems."
131
+ ))
132
+ # Returns: {'stored': True, 'entities': 2, 'relationships': 1, 'decisions': 0, 'traits': 1}
133
+ # Without LLM_API_KEY: {'stored': True, 'mode': 'embedding_only'}
134
+
135
+ # Retrieve context (sync — returns formatted string)
136
+ context = engine.retrieve("What language do I prefer?", depth="summary")
137
+
138
+ # Search knowledge graph
139
+ entities = engine.search_entities(name="Rust") # returns list[dict]
140
+ decisions = engine.search_decisions("backend") # returns list[dict]
141
+ episodes = engine.search_text("Rust") # returns list[dict]
142
+ similar = engine.search_similar("programming language") # returns list[dict]
143
+
144
+ # Generic search (returns formatted string)
145
+ result = engine.search("Rust", type="facts", limit=5)
146
+
147
+ # User profile
148
+ engine.set_profile("language", "Rust", "expertise", 0.9)
149
+ profile = engine.get_profile("expertise") # returns list[dict]
150
+ all_profile = engine.get_profile() # all entries
151
+
152
+ # Forget
153
+ engine.forget_entity("SomeEntity") # returns int (count removed)
154
+ engine.forget_decision("old-topic") # returns int
155
+ engine.forget_profile("old-key") # returns bool
156
+
157
+ # Status (sync)
158
+ stats = engine.status()
159
+ # Returns: {'namespace': '...', 'entities': 142, 'relationships': 87, ...}
160
+
161
+ # Force sync to IPFS (async)
162
+ result = asyncio.run(engine.force_sync())
163
+ # Returns: {'success': True, 'cid': 'Qm...'}
164
+
165
+ # Startup — load from IPFS if snapshot exists (async)
166
+ asyncio.run(engine.startup())
167
+ ```
168
+
169
+ ## Architecture
170
+
171
+ ```
172
+ kausamemory/
173
+ ├── config.py env-based config (passphrase, API keys, model, data dir)
174
+ ├── stores/
175
+ │ ├── database.py SQLite + 6 tables + 4 FTS5 + threading.Lock + WAL
176
+ │ │ + restore_from_bytes (state-machine SQL parser)
177
+ │ │ + reconnect + export_bytes (iterdump)
178
+ │ ├── graph.py entities + typed relationships + recursive CTE traversal
179
+ │ │ + temporal validity (valid_from/valid_to) + upsert
180
+ │ ├── episodes.py conversation timeline + FTS5 search + sanitized queries
181
+ │ │ + LIKE fallback + timerange/recent queries
182
+ │ ├── decisions.py decision ledger + supersede chain + topic search
183
+ │ ├── vectors.py numpy vectorized batch search + pre-normalized matrix
184
+ │ │ + lazy cache + min_similarity threshold
185
+ │ └── profile.py 5 categories (identity/preferences/expertise/workflow/personality)
186
+ │ + confidence scoring + boost_on_confirm + to_prompt()
187
+ ├── engine/
188
+ │ ├── core.py MemoryEngine — 15 public methods + auto-sync + safety check
189
+ │ ├── classifier.py keyword-based 4-strategy classification (English)
190
+ │ ├── retriever.py 4 retrieval strategies × 3 depth levels
191
+ │ │ + profile injection + shared namespace read
192
+ │ └── extractor.py LLM prompt → entities + relationships + decisions
193
+ │ + user_traits + contradiction detection
194
+ ├── providers/
195
+ │ ├── embedder.py FastEmbed BAAI/bge-large-en-v1.5 (1024d, runs locally)
196
+ │ └── llm.py OpenRouter / OpenAI / Anthropic + _extract_json fallback
197
+ ├── crypto/
198
+ │ ├── encryption.py AES-256-GCM + SHA-256 key derivation + user_tag derivation
199
+ │ └── sync.py Pinata IPFS: upload/download/find_latest/unpin
200
+ │ + CID persistence (.latest_cid) + gzip compression
201
+ └── interfaces/
202
+ └── mcp_server.py FastMCP server — 6 tools (stdio transport)
203
+ ```
204
+
205
+ **Hermes plugin** at `plugins/hermes/__init__.py` — full ABC memory provider with prefetch, sync_turn, session hooks, and 7 tool actions.
206
+
207
+ ## Storage
208
+
209
+ Single SQLite file per namespace with WAL journal mode:
210
+
211
+ | Table | Columns | Purpose |
212
+ |-------|---------|---------|
213
+ | `entities` | id, name, type, properties, created_at, updated_at | Knowledge graph nodes |
214
+ | `relationships` | id, source_id, target_id, type, properties, valid_from, valid_to, created_at | Typed edges with temporal validity |
215
+ | `episodes` | id, type, content, session_id, timestamp, metadata | Conversation timeline |
216
+ | `decisions` | id, decision, reason, topic, related_entities, timestamp, superseded_by, session_id | Decision ledger |
217
+ | `embeddings` | id, source_type, source_id, content, vector, timestamp | Vector embeddings (1024d BLOB) |
218
+ | `user_profile` | key, value, category, confidence, updated_at | User traits with confidence |
219
+
220
+ Plus 4 FTS5 virtual tables: `episodes_fts`, `entities_fts`, `decisions_fts`, `user_profile_fts`.
221
+
222
+ Plus 10 indexes on frequently queried columns.
223
+
224
+ ## IPFS Backup & Restore
225
+
226
+ Data flow: SQLite → iterdump → gzip → AES-256-GCM encrypt → Pinata IPFS pin
227
+
228
+ Restore flow: Pinata fetch → AES-256-GCM decrypt → gzip decompress → state-machine SQL parser → filter core table INSERTs → apply on fresh schema
229
+
230
+ Safeguards:
231
+ - CID persisted to `.latest_cid` file before unpinning old snapshot
232
+ - Safety check refuses to sync if total_rows == 0
233
+ - Auto-sync every 5 store operations
234
+ - Background sync loop every 120 seconds (configurable via SYNC_INTERVAL)
235
+ - On startup: check local `.latest_cid` first, fallback to Pinata search by user_tag
236
+
237
+ ### Switch Devices
238
+
239
+ 1. Install KausaMemory on new device
240
+ 2. Set the same `MEMORY_PASSPHRASE` and `PINATA_API_KEY`
241
+ 3. Start your agent — data auto-restores from IPFS
242
+
243
+ ## Configuration
244
+
245
+ | Variable | Required | Default | Description |
246
+ |----------|----------|---------|-------------|
247
+ | `MEMORY_PASSPHRASE` | Yes | — | AES-256-GCM encryption passphrase |
248
+ | `PINATA_API_KEY` | Yes | — | IPFS pinning via Pinata |
249
+ | `LLM_API_KEY` | No | — | Enables auto entity/decision/trait extraction |
250
+ | `LLM_PROVIDER` | No | `openai` | `openai`, `anthropic`, or `openrouter` |
251
+ | `LLM_MODEL` | No | per-provider default | Extraction model |
252
+ | `LLM_BASE_URL` | No | per-provider default | Custom API endpoint |
253
+ | `EMBEDDING_MODEL` | No | `BAAI/bge-large-en-v1.5` | Local embedding model (FastEmbed) |
254
+ | `KAUSAMEMORY_DATA` | No | `~/.kausamemory` | Storage directory |
255
+ | `KAUSAMEMORY_NAMESPACE` | No | `default` | Agent namespace |
256
+ | `SYNC_INTERVAL` | No | `120` | Background sync interval (seconds) |
257
+
258
+ Default models per provider: OpenAI → gpt-4o-mini, Anthropic → claude-sonnet-4-20250514, OpenRouter → google/gemini-2.0-flash-001.
259
+
260
+ ## API Reference
261
+
262
+ ### MemoryEngine — 15 Public Methods
263
+
264
+ **Core (6):**
265
+ - `__init__(namespace=None, shared_read=None)` — config from env vars
266
+ - `startup()` — async, load from IPFS + start background sync
267
+ - `store(user_message, ai_response)` — async, store + extract + auto-sync every 5
268
+ - `retrieve(query, depth="full")` — sync, returns formatted context string
269
+ - `search(query, type="all", limit=10)` — sync, generic search, returns string
270
+ - `status()` — sync, returns dict with all counts
271
+
272
+ **Typed Search (4):**
273
+ - `search_entities(name=None, type=None, limit=10)` — returns list[dict]
274
+ - `search_decisions(query, limit=10, active_only=True)` — returns list[dict]
275
+ - `search_text(query, limit=10)` — returns list[dict]
276
+ - `search_similar(query, limit=10, min_similarity=0.3)` — returns list[dict]
277
+
278
+ **Profile (3):**
279
+ - `get_profile(category=None)` — returns list[dict]
280
+ - `set_profile(key, value, category="general", confidence=0.5)` — sync
281
+ - `forget_profile(key)` — returns bool
282
+
283
+ **Forget (2):**
284
+ - `forget_entity(name)` — returns int (count removed)
285
+ - `forget_decision(topic)` — returns int
286
+
287
+ **Sync (1):**
288
+ - `force_sync()` — async, returns dict with success + cid
289
+
290
+ ## Requirements
291
+
292
+ - Python 3.10+
293
+ - ~1.5 GB disk (FastEmbed model downloads on first use)
294
+ - Internet for IPFS sync and LLM extraction (both optional for local-only use)
295
+
296
+ ## License
297
+
298
+ Apache 2.0
299
+
300
+ ## Links
301
+
302
+ - [KausaLayer](https://kausalayer.com)
303
+ - [Documentation](https://docs.kausalayer.com)
304
+ - [Twitter/X](https://x.com/kausalayer)
File without changes
@@ -0,0 +1,31 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ # Wajib
5
+ MEMORY_PASSPHRASE = os.environ.get("MEMORY_PASSPHRASE", "")
6
+ PINATA_API_KEY = os.environ.get("PINATA_API_KEY", "")
7
+ LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
8
+
9
+ # Opsional
10
+ LLM_PROVIDER = os.environ.get("LLM_PROVIDER", "openai") # "openai", "anthropic", or "openrouter"
11
+ LLM_MODEL = os.environ.get("LLM_MODEL", "") # empty = default per provider
12
+ LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "") # custom base URL for OpenRouter etc
13
+ EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "BAAI/bge-large-en-v1.5")
14
+ DATA_DIR = Path(os.environ.get("KAUSAMEMORY_DATA", str(Path.home() / ".kausamemory")))
15
+ SYNC_INTERVAL_SECONDS = int(os.environ.get("SYNC_INTERVAL", "120"))
16
+
17
+ # Multi-agent namespace: isolate memory per agent identity
18
+ NAMESPACE = os.environ.get("KAUSAMEMORY_NAMESPACE", "default")
19
+
20
+ # Default model per provider
21
+ DEFAULT_MODELS = {
22
+ "openai": "gpt-4o-mini",
23
+ "anthropic": "claude-sonnet-4-20250514",
24
+ "openrouter": "google/gemini-2.0-flash-001",
25
+ }
26
+
27
+ # Default base URLs per provider
28
+ DEFAULT_BASE_URLS = {
29
+ "openai": "https://api.openai.com/v1",
30
+ "openrouter": "https://openrouter.ai/api/v1",
31
+ }
File without changes
@@ -0,0 +1,36 @@
1
+ import os as _os
2
+ import hashlib
3
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
4
+
5
+
6
+ class MemoryEncryption:
7
+ """Encrypt/decrypt memory data using AES-256-GCM derived from passphrase."""
8
+
9
+ @staticmethod
10
+ def derive_key(passphrase: str) -> bytes:
11
+ """Derive AES-256 key from passphrase using SHA-256."""
12
+ return hashlib.sha256(passphrase.encode("utf-8")).digest()
13
+
14
+ @staticmethod
15
+ def derive_user_tag(passphrase: str) -> str:
16
+ """Derive user identifier tag from passphrase (double hash so key != tag)."""
17
+ key_hash = hashlib.sha256(passphrase.encode("utf-8")).hexdigest()
18
+ return hashlib.sha256(("kausa_tag:" + key_hash).encode("utf-8")).hexdigest()[:32]
19
+
20
+ @staticmethod
21
+ def encrypt(data: bytes, passphrase: str) -> bytes:
22
+ """Encrypt data with AES-256-GCM. Returns nonce(12) + ciphertext."""
23
+ key = MemoryEncryption.derive_key(passphrase)
24
+ nonce = _os.urandom(12)
25
+ aesgcm = AESGCM(key)
26
+ ciphertext = aesgcm.encrypt(nonce, data, None)
27
+ return nonce + ciphertext
28
+
29
+ @staticmethod
30
+ def decrypt(encrypted: bytes, passphrase: str) -> bytes:
31
+ """Decrypt AES-256-GCM data. Input: nonce(12) + ciphertext."""
32
+ key = MemoryEncryption.derive_key(passphrase)
33
+ nonce = encrypted[:12]
34
+ ciphertext = encrypted[12:]
35
+ aesgcm = AESGCM(key)
36
+ return aesgcm.decrypt(nonce, ciphertext, None)