@lotargo/memory_plugin 1.4.621 → 1.5.1

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 (39) hide show
  1. package/README.md +352 -366
  2. package/mcp-server/admin/auth.js +31 -4
  3. package/mcp-server/admin/snapshot.js +19 -7
  4. package/mcp-server/cli/direct_commands.js +313 -0
  5. package/mcp-server/cli/handlers/cloud_actions.js +138 -0
  6. package/mcp-server/cli/handlers/diagnostics_actions.js +107 -0
  7. package/mcp-server/cli/handlers/engine_actions.js +214 -0
  8. package/mcp-server/cli/handlers/prompt_actions.js +24 -0
  9. package/mcp-server/cli/handlers/storage_actions.js +749 -0
  10. package/mcp-server/cli/quick_stats.js +39 -0
  11. package/mcp-server/cli/ui.js +565 -0
  12. package/mcp-server/cli.js +324 -2085
  13. package/mcp-server/config/auth_store.js +56 -9
  14. package/mcp-server/config/config_manager.js +1 -0
  15. package/mcp-server/db/database.js +14 -1
  16. package/mcp-server/db/migrations.js +28 -0
  17. package/mcp-server/fact_format.js +244 -177
  18. package/mcp-server/graph/graph_extractor.js +20 -5
  19. package/mcp-server/identity.js +152 -0
  20. package/mcp-server/index.js +42 -679
  21. package/mcp-server/ingest/normalizer.js +40 -4
  22. package/mcp-server/ingest/pipeline.js +6 -13
  23. package/mcp-server/memory.js +50 -63
  24. package/mcp-server/prompt_manager.js +1 -1
  25. package/mcp-server/retrieval/retriever.js +59 -42
  26. package/mcp-server/tools/helpers.js +39 -0
  27. package/mcp-server/tools/identity_tools.js +277 -0
  28. package/mcp-server/tools/index.js +9 -0
  29. package/mcp-server/tools/memory_tools.js +506 -0
  30. package/mcp-server/tools/rag_tools.js +235 -0
  31. package/opencode-plugin/index.js +460 -48
  32. package/package.json +7 -3
  33. package/skills/using-memory/SKILL.md +31 -14
  34. package/mcp-server/benchmarks/fetch_real_corpus.js +0 -351
  35. package/mcp-server/benchmarks/gpu_profile_benchmark.js +0 -170
  36. package/mcp-server/benchmarks/quality_evaluator.js +0 -600
  37. package/mcp-server/benchmarks/run_benchmarks.js +0 -347
  38. package/mcp-server/benchmarks/stress_ingestion.js +0 -195
  39. package/mcp-server/benchmarks/test_dual_layer.js +0 -140
