@bloodyeagle/megamemory 0.0.0-stage → 1.6.3-fork.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 (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +198 -2
  3. package/README.ru.md +201 -0
  4. package/commands/bootstrap-memory.md +51 -0
  5. package/commands/save-memory.md +84 -0
  6. package/dist/cli-utils.d.ts +23 -0
  7. package/dist/cli-utils.d.ts.map +1 -0
  8. package/dist/cli-utils.js +174 -0
  9. package/dist/cli-utils.js.map +1 -0
  10. package/dist/consolidate-cli.d.ts +9 -0
  11. package/dist/consolidate-cli.d.ts.map +1 -0
  12. package/dist/consolidate-cli.js +81 -0
  13. package/dist/consolidate-cli.js.map +1 -0
  14. package/dist/consolidate.d.ts +36 -0
  15. package/dist/consolidate.d.ts.map +1 -0
  16. package/dist/consolidate.js +161 -0
  17. package/dist/consolidate.js.map +1 -0
  18. package/dist/db.d.ts +286 -0
  19. package/dist/db.d.ts.map +1 -0
  20. package/dist/db.js +1028 -0
  21. package/dist/db.js.map +1 -0
  22. package/dist/digest-cli.d.ts +8 -0
  23. package/dist/digest-cli.d.ts.map +1 -0
  24. package/dist/digest-cli.js +51 -0
  25. package/dist/digest-cli.js.map +1 -0
  26. package/dist/digest.d.ts +55 -0
  27. package/dist/digest.d.ts.map +1 -0
  28. package/dist/digest.js +154 -0
  29. package/dist/digest.js.map +1 -0
  30. package/dist/doctor-cli.d.ts +8 -0
  31. package/dist/doctor-cli.d.ts.map +1 -0
  32. package/dist/doctor-cli.js +43 -0
  33. package/dist/doctor-cli.js.map +1 -0
  34. package/dist/doctor.d.ts +16 -0
  35. package/dist/doctor.d.ts.map +1 -0
  36. package/dist/doctor.js +110 -0
  37. package/dist/doctor.js.map +1 -0
  38. package/dist/embed-model.d.ts +11 -0
  39. package/dist/embed-model.d.ts.map +1 -0
  40. package/dist/embed-model.js +11 -0
  41. package/dist/embed-model.js.map +1 -0
  42. package/dist/embeddings.d.ts +72 -0
  43. package/dist/embeddings.d.ts.map +1 -0
  44. package/dist/embeddings.js +204 -0
  45. package/dist/embeddings.js.map +1 -0
  46. package/dist/eval-cli.d.ts +8 -0
  47. package/dist/eval-cli.d.ts.map +1 -0
  48. package/dist/eval-cli.js +63 -0
  49. package/dist/eval-cli.js.map +1 -0
  50. package/dist/eval.d.ts +32 -0
  51. package/dist/eval.d.ts.map +1 -0
  52. package/dist/eval.js +48 -0
  53. package/dist/eval.js.map +1 -0
  54. package/dist/export-cli.d.ts +9 -0
  55. package/dist/export-cli.d.ts.map +1 -0
  56. package/dist/export-cli.js +56 -0
  57. package/dist/export-cli.js.map +1 -0
  58. package/dist/export.d.ts +30 -0
  59. package/dist/export.d.ts.map +1 -0
  60. package/dist/export.js +111 -0
  61. package/dist/export.js.map +1 -0
  62. package/dist/index.d.ts +3 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +559 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/install.d.ts +3 -0
  67. package/dist/install.d.ts.map +1 -0
  68. package/dist/install.js +617 -0
  69. package/dist/install.js.map +1 -0
  70. package/dist/merge-cli.d.ts +4 -0
  71. package/dist/merge-cli.d.ts.map +1 -0
  72. package/dist/merge-cli.js +251 -0
  73. package/dist/merge-cli.js.map +1 -0
  74. package/dist/merge.d.ts +44 -0
  75. package/dist/merge.d.ts.map +1 -0
  76. package/dist/merge.js +468 -0
  77. package/dist/merge.js.map +1 -0
  78. package/dist/migrate-cli.d.ts +16 -0
  79. package/dist/migrate-cli.d.ts.map +1 -0
  80. package/dist/migrate-cli.js +117 -0
  81. package/dist/migrate-cli.js.map +1 -0
  82. package/dist/migrate-schema.d.ts +41 -0
  83. package/dist/migrate-schema.d.ts.map +1 -0
  84. package/dist/migrate-schema.js +264 -0
  85. package/dist/migrate-schema.js.map +1 -0
  86. package/dist/migrate.d.ts +34 -0
  87. package/dist/migrate.d.ts.map +1 -0
  88. package/dist/migrate.js +134 -0
  89. package/dist/migrate.js.map +1 -0
  90. package/dist/norm.d.ts +8 -0
  91. package/dist/norm.d.ts.map +1 -0
  92. package/dist/norm.js +14 -0
  93. package/dist/norm.js.map +1 -0
  94. package/dist/reembed-cli.d.ts +11 -0
  95. package/dist/reembed-cli.d.ts.map +1 -0
  96. package/dist/reembed-cli.js +54 -0
  97. package/dist/reembed-cli.js.map +1 -0
  98. package/dist/reembed.d.ts +26 -0
  99. package/dist/reembed.d.ts.map +1 -0
  100. package/dist/reembed.js +45 -0
  101. package/dist/reembed.js.map +1 -0
  102. package/dist/search.d.ts +76 -0
  103. package/dist/search.d.ts.map +1 -0
  104. package/dist/search.js +176 -0
  105. package/dist/search.js.map +1 -0
  106. package/dist/stats.d.ts +2 -0
  107. package/dist/stats.d.ts.map +1 -0
  108. package/dist/stats.js +159 -0
  109. package/dist/stats.js.map +1 -0
  110. package/dist/timeline.d.ts +13 -0
  111. package/dist/timeline.d.ts.map +1 -0
  112. package/dist/timeline.js +21 -0
  113. package/dist/timeline.js.map +1 -0
  114. package/dist/tools.d.ts +62 -0
  115. package/dist/tools.d.ts.map +1 -0
  116. package/dist/tools.js +655 -0
  117. package/dist/tools.js.map +1 -0
  118. package/dist/types.d.ts +283 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/types.js +3 -0
  121. package/dist/types.js.map +1 -0
  122. package/dist/web.d.ts +2 -0
  123. package/dist/web.d.ts.map +1 -0
  124. package/dist/web.js +776 -0
  125. package/dist/web.js.map +1 -0
  126. package/docs/FORK.md +94 -0
  127. package/fixtures/demo.db +0 -0
  128. package/fixtures/eval.jsonl +25 -0
  129. package/package.json +65 -4
  130. package/plugin/megamemory.ts +170 -0
  131. package/web/index.html +2267 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 0xk3vin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <h1 align="center">MegaMemory <sub><sup>fork</sup></sub></h1>
3
+ </p>
4
+ <p align="center">Persistent project knowledge graph for coding agents — multilingual, token-economical, visible in the UI.</p>
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ <p align="center">
7
+ <a href="./LICENSE"><img alt="license" src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" /></a>
8
+ <img alt="node" src="https://img.shields.io/badge/node-%3E%3D18-brightgreen?style=flat-square" />
9
+ <img alt="version" src="https://img.shields.io/badge/version-1.6.3--fork.1-orange?style=flat-square" />
10
+ </p>
11
+
12
+ <p align="center">
13
+ <img src="./assets/preview.png" alt="MegaMemory web explorer" width="800" />
14
+ </p>
15
+
16
+ > **Fork of [0xK3vin/MegaMemory](https://github.com/0xK3vin/MegaMemory) v1.6.2 (MIT).**
17
+ > Upstream keeps the concept, this fork fixes multilingual IDs, adds hybrid search,
18
+ > a context budget, fact freshness, digests, export and token accounting.
19
+ > Русская версия: [README.ru.md](./README.ru.md).
20
+
21
+ An [MCP](https://modelcontextprotocol.io/) server that lets your coding agent build and query a
22
+ graph of concepts, architecture, and decisions — so it **remembers across sessions**.
23
+
24
+ The LLM is the indexer. No AST parsing, no static analysis: the agent reads code, writes concepts
25
+ in its own words, and queries them before future tasks. The graph stores **concepts** — features,
26
+ modules, patterns, decisions — not code symbols. Everything persists in a per-project SQLite
27
+ database at `.megamemory/knowledge.db`.
28
+
29
+ ---
30
+
31
+ ## What this fork changes
32
+
33
+ | Area | Upstream 1.6.2 | This fork |
34
+ |---|---|---|
35
+ | Node IDs | slug strips everything outside `[a-z0-9-]`; Cyrillic, CJK, Greek, emoji names collapse to `""` and the second such node is lost | Unicode-safe slug: letters of any script, diacritics stripped only after Latin/Cyrillic/Greek/Hebrew bases (katakana dakuten and Hangul jamo are preserved), `/` becomes `-`, NFC output, hash fallback for emoji-only names, `-<hash8>` on collisions |
36
+ | Embeddings | `all-MiniLM-L6-v2`, English-only, dimension hardcoded | `Xenova/multilingual-e5-small` by default (`MEGAMEMORY_EMBED_MODEL`), e5 `passage:`/`query:` prefixes, dimension read from the model, vector search disabled on model mismatch until `megamemory reembed` |
37
+ | Search | cosine similarity only | hybrid: FTS5 + vector fused with RRF, per-hit `via: vector \| fts \| both`, query sanitization for `MATCH`, short-CJK routing, optional trigram index, `name_norm` LIKE fallback |
38
+ | Context | `understand` returns everything it found | `mode: "compact"` by default, bounded by `max_tokens` (1500), summaries trimmed to 240 chars, edges between returned nodes only, `meta.returned / dropped / tokens_estimated` |
39
+ | Freshness | delete or nothing | node `status` (`active`/`superseded`/`deprecated`), `supersedes` and `contradicts` edges, outdated nodes hidden from answers but visible in the graph |
40
+ | Duplicates | manual merge | `megamemory consolidate` finds embedding-similar pairs (≥ 0.95) and merges them with edge transfer |
41
+ | Long modules | every child read separately | `digest` nodes: one per module, rebuilt after the 5th child, lower search weight |
42
+ | Portability | DB only | `megamemory export --md <dir>` writes one markdown file per node (frontmatter + wiki-links), `--check` for CI |
43
+ | Cost visibility | none | every `understand` / `list_roots` / `get_concept` is measured; 7-day aggregates in `megamemory stats`, `/api/stats` and the explorer's **Tokens** panel |
44
+ | Migration | — | `megamemory migrate --dry-run/--apply` upgrades an upstream database in place, additively, with backups and a downgrade-safe schema |
45
+
46
+ ---
47
+
48
+ ## The loop
49
+
50
+ `understand → work → update`
51
+
52
+ 1. **Session start** — the agent calls `list_roots` (budgeted) to orient itself.
53
+ 2. **Before a task** — `understand` with a natural-language query, or `get_concept` for an exact ID.
54
+ 3. **After a task** — `create_concept` / `update_concept`, then `link` for relationships.
55
+
56
+ ---
57
+
58
+ ## Install
59
+
60
+ Requires Node.js >= 18. For Russian-only projects a much smaller model (`cointegrated/rubert-tiny2`, 312-dim) works after an ONNX conversion; the model unloads after 5 minutes idle (`MEGAMEMORY_EMBED_IDLE_MS=0` disables that), and `MEGAMEMORY_SEARCH=fts` avoids loading it at all. The embedding model (~120 MB, multilingual) downloads on first use and is
61
+ cached in `~/.cache/huggingface`.
62
+
63
+ The fork is not published to npm — install from a tarball or a checkout:
64
+
65
+ ```bash
66
+ git clone https://github.com/BloodyEagle/MegaMemoryAgent.git
67
+ cd MegaMemoryAgent
68
+ npm ci
69
+ npm run build
70
+ npm pack # megamemory-1.6.3-fork.1.tgz
71
+ npm install -g ./megamemory-1.6.3-fork.1.tgz
72
+ ```
73
+
74
+ Then either run the installer or register the MCP server by hand:
75
+
76
+ ```bash
77
+ megamemory install # interactive: opencode / [CC] / Codex / Antigravity
78
+ ```
79
+
80
+ ```json
81
+ {
82
+ "megamemory": {
83
+ "type": "local",
84
+ "command": ["megamemory"],
85
+ "enabled": true
86
+ }
87
+ }
88
+ ```
89
+
90
+ The server reads `.megamemory/knowledge.db` relative to the working directory; override with
91
+ `MEGAMEMORY_DB_PATH`.
92
+
93
+ ### Upgrading an existing upstream database
94
+
95
+ ```bash
96
+ megamemory migrate --dry-run # prints the plan, changes nothing
97
+ megamemory migrate --apply # backs up knowledge.db.bak-<ts>, applies the additive schema
98
+ megamemory reembed # only needed if the embedding model changed
99
+ megamemory doctor # health check, exit code 1 on problems
100
+ ```
101
+
102
+ The migration never drops or renames a column, so upstream v1.6.2 still opens a migrated database.
103
+ Nodes lost upstream to the empty-ID bug cannot be recovered; `--dry-run` reports them explicitly.
104
+
105
+ ---
106
+
107
+ ## MCP tools
108
+
109
+ | Tool | Description |
110
+ |---|---|
111
+ | `understand` | Hybrid search over the graph. `top_k`, `max_tokens`, `mode: "compact" \| "full"`, `include_inactive`. |
112
+ | `get_concept` | Exact-ID lookup with children, edges, incoming edges, parent. |
113
+ | `create_concept` | Add a concept with edges, file refs and `supersedes`. |
114
+ | `update_concept` | Update fields; embeddings are regenerated. |
115
+ | `link` | Typed relationship between concepts. |
116
+ | `remove_concept` | Soft-delete with a reason; history kept, status set to `deprecated`. |
117
+ | `list_roots` | Top-level concepts with direct children (budgeted). |
118
+ | `list_conflicts` | Unresolved merge conflicts, plus `contradicts` pairs. |
119
+ | `resolve_conflict` | Resolve a conflict with verified content. |
120
+
121
+ **Kinds:** `feature` · `module` · `pattern` · `config` · `decision` · `component` · `digest`
122
+
123
+ **Relations:** `connects_to` · `depends_on` · `implements` · `calls` · `configured_by` · `supersedes` · `contradicts`
124
+
125
+ ---
126
+
127
+ ## CLI
128
+
129
+ | Command | What it does |
130
+ |---|---|
131
+ | `megamemory install` | Configure an MCP client |
132
+ | `megamemory serve [--port N]` | Web explorer (graph, search, node cards, Tokens panel, consolidate tab) |
133
+ | `megamemory migrate [--dry-run\|--apply]` | Upgrade an upstream database |
134
+ | `megamemory repair-ids [--apply]` | Rebuild empty / trailing-slash IDs from names |
135
+ | `megamemory reembed` | Recompute embeddings (resumable, batched) |
136
+ | `megamemory doctor` | Health check: schema, model, FTS, IDs, vectors, orphans, digests |
137
+ | `megamemory stats` | Graph and token statistics |
138
+ | `megamemory eval` | recall@10 over `fixtures/eval.jsonl` |
139
+ | `megamemory consolidate [--dry-run\|--apply]` | Find and merge near-duplicate nodes |
140
+ | `megamemory digest [--apply]` | Build or rebuild digest nodes |
141
+ | `megamemory export --md <dir> [--check]` | Markdown export, CI-friendly drift check |
142
+ | `megamemory merge`, `conflicts`, `resolve` | Two-way merge of graphs across branches |
143
+
144
+ ---
145
+
146
+ ## Environment
147
+
148
+ | Variable | Default | Meaning |
149
+ |---|---|---|
150
+ | `MEGAMEMORY_DB_PATH` | `./.megamemory/knowledge.db` | Database location |
151
+ | `MEGAMEMORY_EMBED_MODEL` | `Xenova/multilingual-e5-small` | Embedding model (any transformers.js ONNX model) |
152
+ | `MEGAMEMORY_SEARCH` | `hybrid` | `hybrid` / `fts` / `vector` |
153
+ | `MEGAMEMORY_FTS_TOKENIZER` | — | `trigram` adds a second index for CJK |
154
+ | `MEGAMEMORY_AUTO_DIGEST` | on | `0` disables auto-digest after the 5th child |
155
+
156
+ ---
157
+
158
+ ## Web explorer
159
+
160
+ ```bash
161
+ megamemory serve --port 8080
162
+ ```
163
+
164
+ - nodes colored by kind, sized by edge count; `digest` nodes and outdated (`superseded`) nodes are visually distinct
165
+ - `supersedes` edges drawn dashed, status badges in the node card, "show outdated" toggle
166
+ - search hits carry a `via` badge (vector / fts / both) and a budget line: `N nodes, ~X tokens, dropped M`
167
+ - **Tokens** panel: average answer size and saved tokens over 7 days
168
+ - **Consolidate** tab: duplicate candidates with apply
169
+
170
+ ---
171
+
172
+ ## Tests
173
+
174
+ ```bash
175
+ npm run build
176
+ npx vitest run src/__tests__/id-generation.test.ts --reporter=dot # targeted
177
+ npx vitest run # full suite (slow: model download)
178
+ ```
179
+
180
+ `fixtures/demo.db` is a ready-made graph (ru/en/zh/emoji, one `superseded`, one `digest`, one
181
+ duplicate pair) for manual checks in the explorer.
182
+
183
+ ---
184
+
185
+ ## Compatibility and limits
186
+
187
+ - Upstream v1.6.2 keeps working against a migrated database: new columns have defaults, FTS
188
+ triggers maintain the index for upstream inserts. Backups `knowledge.db.bak-<ts>`, last 3 kept.
189
+ - FTS5 requires libsql's local file mode — MegaMemory is local-only; remote Turso forbids virtual tables.
190
+ - After any `VACUUM`, run `megamemory migrate --apply` to rebuild the FTS index (rowids are not stable).
191
+ - Russian text is not stemmed by FTS5's `unicode61`; the vector channel compensates, prefix queries help.
192
+
193
+ ---
194
+
195
+ ## Credits and license
196
+
197
+ Based on [MegaMemory](https://github.com/0xK3vin/MegaMemory) by 0xK3vin (MIT).
198
+ Fork maintained by [BloodyEagle](https://github.com/BloodyEagle). MIT, see [LICENSE](./LICENSE).
199
+ Differences and sync instructions: [docs/FORK.md](./docs/FORK.md).
package/README.ru.md ADDED
@@ -0,0 +1,201 @@
1
+ <p align="center">
2
+ <h1 align="center">MegaMemory <sub><sup>форк</sup></sub></h1>
3
+ </p>
4
+ <p align="center">Граф знаний проекта для кодинг-агентов — мультиязычный, экономный по токенам, видимый в интерфейсе.</p>
5
+
6
+ <p align="center">
7
+ <a href="./LICENSE"><img alt="license" src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" /></a>
8
+ <img alt="node" src="https://img.shields.io/badge/node-%3E%3D18-brightgreen?style=flat-square" />
9
+ <img alt="version" src="https://img.shields.io/badge/version-1.6.3--fork.1-orange?style=flat-square" />
10
+ </p>
11
+
12
+ <p align="center">
13
+ <img src="./assets/preview.png" alt="Веб-обозреватель MegaMemory" width="800" />
14
+ </p>
15
+
16
+ > **Форк [0xK3vin/MegaMemory](https://github.com/0xK3vin/MegaMemory) v1.6.2 (MIT).**
17
+ > Идея и база — upstream. В форке: исправлены идентификаторы для любых языков, добавлены
18
+ > гибридный поиск, бюджет контекста, актуальность фактов, digest-узлы, экспорт и учёт токенов.
19
+ > English version: [README.md](./README.md).
20
+
21
+ [MCP](https://modelcontextprotocol.io/)-сервер, который даёт кодинг-агенту строить граф концепций,
22
+ архитектуры и решений — и **помнить проект между сессиями**.
23
+
24
+ Индексатор — сам LLM. Никакого AST-парсинга и статического анализа: агент читает код, записывает
25
+ концепции своими словами и запрашивает их перед следующими задачами. В графе хранятся **концепции** —
26
+ фичи, модули, паттерны, решения, — а не символы кода. Всё лежит в SQLite проекта:
27
+ `.megamemory/knowledge.db`.
28
+
29
+ ---
30
+
31
+ ## Что изменилось в форке
32
+
33
+ | Область | Upstream 1.6.2 | Этот форк |
34
+ |---|---|---|
35
+ | Идентификаторы | slug вырезает всё вне `[a-z0-9-]`: кириллица, CJK, греческий, эмодзи схлопываются в `""`, второй такой узел теряется | Unicode-слаг: буквы любого алфавита, диакритика снимается только после латиницы/кириллицы/греческого/иврита (дакутэн катаканы и хангыль сохраняются), `/` → `-`, вывод в NFC, hash-фолбэк для имён из эмодзи, суффикс `-<hash8>` при коллизии |
36
+ | Эмбеддинги | `all-MiniLM-L6-v2`, только английский, размерность зашита | по умолчанию `Xenova/multilingual-e5-small` (`MEGAMEMORY_EMBED_MODEL`), префиксы e5 `passage:`/`query:`, размерность берётся из модели, при смене модели векторный поиск отключается до `megamemory reembed` |
37
+ | Поиск | только косинус | гибрид: FTS5 + вектор через RRF, у каждого попадания `via: vector \| fts \| both`, санитизация запросов для `MATCH`, маршрутизация коротких CJK-запросов, опциональный trigram-индекс, LIKE-фолбэк по `name_norm` |
38
+ | Контекст | `understand` отдаёт всё найденное | по умолчанию `mode: "compact"` с лимитом `max_tokens` (1500), summary обрезается до 240 символов, рёбра — только между возвращёнными узлами, `meta.returned / dropped / tokens_estimated` |
39
+ | Актуальность | либо удалить, либо никак | `status` (`active`/`superseded`/`deprecated`), рёбра `supersedes` и `contradicts`, устаревшее скрыто из ответов, но видно в графе |
40
+ | Дубли | только ручной merge | `megamemory consolidate` находит пары с близостью эмбеддингов ≥ 0.95 и сливает их с переносом рёбер |
41
+ | Большие модули | каждый ребёнок читается отдельно | `digest`-узлы: один на модуль, пересобирается после 5-го ребёнка, пониженный вес в поиске |
42
+ | Переносимость | только БД | `megamemory export --md <dir>` — по файлу на узел (frontmatter + wiki-ссылки), `--check` для CI |
43
+ | Видимость цены | нет | каждый `understand` / `list_roots` / `get_concept` измеряется; агрегаты за 7 дней в `megamemory stats`, `/api/stats` и панели **Tokens** в explorer |
44
+ | Миграция | — | `megamemory migrate --dry-run/--apply` обновляет базу upstream на месте, аддитивно, с бэкапами и совместимостью вниз |
45
+
46
+ ---
47
+
48
+ ## Цикл работы
49
+
50
+ `understand → работа → update`
51
+
52
+ 1. **Начало сессии** — агент вызывает `list_roots` (с бюджетом), чтобы сориентироваться.
53
+ 2. **Перед задачей** — `understand` с запросом на естественном языке или `get_concept` по точному id.
54
+ 3. **После задачи** — `create_concept` / `update_concept`, затем `link` для связей.
55
+
56
+ ---
57
+
58
+ ## Установка
59
+
60
+ Нужен Node.js >= 18. Для чисто русских проектов подойдёт значительно меньшая модель (`cointegrated/rubert-tiny2`, 312-мерная) после конвертации в ONNX; модель выгружается после 5 минут простоя (`MEGAMEMORY_EMBED_IDLE_MS=0` отключает выгрузку), а `MEGAMEMORY_SEARCH=fts` не загружает её вовсе. Модель эмбеддингов (~120 МБ, мультиязычная) скачивается при первом
61
+ запуске и кешируется в `~/.cache/huggingface`.
62
+
63
+ Форк не публикуется в npm — ставится из tarball или из чекаута:
64
+
65
+ ```bash
66
+ git clone https://github.com/BloodyEagle/MegaMemoryAgent.git
67
+ cd MegaMemoryAgent
68
+ npm ci
69
+ npm run build
70
+ npm pack # megamemory-1.6.3-fork.1.tgz
71
+ npm install -g ./megamemory-1.6.3-fork.1.tgz
72
+ ```
73
+
74
+ Дальше — либо установщик, либо регистрация MCP-сервера руками:
75
+
76
+ ```bash
77
+ megamemory install # интерактивно: opencode / [CC] / Codex / Antigravity
78
+ ```
79
+
80
+ ```json
81
+ {
82
+ "megamemory": {
83
+ "type": "local",
84
+ "command": ["megamemory"],
85
+ "enabled": true
86
+ }
87
+ }
88
+ ```
89
+
90
+ Сервер читает `.megamemory/knowledge.db` относительно рабочей директории; путь переопределяется
91
+ через `MEGAMEMORY_DB_PATH`.
92
+
93
+ ### Обновление существующей базы upstream
94
+
95
+ ```bash
96
+ megamemory migrate --dry-run # печатает план, ничего не меняет
97
+ megamemory migrate --apply # бэкап knowledge.db.bak-<ts>, аддитивная миграция схемы
98
+ megamemory reembed # нужен только если сменилась модель эмбеддингов
99
+ megamemory doctor # проверка здоровья, код выхода 1 при проблемах
100
+ ```
101
+
102
+ Миграция не удаляет и не переименовывает столбцы, поэтому upstream v1.6.2 открывает
103
+ мигрированную базу. Узлы, потерянные в upstream из-за пустых id, восстановить нельзя —
104
+ `--dry-run` честно их показывает.
105
+
106
+ ---
107
+
108
+ ## MCP-инструменты
109
+
110
+ | Инструмент | Что делает |
111
+ |---|---|
112
+ | `understand` | Гибридный поиск по графу. `top_k`, `max_tokens`, `mode: "compact" \| "full"`, `include_inactive`. |
113
+ | `get_concept` | Точный поиск по id: дети, рёбра, входящие рёбра, родитель. |
114
+ | `create_concept` | Новая концепция с рёбрами, ссылками на файлы и `supersedes`. |
115
+ | `update_concept` | Обновление полей; эмбеддинг пересчитывается. |
116
+ | `link` | Типизированная связь между концепциями. |
117
+ | `remove_concept` | Мягкое удаление с причиной; история сохраняется, статус `deprecated`. |
118
+ | `list_roots` | Корневые концепции с детьми (с бюджетом). |
119
+ | `list_conflicts` | Неразрешённые конфликты merge и пары `contradicts`. |
120
+ | `resolve_conflict` | Разрешение конфликта проверенным содержимым. |
121
+
122
+ **Типы узлов:** `feature` · `module` · `pattern` · `config` · `decision` · `component` · `digest`
123
+
124
+ **Типы связей:** `connects_to` · `depends_on` · `implements` · `calls` · `configured_by` · `supersedes` · `contradicts`
125
+
126
+ ---
127
+
128
+ ## CLI
129
+
130
+ | Команда | Назначение |
131
+ |---|---|
132
+ | `megamemory install` | Настроить MCP-клиент |
133
+ | `megamemory serve [--port N]` | Веб-обозреватель: граф, поиск, карточки узлов, панель Tokens, вкладка consolidate |
134
+ | `megamemory migrate [--dry-run\|--apply]` | Обновить базу upstream |
135
+ | `megamemory repair-ids [--apply]` | Пересобрать пустые id и id с хвостовым `/` |
136
+ | `megamemory reembed` | Пересчитать эмбеддинги (прерываемо, пакетами) |
137
+ | `megamemory doctor` | Проверка: схема, модель, FTS, id, векторы, осиротевшие рёбра, digest |
138
+ | `megamemory stats` | Статистика графа и токенов |
139
+ | `megamemory eval` | recall@10 по `fixtures/eval.jsonl` |
140
+ | `megamemory consolidate [--dry-run\|--apply]` | Поиск и слияние почти одинаковых узлов |
141
+ | `megamemory digest [--apply]` | Сборка и пересборка digest-узлов |
142
+ | `megamemory export --md <dir> [--check]` | Markdown-экспорт и проверка расхождений для CI |
143
+ | `megamemory merge`, `conflicts`, `resolve` | Двусторонний merge графов между ветками |
144
+
145
+ ---
146
+
147
+ ## Переменные окружения
148
+
149
+ | Переменная | По умолчанию | Значение |
150
+ |---|---|---|
151
+ | `MEGAMEMORY_DB_PATH` | `./.megamemory/knowledge.db` | Путь к базе |
152
+ | `MEGAMEMORY_EMBED_MODEL` | `Xenova/multilingual-e5-small` | Модель эмбеддингов (любая ONNX-модель transformers.js) |
153
+ | `MEGAMEMORY_SEARCH` | `hybrid` | `hybrid` / `fts` / `vector` |
154
+ | `MEGAMEMORY_FTS_TOKENIZER` | — | `trigram` добавляет второй индекс для CJK |
155
+ | `MEGAMEMORY_AUTO_DIGEST` | включено | `0` отключает автосборку digest после 5-го ребёнка |
156
+
157
+ ---
158
+
159
+ ## Веб-обозреватель
160
+
161
+ ```bash
162
+ megamemory serve --port 8080
163
+ ```
164
+
165
+ - узлы раскрашены по типу, размер — по числу рёбер; `digest` и устаревшие (`superseded`) визуально отличаются
166
+ - рёбра `supersedes` — пунктиром, бейдж статуса в карточке узла, тумблер «показывать устаревшие»
167
+ - у результатов поиска бейдж `via` (vector / fts / both) и строка бюджета: `N nodes, ~X tokens, dropped M`
168
+ - панель **Tokens**: средний размер ответа и сэкономленные токены за 7 дней
169
+ - вкладка **Consolidate**: кандидаты-дубликаты с кнопкой применения
170
+
171
+ ---
172
+
173
+ ## Тесты
174
+
175
+ ```bash
176
+ npm run build
177
+ npx vitest run src/__tests__/id-generation.test.ts --reporter=dot # целевой прогон
178
+ npx vitest run # всё (долго: скачивание модели)
179
+ ```
180
+
181
+ `fixtures/demo.db` — готовый граф (ru/en/zh/эмодзи, один `superseded`, один `digest`, пара дублей)
182
+ для ручной проверки в обозревателе.
183
+
184
+ ---
185
+
186
+ ## Совместимость и ограничения
187
+
188
+ - Upstream v1.6.2 работает с мигрированной базой: у новых столбцов есть `DEFAULT`, FTS-триггеры
189
+ поддерживают индекс при вставках upstream. Бэкапы `knowledge.db.bak-<ts>`, хранятся 3 последних.
190
+ - FTS5 требует локального файлового режима libsql — MegaMemory локальная; удалённый Turso
191
+ виртуальные таблицы запрещает.
192
+ - После любого `VACUUM` нужен `megamemory migrate --apply` — пересборка FTS (rowid не гарантированы).
193
+ - Русский текст FTS5 `unicode61` не стеммит; компенсирует векторный канал, помогают префикс-запросы.
194
+
195
+ ---
196
+
197
+ ## Авторы и лицензия
198
+
199
+ Основа — [MegaMemory](https://github.com/0xK3vin/MegaMemory), автор 0xK3vin (MIT).
200
+ Форк поддерживает [BloodyEagle](https://github.com/BloodyEagle). MIT, см. [LICENSE](./LICENSE).
201
+ Отличия и порядок синхронизации с upstream: [docs/FORK.md](./docs/FORK.md).
@@ -0,0 +1,51 @@
1
+ <!-- MegaMemory-managed file. Safe for megamemory install to update. -->
2
+ # Bootstrap Project Knowledge Graph
3
+
4
+ RUN { git ls-files; git ls-files --others --exclude-standard; } 2>/dev/null | sort -u | xargs wc -l 2>/dev/null | sort -rn | head -150
5
+ READ README.md
6
+
7
+ You are bootstrapping the megamemory knowledge graph for this project.
8
+
9
+ Your job is to understand the codebase and record its core concepts, architecture,
10
+ and patterns as knowledge graph nodes. The file listing above is sorted by line
11
+ count — the biggest files are where the core logic lives.
12
+
13
+ ## Step 1: Check existing graph
14
+
15
+ Call `megamemory:list_roots` to see what's already recorded. If the graph has
16
+ good coverage, report what's there and ask if I want to fill in specific areas.
17
+
18
+ ## Step 2: Identify major modules
19
+
20
+ From the file listing and README, identify the top-level systems in this project.
21
+ Think in terms of:
22
+ - What does this project DO? (features)
23
+ - What are the distinct subsystems? (modules)
24
+ - How is it structured? (patterns, decisions)
25
+
26
+ ## Step 3: Read and create root concepts
27
+
28
+ For each major module, read its key files to understand what it does. Then call
29
+ `megamemory:create_concept` with a specific, detailed summary. Include parameter
30
+ names, defaults, file paths, and behavior details — not vague descriptions.
31
+
32
+ ## Step 4: Create children for important sub-components
33
+
34
+ For substantial modules, create child concepts for key pieces. Stay max 2 levels
35
+ deep. Focus on things a developer would need to know when working in that area.
36
+
37
+ ## Step 5: Link related concepts
38
+
39
+ Connect concepts that interact across boundaries using `megamemory:link`.
40
+ Focus on meaningful relationships: depends_on, calls, connects_to, implements,
41
+ configured_by.
42
+
43
+ ## Guidelines
44
+
45
+ - Be specific. "Handles auth" is useless. "JWT auth with RS256, tokens from
46
+ /auth/login, validated in middleware, refresh tokens in Redis with 7d TTL" is useful.
47
+ - Focus on the top 10-15 most important concepts first. The graph grows over time.
48
+ - Don't document trivial things. If it's obvious from the file name, skip it.
49
+
50
+ - When a concept replaces an earlier decision, pass `supersedes: [old_id]` instead of deleting.
51
+ - Do not create digest nodes manually — they are built from children automatically.
@@ -0,0 +1,84 @@
1
+ <!-- MegaMemory-managed file. Safe for megamemory install to update. -->
2
+ # Save Session Knowledge
3
+
4
+ You are saving what you learned this session into the megamemory knowledge graph.
5
+ This is YOUR memory — record anything valuable for future sessions: what you
6
+ understood about the project, what you built, decisions that were made, patterns
7
+ you noticed, or intent the user shared.
8
+
9
+ ## Step 1: Load existing graph
10
+
11
+ Call `megamemory:list_roots` to see what's already recorded. Understanding the
12
+ current state prevents duplicates and helps you decide what to update vs create.
13
+
14
+ ## Step 2: Reflect on this session
15
+
16
+ Think about what happened this session. Consider:
17
+ - What did you learn about the project's purpose or intent?
18
+ - What features, modules, or components did you build or change?
19
+ - What design decisions were made and why?
20
+ - What patterns or conventions did you discover?
21
+ - What architectural understanding do you have now that isn't in the graph?
22
+ - Did anything get removed, replaced, or deprecated?
23
+
24
+ ## Step 3: Search for overlap
25
+
26
+ Before creating anything new, call `megamemory:understand` with queries based on
27
+ what you worked on this session. For each area you touched, search to see if
28
+ concepts already exist that should be updated rather than duplicated.
29
+
30
+ For example, if you worked on authentication, call:
31
+ megamemory:understand — query="authentication"
32
+
33
+ Do this for each distinct area. Existing concepts that are stale or incomplete
34
+ should be updated — don't create a new node when an update will do.
35
+
36
+ ## Step 4: Write to the knowledge graph
37
+
38
+ For each thing worth remembering:
39
+
40
+ **New understanding** → `megamemory:create_concept`
41
+ - name: human-readable name
42
+ - kind: use `decision` for intent/rationale, `feature` for capabilities,
43
+ `module` for subsystems, `pattern` for conventions, `config` for setup,
44
+ `component` for distinct pieces of a system
45
+ - summary: be specific — include parameter names, defaults, file paths,
46
+ behavior details, and the WHY behind things
47
+ - why: the rationale — this is often the most valuable part
48
+ - file_refs: relevant files if applicable
49
+ - edges: connect to existing concepts where relationships exist
50
+ [{to: "concept-id", relation: "depends_on|implements|calls|connects_to|configured_by", description: "why"}]
51
+ - created_by_task: brief description of what you were doing this session
52
+
53
+ **Updated understanding** → `megamemory:update_concept`
54
+ - id: the concept slug
55
+ - changes: {summary?, why?, file_refs?, name?, kind?}
56
+ If an existing concept is now stale or incomplete based on what you learned,
57
+ update it. This is often more valuable than creating new nodes.
58
+
59
+ **New connections** → `megamemory:link`
60
+ - from, to: concept IDs
61
+ - relation: depends_on | implements | calls | connects_to | configured_by
62
+ - description: why this relationship exists
63
+ If you discovered how existing concepts relate to each other.
64
+
65
+ **Removed/replaced things** → `megamemory:remove_concept`
66
+ - id: concept to remove
67
+ - reason: why it was removed
68
+ If something in the graph is no longer true.
69
+
70
+ ## Step 5: Verify
71
+
72
+ Call `megamemory:list_roots` again. Confirm the graph reflects your current
73
+ understanding. Report what you saved.
74
+
75
+ ## Guidelines
76
+
77
+ - Record what a future you (with no memory of this session) would need to know.
78
+ - Intent and rationale ("why") are more valuable than implementation details.
79
+ - Update existing concepts before creating new ones — keep the graph lean.
80
+ - Don't record trivial things. If it's obvious from the code, skip it.
81
+ - Max 2 levels of nesting. Flat is better than deep.
82
+ - Connect concepts — isolated nodes are less useful than a connected graph.
83
+ - Be specific. "Handles auth" is useless. "JWT auth with RS256, validated in
84
+ middleware at src/middleware/auth.ts, refresh tokens in Redis with 7d TTL" is useful.
@@ -0,0 +1,23 @@
1
+ export declare function error(msg: string): void;
2
+ export declare function errorBold(msg: string): void;
3
+ export declare function warn(msg: string): void;
4
+ export declare function success(msg: string): void;
5
+ export declare function skip(msg: string): void;
6
+ export declare function info(msg: string): void;
7
+ export declare function heading(msg: string): void;
8
+ export declare function ask(question: string): Promise<string>;
9
+ export declare function multiSelect(prompt: string, options: Array<{
10
+ label: string;
11
+ value: string;
12
+ description?: string;
13
+ }>): Promise<string[]>;
14
+ /**
15
+ * Prompt the user for a port when the current one is in use.
16
+ * Returns the chosen port number, or null if the user wants to cancel.
17
+ */
18
+ export declare function askPort(currentPort: number): Promise<number | null>;
19
+ /**
20
+ * Validate a port number. Returns an error message or null if valid.
21
+ */
22
+ export declare function validatePort(value: unknown, rawInput?: string): string | null;
23
+ //# sourceMappingURL=cli-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-utils.d.ts","sourceRoot":"","sources":["../src/cli-utils.ts"],"names":[],"mappings":"AAKA,wBAAgB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEvC;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAE3C;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEtC;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEzC;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEtC;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEtC;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEzC;AAID,wBAAgB,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAWrD;AAED,wBAAsB,WAAW,CAC/B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACrE,OAAO,CAAC,MAAM,EAAE,CAAC,CAmHnB;AAED;;;GAGG;AACH,wBAAsB,OAAO,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAmBzE;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM7E"}