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
@@ -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')
@@ -33,6 +32,38 @@ function blockText(block) {
33
32
  return undefined
34
33
  }
35
34
 
35
+ /**
36
+ * Harness-injected, user-role text that the user did not write.
37
+ *
38
+ * The session log stores all of this as ordinary `user/message` events: the
39
+ * runtime-context block (which even carries the injected core memory), timing
40
+ * stamps, background-job reports, checkpoints, skill-catalog reminders and the
41
+ * Hindsight refresh. Measured on 2026-11-01: a 2 248-char window was 67 % this
42
+ * material, and one real transcript held a 20 k-char skill catalog next to a
43
+ * 7-char command ("继续做 R26") — the extractor then correctly returns [] for a
44
+ * window that contains nothing of the user. Dropping these keeps the budget and
45
+ * the model's attention on what the person actually said.
46
+ */
47
+ const MACHINE_USER_PREFIXES = [
48
+ 'Current runtime context',
49
+ 'MemVault core memory (persistent facts',
50
+ 'Time sampled while preparing',
51
+ 'Browser time zone for this request',
52
+ 'Elapsed since the preceding',
53
+ 'Current DeepSeek Harness Web GUI URL',
54
+ 'background job ',
55
+ '<system-reminder>',
56
+ '<hindsight_knowledge_refresh>',
57
+ 'This is an automatically generated checkpoint',
58
+ ]
59
+
60
+ /** Whether a user-role text was produced by the harness rather than the person. */
61
+ export function isMachineUserText(text) {
62
+ const trimmed = text.trimStart()
63
+ return MACHINE_USER_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
64
+ }
65
+
66
+
36
67
  /**
37
68
  * Render an event span as a bounded transcript, newest content kept.
38
69
  *
@@ -55,7 +86,7 @@ export function renderTranscript(events, maxChars = 6000, { includeAssistant = f
55
86
  if (event.type === 'user/message') {
56
87
  for (const block of event.data?.content ?? []) {
57
88
  const text = blockText(block)
58
- if (text) lines.push(`用户: ${text}`)
89
+ if (text && !isMachineUserText(text)) lines.push(`用户: ${text}`)
59
90
  }
60
91
  } else if (event.type === 'assistant/message') {
61
92
  for (const block of event.data?.message?.content ?? []) {
@@ -255,14 +286,6 @@ export function saveWatermarks(map, statePath = DEFAULT_STATE_PATH, diagnostics
255
286
  }
256
287
 
257
288
  /** argv for the MemVault CLI call (kept as the documented name for `add`). */
258
- export function buildAddInvocation({ pythonPath, projectDir, user, agent, run }) {
259
- const args = ['add', '--stdin']
260
- if (user) args.push('--user', user)
261
- if (agent) args.push('--agent', agent)
262
- if (run) args.push('--run', run)
263
- return buildCliInvocation({ pythonPath, projectDir, args })
264
- }
265
-
266
289
  /**
267
290
  * How much of each produced memory the diagnostic keeps.
268
291
  *
@@ -274,7 +297,7 @@ export function buildAddInvocation({ pythonPath, projectDir, user, agent, run })
274
297
  export const PRODUCED_MAX = 20
275
298
  export const PRODUCED_TEXT_CLAMP = 200
276
299
 
277
- /** Shape the CLI's `results` into what a diagnostic stores. */
300
+ /** Shape the pipeline's applied rows into what a diagnostic stores. */
278
301
  export function shapeProduced(results) {
279
302
  if (!Array.isArray(results)) return []
280
303
  return results.slice(0, PRODUCED_MAX).map((row) => {
@@ -287,32 +310,3 @@ export function shapeProduced(results) {
287
310
  }
288
311
  }).filter((row) => row.id !== null)
289
312
  }
290
-
291
- /**
292
- * Feed `messages` to MemVault and resolve with the parsed result.
293
- *
294
- * Never rejects and never throws into the caller: memory capture is a
295
- * side-channel and must not break a turn.
296
- *
297
- * @returns {Promise<{ok: boolean, added?: number, relations?: number, produced?: Array, error?: string}>}
298
- */
299
- export async function runExtraction({ config, messages, spawn }) {
300
- const result = await runCli({
301
- config,
302
- args: buildAddInvocation(config).args.slice(2), // drop `-m memvault.cli`
303
- stdin: JSON.stringify(messages),
304
- ...(spawn ? { spawn } : {}),
305
- })
306
- if (!result.ok) return { ok: false, error: result.error }
307
- try {
308
- const parsed = JSON.parse(result.stdout)
309
- return {
310
- ok: true,
311
- added: parsed.results?.length ?? 0,
312
- relations: parsed.relations?.length ?? 0,
313
- produced: shapeProduced(parsed.results),
314
- }
315
- } catch {
316
- return { ok: true, added: 0, produced: [] }
317
- }
318
- }