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/config.js CHANGED
@@ -17,97 +17,78 @@
17
17
  import { statSync } from 'node:fs'
18
18
  import { homedir } from 'node:os'
19
19
  import { fileURLToPath } from 'node:url'
20
- import { DEFAULT_DB_PATH, DEFAULT_SCOPES } from './blocks.js'
20
+ import { DEFAULT_SCOPES } from './blocks.js'
21
21
  import { DEFAULT_STATE_PATH } from './extract.js'
22
22
 
23
23
  /** This package's own root — used as one place to look for a sibling checkout. */
24
24
  const DEFAULT_PLUGIN_DIR = fileURLToPath(new URL('..', import.meta.url))
25
25
 
26
26
  /**
27
- * Find a MemVault checkout, so that "installed the plugin" and "set up MemVault"
28
- * do not have to be two pieces of configuration the user performs.
27
+ * Find the MemVault directory whose `.env` the pipeline should read.
29
28
  *
30
- * Order matters and is deliberate:
29
+ * Since the Python engine retired (DEVLOG §34) nothing is spawned and no MemVault
30
+ * checkout is needed: the only file the runtime still reads from a project
31
+ * directory is its `.env` (embedding endpoint, extractor choice, model overrides).
32
+ * So the test for a candidate is **does it hold a `.env`** — not "does it have a
33
+ * `memvault/` package and a venv", which was the Python-era requirement and made
34
+ * discovery fail on machines that had a perfectly good `.env` but no venv.
31
35
  *
32
- * 1. `MEMVAULT_DIR` / `MEMVAULT_PYTHON` — an explicit answer always wins.
33
- * 2. the author's conventional location, then a few common ones (`~/memvault`,
34
- * `~/projects/memvault`, a sibling of this plugin's own directory);
35
- * 3. nothing found — and then the panel says so instead of guessing silently.
36
+ * Order matters and is deliberate:
36
37
  *
37
- * A candidate counts only if it has both the package (`memvault/__init__.py`) and a
38
- * venv interpreter; a directory with one but not the other is reported as the
39
- * reason, because "found the project but no venv" is a fixable, specific problem.
38
+ * 1. `MEMVAULT_DIR` — an explicit answer always wins, even when it is wrong; the
39
+ * panel then reports the failure instead of silently using another vault.
40
+ * 2. the store's own directory (`~/.dsh/memvault`, where the pipeline also looks
41
+ * for a `.env` next to the database), then the author's conventional location
42
+ * and a few common ones;
43
+ * 3. nothing found — `projectDir` stays empty and the panel says so, listing what
44
+ * was checked. An empty project directory is not an error: the pipeline still
45
+ * finds a `.env` next to the store, and without one it falls back to the
46
+ * offline embedder and the rule extractor.
40
47
  */
