@riligar/agents-memories 1.0.0

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.
package/LICENSE ADDED
@@ -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.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # RiLiGar Agents Memories
2
+
3
+ A high-performance, persistent memory system for AI agents, built on the **Model Context Protocol (MCP)**. This project implements a **Relational Knowledge Graph** featuring **Resonance Intelligence** and **Semantic Bridging**.
4
+
5
+ ## 🧠 Philosophy: The Cognitive Memories
6
+
7
+ > "The original repository is a developer's **Toolbox**; our project are the **Collective Memories** for AIs. We evolved the fixed hierarchy into a self-organizing, relational mind. šŸ›āœØ"
8
+
9
+ RiLiGar focuses on **Relational Intelligence**. By transforming memories into a living graph, the agent doesn't just retrieve facts—it understands how those facts are interconnected across different domains.
10
+
11
+ ## šŸ›”ļø Cryptographic Identity
12
+
13
+ Each RiLiGar installation possesses a unique, professional cryptographic identity (Ed25519):
14
+
15
+ - **Implicit Ownership**: By default, the system uses its own 10-character hex ID (derived from the public key hash) to sign and own memories.
16
+ - **Explicit Identity**: Users or external agents can provide their own `owner_id` to maintain clear boundaries in multi-user environments.
17
+ - **Architecture**: Stored locally in `data/identity.json`, ensuring the agent maintains its "soul" across sessions.
18
+
19
+ ## šŸ•ø The Relational Knowledge Graph
20
+
21
+ RiLiGar moves beyond simple keyword or vector storage into a **Graph Database** paradigm:
22
+
23
+ - **Semantic Magnet (Auto-Bridging)**: The system automatically detects near-identical facts (similarity > 0.9) and creates `similar_to` links during the storage phase.
24
+ - **Manual Bridging**: Explicitly connect disparate paths using the `bridge` tool to establish logical dependencies (e.g., `Architecture` depends_on `Infrastructure`).
25
+ - **Resonance Intelligence**: Priorities ripple through the graph; if a node is marked as critical, its semantic neighbors gain importance via resonance.
26
+
27
+ ## šŸŗ Visualizing the Memories
28
+
29
+ RiLiGar provides a native **Inspection** layer using **Mermaid.js**:
30
+
31
+ - **Command**: `inspect`
32
+ - **Output**: Generates a visual mental map of all connections, allowing the agent and user to see the topology of their stored knowledge.
33
+
34
+ ## āš–ļø Relational Semantic Search
35
+
36
+ Searches in RiLiGar are **Read-Only** and **Relational**. When a fact is retrieved, its connections are automatically surfaced:
37
+
38
+ `[Path.A | P:10] Fact A`
39
+ `šŸ”— Related: Path.B (similar_to), Path.C (depends_on)`
40
+
41
+ - **Scoring (Working Memory Boost)**: `Score = (Similarity * 0.6) + (Recency * 0.4)`.
42
+ - **Short-term Awareness**: The system is tuned for **Cognitive Fluidity**, prioritizing recent thoughts and context to function as an effective short-term "working memory" while maintaining long-term relational links.
43
+
44
+ ## šŸ”Œ MCP Tools
45
+
46
+ - `save`: Stores content with automatic priority inference and **Semantic Magnet** auto-linking.
47
+ - `search`: Executes a fast, weighted relational semantic search.
48
+ - `bridge`: Manually links two memory paths with a specified relation type.
49
+ - `inspect`: Generates a Mermaid.js diagram of the current knowledge graph.
50
+ - `list`: Lists all unique memory paths.
51
+
52
+ ---
53
+
54
+ ## šŸ› ļø Setup & Usage
55
+
56
+ ### Prerequisites
57
+
58
+ - [Bun](https://bun.sh) runtime (v1.x+)
59
+
60
+ ### Installation
61
+
62
+ ```bash
63
+ bun install
64
+ ```
65
+
66
+ ### Running the Server
67
+
68
+ ```bash
69
+ bun start # runs src/index.js
70
+ ```
71
+
72
+ ### Verification
73
+
74
+ ```bash
75
+ bun src/test.js
76
+ ```
77
+
78
+ **Built with ā¤ļø for the global open-source community by the RiLiGar Team.**
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@riligar/agents-memories",
3
+ "version": "1.0.0",
4
+ "description": "RiLiGar Agents Memories - A persistent memories system for AI agents.",
5
+ "module": "src/index.js",
6
+ "main": "src/index.js",
7
+ "type": "module",
8
+ "files": [
9
+ "src",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/riligar/agents-memories.git"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "registry": "https://registry.npmjs.org/"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/riligar/agents-memories/issues"
23
+ },
24
+ "homepage": "https://github.com/riligar/agents-memories#readme",
25
+ "scripts": {
26
+ "dev": "bun --watch src/index.js",
27
+ "start": "bun src/index.js",
28
+ "test": "bun src/test.js",
29
+ "test:sse": "bun src/test-sse.js"
30
+ },
31
+ "dependencies": {
32
+ "@huggingface/transformers": "^4.0.1",
33
+ "@libsql/client": "^0.17.2",
34
+ "@modelcontextprotocol/sdk": "latest",
35
+ "cors": "^2.8.6",
36
+ "express": "^5.2.1"
37
+ },
38
+ "devDependencies": {
39
+ "@semantic-release/commit-analyzer": "^13.0.1",
40
+ "@semantic-release/github": "^12.0.6",
41
+ "@semantic-release/npm": "^13.1.5",
42
+ "@semantic-release/release-notes-generator": "^14.1.0",
43
+ "semantic-release": "^25.0.3"
44
+ }
45
+ }
package/src/index.js ADDED
@@ -0,0 +1,344 @@
1
+ import { createClient } from '@libsql/client'
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
4
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'
5
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
6
+ import { pipeline } from '@huggingface/transformers'
7
+ import express from 'express'
8
+ import cors from 'cors'
9
+ import fs from 'fs'
10
+ import path from 'path'
11
+ import crypto from 'crypto'
12
+
13
+ // ==========================================
14
+ // 1. DATABASE & SETUP (Relational Knowledge Graph)
15
+ // ==========================================
16
+ const db = createClient({ url: 'file:data/memories.db' })
17
+ const DATA_DIR = 'data'
18
+ const IDENTITY_JSON_PATH = path.join(DATA_DIR, 'identity.json')
19
+
20
+ if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR)
21
+
22
+ function getSystemIdentity() {
23
+ if (fs.existsSync(IDENTITY_JSON_PATH)) {
24
+ const data = JSON.parse(fs.readFileSync(IDENTITY_JSON_PATH, 'utf8'))
25
+ return data.owner_id
26
+ }
27
+
28
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519', {
29
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
30
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
31
+ })
32
+
33
+ const ownerId = crypto.createHash('sha256').update(publicKey).digest('hex').substring(0, 10)
34
+
35
+ fs.writeFileSync(IDENTITY_JSON_PATH, JSON.stringify({
36
+ owner_id: ownerId,
37
+ public_key: publicKey,
38
+ private_key: privateKey
39
+ }, null, 2), 'utf8')
40
+
41
+ console.error(`Generated new cryptographic identity: ${ownerId}`)
42
+ return ownerId
43
+ }
44
+
45
+ const SYSTEM_OWNER_ID = getSystemIdentity()
46
+ console.error(`System Identity initialized: ${SYSTEM_OWNER_ID}`)
47
+
48
+ await db.execute(`
49
+ CREATE TABLE IF NOT EXISTS memories (
50
+ id TEXT PRIMARY KEY DEFAULT (LOWER(HEX(RANDOMBLOB(5)))),
51
+ content TEXT NOT NULL,
52
+ path TEXT NOT NULL,
53
+ entities TEXT,
54
+ embedding F32_BLOB(384),
55
+ owner_id TEXT NOT NULL,
56
+ priority INTEGER DEFAULT 5,
57
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
58
+ );
59
+ `)
60
+
61
+ await db.execute(`
62
+ CREATE TABLE IF NOT EXISTS links (
63
+ source_id TEXT,
64
+ target_id TEXT,
65
+ relation_type TEXT,
66
+ PRIMARY KEY (source_id, target_id, relation_type)
67
+ );
68
+ `)
69
+
70
+ let extractor = null
71
+ async function getEmbedding(text) {
72
+ if (!extractor) {
73
+ extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2')
74
+ }
75
+ const output = await extractor(text, { pooling: 'mean', normalize: true })
76
+ return new Float32Array(output.data)
77
+ }
78
+
79
+ // ==========================================
80
+ // 2. COGNITIVE LOGIC (Inference, Ripple & Graph)
81
+ // ==========================================
82
+
83
+ async function inferPriority(vector) {
84
+ const result = await db.execute({
85
+ sql: `SELECT priority, vector_distance_cos(embedding, ?) as distance FROM memories ORDER BY distance ASC LIMIT 5`,
86
+ args: [vector.buffer],
87
+ })
88
+ if (result.rows.length === 0) return 5
89
+ let weightedSum = 0,
90
+ totalWeight = 0
91
+ for (const row of result.rows) {
92
+ const similarity = 1 - row.distance
93
+ const weight = Math.pow(similarity, 2)
94
+ weightedSum += row.priority * weight
95
+ totalWeight += weight
96
+ }
97
+ return totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 5
98
+ }
99
+
100
+ async function propagateRipple(vector, manualPriority) {
101
+ const result = await db.execute({
102
+ sql: `SELECT id, priority, vector_distance_cos(embedding, ?) as distance FROM memories ORDER BY distance ASC LIMIT 5`,
103
+ args: [vector.buffer],
104
+ })
105
+ for (const row of result.rows) {
106
+ const similarity = 1 - row.distance
107
+ const resonantPriority = Math.round(manualPriority * similarity)
108
+ if (resonantPriority > row.priority) {
109
+ await db.execute({ sql: `UPDATE memories SET priority = ? WHERE id = ?`, args: [resonantPriority, row.id] })
110
+ }
111
+ }
112
+ }
113
+
114
+ async function findClosestNeighbor(vector) {
115
+ const result = await db.execute({
116
+ sql: `SELECT id, path, vector_distance_cos(embedding, ?) as distance FROM memories ORDER BY distance ASC LIMIT 1`,
117
+ args: [vector.buffer],
118
+ })
119
+ return result.rows[0] || null
120
+ }
121
+
122
+ // ==========================================
123
+ // 3. MCP SERVER FACTORY
124
+ // ==========================================
125
+
126
+ function createMcpServer() {
127
+ const server = new Server({ name: 'RiLiGar Agents Memories', version: '4.0.0' }, { capabilities: { tools: {} } })
128
+
129
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
130
+ return {
131
+ tools: [
132
+ {
133
+ name: 'save',
134
+ description: 'Saves info with Resonance and Auto-Bridging (Semantic Magnet).',
135
+ inputSchema: {
136
+ type: 'object',
137
+ properties: {
138
+ content: {
139
+ oneOf: [{ type: 'string' }, { type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'object', properties: { content: { type: 'string' }, path: { type: 'string' }, owner_id: { type: 'string' }, priority: { type: 'integer' } }, required: ['content'] }] } }],
140
+ },
141
+ path: { type: 'string' },
142
+ owner_id: { type: 'string' },
143
+ priority: { type: 'integer' },
144
+ },
145
+ required: ['content'],
146
+ },
147
+ },
148
+ {
149
+ name: 'bridge',
150
+ description: 'Manually connects two memory paths.',
151
+ inputSchema: {
152
+ type: 'object',
153
+ properties: {
154
+ source_path: { type: 'string' },
155
+ target_path: { type: 'string' },
156
+ relation: { type: 'string', default: 'related_to' },
157
+ },
158
+ required: ['source_path', 'target_path'],
159
+ },
160
+ },
161
+ {
162
+ name: 'search',
163
+ description: 'Semantic search with Relational Awareness.',
164
+ inputSchema: {
165
+ type: 'object',
166
+ properties: {
167
+ query: { type: 'string' },
168
+ path_filter: { type: 'string' },
169
+ },
170
+ required: ['query'],
171
+ },
172
+ },
173
+ {
174
+ name: 'inspect',
175
+ description: 'Visualizes the Knowledge Graph in Mermaid.js syntax.',
176
+ inputSchema: { type: 'object', properties: {} },
177
+ },
178
+ {
179
+ name: 'list',
180
+ description: 'Lists all memory paths.',
181
+ inputSchema: { type: 'object', properties: {} },
182
+ },
183
+ ],
184
+ }
185
+ })
186
+
187
+ server.setRequestHandler(CallToolRequestSchema, async request => {
188
+ const { name, arguments: args } = request.params
189
+
190
+ try {
191
+ if (name === 'save') {
192
+ const results = []
193
+ const rawContent = args.content
194
+ const defaultPath = args.path || 'General'
195
+ const memoriesToSave = Array.isArray(rawContent) ? rawContent.map(m => (typeof m === 'string' ? { content: m } : m)) : [{ content: rawContent, path: args.path, owner_id: args.owner_id, priority: args.priority }]
196
+
197
+ for (const mem of memoriesToSave) {
198
+ if (!mem.content) continue
199
+ const vector = await getEmbedding(mem.content)
200
+ const path = mem.path || defaultPath
201
+
202
+ const neighbor = await findClosestNeighbor(vector)
203
+ const isManualPriority = typeof mem.priority === 'number'
204
+ const finalPriority = isManualPriority ? mem.priority : await inferPriority(vector)
205
+
206
+ const insertRes = await db.execute({
207
+ sql: `INSERT INTO memories (content, path, embedding, owner_id, priority) VALUES (?, ?, ?, ?, ?) RETURNING id`,
208
+ args: [mem.content, path, vector.buffer, mem.owner_id || args.owner_id || SYSTEM_OWNER_ID, finalPriority],
209
+ })
210
+ const newId = insertRes.rows[0].id
211
+
212
+ if (neighbor && 1 - neighbor.distance > 0.9) {
213
+ await db.execute({
214
+ sql: `INSERT OR IGNORE INTO links (source_id, target_id, relation_type) VALUES (?, ?, ?)`,
215
+ args: [newId, neighbor.id, 'similar_to'],
216
+ })
217
+ }
218
+
219
+ if (isManualPriority) await propagateRipple(vector, finalPriority)
220
+ results.push(path)
221
+ }
222
+ return { content: [{ type: 'text', text: `Saved ${results.length} memories. Semantic Magnet applied.` }] }
223
+ }
224
+
225
+ if (name === 'bridge') {
226
+ const src = await db.execute({ sql: `SELECT id FROM memories WHERE path = ? LIMIT 1`, args: [args.source_path] })
227
+ const tgt = await db.execute({ sql: `SELECT id FROM memories WHERE path = ? LIMIT 1`, args: [args.target_path] })
228
+ if (!src.rows[0] || !tgt.rows[0]) throw new Error('Path(s) not found.')
229
+
230
+ await db.execute({
231
+ sql: `INSERT OR IGNORE INTO links (source_id, target_id, relation_type) VALUES (?, ?, ?)`,
232
+ args: [src.rows[0].id, tgt.rows[0].id, args.relation || 'related_to'],
233
+ })
234
+ return { content: [{ type: 'text', text: `Bridge created: [${args.source_path}] --(${args.relation})--> [${args.target_path}]` }] }
235
+ }
236
+
237
+ if (name === 'search') {
238
+ const vector = await getEmbedding(args.query)
239
+ let sql = `SELECT id, content, path, priority, created_at, vector_distance_cos(embedding, ?) as distance FROM memories`
240
+ const queryArgs = [vector.buffer],
241
+ filters = []
242
+ if (args.path_filter) {
243
+ filters.push(`path LIKE ?`)
244
+ queryArgs.push(args.path_filter)
245
+ }
246
+ if (filters.length > 0) sql += ` WHERE ` + filters.join(' AND ')
247
+
248
+ const result = await db.execute({ sql, args: queryArgs })
249
+ const rows = result.rows
250
+ .map(r => ({ ...r, score: (1 - r.distance) * 0.6 + (1 / (1 + (new Date() - new Date(r.created_at)) / 86400000)) * 0.4 }))
251
+ .sort((a, b) => b.score - a.score)
252
+ .slice(0, 5)
253
+
254
+ const formattedResults = []
255
+ for (const r of rows) {
256
+ const links = await db.execute({
257
+ sql: `SELECT m.path, l.relation_type FROM links l JOIN memories m ON l.target_id = m.id WHERE l.source_id = ?`,
258
+ args: [r.id],
259
+ })
260
+ const linkText = links.rows.length > 0 ? `\nšŸ”— Related: ${links.rows.map(l => `${l.path} (${l.relation_type})`).join(', ')}` : ''
261
+ formattedResults.push(`[${r.path} | P:${r.priority}] ${r.content}${linkText}`)
262
+ }
263
+ return { content: [{ type: 'text', text: formattedResults.join('\n\n') || 'No results.' }] }
264
+ }
265
+
266
+ if (name === 'inspect') {
267
+ const result = await db.execute(`
268
+ SELECT m1.path as src, m2.path as tgt, l.relation_type as rel
269
+ FROM links l
270
+ JOIN memories m1 ON l.source_id = m1.id
271
+ JOIN memories m2 ON l.target_id = m2.id
272
+ `)
273
+ let mermaid = 'graph TD\n'
274
+ result.rows.forEach(r => {
275
+ mermaid += ` ${r.src.replace(/\./g, '_')}["${r.src}"] -- "${r.rel}" --> ${r.tgt.replace(/\./g, '_')}["${r.tgt}"]\n`
276
+ })
277
+ return { content: [{ type: 'text', text: `### Knowledge Graph\n\n\`\`\`mermaid\n${mermaid}\`\`\`` }] }
278
+ }
279
+
280
+ if (name === 'list') {
281
+ const result = await db.execute(`SELECT DISTINCT path FROM memories ORDER BY path`)
282
+ return { content: [{ type: 'text', text: result.rows.map(r => `- ${r.path}`).join('\n') || 'Empty.' }] }
283
+ }
284
+
285
+ throw new Error('Unknown tool.')
286
+ } catch (error) {
287
+ return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true }
288
+ }
289
+ })
290
+
291
+ return server
292
+ }
293
+
294
+ // ==========================================
295
+ // 4. CONNECTION HANDLING (STDIO + HTTP)
296
+ // ==========================================
297
+
298
+ // 4.1. STDIO Connection
299
+ const stdioServer = createMcpServer()
300
+ const stdioTransport = new StdioServerTransport()
301
+ stdioServer.connect(stdioTransport).catch(err => console.error('STDIO Error:', err))
302
+ console.error('RiLiGar Agents Memories running via STDIO.')
303
+
304
+ // 4.2. Express Server with SDK SSE Transport
305
+ const app = express()
306
+ app.use(cors())
307
+ // Note: We do NOT use express.json() because SSEServerTransport handles body parsing manually via getRawBody.
308
+
309
+ const sseSessions = new Map()
310
+
311
+ app.get('/health', (req, res) => {
312
+ res.status(200).send('OK')
313
+ })
314
+
315
+ app.get('/sse', async (req, res) => {
316
+ const transport = new SSEServerTransport('/messages', res)
317
+ const sessionServer = createMcpServer()
318
+ await sessionServer.connect(transport)
319
+
320
+ const sessionId = transport.sessionId
321
+ sseSessions.set(sessionId, transport)
322
+ console.error(`SSE session started: ${sessionId}`)
323
+
324
+ res.on('close', () => {
325
+ console.error(`SSE session closed: ${sessionId}`)
326
+ sseSessions.delete(sessionId)
327
+ })
328
+ })
329
+
330
+ app.post('/messages', async (req, res) => {
331
+ const sessionId = req.query.sessionId
332
+ const transport = sseSessions.get(sessionId)
333
+
334
+ if (!transport) {
335
+ return res.status(404).send('Session not found')
336
+ }
337
+
338
+ await transport.handlePostMessage(req, res)
339
+ })
340
+
341
+ const PORT = 3000
342
+ app.listen(PORT, () => {
343
+ console.error(`RiLiGar Agents Memories (Express) running at http://localhost:${PORT}`)
344
+ })
package/src/test.js ADDED
@@ -0,0 +1,101 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
2
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
3
+
4
+ /**
5
+ * Knowledge Graph & Relational Intelligence Test Suite.
6
+ * Verifies manual bridging, auto-linking (Semantic Magnet), and graph inspection.
7
+ */
8
+ async function runTest() {
9
+ console.log('\nšŸ•øļø Initializing Relational Knowledge Graph E2E Test...\n')
10
+
11
+ const transport = new StdioClientTransport({
12
+ command: process.platform === 'win32' ? 'bun.exe' : (process.env.HOME + '/.bun/bin/bun'),
13
+ args: ['src/index.js']
14
+ })
15
+
16
+ const client = new Client(
17
+ { name: 'Graph-Tester', version: '1.0.0' },
18
+ { capabilities: {} }
19
+ )
20
+
21
+ try {
22
+ await client.connect(transport)
23
+ console.log('āœ… Connected to RiLiGar Agents Memories.')
24
+
25
+ // ==========================================
26
+ // SCENARIO 1: MANUAL BRIDGING
27
+ // ==========================================
28
+ console.log('\nšŸŒ‰ [Scenario 1] Creating a Manual Semantic Bridge')
29
+
30
+ await client.callTool({
31
+ name: 'save',
32
+ arguments: {
33
+ content: [
34
+ { content: 'LibSQL supports local vector extensions.', path: 'Infrastructure.Database' },
35
+ { content: 'Search latency is sub-10ms for local queries.', path: 'Architecture.Performance' }
36
+ ],
37
+ owner_id: 'tester'
38
+ }
39
+ })
40
+
41
+ await client.callTool({
42
+ name: 'bridge',
43
+ arguments: {
44
+ source_path: 'Architecture.Performance',
45
+ target_path: 'Infrastructure.Database',
46
+ relation: 'depends_on'
47
+ }
48
+ })
49
+ console.log('āœ… Bridge established: Performance depends_on Database.')
50
+
51
+ // ==========================================
52
+ // SCENARIO 2: SEMANTIC MAGNET (AUTO-LINKING)
53
+ // ==========================================
54
+ console.log('\n🧲 [Scenario 2] Testing Semantic Magnet (Auto-Linking)')
55
+
56
+ await client.callTool({
57
+ name: 'save',
58
+ arguments: {
59
+ content: 'Neural networks inspired by biological synaptic connections.',
60
+ owner_id: 'tester'
61
+ }
62
+ })
63
+
64
+ console.log('--- Saving extremely similar content to trigger Auto-Link ---')
65
+ await client.callTool({
66
+ name: 'save',
67
+ arguments: {
68
+ content: 'Biological synapses are the foundation for neural network models.',
69
+ owner_id: 'tester'
70
+ }
71
+ })
72
+
73
+ // ==========================================
74
+ // SCENARIO 3: GRAPH INSPECTION (VISUAL)
75
+ // ==========================================
76
+ console.log('\nšŸ—ŗļø [Scenario 3] Inspecting the Mental Map (Graph Visualization)')
77
+ const graphResult = await client.callTool({ name: 'inspect', arguments: {} })
78
+ console.log(graphResult.content[0].text)
79
+
80
+ // ==========================================
81
+ // SCENARIO 4: RELATIONAL SEARCH
82
+ // ==========================================
83
+ console.log('\nšŸ” [Scenario 4] Executing Relational Semantic Search')
84
+ const searchResult = await client.callTool({
85
+ name: 'search',
86
+ arguments: { query: 'How does performance relate to infrastructure?' }
87
+ })
88
+ console.log('šŸŽÆ Search Result (should show šŸ”— Related paths):\n')
89
+ console.log(searchResult.content[0].text)
90
+
91
+ console.log('\nāœ… Knowledge Graph Suite completed successfully.\n')
92
+
93
+ } catch (error) {
94
+ console.error('🚨 Critical failure:', error)
95
+ } finally {
96
+ await transport.close()
97
+ process.exit()
98
+ }
99
+ }
100
+
101
+ runTest()
@@ -0,0 +1,61 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
2
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
3
+ import fs from 'fs'
4
+
5
+ async function runIdentityTest() {
6
+ console.log('\nšŸ†” Testing Persistent Cryptographic Identity...\n')
7
+
8
+ const identityFile = 'data/identity.json'
9
+ if (fs.existsSync(identityFile)) {
10
+ const data = JSON.parse(fs.readFileSync(identityFile, 'utf8'))
11
+ console.log(`Current persistent cryptographic ID: ${data.owner_id}`)
12
+ console.log(`Public Key found: ${data.public_key.substring(0, 40)}...`)
13
+ } else {
14
+ console.log('No cryptographic identity found yet.')
15
+ }
16
+
17
+ const transport = new StdioClientTransport({
18
+ command: (process.env.HOME + '/.bun/bin/bun'),
19
+ args: ['src/index.js']
20
+ })
21
+
22
+ const client = new Client(
23
+ { name: 'Identity-Tester', version: '1.0.0' },
24
+ { capabilities: {} }
25
+ )
26
+
27
+ try {
28
+ await client.connect(transport)
29
+
30
+ console.log('\n--- Case 1: Saving WITHOUT owner_id (Implicit Cryptographic) ---')
31
+ await client.callTool({
32
+ name: 'save',
33
+ arguments: {
34
+ content: 'Implicit cryptographic owner test memory',
35
+ path: 'Test.Identity'
36
+ }
37
+ })
38
+ console.log('āœ… Saved implicit memory.')
39
+
40
+ console.log('\n--- Case 2: Saving WITH owner_id (Explicit Override) ---')
41
+ await client.callTool({
42
+ name: 'save',
43
+ arguments: {
44
+ content: 'Explicit owner test memory',
45
+ path: 'Test.Identity',
46
+ owner_id: 'EXTERNAL_HUMAN'
47
+ }
48
+ })
49
+ console.log('āœ… Saved explicit memory.')
50
+
51
+ console.log('\nāœ… Identity tests completed successfully.\n')
52
+
53
+ } catch (error) {
54
+ console.error('🚨 Test failed:', error)
55
+ } finally {
56
+ await transport.close()
57
+ process.exit()
58
+ }
59
+ }
60
+
61
+ runIdentityTest()
@@ -0,0 +1,74 @@
1
+
2
+ async function testSSE() {
3
+ console.log('--- Testing SSE Connection ---');
4
+ try {
5
+ const response = await fetch('http://localhost:3000/sse');
6
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
7
+
8
+ const reader = response.body.getReader();
9
+ const decoder = new TextDecoder();
10
+
11
+ console.log('Connection opened. Waiting for endpoint event...');
12
+
13
+ let endpointUrl = null;
14
+
15
+ // Read the first chunk
16
+ const { value, done } = await reader.read();
17
+ const chunk = decoder.decode(value);
18
+ console.log('Received chunk:\n', chunk);
19
+
20
+ if (chunk.includes('event: endpoint')) {
21
+ console.log('āœ… Received endpoint event!');
22
+ const lines = chunk.split('\n');
23
+ const dataLine = lines.find(l => l.startsWith('data: '));
24
+ if (dataLine) {
25
+ endpointUrl = dataLine.replace('data: ', '').trim();
26
+ console.log(`Endpoint URL: ${endpointUrl}`);
27
+ }
28
+ } else {
29
+ console.log('āŒ FAILED: Did not receive endpoint event as the first message.');
30
+ }
31
+
32
+ if (endpointUrl) {
33
+ console.log('\n--- Testing Tool Call via SSE ---');
34
+ const message = {
35
+ jsonrpc: '2.0',
36
+ id: 1,
37
+ method: 'tools/call',
38
+ params: {
39
+ name: 'list',
40
+ arguments: {}
41
+ }
42
+ };
43
+
44
+ const postRes = await fetch(`http://localhost:3000${endpointUrl}`, {
45
+ method: 'POST',
46
+ headers: { 'Content-Type': 'application/json' },
47
+ body: JSON.stringify(message)
48
+ });
49
+
50
+ if (postRes.ok) {
51
+ console.log('āœ… Message POST-ed successfully.');
52
+
53
+ // Read next chunk for the result
54
+ const { value: val2 } = await reader.read();
55
+ const chunk2 = decoder.decode(val2);
56
+ console.log('Received response chunk:\n', chunk2);
57
+
58
+ if (chunk2.includes('event: message')) {
59
+ console.log('āœ… Received message event response!');
60
+ } else {
61
+ console.log('āŒ FAILED: Response did not have event: message prefix.');
62
+ }
63
+ } else {
64
+ console.log(`āŒ FAILED to POST message: ${postRes.status} ${await postRes.text()}`);
65
+ }
66
+ }
67
+
68
+ reader.cancel();
69
+ } catch (error) {
70
+ console.error('🚨 Error during SSE test:', error);
71
+ }
72
+ }
73
+
74
+ testSSE();