package/README.md CHANGED
@@ -1,366 +1,352 @@
1
- <div align="center">
2
-
3
- <img src="./assets/hero.jpg" alt="@lotargo/memory_plugin" width="800" style="max-width: 100%; border-radius: 12px; margin-bottom: 16px;">
4
-
5
- <br>
6
-
7
- <img src="./assets/title.svg" alt="@lotargo/memory_plugin" width="520" style="max-width: 100%; margin-bottom: 12px;">
8
-
9
- <br>
10
-
11
- [![npm version](https://img.shields.io/npm/v/@lotargo/memory_plugin)](https://www.npmjs.com/package/@lotargo/memory_plugin)
12
- [![npm downloads](https://img.shields.io/npm/dt/@lotargo/memory_plugin)](https://www.npmjs.com/package/@lotargo/memory_plugin)
13
- [![license](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
14
- [![node version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org)
15
- [![mcp](https://img.shields.io/badge/MCP-Supported-8A2BE2)](https://modelcontextprotocol.io)
16
- [![storage](https://img.shields.io/badge/Storage-100%25%20Local-success)](#storage--privacy)
17
-
18
- <br>
19
-
20
- **Zero-Docker Local Hybrid RAG Engine & Long-Term Memory for AI Coding Agents**
21
-
22
- Automatically remembers durable user facts, ingests complex document repositories, and performs high-precision hybrid retrieval across sessions and platforms.
23
-
24
- </div>
25
-
26
- ---
27
-
28
- ## Overview
29
-
30
- Standard AI coding assistants lose context as soon as a chat session closes or a conversation is reset. You end up repeatedly re-explaining your preferences, architectural decisions, coding style, or project conventions.
31
-
32
- `@lotargo/memory_plugin` gives your AI tools durable, **persistent**, 100% local long-term memory and document retrieval capabilities that persist across restarts and work seamlessly across all supported coding environments. Any LLM-based coding agent (OpenCode, Claude Code, Codex, Antigravity) can query its own memory and hybrid knowledge base via the **Model Context Protocol (MCP)**.
33
-
34
- > **Project Scope & Runtime Notes**:
35
- > `@lotargo/memory_plugin` is designed primarily as a practical plugin to expand capabilities and streamline daily interaction with AI coding tools. Benchmark scores in this repository represent internal synthetic evaluation runs and are not intended as generalized RAG benchmarks.
36
- >
37
- > **Hardware Acceleration**: GPU execution mode is an experimental feature and may vary in stability across different operating systems or models. For optimal stability and consistent runtime performance, using standard CPU mode with `multilingual-e5-small` or `multilingual-e5-base` is recommended.
38
-
39
- ### Practical Use Cases
40
-
41
- - **Architectural Decisions**: _"In this project, we use Fastify instead of Express and strict schema validation via Zod."_
42
- - **Coding Conventions**: _"Place all helper utilities inside `src/utils/` and cover new functions with Vitest tests."_
43
- - **Environment Constraints**: _"Our target deployment environment is Node.js 20 on AWS Lambda."_
44
- - **User Profile & Tone**: _"My name is Alex. I prefer concise, direct answers without conversational filler."_
45
-
46
- ---
47
-
48
- ## Quick Start
49
-
50
- ### Minimum System Requirements
51
-
52
- - **Node.js**: `18.0.0` or higher
53
- - **Package Manager**: `npm` / `npx` (included with Node.js)
54
- - **Supported Environment**: OpenCode, Antigravity / Gemini CLI, Claude Code, or Codex
55
-
56
- ### Installation
57
-
58
- Run the setup command to configure all detected AI environments automatically:
59
-
60
- ```bash
61
- # Recommended: Global installation & setup (works across local CLI, Docker, and CI)
62
- npm install -g @lotargo/memory_plugin && memory_plugin setup
63
-
64
- # Or via npx
65
- npx @lotargo/memory_plugin setup
66
- ```
67
-
68
- To target a specific environment:
69
-
70
- ```bash
71
- # Antigravity / Gemini CLI
72
- npm install -g @lotargo/memory_plugin && memory_plugin setup --antigravity
73
-
74
- # OpenCode
75
- npm install -g @lotargo/memory_plugin && memory_plugin setup --opencode
76
-
77
- # Claude Code
78
- npm install -g @lotargo/memory_plugin && memory_plugin setup --claude
79
-
80
- # Codex
81
- npm install -g @lotargo/memory_plugin && memory_plugin setup --codex
82
- ```
83
-
84
- `setup` also accepts `--gemini` (alias for Antigravity) and `--local` (also registers the MCP server in the project-local `.agents/` directory for Antigravity). Without a specific flag, all detected environments are configured.
85
-
86
- ---
87
-
88
- ## Dual-Layer Architecture
89
-
90
- 1. **Layer 1: Notebook Store (Durable Facts)**
91
- - **Tools**: `remember`, `recall`, `forget`, `update_fact`, `memory_info`
92
- - **Scope**: User preferences, identity, project conventions, system rules.
93
- - **Storage**: Human-readable Markdown format (`global` and per-project stores).
94
- - **Performance**: Guaranteed 100% precision instant lookup without vector degradation or threshold filtering.
95
- - **Project Scoping**: Project stores are bound to their canonical directory path (e.g. `f__projects_plugins_memory.md`), so identical project names in different folders never collide. Legacy basename stores are migrated automatically with a collision guard.
96
-
97
- 2. **Layer 2: RAG Knowledge Base (Technical Documents & Codebases)**
98
- - **Tools**: `ingest_document`, `query_knowledge_base`, `manage_knowledge_base`, `link_knowledge`
99
- - **Capabilities**: Ingests raw text files, Markdown, HTML, Web URLs, and full code repositories.
100
- - **Engine Components**: 3-tier hierarchy chunking (Big / Medium / Small), SQLite FTS5 BM25 search, ONNX dense vector embeddings (`multilingual-e5-small`), Reciprocal Rank Fusion (RRF / RSF), cross-encoder reranking (optional), and GraphRAG Lite code symbol extraction.
101
-
102
- ---
103
-
104
- ## Key Features
105
-
106
- - **Zero Heavy Infrastructure**: No Docker, no Python server, no C++ compilation (`node-gyp`). Uses Node.js native SQLite database.
107
- - **Bilingual & Multilingual Support**: State-of-the-art semantic precision across Russian, English, and technical code symbols.
108
- - **Multilingual Code Symbol Parsing**: High-performance extraction of code entities across 10 programming languages (Python, Go, Rust, C++, Java, Kotlin, C#, PHP, Ruby, JS/TS).
109
- - **Office Document Ingestion**: Native, pure-JS parsing of PDF, DOCX, XLSX, and CSV documents, removing the need for external CLI converters.
110
- - **Hybrid Spreadsheet RAG Representation**: XLSX/CSV tables are converted to Markdown tables for raw document viewing, while row records are transformed into semantic key-value text lines to prevent vector database noise and boost search quality.
111
- - **3-Tier Hierarchy Chunking**: Document (Big) -> Section (Medium) -> Micro-Chunk (Small).
112
- - **Hybrid RRF/RSF Fusion**: Combines SQLite FTS5 keyword precision with ONNX dense vector similarity; lexical-only fallback when embeddings are disabled.
113
- - **Semantic Search**: Cosine-similarity vector retrieval with multilingual ONNX embeddings (E5 / BGE model families).
114
- - **Path-Based Project Memory**: Per-project stores keyed by canonical directory path, with automatic migration of legacy stores.
115
- - **GraphRAG Lite**: Automatically links documents and extracted code symbols (classes, functions, types).
116
- - **Memory-to-Knowledge Linking**: Associate notebook facts with specific documents or line ranges in the RAG base.
117
- - **Content-Addressable Storage (CAS)**: Local S3-style compressed blob store for raw original documents.
118
- - **Dual-Source Model Failover**: Automatic HuggingFace CDN model downloading with GitHub Repository Mirror fallback.
119
- - **Interactive TUI**: Terminal GUI (CLI menu) for runtime engine tuning, snapshot export/import, model cache management, and diagnostics.
120
-
121
- ---
122
-
123
- ## Supported Platforms
124
-
125
- | Platform | Status | Configuration Mechanism |
126
- | :--------------------------- | :----------- | :-------------------------------------------------------------------------- |
127
- | **Antigravity / Gemini CLI** | Supported | MCP Server (`~/.gemini/config/mcp_config.json` & `.agents/mcp_config.json`) |
128
- | **OpenCode** | Native | Native plugin + MCP Server (`~/.config/opencode/opencode.json`) |
129
- | **Claude Code** | Supported | MCP Server (`~/.claude.json`) |
130
- | **Codex** | Supported | MCP Server (`~/.codex/config.toml`) |
131
- | **Google Jules** | Experimental | MCP Server via global install + setup (`npm install -g @lotargo/memory_plugin && memory_plugin setup`) |
132
-
133
- ### Google Jules Integration (Experimental)
134
-
135
- The plugin has been verified inside the **Google Jules** cloud workspace environment. This feature is **experimental**.
136
-
137
- - **Setup Method**: Global pre-installation with auto-setup:
138
- ```bash
139
- npm install -g @lotargo/memory_plugin && memory_plugin setup
140
- ```
141
- - **Verification**: All current tools and capabilities have been verified inside the Google Jules cloud workspace. Google Jules automatically discovers the registered MCP server upon workspace initialization and seamlessly interacts with the full set of memory & RAG tools — `remember`, `recall`, `forget`, `update_fact`, `memory_info`, `link_knowledge`, `ingest_document`, `query_knowledge_base`, and `manage_knowledge_base` — including project-scoped memory, knowledge linking, and snapshot export/import.
142
- - **Current Limitation**: All memory stores and vector indexes operate locally within the workspace environment. For cross-session cloud synchronization (Turso `only-cloud` / `hybrid-sync`) inside headless environments like Jules, authenticate without a browser using the token/env methods below.
143
-
144
- ### Headless Turso Authentication (Docker, Google Jules, VPS/VDS)
145
-
146
- Browser OAuth requires a desktop session, so headless deployments use token- or env-based login. The **Turso account API token is the primary source of truth**: it resolves an org/database and mints a per-database token via the Platform API, exactly like the browser flow, and the resulting session is stored encrypted. In priority order, secrets resolve as **env `TURSO_API_TOKEN` → stored API-token session → env `TURSO_DB_URL`/`TURSO_DB_TOKEN` → stored browser/database session**:
147
-
148
- | Method | Command | Notes |
149
- | :----- | :------ | :---- |
150
- | Account API token | `memory_plugin login --api-key <TOKEN> [--org <ORG>] [--database <DB>]` | Preferred. Validates the token, resolves org/db, mints and stores a per-database token |
151
- | Direct endpoint | `memory_plugin login --db-url libsql://<db>-<org>.turso.io --db-token <TOKEN>` | No Platform API calls; org/db derived from the URL |
152
- | Environment | `memory_plugin login --from-env` | Imports `TURSO_DB_URL`+`TURSO_DB_TOKEN` (preferred) or `TURSO_API_TOKEN` |
153
- | Remove API key | `memory_plugin logout --api-key` | Removes only the API token; the resolved database session is kept |
154
- | Status | `memory_plugin auth-status` | Shows source (env / api-key / store), authorized flag, API-key flag, endpoint, org, database and mode |
155
-
156
- One-shot headless setup (no browser, no interactive `login`):
157
-
158
- ```bash
159
- memory_plugin setup --api-key <TURSO_API_TOKEN> --mode hybrid-sync # auth + set sync mode in one step
160
- memory_plugin setup --mode only-cloud # mode only, if already authorized
161
- ```
162
-
163
- Supported environment variables (usable without any `login` step — `loadSecrets()` picks them up automatically):
164
-
165
- - `TURSO_API_TOKEN` account API token (requires Platform API access). On first use the plugin mints a per-database JWT on the fly without touching the encrypted store; optional `TURSO_ORG`, `TURSO_DATABASE` / `TURSO_DB_NAME`, `TURSO_USERNAME`
166
- - `TURSO_DB_URL` / `TURSO_URL` + `TURSO_DB_TOKEN` / `TURSO_TOKEN` direct database credentials
167
-
168
- The interactive TUI (`memory_plugin cli` → `[CLOUD] ...`) offers a method chooser: Browser OAuth, account API token, database URL + token, or import from environment — plus `[API KEY] Set / Replace Account API Token` and `[API KEY] Remove Account API Token` menu entries. For example, to run a Google Jules workspace with cloud sync:
169
-
170
- ```bash
171
- export TURSO_API_TOKEN="eyJhbGciOi..."
172
- memory_plugin setup --api-key "$TURSO_API_TOKEN" --mode hybrid-sync # or rely on env auto-detection
173
- memory_plugin auth-status
174
- ```
175
-
176
- ---
177
-
178
- ## Available MCP Tools
179
-
180
- ### 1. Memory Tools (Key-Value Notebook)
181
-
182
- | Tool | Scope / Target | Description |
183
- | :-------------- | :-------------------------------------- | :---------------------------------------------------------------- |
184
- | `remember` | `global` or `project` | Save an important durable fact or preference |
185
- | `recall` | `project`, `global`, `all`, `list_projects` | Display saved facts; read another project's store via `project: '<path>'` |
186
- | `forget` | Index ID, range, or query | Remove a saved fact (e.g. `"3-30"` ranges; `force` for protected) |
187
- | `update_fact` | Index ID, metadata id, or text | Rewrite a fact while preserving its original date and links |
188
- | `memory_info` | - | Show storage paths, fact counts, RAG stats, and package version |
189
-
190
- ### 2. Hybrid RAG Knowledge Base Tools
191
-
192
- | Tool | Target | Description |
193
- | :---------------------- | :------------------------------ | :--------------------------------------------------------------------------- |
194
- | `ingest_document` | Local files, Web URLs, Raw text | Ingest into 3-tier index with ONNX vector embeddings & symbol extraction |
195
- | `query_knowledge_base` | Text / Code query | Perform hybrid RSF/RRF search (BM25 + Vector) to retrieve candidate sections |
196
- | `manage_knowledge_base` | Actions / Documents | Stats, list, read, delete documents, or export/import snapshots |
197
- | `link_knowledge` | Facts + Document ranges | Explicitly link a memory fact to a KB document or line range |
198
-
199
- ### 3. Native OpenCode Plugin
200
-
201
- When installed as an OpenCode plugin, all MCP tools above plus `list-mcp-tools` and `mcp-reminder` are exposed. A chat hook (`experimental.chat.messages.transform`) automatically injects your saved memory into every conversation as a `<MEMORY>` block, so your agent starts each session already knowing your preferences and project context.
202
-
203
- ---
204
-
205
- ## GraphRAG Lite
206
-
207
- The RAG engine includes a lightweight graph layer built on the same SQLite database. It combines code symbol extraction, hierarchy edges, and explicit memory-to-document links without requiring a separate graph store or an LLM at ingest time.
208
-
209
- **Code Symbol Extraction** during `ingest_document`, code symbols are extracted from the chunk content using fast, highly-optimized regex heuristics (maintaining 100% portability and avoiding heavy binary parsers):
210
-
211
- - **JavaScript / TypeScript**: `function`, `class`, `interface`, `type`, `enum`, `const`, `let`, `var`
212
- - **Python**: `def`, `class`
213
- - **Go**: `struct`, `interface`, `func` (including methods with receivers)
214
- - **Rust**: `struct`, `enum`, `trait`, `fn` (including async/pub)
215
- - **C++**: `class`, `struct`, `namespace`, functions and methods
216
- - **Java & Kotlin**: `class`, `interface`, `record`, `enum`, `fun` and synchronized methods
217
- - **C#**: `class`, `interface`, `struct`, `record`, methods and properties
218
- - **PHP**: `class`, `interface`, `trait`, functions
219
- - **Ruby**: `module`, `class`, methods
220
- - Standard language keywords and symbols shorter than 3 characters are automatically filtered out using a comprehensive, cross-language ignored keyword list to prevent graph clutter.
221
-
222
- **Graph Edges** — three built-in relation types are created automatically, and custom relation types are supported for explicit linking:
223
-
224
- | Relation Type | Direction / Example |
225
- | :------------------ | :----------------------------------------------------------- |
226
- | `CONTAINS` | Document -> Section -> Micro-Chunk (3-tier hierarchy) |
227
- | `DEFINES_SYMBOL` | Section -> `symbol:<name>` (extracted code symbol) |
228
- | `LINKS_TO` (default) | Memory fact -> Document or line range (via `link_knowledge`) |
229
-
230
- **Memory-to-Knowledge Linking** the `link_knowledge` tool connects a notebook fact to a specific document or line range (`RULES_FOR`, `IMPLEMENTS`, `EXPLAINS`, `REFERENCES`, ...):
231
-
232
- - `link` — create the link and its graph edge
233
- - `list_links` — list all links, optionally filtered by fact key
234
- - `get_doc_links` list all links pointing to a given document
235
-
236
- Linked facts are surfaced automatically in `recall` results as `🔗 [Linked Docs: ...]`, and `remember` accepts an optional `docId` to link immediately.
237
-
238
- **Retrieval Integration** `query_knowledge_base` augments each retrieved section with `defined_symbols`: the code symbols defined in that same section (a single-hop lookup along `DEFINES_SYMBOL` edges). Symbol extraction also improves BM25 scoring, since symbol names become searchable tokens.
239
-
240
- **Lifecycle** edges are rebuilt transactionally on re-ingest of the same document, and `manage_knowledge_base` delete operations clean up all graph edges and knowledge links owned by the document (including `GLOB`-matched section/micro-chunk suffixes).
241
-
242
- ---
243
-
244
- ## Interactive TUI (CLI Menu)
245
-
246
- Launch the interactive terminal UI to manage engine settings, inspect databases, tune retrieval parameters, and run diagnostics:
247
-
248
- ```bash
249
- # From local repository folder:
250
- node mcp-server/index.js cli
251
- # or
252
- npx . cli
253
-
254
- # If installed / linked globally:
255
- memory_plugin cli
256
- # or
257
- memory-cli
258
- ```
259
-
260
- ### TUI Menu Overview
261
-
262
- The interactive menu exposes runtime parameters that `hybridQuery` honors, allowing search behavior modifications without restarting the MCP server. Use **Up / Down** arrows to navigate, **ENTER** to select, and **BACKSPACE** to go back.
263
-
264
- | Block | Menu Item | Functionality |
265
- | :-------------------------------------- | :------------------------------ | :----------------------------------------------------------------------------- |
266
- | **Engine & Hybrid Search Settings** | Fusion Algorithm | Switch between `rsf`, `rrf`, `semantic_only`, `lexical_only`. |
267
- | | RSF Alpha Balance | Weight of semantic over lexical in `rsf` fusion (`α ∈ [0,1]`). Default: `0.5`. |
268
- | | Embedding Model | Select ONNX model (e.g. `Xenova/multilingual-e5-small`, custom HF models). |
269
- | | Reranker Model | Enable Cross-Encoder reranking or disable for zero-latency fusion. |
270
- | | Vector Batch Size | Ingestion vector batch size `[1 - 256]` (default `12`). |
271
- | | GPU Attention Budget | GPU micro-batch attention budget `[1M - 16M]` (default `2.0M`, ~1.5 GB VRAM). |
272
- | | CPU WASM Threads | ONNX WASM threads: `0` auto-detect or `1-16`. |
273
- | | Execution Hardware | `cpu` or `webgpu` (experimental). |
274
- | **Knowledge Base & Storage Management** | Notebook (Layer 1 Facts) | Browse and manage `global` and per-project `.md` fact stores. |
275
- | | RAG Docs (Layer 2 Base) | List ingested documents, inspect chunk counts, and purge entries. |
276
- | | Snapshot Export / Import | Export or restore the full RAG base + blob store as a JSON snapshot. |
277
- | | Manage & Purge ML Model Cache | Inspect or purge downloaded ONNX model weights. |
278
- | | Hard Reset | Purge RAG base, blob storage, and graph edges. |
279
- | **Global Prompt & Integration** | Enable / Disable Global Prompt | Inject memory instructions into `~/.gemini/config/AGENTS.md`, `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md`. |
280
- | **Diagnostics & System Actions** | Search Quality Benchmark | Execute in-process search evaluation across the benchmark query set. |
281
- | | Verification Query | Run a test `hybridQuery` against the active index. |
282
- | | Clear Benchmark Corpus Cache | Clear cached benchmark corpus. |
283
- | | Reset Config to Factory Defaults| Restore default engine configuration. |
284
-
285
- Settings persist to `<memory-dir>/config.json` and are immediately loaded by the MCP server.
286
-
287
- ---
288
-
289
- ## Configuration
290
-
291
- The engine is configured through `<memory-dir>/config.json` (created with defaults on first run):
292
-
293
- | Key | Default | Description |
294
- | :-------------------- | :--------------------------------- | :-------------------------------------------------------------- |
295
- | `fusionAlgorithm` | `rsf` | `rsf`, `rrf`, `semantic_only`, or `lexical_only` |
296
- | `alpha` | `0.5` | Vector vs BM25 weight in RSF `[0.0 - 1.0]` |
297
- | `embeddingModel` | `Xenova/multilingual-e5-small` | ONNX dense embedding model (E5 / BGE families supported) |
298
- | `rerankerModel` | `none` | Cross-encoder reranker, or `Xenova/bge-reranker-base` |
299
- | `rerankerEnabled` | `false` | Enable cross-encoder re-ranking |
300
- | `batchSize` | `12` | Ingestion vector batch size `[1 - 256]` |
301
- | `gpuAttentionBudget` | `2000000` | GPU micro-batch attention budget `[1M - 16M]` |
302
- | `onnxThreads` | `0` | ONNX WASM threads: `0` auto-detect, or `1-16` |
303
- | `executionDevice` | `cpu` | `cpu` or `webgpu` (experimental) |
304
-
305
- ---
306
-
307
- ## Testing & Benchmarking
308
-
309
- To run the automated test suite and benchmarks locally:
310
-
311
- ```bash
312
- cd mcp-server
313
-
314
- # Run unit and integration tests
315
- npm test
316
-
317
- # Run search quality & ingestion benchmarks
318
- npm run benchmark
319
- ```
320
-
321
- ### Benchmark Methodology
322
-
323
- The benchmark suite (`mcp-server/benchmarks/`) evaluates retrieval quality across three phases:
324
-
325
- 1. **Dual-Layer Verification**: Asserts Notebook and RAG layers are isolated (zero crosstalk, 100% precision on `recall`).
326
- 2. **Ingestion Benchmark**: Ingests test documents with ONNX `multilingual-e5-small` embeddings, reporting throughput, DB size, CAS blob footprint, and heap delta.
327
- 3. **Search Quality Benchmark**: Evaluates cross-lingual and code-keyword queries against 4 retrieval strategies with bootstrap 95% CIs, paired t-tests, and hyperparameter sweeps over RSF $\alpha$ and RRF $k$.
328
-
329
- ### Search Quality Results (Smoke Test)
330
-
331
- _Note: The following metrics reflect a quick smoke-test evaluation run performed on a reduced subset of documents to verify retrieval logic precision._
332
-
333
- Evaluated across a reduced document subset using Mean Reciprocal Rank (MRR@5), Recall@5, and Normalized Discounted Cumulative Gain (NDCG@5):
334
-
335
- | Retrieval Strategy | MRR@5 | Recall@5 | NDCG@5 |
336
- | :---------------------------- | :--------: | :---------: | :--------: |
337
- | BM25 Lexical Search Only | 0.6706 | 76.19% | 0.6934 |
338
- | Dense ONNX Vector Only | 0.8135 | 100.00% | 0.8612 |
339
- | Hybrid RRF ($k=10$) | 0.8810 | 95.24% | 0.8997 |
340
- | **Hybrid RSF ($\alpha=0.5$)** | **0.9286** | **100.00%** | **0.9473** |
341
-
342
- For complete methodology details, see [`docs/BENCHMARKS.md`](./docs/BENCHMARKS.md).
343
-
344
- ---
345
-
346
- ## Documentation & Reports
347
-
348
- Detailed technical documentation and architectural specifications are available in the [`docs/`](./docs) directory:
349
-
350
- - [**Verification Report (`MEMORY_PLUGIN_REPORT.md`)**](./docs/MEMORY_PLUGIN_REPORT.md): Summary report covering MCP Tool Registry, JSON-RPC integration testing, layer isolation validation, and search precision.
351
- - [**Comprehensive Technical Report (`MEMORY_PLUGIN_COMPREHENSIVE_REPORT.md`)**](./docs/MEMORY_PLUGIN_COMPREHENSIVE_REPORT.md): Scientific analysis of system architecture, dual-layer model, hardware environment specifications, mathematical search formulations, and event-loop profiling.
352
- - [**Benchmark Methodology & Guide (`BENCHMARKS.md`)**](./docs/BENCHMARKS.md): Guide to automated benchmark execution, hyperparameter sweeps (RSF $\alpha$, RRF $k$), search quality metrics, and performance tracking across releases.
353
-
354
- ---
355
-
356
- ## Storage & Privacy
357
-
358
- - **100% Local Storage**: All SQLite indexes, ONNX models, CAS blobs, and Markdown notebooks are stored locally in the memory directory. The location resolves to, in order of priority: `$MEMORY_DIR`, `$OPENCODE_CONFIG_DIR/memory`, the legacy `~/.config/opencode/memory` (on Windows: `%LOCALAPPDATA%\opencode\memory`), or `$XDG_CONFIG_HOME/opencode/memory`.
359
- - **Dual-Source Failover Model Fetching**: Primary model weights are fetched from HuggingFace CDN with automatic failover to GitHub Repository Mirror.
360
- - **Zero External Telemetry**: No third-party network calls are required after initial model setup.
361
-
362
- ---
363
-
364
- ## License
365
-
366
- [MIT](./LICENSE)
1
+ <div align="center">
2
+
3
+ <img src="./assets/hero.jpg" alt="@lotargo/memory_plugin" width="800" style="max-width: 100%; border-radius: 12px; margin-bottom: 16px;">
4
+
5
+ <br>
6
+
7
+ <img src="./assets/title.svg" alt="@lotargo/memory_plugin" width="520" style="max-width: 100%; margin-bottom: 12px;">
8
+
9
+ <br>
10
+
11
+ [![npm version](https://img.shields.io/npm/v/@lotargo/memory_plugin)](https://www.npmjs.com/package/@lotargo/memory_plugin)
12
+ [![npm downloads](https://img.shields.io/npm/dt/@lotargo/memory_plugin)](https://www.npmjs.com/package/@lotargo/memory_plugin)
13
+ [![license](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
14
+ [![node version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org)
15
+ [![mcp](https://img.shields.io/badge/MCP-Supported-8A2BE2)](https://modelcontextprotocol.io)
16
+ [![storage](https://img.shields.io/badge/Storage-Local%20%2B%20Cloud%20Sync-success)](#storage--privacy)
17
+
18
+ <br>
19
+
20
+ **Zero-Docker Local Hybrid RAG Engine & Long-Term Memory for AI Coding Agents**
21
+
22
+ Automatically remembers durable user facts, ingests complex document repositories, and performs high-precision hybrid retrieval across sessions, platforms, and devices.
23
+
24
+ </div>
25
+
26
+ ---
27
+
28
+ ## Overview
29
+
30
+ Standard AI coding assistants lose context as soon as a chat session closes or a conversation is reset. You end up repeatedly re-explaining your preferences, architectural decisions, coding style, or project conventions.
31
+
32
+ `@lotargo/memory_plugin` gives your AI tools durable, **persistent**, local-first long-term memory and document retrieval capabilities that persist across restarts and work seamlessly across all supported coding environments. Any LLM-based coding agent (OpenCode, Claude Code, Codex, Antigravity / Gemini CLI) can query its own memory and hybrid knowledge base via the **Model Context Protocol (MCP)**.
33
+
34
+ > **Project Scope & Runtime Notes**:
35
+ > `@lotargo/memory_plugin` is designed primarily as a practical plugin to expand capabilities and streamline daily interaction with AI coding tools. Benchmark scores in this repository represent internal synthetic evaluation runs and are not intended as generalized RAG benchmarks.
36
+ >
37
+ > **Hardware Acceleration**: GPU execution mode is an experimental feature and may vary in stability across different operating systems or models. For optimal stability and consistent runtime performance, using standard CPU mode with `multilingual-e5-small` or `multilingual-e5-base` is recommended.
38
+
39
+ ### Practical Use Cases
40
+
41
+ - **Architectural Decisions**: _"In this project, we use Fastify instead of Express and strict schema validation via Zod."_
42
+ - **Coding Conventions**: _"Place all helper utilities inside `src/utils/` and cover new functions with Vitest tests."_
43
+ - **Environment Constraints**: _"Our target deployment environment is Node.js 20 on AWS Lambda."_
44
+ - **User Profile & Tone**: _"My name is Alex. I prefer concise, direct answers without conversational filler."_
45
+
46
+ ---
47
+
48
+ ## Quick Start
49
+
50
+ ### Minimum System Requirements
51
+
52
+ - **Node.js**: `18.0.0` or higher
53
+ - **Package Manager**: `npm` / `npx` (included with Node.js)
54
+ - **Supported Environment**: OpenCode, Antigravity / Gemini CLI, Claude Code, Codex, or Google Jules
55
+
56
+ ### Installation & Auto-Setup
57
+
58
+ Run the setup command to configure all detected AI environments automatically:
59
+
60
+ ```bash
61
+ # Recommended: Global installation & auto-setup across all environments
62
+ npm install -g @lotargo/memory_plugin && memory_plugin setup
63
+
64
+ # Or via npx
65
+ npx @lotargo/memory_plugin setup
66
+ ```
67
+
68
+ To target a specific environment:
69
+
70
+ ```bash
71
+ # Antigravity / Gemini CLI
72
+ memory_plugin setup --antigravity
73
+
74
+ # OpenCode
75
+ memory_plugin setup --opencode
76
+
77
+ # Claude Code
78
+ memory_plugin setup --claude
79
+
80
+ # Codex
81
+ memory_plugin setup --codex
82
+ ```
83
+
84
+ `setup` also accepts `--gemini` (alias for Antigravity) and `--local` (registers the MCP server in the project-local `.agents/` directory). Without a specific flag, all detected environments are configured.
85
+
86
+ ### Headless & Cloud Setup (CI / Docker / Cloud Workspaces)
87
+
88
+ For headless environments (e.g., Google Jules, VPS, CI/CD pipelines), configure auth and sync mode in a single non-interactive command:
89
+
90
+ ```bash
91
+ # Authenticate via Turso API token and set hybrid sync mode
92
+ memory_plugin setup --api-key <TURSO_API_TOKEN> --mode hybrid-sync
93
+
94
+ # Or set sync mode if already authorized
95
+ memory_plugin setup --mode only-cloud
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Multi-Layer Architecture
101
+
102
+ 1. **Layer 1: Notebook Store (Durable Facts)**
103
+ - **Tools**: `remember`, `recall`, `get_fact`, `update_fact`, `forget`, `memory_info`
104
+ - **Scope**: User preferences, identity, project conventions, system rules.
105
+ - **Storage**: Human-readable Markdown format (`global` and per-project stores).
106
+ - **Fact Schema**: Every fact is formatted as `**Title** body` with inline metadata badges (`[id]`, `[ttl]`, `[keep]`, `[tags]`, `[supersedes]`, `[inject]`).
107
+ - **Project Identity**: Project stores are bound to a **Git-based project identity** — the normalized remote URL (`git:github.com/owner/repo`) or `git:local:<repo basename>` — never to a directory path. Memories follow the repository across machines, OSes, and subdirectories. Legacy path/basename stores can be linked and merged via `link_project_memory`.
108
+
109
+ 2. **Layer 2: RAG Knowledge Base (Technical Documents & Codebases)**
110
+ - **Tools**: `ingest_document`, `query_knowledge_base`, `manage_knowledge_base`
111
+ - **Capabilities**: Ingests raw text files, Markdown, HTML, Web URLs, office documents (PDF, DOCX, XLSX, CSV), and codebases.
112
+ - **Engine Components**: 3-tier hierarchy chunking (Big / Medium / Small), SQLite FTS5 BM25 search, ONNX dense vector embeddings (`multilingual-e5-small`), Reciprocal Rank Fusion (RRF / RSF), cross-encoder reranking (optional), and GraphRAG Lite code symbol extraction.
113
+
114
+ 3. **Layer 3: Agent-Driven Knowledge Graph**
115
+ - **Tools**: `link_knowledge` (plus `docId`, `startLine`, `endLine` in `remember`)
116
+ - **Capabilities**: Connects Layer 1 notebook facts directly to Layer 2 documents, sections, or exact line ranges with semantic edge relations (`RULES_FOR`, `IMPLEMENTS`, `EXPLAINS`, `REFERENCES`).
117
+ - **Surfacing**: Linked facts automatically highlight target documents and line ranges in `recall` output (`🔗 [Linked Docs: ...]`).
118
+
119
+ ---
120
+
121
+ ## Cloud Synchronization & Database Modes (Turso / LibSQL)
122
+
123
+ The plugin provides local-first SQLite persistence with optional cloud database synchronization powered by Turso (LibSQL):
124
+
125
+ ### 3 Storage Sync Modes
126
+
127
+ | Mode | Command / Flag | Description |
128
+ | :--- | :------------- | :---------- |
129
+ | **`only-local`** (default) | `--mode only-local` | 100% local SQLite database. No external network traffic for data storage. |
130
+ | **`only-cloud`** | `--mode only-cloud` | Direct LibSQL connection to a remote Turso database instance. |
131
+ | **`hybrid-sync`** | `--mode hybrid-sync` | Local SQLite performance with background asynchronous synchronization to Turso Cloud, featuring automatic reverse-sync and conflict resolution. |
132
+
133
+ ### Cloud Failover & Circuit Breaker
134
+
135
+ When operating in cloud modes (`only-cloud` or `hybrid-sync`), the database engine incorporates a built-in **Circuit Breaker**:
136
+ - If the primary cloud database endpoint is unreachable or encounters network failure, queries seamlessly fail over to the local database cache.
137
+ - Prevents agent blocking or crash loops during internet outages or cloud service degradation.
138
+
139
+ ### Secure Credential Storage
140
+
141
+ Cloud authentication tokens and secrets are stored securely using platform-native hardware-bound encryption (Windows DPAPI / OS Secret Store), preventing token exposure in plain-text configuration files.
142
+
143
+ ---
144
+
145
+ ## Available MCP Tools
146
+
147
+ The plugin registers **15 MCP tools** accessible across all connected AI environments:
148
+
149
+ ### 1. Memory Notebook Tools (Layer 1)
150
+
151
+ | Tool | Scope / Target | Key Parameters | Description |
152
+ | :--- | :------------- | :------------- | :---------- |
153
+ | `remember` | `project` / `global` | `fact`, `title`, `scope`, `docId`, `startLine`, `endLine`, `relationType`, `ttl`, `keep`, `tags`, `supersedes` | Save a durable fact or preference. Supports optional title, document linking, TTL, keep protection, tags, and version superseding. |
154
+ | `recall` | `all`, `project`, `global`, `list_projects` | `scope`, `project`, `query`, `tags`, `since`, `until`, `mode`, `offset`, `limit` | Display saved facts with metadata badges and linked docs. Supports cross-project lookup via `project: '<path>'` and header-only mode (`mode: "headers"`). |
155
+ | `get_fact` | `all`, `project`, `global` | `id`, `scope` | Retrieve full text, raw line, and metadata of a single fact by its metadata ID (e.g. `"8f3a2c"`). |
156
+ | `update_fact` | `project` / `global` | `id`, `newText`, `scope` | Rewrite a fact while preserving its original creation date, metadata, and knowledge links. |
157
+ | `forget` | `project` / `global` | `id` / `range` / `query`, `scope`, `force` | Remove a fact by index number, ID, range (e.g. `"3-30"`), or query. Requires `force: true` for protected (`[KEEP]`) facts. |
158
+ | `memory_info` | - | - | Show storage paths, fact counts, RAG statistics, git identity bindings, and package version. |
159
+
160
+ ### 2. Project Identity Tools
161
+
162
+ | Tool | Key Parameters | Description |
163
+ | :--- | :------------- | :---------- |
164
+ | `link_project_memory` | `directory`, `remote` | Link a directory path to a Git-based project identity key, register aliases, and migrate legacy path/basename stores with deduplication. |
165
+ | `unlink_project_memory` | `directory`, `purge` | Remove a path alias binding for a directory. Optionally purge the project identity entry if `purge: true`. |
166
+ | `relink_project_memory` | `directory`, `remote` | Switch a project's primary identity to a new remote URL and merge all stored facts into the target store with fact-text deduplication. |
167
+
168
+ ### 3. RAG Knowledge Base & Graph Tools (Layers 2 & 3)
169
+
170
+ | Tool | Key Parameters | Description |
171
+ | :--- | :------------- | :---------- |
172
+ | `ingest_document` | `content`, `type`, `title`, `path`, `generateEmbeddings` | Ingest local files, URLs, or raw text into the 3-tier index (Big/Medium/Small) with ONNX vector embeddings and GraphRAG symbol extraction. |
173
+ | `query_knowledge_base` | `query`, `limit`, `instruction`, `generateEmbeddings` | Perform hybrid search (RSF/RRF BM25 + dense vector similarity) to retrieve candidate document sections with defined code symbols. |
174
+ | `manage_knowledge_base` | `action`, `docId`, `snapshotPath` | Inspect DB stats (`stats`), list documents (`list`), read full raw document (`read_document`), delete document (`delete`), or export/import snapshots (`export_snapshot` / `import_snapshot`). |
175
+ | `link_knowledge` | `action`, `factText`, `docId`, `scope`, `startLine`, `endLine`, `relationType` | Create, list, or retrieve semantic graph links connecting Notebook facts to Knowledge Base documents, sections, or line ranges. Actions: `link`, `list_links`, `get_doc_links`. |
176
+
177
+ ### 4. Agent & OpenCode Helpers
178
+
179
+ | Tool | Key Parameters | Description |
180
+ | :--- | :------------- | :---------- |
181
+ | `list-mcp-tools` | - | Discover all connected MCP servers and their available tool definitions. |
182
+ | `mcp-reminder` | `task` | Recommends the appropriate MCP tool or server for a specific developer task. |
183
+
184
+ ---
185
+
186
+ ## CLI Command Reference
187
+
188
+ The plugin provides both direct non-interactive CLI commands and an interactive terminal UI (TUI):
189
+
190
+ ```bash
191
+ # Executable commands (available globally or via npx)
192
+ memory_plugin <command> [options]
193
+ # or
194
+ memory-cli <command> [options]
195
+ ```
196
+
197
+ ### Direct Non-Interactive Commands
198
+
199
+ | Command | Options / Flags | Description |
200
+ | :------ | :-------------- | :---------- |
201
+ | **`setup`** | `--antigravity`, `--opencode`, `--claude`, `--codex`, `--local`, `--api-key <TOKEN>`, `--mode <MODE>` | Configures MCP server registrations across detected environments and sets initial cloud auth/sync mode. |
202
+ | **`link`** | `--dir <path>`, `--remote <url>` | Links a directory to a Git project identity or remote URL. |
203
+ | **`unlink`** | `--dir <path>`, `--purge` | Unlinks a directory path alias. `--purge` removes the identity record. |
204
+ | **`relink`** | `--remote <url>`, `--dir <path>` | Relinks project identity to a new remote URL and merges facts. |
205
+ | **`identity`** | `--dir <path>` | Inspects Git project identity key, primary remote, name, and toplevel path for a directory. |
206
+ | **`migrate_titles`** | `--key <key>` | Auto-generates `**Title**` prefixes for legacy facts without titles. |
207
+ | **`enable-prompt`** | - | Injects memory agent instructions into client agent files (`AGENTS.md`, `CLAUDE.md`). |
208
+ | **`disable-prompt`** | - | Removes memory agent instructions from client agent files. |
209
+ | **`login`** | `--api-key <TOKEN>`, `--from-env`, `--db-url <URL> --db-token <TOKEN>` | Authenticates with Turso Cloud via API key, direct DB token, or environment variables. |
210
+ | **`logout`** | `--api-key` | Signs out of Turso Cloud or removes stored API key while retaining DB session. |
211
+ | **`auth-status`** | - | Displays authentication source, endpoint URL, username, organization, database, and sync mode. |
212
+
213
+ ### Interactive TUI (CLI Menu)
214
+
215
+ Launch the interactive terminal UI to manage engine settings, tune retrieval algorithms, inspect databases, and run diagnostics:
216
+
217
+ ```bash
218
+ memory_plugin cli
219
+ # or
220
+ memory-cli
221
+ ```
222
+
223
+ #### TUI Menu Navigation
224
+
225
+ Use **Up / Down** arrows to navigate, **ENTER** to select, and **BACKSPACE** to go back.
226
+
227
+ - **Engine & Hybrid Search Settings**: Switch fusion algorithms (`rsf`, `rrf`, `semantic_only`, `lexical_only`), adjust RSF $\alpha$ balance, select ONNX embedding models, toggle Cross-Encoder rerankers, configure GPU attention budget, and set WASM threads.
228
+ - **Knowledge Base & Storage Management**: Browse Layer 1 facts, manage Layer 2 RAG docs, export/import JSON snapshots, purge model cache, or perform a hard reset.
229
+ - **Global Prompt & Integration**: Toggle memory instruction sync across client configurations (`~/.gemini/config/AGENTS.md`, `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md`).
230
+ - **Diagnostics & System Actions**: Run in-process search quality benchmarks, execute verification queries, clear corpus cache, and reset config to factory defaults.
231
+
232
+ ---
233
+
234
+ ## Agent Skill & System Prompt Integration
235
+
236
+ ### Built-in Agent Skill (`using-memory`)
237
+
238
+ The plugin bundles a pre-configured Agent Skill located at [`skills/using-memory/SKILL.md`](./skills/using-memory/SKILL.md). When installed in supported environments (such as Antigravity / Gemini CLI or OpenCode), coding agents automatically read this skill to:
239
+ 1. **Initialize Sessions**: Automatically invoke `recall(scope: "all")` at the start of every chat turn to load all saved preferences and project rules.
240
+ 2. **Proactively Save Context**: Automatically call `remember` whenever you share durable facts, tech stack choices, or coding guidelines.
241
+ 3. **Architect Knowledge Graphs**: Use `link_knowledge` or `remember(docId, startLine, endLine)` to connect memories directly to technical documentation.
242
+
243
+ ### Global System Prompt Synchronization
244
+
245
+ Run `memory_plugin enable-prompt` to automatically inject memory agent guidance into your global LLM configuration files:
246
+ - `~/.gemini/config/AGENTS.md` (Antigravity / Gemini CLI)
247
+ - `~/.codex/AGENTS.md` (Codex)
248
+ - `~/.claude/CLAUDE.md` (Claude Code)
249
+
250
+ This ensures your coding assistant is always aware of its memory capabilities even in fresh workspace sessions.
251
+
252
+ ---
253
+
254
+ ## GraphRAG Lite
255
+
256
+ The RAG engine includes a lightweight graph layer built on SQLite. It combines code symbol extraction, hierarchy edges, and explicit memory-to-document links without requiring external graph databases or LLM calls at ingest time.
257
+
258
+ ### Multilingual Code Symbol Parsing
259
+
260
+ During `ingest_document`, code symbols are extracted from code blocks using fast regex heuristics across 10 programming languages:
261
+
262
+ - **JavaScript / TypeScript**: `function`, `class`, `interface`, `type`, `enum`, `const`, `let`, `var`
263
+ - **Python**: `def`, `class`
264
+ - **Go**: `struct`, `interface`, `func` (including methods with receivers)
265
+ - **Rust**: `struct`, `enum`, `trait`, `fn` (including async/pub)
266
+ - **C++**: `class`, `struct`, `namespace`, functions and methods
267
+ - **Java & Kotlin**: `class`, `interface`, `record`, `enum`, `fun`, synchronized methods
268
+ - **C#**: `class`, `interface`, `struct`, `record`, methods and properties
269
+ - **PHP**: `class`, `interface`, `trait`, functions
270
+ - **Ruby**: `module`, `class`, methods
271
+
272
+ ### Graph Edges
273
+
274
+ | Relation Type | Direction / Example |
275
+ | :--- | :--- |
276
+ | `CONTAINS` | Document -> Section -> Micro-Chunk (3-tier hierarchy) |
277
+ | `DEFINES_SYMBOL` | Section -> `symbol:<name>` (extracted code symbol) |
278
+ | `LINKS_TO` (default) | Memory fact -> Document or line range (via `link_knowledge`) |
279
+
280
+ ---
281
+
282
+ ## Supported Platforms
283
+
284
+ | Platform | Status | Configuration Mechanism |
285
+ | :--- | :--- | :--- |
286
+ | **Antigravity / Gemini CLI** | Supported | MCP Server (`~/.gemini/config/mcp_config.json` & `.agents/mcp_config.json`) |
287
+ | **OpenCode** | Native | Native plugin + MCP Server (`~/.config/opencode/opencode.json`) |
288
+ | **Claude Code** | Supported | MCP Server (`~/.claude.json`) |
289
+ | **Codex** | Supported | MCP Server (`~/.codex/config.toml`) |
290
+ | **Google Jules** | Supported | MCP Server via global install + setup (`memory_plugin setup`) |
291
+
292
+ ---
293
+
294
+ ## Configuration
295
+
296
+ The engine is configured through `<memory-dir>/config.json` (created with defaults on first run):
297
+
298
+ | Key | Default | Description |
299
+ | :--- | :--- | :--- |
300
+ | `mode` | `only-local` | Storage sync mode: `only-local`, `only-cloud`, or `hybrid-sync` |
301
+ | `fusionAlgorithm` | `rsf` | `rsf`, `rrf`, `semantic_only`, or `lexical_only` |
302
+ | `alpha` | `0.5` | Vector vs BM25 weight in RSF `[0.0 - 1.0]` |
303
+ | `embeddingModel` | `Xenova/multilingual-e5-small` | ONNX dense embedding model (E5 / BGE families supported) |
304
+ | `rerankerModel` | `none` | Cross-encoder reranker model (e.g. `Xenova/bge-reranker-base`) |
305
+ | `rerankerEnabled` | `false` | Enable cross-encoder re-ranking |
306
+ | `batchSize` | `12` | Ingestion vector batch size `[1 - 256]` |
307
+ | `gpuAttentionBudget` | `2000000` | GPU micro-batch attention budget `[1M - 16M]` |
308
+ | `onnxThreads` | `0` | ONNX WASM threads: `0` auto-detect, or `1-16` |
309
+ | `executionDevice` | `cpu` | `cpu` or `webgpu` (experimental) |
310
+
311
+ ---
312
+
313
+ ## Testing & Benchmarking
314
+
315
+ To run the automated test suite and benchmarks locally:
316
+
317
+ ```bash
318
+ cd mcp-server
319
+
320
+ # Run unit and integration tests
321
+ npm test
322
+
323
+ # Run search quality & ingestion benchmarks
324
+ npm run benchmark
325
+ ```
326
+
327
+ For complete methodology details and search quality evaluation metrics, see [`docs/BENCHMARKS.md`](./docs/BENCHMARKS.md).
328
+
329
+ ### Empirical Search Quality Results
330
+
331
+ Evaluated across a 32-document technical corpus (21 queries) using Mean Reciprocal Rank (MRR@5), Recall@5, and Normalized Discounted Cumulative Gain (NDCG@5):
332
+
333
+ | Retrieval Strategy | MRR@5 | Recall@5 | NDCG@5 |
334
+ | :---------------------------- | :--------: | :---------: | :--------: |
335
+ | BM25 Lexical Search Only | 0.6706 | 76.19% | 0.6934 |
336
+ | Dense ONNX Vector Only | 0.8135 | 100.00% | 0.8612 |
337
+ | Hybrid RRF ($k=10$) | 0.8810 | 95.24% | 0.8997 |
338
+ | **Hybrid RSF ($\alpha=0.5$)** | **0.9286** | **100.00%** | **0.9473** |
339
+
340
+ ---
341
+
342
+ ## Storage & Privacy
343
+
344
+ - **Local-First Storage**: All SQLite indexes, ONNX models, CAS blobs, and Markdown notebooks are stored locally in the memory directory (`$MEMORY_DIR` or `%LOCALAPPDATA%\opencode\memory`).
345
+ - **Dual-Source Failover Model Fetching**: Primary model weights are fetched from HuggingFace CDN with automatic failover to GitHub Repository Mirror.
346
+ - **Zero Telemetry**: No third-party network telemetry calls are made.
347
+
348
+ ---
349
+
350
+ ## License
351
+
352
+ [MIT](./LICENSE)