41
- export function discoverMemVault({ env = process.env, pluginDir = DEFAULT_PLUGIN_DIR } = {}) {
48
+ export function discoverVault({ env = process.env, pluginDir = DEFAULT_PLUGIN_DIR } = {}) {
42
49
  const isFile = (path) => { try { return statSync(path).isFile() } catch { return false } }
43
- const isDir = (path) => { try { return statSync(path).isDirectory() } catch { return false } }
44
50
  const join = (...parts) => parts.join('/').replace(/\/+/g, '/')
45
51
 
46
52
  const explicitDir = env.MEMVAULT_DIR
47
- const explicitPython = env.MEMVAULT_PYTHON
48
53
  const candidates = [
49
54
  explicitDir,
55
+ join(homedir(), '.dsh', 'memvault'),
50
56
  'D:/Claude_code/memory',
51
57
  join(homedir(), 'memvault'),
52
58
  join(homedir(), 'projects', 'memvault'),
53
59
  join(pluginDir, '..', 'memory'),
54
60
  ].filter((dir) => typeof dir === 'string' && dir !== '')
55
61
 
56
- const venvOf = (dir) => (process.platform === 'win32'
57
- ? [`${dir}/.venv/Scripts/python.exe`, `${dir}/.venv/bin/python`]
58
- : [`${dir}/.venv/bin/python`, `${dir}/.venv/Scripts/python.exe`])
59
-
60
62
  const checked = []
61
- // An explicit answer wins even when it is wrong: silently substituting a working
62
- // directory for the one the user named is how "my memories are in the other
63
- // vault" happens. Report the failure instead — the panel shows it.
64
63
  const explicit = typeof explicitDir === 'string' && explicitDir !== ''
65
64
  for (const dir of [...new Set(candidates)]) {
66
- const hasPackage = isFile(`${dir}/memvault/__init__.py`)
67
- const python = venvOf(dir).find(isFile)
68
- checked.push({ dir, hasPackage, python: python ?? null })
69
- if (hasPackage && python) {
70
- return { found: true, source: dir === explicitDir ? 'env' : 'discovered', projectDir: dir, pythonPath: python, checked }
65
+ const hasEnv = isFile(`${dir}/.env`)
66
+ checked.push({ dir, hasEnv })
67
+ if (hasEnv) {
68
+ return { found: true, source: dir === explicitDir ? 'env' : 'discovered', projectDir: dir, checked }
71
69
  }
70
+ // An explicit answer wins even when it is wrong: substituting a working
71
+ // directory for the one the user named is how "my memories are in the other
72
+ // vault" happens.
72
73
  if (explicit) break
73
74
  }
74
- // Nothing usable: keep whatever the environment said, so the failure is visible
75
- // rather than silently replaced by a path that does not exist either.
76
75
  return {
77
76
  found: false,
78
- // Either env variable counts as "the user answered" — claiming `none` while a
79
- // wrong MEMVAULT_DIR is in force would be the panel telling a small lie.
80
- source: (explicit || explicitPython) ? 'env' : 'none',
81
- projectDir: explicitDir ?? candidates[1] ?? '',
82
- pythonPath: explicitPython ?? venvOf(explicitDir ?? candidates[1] ?? '')[0],
77
+ source: explicit ? 'env' : 'none',
78
+ // Empty, not a guess: the default `projectDir` must not claim a directory the
79
+ // plugin did not verify. The pipeline still checks the store's own directory.
80
+ projectDir: explicit ? explicitDir : '',
83
81
  checked,
84
82
  }
85
83
  }
86
84
 
87
- const discovered = discoverMemVault()
88
-
89
- /** MemVault checkout the write half drives (discovered, or the explicit env). */
90
- export const MEMVAULT_DIR = discovered.projectDir
91
-
92
- /** Interpreter that can `import memvault` — the venv, not the system python. */
93
- export const MEMVAULT_PYTHON = discovered.pythonPath
85
+ /** Backwards-compatible alias: the name the earlier releases exported. */
86
+ export const discoverMemVault = discoverVault
94
87
 
95
- /** How the path was decided: `env`, `discovered`, or `none`. The panel shows it. */
96
- export const MEMVAULT_SOURCE = discovered.source
88
+ const discovered = discoverVault()
97
89
 
98
- /** Candidate directories that were looked at, for the setup card's explanation. */
99
- export const MEMVAULT_CANDIDATES = discovered.checked
100
-
101
- /**
102
- * The store path this plugin will use when nothing is configured.
103
- *
104
- * Derived from the *discovered* checkout rather than written down: MemVault's own
105
- * relative default is `data/memvault.db` inside its project directory, so a machine
106
- * whose MemVault lives somewhere else gets that somewhere else. `MEMVAULT_DB_PATH`
107
- * still wins when set - an explicit answer outranks a discovered one.
108
- */
109
- export const MEMVAULT_DB_PATH_DEFAULT = process.env.MEMVAULT_DB_PATH
110
- ?? `${discovered.projectDir}/data/memvault.db`
90
+ /** Directory whose `.env` the extractor/embedder resolve against (may be empty). */
91
+ export const MEMVAULT_DIR = discovered.projectDir
111
92
 
112
93
  /** Whether the paths came from the environment or from discovery, plus the search. */
113
94
  export function discoverySnapshot() {
@@ -115,7 +96,6 @@ export function discoverySnapshot() {
115
96
  source: discovered.source,
116
97
  found: discovered.found,
117
98
  projectDir: discovered.projectDir,
118
- pythonPath: discovered.pythonPath,
119
99
  candidates: discovered.checked,
120
100
  }
121
101
  }
@@ -146,15 +126,11 @@ export const CONFIG_SPEC = {
146
126
  default: 210,
147
127
  description: 'Order among runtime-context contributions (skill-catalog and friends).',
148
128
  },
149
- dbPath: {
150
- kind: 'string',
151
- default: MEMVAULT_DB_PATH_DEFAULT,
152
- description: 'Path to memvault.db. Read-only; the MemVault service and MCP clients share this file.',
153
- },
154
129
  scopes: {
155
130
  kind: 'array',
156
131
  default: DEFAULT_SCOPES,
157
- description: 'Core blocks are keyed by (scope_type, scope_id); both halves must be listed explicitly.',
132
+ description: 'Core blocks are keyed by (scope_type, scope_id); both halves must be listed explicitly. '
133
+ + 'These scopes are also the write scope: the first user scope becomes user_id, the first agent scope agent_id.',
158
134
  of: {
159
135
  kind: 'object',
160
136
  fields: {
@@ -286,38 +262,21 @@ export const CONFIG_SPEC = {
286
262
  kind: 'number',
287
263
  integer: true,
288
264
  min: 1000,
289
- default: 120_000,
290
- description: 'Timeout for one extraction; the child is killed and a single warning is recorded.',
291
- },
292
- pythonPath: {
293
- kind: 'string',
294
- default: MEMVAULT_PYTHON,
295
- description: 'Interpreter that can import memvault — the venv, not the system python.',
265
+ default: 60_000,
266
+ description: 'Deadline of one extraction model request, in milliseconds. '
267
+ + 'Applied as MEMVAULT_EXTRACT_TIMEOUT_MS unless the env map sets it explicitly.',
296
268
  },
297
269
  projectDir: {
298
270
  kind: 'string',
299
271
  default: MEMVAULT_DIR,
300
- description: 'Working directory of the child (the MemVault checkout, whose .env it loads).',
301
- },
302
- user: {
303
- kind: 'string',
304
- default: 'lenovo',
305
- description: 'user_id written with. The three scope axes are orthogonal; leave empty to omit the flag.',
306
- },
307
- agent: {
308
- kind: 'string',
309
- default: 'claude-code-memory',
310
- description: 'agent_id written with.',
311
- },
312
- run: {
313
- kind: 'string',
314
- default: '',
315
- description: 'run_id written with; an empty value omits the flag (the three scope axes are orthogonal).',
272
+ description: 'Directory whose .env supplies the extractor, embedding endpoint and model overrides. '
273
+ + 'No process is spawned: an empty value falls back to the .env next to the store.',
316
274
  },
317
275
  env: {
318
276
  kind: 'dict',
319
- default: { PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' },
320
- description: 'Extra child environment. The UTF-8 pair is what keeps a Chinese Windows from mangling the transcript.',
277
+ default: {},
278
+ description: 'Extra environment for this plugin: MEMVAULT_EXTRACTOR, MEMVAULT_EMBEDDER, '
279
+ + 'MEMVAULT_EXTRACT_TIMEOUT_MS, API keys. Empty means "use the .env".',
321
280
  },
322
281
  statePath: {
323
282
  kind: 'string',
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The semantic half of "can these memories answer the question?".
3
+ *
4
+ * `answerabilityGuard()` only understands hard demands (numbers, times, ports):
5
+ * when the question asks for a value and no candidate carries one, it rejects.
6
+ * Everything else — "which editor do I use?" against a memory that merely
7
+ * mentions editors — needs a judgement, and this asks the model for it.
8
+ *
9
+ * Fail-open on purpose: a timeout, an HTTP error or an unreadable answer returns
10
+ * `{ answerable: null }`, leaving the guard's verdict (usually "unknown") in
11
+ * place. A memory tool that breaks because the adjudicator is down would be worse
12
+ * than one that returns a merely plausible answer.
13
+ */
14
+ import { ChatClient } from './llm.js'
15
+ import { findEnvFile, readEnvFile } from './env.js'
16
+
17
+ export const ADJUDICATOR_MAX_CANDIDATES = 5
18
+ export const ADJUDICATOR_SNIPPET_CHARS = 300
19
+
20
+ export const ADJUDICATOR_PROMPT = (
21
+ '你在判断记忆库里的候选记忆能否回答用户的问题。只输出一个 JSON 对象:'
22
+ + '{"answerable": true 或 false, "reason": "不超过 30 字的中文理由"}。\n'
23
+ + '规则:候选只是提到相关主题、但没有给出问题要的具体事实 → false;'
24
+ + '候选给出了回答问题所需的事实 → true;'
25
+ + '问题要求数字、时间或路径而候选没有对应值 → false。'
26
+ )
27
+
28
+ /** Parse `{"answerable": bool, "reason": string}` out of a model answer, tolerantly. */
29
+ export function parseVerdict(content) {
30
+ const text = String(content ?? '')
31
+ const start = text.indexOf('{')
32
+ const end = text.lastIndexOf('}')
33
+ if (start === -1 || end <= start) return null
34
+ try {
35
+ const data = JSON.parse(text.slice(start, end + 1))
36
+ if (typeof data?.answerable !== 'boolean') return null
37
+ return {
38
+ answerable: data.answerable,
39
+ reason: typeof data.reason === 'string' ? data.reason.slice(0, 200) : null,
40
+ }
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+
46
+ export class LLMAdjudicator {
47
+ constructor(client, { prompt = ADJUDICATOR_PROMPT } = {}) {
48
+ this.client = client
49
+ this.prompt = prompt
50
+ }
51
+
52
+ /** @returns {Promise<{answerable: boolean|null, reason: string|null}>} — never throws. */
53
+ async check(query, results = []) {
54
+ const lines = results
55
+ .slice(0, ADJUDICATOR_MAX_CANDIDATES)
56
+ .map((row, index) => `[${index + 1}] ${String(row?.text ?? '').slice(0, ADJUDICATOR_SNIPPET_CHARS)}`)
57
+ try {
58
+ const content = await this.client.complete([
59
+ { role: 'system', content: this.prompt },
60
+ { role: 'user', content: `问题:${query}\n\n候选记忆:\n${lines.join('\n')}` },
61
+ ])
62
+ return parseVerdict(content) ?? { answerable: null, reason: 'adjudicator returned no verdict' }
63
+ } catch (error) {
64
+ return { answerable: null, reason: `adjudicator failed: ${error?.message ?? String(error)}` }
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Build an adjudicator from the same `.env` the rest of the pipeline reads.
71
+ * Returns null when disabled (`MEMVAULT_ADJUDICATOR=off`) or when there is no key
72
+ * to call a model with — in both cases retrieval simply keeps the guard's answer.
73
+ */
74
+ export function resolveAdjudicator({ projectDir = '', dbPath = '', env = process.env, envFile = null } = {}) {
75
+ const file = findEnvFile({ projectDir, dbPath, envFile })
76
+ const merged = { ...(file ? readEnvFile(file) : {}), ...env }
77
+ const requested = String(merged.MEMVAULT_ADJUDICATOR ?? '').toLowerCase()
78
+ if (requested === 'off' || !merged.OPENAI_API_KEY) return null
79
+ let extraBody = {}
80
+ if (merged.MEMVAULT_LLM_EXTRA_BODY) {
81
+ try {
82
+ extraBody = JSON.parse(merged.MEMVAULT_LLM_EXTRA_BODY)
83
+ } catch {
84
+ extraBody = {}
85
+ }
86
+ }
87
+ return new LLMAdjudicator(new ChatClient({
88
+ baseUrl: merged.OPENAI_BASE_URL || 'https://api.openai.com/v1',
89
+ apiKey: merged.OPENAI_API_KEY,
90
+ model: merged.OPENAI_CHAT_MODEL || 'gpt-4o-mini',
91
+ timeoutMs: Number(merged.MEMVAULT_ADJUDICATOR_TIMEOUT_MS ?? 10_000),
92
+ extraBody,
93
+ }))
94
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Backfill: embed memories that have no vector for the selected model.
3
+ *
4
+ * Imported memories carry text but no embeddings (the export drops vectors by
5
+ * default because they are model-specific). Until they are embedded, retrieval
6
+ * on them is keyword-only — measurably worse than the old store's semantic
7
+ * search — so the migration is not finished until this runs.
8
+ *
9
+ * Batched and resumable: only rows missing a vector for `embedder.model` are
10
+ * selected, so re-running after an interruption continues where it stopped.
11
+ */
12
+ export async function backfillEmbeddings(store, embedder, { batchSize = 32, onBatch = null } = {}) {
13
+ const rows = store.db.prepare(`
14
+ SELECT id, text FROM memories
15
+ WHERE id NOT IN (SELECT memory_id FROM memory_embeddings WHERE model = ?)
16
+ ORDER BY created_at
17
+ `).all(embedder.model)
18
+
19
+ let embedded = 0
20
+ for (let offset = 0; offset < rows.length; offset += batchSize) {
21
+ const batch = rows.slice(offset, offset + batchSize)
22
+ const vectors = await embedder.embed(batch.map((row) => row.text))
23
+ batch.forEach((row, index) => {
24
+ const vector = vectors[index]
25
+ if (!vector) return
26
+ store.saveEmbedding(row.id, embedder.model, vector)
27
+ embedded += 1
28
+ })
29
+ onBatch?.({ done: Math.min(offset + batchSize, rows.length), total: rows.length })
30
+ }
31
+ return { model: embedder.model, missing: rows.length, embedded }
32
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Core block writes on the in-plugin store (the panel's only write action).
3
+ *
4
+ * Validation lives here now that the Python transport is gone: same limits and
5
+ * the same "an empty value would be invisible" refusal, but no argv builders —
6
+ * there is no CLI to feed. The write is an upsert on `blocks`, which is what the
7
+ * prompt reader reads; the old comment argued a direct write would skip
8
+ * MemVault's events and `value_limit`, and with the store in-process there is no
9
+ * event bus to skip and the limit is written here.
10
+ */
11
+
12
+ /** Hard cap on a block value. */
13
+ export const BLOCK_VALUE_MAX = 8000
14
+
15
+ /** Hard cap on a block label. */
16
+ export const BLOCK_LABEL_MAX = 120
17
+
18
+ /** Accepted actions. */
19
+ export const BLOCK_ACTIONS = ['set', 'delete']
20
+
21
+ /**
22
+ * Validate a panel write request.
23
+ *
24
+ * @returns `{ ok: true, action, type, id, label, value, limit }` or
25
+ * `{ ok: false, error }`. Never throws.
26
+ */
27
+ export function validateBlockAction(input = {}) {
28
+ const action = String(input?.action ?? '').trim()
29
+ if (!BLOCK_ACTIONS.includes(action)) return { ok: false, error: `action must be one of ${BLOCK_ACTIONS.join(' | ')}` }
30
+
31
+ const type = String(input?.type ?? '').trim()
32
+ if (type !== 'user' && type !== 'agent') return { ok: false, error: 'type must be user or agent' }
33
+
34
+ const id = String(input?.id ?? '').trim()
35
+ if (id === '') return { ok: false, error: 'id is required' }
36
+ if (id.length > 200) return { ok: false, error: 'id is longer than 200 characters' }
37
+
38
+ const label = String(input?.label ?? '').trim()
39
+ if (label === '') return { ok: false, error: 'label is required' }
40
+ if (label.length > BLOCK_LABEL_MAX) return { ok: false, error: `label is longer than ${BLOCK_LABEL_MAX} characters` }
41
+ if (/[\r\n]/.test(label)) return { ok: false, error: 'label must be a single line' }
42
+
43
+ const value = input?.value === undefined || input?.value === null ? '' : String(input.value)
44
+ if (value.length > BLOCK_VALUE_MAX) {
45
+ return { ok: false, error: `value is ${value.length} characters; the panel limit is ${BLOCK_VALUE_MAX}` }
46
+ }
47
+
48
+ let limit
49
+ if (input?.limit !== undefined && input?.limit !== null && input?.limit !== '') {
50
+ limit = Number(input.limit)
51
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100_000) {
52
+ return { ok: false, error: 'limit must be a positive integer' }
53
+ }
54
+ }
55
+
56
+ if (action === 'delete') {
57
+ if (value !== '') return { ok: false, error: 'delete takes no value' }
58
+ return { ok: true, action, type, id, label, value: '', limit: undefined }
59
+ }
60
+ if (value.trim() === '') {
61
+ return { ok: false, error: 'value is required: the prompt reader skips empty blocks, so an empty write would be invisible' }
62
+ }
63
+ return { ok: true, action, type, id, label, value, limit }
64
+ }
65
+
66
+ export async function runBlockActionCore({ store, input } = {}) {
67
+ const valid = validateBlockAction(input)
68
+ if (!valid.ok) return { ok: false, status: 400, error: valid.error }
69
+
70
+ if (valid.action === 'delete') {
71
+ store.db.prepare(
72
+ 'DELETE FROM blocks WHERE scope_type = ? AND scope_id = ? AND label = ?',
73
+ ).run(valid.type, valid.id, valid.label)
74
+ return { ok: true, status: 200, action: 'delete', result: { deleted: true } }
75
+ }
76
+
77
+ const block = store.setBlock({
78
+ scopeType: valid.type,
79
+ scopeId: valid.id,
80
+ label: valid.label,
81
+ value: valid.value,
82
+ valueLimit: valid.limit ?? 2000,
83
+ })
84
+ return { ok: true, status: 200, action: 'set', result: block }
85
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Write decisions (M1): add / supersede / none for each extracted fact.
3
+ *
4
+ * The rule path is deliberately conservative — it only supersedes when it can
5
+ * name *why* (a duplicate, a negation, or the same attribute slot with real
6
+ * textual overlap). Anything else becomes an ADD rather than silently replacing
7
+ * a memory. When a chat client is configured, the model sees the same candidate
8
+ * set and may choose the operation instead; every answer is validated against
9
+ * that set, and an invalid or failed answer falls back to the rule per fact —
10
+ * the same failure-open contract the Python engine settled on.
11
+ */
12
+ import { DEFAULT_LLM_PROMPT } from './extract.js'
13
+
14
+ /** Character bigrams, punctuation and case folded away. */
15
+ export function bigrams(text) {
16
+ const clean = String(text ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
17
+ const out = new Set()
18
+ for (let i = 0; i < clean.length - 1; i += 1) out.add(clean.slice(i, i + 2))
19
+ return out
20
+ }
21
+
22
+ /** Jaccard overlap of bigrams: cheap, language-agnostic, no model. */
23
+ export function similarity(a, b) {
24
+ const left = bigrams(a)
25
+ const right = bigrams(b)
26
+ if (!left.size || !right.size) return 0
27
+ let shared = 0
28
+ for (const gram of left) if (right.has(gram)) shared += 1
29
+ return shared / (left.size + right.size - shared)
30
+ }
31
+
32
+ const NEGATION = /(?:不|没|别|不再|不是|改用|改成|换成|现在用)/
33
+ const SLOTS = ['名字', '职业', '学校', '专业', '编辑器', '终端', '住址', '城市', '生日', '邮箱', '电话', '数据库', '端口', '路径']
34
+
35
+ /** Do both texts talk about the same attribute slot? */
36
+ export function sameSlot(a, b) {
37
+ return SLOTS.some((slot) => a.includes(slot) && b.includes(slot))
38
+ }
39
+
40
+ export function ruleDecision(fact, candidates = []) {
41
+ for (const candidate of candidates) {
42
+ if (candidate.text === fact) {
43
+ return { op: 'none', targetId: candidate.id, reason: 'exact duplicate' }
44
+ }
45
+ const score = similarity(fact, candidate.text)
46
+ if (score < 0.3) continue
47
+ if (NEGATION.test(fact)) {
48
+ return { op: 'supersede', targetId: candidate.id, reason: 'negation' }
49
+ }
50
+ if (sameSlot(fact, candidate.text) && score >= 0.25) {
51
+ // A slot change replaces its value ("编辑器是 VS Code" -> "编辑器是
52
+ // Neovim"), so the overlap between the two texts is low by construction;
53
+ // requiring a high score here would turn every such change into a second
54
+ // fact. The slot itself is the evidence.
55
+ return { op: 'supersede', targetId: candidate.id, reason: 'same slot' }
56
+ }
57
+ }
58
+ return { op: 'add', targetId: null, reason: 'new fact' }
59
+ }
60
+
61
+ export const DECIDER_PROMPT = (
62
+ '你是记忆库的写入决策器。给定若干条新事实,以及每条事实在库中的候选记忆,'
63
+ + '为每条事实选择一个操作。只输出一个 JSON 数组,每项形如:'
64
+ + '{"fact": 序号, "op": "add|update|delete|none", "target_id": "候选 id(update/delete 必填)", '
65
+ + '"confidence": 0 到 1}。'
66
+ + '规则:只是换了一种说法的同一件事 → update(选最接近的候选 id);'
67
+ + '新事实否定或替换旧事实 → delete(选被否定的 id);'
68
+ + '候选与事实完全相同、没有新信息 → none;否则 add。'
69
+ + '不要输出解释,不要编造候选里没有的 id。'
70
+ )
71
+
72
+ /** Tolerant parse of the decider's JSON array, keyed by fact index. */
73
+ export function parseDecisions(content) {
74
+ const text = String(content ?? '')
75
+ const start = text.indexOf('[')
76
+ const end = text.lastIndexOf(']')
77
+ if (start === -1 || end <= start) return null
78
+ let data
79
+ try {
80
+ data = JSON.parse(text.slice(start, end + 1))
81
+ } catch {
82
+ return null
83
+ }
84
+ if (!Array.isArray(data)) return null
85
+ const out = new Map()
86
+ for (const item of data) {
87
+ const fact = Number(item?.fact)
88
+ const op = String(item?.op ?? '').toLowerCase()
89
+ if (!Number.isInteger(fact) || !['add', 'update', 'delete', 'none'].includes(op)) continue
90
+ out.set(fact, {
91
+ op: op === 'update' || op === 'delete' ? 'supersede' : op,
92
+ targetId: typeof item?.target_id === 'string' ? item.target_id : null,
93
+ confidence: Number(item?.confidence) || 0,
94
+ })
95
+ }
96
+ return out.size ? out : null
97
+ }
98
+
99
+ export class LLMDecider {
100
+ constructor(client) {
101
+ this.client = client
102
+ }
103
+
104
+ async decide(facts, candidatesByFact, prompt = DECIDER_PROMPT) {
105
+ const payload = facts.map((fact, index) => ({
106
+ fact: index,
107
+ text: fact,
108
+ candidates: (candidatesByFact[index] || []).map((row) => ({ id: row.id, text: row.text })),
109
+ }))
110
+ const content = await this.client.complete([
111
+ { role: 'system', content: prompt },
112
+ { role: 'user', content: JSON.stringify(payload) },
113
+ ])
114
+ return parseDecisions(content)
115
+ }
116
+ }
117
+
118
+ function valid(decision, candidates) {
119
+ if (!decision || !['add', 'supersede', 'none'].includes(decision.op)) return false
120
+ if (decision.op !== 'supersede') return true
121
+ return Boolean(decision.targetId) && candidates.some((row) => row.id === decision.targetId)
122
+ }
123
+
124
+ /**
125
+ * Decide every fact: model answer when valid, rule decision otherwise.
126
+ * Also returns the candidate set, so callers can report what the model saw.
127
+ */
128
+ export async function decideFacts(store, scope, facts, { decider = null, limit = 3, poolLimit = 500 } = {}) {
129
+ // Candidates are scored here, not by FTS: a trigram MATCH is an AND over the
130
+ // query's trigrams, so a paraphrased fact ("…是李四" vs "…是张三") matches
131
+ // nothing — exactly the case a write decision exists for. Scopes are small
132
+ // enough (hundreds of rows) that scoring the current set is cheap.
133
+ const pool = store.currentMemories({ ...scope, limit: poolLimit })
134
+ const candidatesByFact = facts.map((fact) => pool
135
+ .map((row) => ({ row, score: similarity(fact, row.text) }))
136
+ .filter((entry) => entry.score >= 0.3)
137
+ .sort((a, b) => b.score - a.score)
138
+ .slice(0, limit)
139
+ .map((entry) => entry.row))
140
+
141
+ let model = null
142
+ if (decider && facts.length) {
143
+ try {
144
+ model = await decider.decide(facts, candidatesByFact)
145
+ } catch {
146
+ model = null
147
+ }
148
+ }
149
+ return facts.map((fact, index) => {
150
+ const candidates = candidatesByFact[index]
151
+ const fromModel = model?.get(index)
152
+ if (fromModel && valid(fromModel, candidates)) {
153
+ return { fact, ...fromModel, reason: 'model' }
154
+ }
155
+ return { fact, ...ruleDecision(fact, candidates) }
156
+ })
157
+ }
158
+
159
+ export { DEFAULT_LLM_PROMPT }