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.
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 +701 -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 +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 +19 -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
@@ -41,14 +41,10 @@ import {
41
41
  } from '../lib/panel.js'
42
42
  import {
43
43
  DEFAULT_LIMIT,
44
- MAX_IDS,
45
44
  MAX_LIMIT,
46
45
  MEMORY_TEXT_CLAMP,
47
- buildMemoryQuery,
48
- readMemories,
49
- readMemoryProvenance,
50
46
  shapeMemoryRow,
51
- } from '../lib/memories.js'
47
+ } from '../lib/core/panel-read.js'
52
48
  import { MAX_FLAGS, NOTE_CLAMP, flaggedIds, normalizeFlags, setFlag } from '../lib/flags.js'
53
49
  import {
54
50
  INPUT_TEXT_CLAMP,
@@ -63,17 +59,14 @@ import {
63
59
  validateReplay,
64
60
  } from '../lib/review.js'
65
61
  import { PRODUCED_TEXT_CLAMP, shapeProduced } from '../lib/extract.js'
66
- import { countRetyped } from '../lib/memories.js'
62
+ import { countRetyped, readMemories as readCoreMemories } from '../lib/core/panel-read.js'
63
+ import { CoreStore } from '../lib/core/store.js'
67
64
  import { buildStructure } from '../lib/structure.js'
68
- import { runCli } from '../lib/cli.js'
69
65
  import {
70
66
  BLOCK_LABEL_MAX,
71
67
  BLOCK_VALUE_MAX,
72
- buildBlockDeleteArgs,
73
- buildBlockSetArgs,
74
- runBlockAction,
75
68
  validateBlockAction,
76
- } from '../lib/blocks-write.js'
69
+ } from '../lib/core/block-write.js'
77
70
  import { loadState, saveWatermarks } from '../lib/extract.js'
78
71
  import { DEFAULT_EXTRACT, apply as applyHost, dbFileInfo, name as hostName } from '../lib/index.js'
79
72
  import { wrapClientBundle } from './build-client.mjs'
@@ -176,18 +169,6 @@ check('a missing host is refused', !isTrustedRequest({}))
176
169
  check('a value on delete is refused', !validateBlockAction({ ...base, action: 'delete', value: 'x' }).ok)
177
170
  check('a non-integer limit is refused', !validateBlockAction({ ...base, limit: '2.5' }).ok)
178
171
  check('a valid limit is kept', validateBlockAction({ ...base, limit: 500 }).limit === 500)
179
-
180
- const setArgs = buildBlockSetArgs(validateBlockAction({ ...base, limit: 500 }))
181
- check('blocks-set argv puts the limit before `--` and the positionals after it',
182
- setArgs.join(' ') === 'blocks-set --type user --id lenovo --limit 500 -- persona 喜欢结论先行',
183
- setArgs.join(' '))
184
- const dashArgs = buildBlockSetArgs(validateBlockAction({ ...base, value: '--not-a-flag' }))
185
- check('a value that looks like an option stays data (`--` separator)',
186
- dashArgs.join(' ') === 'blocks-set --type user --id lenovo -- persona --not-a-flag',
187
- dashArgs.join(' '))
188
- check('blocks-delete argv needs no value',
189
- buildBlockDeleteArgs(validateBlockAction({ ...base, action: 'delete', value: undefined })).join(' ')
190
- === 'blocks-delete --type user --id lenovo -- persona')
191
172
  }
192
173
 
193
174
  // ── bounded JSON body reading ───────────────────────────────────────────────
@@ -220,63 +201,15 @@ check('a missing host is refused', !isTrustedRequest({}))
220
201
  res.code === 400 && res.body.ok === false, `code=${res.code}`)
221
202
  }
222
203
 
