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/rpc.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  backupDatabases, listBackups, restoreBackup, deleteBackup, globalDbPath, normalizeCwd, getWorkspacePolicy, listWorkspacePolicies, setWorkspacePolicy,
8
8
  storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
9
9
  } from './state.js'
10
- import { commit } from './memu.js'
10
+ import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
11
11
  import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
@@ -22,6 +22,8 @@ import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, merge
22
22
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
23
23
  import { listEvents, logStats, clearEvents } from './activity-log.js'
24
24
  import { warn } from './paths.js'
25
+ import { GLOBAL_LEXICON_ID } from './lexicon.js'
26
+ import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
25
27
 
26
28
  const ENDPOINT = '/dsh-memu-memory'
27
29
 
@@ -132,12 +134,30 @@ async function authorizeGlobalReviewRoute(connection, req, endpoint, payload) {
132
134
  return authorizeWithCapability(connection, req, { libraryId: null, operation: 'review.manage', label: 'global review queue' })
133
135
  }
134
136
 
137
+ // The global lexicon (lib/lexicon.js GLOBAL_LEXICON_ID) is one shared store, not a
138
+ // library: like listGlobal and removeGlobalLink it is governed by the plugin's own
139
+ // HTTP boundary, so a standalone request never consults authorizeLibrary. A session
140
+ // id is still a credential — the conversation must exist, and the folder/session
141
+ // ceiling must still let it see the global layer, or there is no global lexicon to
142
+ // read or write from that conversation.
143
+ async function authorizeGlobalLexiconRoute(connection, req, endpoint, payload) {
144
+ if (payload?.sessionId === undefined) return true
145
+ if (typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) return false
146
+ const binding = getSessionBinding(payload.sessionId.trim())
147
+ if (!binding) return false
148
+ return effectiveScope(binding).useGlobal !== false
149
+ }
150
+
135
151
  async function authorizeLibraryRoute(connection, req, endpoint, payload, libraryId = routeLibraryId(endpoint, payload)) {
136
152
  // Review endpoints are dual-scope: without an explicit libraryId they address
137
153
  // the global curator queue, which follows its own management model.
138
154
  if ((endpoint === 'listReviews' || endpoint === 'resolveReview') && !String(payload?.libraryId || '').trim()) {
139
155
  return authorizeGlobalReviewRoute(connection, req, endpoint, payload)
140
156
  }
157
+ // The global lexicon is a reserved store name, not a private library: the host
158
+ // must never be asked to authorize a library that does not exist, and a bound
159
+ // session must not be denied for naming it instead of its own library.
160
+ if (libraryId === GLOBAL_LEXICON_ID) return authorizeGlobalLexiconRoute(connection, req, endpoint, payload)
141
161
  if (!LIBRARY_ROUTE_OPERATIONS.has(endpoint)) return true
142
162
  // Session-bound requests are checked first: a valid binding must name the exact
143
163
  // target library, and a present-but-unresolvable session is a bad credential
@@ -184,6 +204,7 @@ function globalGraphApi() {
184
204
  if (!globalGraphModulePromise) {
185
205
  globalGraphModulePromise = import('./global-graph.js').then((mod) => {
186
206
  if (typeof mod.removeGlobalLink !== 'function') throw new Error('removeGlobalLink not exported yet')
207
+ if (typeof mod.getGlobalGraph !== 'function') throw new Error('getGlobalGraph not exported yet')
187
208
  return mod
188
209
  }).catch((error) => {
189
210
  globalGraphModulePromise = null
@@ -195,8 +216,12 @@ function globalGraphApi() {
195
216
 
196
217
  // 词典 RPC 的库映射(§4.1):显式 libraryId 必须是已存在的库——不信任客户端任意
197
218
  // id——否则回落到会话绑定,与 case 'listReviews' 的入口模式一致。
219
+ // 全局词典是个保留存储名(lib/lexicon.js GLOBAL_LEXICON_ID),不是私有库,所以它
220
+ // 绕开 getLibrary 校验;带 sessionId 也不按会话的 useGlobal 收窄——那是注入的天花板,
221
+ // 不是用户维护共享词典的天花板。
198
222
  function lexiconLibraryId(payload) {
199
223
  const id = String(payload?.libraryId || '').trim()
224
+ if (id === GLOBAL_LEXICON_ID) return GLOBAL_LEXICON_ID
200
225
  if (id) {
201
226
  if (!getLibrary(id)) throw new Error('library not found')
202
227
  if (payload?.sessionId !== undefined) {
@@ -345,10 +370,14 @@ async function mergeLexiconImport(libraryId, member) {
345
370
  // List one library's memories. Retrieval needs the MemU engine, but the sidecar
346
371
  // index holds the same rows, so an engine that is still installing (or broken)
347
372
  // degrades to the index instead of failing the browser.
348
- async function privateListView(scope) {
373
+ async function privateListView(scope, { limit = null, previewChars = 4000 } = {}) {
349
374
  const libraryId = scope.libraryId ?? getSessionBinding(scope.exec ? scope.exec?.agent?.session?.header?.id : null)?.libraryId
350
- const shape = (id, e, content) => ({
375
+ const contentLimit = Math.max(40, Math.min(4000, Number(previewChars) || 4000))
376
+ const itemLimit = Number.isInteger(limit) && limit > 0 ? Math.min(500, limit) : null
377
+ const shape = (fileLibraryId, id, e, content, libraryName = null) => ({
351
378
  id,
379
+ libraryId: fileLibraryId,
380
+ ...(libraryName ? { libraryName } : {}),
352
381
  title: e?.title || '',
353
382
  layer: e?.layer || 'long_term',
354
383
  status: e?.status || 'active',
@@ -381,20 +410,22 @@ async function privateListView(scope) {
381
410
  emotionSource: e?.emotionSource ?? null,
382
411
  peak: e?.peak === true,
383
412
  salientDate: e?.salientDate || null,
384
- attachments: attachmentPreview(libraryId, e || {}),
413
+ attachments: attachmentPreview(fileLibraryId, e || {}),
385
414
  context: e?.context || {},
386
415
  accessCount: e?.accessCount ?? 0,
387
416
  lastAccessAt: e?.lastAccessAt || null,
388
417
  createdAt: e?.createdAt || null,
389
418
  updatedAt: e?.updatedAt || e?.createdAt || null,
390
- content: String(content ?? e?.content ?? '').slice(0, 4000),
419
+ content: String(content ?? e?.content ?? '').slice(0, contentLimit),
391
420
  })
392
421
  try {
393
422
  const result = await privateList({ ...scope, preferIndex: true })
423
+ const files = (result.files || []).map((f) => shape(f.libraryId || libraryId, f.name, f.entry, f.content, f.libraryName))
394
424
  return {
395
425
  libraryId: result.libraryId,
426
+ ...(result.libraries ? { libraries: result.libraries } : {}),
396
427
  source: result.source || 'engine',
397
- files: (result.files || []).map((f) => shape(f.name, f.entry, f.content)),
428
+ files: itemLimit ? files.slice(0, itemLimit) : files,
398
429
  }
399
430
  } catch (error) {
400
431
  if (error?.code !== 'MEMU_ENGINE_NOT_READY') throw error
@@ -402,7 +433,7 @@ async function privateListView(scope) {
402
433
  return {
403
434
  libraryId,
404
435
  source: 'index',
405
- files: Object.entries(index.entries || {}).filter(([, entry]) => !scope.exec || (isMemoryEligible(entry) && visibleToSession(entry, scope.exec?.agent?.session?.header?.id))).map(([id, e]) => shape(id, e)),
436
+ files: Object.entries(index.entries || {}).filter(([, entry]) => !scope.exec || (isMemoryEligible(entry) && visibleToSession(entry, scope.exec?.agent?.session?.header?.id))).map(([id, e]) => shape(libraryId, id, e)),
406
437
  }
407
438
  }
408
439
  }
@@ -590,9 +621,27 @@ async function sessionCatalog(ctx) {
590
621
  try {
591
622
  const records = (await sessionQuery.listSessions() || [])
592
623
  .filter((r) => r?.header?.origin !== 'subagent')
624
+ // `listSessions()` also returns conversations the user archived or whose
625
+ // workspace was removed from DSH: the session log survives both. The global
626
+ // curation picker must apply the same visibility rules as the folder sidebar,
627
+ // otherwise a deleted conversation stays selectable for extraction forever.
628
+ let archived = new Set()
629
+ let members = null
630
+ try {
631
+ const registry = ctx.get?.('workspaceRegistry')
632
+ archived = new Set((registry?.archivedSessionIds || []).map(String))
633
+ const union = new Set()
634
+ for (const workspace of registry?.list?.() || []) {
635
+ for (const id of workspace?.sessionIds || []) union.add(String(id))
636
+ }
637
+ // An empty registry means "no membership information", not "hide everything".
638
+ if (union.size > 0) members = union
639
+ } catch {}
593
640
  return {
594
641
  sessionQuery,
595
642
  byId: new Map(records.map((r) => [r.header.id, r])),
643
+ archived,
644
+ members,
596
645
  }
597
646
  } catch {
598
647
  return null
@@ -603,7 +652,14 @@ async function recentSessions(ctx, limitHint) {
603
652
  const catalog = await sessionCatalog(ctx)
604
653
  if (!catalog) return []
605
654
  const limit = Math.max(1, Math.min(200, Number(limitHint) || 60))
606
- const filtered = [...catalog.byId.values()].slice(0, limit)
655
+ const filtered = [...catalog.byId.values()]
656
+ .filter((r) => {
657
+ const id = String(r.header.id)
658
+ if (catalog.archived.has(id)) return false
659
+ if (catalog.members && !catalog.members.has(id)) return false
660
+ return true
661
+ })
662
+ .slice(0, limit)
607
663
  const titles = await readSessionTitles(catalog.sessionQuery, filtered.map((r) => r.header.id))
608
664
  return filtered.map((r) => ({
609
665
  id: r.header.id,
@@ -745,6 +801,51 @@ async function dispatch(ctx, endpoint, payload = {}) {
745
801
  }
746
802
  }
747
803
 
804
+ // The sidebar preview must follow the same cross-library scope as recall.
805
+ // `privateList` owns that rule (explicit library browsing stays single);
806
+ // the old local `preview(privateIndex)` only read the bound library.
807
+ let privatePreview = null
808
+ if (binding?.libraryId && effective?.useLibrary) {
809
+ if (getSettings().crossLibraryRecall === true) {
810
+ try {
811
+ const listed = await privateList({ exec: execFor(sessionId), preferIndex: true })
812
+ const rows = (listed.files || []).map((file) => {
813
+ const entry = file.entry || {}
814
+ const ownerId = file.libraryId || listed.libraryId
815
+ return {
816
+ id: file.name,
817
+ libraryId: ownerId,
818
+ libraryName: file.libraryName || getLibrary(ownerId)?.name || null,
819
+ title: entry.title || '',
820
+ layer: entry.layer || 'long_term',
821
+ status: entry.status || 'active',
822
+ domain: entry.domain || null,
823
+ openLoop: entry.openLoop === true,
824
+ marginalized: entry.marginalized === true,
825
+ source: entry.source || 'inferred',
826
+ marginalReason: entry.marginalReason || null,
827
+ unpinnedBy: entry.unpinnedBy || null,
828
+ confidence: entry.confidence,
829
+ createdAt: entry.createdAt || null,
830
+ updatedAt: entry.updatedAt || null,
831
+ decay: decayStrength(entry),
832
+ preview: String(entry.content || '').slice(0, previewChars),
833
+ entry,
834
+ }
835
+ }).sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')))
836
+ privatePreview = {
837
+ ...summarizeIndex({ entries: Object.fromEntries(rows.map((row, index) => [`${row.libraryId || 'x'}:${row.id}:${index}`, row.entry])) }),
838
+ crossLibrary: true,
839
+ shown: Math.min(rows.length, previewLimit),
840
+ items: rows.slice(0, previewLimit).map(({ entry, ...item }) => item),
841
+ }
842
+ } catch {
843
+ privatePreview = preview(privateIndex)
844
+ }
845
+ } else {
846
+ privatePreview = preview(privateIndex)
847
+ }
848
+ }
748
849
  return {
749
850
  binding: bindingView(binding),
750
851
  domain: binding ? domainOf(binding) : 'general',
@@ -756,7 +857,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
756
857
  // Only what the first screen paints. The conversation list and the
757
858
  // curation-job scan are what made opening the sidebar take seconds; the
758
859
  // list is fetched by `listSessions` when the Global tab is opened.
759
- private: binding?.libraryId && effective?.useLibrary ? preview(privateIndex) : null,
860
+ private: privatePreview,
760
861
  global: preview(effective?.useGlobal ? globalIndex : { entries: {} }, { domainFiltered: true }),
761
862
  domains: getPromptDomains(),
762
863
  sidebarSettings: getSettings().sidebarSettings === true,
@@ -869,8 +970,17 @@ async function dispatch(ctx, endpoint, payload = {}) {
869
970
  if (typeof payload?.[key] === 'boolean') patch[key] = payload[key]
870
971
  }
871
972
  // Turning the private switch on should make the folder usable immediately,
872
- // even if it never had a library. Turning it off leaves the existing one alone.
873
- if (patch.useLibrary === true) ensureLibraryForCwd(scopeKey)
973
+ // even if it never had a library. Also backfill conversations in this folder
974
+ // that already opted into private memory but were left without a library
975
+ // (they were created while the folder switch was off). Turning it off leaves
976
+ // the existing library and bindings alone.
977
+ if (patch.useLibrary === true) {
978
+ const library = ensureLibraryForCwd(scopeKey)
979
+ for (const [sessionId, binding] of Object.entries(loadState().sessions || {})) {
980
+ if (binding.libraryId || binding.useLibrary === false || normalizeCwd(binding.scopeKey) !== scopeKey) continue
981
+ setSessionBinding(sessionId, { libraryId: library.id, useLibrary: true })
982
+ }
983
+ }
874
984
  const policy = setWorkspacePolicy(scopeKey, patch)
875
985
  return { policy, folders: folderView(ctx).folders }
876
986
  }
@@ -881,7 +991,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
881
991
  case 'resetSettings': {
882
992
  const patch = {}
883
993
  for (const key of [
884
- 'autoInject', 'privateTopK', 'globalTopK', 'anchorTokens', 'turnTokens', 'injectionTotalTokens', 'dedupeTurns',
994
+ 'autoInject', 'privateTopK', 'globalTopK', 'crossLibraryRecall', 'anchorTokens', 'turnTokens', 'injectionTotalTokens', 'dedupeTurns',
885
995
  'globalEveryNTurns', 'minUserChars', 'mustRememberCap', 'randomCueChance',
886
996
  'autoInstallEngine', 'newSessionPromptDismissed', 'newSessionDefault', 'habitsInjection',
887
997
  'sleepConsolidation', 'sleepAfterIdleMinutes', 'autoCurateEveryHours',
@@ -900,7 +1010,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
900
1010
  case 'setSettings': {
901
1011
  const patch = payload?.patch && typeof payload.patch === 'object' ? payload.patch : {}
902
1012
  const allowed = new Set([
903
- 'autoInject', 'privateTopK', 'globalTopK', 'anchorTokens', 'turnTokens', 'injectionTotalTokens',
1013
+ 'autoInject', 'privateTopK', 'globalTopK', 'crossLibraryRecall', 'anchorTokens', 'turnTokens', 'injectionTotalTokens',
904
1014
  'relevanceThreshold', 'dedupeTurns', 'globalEveryNTurns', 'minUserChars',
905
1015
  // newSessionDefault has to be writable here: "remember my choice" stores
906
1016
  // it, and a dropped patch silently turned every remembered answer into
@@ -942,6 +1052,16 @@ async function dispatch(ctx, endpoint, payload = {}) {
942
1052
  delete patch.useGlobal
943
1053
  clamped.push({ field: 'useGlobal', reason: 'folder' })
944
1054
  }
1055
+ // Turning private memory on must also create/adopt the folder library. The
1056
+ // old path only flipped the switch, leaving libraryId null forever when the
1057
+ // conversation had been created while private memory was off.
1058
+ if (patch.useLibrary === true && before.scopeKey) {
1059
+ const current = before.libraryId ? getLibrary(before.libraryId) : null
1060
+ if (!current || current.archived === true) {
1061
+ const ensured = ensureLibraryForCwd(before.scopeKey)
1062
+ patch.libraryId = ensured.id
1063
+ }
1064
+ }
945
1065
  const binding = setSessionBinding(sessionId, patch)
946
1066
  return { binding: bindingView(binding), effective: effectiveScope(binding), clamped }
947
1067
  }
@@ -1036,7 +1156,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1036
1156
  const sessionId = requireSessionId(payload)
1037
1157
  const binding = getSessionBinding(sessionId)
1038
1158
  if (!binding) return { files: [] }
1039
- return privateListView({ exec: execFor(sessionId) })
1159
+ return privateListView({ exec: execFor(sessionId) }, {
1160
+ limit: payload?.limit,
1161
+ previewChars: payload?.previewChars,
1162
+ })
1040
1163
  }
1041
1164
  case 'browseLibrary': {
1042
1165
  const id = String(payload?.libraryId || '')
@@ -1240,6 +1363,13 @@ async function dispatch(ctx, endpoint, payload = {}) {
1240
1363
  return { items: items.slice(0, limit), total: items.length, libraries, errors }
1241
1364
  }
1242
1365
  case 'getGraph':
1366
+ // Reuse the private graph endpoint instead of adding a second read method:
1367
+ // the authorization map and RPC method count stay unchanged. Global edges
1368
+ // have no entity store, so the module is loaded lazily like unlink.
1369
+ if (payload?.scope === 'global') {
1370
+ const globalGraph = await globalGraphApi()
1371
+ return globalGraph.getGlobalGraph(payload || {})
1372
+ }
1243
1373
  return getGraph(payload || {})
1244
1374
  case 'listEntities':
1245
1375
  return listEntities(payload || {})
@@ -1417,6 +1547,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1417
1547
  const page = Math.min(pages, Math.max(1, Number(payload?.page) || 1))
1418
1548
  return {
1419
1549
  libraryId,
1550
+ scope: libraryId === GLOBAL_LEXICON_ID ? 'global' : 'private',
1420
1551
  version: data.version ?? null,
1421
1552
  items: filtered.slice((page - 1) * pageSize, page * pageSize).map(lexiconTermView),
1422
1553
  total,
@@ -1433,20 +1564,28 @@ async function dispatch(ctx, endpoint, payload = {}) {
1433
1564
  const query = String(payload?.q ?? payload?.query ?? '').trim()
1434
1565
  if (!query) throw new Error('q is required')
1435
1566
  // 会话路径带着该会话的 memoryContext 做可见过滤;设置页显式选库时是管理视角,
1436
- // 与 browseLibrary 一样不按场景收窄。归档词条只有管理面显式 includeArchived 才查;
1437
- // pending/rejected 由核心永远排除。
1567
+ // 与 browseLibrary 一样不按场景收窄,也**不**跨库——「我在查哪本词典」要有答案。
1568
+ // 没显式选库 = 会话视角,作用域与注入、与 memu_lexicon_search 同一条尺:
1569
+ // 当前库 + 全局词典 +(开了跨库开关时)同领域其它库(§8.15)。
1438
1570
  const binding = explicit ? null : getSessionBinding(requireSessionId(payload))
1439
1571
  const lexicon = await lexiconApi()
1440
- const hits = await lexicon.searchLexicon(
1441
- { libraryId, query, memoryContext: binding?.memoryContext || {} },
1442
- { includeArchived: payload?.includeArchived === true },
1443
- )
1572
+ const includeArchived = payload?.includeArchived === true
1573
+ const hits = binding
1574
+ ? (lexiconSources(binding).length
1575
+ ? lexiconSearch(binding, query, { includeArchived }).items
1576
+ : [])
1577
+ : await lexicon.searchLexicon(
1578
+ { libraryId, query, memoryContext: {} },
1579
+ { includeArchived },
1580
+ )
1444
1581
  return {
1445
1582
  libraryId,
1583
+ ...(binding ? { scope: 'session' } : {}),
1446
1584
  items: (Array.isArray(hits) ? hits : []).map((hit) => {
1447
1585
  const e = hit?.entry && typeof hit.entry === 'object' ? hit.entry : hit
1448
1586
  return {
1449
1587
  id: hit?.id || hit?.termId || null,
1588
+ ...(hit?.libraryId ? { libraryId: hit.libraryId, libraryName: hit.libraryName || null, lexiconScope: hit.lexiconScope || 'private' } : {}),
1450
1589
  term: e?.term,
1451
1590
  kind: e?.kind || 'term',
1452
1591
  meaning: String(e?.meaning || '').slice(0, 2000),
@@ -1470,6 +1609,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
1470
1609
  if (!kind) throw new Error('kind is required')
1471
1610
  if (!meaning) throw new Error('meaning is required')
1472
1611
  const lexicon = await lexiconApi()
1612
+ // 领域戳只打给私有库:全局词典是跨领域共享的词汇表,把它戳成当前领域就等于
1613
+ // 降级成某一次会话的私有词。没有会话上下文(standalone 管理面)也不戳。
1614
+ const stampDomain = libraryId !== GLOBAL_LEXICON_ID && typeof payload?.sessionId === 'string' && payload.sessionId.trim()
1615
+ ? domainOf(getSessionBinding(requireSessionId(payload)))
1616
+ : null
1473
1617
  const result = await lexicon.upsertLexiconTerm({
1474
1618
  libraryId,
1475
1619
  term,
@@ -1484,6 +1628,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1484
1628
  sensitivity: payload?.sensitivity,
1485
1629
  confidence: payload?.confidence,
1486
1630
  evidence: payload?.evidence,
1631
+ ...(stampDomain ? { domain: stampDomain } : {}),
1487
1632
  // 面板/管理入口是"用户"来源,直接落 active;敏感字段校验在核心层。
1488
1633
  source: 'user',
1489
1634
  status: 'active',
@@ -1599,6 +1744,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1599
1744
  case 'setup': {
1600
1745
  const status = engineStatus()
1601
1746
  if (status.status !== 'installing') {
1747
+ // A reinstall may replace the venv the resident interpreter is running from;
1748
+ // stop it first so Windows can rename/delete the old engine directory.
1749
+ closeMemuResident()
1602
1750
  void ensureEngine({ force: payload?.force === true, beforeSwitch: backupDatabases }).catch(() => {})
1603
1751
  }
1604
1752
  return { started: true, engine: engineView() }
@@ -1606,6 +1754,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1606
1754
  case 'switchEngine': {
1607
1755
  const version = String(payload?.version || '')
1608
1756
  if (!version) throw new Error('version is required')
1757
+ closeMemuResident()
1609
1758
  const result = await switchEngineVersion(version, {
1610
1759
  beforeSwitch: backupDatabases,
1611
1760
  force: payload?.force === true,
@@ -1668,8 +1817,14 @@ async function dispatch(ctx, endpoint, payload = {}) {
1668
1817
  }
1669
1818
  case 'getMemuConfig':
1670
1819
  return getMemuConfig()
1671
- case 'setEmbeddingSource':
1672
- return setEmbeddingSource(String(payload?.source || ''))
1820
+ case 'setEmbeddingSource': {
1821
+ const config = setEmbeddingSource(String(payload?.source || ''))
1822
+ // Local mode is the resident route: warm it as soon as the switch flips, and
1823
+ // release it when the user goes back to the remote API route.
1824
+ if (config?.source === 'local') void prewarmMemuResident()
1825
+ else closeMemuResident()
1826
+ return config
1827
+ }
1673
1828
  case 'saveMemuConfig':
1674
1829
  return saveMemuConfig({
1675
1830
  provider: payload?.provider,
@@ -1698,7 +1853,12 @@ async function dispatch(ctx, endpoint, payload = {}) {
1698
1853
  case 'selectLocalVectorModel':
1699
1854
  return selectLocalVectorModel(String(payload?.id || ''))
1700
1855
  case 'installLocalVectorRuntime':
1701
- return await installLocalVectorRuntime({ modelId: payload?.id || null, confirmed: payload?.confirmed === true })
1856
+ return await installLocalVectorRuntime({
1857
+ modelId: payload?.id || null,
1858
+ confirmed: payload?.confirmed === true,
1859
+ source: payload?.source || null,
1860
+ action: payload?.action || 'start',
1861
+ })
1702
1862
  case 'switchLocalVectorProfile':
1703
1863
  if (payload?.confirmed !== true) throw new Error('switching the local vector profile requires explicit confirmation')
1704
1864
  return await switchLocalVectorProfile({ id: payload?.id })
@@ -13,7 +13,7 @@
13
13
  // 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
14
14
  //
15
15
  // 返回值有两种形状,调用方要同时接受:
16
- // - 整个 pass 没跑:`{ skipped: '<off|service|timezone|time>' }`
16
+ // - 整个 pass 没跑:`{ skipped: '<off|service|schedule-api|timezone|time>' }`
17
17
  // - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
18
18
  import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
19
19
  import {
@@ -38,9 +38,32 @@ const KNOWN_CODES = [
38
38
 
39
39
  // "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
40
40
  let serviceWarned = false
41
+ // 0.2.0/0.2.1 的 schedule 是会话级 API;本 pass 用的是 0.2.2 起的宿主级任务表。
42
+ // 这是能力差异,不是每次 sweep 的故障,同样只提醒一次。
43
+ let sessionScopedWarned = false
41
44
  // 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
42
45
  let zoneWarnedFor = null
43
46
 
47
+ /**
48
+ * Which schedule API a host exposes.
49
+ *
50
+ * - `global`: 0.2.2+ creates a host-wide task from one request
51
+ * (`create(request)`, `list(request) -> { items }`, `edit({ id, action })`).
52
+ * - `session`: 0.2.0/0.2.1 binds every reminder to one session
53
+ * (`create(sessionId, request)`, `list({ sessionId }) -> array`, `delete({ sessionId, id })`).
54
+ *
55
+ * The pass only implements the host-wide shape. Probing structurally (instead of
56
+ * comparing versions) keeps this working when a host backports or renames the
57
+ * service, and lets an old host skip with one readable line instead of failing
58
+ * the same `list` call every sweep.
59
+ */
60
+ export function scheduleFlavor(schedule) {
61
+ if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') return null
62
+ if (typeof schedule.edit === 'function') return 'global'
63
+ if (typeof schedule.delete === 'function') return 'session'
64
+ return null
65
+ }
66
+
44
67
  function pad2(value) {
45
68
  return String(value).padStart(2, '0')
46
69
  }
@@ -218,7 +241,8 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
218
241
 
219
242
  let schedule = null
220
243
  try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
221
- if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') {
244
+ const flavor = scheduleFlavor(schedule)
245
+ if (flavor === null) {
222
246
  if (!serviceWarned) {
223
247
  serviceWarned = true
224
248
  notify('salient wake is enabled but this host exposes no schedule service; skipping')
@@ -230,6 +254,18 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
230
254
  }
231
255
  return { skipped: 'service' }
232
256
  }
257
+ if (flavor === 'session') {
258
+ if (!sessionScopedWarned) {
259
+ sessionScopedWarned = true
260
+ notify('salient wake needs the host-wide schedule API (0.2.2+); this host exposes session-scoped reminders, skipping')
261
+ record({
262
+ kind: 'wake', level: 'warn', ok: false,
263
+ message: '日期唤醒需要宿主级 schedule API(0.2.2+);当前宿主只有会话级提醒,本轮跳过',
264
+ detail: { trigger: 'wake', stage: 'schedule-api' },
265
+ })
266
+ }
267
+ return { skipped: 'schedule-api' }
268
+ }
233
269
 
234
270
  const when = now instanceof Date ? now : new Date(now)
235
271
  if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
package/lib/state.js CHANGED
@@ -35,6 +35,10 @@ export const DEFAULT_SETTINGS = {
35
35
  // are small, and the windows that stop repetition are measured in many turns.
36
36
  privateTopK: 5,
37
37
  globalTopK: 5,
38
+ // Cross-library recall: merge private candidates from other libraries that use
39
+ // the same memory domain. Reading across folders changes the isolation boundary,
40
+ // so it is opt-in; writes still target the bound library only.
41
+ crossLibraryRecall: false,
38
42
  anchorTokens: 800,
39
43
  // 800 tokens for one recall block. A dense chat calls recall on almost every
40
44
  // message, so the injected block has to stay clearly smaller than the message it
@@ -95,11 +99,9 @@ export const DEFAULT_SETTINGS = {
95
99
  // These stay ordinary switches, and an existing saved choice is preserved.
96
100
  sleepConsolidation: true,
97
101
  // Group chat arrives in bursts, but a burst is seconds apart and the per-turn
98
- // timestamps already cover that. Three idle minutes is long enough that an
99
- // ordinary pause (reading a diff, thinking about the next question) is not
100
- // "gone", and short enough that a conversation which ended gets tidied in the
101
- // same sitting instead of waiting for a quiet hour that may never arrive.
102
- sleepAfterIdleMinutes: 3,
102
+ // timestamps already cover that. Two idle minutes still separates "reading a
103
+ // diff / thinking" from "gone", and keeps the per-run window small.
104
+ sleepAfterIdleMinutes: 2,
103
105
  // 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
104
106
  // 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
105
107
  activeMemoryMinScore: 0.8,
package/lib/tools.js CHANGED
@@ -11,6 +11,7 @@ import { linkEntries, createEntity, listEntities, updateRelationship } from './g
11
11
  import { normalizeEntityName } from './private-links.js'
12
12
  import { autoLinkPrivateMemories } from './private-links.js'
13
13
  import { getSettings, listLibraries, getLibrary, loadPrivateIndex, loadGlobalIndex, storageHealth, syncActivity } from './state.js'
14
+ import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
14
15
 
15
16
  function text(value) {
16
17
  return String(value ?? '')
@@ -130,6 +131,12 @@ function formatPrivateItem(item, index, options = {}) {
130
131
  if (when) lines.push(` updated=${when}`)
131
132
  if (entry.disclosure && entry.disclosure !== 'can_tell') lines.push(` disclosure=${entry.disclosure}`)
132
133
  if (entry.owner && entry.owner !== 'me') lines.push(` owner=${entry.owner}`)
134
+ // Cross-library recall is read-only: the id is real, but updates/archives
135
+ // still resolve against the bound library. Say where it lives so the model
136
+ // does not treat "unknown memory" as "it was deleted".
137
+ if (options.homeLibraryId && item.libraryId && item.libraryId !== options.homeLibraryId) {
138
+ lines.push(` library=${item.libraryId}(跨库只读;写入仍落在当前库)`)
139
+ }
133
140
  if (entry.visibility && entry.visibility !== 'shared') {
134
141
  // 'secret' is a presentation rule, not a lock: it stays out of the prompt and out of
135
142
  // automatic recall, but anyone in the same folder can still pull it up on purpose.
@@ -371,16 +378,17 @@ export function registerTools(ctx, { only = null } = {}) {
371
378
  const warning = (result.errors || []).length ? `\n注意:本次召回已降级:${(result.errors || []).join('; ')}` : ''
372
379
  // Read-only: never materialize a binding/library from a recall header.
373
380
  const binding = peekBinding(exec)
374
- const header = `私有记忆(library=${binding?.libraryId || '?'}, domain=${domainOf(binding)})`
381
+ const foreign = (result.libraries || []).filter((id) => id !== binding?.libraryId)
382
+ const header = `私有记忆(library=${binding?.libraryId || '?'}, domain=${domainOf(binding)}${foreign.length ? `,跨库=${foreign.join(',')}` : ''})`
375
383
  if (!result.files?.length) return `${header}\n没有命中。${warning}`
376
- return [header, ...result.files.map((f, i) => formatPrivateItem(f, i + 1, { query: args.query }))].join('\n\n') + warning
384
+ return [header, ...result.files.map((f, i) => formatPrivateItem(f, i + 1, { query: args.query, homeLibraryId: binding?.libraryId || null }))].join('\n\n') + warning
377
385
  },
378
386
  { isConcurrencySafe: () => true },
379
387
  ))
380
388
 
381
389
  tools.push(toolBase(
382
390
  'memu_private_list',
383
- 'List private memory metadata for the library bound to this conversation. Does not return full bodies.',
391
+ 'List private memory metadata for the library bound to this conversation. When cross-library recall is on, same-domain libraries are included too. Does not return full bodies.',
384
392
  {},
385
393
  async (_args, exec) => {
386
394
  // A list is a pure read: if the conversation has no binding yet, say so
@@ -388,12 +396,17 @@ export function registerTools(ctx, { only = null } = {}) {
388
396
  if (!peekBinding(exec)?.libraryId) return '当前对话没有绑定记忆库。'
389
397
  const result = await privateList({ exec })
390
398
  const warning = result.warning ? `\n注意:${result.warning}` : ''
391
- if (!result.files?.length) return `私有记忆库 ${result.libraryId} 为空。${warning}`
392
- const lines = [`私有记忆库 ${result.libraryId}(${result.files.length} 条)`]
399
+ const foreign = (result.libraries || []).filter((library) => library.id !== result.libraryId)
400
+ const scopeNote = foreign.length ? `,跨库=${foreign.map((library) => library.name || library.id).join(',')}` : ''
401
+ if (!result.files?.length) return `私有记忆库 ${result.libraryId} 为空${scopeNote}。${warning}`
402
+ const lines = [`私有记忆库 ${result.libraryId}(${result.files.length} 条${scopeNote})`]
393
403
  for (const file of result.files) {
394
404
  const e = file.entry || {}
395
405
  const tag = salientTag(e)
396
- lines.push(`- [${file.name}] ${e.title || file.description || '(untitled)'} · ${e.layer || 'long_term'} · ${e.status || 'active'}${e.marginalized ? ' · marginalized' : ''}${tag ? ` · ${tag}` : ''}`)
406
+ const owner = file.libraryId && file.libraryId !== result.libraryId
407
+ ? ` · lib=${file.libraryName || file.libraryId}`
408
+ : ''
409
+ lines.push(`- [${file.name}] ${e.title || file.description || '(untitled)'} · ${e.layer || 'long_term'} · ${e.status || 'active'}${e.marginalized ? ' · marginalized' : ''}${tag ? ` · ${tag}` : ''}${owner}`)
397
410
  }
398
411
  return lines.join('\n') + warning
399
412
  },
@@ -474,7 +487,7 @@ export function registerTools(ctx, { only = null } = {}) {
474
487
 
475
488
  tools.push(toolBase(
476
489
  'memu_lexicon_search',
477
- 'Search the ACTIVE lexicon (user-coined slang, memes, triggers and terms) of the library bound to this conversation; archived entries are excluded. Read-only. When a user-coined word or phrase appears and you are not sure what it means, look it up here before asking or guessing; returns term → meaning/usage with short evidence.',
490
+ 'Search the ACTIVE lexicon (user-coined slang, memes, triggers and terms) this conversation can see: the bound library plus the global lexicon, and — when cross-library recall is on — other same-domain libraries; archived entries are excluded. Read-only. When a user-coined word or phrase appears and you are not sure what it means, look it up here before asking or guessing; returns term → meaning/usage with short evidence. Hits from outside the bound library are read-only: writing still lands in the bound library.',
478
491
  {
479
492
  query: { type: 'string', required: true, description: 'The word or phrase to look up. Exact term/alias match first with a bounded fuzzy fallback; short queries work best.' },
480
493
  },
@@ -483,25 +496,33 @@ export function registerTools(ctx, { only = null } = {}) {
483
496
  // same rule as memu_private_recall.
484
497
  const binding = peekBinding(exec)
485
498
  if (!binding?.libraryId) return '当前对话没有绑定记忆库,无法查询词典。请先初始化或绑定记忆库。'
486
- const lexicon = await lexiconApi()
487
- const hits = await lexicon.searchLexicon(
488
- { libraryId: binding.libraryId, query: String(args.query || ''), memoryContext: binding.memoryContext || {} },
489
- { includeArchived: false },
490
- )
491
- const rows = (Array.isArray(hits) ? hits : []).map((hit) => (hit?.entry && typeof hit.entry === 'object' ? hit.entry : hit))
492
- if (!rows.length) return `词典(library=${binding.libraryId})没有命中「${truncate(args.query, 80)}」。`
493
- const lines = [`词典命中(library=${binding.libraryId},${rows.length} 条)`]
494
- for (const [index, e] of rows.entries()) {
499
+ const { items, errors } = lexiconSearch(binding, String(args.query || ''))
500
+ const warning = errors.length ? `\n注意:本次词典查询已降级:${errors.join('; ')}` : ''
501
+ // 作用域头:当前库 + 全局(+ 开关打开时的同域库)。同词面只留优先级最高的一份
502
+ // (lexicon-scope 的源序:当前库 → 同域库 → 全局)。
503
+ const foreign = lexiconSources(binding).filter((source) => !source.primary && source.scope === 'private')
504
+ const scopeSuffix = foreign.length ? `,跨库=${foreign.map((source) => source.name || source.libraryId).join(',')}` : ''
505
+ const scopeLabel = `library=${binding.libraryId} + 全局${scopeSuffix}`
506
+ if (!items.length) return `词典(${scopeLabel})没有命中「${truncate(args.query, 80)}」。${warning}`
507
+ const lines = [`词典命中(${scopeLabel},${items.length} 条)`]
508
+ for (const [index, hit] of items.entries()) {
509
+ const e = hit?.entry && typeof hit.entry === 'object' ? hit.entry : hit
495
510
  const evidence = (Array.isArray(e.evidence) ? e.evidence : []).slice(0, 2)
496
511
  .map((item) => String(item?.quote || item?.id || '')).filter(Boolean).join(' / ')
512
+ const home = hit.lexiconScope === 'global'
513
+ ? ' home=全局词典(只读;写入仍落在当前库)'
514
+ : hit.libraryId && hit.libraryId !== binding.libraryId
515
+ ? ` home=${hit.libraryName || hit.libraryId}(跨库只读;写入仍落在当前库)`
516
+ : ''
497
517
  lines.push([
498
518
  `${index + 1}. [${e.term || '?'}] kind=${e.kind || 'term'} status=${e.status || 'active'}`,
519
+ home,
499
520
  ` meaning=${truncate(e.meaning, 300)}`,
500
521
  e.usage ? ` usage=${truncate(e.usage, 200)}` : '',
501
522
  evidence ? ` evidence=${truncate(evidence, 200)}` : '',
502
523
  ].filter(Boolean).join('\n'))
503
524
  }
504
- return lines.join('\n')
525
+ return lines.join('\n') + warning
505
526
  },
506
527
  { isConcurrencySafe: () => true },
507
528
  ))
@@ -535,6 +556,8 @@ export function registerTools(ctx, { only = null } = {}) {
535
556
  examples: args.examples,
536
557
  // 词条继承当前会话的场景身份;没有场景就是空 context(全场景可见)。
537
558
  context: binding.memoryContext || {},
559
+ // 领域戳:跨库召回判「同域」靠它(§8.15),与 privateRemember 同一口径。
560
+ domain: domainOf(binding),
538
561
  evidence: args.evidence,
539
562
  confidence: args.confidence,
540
563
  // 来源固定 model-proposal;普通词条直接 active(§2.1),sensitive trigger 由