dsh-memu-memory 1.2.4 → 1.2.6

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 (57) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +9 -9
  3. package/README.zh.md +6 -6
  4. package/docs/binding-lifecycle.md +1 -1
  5. package/docs/env-and-commands.md +4 -1
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +45 -9
  9. package/docs/troubleshooting.md +27 -8
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +246 -56
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/cycle.js +51 -17
  15. package/lib/embedding-catalog.js +14 -0
  16. package/lib/embedding-runtime.js +202 -25
  17. package/lib/global-graph.js +99 -1
  18. package/lib/index.js +8 -0
  19. package/lib/inject.js +71 -33
  20. package/lib/lexicon-scope.js +143 -0
  21. package/lib/lexicon.js +31 -4
  22. package/lib/local-vector-service.js +82 -6
  23. package/lib/memory.js +186 -12
  24. package/lib/memu.js +318 -3
  25. package/lib/private.js +310 -67
  26. package/lib/rpc.js +183 -23
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +7 -5
  29. package/lib/tools.js +40 -17
  30. package/lib/vector-migration.js +13 -1
  31. package/lib/webui/graph-view.bundle.js +1 -1
  32. package/lib/webui/graph-view.js +4 -1
  33. package/package.json +1 -1
  34. package/tests/absorb-review.test.mjs +2 -1
  35. package/tests/backend-compensation.test.mjs +1 -1
  36. package/tests/browser.test.mjs +58 -1
  37. package/tests/client-render.test.mjs +39 -0
  38. package/tests/consolidation-fork.test.mjs +81 -6
  39. package/tests/cross-library-recall.test.mjs +113 -0
  40. package/tests/curator-absorb.test.mjs +2 -1
  41. package/tests/curator-clusters.test.mjs +2 -1
  42. package/tests/curator-commit.test.mjs +2 -1
  43. package/tests/curator-link.test.mjs +2 -1
  44. package/tests/curator-review-mode.test.mjs +2 -1
  45. package/tests/cycle.test.mjs +2 -2
  46. package/tests/embedding-runtime.test.mjs +53 -1
  47. package/tests/global-graph.test.mjs +90 -0
  48. package/tests/lexicon-scope.test.mjs +256 -0
  49. package/tests/lexicon-ui.test.mjs +23 -0
  50. package/tests/managed-memory.test.mjs +1 -1
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/settings-plumbing.test.mjs +1 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/ui-defaults.test.mjs +1 -1
  56. package/tests/vector-migration.test.mjs +20 -0
  57. package/tests/webui-auth.test.mjs +28 -0
package/lib/memu.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { spawn } from 'node:child_process'
4
- import { dataDir, ensureDir, redactSecrets, windowsSystemEnv } from './paths.js'
4
+ import { dataDir, ensureDir, redactSecrets, warn, windowsSystemEnv } from './paths.js'
5
5
  import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
6
- import { getSettings } from './state.js'
6
+ import { effectiveVectorRoute, getSettings } from './state.js'
7
7
  import { activeProfile, captureVectorGeneration, assertVectorGeneration, assertProfileVerified, assertMigrationProfile } from './vector-profile.js'
8
8
  import { embeddingWorkerManager } from './local-embedding-manager.js'
9
9
  import { modelIdForRole } from './local-embedding-protocol.js'
@@ -79,6 +79,316 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
79
79
  })
80
80
  }
81
81
 
