dsh-memvault 0.9.12 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -396
- package/README.zh.md +50 -324
- package/cordis.patch.yml +18 -20
- package/docs/CORE-DESIGN.md +277 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/DEVLOG.md +701 -0
- package/docs/images/relation-graph-2026-11-02.png +0 -0
- package/docs/preview.svg +41 -0
- package/icon.svg +9 -0
- package/lib/blocks.js +11 -2
- package/lib/client.js +705 -168
- package/lib/config.js +46 -87
- package/lib/core/adjudicate.js +94 -0
- package/lib/core/backfill.js +32 -0
- package/lib/core/block-write.js +85 -0
- package/lib/core/decide.js +159 -0
- package/lib/core/embed.js +122 -0
- package/lib/core/env.js +72 -0
- package/lib/core/extract.js +151 -0
- package/lib/core/host.js +81 -0
- package/lib/core/importers.js +261 -0
- package/lib/core/llm.js +49 -0
- package/lib/{memories.js → core/panel-read.js} +80 -136
- package/lib/core/pipeline.js +95 -0
- package/lib/core/schema.js +123 -0
- package/lib/core/search.js +191 -0
- package/lib/core/store.js +347 -0
- package/lib/core/tools.js +182 -0
- package/lib/core/write.js +89 -0
- package/lib/extract.js +1 -39
- package/lib/index.js +194 -128
- package/lib/panel.js +13 -11
- package/lib/review.js +5 -1
- package/lib/structure.js +6 -1
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +10 -7
- package/scripts/backfill-core.mjs +53 -0
- package/scripts/import-core.mjs +56 -0
- package/scripts/smoke-config.mjs +12 -14
- package/scripts/smoke-extract.mjs +19 -40
- package/scripts/smoke-package.mjs +88 -27
- package/scripts/smoke-panel.mjs +293 -162
- package/src/client/index.js +703 -166
- package/lib/blocks-write.js +0 -121
- package/lib/cli.js +0 -90
- package/lib/reindex.js +0 -32
package/lib/core/llm.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The smallest OpenAI-compatible chat client the core needs.
|
|
3
|
+
*
|
|
4
|
+
* Extraction and decisions both speak Chat Completions; one client keeps the
|
|
5
|
+
* timeout, auth header and error shape in one place. `fetchImpl` is injectable so
|
|
6
|
+
* tests never touch the network, and a timeout aborts instead of hanging a turn
|
|
7
|
+
* — the old engine's 60s extraction timeouts are the lesson behind that.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export class ChatClient {
|
|
11
|
+
constructor({
|
|
12
|
+
baseUrl = 'https://api.openai.com/v1',
|
|
13
|
+
apiKey = '',
|
|
14
|
+
model = 'gpt-4o-mini',
|
|
15
|
+
timeoutMs = 60_000,
|
|
16
|
+
extraBody = {},
|
|
17
|
+
fetchImpl = fetch,
|
|
18
|
+
} = {}) {
|
|
19
|
+
if (!apiKey) throw new Error('apiKey is required')
|
|
20
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '')
|
|
21
|
+
this.apiKey = apiKey
|
|
22
|
+
this.model = model
|
|
23
|
+
this.timeoutMs = timeoutMs
|
|
24
|
+
this.extraBody = { ...extraBody }
|
|
25
|
+
this.fetchImpl = fetchImpl
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** One chat completion; returns the assistant's text. */
|
|
29
|
+
async complete(messages, { temperature = 0 } = {}) {
|
|
30
|
+
const controller = new AbortController()
|
|
31
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs)
|
|
32
|
+
try {
|
|
33
|
+
const response = await this.fetchImpl(`${this.baseUrl}/chat/completions`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: {
|
|
36
|
+
'content-type': 'application/json',
|
|
37
|
+
authorization: `Bearer ${this.apiKey}`,
|
|
38
|
+
},
|
|
39
|
+
body: JSON.stringify({ ...this.extraBody, model: this.model, temperature, messages }),
|
|
40
|
+
signal: controller.signal,
|
|
41
|
+
})
|
|
42
|
+
if (!response.ok) throw new Error(`chat HTTP ${response.status}`)
|
|
43
|
+
const data = await response.json()
|
|
44
|
+
return data?.choices?.[0]?.message?.content ?? ''
|
|
45
|
+
} finally {
|
|
46
|
+
clearTimeout(timer)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -1,29 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Panel reads on the in-plugin store.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* A substring match over `memory` is honest about being a browse: there is no
|
|
11
|
-
* index on that column, so it is a scan, which is exactly why the result set is
|
|
12
|
-
* bounded and says so.
|
|
13
|
-
*
|
|
14
|
-
* **Never `SELECT *`.** `memories.embedding` is a blob per row; MemVault's own
|
|
15
|
-
* maintenance paths use an explicit column list for this reason
|
|
16
|
-
* (`storage.iter_memory_meta`). Selecting the columns we display keeps a browse
|
|
17
|
-
* cheap regardless of how many rows exist.
|
|
4
|
+
* The shapes are the ones the panel already renders (`readMemories` /
|
|
5
|
+
* `readMemoryProvenance` / `countRetyped`), and the SQL differs only where the
|
|
6
|
+
* schema does: the memory text column is `text`, and history keeps
|
|
7
|
+
* `old_text`/`new_text`/`at`. The row shaping lives here now: the old reader
|
|
8
|
+
* module went away with the Python store, so this file owns both the SQL and the
|
|
9
|
+
* display contract.
|
|
18
10
|
*/
|
|
19
11
|
import { DatabaseSync } from 'node:sqlite'
|
|
20
12
|
|
|
21
|
-
/** Columns a browse reads — everything shown, and nothing that is a blob. */
|
|
22
|
-
export const MEMORY_COLUMNS = 'id, user_id, agent_id, run_id, memory, memory_type, metadata, created_at, updated_at'
|
|
23
|
-
|
|
24
|
-
/** Memory kinds MemVault writes. */
|
|
25
|
-
export const MEMORY_TYPES = ['user', 'agent', 'procedural']
|
|
26
|
-
|
|
27
13
|
/** Sort orders, mapped to a column so the value is never interpolated. */
|
|
28
14
|
export const MEMORY_ORDERS = { created: 'created_at', updated: 'updated_at' }
|
|
29
15
|
|
|
@@ -47,26 +33,55 @@ export const MAX_RELATIONS = 50
|
|
|
47
33
|
/** Longest old/new text shipped per history entry. */
|
|
48
34
|
export const HISTORY_TEXT_CLAMP = 1000
|
|
49
35
|
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
36
|
+
/** Text clamp for a related memory shown inside another memory's card. */
|
|
37
|
+
export const PRODUCED_VIEW_CLAMP = 400
|
|
38
|
+
|
|
39
|
+
/** Column list with the one alias the shaping helper expects. */
|
|
40
|
+
const CORE_COLUMNS = 'id, user_id, agent_id, run_id, text AS memory, memory_type, metadata, created_at, updated_at'
|
|
41
|
+
|
|
42
|
+
const clampText = (value, max) => {
|
|
43
|
+
if (typeof value !== 'string') return null
|
|
44
|
+
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const parseMetadata = (raw) => {
|
|
48
|
+
if (typeof raw !== 'string' || raw === '') return null
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(raw)
|
|
51
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
52
|
+
const text = JSON.stringify(parsed)
|
|
53
|
+
return text.length > METADATA_CLAMP ? { truncated: text.slice(0, METADATA_CLAMP) } : parsed
|
|
54
|
+
} catch {
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Shape one row for the panel: display fields only, long values clamped. */
|
|
60
|
+
export function shapeMemoryRow(row) {
|
|
61
|
+
const text = typeof row.memory === 'string' ? row.memory : ''
|
|
62
|
+
return {
|
|
63
|
+
id: row.id,
|
|
64
|
+
memory: text.length > MEMORY_TEXT_CLAMP ? `${text.slice(0, MEMORY_TEXT_CLAMP)}…` : text,
|
|
65
|
+
chars: text.length,
|
|
66
|
+
type: row.memory_type ?? null,
|
|
67
|
+
user: row.user_id ?? null,
|
|
68
|
+
agent: row.agent_id ?? null,
|
|
69
|
+
run: row.run_id ?? null,
|
|
70
|
+
metadata: parseMetadata(row.metadata),
|
|
71
|
+
createdAt: row.created_at ?? null,
|
|
72
|
+
updatedAt: row.updated_at ?? null,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Same filters as the old builder, over the core schema. */
|
|
77
|
+
export function buildCoreMemoryQuery(query = {}) {
|
|
62
78
|
const where = []
|
|
63
79
|
const args = []
|
|
64
80
|
|
|
65
81
|
const text = typeof query.q === 'string' ? query.q.trim() : ''
|
|
66
82
|
if (text !== '') {
|
|
67
|
-
// `%` and `_` are LIKE wildcards; a search for "50%" must not match everything.
|
|
68
83
|
const escaped = text.replace(/[\\%_]/g, (char) => `\\${char}`)
|
|
69
|
-
where.push("
|
|
84
|
+
where.push("text LIKE ? ESCAPE '\\'")
|
|
70
85
|
args.push(`%${escaped}%`)
|
|
71
86
|
}
|
|
72
87
|
|
|
@@ -83,8 +98,6 @@ export function buildMemoryQuery(query = {}) {
|
|
|
83
98
|
args.push(value)
|
|
84
99
|
}
|
|
85
100
|
|
|
86
|
-
// An explicit id list: how a diagnostic's "these are the memories this window
|
|
87
|
-
// produced" turns back into rows. Ids are values, so they are placeholders too.
|
|
88
101
|
const ids = typeof query.ids === 'string'
|
|
89
102
|
? query.ids.split(',').map((id) => id.trim()).filter((id) => id !== '').slice(0, MAX_IDS)
|
|
90
103
|
: []
|
|
@@ -93,14 +106,8 @@ export function buildMemoryQuery(query = {}) {
|
|
|
93
106
|
args.push(...ids)
|
|
94
107
|
}
|
|
95
108
|
|
|
96
|
-
// Rows the store's own type refinement moved out of `user` (metadata carries
|
|
97
|
-
// `retyped_from`). Surfacing them is the point: a heuristic that silently
|
|
98
|
-
// reclassifies a row is indistinguishable from one that got it wrong, so the
|
|
99
|
-
// panel has to be able to list exactly those rows and let a human judge.
|
|
100
109
|
const retyped = query.retyped === '1' || query.retyped === 'true' || query.retyped === true
|
|
101
|
-
if (retyped)
|
|
102
|
-
where.push(`metadata LIKE '%"retyped_from"%'`)
|
|
103
|
-
}
|
|
110
|
+
if (retyped) where.push(`metadata LIKE '%"retyped_from"%'`)
|
|
104
111
|
|
|
105
112
|
const rawLimit = Number(query.limit)
|
|
106
113
|
const limit = Number.isFinite(rawLimit) && rawLimit > 0
|
|
@@ -112,7 +119,7 @@ export function buildMemoryQuery(query = {}) {
|
|
|
112
119
|
const clause = where.length > 0 ? ` WHERE ${where.join(' AND ')}` : ''
|
|
113
120
|
|
|
114
121
|
return {
|
|
115
|
-
sql: `SELECT ${
|
|
122
|
+
sql: `SELECT ${CORE_COLUMNS} FROM memories${clause} ORDER BY ${MEMORY_ORDERS[order]} DESC, id DESC LIMIT ? OFFSET ?`,
|
|
116
123
|
countSql: `SELECT COUNT(*) AS n FROM memories${clause}`,
|
|
117
124
|
args: [...args, limit, offset],
|
|
118
125
|
countArgs: args,
|
|
@@ -131,63 +138,47 @@ export function buildMemoryQuery(query = {}) {
|
|
|
131
138
|
}
|
|
132
139
|
}
|
|
133
140
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const parsed = JSON.parse(raw)
|
|
138
|
-
if (parsed === null || typeof parsed !== 'object') return null
|
|
139
|
-
const text = JSON.stringify(parsed)
|
|
140
|
-
return text.length > METADATA_CLAMP ? JSON.parse(JSON.stringify({ truncated: text.slice(0, METADATA_CLAMP) })) : parsed
|
|
141
|
-
} catch {
|
|
142
|
-
return null
|
|
143
|
-
}
|
|
141
|
+
/** One read-only connection per call, same as the old module. */
|
|
142
|
+
function open(dbPath) {
|
|
143
|
+
return new DatabaseSync(dbPath, { readOnly: true, timeout: 2000 })
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
146
|
+
export function readMemories({ dbPath, query = {} } = {}) {
|
|
147
|
+
const built = buildCoreMemoryQuery(query)
|
|
148
|
+
const db = open(dbPath)
|
|
149
|
+
try {
|
|
150
|
+
const total = db.prepare(built.countSql).get(...built.countArgs)?.n ?? 0
|
|
151
|
+
const rows = db.prepare(built.sql).all(...built.args)
|
|
152
|
+
return {
|
|
153
|
+
rows: rows.map(shapeMemoryRow),
|
|
154
|
+
total,
|
|
155
|
+
limit: built.limit,
|
|
156
|
+
offset: built.offset,
|
|
157
|
+
order: built.order,
|
|
158
|
+
applied: built.applied,
|
|
159
|
+
mode: 'substring',
|
|
160
|
+
}
|
|
161
|
+
} finally {
|
|
162
|
+
db.close()
|
|
160
163
|
}
|
|
161
164
|
}
|
|
162
165
|
|
|
163
|
-
/**
|
|
164
|
-
* Read one memory's provenance: the row, every decision recorded about it, and
|
|
165
|
-
* the contradictions it takes part in.
|
|
166
|
-
*
|
|
167
|
-
* MemVault audits every ADD/UPDATE/DELETE in `history` (with the old and new
|
|
168
|
-
* text) and records contradictions as `relations`. That is what answers "how did
|
|
169
|
-
* this memory become what it is" — the question a quality judgement actually needs
|
|
170
|
-
* — and it is all read-only.
|
|
171
|
-
*
|
|
172
|
-
* @returns `{ memory, history, relations, missing }`; `missing: true` when the id
|
|
173
|
-
* is unknown (a flagged memory can be deleted later, and that must not 500).
|
|
174
|
-
*/
|
|
175
166
|
export function readMemoryProvenance({ dbPath, id } = {}) {
|
|
176
167
|
const wanted = typeof id === 'string' ? id.trim() : ''
|
|
177
168
|
if (wanted === '') return { memory: null, history: [], relations: [], missing: true }
|
|
178
169
|
|
|
179
|
-
const db =
|
|
170
|
+
const db = open(dbPath)
|
|
180
171
|
try {
|
|
181
|
-
const row = db.prepare(`SELECT ${
|
|
172
|
+
const row = db.prepare(`SELECT ${CORE_COLUMNS} FROM memories WHERE id = ?`).get(wanted)
|
|
182
173
|
if (row === undefined) return { memory: null, history: [], relations: [], missing: true }
|
|
183
174
|
|
|
184
175
|
const history = db.prepare(
|
|
185
|
-
'SELECT action,
|
|
176
|
+
'SELECT action, old_text, new_text, at FROM history WHERE memory_id = ? ORDER BY id',
|
|
186
177
|
).all(wanted).slice(-MAX_HISTORY).map((entry) => ({
|
|
187
178
|
action: entry.action ?? null,
|
|
188
|
-
old: clampText(entry.
|
|
189
|
-
new: clampText(entry.
|
|
190
|
-
at: entry.
|
|
179
|
+
old: clampText(entry.old_text, HISTORY_TEXT_CLAMP),
|
|
180
|
+
new: clampText(entry.new_text, HISTORY_TEXT_CLAMP),
|
|
181
|
+
at: entry.at ?? null,
|
|
191
182
|
}))
|
|
192
183
|
|
|
193
184
|
const links = db.prepare(
|
|
@@ -195,7 +186,7 @@ export function readMemoryProvenance({ dbPath, id } = {}) {
|
|
|
195
186
|
).all(wanted, wanted, MAX_RELATIONS)
|
|
196
187
|
const otherIds = [...new Set(links.map((link) => (link.source_id === wanted ? link.target_id : link.source_id)))]
|
|
197
188
|
const others = otherIds.length === 0 ? [] : db.prepare(
|
|
198
|
-
`SELECT ${
|
|
189
|
+
`SELECT ${CORE_COLUMNS} FROM memories WHERE id IN (${otherIds.map(() => '?').join(', ')})`,
|
|
199
190
|
).all(...otherIds)
|
|
200
191
|
const byId = new Map(others.map((other) => [other.id, other]))
|
|
201
192
|
|
|
@@ -207,8 +198,6 @@ export function readMemoryProvenance({ dbPath, id } = {}) {
|
|
|
207
198
|
direction: outgoing ? 'out' : 'in',
|
|
208
199
|
id: otherId,
|
|
209
200
|
weight: typeof link.weight === 'number' ? link.weight : null,
|
|
210
|
-
// A relation can outlive the memory it points at (deletes drop the row,
|
|
211
|
-
// not always the edge); say so instead of showing an empty card.
|
|
212
201
|
alive: other !== undefined,
|
|
213
202
|
text: other ? clampText(other.memory, PRODUCED_VIEW_CLAMP) : null,
|
|
214
203
|
}
|
|
@@ -220,54 +209,9 @@ export function readMemoryProvenance({ dbPath, id } = {}) {
|
|
|
220
209
|
}
|
|
221
210
|
}
|
|
222
211
|
|
|
223
|
-
/** Text clamp for a related memory shown inside another memory's card. */
|
|
224
|
-
export const PRODUCED_VIEW_CLAMP = 400
|
|
225
|
-
|
|
226
|
-
const clampText = (value, max) => {
|
|
227
|
-
if (typeof value !== 'string') return null
|
|
228
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Read one page of memories from the store, read-only.
|
|
233
|
-
*
|
|
234
|
-
* Throws when the store is unreadable; the route turns that into a reported
|
|
235
|
-
* error, because a panel that shows a stale list would be worse than one that
|
|
236
|
-
* says it cannot read.
|
|
237
|
-
*/
|
|
238
|
-
export function readMemories({ dbPath, query = {} } = {}) {
|
|
239
|
-
const built = buildMemoryQuery(query)
|
|
240
|
-
const db = new DatabaseSync(dbPath, { readOnly: true, timeout: 2000 })
|
|
241
|
-
try {
|
|
242
|
-
const total = db.prepare(built.countSql).get(...built.countArgs)?.n ?? 0
|
|
243
|
-
const rows = db.prepare(built.sql).all(...built.args)
|
|
244
|
-
return {
|
|
245
|
-
rows: rows.map(shapeMemoryRow),
|
|
246
|
-
total,
|
|
247
|
-
limit: built.limit,
|
|
248
|
-
offset: built.offset,
|
|
249
|
-
order: built.order,
|
|
250
|
-
applied: built.applied,
|
|
251
|
-
// Stated in the payload because the panel says it out loud: this is a
|
|
252
|
-
// substring scan over the text column, not ranked retrieval.
|
|
253
|
-
mode: 'substring',
|
|
254
|
-
}
|
|
255
|
-
} finally {
|
|
256
|
-
db.close()
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* How many rows the type refinement moved out of `user`.
|
|
262
|
-
*
|
|
263
|
-
* A separate count because the panel needs the number even when it is not
|
|
264
|
-
* filtering by it — "the heuristic acted N times, here they are" is the whole
|
|
265
|
-
* point of surfacing it. Returns 0 on an unreadable store rather than throwing:
|
|
266
|
-
* the badge is not worth failing a browse over.
|
|
267
|
-
*/
|
|
268
212
|
export function countRetyped({ dbPath } = {}) {
|
|
269
213
|
try {
|
|
270
|
-
const db =
|
|
214
|
+
const db = open(dbPath)
|
|
271
215
|
try {
|
|
272
216
|
return db.prepare(`SELECT COUNT(*) AS n FROM memories WHERE metadata LIKE '%"retyped_from"%'`).get()?.n ?? 0
|
|
273
217
|
} finally {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The extraction pipeline on the in-plugin store (replaces the Python CLI call).
|
|
3
|
+
*
|
|
4
|
+
* Same contract as the old Python extraction path returned — `{ ok, added, produced }`
|
|
5
|
+
* and never throwing into the caller, because memory capture is a side channel
|
|
6
|
+
* that must not break a turn. What changes is the implementation: extraction,
|
|
7
|
+
* decisions and writes all happen in-process against `CoreStore`.
|
|
8
|
+
*
|
|
9
|
+
* The extractor is chosen from the merged environment, exactly like the Python
|
|
10
|
+
* engine did: `MEMVAULT_EXTRACTOR` wins when set (`llm` needs a key, `rule`
|
|
11
|
+
* forces the deterministic path), otherwise a key selects the LLM extractor and
|
|
12
|
+
* its absence falls back to rules. No key is an install state, not an error.
|
|
13
|
+
*/
|
|
14
|
+
import { ChatClient } from './llm.js'
|
|
15
|
+
import { LLMExtractor, RuleExtractor } from './extract.js'
|
|
16
|
+
import { resolveEmbedder, findEnvFile, readEnvFile } from './env.js'
|
|
17
|
+
import { shapeProduced } from '../extract.js'
|
|
18
|
+
import { remember } from './write.js'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Build the extractor + embedder for this install.
|
|
22
|
+
*
|
|
23
|
+
* @param {object} options
|
|
24
|
+
* @param {string} [options.projectDir] - where the MemVault `.env` lives.
|
|
25
|
+
* @param {string} [options.dbPath] - core store path (used for `.env` fallback).
|
|
26
|
+
* @param {object} [options.env] - explicit environment (config, tests).
|
|
27
|
+
*/
|
|
28
|
+
export function buildPipeline({ projectDir = '', dbPath = '', env = process.env } = {}) {
|
|
29
|
+
const file = findEnvFile({ projectDir, dbPath })
|
|
30
|
+
const merged = { ...(file ? readEnvFile(file) : {}), ...env }
|
|
31
|
+
let extraBody = {}
|
|
32
|
+
if (merged.MEMVAULT_LLM_EXTRA_BODY) {
|
|
33
|
+
try {
|
|
34
|
+
extraBody = JSON.parse(merged.MEMVAULT_LLM_EXTRA_BODY)
|
|
35
|
+
} catch {
|
|
36
|
+
extraBody = {}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const requested = String(merged.MEMVAULT_EXTRACTOR ?? '').toLowerCase()
|
|
40
|
+
const useLlm = requested === 'rule' ? false : Boolean(merged.OPENAI_API_KEY)
|
|
41
|
+
const extractor = useLlm
|
|
42
|
+
? new LLMExtractor(new ChatClient({
|
|
43
|
+
baseUrl: merged.OPENAI_BASE_URL || 'https://api.openai.com/v1',
|
|
44
|
+
apiKey: merged.OPENAI_API_KEY,
|
|
45
|
+
model: merged.OPENAI_CHAT_MODEL || 'gpt-4o-mini',
|
|
46
|
+
timeoutMs: Number(merged.MEMVAULT_EXTRACT_TIMEOUT_MS ?? 60_000),
|
|
47
|
+
extraBody,
|
|
48
|
+
}))
|
|
49
|
+
: new RuleExtractor()
|
|
50
|
+
return {
|
|
51
|
+
extractor,
|
|
52
|
+
embedder: resolveEmbedder({ projectDir, dbPath, env: merged }),
|
|
53
|
+
usesModel: useLlm,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A pipeline honouring a per-call override.
|
|
59
|
+
*
|
|
60
|
+
* The plugin builds one pipeline at startup, but a replay can ask for a different
|
|
61
|
+
* extractor (`MEMVAULT_EXTRACTOR=rule|llm`). Before this, that request was
|
|
62
|
+
* silently ignored — the replay UI offered the choice and the fixed startup
|
|
63
|
+
* pipeline made it anyway. Overrides win over the base environment, which is how
|
|
64
|
+
* the Python path used to treat them.
|
|
65
|
+
*/
|
|
66
|
+
export function resolvePipeline({ projectDir = '', dbPath = '', baseEnv = {}, overrides = {} } = {}) {
|
|
67
|
+
return buildPipeline({ projectDir, dbPath, env: { ...baseEnv, ...overrides } })
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Run one extraction window against the core store.
|
|
72
|
+
*
|
|
73
|
+
* @returns {Promise<{ok: boolean, added?: number, superseded?: number,
|
|
74
|
+
* produced?: Array, error?: string}>}
|
|
75
|
+
*/
|
|
76
|
+
export async function runCoreExtraction({ store, extractor, embedder = null, scope = {}, messages }) {
|
|
77
|
+
try {
|
|
78
|
+
const summary = await remember({ store, scope, messages, extractor, embedder, origin: 'extract' })
|
|
79
|
+
const applied = summary.applied ?? []
|
|
80
|
+
const produced = shapeProduced(applied.map((memory) => ({
|
|
81
|
+
id: memory.id,
|
|
82
|
+
memory: memory.text,
|
|
83
|
+
memory_type: memory.type,
|
|
84
|
+
})))
|
|
85
|
+
return {
|
|
86
|
+
ok: true,
|
|
87
|
+
added: summary.added + summary.superseded,
|
|
88
|
+
superseded: summary.superseded,
|
|
89
|
+
relations: summary.relations,
|
|
90
|
+
produced,
|
|
91
|
+
}
|
|
92
|
+
} catch (error) {
|
|
93
|
+
return { ok: false, error: `${error?.name ?? 'Error'}: ${error?.message ?? String(error)}` }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DDL for the in-plugin store.
|
|
3
|
+
*
|
|
4
|
+
* This is the schema from `docs/CORE-DESIGN.md`, and it deliberately differs
|
|
5
|
+
* from the Python engine's: embeddings live in their own table (so a model
|
|
6
|
+
* change never rewrites a memory row), updates are supersede operations with a
|
|
7
|
+
* validity window instead of in-place overwrites, provenance is first class,
|
|
8
|
+
* and keyword search is an FTS5 trigram index (verified to match Chinese
|
|
9
|
+
* substrings on the DSH runtime: Node 24 / SQLite 3.53).
|
|
10
|
+
*
|
|
11
|
+
* `meta.schema_version` is written on creation so a future migration has a
|
|
12
|
+
* version to read rather than a schema to guess.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const SCHEMA_VERSION = 1
|
|
16
|
+
|
|
17
|
+
export const DDL = `
|
|
18
|
+
PRAGMA journal_mode = WAL;
|
|
19
|
+
PRAGMA foreign_keys = ON;
|
|
20
|
+
PRAGMA busy_timeout = 3000;
|
|
21
|
+
|
|
22
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
23
|
+
key TEXT PRIMARY KEY,
|
|
24
|
+
value TEXT NOT NULL
|
|
25
|
+
) WITHOUT ROWID;
|
|
26
|
+
|
|
27
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
28
|
+
id TEXT PRIMARY KEY,
|
|
29
|
+
user_id TEXT,
|
|
30
|
+
agent_id TEXT,
|
|
31
|
+
run_id TEXT,
|
|
32
|
+
text TEXT NOT NULL,
|
|
33
|
+
memory_type TEXT NOT NULL DEFAULT 'user'
|
|
34
|
+
CHECK (memory_type IN ('user','agent','procedural')),
|
|
35
|
+
metadata TEXT NOT NULL DEFAULT '{}',
|
|
36
|
+
origin TEXT NOT NULL DEFAULT 'manual',
|
|
37
|
+
source_ref TEXT,
|
|
38
|
+
confidence REAL NOT NULL DEFAULT 1.0,
|
|
39
|
+
created_at TEXT NOT NULL,
|
|
40
|
+
updated_at TEXT NOT NULL,
|
|
41
|
+
valid_from TEXT NOT NULL,
|
|
42
|
+
superseded_by TEXT REFERENCES memories(id) ON DELETE SET NULL,
|
|
43
|
+
CHECK (user_id IS NOT NULL OR agent_id IS NOT NULL OR run_id IS NOT NULL)
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
CREATE INDEX IF NOT EXISTS memories_scope_current
|
|
47
|
+
ON memories(user_id, agent_id, run_id) WHERE superseded_by IS NULL;
|
|
48
|
+
CREATE INDEX IF NOT EXISTS memories_superseded ON memories(superseded_by);
|
|
49
|
+
|
|
50
|
+
CREATE TABLE IF NOT EXISTS memory_embeddings (
|
|
51
|
+
memory_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
|
52
|
+
model TEXT NOT NULL,
|
|
53
|
+
dim INTEGER NOT NULL,
|
|
54
|
+
vector BLOB NOT NULL,
|
|
55
|
+
created_at TEXT NOT NULL,
|
|
56
|
+
PRIMARY KEY (memory_id, model)
|
|
57
|
+
) WITHOUT ROWID;
|
|
58
|
+
|
|
59
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
60
|
+
text,
|
|
61
|
+
content='memories',
|
|
62
|
+
content_rowid='rowid',
|
|
63
|
+
tokenize='trigram'
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
|
|
67
|
+
INSERT INTO memories_fts(rowid, text) VALUES (new.rowid, new.text);
|
|
68
|
+
END;
|
|
69
|
+
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
|
|
70
|
+
INSERT INTO memories_fts(memories_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
|
|
71
|
+
END;
|
|
72
|
+
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE OF text ON memories BEGIN
|
|
73
|
+
INSERT INTO memories_fts(memories_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
|
|
74
|
+
INSERT INTO memories_fts(rowid, text) VALUES (new.rowid, new.text);
|
|
75
|
+
END;
|
|
76
|
+
|
|
77
|
+
CREATE TABLE IF NOT EXISTS blocks (
|
|
78
|
+
scope_type TEXT NOT NULL CHECK (scope_type IN ('user','agent')),
|
|
79
|
+
scope_id TEXT NOT NULL,
|
|
80
|
+
label TEXT NOT NULL,
|
|
81
|
+
value TEXT NOT NULL,
|
|
82
|
+
value_limit INTEGER NOT NULL DEFAULT 2000,
|
|
83
|
+
position INTEGER NOT NULL DEFAULT 0,
|
|
84
|
+
created_at TEXT NOT NULL,
|
|
85
|
+
updated_at TEXT NOT NULL,
|
|
86
|
+
PRIMARY KEY (scope_type, scope_id, label)
|
|
87
|
+
) WITHOUT ROWID;
|
|
88
|
+
|
|
89
|
+
CREATE TABLE IF NOT EXISTS relations (
|
|
90
|
+
id INTEGER PRIMARY KEY,
|
|
91
|
+
source_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
|
92
|
+
target_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
|
93
|
+
kind TEXT NOT NULL DEFAULT 'related'
|
|
94
|
+
CHECK (kind IN ('related','similar','contradicts','supersedes')),
|
|
95
|
+
weight REAL NOT NULL DEFAULT 0,
|
|
96
|
+
created_at TEXT NOT NULL,
|
|
97
|
+
UNIQUE (source_id, target_id, kind)
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
CREATE TABLE IF NOT EXISTS history (
|
|
101
|
+
id INTEGER PRIMARY KEY,
|
|
102
|
+
-- No foreign key on purpose: the audit trail must outlive the memory it is
|
|
103
|
+
-- about, or a delete erases its own record. The real export proved this:
|
|
104
|
+
-- it carries history rows whose memory was deleted in the old store.
|
|
105
|
+
memory_id TEXT NOT NULL,
|
|
106
|
+
action TEXT NOT NULL
|
|
107
|
+
CHECK (action IN ('add','update','supersede','delete','import')),
|
|
108
|
+
old_text TEXT,
|
|
109
|
+
new_text TEXT,
|
|
110
|
+
actor TEXT NOT NULL DEFAULT 'system',
|
|
111
|
+
at TEXT NOT NULL
|
|
112
|
+
);
|
|
113
|
+
CREATE INDEX IF NOT EXISTS history_memory ON history(memory_id, at);
|
|
114
|
+
|
|
115
|
+
CREATE TABLE IF NOT EXISTS flags (
|
|
116
|
+
memory_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
|
117
|
+
reason TEXT NOT NULL,
|
|
118
|
+
status TEXT NOT NULL DEFAULT 'open'
|
|
119
|
+
CHECK (status IN ('open','resolved','dismissed')),
|
|
120
|
+
created_at TEXT NOT NULL,
|
|
121
|
+
PRIMARY KEY (memory_id, reason)
|
|
122
|
+
) WITHOUT ROWID;
|
|
123
|
+
`
|