dsh-memvault 0.9.11 → 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.
Files changed (48) hide show
  1. package/README.md +51 -396
  2. package/README.zh.md +50 -324
  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 +739 -2
  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 +34 -40
  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 +10 -7
  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 +40 -40
  43. package/scripts/smoke-package.mjs +88 -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
package/lib/index.js CHANGED
@@ -25,7 +25,6 @@ import {
25
25
  createEventBuffer,
26
26
  loadState,
27
27
  renderTranscript,
28
- runExtraction,
29
28
  saveState,
30
29
  saveWatermarks,
31
30
  turnSpanByBoundary,
@@ -45,9 +44,13 @@ import {
45
44
  buildStatus,
46
45
  createPanelApi,
47
46
  } from './panel.js'
48
- import { runBlockAction } from './blocks-write.js'
49
- import { countRetyped, readMemories, readMemoryProvenance } from './memories.js'
47
+ import { countRetyped, readMemories, readMemoryProvenance } from './core/panel-read.js'
50
48
  import { buildStructure } from './structure.js'
49
+ import { CoreStore } from './core/store.js'
50
+ import { DEFAULT_CORE_DB } from './core/host.js'
51
+ import { buildPipeline, resolvePipeline, runCoreExtraction } from './core/pipeline.js'
52
+ import { runBlockActionCore } from './core/block-write.js'
53
+ import { backfillEmbeddings } from './core/backfill.js'
51
54
  import { flaggedIds, normalizeFlags, setFlag } from './flags.js'
52
55
  import {
53
56
  MAX_REVIEW_ITEMS,
@@ -60,8 +63,8 @@ import {
60
63
  validateReplay,
61
64
  } from './review.js'
62
65
  import { createTurnWindow } from './window.js'
63
- import { runReindex } from './reindex.js'
64
- import { MEMVAULT_DIR, MEMVAULT_PYTHON, configDefaults, discoverySnapshot, resolveConfig } from './config.js'
66
+ import { attachMemoryTools } from './core/host.js'
67
+ import { MEMVAULT_DIR, configDefaults, discoverySnapshot, resolveConfig } from './config.js'
65
68
 
66
69
  /** Plugin row id (must match the name in cordis.patch.yml). */
67
70
  export const name = 'dsh-memvault'
@@ -95,12 +98,12 @@ export function dbFileInfo(dbPath) {
95
98
  /**
96
99
  * Do the configured paths actually resolve?
97
100
  *
98
- * Setup-time validation. Without it a wrong `pythonPath` or `projectDir` shows up
99
- * only as "extraction quietly stopped", and a wrong `dbPath` as "my memories are
100
- * gone" — both much later, and both easy to misread as a bug in the memory itself.
101
+ * Setup-time validation. Without it a wrong `projectDir` shows up only as
102
+ * "extraction quietly stopped" and a wrong store path as "my memories are gone" —
103
+ * both much later, and both easy to misread as a bug in the memory itself.
101
104
  * Each entry is `{ key, label, target, ok, detail }`; nothing here throws.
102
105
  */
103
- export function checkPaths({ pythonPath, projectDir, dbPath, statePath } = {}) {
106
+ export function checkPaths({ projectDir, dbPath, statePath } = {}) {
104
107
  const isDir = (path) => {
105
108
  try { return statSync(path).isDirectory() } catch { return false }
106
109
  }
@@ -114,32 +117,27 @@ export function checkPaths({ pythonPath, projectDir, dbPath, statePath } = {}) {
114
117
  }
115
118
  const checks = []
116
119
 
117
- checks.push(pythonPath
118
- ? {
119
- key: 'python',
120
- label: 'Python',
121
- target: pythonPath,
122
- ok: isFile(pythonPath),
123
- detail: isFile(pythonPath) ? '可执行文件存在' : '找不到这个 python(抽取与写块都会失败)',
124
- }
125
- : { key: 'python', label: 'Python', target: '', ok: false, detail: '未配置 pythonPath' })
126
-
127
- checks.push(projectDir ? {
120
+ // `projectDir` no longer drives a child process: since the Python engine retired
121
+ // it is only where the pipeline reads `.env`. A directory with no `.env` is
122
+ // therefore a *reported* state, not a failure — offline embedding and the rule
123
+ // extractor are a supported install.
124
+ const hasEnv = projectDir !== undefined && projectDir !== '' && isFile(`${projectDir}/.env`)
125
+ checks.push(projectDir ? {
128
126
  key: 'projectDir',
129
- label: 'MemVault 项目目录',
127
+ label: '项目目录(.env 所在)',
130
128
  target: projectDir,
131
- ok: isDir(projectDir) && isDir(`${projectDir.replace(/[\\/]+$/, '')}/memvault`),
129
+ ok: isDir(projectDir),
132
130
  detail: !isDir(projectDir)
133
- ? '目录不存在'
134
- : (isDir(`${projectDir.replace(/[\\/]+$/, '')}/memvault`) ? '目录里能找到 memvault 包' : '目录存在,但找不到 memvault/ 包(可能指错了地方)'),
131
+ ? '目录不存在(读不到 .env,抽取与嵌入会退回离线规则)'
132
+ : (hasEnv ? '.env 存在' : '目录存在但没有 .env(嵌入退回离线哈希,抽取退回规则)'),
135
133
  }
136
- : { key: 'projectDir', label: 'MemVault 项目目录', target: '', ok: false, detail: '未配置 projectDir' })
134
+ : { key: 'projectDir', label: '项目目录(.env 所在)', target: '', ok: true, detail: '未配置:只用库旁与进程环境的 .env' })
137
135
 
138
136
  checks.push({
139
137
  key: 'db',
140
138
  label: '库文件',
141
139
  target: dbPath ?? '',
142
- // Missing file is fine as long as its folder exists: MemVault creates the file
140
+ // Missing file is fine as long as its folder exists: the store creates the file
143
141
  // on the first write. A missing *folder* is the case that silently fails.
144
142
  ok: isFile(dbPath) || isDir(parentOf(dbPath)),
145
143
  detail: isFile(dbPath)
@@ -155,21 +153,18 @@ export function checkPaths({ pythonPath, projectDir, dbPath, statePath } = {}) {
155
153
  detail: statePath ? (isFile(statePath) ? '文件存在' : `尚未创建(父目录${isDir(parentOf(statePath)) ? '存在' : '不存在'})`) : '未配置 statePath(会用默认位置)',
156
154
  })
157
155
 
158
- // The service's own answer to "which store". This plugin states its path to the
159
- // children it spawns, but MemVault also reads its project `.env`, and anything that
160
- // talks to the store without going through the plugin — an MCP server, a plain CLI
161
- // call — uses that one. Two answers to the same question is the confusion 0.9.6
162
- // spent a release removing, so it is checked here rather than left invisible.
163
- const envFile = `${parentOf(dbPath ?? '')}/.env`
156
+ // The plugin's own embedding choice, read from the same `.env` the pipeline
157
+ // resolves at runtime: a key means the OpenAI-compatible endpoint, an explicit
158
+ // MEMVAULT_EMBEDDER wins, and neither means the offline hashing embedder. The
159
+ // store's vectors are keyed by model, so this is the row the panel must show.
160
+ const envFile = `${projectDir ?? ''}/.env`
164
161
  const envText = (() => {
165
- for (const candidate of [envFile, `${projectDir ?? ''}/.env`]) {
162
+ for (const candidate of [envFile, `${parentOf(dbPath ?? '')}/.env`]) {
166
163
  if (candidate === '' || !isFile(candidate)) continue
167
164
  try { return { path: candidate, text: readFileSync(candidate, 'utf8') } } catch { /* unreadable: try the next */ }
168
165
  }
169
166
  return null
170
167
  })()
171
- // One reader for every variable in that file. Adding a variable used to mean copying this
172
- // parsing loop, which is how two copies of a rule start to disagree.
173
168
  const declaredVar = (name) => {
174
169
  if (envText === null) return null
175
170
  for (const line of envText.text.split('\n')) {
@@ -181,58 +176,26 @@ export function checkPaths({ pythonPath, projectDir, dbPath, statePath } = {}) {
181
176
  }
182
177
  return null
183
178
  }
184
- const declared = declaredVar('MEMVAULT_DB_PATH')
185
- // Windows treats D:\x\y.db and d:/x/y.db as one file, and a false "mismatch" would
186
- // be its own small lie.
187
- const normalize = (value) => String(value ?? '').split('\\').join('/').toLowerCase()
188
- if (declared === null) {
189
- checks.push({
190
- key: 'serviceStore',
191
- label: '服务端库文件(.env)',
192
- target: envText?.path ?? envFile,
193
- ok: true,
194
- detail: envText === null
195
- ? '没有 .env,服务端会用相对默认 data/memvault.db(与插件的 dbPath 同目录时才一致)'
196
- : '.env 里没有 MEMVAULT_DB_PATH',
197
- })
198
- } else {
199
- const same = normalize(declared) === normalize(dbPath)
200
- checks.push({
201
- key: 'serviceStore',
202
- label: '服务端库文件(.env)',
203
- target: envText.path,
204
- ok: same,
205
- detail: same
206
- ? `${declared} · 与插件的库文件一致`
207
- : `${declared} · 与插件的库文件不一致——不经插件的调用(MCP 工具等)读的是它,不是面板显示的这份`,
208
- })
209
- }
210
-
211
- // Which embedder the service will use. This plugin embeds nothing itself, so the answer
212
- // comes from the same .env - and it decides whether a query is compared against vectors
213
- // from the same model. A store whose vectors all come from one model while nothing records
214
- // that is exactly the confusion this makes visible.
215
179
  const serviceEmbedder = declaredVar('MEMVAULT_EMBEDDER')
216
180
  const serviceModel = declaredVar('OPENAI_EMBEDDING_MODEL')
217
181
  const serviceDim = declaredVar('MEMVAULT_EMBEDDING_DIM')
182
+ const apiKey = declaredVar('OPENAI_API_KEY')
183
+ const chosen = serviceEmbedder !== null
184
+ ? [serviceEmbedder, serviceModel].filter(Boolean).join(' · ')
185
+ : (apiKey ? ['openai', serviceModel].filter(Boolean).join(' · ') : 'local(特征哈希,只比字面)')
218
186
  checks.push({
219
187
  key: 'serviceEmbedder',
220
- label: '服务端嵌入器(.env)',
188
+ label: '嵌入器(.env)',
221
189
  target: envText?.path ?? envFile,
222
190
  ok: true,
223
- detail: [
224
- serviceEmbedder === null
225
- ? '未设置 → 默认 local(特征哈希,只比字面)'
226
- : [serviceEmbedder, serviceModel].filter(Boolean).join(' · '),
227
- serviceDim !== null ? ('dim ' + serviceDim) : '维度未写死,由模型首次调用时确定',
228
- ].join(' · '),
191
+ detail: `${chosen} · ${serviceDim !== null ? `dim ${serviceDim}` : '维度由模型首次调用时确定'}`,
229
192
  })
230
193
 
231
194
  return checks
232
195
  }
233
196
 
234
- /** MemVault checkout the write half drives, and its interpreter (see `config.js`). */
235
- export { MEMVAULT_DIR, MEMVAULT_PYTHON }
197
+ /** Directory whose `.env` the extractor/embedder resolve against (see `config.js`). */
198
+ export { MEMVAULT_DIR }
236
199
 
237
200
  /**
238
201
  * Extraction defaults, derived from the config spec — one description of every
@@ -273,7 +236,10 @@ export function apply(ctx, config = {}) {
273
236
 
274
237
  // ── half 1: core blocks → system prompt ────────────────────────────────────
275
238
  const enabled = settings.enabled !== false
276
- const dbPath = settings.dbPath
239
+ // The in-plugin store is the single place this plugin writes and reads: prompt
240
+ // blocks, extraction, block edits, the panel and the memory tools. The old
241
+ // `dbPath` config key is kept for compatibility but no longer used anywhere.
242
+ const coreDbPath = process.env.DSH_MEMVAULT_CORE_DB || DEFAULT_CORE_DB
277
243
  const scopes = settings.scopes
278
244
  const labels = settings.labels
279
245
  const maxChars = settings.maxChars
@@ -281,21 +247,6 @@ export function apply(ctx, config = {}) {
281
247
  const contextName = settings.name
282
248
  const refreshMs = settings.refreshMs
283
249
 
284
- /**
285
- * One source for the store path, shared by this plugin's reads and by every
286
- * child process it spawns.
287
- *
288
- * Before this, the children found the store only through their cwd plus
289
- * MemVault's relative default (`data/memvault.db`), which merely happened to
290
- * point at the same file as `read.dbPath`. Changing either side silently split
291
- * the memory in two — the symptom being "I know I saved that". An explicit
292
- * `MEMVAULT_DB_PATH` in `extract.env` still wins: that is the deliberate
293
- * override, not an accident.
294
- */
295
- const childEnv = {
296
- ...(settings.extract?.env ?? {}),
297
- MEMVAULT_DB_PATH: settings.extract?.env?.MEMVAULT_DB_PATH ?? dbPath,
298
- }
299
250
 
300
251
  /**
301
252
  * Cached render + the exact blocks it was built from.
@@ -307,7 +258,7 @@ export function apply(ctx, config = {}) {
307
258
 
308
259
  /** One read: blocks, then the rendered prompt text. Throws if the store is unreadable. */
309
260
  function readNow() {
310
- const blocks = readCoreBlocks({ dbPath, scopes, labels })
261
+ const blocks = readCoreBlocks({ dbPath: coreDbPath, scopes, labels })
311
262
  return { blocks, text: formatCoreBlocks(blocks, { maxChars }) }
312
263
  }
313
264
 
@@ -331,19 +282,72 @@ export function apply(ctx, config = {}) {
331
282
  cache = { ...readNow(), at: now, error: null }
332
283
  } catch (error) {
333
284
  cache = { ...cache, at: now, error: String(error.code ?? error.message) }
334
- warnOnce('read', `cannot read ${dbPath} (${error.code ?? error.message}); serving the last known blocks, if any.`, error)
285
+ warnOnce('read', `cannot read ${coreDbPath} (${error.code ?? error.message}); serving the last known blocks, if any.`, error)
335
286
  }
336
287
  return cache.text
337
288
  }
338
289
 
290
+ /**
291
+ * The injection itself.
292
+ *
293
+ * Two switches on the contribution are load-bearing, not decoration:
294
+ *
295
+ * - `interpolate: false` — the text is **memory content**, i.e. arbitrary user
296
+ * prose and code. With interpolation on, any `{{name}}` inside a stored memory
297
+ * is resolved as a prompt variable, and an unknown or malformed one *throws*
298
+ * during `assemble()` — which fails the model request, not just the injection.
299
+ * Memory must never be able to break a turn.
300
+ * - `required: true` — a deployment that calls `suppressRuntimeContext()` (or sets
301
+ * `includeRuntimeContext: false`) drops optional context. Long-term memory is
302
+ * the reason this plugin exists, so it stays; turning injection off is this
303
+ * plugin's own `enabled` switch, which the panel reports.
304
+ */
339
305
  ctx.effect(() => ctx.systemPrompt.context({
340
306
  name: contextName,
341
307
  order,
342
308
  text: () => current(),
309
+ interpolate: false,
310
+ required: true,
343
311
  }), 'dsh-memvault: core memory context')
344
312
 
345
313
  // ── half 2: turn/end → MemVault write pipeline ─────────────────────────────
346
314
  const extract = settings.extract
315
+
316
+ // ── the in-plugin store (JS kernel) ──────────────────────────────────────
317
+ // Opened lazily so a read-only composition never creates a database file.
318
+ // Everything this plugin writes goes here; the extractor is chosen once from
319
+ // the merged environment (LLM when a key exists, deterministic rules
320
+ // otherwise, `MEMVAULT_EXTRACTOR` forcing a choice).
321
+ let core = null
322
+ const coreStore = () => {
323
+ if (core === null) core = new CoreStore(coreDbPath)
324
+ return core
325
+ }
326
+ ctx.effect(() => () => {
327
+ try {
328
+ core?.close()
329
+ } catch {
330
+ // Already closed; nothing to do.
331
+ }
332
+ core = null
333
+ }, 'dsh-memvault: core store')
334
+ // Extraction environment for this install: the process environment, then the
335
+ // config's `env` map, then the config's `timeoutMs` as `MEMVAULT_EXTRACT_TIMEOUT_MS`
336
+ // — unless either of the first two already named that variable explicitly.
337
+ const extractionEnv = { ...process.env, ...(extract.env ?? {}) }
338
+ if (extractionEnv.MEMVAULT_EXTRACT_TIMEOUT_MS === undefined && Number.isFinite(extract.timeoutMs)) {
339
+ extractionEnv.MEMVAULT_EXTRACT_TIMEOUT_MS = String(extract.timeoutMs)
340
+ }
341
+ const corePipeline = buildPipeline({
342
+ projectDir: extract.projectDir ?? '',
343
+ dbPath: coreDbPath,
344
+ env: extractionEnv,
345
+ })
346
+ const writeScope = {
347
+ userId: scopes.find((scope) => scope.type === 'user')?.id ?? null,
348
+ agentId: scopes.find((scope) => scope.type === 'agent')?.id ?? null,
349
+ runId: null,
350
+ }
347
351
  // Loaded even when extraction is off: the panel reports the history, and
348
352
  // "extraction is off" is exactly the state a reader needs to be able to see.
349
353
  const state = loadState(extract.statePath)
@@ -369,6 +373,8 @@ export function apply(ctx, config = {}) {
369
373
  // `panel.writes: false` makes the panel read-only: the write route then answers
370
374
  // 403 instead of running MemVault's CLI.
371
375
  const panelWrites = settings.panel?.writes !== false
376
+ // Replay writes through the extraction pipeline, so it needs both switches.
377
+ const canReplay = panelWrites && extract.enabled
372
378
  // Bound the persisted windows: the panel and the recovery path are the only
373
379
  // readers, and an unbounded map in one small file is a slow leak.
374
380
  const MAX_PENDING_SESSIONS = 4
@@ -404,7 +410,7 @@ let pendingStats = () => null
404
410
  enabled,
405
411
  name: contextName,
406
412
  order,
407
- dbPath,
413
+ dbPath: coreDbPath,
408
414
  scopes,
409
415
  labels,
410
416
  maxChars,
@@ -417,20 +423,23 @@ let pendingStats = () => null
417
423
  // Whether the configured store file is actually there, and how big. The panel
418
424
  // shows this at setup time: "the path exists but nothing is in it" and "the
419
425
  // path is wrong" look identical in a row count alone.
420
- dbFile: dbFileInfo(dbPath),
426
+ dbFile: dbFileInfo(coreDbPath),
421
427
  // Does the configuration actually resolve? Reported at setup time, because a
422
428
  // wrong path otherwise surfaces much later as "extraction stopped" or "my
423
429
  // memories are gone" — and both read as a bug in the memory, not the wiring.
424
430
  paths: checkPaths({
425
- pythonPath: extract.pythonPath,
426
431
  projectDir: extract.projectDir,
427
- dbPath,
432
+ dbPath: coreDbPath,
428
433
  statePath: extract.statePath,
429
434
  }),
430
435
  // How those paths were decided — and, when nothing was found, what was looked
431
436
  // at. Without this the plugin can be talking to another vault with no sign of
432
437
  // it anywhere in the UI.
433
438
  discovery: discoverySnapshot(),
439
+ // The scope extraction writes under. Derived from `scopes`, because that is
440
+ // what the rest of the plugin (and the prompt) already uses; the panel used to
441
+ // show three config keys that nothing read.
442
+ writeScope,
434
443
  writable: panelWrites,
435
444
  configIssues: { unknown: resolved.unknown, problems: resolved.problems },
436
445
  extract: {
@@ -449,16 +458,6 @@ let pendingStats = () => null
449
458
  // `webServer` is optional on purpose: a headless composition has no browser,
450
459
  // and an unavailable service must never keep the memory bridge from injecting.
451
460
  // `ctx.inject` starts a child fiber that waits for the service instead.
452
- const writeConfig = {
453
- pythonPath: extract.pythonPath,
454
- projectDir: extract.projectDir,
455
- // Same store the panel reads (see `childEnv`): the path is stated, not inferred
456
- // from a cwd plus a default that merely coincided.
457
- env: childEnv,
458
- // A block write is one small upsert — it must not inherit the 120 s budget
459
- // extraction needs for an LLM call.
460
- timeoutMs: 30_000,
461
- }
462
461
  /**
463
462
  * The one place plugin state is written.
464
463
  *
@@ -481,7 +480,7 @@ let pendingStats = () => null
481
480
  },
482
481
  writeBlock: panelWrites
483
482
  ? async (input) => {
484
- const out = await runBlockAction({ config: writeConfig, input })
483
+ const out = await runBlockActionCore({ store: coreStore(), input })
485
484
  // A write changes the store, so the next assemble must not serve a
486
485
  // render that predates it.
487
486
  if (out.ok) cache = { ...cache, at: 0 }
@@ -496,22 +495,26 @@ let pendingStats = () => null
496
495
  * or apply: false) only reports, and writing requires apply: true.
497
496
  */
498
497
  reindex: extract.enabled
499
- ? async ({ apply = false } = {}) => runReindex({
500
- pythonPath: MEMVAULT_PYTHON,
501
- projectDir: MEMVAULT_DIR,
502
- env: childEnv,
503
- apply: apply === true,
504
- })
498
+ ? async ({ apply = false } = {}) => {
499
+ const store = coreStore()
500
+ const embedder = corePipeline.embedder
501
+ const missing = store.db.prepare(
502
+ 'SELECT COUNT(*) AS n FROM memories WHERE id NOT IN (SELECT memory_id FROM memory_embeddings WHERE model = ?)',
503
+ ).get(embedder.model).n
504
+ if (!apply) return { ok: true, report: { model: embedder.model, missing, applied: false } }
505
+ const report = await backfillEmbeddings(store, embedder)
506
+ return { ok: true, report: { ...report, applied: true } }
507
+ }
505
508
  : null,
506
509
  // The structure view: which scope dimensions hold what, which blocks are
507
510
  // actually injected, and the relation graph as it stands. `scopes` comes from
508
511
  // this plugin's own config, which is the only place that knows what is
509
512
  // injected — the store cannot tell you that.
510
513
  readStructure: () => buildStructure({
511
- dbPath,
514
+ dbPath: coreDbPath,
512
515
  injectedScopes: (scopes ?? []).map((scope) => `${scope.type}/${scope.id}`),
513
516
  flags: normalizeFlags(flags),
514
- retypedCount: countRetyped({ dbPath }),
517
+ retypedCount: countRetyped({ dbPath: coreDbPath }),
515
518
  }),
516
519
  // The browse view reads the same store the prompt reads, read-only, and
517
520
  // carries the review flags — which live here, not in MemVault.
@@ -524,7 +527,7 @@ let pendingStats = () => null
524
527
  // How many rows the store's type refinement moved out of `user`. The
525
528
  // panel shows the number and can filter by it (`?retyped=1`), because a
526
529
  // heuristic that acts silently is indistinguishable from one that erred.
527
- retypedCount: countRetyped({ dbPath }),
530
+ retypedCount: countRetyped({ dbPath: coreDbPath }),
528
531
  }
529
532
  // "Only flagged" is a filter over plugin state, so it is resolved here and
530
533
  // turned into an id list the store can answer.
@@ -533,11 +536,11 @@ let pendingStats = () => null
533
536
  if (ids.length === 0) {
534
537
  return { rows: [], total: 0, limit: 0, offset: 0, order: 'created', applied: { ids: [] }, mode: 'substring', ...extra }
535
538
  }
536
- return { ...readMemories({ dbPath, query: { ...query, ids: ids.join(',') } }), ...extra }
539
+ return { ...readMemories({ dbPath: coreDbPath, query: { ...query, ids: ids.join(',') } }), ...extra }
537
540
  }
538
- return { ...readMemories({ dbPath, query }), ...extra }
541
+ return { ...readMemories({ dbPath: coreDbPath, query }), ...extra }
539
542
  },
540
- readProvenance: (id) => readMemoryProvenance({ dbPath, id }),
543
+ readProvenance: (id) => readMemoryProvenance({ dbPath: coreDbPath, id }),
541
544
  // Flagging writes this plugin's own state file: the store is untouched, so
542
545
  // the panel keeps its "it never modifies your memories" promise.
543
546
  writeFlag: panelWrites
@@ -556,8 +559,8 @@ let pendingStats = () => null
556
559
  readReview: () => {
557
560
  const flagsNow = normalizeFlags(flags)
558
561
  const ids = flaggedIds(flagsNow).slice(0, MAX_REVIEW_ITEMS)
559
- if (ids.length === 0) return { items: [], total: 0, truncated: false, request: '' }
560
- const rows = readMemories({ dbPath, query: { ids: ids.join(','), limit: MAX_REVIEW_ITEMS } })
562
+ if (ids.length === 0) return { items: [], total: 0, truncated: false, request: '', replayEnabled: canReplay }
563
+ const rows = readMemories({ dbPath: coreDbPath, query: { ids: ids.join(','), limit: MAX_REVIEW_ITEMS } })
561
564
  const byId = new Map(rows.rows.map((row) => [row.id, row]))
562
565
  const items = ids
563
566
  .map((id) => {
@@ -565,7 +568,7 @@ let pendingStats = () => null
565
568
  // A flag can outlive the memory it points at; drop those from the queue
566
569
  // (the flag map keeps them until cleared, which is not this route's job).
567
570
  if (row === undefined) return null
568
- const provenance = readMemoryProvenance({ dbPath, id })
571
+ const provenance = readMemoryProvenance({ dbPath: coreDbPath, id })
569
572
  const window = producedIndex[id] ?? null
570
573
  const replayable = window?.inputKey != null && Object.hasOwn(inputs, window.inputKey)
571
574
  return {
@@ -580,6 +583,9 @@ let pendingStats = () => null
580
583
  items,
581
584
  total: items.length,
582
585
  truncated: flaggedIds(flagsNow).length > MAX_REVIEW_ITEMS,
586
+ // Replay needs the extraction half; the panel hides the control rather than
587
+ // offering a button whose route answers 403.
588
+ replayEnabled: canReplay,
583
589
  // Ready to hand to a model: this is the plugin's half of "the model
584
590
  // proposes, the human approves".
585
591
  request: buildReviewRequest(items),
@@ -587,9 +593,13 @@ let pendingStats = () => null
587
593
  },
588
594
  /**
589
595
  * Replay a retained input — the panel's one action that writes the store, and
590
- * it does so through MemVault's own `add()`, never around it.
596
+ * it does so through the same extraction pipeline the window uses.
597
+ *
598
+ * Gated on extraction as well as on `panel.writes`: the pipeline, the retained
599
+ * inputs and the queue only exist in the extraction half, so offering replay
600
+ * with extraction off would answer a reference error instead of a reason.
591
601
  */
592
- replay: panelWrites
602
+ replay: canReplay
593
603
  ? ({ input }) => {
594
604
  const valid = validateReplay(input, { inputs, minTranscriptChars: extract.minTranscriptChars })
595
605
  if (!valid.ok) return { ok: false, status: valid.status, error: valid.error }
@@ -662,6 +672,22 @@ let pendingStats = () => null
662
672
  }), 'dsh-memvault: panel structure route')
663
673
  })
664
674
 
675
+ // ── half: memory tools on the in-plugin store (optional) ─────────────────
676
+ // Registered **before** the extraction switch below on purpose: the tools read and
677
+ // write the same store the prompt reads, and they have nothing to do with windowed
678
+ // extraction. Gating them behind `extract.enabled` (as this used to) meant that
679
+ // turning extraction off silently removed `memory_search`/`memory_add` as well —
680
+ // a read-only install lost the only way the model could look memories up.
681
+ //
682
+ // No runtime package is imported: the definitions are plain objects, and the
683
+ // store opens only when the host exposes the `tools` service (core/host.js).
684
+ // A failure here leaves block injection and extraction exactly as they were.
685
+ try {
686
+ attachMemoryTools(ctx, { logger: ctx.logger, projectDir: extract.projectDir })
687
+ } catch (error) {
688
+ warnOnce('memory-tools', 'memory tools unavailable', error)
689
+ }
690
+
665
691
  if (!extract.enabled) return
666
692
 
667
693
  /**
@@ -732,7 +758,7 @@ let pendingStats = () => null
732
758
  }
733
759
 
734
760
  if (text.replace(/\s/g, '').length < extract.minTranscriptChars) {
735
- // Too little to be worth a Python process plus an LLM call. The watermark
761
+ // Too little to be worth one embedder/extractor round trip. The watermark
736
762
  // still advances so the same turns are never re-mined.
737
763
  diagnostics.push({
738
764
  at: new Date().toISOString(),
@@ -746,8 +772,24 @@ let pendingStats = () => null
746
772
  return
747
773
  }
748
774
 
749
- const result = await runExtraction({
750
- config: { ...extract, env: { ...childEnv, ...env } },
775
+ // A replay may ask for a specific extractor. Build a pipeline for that call
776
+ // instead of silently using the one fixed at startup. The base environment is
777
+ // the same resolved one the startup pipeline used, so a replay differs only by
778
+ // what it explicitly overrides.
779
+ const overrides = env && Object.keys(env).length > 0 ? env : null
780
+ const plan = overrides
781
+ ? resolvePipeline({
782
+ projectDir: extract.projectDir ?? '',
783
+ dbPath: coreDbPath,
784
+ baseEnv: extractionEnv,
785
+ overrides,
786
+ })
787
+ : corePipeline
788
+ const result = await runCoreExtraction({
789
+ store: coreStore(),
790
+ extractor: plan.extractor,
791
+ embedder: plan.embedder,
792
+ scope: writeScope,
751
793
  messages: [{ role: 'user', content: text }],
752
794
  })
753
795
  const at = new Date().toISOString()
@@ -756,6 +798,9 @@ let pendingStats = () => null
756
798
  seq,
757
799
  turns,
758
800
  transcriptChars: text.length,
801
+ // Which extractor actually ran: "the replay said rule but the LLM answered"
802
+ // was invisible before, and that is exactly the kind of thing this table exists for.
803
+ extractor: plan.usesModel ? 'llm' : 'rule',
759
804
  outcome: result.ok ? `ok added=${result.added ?? 0}` : `failed: ${result.error}`,
760
805
  // What this window actually produced, so "was this extraction any good?" has
761
806
  // a link back to the rows instead of only a count.
@@ -859,4 +904,25 @@ let pendingStats = () => null
859
904
  })
860
905
  persistPending()
861
906
  })
907
+
908
+ /**
909
+ * A closed session takes its window with it.
910
+ *
911
+ * The idle timer only fires while the process lives, and restart recovery only
912
+ * covers what was persisted — so without this, a session archived right after its
913
+ * third turn waits for attention it will never get. `session/disposed` is the exact
914
+ * moment "this conversation is over" is known.
915
+ *
916
+ * Only windows that reached `everyNTurns` are handed over: a session closing with
917
+ * one or two turns is precisely the low-signal window the idle rule declines to
918
+ * extract, and a shutdown disposes every session at once.
919
+ */
920
+ ctx.on('session/disposed', (session) => {
921
+ const sessionId = String(session?.id ?? '')
922
+ if (sessionId === '') return
923
+ if (turnWindow.pending(sessionId) < extract.everyNTurns) return
924
+ if (turnWindow.flushNow(sessionId) > 0) {
925
+ ctx.logger?.info?.(`dsh-memvault: flushed ${sessionId.slice(-8)} when its session closed`)
926
+ }
927
+ })
862
928
  }
package/lib/panel.js CHANGED
@@ -61,7 +61,7 @@ export const MAX_BODY_BYTES = 64 * 1024
61
61
  * per-block `value_limit` is advisory), so this only clamps what the panel
62
62
  * renders and the true length travels beside it as `chars`.
63
63
  *
64
- * Not to be confused with `blocks-write.js`'s `BLOCK_VALUE_MAX`, which is the cap
64
+ * Not to be confused with `core/block-write.js`'s `BLOCK_VALUE_MAX`, which is the cap
65
65
  * on what a write may send.
66
66
  */
67
67
  export const BLOCK_VALUE_CLAMP = 2000
@@ -116,7 +116,7 @@ const clampValue = (value) => {
116
116
  */
117
117
  export function buildStatus({
118
118
  read = {}, blocks = [], extract = {}, at = new Date().toISOString(), writable = true, configIssues = {}, dbFile = {},
119
- paths = [], discovery = {},
119
+ paths = [], discovery = {}, writeScope = {},
120
120
  } = {}) {
121
121
  return {
122
122
  at,
@@ -131,9 +131,15 @@ export function buildStatus({
131
131
  source: discovery.source ?? 'none',
132
132
  found: discovery.found === true,
133
133
  projectDir: discovery.projectDir ?? '',
134
- pythonPath: discovery.pythonPath ?? '',
135
134
  candidates: Array.isArray(discovery.candidates) ? discovery.candidates : [],
136
135
  },
136
+ // Which scope extraction writes under. Derived from `scopes` by the host half;
137
+ // the panel used to display three config keys that no code path read.
138
+ writeScope: {
139
+ userId: writeScope.userId ?? null,
140
+ agentId: writeScope.agentId ?? null,
141
+ runId: writeScope.runId ?? null,
142
+ },
137
143
  // Setup-time facts the panel shows next to the configured path: whether it
138
144
  // resolves to a real file. Zero rows plus a missing file is a wrong path;
139
145
  // zero rows plus a present file is a store that simply has nothing in it.
@@ -174,10 +180,6 @@ export function buildStatus({
174
180
  maxInputChars: extract.maxInputChars ?? null,
175
181
  minTranscriptChars: extract.minTranscriptChars ?? null,
176
182
  timeoutMs: extract.timeoutMs ?? null,
177
- user: extract.user ?? null,
178
- agent: extract.agent ?? null,
179
- run: extract.run ?? null,
180
- pythonPath: extract.pythonPath ?? '',
181
183
  projectDir: extract.projectDir ?? '',
182
184
  statePath: extract.statePath ?? '',
183
185
  sessions: extract.sessions ?? 0,
@@ -467,7 +469,7 @@ export function createPanelApi({
467
469
  * Replay a retained input.
468
470
  *
469
471
  * The one panel action that writes the store — and it writes it through
470
- * MemVault's own `add()` (the CLI), so ADD/UPDATE/DELETE, the audit trail and
472
+ * the extractor's own `add()` (`core/write.js`), so ADD/UPDATE/supersede, the audit trail and
471
473
  * the relation bookkeeping all stay in one implementation. The caller supplies
472
474
  * an explicit `key`; nothing here picks a window on its own.
473
475
  */
@@ -478,7 +480,7 @@ export function createPanelApi({
478
480
  return
479
481
  }
480
482
  if (!replay) {
481
- sendJson(res, 403, { ok: false, error: 'replay is disabled (config panel.writes: false)' })
483
+ sendJson(res, 403, { ok: false, error: 'replay needs the write half (config panel.writes: true and extract.enabled: true)' })
482
484
  return
483
485
  }
484
486
  const read = await readJsonBody(req)
@@ -496,7 +498,7 @@ export function createPanelApi({
496
498
  sendJson(res, out?.status ?? 400, { ok: false, error: String(out?.error ?? 'replay failed') })
497
499
  return
498
500
  }
499
- // Queued, not awaited: an extraction is a Python process plus an LLM call,
501
+ // Queued, not awaited: an extraction is an embedding call plus a model request,
500
502
  // and the panel learns the outcome from the next status poll.
501
503
  sendJson(res, 202, { ok: true, key: out.key, extractor: out.extractor, queued: out.queued === true })
502
504
  } catch (error) {
@@ -538,7 +540,7 @@ export function createPanelApi({
538
540
  return
539
541
  }
540
542
  if (!reindex) {
541
- sendJson(res, 403, { ok: false, error: 'reindexing needs the write half (extraction is disabled)' })
543
+ sendJson(res, 403, { ok: false, error: 'reindexing needs the write half (extract.enabled: true)' })
542
544
  return
543
545
  }
544
546
  const read = await readJsonBody(req)