dsh-memvault 0.9.12 → 0.10.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 (48) hide show
  1. package/README.md +52 -397
  2. package/README.zh.md +51 -325
  3. package/cordis.patch.yml +18 -20
  4. package/docs/CORE-DESIGN.md +277 -0
  5. package/docs/DETAIL.md +1 -0
  6. package/docs/DETAIL.zh.md +1 -0
  7. package/docs/DEVLOG.md +752 -0
  8. package/docs/images/relation-graph-2026-11-02.png +0 -0
  9. package/docs/preview.svg +41 -0
  10. package/icon.svg +9 -0
  11. package/lib/blocks.js +11 -2
  12. package/lib/client.js +705 -168
  13. package/lib/config.js +46 -87
  14. package/lib/core/adjudicate.js +94 -0
  15. package/lib/core/backfill.js +32 -0
  16. package/lib/core/block-write.js +85 -0
  17. package/lib/core/decide.js +159 -0
  18. package/lib/core/embed.js +122 -0
  19. package/lib/core/env.js +72 -0
  20. package/lib/core/extract.js +151 -0
  21. package/lib/core/host.js +81 -0
  22. package/lib/core/importers.js +261 -0
  23. package/lib/core/llm.js +49 -0
  24. package/lib/{memories.js → core/panel-read.js} +80 -136
  25. package/lib/core/pipeline.js +95 -0
  26. package/lib/core/schema.js +123 -0
  27. package/lib/core/search.js +191 -0
  28. package/lib/core/store.js +347 -0
  29. package/lib/core/tools.js +182 -0
  30. package/lib/core/write.js +89 -0
  31. package/lib/extract.js +1 -39
  32. package/lib/index.js +194 -128
  33. package/lib/panel.js +13 -11
  34. package/lib/review.js +5 -1
  35. package/lib/structure.js +6 -1
  36. package/locale/en.json +7 -0
  37. package/locale/zh.json +7 -0
  38. package/package.json +11 -8
  39. package/scripts/backfill-core.mjs +53 -0
  40. package/scripts/import-core.mjs +56 -0
  41. package/scripts/smoke-config.mjs +12 -14
  42. package/scripts/smoke-extract.mjs +19 -40
  43. package/scripts/smoke-package.mjs +105 -27
  44. package/scripts/smoke-panel.mjs +293 -162
  45. package/src/client/index.js +703 -166
  46. package/lib/blocks-write.js +0 -121
  47. package/lib/cli.js +0 -90
  48. package/lib/reindex.js +0 -32
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Embedders: the offline default and an OpenAI-compatible endpoint.
3
+ *
4
+ * Both are **async** on purpose. A network embedder is asynchronous by nature,
5
+ * and giving the offline one the same interface keeps every caller honest
6
+ * instead of special-casing "this embedder never waits" — the kind of branch
7
+ * that silently stops working the day a real model is configured.
8
+ *
9
+ * `LocalEmbedder` is deterministic feature hashing ported from the Python
10
+ * engine (lowercase ascii words + single CJK chars + CJK bigrams, signed md5,
11
+ * normalised). No model, no network: it is what makes the plugin work on first
12
+ * install. `OpenAIEmbedder` is the upgrade, stored as a second `model` row so
13
+ * switching models never rewrites a memory.
14
+ */
15
+ import { createHash } from 'node:crypto'
16
+
17
+ const ASCII_WORD = /[a-z0-9_]+/g
18
+ const CJK_CHAR = /[\u4e00-\u9fff]/g
19
+
20
+ /** Lowercase ascii words + single CJK chars + CJK bigrams. */
21
+ export function tokenize(text) {
22
+ const lowered = String(text ?? '').toLowerCase()
23
+ const words = lowered.match(ASCII_WORD) || []
24
+ const cjk = lowered.match(CJK_CHAR) || []
25
+ const bigrams = []
26
+ for (let i = 0; i < cjk.length - 1; i += 1) bigrams.push(cjk[i] + cjk[i + 1])
27
+ return [...words, ...cjk, ...bigrams]
28
+ }
29
+
30
+ function unit(vector) {
31
+ let norm = 0
32
+ for (const value of vector) norm += value * value
33
+ norm = Math.sqrt(norm)
34
+ if (norm > 0) for (let i = 0; i < vector.length; i += 1) vector[i] /= norm
35
+ return vector
36
+ }
37
+
38
+ export class LocalEmbedder {
39
+ constructor(dim = 384) {
40
+ if (!Number.isInteger(dim) || dim <= 0) throw new Error('dim must be a positive integer')
41
+ this.dim = dim
42
+ this.model = `local/${dim}`
43
+ this.id = 'local'
44
+ }
45
+
46
+ async embed(texts) {
47
+ return texts.map((text) => this.embedOneSync(text))
48
+ }
49
+
50
+ async embedOne(text) {
51
+ return this.embedOneSync(text)
52
+ }
53
+
54
+ embedOneSync(text) {
55
+ const vector = new Float32Array(this.dim)
56
+ for (const token of tokenize(text)) {
57
+ const digest = createHash('md5').update(token, 'utf8').digest()
58
+ const index = digest.readUInt32BE(0) % this.dim
59
+ vector[index] += (digest[4] & 1) ? 1 : -1
60
+ }
61
+ return unit(vector)
62
+ }
63
+ }
64
+
65
+ export class OpenAIEmbedder {
66
+ constructor({
67
+ baseUrl = 'https://api.openai.com/v1',
68
+ apiKey,
69
+ model = 'text-embedding-3-small',
70
+ timeoutMs = 30_000,
71
+ fetchImpl = fetch,
72
+ } = {}) {
73
+ if (!apiKey) throw new Error('apiKey is required')
74
+ this.baseUrl = String(baseUrl).replace(/\/+$/, '')
75
+ this.apiKey = apiKey
76
+ this.name = model
77
+ this.model = `openai/${model}`
78
+ this.dim = null
79
+ this.timeoutMs = timeoutMs
80
+ this.fetchImpl = fetchImpl
81
+ this.id = 'openai'
82
+ }
83
+
84
+ /** Embed a batch; returns one Float32Array per input, in input order. */
85
+ async embed(texts) {
86
+ if (!texts.length) return []
87
+ const controller = new AbortController()
88
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs)
89
+ try {
90
+ const response = await this.fetchImpl(`${this.baseUrl}/embeddings`, {
91
+ method: 'POST',
92
+ headers: {
93
+ 'content-type': 'application/json',
94
+ authorization: `Bearer ${this.apiKey}`,
95
+ },
96
+ body: JSON.stringify({ model: this.name, input: texts }),
97
+ signal: controller.signal,
98
+ })
99
+ if (!response.ok) throw new Error(`embeddings HTTP ${response.status}`)
100
+ const data = await response.json()
101
+ const items = [...(data?.data ?? [])].sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
102
+ const vectors = items.map((item) => unit(Float32Array.from(item.embedding)))
103
+ this.dim = vectors[0]?.length ?? this.dim
104
+ return vectors
105
+ } finally {
106
+ clearTimeout(timer)
107
+ }
108
+ }
109
+
110
+ async embedOne(text) {
111
+ const [vector] = await this.embed([text])
112
+ return vector
113
+ }
114
+ }
115
+
116
+ /** Cosine similarity of two normalised vectors. */
117
+ export function cosine(a, b) {
118
+ if (!a || !b || a.length !== b.length) return 0
119
+ let dot = 0
120
+ for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i]
121
+ return dot
122
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Embedder selection: the same `.env` the Python engine read, so the in-plugin
3
+ * core does not invent a second configuration source.
4
+ *
5
+ * Precedence mirrors the engine's `load_dotenv`: real environment variables win
6
+ * over the file. A configured `OPENAI_API_KEY` selects the OpenAI-compatible
7
+ * embedder (the endpoint MemVault already used); otherwise the offline hashing
8
+ * embedder is the default, which keeps a fresh install working with no key.
9
+ */
10
+ import { existsSync, readFileSync } from 'node:fs'
11
+ import { dirname, join } from 'node:path'
12
+
13
+ import { LocalEmbedder, OpenAIEmbedder } from './embed.js'
14
+
15
+ /** Minimal dotenv reader: KEY=VALUE, comments, optional surrounding quotes. */
16
+ export function readEnvFile(path) {
17
+ try {
18
+ const out = {}
19
+ for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {
20
+ const trimmed = line.trim()
21
+ if (!trimmed || trimmed.startsWith('#')) continue
22
+ const equals = trimmed.indexOf('=')
23
+ if (equals <= 0) continue
24
+ const key = trimmed.slice(0, equals).trim()
25
+ let value = trimmed.slice(equals + 1).trim()
26
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
27
+ value = value.slice(1, -1)
28
+ }
29
+ out[key] = value
30
+ }
31
+ return out
32
+ } catch {
33
+ return {}
34
+ }
35
+ }
36
+
37
+ /** First existing `.env` among explicit path, project dir, store dir. */
38
+ export function findEnvFile({ projectDir = '', dbPath = '', envFile = null } = {}) {
39
+ const candidates = [
40
+ envFile,
41
+ projectDir ? join(projectDir, '.env') : null,
42
+ dbPath ? join(dirname(dbPath), '.env') : null,
43
+ ].filter(Boolean)
44
+ for (const candidate of candidates) {
45
+ if (existsSync(candidate)) return candidate
46
+ }
47
+ return null
48
+ }
49
+
50
+ /**
51
+ * Pick an embedder for this install.
52
+ *
53
+ * `model` is the row key in `memory_embeddings`, so a later switch keeps the old
54
+ * vectors instead of invalidating them.
55
+ */
56
+ export function resolveEmbedder({ projectDir = '', dbPath = '', env = process.env, envFile = null } = {}) {
57
+ const file = findEnvFile({ projectDir, dbPath, envFile })
58
+ const merged = { ...(file ? readEnvFile(file) : {}), ...env }
59
+ const apiKey = merged.OPENAI_API_KEY || ''
60
+ // An explicit MEMVAULT_EMBEDDER wins, so a test or a user can pin the offline
61
+ // embedder even when a key happens to be present in the same environment.
62
+ const requested = String(merged.MEMVAULT_EMBEDDER ?? '').toLowerCase()
63
+ const wantsOpenAI = requested === 'openai' || (requested === '' && Boolean(apiKey))
64
+ if (wantsOpenAI && apiKey) {
65
+ return new OpenAIEmbedder({
66
+ baseUrl: merged.OPENAI_BASE_URL || 'https://api.openai.com/v1',
67
+ apiKey,
68
+ model: merged.OPENAI_EMBEDDING_MODEL || 'text-embedding-3-small',
69
+ })
70
+ }
71
+ return new LocalEmbedder(Number(merged.MEMVAULT_EMBEDDING_DIM) || 384)
72
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Fact extraction (M1).
3
+ *
4
+ * Two extractors behind one method:
5
+ *
6
+ * - `RuleExtractor` — deterministic regexes for common zh/en self-disclosure.
7
+ * Offline, no model, and deliberately narrow: it only catches the patterns
8
+ * below, so it under-extracts rather than inventing facts.
9
+ * - `LLMExtractor` — the prompt is ported from the Python engine unchanged,
10
+ * including rule 6/7 (never turn "the agent used a tool" into "the user knows
11
+ * that tool"), because that clause exists to stop a real bad row.
12
+ *
13
+ * Only user turns are mined: an assistant's "I'll remember that" is not a fact.
14
+ */
15
+
16
+ /** The prompt the Python engine used, verbatim, so behaviour does not drift. */
17
+ export const DEFAULT_LLM_PROMPT = (
18
+ '你是记忆抽取器。从下面的对话中抽取关于用户(或智能体)的、长期有效的独立事实,'
19
+ + '要求:1) 每条是一句完整陈述(例如“用户喜欢用中文沟通”),不要时间性问候;'
20
+ + '2) 去掉寒暄、确认语与无法复用的临时信息;3) 不要臆造;'
21
+ + '4) 同一主题必须合并成一条:把同一主体的多个属性写成一句完整陈述'
22
+ + '(例如姓名、学校、年级合成一句,而不是拆成三条),宁少勿多,'
23
+ + '不要把一件事拆成多条琐碎记录;'
24
+ + '6) 只写用户(或智能体)自己陈述过的、关于自身的长期事实;'
25
+ + '不要把助手或工具做过的事、用过的技术方法改写成人的属性'
26
+ + '(反面例:“用户熟悉 Electron 应用的 asar 文件格式结构”是一次操作,不是用户属性);'
27
+ + '7) 工具、命令、文件格式这类技术做法若确实值得保留,写成过程陈述'
28
+ + '(如“做法:…”),不要写成“用户会 / 掌握 / 熟悉…”;'
29
+ + '8) 只输出 JSON 字符串数组;没有合格事实时必须输出 [],'
30
+ + '宁可输出 [] 也不要凑一条弱事实。对话如下:\n'
31
+ )
32
+
33
+ const RULES = [
34
+ [/(?:我的名字(?:叫|是)|我叫|请叫我)([\u4e00-\u9fa5A-Za-z0-9_]{1,20})/g, '用户的名字是{0}'],
35
+ [/(?<!不)我(?:喜欢|喜爱|偏爱|最爱)(.{1,30})/g, '用户喜欢{0}'],
36
+ [/(?:我不喜欢|我讨厌|我不爱|我忌口)(.{1,30})/g, '用户不喜欢{0}'],
37
+ [/(?:我住在|我来自|我老家在)([\u4e00-\u9fa5A-Za-z0-9_]{1,20})/g, '用户住在{0}'],
38
+ [/(?:我的职业是|我是一名|我是)([\u4e00-\u9fa5A-Za-z0-9_]{2,20})/g, '用户的职业是{0}'],
39
+ [/(?:请记住|记住[:: ]?)\s*(.{2,40})/g, '{0}'],
40
+ [/\b(?:my name is|call me)\s+([A-Za-z0-9_]{1,20})/gi, "user's name is {0}"],
41
+ [/\bi (?:like|love|prefer|enjoy)\s+(.{1,40})/gi, 'user likes {0}'],
42
+ [/\bi (?:don'?t like|hate|dislike)\s+(.{1,40})/gi, 'user dislikes {0}'],
43
+ [/\bi (?:live in|am from)\s+([A-Za-z0-9 _.,'-]{1,30})/gi, 'user lives in {0}'],
44
+ [/\bi work (?:at|for)\s+([A-Za-z0-9 _.,'-]{1,30})/gi, 'user works at {0}'],
45
+ [/\bremember that\s+(.{2,60})/gi, '{0}'],
46
+ ]
47
+
48
+ const TAIL = /[。!?;,.\s]+$/
49
+ const SPLIT = /[。!?;\n]+/
50
+
51
+ function clean(fact) {
52
+ return fact.replace(TAIL, '').trim()
53
+ }
54
+
55
+ /** Shared extraction of a JSON array; `null` means "not an array in here". */
56
+ function arrayFrom(content) {
57
+ let text = String(content ?? '').trim()
58
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/)
59
+ if (fenced) text = fenced[1].trim()
60
+ const start = text.indexOf('[')
61
+ const end = text.lastIndexOf(']')
62
+ if (start === -1 || end <= start) return null
63
+ try {
64
+ const data = JSON.parse(text.slice(start, end + 1))
65
+ return Array.isArray(data) ? data : null
66
+ } catch {
67
+ return null
68
+ }
69
+ }
70
+
71
+ /** Tolerant parse of a JSON string array from a model answer. */
72
+ export function parseFacts(content) {
73
+ const data = arrayFrom(content)
74
+ if (data === null) return []
75
+ return data.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
76
+ }
77
+
78
+ /**
79
+ * Strict parse for the live pipeline.
80
+ *
81
+ * The tolerant version answers "no facts" for anything it cannot read, which made
82
+ * a model that returned prose (or nothing) indistinguishable from a model that
83
+ * correctly answered `[]` — both surfaced as `ok added=0`. Here an unreadable
84
+ * answer throws, so the diagnostic says `failed: …` with a snippet of what the
85
+ * model actually said. An empty answer is still `[]`: "nothing to store" is a
86
+ * legitimate answer, silence from the model is not.
87
+ */
88
+ export function parseFactsStrict(content) {
89
+ const text = String(content ?? '').trim()
90
+ if (text === '') return []
91
+ const data = arrayFrom(text)
92
+ if (data === null) {
93
+ throw new Error(`the model did not return a JSON array: ${text.replace(/\s+/g, ' ').slice(0, 120)}`)
94
+ }
95
+ const facts = data.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
96
+ if (data.length > 0 && facts.length === 0) {
97
+ throw new Error(`the model returned ${data.length} entr${data.length === 1 ? 'y' : 'ies'} that are not strings`)
98
+ }
99
+ return facts
100
+ }
101
+
102
+ function userTexts(messages) {
103
+ return (messages || [])
104
+ .filter((message) => message && message.role === 'user' && typeof message.content === 'string')
105
+ .map((message) => message.content)
106
+ }
107
+
108
+ export class RuleExtractor {
109
+ /** @param {Array} messages @returns {string[]} */
110
+ extract(messages) {
111
+ const facts = []
112
+ const seen = new Set()
113
+ for (const text of userTexts(messages)) {
114
+ for (const sentence of text.split(SPLIT)) {
115
+ if (!sentence.trim()) continue
116
+ for (const [pattern, template] of RULES) {
117
+ pattern.lastIndex = 0
118
+ for (const match of sentence.matchAll(pattern)) {
119
+ const fact = clean(template.replace('{0}', (match[1] ?? '').trim()))
120
+ if (fact && !seen.has(fact)) {
121
+ seen.add(fact)
122
+ facts.push(fact)
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ return facts
129
+ }
130
+ }
131
+
132
+ export class LLMExtractor {
133
+ constructor(client, { prompt = DEFAULT_LLM_PROMPT } = {}) {
134
+ this.client = client
135
+ this.prompt = prompt
136
+ }
137
+
138
+ async extract(messages, prompt = null) {
139
+ const transcript = userTexts(messages)
140
+ .map((text, index) => `[${index + 1}] ${text}`)
141
+ .join('\n')
142
+ if (!transcript.trim()) return []
143
+ const content = await this.client.complete([
144
+ { role: 'system', content: prompt || this.prompt },
145
+ { role: 'user', content: transcript },
146
+ ])
147
+ // Strict on purpose: an unreadable answer must become a failed diagnostic,
148
+ // not a silent "nothing to store" (see parseFactsStrict).
149
+ return parseFactsStrict(content)
150
+ }
151
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Host wiring for the memory tools: one store, opened only when the tool
3
+ * service actually exists, closed when the plugin unloads.
4
+ *
5
+ * Why lazy: the store file is a new artifact on disk. Opening it during
6
+ * `apply()` would create `~/.dsh/memvault/memvault.db` even for a headless
7
+ * composition that never registers a tool. The `ctx.inject(['tools'], ...)`
8
+ * callback only runs when the service is present, so the file appears exactly
9
+ * when the capability does.
10
+ *
11
+ * A failure to open the store logs and returns; it must not take block
12
+ * injection or extraction down with it.
13
+ */
14
+ import { DEFAULT_DB_PATH } from '../blocks.js'
15
+ import { CoreStore } from './store.js'
16
+ import { resolveEmbedder } from './env.js'
17
+ import { resolveAdjudicator } from './adjudicate.js'
18
+ import { registerTools } from './tools.js'
19
+
20
+ /**
21
+ * Default location of the in-plugin store: the same database the prompt reads
22
+ * (`blocks.js`), so "what is injected" and "what the tools search" cannot drift.
23
+ * `DSH_MEMVAULT_CORE_DB` overrides it (tests, a second vault).
24
+ */
25
+ export const DEFAULT_CORE_DB = process.env.DSH_MEMVAULT_CORE_DB ?? DEFAULT_DB_PATH
26
+
27
+ export function attachMemoryTools(ctx, {
28
+ storePath = process.env.DSH_MEMVAULT_CORE_DB || DEFAULT_CORE_DB,
29
+ projectDir = '',
30
+ logger = null,
31
+ // Resolved the same way the Python engine resolved it: the project `.env`
32
+ // selects the OpenAI-compatible endpoint when a key is present, otherwise the
33
+ // offline hashing embedder keeps a fresh install working with no key.
34
+ embedder = null,
35
+ adjudicator = null,
36
+ } = {}) {
37
+ if (!ctx || (typeof ctx.inject !== 'function' && typeof ctx.get !== 'function')) {
38
+ throw new Error('ctx.inject or ctx.get is required')
39
+ }
40
+ const effectiveEmbedder = embedder ?? resolveEmbedder({ projectDir, dbPath: storePath })
41
+ // Same .env, same rule: an endpoint means the semantic answerability check is
42
+ // available; `MEMVAULT_ADJUDICATOR=off` turns it back off.
43
+ const effectiveAdjudicator = adjudicator ?? resolveAdjudicator({ projectDir, dbPath: storePath })
44
+
45
+ const attach = (toolCtx, tools) => {
46
+ let store
47
+ try {
48
+ store = new CoreStore(storePath)
49
+ } catch (error) {
50
+ logger?.warn?.('dsh-memvault: could not open the memory store; tools stay off', error)
51
+ return
52
+ }
53
+ toolCtx.effect(() => {
54
+ let dispose = null
55
+ try {
56
+ dispose = registerTools(tools, store, { logger, embedder: effectiveEmbedder, adjudicator: effectiveAdjudicator })
57
+ } catch (error) {
58
+ logger?.warn?.('dsh-memvault: memory tools could not be registered', error)
59
+ }
60
+ return () => {
61
+ try {
62
+ dispose?.()
63
+ } finally {
64
+ store.close()
65
+ }
66
+ }
67
+ })
68
+ logger?.info?.(`dsh-memvault: memory tools registered (${storePath})`)
69
+ }
70
+
71
+ // Two shapes are supported on purpose: a plain context exposes the service
72
+ // through `get`, while an injected child context receives it as a property.
73
+ // Checking `get` first keeps the common case synchronous and makes a missing
74
+ // service a no-op instead of a pending injection that never fires.
75
+ const direct = typeof ctx.get === 'function' ? ctx.get('tools') : null
76
+ if (direct) {
77
+ attach(ctx, direct)
78
+ return () => {}
79
+ }
80
+ return ctx.inject(['tools'], (toolCtx) => attach(toolCtx, toolCtx.tools))
81
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Importers for the new store (M0).
3
+ *
4
+ * Every source is a local file; nothing is fetched. The mapping rule is the same
5
+ * one the Python importers used, with one addition that the new schema allows:
6
+ * memories keep their provenance (`origin` + `source_ref`) and their original
7
+ * timestamps, so an import is auditable and "when was this learned" survives the
8
+ * move.
9
+ *
10
+ * Idempotency: a source id is preserved when it has one; otherwise the id is
11
+ * derived from scope + text, so importing the same file twice skips rather than
12
+ * duplicates. Old history rows are replayed as `import` events (the schema's
13
+ * action enum has no place for the engine's internal add/update distinction).
14
+ */
15
+ import { createHash } from 'node:crypto'
16
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+
19
+ /** Deterministic id for sources that carry none. */
20
+ export function stableId(scopeKey, text) {
21
+ const digest = createHash('sha1').update(`${scopeKey}\u0000${text}`).digest('hex')
22
+ return `mem_${digest.slice(0, 12)}`
23
+ }
24
+
25
+ function scopeKeyOf(scope = {}) {
26
+ return `${scope.userId ?? ''}|${scope.agentId ?? ''}|${scope.runId ?? ''}`
27
+ }
28
+
29
+ function importRecords(store, records, origin) {
30
+ let added = 0
31
+ let skipped = 0
32
+ for (const record of records) {
33
+ const id = record.id || stableId(scopeKeyOf(record), record.text)
34
+ if (store.getMemory(id)) {
35
+ skipped += 1
36
+ continue
37
+ }
38
+ store.addMemory({ ...record, id, origin, actor: origin })
39
+ added += 1
40
+ }
41
+ return { added, skipped }
42
+ }
43
+
44
+ // ── memvault-export (the old store's JSON) ─────────────────────────────────
45
+
46
+ /**
47
+ * Import a `memvault-export` v1 payload into the new store.
48
+ *
49
+ * Memories keep their ids and scopes; blocks keep their keys; relations keep
50
+ * their weight (the old store had a single relation kind, so they become
51
+ * `related`); history rows become `import` events rather than being dropped.
52
+ */
53
+ export function importMemvaultExport(store, payload, { origin = 'import:memvault-export' } = {}) {
54
+ if (!payload || payload.format !== 'memvault-export') {
55
+ throw new Error('not a memvault-export payload')
56
+ }
57
+ const report = {
58
+ added: 0, skipped: 0, blocks: 0, relations: 0, history: 0,
59
+ withVectors: Boolean(payload.counts?.with_vectors),
60
+ }
61
+
62
+ const records = (payload.memories || []).map((row) => ({
63
+ id: row.id,
64
+ userId: row.user_id ?? null,
65
+ agentId: row.agent_id ?? null,
66
+ runId: row.run_id ?? null,
67
+ text: row.memory,
68
+ type: row.memory_type ?? 'user',
69
+ metadata: row.metadata ?? {},
70
+ sourceRef: row.metadata?.source_ref ?? null,
71
+ confidence: 1.0,
72
+ createdAt: row.created_at ?? null,
73
+ }))
74
+ const memories = importRecords(store, records, origin)
75
+ report.added = memories.added
76
+ report.skipped = memories.skipped
77
+
78
+ for (const block of payload.blocks || []) {
79
+ store.setBlock({
80
+ scopeType: block.scope_type,
81
+ scopeId: block.scope_id,
82
+ label: block.label,
83
+ value: block.value,
84
+ valueLimit: block.value_limit ?? 2000,
85
+ createdAt: block.created_at ?? null,
86
+ })
87
+ report.blocks += 1
88
+ }
89
+
90
+ for (const relation of payload.relations || []) {
91
+ store.addRelation(relation.source_id, relation.target_id, 'related', relation.weight ?? 0)
92
+ report.relations += 1
93
+ }
94
+
95
+ for (const event of payload.history || []) {
96
+ store.recordHistory({
97
+ memoryId: event.memory_id,
98
+ action: 'import',
99
+ oldText: event.old_memory ?? null,
100
+ newText: event.new_memory ?? null,
101
+ actor: origin,
102
+ at: event.changed_at ?? null,
103
+ })
104
+ report.history += 1
105
+ }
106
+
107
+ return report
108
+ }
109
+
110
+ // ── MCP memory JSONL ───────────────────────────────────────────────────────
111
+
112
+ export function readMcpMemory(text) {
113
+ const records = []
114
+ let relations = 0
115
+ const entities = new Set()
116
+ for (const line of String(text ?? '').split(/\r?\n/)) {
117
+ const trimmed = line.trim()
118
+ if (!trimmed) continue
119
+ let item
120
+ try {
121
+ item = JSON.parse(trimmed)
122
+ } catch {
123
+ continue
124
+ }
125
+ if (item?.type === 'entity') {
126
+ const name = String(item.name ?? '').trim()
127
+ if (name) entities.add(name)
128
+ for (const observation of item.observations || []) {
129
+ const body = String(observation ?? '').trim()
130
+ if (body) {
131
+ records.push({
132
+ text: body,
133
+ type: 'user',
134
+ metadata: { source: 'mcp-memory', entity: name, entityType: String(item.entityType ?? '') },
135
+ sourceRef: `entity:${name}`,
136
+ })
137
+ }
138
+ }
139
+ } else if (item?.type === 'relation') {
140
+ relations += 1
141
+ }
142
+ }
143
+ return { records, stats: { entities: entities.size, relations } }
144
+ }
145
+
146
+ export function importMcpMemory(store, text, scope = {}, { origin = 'import:mcp-memory' } = {}) {
147
+ const { records, stats } = readMcpMemory(text)
148
+ const withScope = records.map((record) => ({ ...record, ...scope }))
149
+ return { ...importRecords(store, withScope, origin), stats }
150
+ }
151
+
152
+ // ── Basic Memory Markdown ─────────────────────────────────────────────────
153
+
154
+ function splitFrontmatter(text) {
155
+ if (!text.startsWith('---')) return [{}, text]
156
+ const end = text.indexOf('\n---', 3)
157
+ if (end === -1) return [{}, text]
158
+ const raw = text.slice(3, end).trim()
159
+ const body = text.slice(end + 4).replace(/^\n+/, '')
160
+ const meta = {}
161
+ for (const line of raw.split(/\r?\n/)) {
162
+ const index = line.indexOf(':')
163
+ if (index === -1) continue
164
+ const key = line.slice(0, index).trim()
165
+ let value = line.slice(index + 1).trim()
166
+ if (value.startsWith('[') && value.endsWith(']')) {
167
+ value = value.slice(1, -1).split(',').map((item) => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
168
+ } else {
169
+ value = value.replace(/^['"]|['"]$/g, '')
170
+ }
171
+ meta[key] = value
172
+ }
173
+ return [meta, body]
174
+ }
175
+
176
+ function markdownFiles(path) {
177
+ if (statSync(path).isFile()) return path.endsWith('.md') ? [path] : []
178
+ const out = []
179
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
180
+ const child = join(path, entry.name)
181
+ if (entry.isDirectory()) out.push(...markdownFiles(child))
182
+ else if (entry.name.endsWith('.md')) out.push(child)
183
+ }
184
+ return out.sort()
185
+ }
186
+
187
+ export function readBasicMemory(path) {
188
+ const records = []
189
+ let notes = 0
190
+ let withoutObservations = 0
191
+ for (const file of markdownFiles(path)) {
192
+ const [meta, body] = splitFrontmatter(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
193
+ notes += 1
194
+ const observations = []
195
+ let inSection = false
196
+ for (const line of body.split(/\r?\n/)) {
197
+ if (/^##\s+Observations\s*$/i.test(line)) {
198
+ inSection = true
199
+ continue
200
+ }
201
+ if (inSection && line.startsWith('## ')) inSection = false
202
+ if (inSection && line.trimStart().startsWith('- ')) observations.push(line.trimStart().slice(2).trim())
203
+ }
204
+ if (!observations.length) {
205
+ withoutObservations += 1
206
+ continue
207
+ }
208
+ const title = String(meta.title || file.split(/[\\/]/).pop().replace(/\.md$/, ''))
209
+ for (const observation of observations) {
210
+ const match = observation.match(/^\[([^\]]+)\]\s*(.*)$/)
211
+ records.push({
212
+ text: match ? match[2].trim() : observation,
213
+ type: 'user',
214
+ metadata: {
215
+ source: 'basic-memory',
216
+ note: title,
217
+ category: match ? match[1].trim() : '',
218
+ tags: meta.tags || [],
219
+ permalink: meta.permalink || '',
220
+ path: file,
221
+ },
222
+ sourceRef: `note:${title}`,
223
+ })
224
+ }
225
+ }
226
+ return { records, stats: { notes, notes_without_observations: withoutObservations } }
227
+ }
228
+
229
+ export function importBasicMemory(store, path, scope = {}, { origin = 'import:basic-memory' } = {}) {
230
+ const { records, stats } = readBasicMemory(path)
231
+ const withScope = records.map((record) => ({ ...record, ...scope }))
232
+ return { ...importRecords(store, withScope, origin), stats }
233
+ }
234
+
235
+ // ── Mem0 ──────────────────────────────────────────────────────────────────
236
+
237
+ export function readMem0(payload) {
238
+ const items = Array.isArray(payload) ? payload
239
+ : (payload?.results || payload?.memories || payload?.items || [])
240
+ const records = []
241
+ for (const item of items) {
242
+ if (!item || typeof item !== 'object') continue
243
+ const text = String(item.memory ?? item.text ?? item.content ?? '').trim()
244
+ if (!text) continue
245
+ const metadata = (item.metadata && typeof item.metadata === 'object') ? item.metadata : {}
246
+ records.push({
247
+ text,
248
+ type: metadata.type ?? 'user',
249
+ metadata: { ...metadata, source: 'mem0' },
250
+ sourceRef: item.id ? String(item.id) : null,
251
+ createdAt: item.created_at ?? null,
252
+ })
253
+ }
254
+ return { records, stats: { items: items.length } }
255
+ }
256
+
257
+ export function importMem0(store, payload, scope = {}, { origin = 'import:mem0' } = {}) {
258
+ const { records, stats } = readMem0(payload)
259
+ const withScope = records.map((record) => ({ ...record, ...scope }))
260
+ return { ...importRecords(store, withScope, origin), stats }
261
+ }