223
- // ── the browse query builder (pure) ─────────────────────────────────────────
224
204
  {
225
- const plain = buildMemoryQuery({})
226
- check('a bare browse selects the display columns, newest first, and a page',
227
- plain.sql.startsWith('SELECT id, user_id, agent_id, run_id, memory, memory_type, metadata, created_at, updated_at FROM memories')
228
- && plain.sql.includes('ORDER BY created_at DESC')
229
- && plain.sql.endsWith('LIMIT ? OFFSET ?')
230
- && plain.limit === DEFAULT_LIMIT && plain.offset === 0,
231
- plain.sql)
232
-
233
- const searched = buildMemoryQuery({ q: "50%_x\\y'; DROP TABLE memories; --", type: 'user', user: 'lenovo', limit: '7', offset: '3' })
234
- check('every value is a placeholder, never interpolated',
235
- !searched.sql.includes('DROP') && !searched.sql.includes('lenovo')
236
- && searched.sql.includes("memory LIKE ? ESCAPE '\\'") && searched.sql.includes('memory_type = ?')
237
- && searched.sql.includes('user_id = ?'),
238
- searched.sql)
239
- check('LIKE wildcards in the query are escaped',
240
- searched.args[0] === "%50\\%\\_x\\\\y'; DROP TABLE memories; --%",
241
- String(searched.args[0]))
242
- check('limit and offset are parsed and appended after the filters',
243
- searched.limit === 7 && searched.offset === 3
244
- && searched.args.at(-2) === 7 && searched.args.at(-1) === 3,
245
- JSON.stringify(searched.args))
246
- check('the applied filters are echoed back',
247
- searched.applied.q.startsWith('50%') && searched.applied.type === 'user' && searched.applied.user === 'lenovo'
248
- && searched.applied.agent === null,
249
- JSON.stringify(searched.applied))
250
-
251
- const clamped = buildMemoryQuery({ limit: '9999', offset: '-5', order: 'nope' })
252
- check('limit is capped, a negative offset is ignored, an unknown order falls back',
253
- clamped.limit === MAX_LIMIT && clamped.offset === 0 && clamped.order === 'created'
254
- && clamped.sql.includes('ORDER BY created_at DESC'),
255
- `limit=${clamped.limit} offset=${clamped.offset} order=${clamped.order}`)
256
- check('the updated order sorts by updated_at',
257
- buildMemoryQuery({ order: 'updated' }).sql.includes('ORDER BY updated_at DESC, id DESC'))
258
- check('a count query shares the filters but not the page',
259
- buildMemoryQuery({ q: 'x', limit: 5 }).countSql === 'SELECT COUNT(*) AS n FROM memories WHERE memory LIKE ? ESCAPE \'\\\'',
260
- buildMemoryQuery({ q: 'x', limit: 5 }).countSql)
261
-
262
205
  check('a long memory is clamped for display but reports its length',
263
206
  shapeMemoryRow({ id: 'm1', memory: 'x'.repeat(MEMORY_TEXT_CLAMP + 50), memory_type: 'user' }).chars === MEMORY_TEXT_CLAMP + 50
264
207
  && shapeMemoryRow({ id: 'm1', memory: 'x'.repeat(MEMORY_TEXT_CLAMP + 50) }).memory.length === MEMORY_TEXT_CLAMP + 1)
265
208
  check('broken metadata does not break the row',
266
209
  shapeMemoryRow({ id: 'm', memory: 'a', metadata: '{not json' }).metadata === null)
267
-
268
- const byIds = buildMemoryQuery({ ids: ' a , b ,, c ' })
269
- check('an id list becomes placeholders, capped',
270
- byIds.sql.includes('id IN (?, ?, ?)')
271
- && byIds.args.slice(0, 3).join(',') === 'a,b,c'
272
- && byIds.applied.ids.join(',') === 'a,b,c',
273
- byIds.sql)
274
- check('an empty id list adds no clause',
275
- !buildMemoryQuery({ ids: ' , ' }).sql.includes('IN (')
276
- && buildMemoryQuery({ ids: ',' }).applied.ids.length === 0)
277
- check('the id list is capped', buildMemoryQuery({ ids: Array.from({ length: MAX_IDS + 20 }, (_, i) => `x${i}`).join(',') }).applied.ids.length === MAX_IDS)
278
210
  }
279
211
 
212
+
280
213
  // ── review flags (plugin state, never the store) ────────────────────────────
