dsh-memvault 0.9.12 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +52 -397
  2. package/README.zh.md +51 -325
  3. package/cordis.patch.yml +18 -20
  4. package/docs/CORE-DESIGN.md +277 -0
  5. package/docs/DETAIL.md +1 -0
  6. package/docs/DETAIL.zh.md +1 -0
  7. package/docs/DEVLOG.md +752 -0
  8. package/docs/images/relation-graph-2026-11-02.png +0 -0
  9. package/docs/preview.svg +41 -0
  10. package/icon.svg +9 -0
  11. package/lib/blocks.js +11 -2
  12. package/lib/client.js +705 -168
  13. package/lib/config.js +46 -87
  14. package/lib/core/adjudicate.js +94 -0
  15. package/lib/core/backfill.js +32 -0
  16. package/lib/core/block-write.js +85 -0
  17. package/lib/core/decide.js +159 -0
  18. package/lib/core/embed.js +122 -0
  19. package/lib/core/env.js +72 -0
  20. package/lib/core/extract.js +151 -0
  21. package/lib/core/host.js +81 -0
  22. package/lib/core/importers.js +261 -0
  23. package/lib/core/llm.js +49 -0
  24. package/lib/{memories.js → core/panel-read.js} +80 -136
  25. package/lib/core/pipeline.js +95 -0
  26. package/lib/core/schema.js +123 -0
  27. package/lib/core/search.js +191 -0
  28. package/lib/core/store.js +347 -0
  29. package/lib/core/tools.js +182 -0
  30. package/lib/core/write.js +89 -0
  31. package/lib/extract.js +1 -39
  32. package/lib/index.js +194 -128
  33. package/lib/panel.js +13 -11
  34. package/lib/review.js +5 -1
  35. package/lib/structure.js +6 -1
  36. package/locale/en.json +7 -0
  37. package/locale/zh.json +7 -0
  38. package/package.json +11 -8
  39. package/scripts/backfill-core.mjs +53 -0
  40. package/scripts/import-core.mjs +56 -0
  41. package/scripts/smoke-config.mjs +12 -14
  42. package/scripts/smoke-extract.mjs +19 -40
  43. package/scripts/smoke-package.mjs +105 -27
  44. package/scripts/smoke-panel.mjs +293 -162
  45. package/src/client/index.js +703 -166
  46. package/lib/blocks-write.js +0 -121
  47. package/lib/cli.js +0 -90
  48. package/lib/reindex.js +0 -32
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `memory_search` / `memory_add` as Host tools.
3
+ *
4
+ * The definitions are built as plain objects instead of importing
5
+ * `@deepseek-ai/dsh-tools`: the registry only requires
6
+ * `output: { schema, render }` and JSON-Schema `parameters` (read from the
7
+ * installed 0.2.1-rc.5 implementation), so building them here keeps the
8
+ * plugin's "no runtime dependencies" promise — and keeps this module loadable
9
+ * by the plain-Node smoke tests.
10
+ *
11
+ * Parameters are JSON Schema, not the authoring DSL: `required` is an array on
12
+ * the object, every object declares `additionalProperties` explicitly, and only
13
+ * the types the runtime accepts (object/array/string/number/integer/boolean) are
14
+ * used. `enum` is expressed in the description and validated in `execute`
15
+ * because the tool layer should not be the only thing saying "user" is a kind.
16
+ *
17
+ * Registration is `ctx.tools.register(tool)`; the returned disposer belongs to
18
+ * the plugin's effect. The tool layer never decides scope silently — an
19
+ * unscoped call is an error the model can correct, not a memory filed under an
20
+ * implicit identity.
21
+ */
22
+ import { searchMemories } from './search.js'
23
+
24
+ export const MEMORY_TYPES = ['user', 'agent', 'procedural']
25
+
26
+ /** Model-facing JSON: one text block carrying the result object. */
27
+ export function jsonOutput(schema) {
28
+ return {
29
+ schema,
30
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
31
+ }
32
+ }
33
+
34
+ const SEARCH_OUTPUT = {
35
+ type: 'object',
36
+ properties: {
37
+ results: { type: 'array', items: { type: 'object', additionalProperties: true } },
38
+ answerable: { type: 'boolean' },
39
+ note: { type: 'string' },
40
+ },
41
+ additionalProperties: false,
42
+ }
43
+
44
+ const ADD_OUTPUT = {
45
+ type: 'object',
46
+ properties: {
47
+ id: { type: 'string' },
48
+ text: { type: 'string' },
49
+ type: { type: 'string' },
50
+ },
51
+ additionalProperties: false,
52
+ }
53
+
54
+ const SCOPE_PROPERTIES = {
55
+ user_id: { type: 'string', description: 'Scope: the human the memory belongs to.' },
56
+ agent_id: { type: 'string', description: 'Scope: the project/agent the memory belongs to.' },
57
+ run_id: { type: 'string', description: 'Scope: a single session, when the memory is run-specific.' },
58
+ }
59
+
60
+ const SEARCH_PARAMETERS = {
61
+ type: 'object',
62
+ properties: {
63
+ query: { type: 'string', description: 'What to look for; concrete nouns work best.' },
64
+ limit: { type: 'integer', description: 'How many memories to return (default 10).' },
65
+ ...SCOPE_PROPERTIES,
66
+ },
67
+ required: ['query'],
68
+ additionalProperties: false,
69
+ }
70
+
71
+ const ADD_PARAMETERS = {
72
+ type: 'object',
73
+ properties: {
74
+ text: { type: 'string', description: 'One standalone statement, e.g. "用户偏好中文回答。".' },
75
+ type: {
76
+ type: 'string',
77
+ description: 'Kind of memory: user | agent | procedural (default user).',
78
+ },
79
+ metadata: { type: 'object', additionalProperties: true, description: 'Free-form metadata object.' },
80
+ ...SCOPE_PROPERTIES,
81
+ },
82
+ required: ['text'],
83
+ additionalProperties: false,
84
+ }
85
+
86
+ function scopeOf(args) {
87
+ return {
88
+ userId: args.user_id ?? null,
89
+ agentId: args.agent_id ?? null,
90
+ runId: args.run_id ?? null,
91
+ }
92
+ }
93
+
94
+ /** Build the two tool definitions against one store. */
95
+ export function buildMemoryTools(store, { embedder = null, adjudicator = null } = {}) {
96
+ if (!store) throw new Error('store is required')
97
+
98
+ const search = {
99
+ name: 'memory_search',
100
+ description: 'Retrieve long-term memories by keyword + vector similarity. '
101
+ + 'Returns the closest memories; when nothing truly answers the question, `answerable` is false and `results` is empty.',
102
+ parameters: SEARCH_PARAMETERS,
103
+ output: jsonOutput(SEARCH_OUTPUT),
104
+ async execute(args) {
105
+ const out = await searchMemories(store, args.query, {
106
+ ...scopeOf(args),
107
+ limit: args.limit ?? 10,
108
+ embedder,
109
+ adjudicator,
110
+ })
111
+ const results = out.answerable === false ? [] : out.results.map((row) => ({
112
+ id: row.id,
113
+ text: row.text,
114
+ type: row.type,
115
+ score: Math.round(row.score * 10_000) / 10_000,
116
+ createdAt: row.createdAt,
117
+ }))
118
+ // An empty result set is not an answer: `answerable` must not be true
119
+ // just because the guard could not reject a candidate it never saw.
120
+ const empty = results.length === 0
121
+ return {
122
+ results,
123
+ answerable: out.answerable === false ? false : !empty,
124
+ note: out.note ?? (empty ? 'no matching memories in this scope' : ''),
125
+ }
126
+ },
127
+ }
128
+
129
+ const add = {
130
+ name: 'memory_add',
131
+ description: 'Store one long-term memory verbatim. Use for a fact the automatic extraction would miss; '
132
+ + 'scope (user_id / agent_id / run_id) is required so the memory is findable later.',
133
+ parameters: ADD_PARAMETERS,
134
+ output: jsonOutput(ADD_OUTPUT),
135
+ async execute(args) {
136
+ const scope = scopeOf(args)
137
+ if (!scope.userId && !scope.agentId && !scope.runId) {
138
+ throw new Error('memory_add requires a scope: at least one of user_id / agent_id / run_id')
139
+ }
140
+ if (args.type !== undefined && !MEMORY_TYPES.includes(args.type)) {
141
+ throw new Error(`memory_add: unknown memory type ${JSON.stringify(args.type)} (user|agent|procedural)`)
142
+ }
143
+ const memory = store.addMemory({
144
+ ...scope,
145
+ text: args.text,
146
+ type: args.type ?? 'user',
147
+ metadata: args.metadata ?? {},
148
+ origin: 'manual',
149
+ actor: 'manual',
150
+ })
151
+ // Embed at write time when a default embedder is wired in, so the very
152
+ // next search can score this memory on the vector channel too.
153
+ if (embedder) {
154
+ const vector = await embedder.embedOne(memory.text)
155
+ if (vector) store.saveEmbedding(memory.id, embedder.model, vector)
156
+ }
157
+ return { id: memory.id, text: memory.text, type: memory.type }
158
+ },
159
+ }
160
+
161
+ return [search, add]
162
+ }
163
+
164
+ /** Register both tools on a tools service; returns one disposer for both. */
165
+ export function registerTools(tools, store, { logger = null, embedder = null, adjudicator = null } = {}) {
166
+ if (!tools || typeof tools.register !== 'function') throw new Error('tools service is not available')
167
+ const disposers = buildMemoryTools(store, { embedder, adjudicator }).map((tool) => tools.register(tool))
168
+ return () => {
169
+ for (const dispose of disposers) {
170
+ try {
171
+ dispose?.()
172
+ } catch (error) {
173
+ logger?.warn?.('dsh-memvault: failed to dispose a memory tool', error)
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ /** Register on a context's `tools` service (the shape tests and apply use). */
180
+ export function registerMemoryTools(ctx, { store, logger = null, embedder = null, adjudicator = null } = {}) {
181
+ return registerTools(ctx?.tools, store, { logger, embedder, adjudicator })
182
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The write pipeline in one call (M1): extract -> decide -> apply.
3
+ *
4
+ * Applying is where the new store differs from the Python engine: an update is
5
+ * a `supersede` (new row, old row linked), never an in-place text change. Facts
6
+ * from the same pass are related to each other by textual similarity so the
7
+ * graph does not go flat, and every applied decision is reported back for the
8
+ * panel and for tests.
9
+ */
10
+ import { decideFacts, similarity } from './decide.js'
11
+
12
+ export async function remember({
13
+ store,
14
+ scope = {},
15
+ messages,
16
+ extractor,
17
+ decider = null,
18
+ metadata = {},
19
+ origin = 'extract',
20
+ embedder = null,
21
+ } = {}) {
22
+ if (!store) throw new Error('store is required')
23
+ if (!extractor) throw new Error('extractor is required')
24
+
25
+ const facts = await extractor.extract(messages)
26
+ // `applied` is part of the contract even when nothing was written: callers
27
+ // (the extraction pipeline) map over it, and an undefined here used to turn
28
+ // "the window produced no facts" into a TypeError.
29
+ const summary = { facts, added: 0, superseded: 0, skipped: 0, relations: 0, decisions: [], applied: [] }
30
+ if (!facts.length) return summary
31
+
32
+ const decisions = await decideFacts(store, scope, facts, { decider })
33
+ summary.decisions = decisions.map((decision) => ({
34
+ fact: decision.fact,
35
+ op: decision.op,
36
+ targetId: decision.targetId ?? null,
37
+ reason: decision.reason ?? null,
38
+ }))
39
+
40
+ const applied = []
41
+ for (const decision of decisions) {
42
+ if (decision.op === 'none') {
43
+ summary.skipped += 1
44
+ continue
45
+ }
46
+ if (decision.op === 'supersede' && decision.targetId) {
47
+ applied.push(store.supersede(decision.targetId, {
48
+ text: decision.fact,
49
+ metadata,
50
+ origin,
51
+ actor: origin,
52
+ }))
53
+ summary.superseded += 1
54
+ continue
55
+ }
56
+ applied.push(store.addMemory({
57
+ ...scope,
58
+ text: decision.fact,
59
+ metadata,
60
+ origin,
61
+ actor: origin,
62
+ }))
63
+ summary.added += 1
64
+ }
65
+
66
+ for (let i = 0; i < applied.length; i += 1) {
67
+ for (let j = i + 1; j < applied.length; j += 1) {
68
+ const weight = similarity(applied[i].text, applied[j].text)
69
+ if (weight > 0) {
70
+ store.addRelation(applied[i].id, applied[j].id, 'similar', Math.round(weight * 10_000) / 10_000)
71
+ summary.relations += 1
72
+ }
73
+ }
74
+ }
75
+
76
+ // Vectors are stored per applied memory so retrieval has something to score on
77
+ // the very next search; the embedding model is the row key, so a later switch
78
+ // to a real endpoint adds rows instead of losing the old ones.
79
+ if (embedder && applied.length) {
80
+ const vectors = await embedder.embed(applied.map((memory) => memory.text))
81
+ applied.forEach((memory, index) => {
82
+ if (vectors[index]) store.saveEmbedding(memory.id, embedder.model, vectors[index])
83
+ })
84
+ }
85
+ // Ids and text of what was actually written: the extraction pipeline records
86
+ // these as "produced" so a window stays traceable to its rows.
87
+ summary.applied = applied.map((memory) => ({ id: memory.id, text: memory.text, type: memory.type }))
88
+ return summary
89
+ }
package/lib/extract.js CHANGED
@@ -18,7 +18,6 @@
18
18
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
19
19
  import { homedir } from 'node:os'
20
20
  import { dirname, join } from 'node:path'
21
- import { buildCliInvocation, runCli } from './cli.js'
22
21
 
23
22
  /** Where the per-session extraction watermark lives (survives a DSH restart). */
24
23
  export const DEFAULT_STATE_PATH = join(homedir(), '.dsh', 'storages', 'dsh-memvault-state.json')
@@ -287,14 +286,6 @@ export function saveWatermarks(map, statePath = DEFAULT_STATE_PATH, diagnostics
287
286
  }
288
287
 
289
288
  /** argv for the MemVault CLI call (kept as the documented name for `add`). */
290
- export function buildAddInvocation({ pythonPath, projectDir, user, agent, run }) {
291
- const args = ['add', '--stdin']
292
- if (user) args.push('--user', user)
293
- if (agent) args.push('--agent', agent)
294
- if (run) args.push('--run', run)
295
- return buildCliInvocation({ pythonPath, projectDir, args })
296
- }
297
-
298
289
  /**
299
290
  * How much of each produced memory the diagnostic keeps.
300
291
  *
@@ -306,7 +297,7 @@ export function buildAddInvocation({ pythonPath, projectDir, user, agent, run })
306
297
  export const PRODUCED_MAX = 20
307
298
  export const PRODUCED_TEXT_CLAMP = 200
308
299
 
309
- /** Shape the CLI's `results` into what a diagnostic stores. */
300
+ /** Shape the pipeline's applied rows into what a diagnostic stores. */
310
301
  export function shapeProduced(results) {
311
302
  if (!Array.isArray(results)) return []
312
303
  return results.slice(0, PRODUCED_MAX).map((row) => {
@@ -319,32 +310,3 @@ export function shapeProduced(results) {
319
310
  }
320
311
  }).filter((row) => row.id !== null)
321
312
  }
322
-
323
- /**
324
- * Feed `messages` to MemVault and resolve with the parsed result.
325
- *
326
- * Never rejects and never throws into the caller: memory capture is a
327
- * side-channel and must not break a turn.
328
- *
329
- * @returns {Promise<{ok: boolean, added?: number, relations?: number, produced?: Array, error?: string}>}
330
- */
331
- export async function runExtraction({ config, messages, spawn }) {
332
- const result = await runCli({
333
- config,
334
- args: buildAddInvocation(config).args.slice(2), // drop `-m memvault.cli`
335
- stdin: JSON.stringify(messages),
336
- ...(spawn ? { spawn } : {}),
337
- })
338
- if (!result.ok) return { ok: false, error: result.error }
339
- try {
340
- const parsed = JSON.parse(result.stdout)
341
- return {
342
- ok: true,
343
- added: parsed.results?.length ?? 0,
344
- relations: parsed.relations?.length ?? 0,
345
- produced: shapeProduced(parsed.results),
346
- }
347
- } catch {
348
- return { ok: true, added: 0, produced: [] }
349
- }
350
- }