82
+ // ---- resident engine ---------------------------------------------------------
83
+ // MemU is a Python CLI: every command normally pays the whole import chain
84
+ // (~2 s), because the process exits when the command ends. Local vector mode
85
+ // calls the same three commands on every turn (recall) and on every write,
86
+ // so one warm interpreter removes that constant from both paths.
87
+ //
88
+ // The worker imports ``memu.cli`` once and calls the exact ``main(argv)`` the
89
+ // CLI entrypoint calls — command semantics stay in MemU's own code. One JSON
90
+ // object per line is the protocol on both directions. ``_close_backends`` is
91
+ // what keeps the per-command process model intact: a command that ends must
92
+ // release its sqlite handles, otherwise backup / migration / rollback would
93
+ // see a database still held open by a process that is supposed to be idle.
94
+ const RESIDENT_SCRIPT = String.raw`
95
+ import contextlib
96
+ import io
97
+ import json
98
+ import os
99
+ import sys
100
+
101
+ for _stream in (sys.stdin, sys.stdout, sys.stderr):
102
+ try:
103
+ _stream.reconfigure(encoding="utf-8", errors="replace")
104
+ except Exception:
105
+ pass
106
+
107
+
108
+ def _reply(payload):
109
+ sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
110
+ sys.stdout.flush()
111
+
112
+
113
+ BASE_ENV = dict(os.environ)
114
+ try:
115
+ import memu.cli as _cli
116
+ except Exception as _exc:
117
+ _reply({"ready": False, "error": "memu import failed: %s" % (_exc,)})
118
+ raise SystemExit(1)
119
+
120
+ _original_build = _cli.build_agentic_memory_backend_from_env
121
+ _created = []
122
+
123
+
124
+ def _tracked_build(*args, **kwargs):
125
+ backend = _original_build(*args, **kwargs)
126
+ _created.append(backend)
127
+ return backend
128
+
129
+
130
+ _cli.build_agentic_memory_backend_from_env = _tracked_build
131
+
132
+
133
+ def _close_backends():
134
+ while _created:
135
+ backend = _created.pop()
136
+ try:
137
+ closer = getattr(getattr(backend, "database", None), "close", None)
138
+ if callable(closer):
139
+ closer()
140
+ except Exception:
141
+ pass
142
+
143
+
144
+ _reply({"ready": True})
145
+
146
+ for _line in sys.stdin:
147
+ _line = _line.strip()
148
+ if not _line:
149
+ continue
150
+ try:
151
+ _request = json.loads(_line)
152
+ except Exception:
153
+ continue
154
+ if _request.get("op") == "shutdown":
155
+ break
156
+ os.environ.clear()
157
+ os.environ.update(BASE_ENV)
158
+ for _key, _value in (_request.get("env") or {}).items():
159
+ if _value is None:
160
+ os.environ.pop(str(_key), None)
161
+ else:
162
+ os.environ[str(_key)] = str(_value)
163
+ _argv = [str(_item) for _item in (_request.get("argv") or [])]
164
+ _out = io.StringIO()
165
+ _err = io.StringIO()
166
+ _code = 1
167
+ try:
168
+ with contextlib.redirect_stdout(_out), contextlib.redirect_stderr(_err):
169
+ _result = _cli.main(_argv)
170
+ _code = 0 if _result is None else int(_result)
171
+ except BaseException as _exc:
172
+ _err.write("%s: %s\n" % (type(_exc).__name__, _exc))
173
+ finally:
174
+ _close_backends()
175
+ _reply({"id": _request.get("id"), "code": _code, "stdout": _out.getvalue(), "stderr": _err.getvalue()})
176
+ `
177
+
178
+ const RESIDENT_READY_TIMEOUT_MS = 30_000
179
+ const RESIDENT_LINE_LIMIT = 8 << 20
180
+
181
+ function residentKey(current) {
182
+ return `${current.python}\u0000${String(current.version || '')}`
183
+ }
184
+
185
+ function residentBaseEnv() {
186
+ return {
187
+ ...windowsSystemEnv(),
188
+ ...process.env,
189
+ PYTHONUTF8: '1',
190
+ PYTHONIOENCODING: 'utf-8',
191
+ MEMU_MEMORY_MODE: memoryMode(),
192
+ }
193
+ }
194
+
195
+ function stopResident(record, failure = null) {
196
+ if (!record) return
197
+ record.stopping = true
198
+ if (residentRecord === record) residentRecord = null
199
+ if (failure) {
200
+ for (const pending of record.pending.values()) {
201
+ clearTimeout(pending.timer)
202
+ pending.reject(failure)
203
+ }
204
+ }
205
+ record.pending.clear()
206
+ try { record.child?.stdin?.end() } catch {}
207
+ try { record.child?.kill() } catch {}
208
+ }
209
+
210
+ function residentFailure(pending, code, detail, timedOut = false) {
211
+ const stdout = redactSecrets(String(detail?.stdout || ''), pending.secrets)
212
+ const stderr = redactSecrets(String(detail?.stderr || ''), pending.secrets)
213
+ const text = (stderr || stdout || '').trim()
214
+ return new MemuError(
215
+ `memu ${pending.label} failed (exit ${code}${timedOut ? ', timeout' : ''}): ${text.slice(-2000)}`,
216
+ 'MEMU_COMMAND_FAILED',
217
+ { code, stdout, stderr, timedOut },
218
+ )
219
+ }
220
+
221
+ function startResident(current, key) {
222
+ const record = { key, child: null, pending: new Map(), seq: 0, stopping: false, stderr: '', readySettled: false }
223
+ const abortReady = (message) => {
224
+ if (record.readySettled) return
225
+ record.readySettled = true
226
+ if (residentRecord === record) residentRecord = null
227
+ try { clearTimeout(record.bootTimer) } catch {}
228
+ try { record.child?.kill() } catch {}
229
+ record.readyReject?.(new MemuError(`failed to start memu: ${message}`, 'MEMU_SPAWN_FAILED'))
230
+ }
231
+ record.ready = new Promise((resolve, reject) => {
232
+ record.readyReject = reject
233
+ let buffer = ''
234
+ const settle = () => {
235
+ record.readySettled = true
236
+ try { clearTimeout(record.bootTimer) } catch {}
237
+ resolve(record)
238
+ }
239
+ record.bootTimer = setTimeout(() => abortReady('the memu resident process did not become ready in time'), RESIDENT_READY_TIMEOUT_MS)
240
+ try {
241
+ record.child = spawn(current.python, ['-c', RESIDENT_SCRIPT], {
242
+ env: residentBaseEnv(),
243
+ windowsHide: true,
244
+ stdio: ['pipe', 'pipe', 'pipe'],
245
+ })
246
+ } catch (error) {
247
+ abortReady(error.message)
248
+ return
249
+ }
250
+ // An unhandled 'error' event on a child pipe is an uncaught exception in the host.
251
+ for (const pipe of [record.child.stdin, record.child.stdout, record.child.stderr]) {
252
+ try { pipe?.on?.('error', () => {}) } catch {}
253
+ }
254
+ record.child.stderr?.on('data', (chunk) => {
255
+ record.stderr = (record.stderr + String(chunk)).slice(-4096)
256
+ })
257
+ record.child.stdout?.on('data', (chunk) => {
258
+ buffer += String(chunk)
259
+ if (buffer.length > RESIDENT_LINE_LIMIT) {
260
+ buffer = ''
261
+ abortReady('the resident engine response exceeded the line limit')
262
+ return
263
+ }
264
+ let newline = buffer.indexOf('\n')
265
+ while (newline >= 0) {
266
+ const line = buffer.slice(0, newline).replace(/\r+$/, '')
267
+ buffer = buffer.slice(newline + 1)
268
+ newline = buffer.indexOf('\n')
269
+ if (!line.trim()) continue
270
+ let message = null
271
+ try { message = JSON.parse(line) } catch { continue }
272
+ if (!record.readySettled) {
273
+ if (message.ready === true) settle()
274
+ else abortReady(String(message.error || 'the resident worker did not report ready'))
275
+ continue
276
+ }
277
+ const pending = record.pending.get(message.id)
278
+ if (!pending) continue
279
+ record.pending.delete(message.id)
280
+ clearTimeout(pending.timer)
281
+ const code = Number(message.code)
282
+ if (code === 0) pending.resolve({ stdout: String(message.stdout || ''), stderr: String(message.stderr || ''), code: 0 })
283
+ else pending.reject(residentFailure(pending, code, message))
284
+ }
285
+ })
286
+ record.child.on('error', (error) => abortReady(error.message))
287
+ record.child.on('close', (code) => {
288
+ if (!record.readySettled) {
289
+ abortReady(`the resident engine exited before it was ready (exit ${code})`)
290
+ return
291
+ }
292
+ if (residentRecord === record) residentRecord = null
293
+ if (record.stopping) return
294
+ const tail = redactSecrets(record.stderr.trim(), [])
295
+ const failure = new MemuError(
296
+ `memu resident process exited (exit ${code})${tail ? `: ${tail.slice(-2000)}` : ''}`,
297
+ 'MEMU_COMMAND_FAILED',
298
+ { code, timedOut: false, stderr: tail },
299
+ )
300
+ for (const pending of record.pending.values()) {
301
+ clearTimeout(pending.timer)
302
+ pending.reject(failure)
303
+ }
304
+ record.pending.clear()
305
+ warn('dsh-memu-memory: the resident memu engine exited; the next command will cold-start')
306
+ })
307
+ })
308
+ return record
309
+ }
310
+
311
+ function ensureResident(current) {
312
+ const key = residentKey(current)
313
+ if (residentRecord && residentRecord.key !== key) {
314
+ stopResident(residentRecord, new MemuError('the memu engine changed; the resident process was stopped', 'MEMU_COMMAND_FAILED'))
315
+ }
316
+ if (!residentRecord) residentRecord = startResident(current, key)
317
+ return residentRecord.ready
318
+ }
319
+
320
+ async function runResident(args, { env, timeoutMs = 90_000 } = {}) {
321
+ const current = currentEngine()
322
+ let record
323
+ try {
324
+ record = await ensureResident(current)
325
+ } catch (error) {
326
+ throw error instanceof MemuError ? error : new MemuError(String(error?.message || error), 'MEMU_SPAWN_FAILED')
327
+ }
328
+ if (!record || record.stopping) throw new MemuError('the resident memu engine is not available', 'MEMU_SPAWN_FAILED')
329
+ const label = args[0] || ''
330
+ const id = ++record.seq
331
+ const secrets = Object.entries({ ...process.env, ...(env || {}) })
332
+ .filter(([key]) => /(?:API_KEY|TOKEN|SECRET)$/.test(key)).map(([, value]) => value)
333
+ const payload = JSON.stringify({
334
+ id,
335
+ argv: args,
336
+ env: { ...(env || {}), MEMU_MEMORY_MODE: memoryMode() },
337
+ }) + '\n'
338
+ return new Promise((resolve, reject) => {
339
+ const timer = setTimeout(() => {
340
+ record.pending.delete(id)
341
+ const failure = new MemuError(
342
+ `memu ${label} failed (timeout): the resident engine did not answer in ${Math.round(timeoutMs / 1000)}s`,
343
+ 'MEMU_COMMAND_FAILED',
344
+ { code: null, stdout: '', stderr: '', timedOut: true },
345
+ )
346
+ reject(failure)
347
+ // A Python command cannot be cancelled from the outside, so a stuck command
348
+ // costs this process; the next request cold-starts a fresh one.
349
+ stopResident(record, failure)
350
+ }, timeoutMs)
351
+ record.pending.set(id, { resolve, reject, timer, label, secrets })
352
+ try {
353
+ record.child.stdin.write(payload)
354
+ } catch (error) {
355
+ record.pending.delete(id)
356
+ clearTimeout(timer)
357
+ const failure = new MemuError(`failed to start memu: ${error.message}`, 'MEMU_SPAWN_FAILED', { error })
358
+ reject(failure)
359
+ stopResident(record, failure)
360
+ }
361
+ })
362
+ }
363
+
364
+ /** Close the resident engine (plugin dispose, or an explicit teardown). */
365
+ export function closeMemuResident() {
366
+ const record = residentRecord
367
+ residentRecord = null
368
+ if (!record) return 0
369
+ stopResident(record, new MemuError('the resident memu engine is closed', 'MEMU_COMMAND_FAILED'))
370
+ return 1
371
+ }
372
+
373
+ /**
374
+ * Warm the resident engine for local vector mode. Called after the local vector
375
+ * bootstrap (or on the first managed-local command), and deliberately fail-open:
376
+ * an engine that is missing or broken must not delay plugin activation.
377
+ */
378
+ export async function prewarmMemuResident() {
379
+ try {
380
+ if (effectiveVectorRoute() !== 'managed-local') return false
381
+ if (!activeProfile()) return false
382
+ const current = readCurrent()
383
+ if (!current?.python) return false
384
+ await ensureResident(current)
385
+ return true
386
+ } catch (error) {
387
+ try { warn(`dsh-memu-memory: resident memu prewarm skipped: ${error?.message || error}`) } catch {}
388
+ return false
389
+ }
390
+ }
391
+
82
392
  async function runConfigured(args, options = {}) {
83
393
  const route = options.route || (options.vectorProfile ? 'managed-local' : 'remote-api')
84
394
  const useManagedLocal = route === 'managed-local'
@@ -90,7 +400,12 @@ async function runConfigured(args, options = {}) {
90
400
  const env = await envFor({ ...options, route })
91
401
  if (generation) assertVectorGeneration(generation)
92
402
  if (migration) assertMigrationProfile(migration)
93
- const result = await runRaw(['-m', 'memu', ...args], { env, timeoutMs: options.timeoutMs })
403
+ // Local vector mode is the only route this plugin can reach without a vendor key,
404
+ // so it is where a cold Python import is paid most often. Keep one interpreter warm
405
+ // there; the remote API path keeps the one-process-per-command behavior.
406
+ const result = useManagedLocal
407
+ ? await runResident(args, { env, timeoutMs: options.timeoutMs })
408
+ : await runRaw(['-m', 'memu', ...args], { env, timeoutMs: options.timeoutMs })
94
409
  if (generation) assertVectorGeneration(generation)
95
410
  if (migration) assertMigrationProfile(migration)
96
411
  return result