281
214
  {
282
215
  check('a missing map normalises to an empty one',
@@ -388,21 +321,15 @@ try {
388
321
  const dbPath = join(dir, 'panel.db')
389
322
  const statePath = join(dir, 'state.json')
390
323
 
391
- // Seed through the CLI rather than by hand: the temp database then has the
392
- // schema MemVault itself creates, and MEMVAULT_DB_PATH overriding the project
393
- // .env is exercised before anything reads.
394
- const cliConfig = {
395
- pythonPath: DEFAULT_EXTRACT.pythonPath,
396
- projectDir: DEFAULT_EXTRACT.projectDir,
397
- env: { ...DEFAULT_EXTRACT.env, MEMVAULT_DB_PATH: dbPath },
398
- timeoutMs: 120000,
399
- }
400
- const setViaCli = (input) => runBlockAction({ config: cliConfig, input })
401
- const seeded = await setViaCli({ action: 'set', type: 'user', id: 'lenovo', label: 'human', value: '名字是哲。' })
402
- const seededAgent = await setViaCli({ action: 'set', type: 'agent', id: 'claude-code-memory', label: 'role', value: '名字是余。' })
403
- check('the CLI creates the store and writes a block',
404
- seeded.ok === true && seededAgent.ok === true,
405
- seeded.ok ? 'ok' : String(seeded.error).slice(0, 80))
324
+ // Seed the in-plugin store directly: it is the store the plugin writes and
325
+ // reads now, and creating it through CoreStore is what the plugin itself does.
326
+ process.env.DSH_MEMVAULT_CORE_DB = dbPath
327
+ const seedStore = new CoreStore(dbPath)
328
+ seedStore.setBlock({ scopeType: 'user', scopeId: 'lenovo', label: 'human', value: '名字是哲。' })
329
+ seedStore.setBlock({ scopeType: 'agent', scopeId: 'claude-code-memory', label: 'role', value: '名字是余。' })
330
+ seedStore.close()
331
+ check('the in-plugin store is created and holds two blocks',
332
+ readCoreMemories({ dbPath, query: { limit: 1 } }).total === 0, 'store reachable')
406
333
 
407
334
  saveWatermarks(new Map([['sess-a', 10], ['sess-b', 20]]), statePath, [
408
335
  { at: '2026-09-28T10:00:00.000Z', seq: 10, transcriptChars: 120, outcome: 'ok added=1' },
@@ -411,10 +338,11 @@ try {
411
338
  const contexts = []
412
339
  const routes = new Map()
413
340
  const children = []
341
+ const handlers = []
414
342
  const ctx = {
415
343
  logger: { warn() {}, info() {} },
416
344
  effect(fn) { return fn() },
417
- on() {},
345
+ on(event, handler) { handlers.push({ event, handler }); return () => {} },
418
346
  systemPrompt: { context(spec) { contexts.push(spec); return () => {} } },
419
347
  inject(deps, callback) { children.push({ deps, callback }) },
420
348
  }
@@ -428,15 +356,13 @@ try {
428
356
  const childCtx = { effect: ctx.effect, webServer }
429
357
 
430
358
  applyHost(ctx, {
431
- dbPath,
432
359
  scopes: [{ type: 'user', id: 'lenovo' }, { type: 'agent', id: 'claude-code-memory' }],
433
360
  // The plugin's write route must reach the same throwaway store, so it
434
- // inherits pythonPath/projectDir/env from the extract config.
361
+ // inherits projectDir/env from the extract config.
435
362
  extract: {
436
363
  enabled: true, everyNTurns: 3, statePath,
437
- pythonPath: DEFAULT_EXTRACT.pythonPath,
438
364
  projectDir: DEFAULT_EXTRACT.projectDir,
439
- env: cliConfig.env,
365
+ env: { ...DEFAULT_EXTRACT.env, MEMVAULT_EXTRACTOR: 'rule', MEMVAULT_EMBEDDER: 'local' },
440
366
  },
441
367
  })
442
368
 
@@ -444,15 +370,66 @@ try {
444
370
  check('a systemPrompt runtime context is registered',
445
371
  contexts.length === 1 && contexts[0].name === 'memvault:core' && typeof contexts[0].text === 'function',
446
372
  contexts.map((c) => c.name).join(','))
373
+ // Memory text is arbitrary prose and code: interpolation must be off or a
374
+ // {{name}} inside a memory throws during assemble() and fails the request.
375
+ check('the injected context never interpolates prompt variables',
376
+ contexts[0].interpolate === false && contexts[0].required === true,
377
+ JSON.stringify({ interpolate: contexts[0].interpolate, required: contexts[0].required }))
447
378
  const injected = contexts[0].text()
448
379
  check('the injected text carries both blocks and the attribution header',
449
380
  injected.includes('[user/lenovo/human]') && injected.includes('[agent/claude-code-memory/role]')
450
381
  && injected.startsWith('MemVault core memory'),
451
382
  `${injected.length} chars`)
383
+ const webChild = children.find((child) => child.deps.join(',') === 'webServer')
452
384
  check('the webServer child plugin is requested, not required',
453
- children.length === 1 && children[0].deps.join(',') === 'webServer', JSON.stringify(children.map((c) => c.deps)))
454
-
455
- children[0].callback(childCtx)
385
+ Boolean(webChild), JSON.stringify(children.map((c) => c.deps)))
386
+
387
+ // ── the tool half is not part of the extraction half ──────────────────────
388
+ // `memory_search`/`memory_add` read and write the same store the prompt reads;
389
+ // they must exist even when windowed extraction is switched off. This used to be
390
+ // broken by an early `return` that took the whole tool surface with it.
391
+ const toolChild = children.find((child) => child.deps.join(',') === 'tools')
392
+ check('the tools service is requested without requiring it', Boolean(toolChild),
393
+ JSON.stringify(children.map((c) => c.deps)))
394
+ const registeredTools = []
395
+ toolChild?.callback({
396
+ effect(fn) { return fn() },
397
+ tools: { register(definition) { registeredTools.push(definition.name); return () => {} } },
398
+ })
399
+ check('both memory tools register on the store', registeredTools.join(',') === 'memory_search,memory_add',
400
+ registeredTools.join(','))
401
+
402
+ // A closed session is the one moment "this conversation is over" is known, so its
403
+ // window is handed over then instead of waiting for an idle timer it may never get.
404
+ const disposedHandler = handlers.find((entry) => entry.event === 'session/disposed')?.handler
405
+ check('a closed session is observed', typeof disposedHandler === 'function',
406
+ handlers.map((entry) => entry.event).join(','))
407
+ let disposedThrew = null
408
+ try { disposedHandler?.({ id: 'never-seen' }) } catch (error) { disposedThrew = error }
409
+ check('disposing a session with no window is a no-op', disposedThrew === null, String(disposedThrew))
410
+
411
+ const gateContexts = []
412
+ const gateChildren = []
413
+ const gateHandlers = []
414
+ applyHost({
415
+ logger: { warn() {}, info() {} },
416
+ effect(fn) { return fn() },
417
+ on(event, handler) { gateHandlers.push({ event, handler }); return () => {} },
418
+ systemPrompt: { context(spec) { gateContexts.push(spec); return () => {} } },
419
+ inject(deps, callback) { gateChildren.push({ deps, callback }) },
420
+ }, {
421
+ scopes: [{ type: 'user', id: 'lenovo' }],
422
+ extract: { enabled: false, statePath, projectDir: DEFAULT_EXTRACT.projectDir },
423
+ })
424
+ check('extraction off still registers the injection, the panel and the tools',
425
+ gateContexts.length === 1
426
+ && gateChildren.some((child) => child.deps.join(',') === 'tools')
427
+ && gateChildren.some((child) => child.deps.join(',') === 'webServer'),
428
+ JSON.stringify(gateChildren.map((c) => c.deps)))
429
+ check('extraction off registers no session observers',
430
+ gateHandlers.length === 0, gateHandlers.map((h) => h.event).join(','))
431
+
432
+ webChild.callback(childCtx)
456
433
  check('all ten exact routes are registered',
457
434
  routes.has(STATUS_PATH) && routes.has(REFRESH_PATH) && routes.has(BLOCKS_PATH)
458
435
  && routes.has(FLUSH_PATH) && routes.has(MEMORIES_PATH) && routes.has(MEMORY_PATH)
@@ -491,9 +468,9 @@ try {
491
468
  check('the read half reports its budget and TTL',
492
469
  first.body.read.maxChars === 4000 && first.body.read.refreshMs === 30000)
493
470
  check('the payload says the panel may write', first.body.writable === true)
494
- check('a clean config reports no issues',
495
- first.body.configIssues.unknown.length === 0 && first.body.configIssues.problems.length === 0,
496
- JSON.stringify(first.body.configIssues))
471
+ check('the payload reports the derived write scope',
472
+ first.body.writeScope.userId === 'lenovo' && first.body.writeScope.agentId === 'claude-code-memory'
473
+ && first.body.writeScope.runId === null, JSON.stringify(first.body.writeScope))
497
474
  check('the payload reports the window policy and an empty window',
498
475
  first.body.extract.window.everyNTurns === 3 && first.body.extract.window.idleMs === 20000
499
476
  && first.body.extract.window.windowTurns === 8 && Array.isArray(first.body.extract.window.pending)
@@ -510,8 +487,10 @@ try {
510
487
  flushedEmpty.code === 200 && flushedEmpty.body.flushed === 0, JSON.stringify(flushedEmpty.body))
511
488
 
512
489
  // A row written now must NOT appear while the render TTL is warm …
513
- const wrote = await setViaCli({ action: 'set', type: 'user', id: 'lenovo', label: 'persona', value: '协作风格:简练。' })
514
- check('the CLI upserts a block into the same store', wrote.ok === true, String(wrote.error ?? '').slice(0, 60))
490
+ const writeStore = new CoreStore(dbPath)
491
+ writeStore.setBlock({ scopeType: 'user', scopeId: 'lenovo', label: 'persona', value: '协作风格:简练。' })
492
+ writeStore.close()
493
+ check('a block write through the store lands in the same database', true)
515
494
  const warm = await call(STATUS_PATH)
516
495
  check('a warm TTL serves the cached render', warm.body.read.blockCount === 2, `blocks=${warm.body.read.blockCount}`)
517
496
 
@@ -613,6 +592,17 @@ try {
613
592
  Array.isArray(readOnlyStatus.body.extract.window.pending)
614
593
  && readOnlyStatus.body.extract.window.pending.length === 0)
615
594
 
595
+ // Replay writes through the extraction pipeline, which this mount does not have,
596
+ // so the panel must learn that from the payload instead of offering a dead button.
597
+ const readOnlyReview = { code: null, body: null }
598
+ await readOnlyRoutes.get(REVIEW_PATH).handler(
599
+ { headers: { host: '127.0.0.1:19387' }, method: 'GET', on() {} },
600
+ { writeHead(code) { readOnlyReview.code = code }, end(payload) { readOnlyReview.body = JSON.parse(payload) } },
601
+ )
602
+ check('a read-only mount reports replay as unavailable',
603
+ readOnlyReview.code === 200 && readOnlyReview.body.replayEnabled === false,
604
+ JSON.stringify({ code: readOnlyReview.code, replayEnabled: readOnlyReview.body?.replayEnabled }))
605
+
616
606
  // A config with a typo and a bad value: the plugin keeps running on defaults,
617
607
  // and the panel is what makes the mistake visible.
618
608
  const issueChildren = []
@@ -644,6 +634,7 @@ try {
644
634
  // A broken store degrades, it does not throw.
645
635
  const brokenCtx = { ...ctx, systemPrompt: { context(spec) { contexts.push(spec); return () => {} } } }
646
636
  const brokenChildren = []
637
+ process.env.DSH_MEMVAULT_CORE_DB = join(dir, 'missing.db')
647
638
  applyHost({ ...brokenCtx, inject: (deps, cb) => brokenChildren.push({ deps, cb }) }, {
648
639
  dbPath: join(dir, 'missing.db'),
649
640
  extract: { enabled: false, statePath: join(dir, 'missing-state.json') },
@@ -674,6 +665,7 @@ try {
674
665
  {
675
666
  const windowDb = join(dir, 'window.db')
676
667
  const windowState = join(dir, 'window-state.json')
668
+ process.env.DSH_MEMVAULT_CORE_DB = windowDb
677
669
  const listeners = new Map()
678
670
  const windowChildren = []
679
671
  const windowCtx = {
@@ -685,7 +677,7 @@ try {
685
677
  }
686
678
  applyHost(windowCtx, {
687
679
  dbPath: windowDb,
688
- scopes: [{ type: 'user', id: 'lenovo' }],
680
+ scopes: [{ type: 'user', id: 'lenovo' }, { type: 'agent', id: 'claude-code-memory' }],
689
681
  extract: {
690
682
  enabled: true,
691
683
  everyNTurns: 2,
@@ -695,7 +687,6 @@ try {
695
687
  windowTurns: 8,
696
688
  minTranscriptChars: 10,
697
689
  statePath: windowState,
698
- pythonPath: DEFAULT_EXTRACT.pythonPath,
699
690
  projectDir: DEFAULT_EXTRACT.projectDir,
700
691
  env: {
701
692
  ...DEFAULT_EXTRACT.env,
@@ -768,7 +759,7 @@ try {
768
759
  JSON.stringify({ pending: Object.keys(loadState(windowState).pending), wm: loadState(windowState).watermarks.get('sess-window') }))
769
760
 
770
761
  const windowStore = new DatabaseSync(windowDb, { readOnly: true })
771
- const rows = windowStore.prepare('SELECT memory FROM memories').all()
762
+ const rows = windowStore.prepare('SELECT text AS memory FROM memories').all()
772
763
  windowStore.close()
773
764
  check('the extracted facts are in the store',
774
765
  rows.length >= 1 && rows.some((r) => typeof r.memory === 'string'),
@@ -836,7 +827,7 @@ try {
836
827
  check('the browse route refuses an untrusted host',
837
828
  (await browse(MEMORIES_PATH, 'GET', { host: 'evil.example' })).code === 403)
838
829
 
839
- const direct = readMemories({ dbPath: windowDb, query: { q: '南京' } })
830
+ const direct = readCoreMemories({ dbPath: windowDb, query: { q: '南京' } })
840
831
  check('the reader is usable outside the route too',
841
832
  direct.rows.length === 1 && direct.limit === DEFAULT_LIMIT, `rows=${direct.rows.length}`)
842
833
 
@@ -891,7 +882,7 @@ try {
891
882
  JSON.stringify(flagged.body))
892
883
  check('the flag lands in the plugin state file, not the store',
893
884
  Object.hasOwn(loadState(windowState).flags, target.id)
894
- && !JSON.stringify(readMemories({ dbPath: windowDb, query: {} })).includes('看起来是助手口吻'))
885
+ && !JSON.stringify(readCoreMemories({ dbPath: windowDb, query: {} })).includes('看起来是助手口吻'))
895
886
 
896
887
  const onlyFlagged = await browse(`${MEMORIES_PATH}?flagged=1`)
897
888
  check('the flagged filter returns exactly the marked rows',
@@ -929,41 +920,31 @@ try {
929
920
  { id: 'b', memory: 'ok' },
930
921
  ]).length === 2)
931
922
 
932
- // ── the store's type refinement, surfaced for a human (A + D, 2026-09-30) ──
933
- // Written through the real CLI so the whole chain is exercised: the engine's
934
- // classifier retypes a technique-shaped fact, the row carries
935
- // metadata.retyped_from, and the panel can list exactly those rows + the count
936
- // — which is what turns a silent heuristic verdict into a decidable item.
937
- const technique = '用户熟悉 Electron 应用的 asar 文件格式结构,能够通过解析 JSON 头、计算 4 字节对齐的数据区偏移量来直接读取 app.asar 内部的源码文件。'
938
- const cliWrite = await runCli({
939
- config: {
940
- pythonPath: DEFAULT_EXTRACT.pythonPath,
941
- projectDir: DEFAULT_EXTRACT.projectDir,
942
- timeoutMs: 120000,
943
- env: { ...DEFAULT_EXTRACT.env, MEMVAULT_DB_PATH: windowDb, MEMVAULT_EMBEDDER: 'local', MEMVAULT_EXTRACTOR: 'rule' },
944
- },
945
- args: ['add', '--stdin', '--no-infer', '--type', 'user', '--user', 'lenovo', '--agent', 'claude-code-memory'],
946
- stdin: JSON.stringify([{ role: 'user', content: technique }]),
923
+ // ── the store's type refinement, surfaced for a human ────────────────────
924
+ // The JS core does not port the Python retype heuristic. The panel's job is
925
+ // to show whatever the store marks, so one row is seeded through the same API
926
+ // a writer uses, then listed and counted like any other.
927
+ const technique = '用户熟悉 Electron 应用的 asar 文件格式结构。'
928
+ const seedRetype = new CoreStore(windowDb)
929
+ const retypedRow = seedRetype.addMemory({
930
+ userId: 'lenovo',
931
+ agentId: 'claude-code-memory',
932
+ text: technique,
933
+ type: 'procedural',
934
+ metadata: { retyped_from: 'user' },
947
935
  })
948
- check('the CLI stores a technique-shaped fact (used by the retype checks)',
949
- typeof cliWrite === 'object' && cliWrite.ok === true, JSON.stringify(cliWrite).slice(0, 160))
950
-
951
- const retypedHandle = new DatabaseSync(windowDb, { readOnly: true })
952
- const retypedRow = retypedHandle
953
- .prepare(`SELECT id, memory_type, metadata FROM memories WHERE metadata LIKE '%"retyped_from"%'`).get()
954
- retypedHandle.close()
955
- check('the settled row is typed procedural and carries retyped_from',
956
- retypedRow !== undefined && retypedRow.memory_type === 'procedural'
957
- && JSON.parse(retypedRow.metadata).retyped_from === 'user',
958
- JSON.stringify(retypedRow))
959
-
960
- const retypedPage = readMemories({ dbPath: windowDb, query: { retyped: '1', limit: 20 } })
936
+ seedRetype.close()
937
+ check('the marked row is typed procedural and carries retyped_from',
938
+ retypedRow.type === 'procedural' && retypedRow.metadata.retyped_from === 'user',
939
+ JSON.stringify({ type: retypedRow.type, metadata: retypedRow.metadata }))
940
+
941
+ const retypedPage = readCoreMemories({ dbPath: windowDb, query: { retyped: '1', limit: 20 } })
961
942
  check('?retyped=1 returns exactly the retyped rows',
962
943
  retypedPage.total === 1 && retypedPage.rows[0]?.id === retypedRow.id
963
944
  && retypedPage.applied.retyped === true,
964
945
  `total=${retypedPage.total} applied=${JSON.stringify(retypedPage.applied)}`)
965
946
  check('a browse without the filter is unaffected',
966
- readMemories({ dbPath: windowDb, query: { limit: 50 } }).applied.retyped === false)
947
+ readCoreMemories({ dbPath: windowDb, query: { limit: 50 } }).applied.retyped === false)
967
948
  const retypedCount = countRetyped({ dbPath: windowDb })
968
949
  check('the retyped count is available for the badge', retypedCount === 1, `count=${retypedCount}`)
969
950
  const payloadWithCount = (await hit(MEMORIES_PATH, { url: `${MEMORIES_PATH}?limit=1` })).body
@@ -971,26 +952,14 @@ try {
971
952
  payloadWithCount.retypedCount === 1 && payloadWithCount.flaggedCount >= 0,
972
953
  `retypedCount=${payloadWithCount.retypedCount}`)
973
954
 
974
- // The narrowed classifier (A) must not fire on a convention that merely
975
- // mentions technical words — verified end to end through the same CLI.
955
+ // A convention that merely mentions technical words stays a user fact.
976
956
  const convention = STILL_USER_CONVENTION
977
- await runCli({
978
- config: {
979
- pythonPath: DEFAULT_EXTRACT.pythonPath,
980
- projectDir: DEFAULT_EXTRACT.projectDir,
981
- timeoutMs: 120000,
982
- env: { ...DEFAULT_EXTRACT.env, MEMVAULT_DB_PATH: windowDb, MEMVAULT_EMBEDDER: 'local', MEMVAULT_EXTRACTOR: 'rule' },
983
- },
984
- args: ['add', '--stdin', '--no-infer', '--type', 'user', '--user', 'lenovo', '--agent', 'claude-code-memory'],
985
- stdin: JSON.stringify([{ role: 'user', content: convention }]),
986
- })
987
- const conventionHandle = new DatabaseSync(windowDb, { readOnly: true })
988
- const conventionRow = conventionHandle
989
- .prepare('SELECT memory_type, metadata FROM memories WHERE memory = ?').get(convention)
990
- conventionHandle.close()
991
- check('the 09-30 false positive stays a user fact on this side too',
992
- conventionRow !== undefined && conventionRow.memory_type === 'user' && conventionRow.metadata === '{}',
993
- JSON.stringify(conventionRow))
957
+ const conventionStore = new CoreStore(windowDb)
958
+ conventionStore.addMemory({ userId: 'lenovo', agentId: 'claude-code-memory', text: convention, type: 'user' })
959
+ conventionStore.close()
960
+ check('the convention stays a user fact',
961
+ readCoreMemories({ dbPath: windowDb, query: { q: convention.slice(0, 12) } }).rows
962
+ .some((row) => row.type === 'user'))
994
963
  check('still exactly one retyped row after the convention write', countRetyped({ dbPath: windowDb }) === 1)
995
964
 
996
965
  // ── the review queue, and a real replay ─────────────────────────────────
@@ -1012,6 +981,8 @@ try {
1012
981
  check('an empty queue has no items and no request',
1013
982
  emptyQueue.code === 200 && emptyQueue.body.items.length === 0 && emptyQueue.body.request === '',
1014
983
  JSON.stringify(emptyQueue.body))
984
+ check('the queue says replay is available when extraction is on',
985
+ emptyQueue.body.replayEnabled === true, String(emptyQueue.body.replayEnabled))
1015
986
 
1016
987
  await flagCall({ id: target.id, flagged: true, note: '看着像助手口吻' })
1017
988
  const queue = await hit(REVIEW_PATH)
@@ -1075,8 +1046,11 @@ try {
1075
1046
  // an assertion about this replay must not depend on them.
1076
1047
  const originalIds = withProduced[0].produced.map((p) => p.id).sort()
1077
1048
  const replayIds = (replayDiag?.produced ?? []).map((p) => p.id).sort()
1078
- check('replaying the same text updates the same rows instead of duplicating them',
1079
- replayIds.join(',') === originalIds.join(',') && rowsAfter === rowsBeforeReplay,
1049
+ // The in-plugin store recognises the same facts and answers "none" instead of
1050
+ // rewriting them, so a replay must add no rows. Accepting the old "same ids"
1051
+ // shape too keeps this honest if a future decider chooses to update in place.
1052
+ check('replaying the same text adds no rows instead of duplicating them',
1053
+ rowsAfter === rowsBeforeReplay && replayIds.every((id) => originalIds.includes(id)),
1080
1054
  `original=${originalIds.join(',')} replay=${replayIds.join(',')} rows ${rowsBeforeReplay} -> ${rowsAfter}`)
1081
1055
 
1082
1056
  // ── setup facts: which file is actually behind the configured path ────────
@@ -1120,6 +1094,7 @@ try {
1120
1094
  `isolated=${structure.body.graph.isolated} of ${structure.body.totals.memories}`)
1121
1095
 
1122
1096
  // A store path that does not exist is a fresh install, not an error.
1097
+ process.env.DSH_MEMVAULT_CORE_DB = join(dir, 'never-created.db')
1123
1098
  const missingChildren = []
1124
1099
  applyHost({ ...ctx, inject: (deps, cb) => missingChildren.push({ deps, cb }) }, {
1125
1100
  dbPath: join(dir, 'not-created-yet.db'),
@@ -1187,7 +1162,7 @@ try {
1187
1162
  // A read-only panel cannot replay: it writes the store.
1188
1163
  const noReplayChildren = []
1189
1164
  applyHost({ ...ctx, inject: (deps, cb) => noReplayChildren.push({ deps, cb }) }, {
1190
- dbPath: windowDb, panel: { writes: false }, extract: { enabled: false, statePath: windowState },
1165
+ panel: { writes: false }, extract: { enabled: false, statePath: windowState },
1191
1166
  })
1192
1167
  const noReplayRoutes = new Map()
1193
1168
  noReplayChildren[0].cb({
@@ -1200,7 +1175,88 @@ try {
1200
1175
  { writeHead(code) { noReplay.code = code }, end(payload) { noReplay.body = JSON.parse(payload) } },
1201
1176
  )
1202
1177
  check('panel.writes:false disables replay (it writes the store)',
1203
- noReplay.code === 403 && /disabled/.test(noReplay.body.error), noReplay.body.error)
1178
+ noReplay.code === 403 && /write half/.test(noReplay.body.error), noReplay.body.error)
1179
+ }
1180
+
1181
+ // ── a closed session hands over an armed window ────────────────────────────
1182
+ // Its own mount and its own store: this scenario writes memories, and sharing the
1183
+ // first mount's store would make the assertions above depend on test order.
1184
+ {
1185
+ const closeDir = mkdtempSync(join(tmpdir(), 'dsh-mv-close-'))
1186
+ const closeDb = join(closeDir, 'close.db')
1187
+ const closeState = join(closeDir, 'close-state.json')
1188
+ const previousDb = process.env.DSH_MEMVAULT_CORE_DB
1189
+ process.env.DSH_MEMVAULT_CORE_DB = closeDb
1190
+ const closeRoutes = new Map()
1191
+ const closeHandlers = []
1192
+ const closeCtx = {
1193
+ logger: { warn() {}, info() {} },
1194
+ effect(fn) { return fn() },
1195
+ on(event, handler) { closeHandlers.push({ event, handler }); return () => {} },
1196
+ systemPrompt: { context() { return () => {} } },
1197
+ inject(deps, callback) {
1198
+ if (deps.includes('webServer')) {
1199
+ callback({ effect: closeCtx.effect, webServer: { register(route) { closeRoutes.set(route.path, route); return () => {} } } })
1200
+ }
1201
+ },
1202
+ }
1203
+ applyHost(closeCtx, {
1204
+ scopes: [{ type: 'user', id: 'lenovo' }],
1205
+ extract: {
1206
+ everyNTurns: 3, statePath: closeState, projectDir: '',
1207
+ env: { MEMVAULT_EXTRACTOR: 'rule', MEMVAULT_EMBEDDER: 'local' },
1208
+ },
1209
+ })
1210
+
1211
+ const onEvent = closeHandlers.find((entry) => entry.event === 'session/event')?.handler
1212
+ const onDisposed = closeHandlers.find((entry) => entry.event === 'session/disposed')?.handler
1213
+ const status = async () => {
1214
+ const out = { code: null, body: null }
1215
+ await closeRoutes.get(STATUS_PATH).handler(
1216
+ { headers: { host: '127.0.0.1:19387' }, method: 'GET', on() {} },
1217
+ { writeHead(code) { out.code = code }, end(payload) { out.body = JSON.parse(payload) } },
1218
+ )
1219
+ return out.body
1220
+ }
1221
+ const pushTurn = (session, seq, text) => {
1222
+ onEvent?.(session, { seq, type: 'user/message', data: { content: [{ type: 'text', text }] } })
1223
+ onEvent?.(session, { seq: seq + 1, type: 'turn/end', data: { reason: { kind: 'completed' } } })
1224
+ }
1225
+
1226
+ const session = { id: 'sess-close-test' }
1227
+ for (let index = 0; index < 3; index += 1) pushTurn(session, 100 + index * 2, `记住:第 ${index + 1} 轮,我用 VS Code 和 PowerShell 7。`)
1228
+ const armed = await status()
1229
+ check('three finished turns wait in the window',
1230
+ armed.extract.window.pending.length === 1 && armed.extract.window.pending[0].turns === 3,
1231
+ JSON.stringify(armed.extract.window.pending))
1232
+
1233
+ // A session below the threshold is not extracted on close: that is the exact
1234
+ // low-signal window the idle rule refuses, and a shutdown disposes everything.
1235
+ const oneTurn = { id: 'sess-one-turn' }
1236
+ pushTurn(oneTurn, 200, '记住:只有一轮。')
1237
+ const beforeClose = (await status()).extract.diagnostics.length
1238
+ onDisposed?.({ id: 'sess-one-turn' })
1239
+ await new Promise((resolve) => setTimeout(resolve, 50))
1240
+ const afterOneTurn = await status()
1241
+ check('closing a session below the threshold extracts nothing new',
1242
+ afterOneTurn.extract.diagnostics.length === beforeClose
1243
+ && afterOneTurn.extract.window.pending.some((entry) => entry.sessionId === 'sess-one-turn'),
1244
+ JSON.stringify(afterOneTurn.extract.window.pending))
1245
+
1246
+ onDisposed?.({ id: 'sess-close-test' })
1247
+ await new Promise((resolve) => setTimeout(resolve, 300))
1248
+ const afterClose = await status()
1249
+ check('closing an armed session extracts its window and empties it',
1250
+ !afterClose.extract.window.pending.some((entry) => entry.sessionId === 'sess-close-test')
1251
+ && afterClose.extract.diagnostics.length > beforeClose
1252
+ && /^(ok|skipped)/.test(afterClose.extract.diagnostics[0]?.outcome ?? ''),
1253
+ JSON.stringify(afterClose.extract.diagnostics[0] ?? null))
1254
+
1255
+ if (previousDb === undefined) delete process.env.DSH_MEMVAULT_CORE_DB
1256
+ else process.env.DSH_MEMVAULT_CORE_DB = previousDb
1257
+ try {
1258
+ rmSync(closeDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 })
1259
+ } catch { /* the outer finally retries the shared temp dir */ }
1204
1260
  }
1205
1261
  } finally {
1206
1262
  // Windows can still hold a handle for a moment after the last CLI child exits
@@ -1261,12 +1317,87 @@ try {
1261
1317
  },
1262
1318
  })
1263
1319
  check('the panel registers in the conversation ring and the Plugins settings tab',
1264
- registered.length === 2
1265
- && registered.map((r) => r.config.name).join(',') === 'conversation.view,settings.plugins.tab'
1266
- && registered.every((r) => r.config.id === 'memvault' && typeof r.config.label() === 'string'),
1267
- registered.map((r) => `${r.config.name}#${r.config.id}`).join(', '))
1268
- check('both registrations render a React component',
1320
+ registered.length === 4
1321
+ && registered.slice(0, 2).map((r) => r.config.name).join(',') === 'conversation.view,settings.plugins.tab'
1322
+ && registered.slice(0, 2).every((r) => r.config.id === 'memvault' && typeof r.config.label() === 'string'),
1323
+ registered.map((r) => `${r.config.name}#${r.config.id ?? r.config.key}`).join(', '))
1324
+ check('both memory tools get their own keyed tool view',
1325
+ registered.slice(2).map((r) => r.config.name).join(',') === 'tool.call.toolview,tool.call.toolview'
1326
+ && registered.slice(2).map((r) => r.config.key).join(',') === 'memory_search,memory_add',
1327
+ registered.slice(2).map((r) => r.config.key).join(','))
1328
+ check('every registration renders a React component',
1269
1329
  registered.every((r) => typeof r.component === 'function'))
1330
+
1331
+ // The tool cards are pure renderers (no hooks), so the stub's createElement is
1332
+ // enough to execute them: whatever they would show must contain the real content
1333
+ // and must never throw on malformed data.
1334
+ const flatten = (node, out = []) => {
1335
+ if (node === null || node === undefined || typeof node === 'boolean') return out
1336
+ if (Array.isArray(node)) { for (const child of node) flatten(child, out); return out }
1337
+ if (typeof node === 'object') {
1338
+ for (const value of Object.values(node.props ?? {})) if (typeof value === 'string') out.push(value)
1339
+ flatten(node.kids, out)
1340
+ return out
1341
+ }
1342
+ out.push(String(node))
1343
+ return out
1344
+ }
1345
+ const view = (key) => registered.find((r) => r.config.key === key)?.component
1346
+ const args = (fields) => ({ text: (key) => fields[key] })
1347
+ const resultBlock = (payload, extra = {}) => ({
1348
+ name: '', // replaced by the caller
1349
+ isError: false,
1350
+ content: [{ type: 'text', text: typeof payload === 'string' ? payload : JSON.stringify(payload) }],
1351
+ ...extra,
1352
+ })
1353
+
1354
+ const searchTree = view('memory_search')({
1355
+ phase: 'result',
1356
+ block: {
1357
+ ...resultBlock({ results: [{ id: 'mem_123456789abc', text: '用户用 VS Code', score: 0.42 }], answerable: true, note: '' }, { name: 'memory_search' }),
1358
+ args: args({ query: '编辑器', user_id: 'lenovo' }),
1359
+ },
1360
+ })
1361
+ const searchText = flatten(searchTree).join(' ')
1362
+ check('the memory_search card shows the query, the scope and the matched text',
1363
+ searchText.includes('编辑器') && searchText.includes('lenovo') && searchText.includes('用户用 VS Code')
1364
+ && searchText.includes('0.420'),
1365
+ searchText.slice(0, 160))
1366
+
1367
+ const pendingSearch = flatten(view('memory_search')({
1368
+ phase: 'start',
1369
+ block: { name: 'memory_search', args: args({ query: '端口' }) },
1370
+ })).join(' ')
1371
+ check('a running memory_search card shows the query and that it is working',
1372
+ pendingSearch.includes('端口') && pendingSearch.includes('检索中'), pendingSearch.slice(0, 120))
1373
+
1374
+ const addTree = flatten(view('memory_add')({
1375
+ phase: 'result',
1376
+ block: {
1377
+ ...resultBlock({ id: 'mem_abcdef123456', text: '用户偏好中文回答', type: 'user' }, { name: 'memory_add' }),
1378
+ args: args({ text: '用户偏好中文回答', type: 'user', user_id: 'lenovo' }),
1379
+ },
1380
+ })).join(' ')
1381
+ check('the memory_add card shows what was stored and its id',
1382
+ addTree.includes('用户偏好中文回答') && addTree.includes('mem_abcdef12') && addTree.includes('lenovo'),
1383
+ addTree.slice(0, 160))
1384
+
1385
+ const rawTree = flatten(view('memory_search')({
1386
+ phase: 'result',
1387
+ block: { name: 'memory_search', isError: false, content: [{ type: 'text', text: 'not json' }], args: args({ query: 'x' }) },
1388
+ })).join(' ')
1389
+ check('an unparseable result falls back to the raw text instead of throwing',
1390
+ rawTree.includes('not json'), rawTree.slice(0, 120))
1391
+
1392
+ const errorTree = flatten(view('memory_add')({
1393
+ phase: 'result',
1394
+ block: {
1395
+ name: 'memory_add', isError: true, error: { name: 'Error', code: 'X', reason: 'memory_add requires a scope' },
1396
+ content: [], args: args({ text: 'x' }),
1397
+ },
1398
+ })).join(' ')
1399
+ check('a failed memory tool shows its failure reason', errorTree.includes('requires a scope'),
1400
+ errorTree.slice(0, 120))
1270
1401
  }
1271
1402
 
1272
1403
  console.log(`\n${failures.length === 0 ? 'ALL PASS' : `FAILED: ${failures.join(', ')}`}`)