dsh-memu-memory 1.4.1 → 1.4.2

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.
package/lib/memory.js CHANGED
@@ -565,6 +565,8 @@ export function resolveLibrary({ exec, libraryId, readOnly = false }) {
565
565
  const binding = peekBinding(exec)
566
566
  if (sessionIdOf(exec) && (!binding || binding.libraryId !== id)) throw new Error('library is not bound to this conversation')
567
567
  if (binding) assertScopeEnabled(binding)
568
+ // 无会话调用没有 binding:退到库所属文件夹的策略,同类判据一处不漏。
569
+ else assertLibraryEnabled(lib)
568
570
  return { libraryId: lib.id, binding }
569
571
  }
570
572
  const binding = readOnly ? peekBinding(exec) : bindingFor(exec)
@@ -608,6 +610,18 @@ function assertScopeEnabled(binding, { layer = 'library' } = {}) {
608
610
  }
609
611
  }
610
612
 
613
+ /**
614
+ * 无会话调用(MCP server / 脚本)没有 binding 可查,退到库所属文件夹的策略。
615
+ * 用户在设置里关掉的库,不能因为「调用方没有会话」就重新打开——否则同一份数据
616
+ * 在宿主里被禁、换个入口又能写。
617
+ */
618
+ function assertLibraryEnabled(lib) {
619
+ if (!lib) return
620
+ if (getWorkspacePolicy(lib.scopeKey)?.useLibrary === false) {
621
+ throw new Error('private memory is disabled for this folder; enable it in Settings → Folders first')
622
+ }
623
+ }
624
+
611
625
  function clampText(text, max) {
612
626
  const s = String(text || '')
613
627
  return s.length > max ? s.slice(0, max) : s
@@ -2859,17 +2873,30 @@ export function readMemoryByRef({ exec, scope = 'private', id, libraryId = null,
2859
2873
  }
2860
2874
  }
2861
2875
 
2862
- export async function privateRecall({ exec, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
2876
+ export async function privateRecall({ exec, libraryId: explicitLibraryId, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
2863
2877
  const binding = peekBinding(exec)
2864
- if (!binding) throw new Error('no bound session')
2865
- if (!binding.libraryId) throw new Error('this conversation has no memory library')
2878
+ // 绑定是会话级的:没有会话就没有默认库,必须显式给 libraryId。这条口子是给
2879
+ // 无宿主调用方(MCP server / 脚本 / 移植适配器)留的,宿主内的行为一字不变。
2880
+ if (!binding && !explicitLibraryId) throw new Error('no bound session')
2881
+ // scope 是下游唯一的取数口径:有会话时就是原 binding(逐字等价),无会话时是
2882
+ // 只带库的最小只读 scope——跨库聚合、情绪、场景时间都退回中性值。
2883
+ const scope = binding ?? { libraryId: String(explicitLibraryId), sceneTime: null, mood: null, memoryOwnerSessionId: null }
2884
+ if (!scope.libraryId) throw new Error('this conversation has no memory library')
2866
2885
  assertScopeEnabled(binding)
2886
+ // 无会话路径没有 binding 可校验,必须自己确认库存在、且没有被文件夹策略关掉:
2887
+ // 否则一个拼错的 libraryId 会静默返回空结果(loadPrivateIndex 对未知库给空索引),
2888
+ // 既违反「召回为空必须留信号」,也绕过了用户在设置里关掉的那个开关。
2889
+ if (!binding) {
2890
+ const library = getLibrary(scope.libraryId)
2891
+ if (!library) throw new Error(`unknown library: ${scope.libraryId}`)
2892
+ assertLibraryEnabled(library)
2893
+ }
2867
2894
  const settings = getSettings()
2868
2895
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
2869
2896
  const byId = /^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())
2870
2897
  // S1:相对日期在召回前先落到绝对日期;sceneTime 是这一轮的逻辑时间。
2871
2898
  // S5:同一处识别意图并抽取日期/实体,意图决定候选数与过滤策略。
2872
- const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
2899
+ const sceneAt = Number.isFinite(Date.parse(scope.sceneTime || '')) ? new Date(scope.sceneTime) : new Date()
2873
2900
  const recallIntent = detectQueryIntent(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2874
2901
  const decomposed = decomposeQuery(query, recallIntent, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2875
2902
  const queryDates = decomposed.dates
@@ -2878,10 +2905,11 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2878
2905
  const requested = Math.max(1, Math.min(20, Math.floor(Number(topK ?? settings.privateTopK) || 5)))
2879
2906
  let candidateK = intentTopK(recallIntent, requested)
2880
2907
  const wanted = requested
2881
- const domain = domainOf(binding)
2882
- const sources = (settings.crossLibraryRecall === true
2908
+ const domain = domainOf(scope)
2909
+ // 跨库聚合只对会话成立:无会话时只读显式指定的那一个库(最小权限)。
2910
+ const sources = (binding && settings.crossLibraryRecall === true
2883
2911
  ? crossLibrarySources(binding, domain)
2884
- : [{ libraryId: binding.libraryId, primary: true }])
2912
+ : [{ libraryId: scope.libraryId, primary: true }])
2885
2913
  .map((source) => ({ ...source, index: loadPrivateIndex(source.libraryId) }))
2886
2914
  if (purpose === 'automatic') {
2887
2915
  const allowed = new Set(sources.map(source => source.libraryId))
@@ -2904,10 +2932,12 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2904
2932
  disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) })
2905
2933
  const retrievalMs = performance.now() - retrievalStarted
2906
2934
  const current = peekBinding(exec)
2907
- if (!current || current.libraryId !== binding.libraryId || scopeGenerationOf(current) !== generationAtStart) throw new Error('memory scope changed during recall; retry')
2935
+ // 无会话没有「中途换库」这回事(scope 是调用方给的常量),跳过这轮校验;
2936
+ // 有会话时保持原来的并发守卫。
2937
+ if (binding && (!current || current.libraryId !== scope.libraryId || scopeGenerationOf(current) !== generationAtStart)) throw new Error('memory scope changed during recall; retry')
2908
2938
  assertScopeEnabled(current)
2909
- const index = loadPrivateIndex(binding.libraryId)
2910
- const indexByLibrary = new Map(sources.map((source) => [source.libraryId, source.libraryId === binding.libraryId ? index : domainScopedIndex(source.index, domain)]))
2939
+ const index = loadPrivateIndex(scope.libraryId)
2940
+ const indexByLibrary = new Map(sources.map((source) => [source.libraryId, source.libraryId === scope.libraryId ? index : domainScopedIndex(source.index, domain)]))
2911
2941
  // enrichFiles fills body/strength from one index; doing that against the bound
2912
2942
  // library would blank every foreign hit. Cross-library files already carry
2913
2943
  // their entry from the library that produced them.
@@ -2927,9 +2957,9 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2927
2957
  if (result?.fusion) enriched.fusion = result.fusion
2928
2958
  if (result?.libraries) enriched.libraries = result.libraries.slice()
2929
2959
  const span = createdAtSpan(sources.flatMap((source) => Object.values(
2930
- (source.libraryId === binding.libraryId ? index : source.index).entries || {},
2960
+ (source.libraryId === scope.libraryId ? index : source.index).entries || {},
2931
2961
  ).map((entry) => ({ entry }))))
2932
- const mood = moodDecay(binding.mood)
2962
+ const mood = moodDecay(scope.mood)
2933
2963
  const canRead = entry => isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, memorySessionId(exec))
2934
2964
  && isDisclosureEligible(entry, { automatic: true, asked: recallIntent === 'boundary' })
2935
2965
  const scored = privateWeighted(enriched, wanted, {
@@ -2953,7 +2983,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2953
2983
  sessionId: memorySessionId(exec),
2954
2984
  automatic: purpose === 'automatic', excludedRefs, indexesByLibrary: indexByLibrary, canRead,
2955
2985
  })
2956
- const paired = new Set(scored.files.map(file => JSON.stringify([file.libraryId || binding.libraryId, file.name])))
2986
+ const paired = new Set(scored.files.map(file => JSON.stringify([file.libraryId || scope.libraryId, file.name])))
2957
2987
  const groupsByKey = new Map((scored.groups || []).map(group => [group.key, group]))
2958
2988
  const conflictPairs = []
2959
2989
  const pairKeys = new Set()
@@ -2961,7 +2991,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2961
2991
  const group = groupsByKey.get(file.groupKey)
2962
2992
  const otherId = file.entry?.conflicts_with || (group?.conflict ? group.files.find(other => other.name !== file.name)?.name : null)
2963
2993
  if (!otherId) continue
2964
- const owner = file.libraryId || binding.libraryId
2994
+ const owner = file.libraryId || scope.libraryId
2965
2995
  file.conflictPair = otherId
2966
2996
  file.conflictComplete = group ? group.complete : otherId !== file.name && paired.has(JSON.stringify([owner, otherId]))
2967
2997
  if (!file.conflictComplete) continue
@@ -2976,7 +3006,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2976
3006
  // cross-library recall touches the owning index, not the bound one.
2977
3007
  const recalledByLibrary = new Map()
2978
3008
  for (const file of scored.files || []) {
2979
- const libraryId = file.libraryId || binding.libraryId
3009
+ const libraryId = file.libraryId || scope.libraryId
2980
3010
  if (!recalledByLibrary.has(libraryId)) recalledByLibrary.set(libraryId, [])
2981
3011
  recalledByLibrary.get(libraryId).push(file.name)
2982
3012
  }
@@ -2993,14 +3023,14 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2993
3023
  kind: 'recall',
2994
3024
  scope: 'private',
2995
3025
  sessionId: memorySessionId(exec),
2996
- libraryId: binding.libraryId,
3026
+ libraryId: scope.libraryId,
2997
3027
  message: `去重折叠 ${folded} 条候选(${scored.dedup.clusterCount} 簇)`,
2998
3028
  detail: { collapsed: scored.dedup.collapsed, clusterCount: scored.dedup.clusterCount },
2999
3029
  refs: scored.dedup.collapsed.map((group) => group.kept).slice(0, 20),
3000
3030
  })
3001
3031
  }
3002
3032
  for (const file of scored.files || []) {
3003
- const fileLibraryId = file.libraryId || binding.libraryId
3033
+ const fileLibraryId = file.libraryId || scope.libraryId
3004
3034
  const fileIndex = indexByLibrary.get(fileLibraryId) || index
3005
3035
  file.ref ??= memoryRef({ scope: 'private', libraryId: fileLibraryId, id: file.name, entry: file.entry })
3006
3036
  if (file.entry?.attachments?.length) {
@@ -3026,7 +3056,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
3026
3056
  const conflictAddedRows = Math.max(0, scored.files.length - rankingSelectedRows)
3027
3057
  const expansionRoom = Math.max(0, Number(wanted) - (scored.groups?.length ?? scored.files.length))
3028
3058
  const expansionLimit = Math.min(recallIntent === 'entity' ? 3 : 2, expansionRoom)
3029
- const knownIds = new Set(scored.files.map(file => JSON.stringify([file.libraryId || binding.libraryId, file.name])))
3059
+ const knownIds = new Set(scored.files.map(file => JSON.stringify([file.libraryId || scope.libraryId, file.name])))
3030
3060
  const expanded = []
3031
3061
  let expandedGroups = 0
3032
3062
  // One hop is a guess: "the query hit this, and this is linked to it". A relation
@@ -3040,7 +3070,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
3040
3070
  const collected = new Set()
3041
3071
  for (const file of scored.files) {
3042
3072
  for (const link of file.related || []) {
3043
- const libraryId = file.libraryId || binding.libraryId
3073
+ const libraryId = file.libraryId || scope.libraryId
3044
3074
  const key = JSON.stringify([libraryId, link?.id])
3045
3075
  if (!link?.id || link.missing || link.kind === 'conflict' || knownIds.has(key) || collected.has(key)) continue
3046
3076
  if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
@@ -3073,7 +3103,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
3073
3103
  for (const file of scored.files.slice()) {
3074
3104
  if (expanded.length >= expansionLimit) break
3075
3105
  for (const link of file.related || []) {
3076
- const fileLibraryId = file.libraryId || binding.libraryId
3106
+ const fileLibraryId = file.libraryId || scope.libraryId
3077
3107
  const ref = JSON.stringify([fileLibraryId, link?.id])
3078
3108
  if (!link?.id || link.missing || link.kind === 'conflict' || knownIds.has(ref)) continue
3079
3109
  if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
@@ -3101,7 +3131,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
3101
3131
  scored.trace.counts.expandedGroups = expandedGroups
3102
3132
  scored.trace.counts.selectedRows = scored.files.length
3103
3133
  if (scored.groups) scored.trace.counts.selectedGroups = scored.groups.length
3104
- for (const file of scored.files) file.ref ??= memoryRef({ scope: 'private', libraryId: file.libraryId || binding.libraryId, id: file.name, entry: file.entry })
3134
+ for (const file of scored.files) file.ref ??= memoryRef({ scope: 'private', libraryId: file.libraryId || scope.libraryId, id: file.name, entry: file.entry })
3105
3135
  scored.refs = scored.files.map(file => file.ref)
3106
3136
  return scored
3107
3137
  }
@@ -0,0 +1,82 @@
1
+ // 移植适配器的稳定入口(`package.json` exports: "./port")。
2
+ //
3
+ // 为什么单独一个文件:MCP server / 脚本 / 其它宿主只需要「工具规格 + 记忆读写 +
4
+ // 库与索引」,不该为了这三样去读 tools.js 里三十段内联闭包,也不该依赖
5
+ // lib/index.js——那是宿主插件入口,注册的是 ctx 服务、注入钩子和 RPC。
6
+ //
7
+ // 无会话调用方(MCP server、CLI):
8
+ // const specs = collectToolSpecs() // 30 个 { name, description, parameters, execute }
9
+ // await privateRecall({ libraryId, query, topK }) // 显式库,不需要会话
10
+ // await privateRemember({ libraryId, content, title })
11
+ // listLibraries() / loadPrivateIndex(libraryId)
12
+ //
13
+ // 有会话调用方照旧传 exec({ agent: { session: { header: { id, cwd } } } }),行为与
14
+ // 插件内部完全一致。
15
+ //
16
+ // 两条必须知道的边界(都是刻意的):
17
+ // 1. 无会话的 privateRecall 只读显式指定的那个库:跨库聚合、情绪、场景时间全部
18
+ // 退回中性值(见 lib/memory.js 里 scope 的注释)。要跨库请自己按库循环。
19
+ // 2. 没有会话就没有 memoryContext,所以带 channelId/characterId 等边界的记忆对
20
+ // 无会话调用方不可见(context.js 的 contextVisible)。这是安全默认,不是 bug。
21
+ //
22
+ // 本文件只做 re-export,不含逻辑;不要在这里加会改变内部状态的东西。
23
+ // 例外只有 toInputSchema:它是纯函数,存在的唯一目的是把宿主 schema 方言翻译成
24
+ // MCP / JSON Schema,避免每个适配器各写一遍、各错一遍。
25
+
26
+ export { collectToolSpecs } from './tools.js'
27
+
28
+ /**
29
+ * 把宿主值 schema 方言的「属性映射」转成标准 JSON Schema 的 object 节点。
30
+ *
31
+ * 两者只差一处:宿主把必填写成属性上的 `required: true`,JSON Schema 要求父级
32
+ * `required: [...]`。其余键(type/description/title/default/examples/enum/const/
33
+ * properties/additionalProperties/items)语义一致,原样保留。
34
+ *
35
+ * @param {object} parameters `collectToolSpecs()` 里某个工具的 `parameters`
36
+ * @returns {{type:'object', properties:object, required?:string[]}}
37
+ */
38
+ export function toInputSchema(parameters) {
39
+ const { properties, required } = convertProperties(parameters || {})
40
+ return { type: 'object', properties, ...(required.length ? { required } : {}) }
41
+ }
42
+
43
+ function convertProperties(map) {
44
+ const properties = {}
45
+ const required = []
46
+ for (const [key, spec] of Object.entries(map || {})) {
47
+ if (!spec || typeof spec !== 'object') { properties[key] = spec; continue }
48
+ const { required: isRequired, ...rest } = spec
49
+ properties[key] = convertNode(rest)
50
+ if (isRequired === true) required.push(key)
51
+ }
52
+ return { properties, required }
53
+ }
54
+
55
+ function convertNode(node) {
56
+ if (Array.isArray(node)) return node.map(convertNode)
57
+ if (!node || typeof node !== 'object') return node
58
+ const out = {}
59
+ for (const [key, value] of Object.entries(node)) {
60
+ // 嵌套属性映射同样把 required 提到该层 object 上。
61
+ if (key === 'properties' && value && typeof value === 'object' && !Array.isArray(value)) {
62
+ const nested = convertProperties(value)
63
+ out.properties = nested.properties
64
+ if (nested.required.length) out.required = nested.required
65
+ continue
66
+ }
67
+ out[key] = convertNode(value)
68
+ }
69
+ return out
70
+ }
71
+
72
+ export {
73
+ privateRecall, privateList, privateRemember, privateUpdate, privateArchive, privateDelete,
74
+ previewDelete, restoreDeleted, globalList, globalRecall, globalSetStatus, globalDelete,
75
+ importMemories, domainOf, decayStrength, appliesToDomain, visibleToSession, isMemoryEligible,
76
+ } from './memory.js'
77
+
78
+ export {
79
+ listLibraries, listLibrariesAll, getLibrary, createLibrary, ensureLibraryForCwd,
80
+ getSessionBinding, ensureSession, effectiveScope,
81
+ loadPrivateIndex, loadGlobalIndex,
82
+ } from './state.js'
package/lib/rpc.js CHANGED
@@ -492,7 +492,10 @@ async function mergeLexiconImport(libraryId, member) {
492
492
  // degrades to the index instead of failing the browser.
493
493
  async function privateListView(scope, { limit = null, previewChars = 4000 } = {}) {
494
494
  const libraryId = scope.libraryId ?? getSessionBinding(scope.exec ? scope.exec?.agent?.session?.header?.id : null)?.libraryId
495
- const contentLimit = Math.max(40, Math.min(4000, Number(previewChars) || 4000))
495
+ // 4000 的上限原本是"预览"口径,但浏览库的卡片是可编辑的 textarea:正文一旦
496
+ // 被截断,用户改一个字保存就会把尾部丢掉。列表默认仍是 4000(侧栏轻量预览),
497
+ // 浏览库显式要大值时按真实长度给。
498
+ const contentLimit = Math.max(40, Math.min(200_000, Number(previewChars) || 4000))
496
499
  const itemLimit = Number.isInteger(limit) && limit > 0 ? Math.min(500, limit) : null
497
500
  const shape = (fileLibraryId, id, e, content, libraryName = null) => ({
498
501
  id,
@@ -538,10 +541,18 @@ async function privateListView(scope, { limit = null, previewChars = 4000 } = {}
538
541
  createdAt: e?.createdAt || null,
539
542
  updatedAt: e?.updatedAt || e?.createdAt || null,
540
543
  content: String(content ?? e?.content ?? '').slice(0, contentLimit),
544
+ // 正文被列表口径截断时标出来:浏览页的 textarea 一旦被编辑就会把截断版写回,
545
+ // 客户端据此在聚焦时用 getMemory 补拉全文(§7.4「列表项预览就地截断」)。
546
+ truncated: String(content ?? e?.content ?? '').length > contentLimit,
541
547
  })
548
+ // 新到旧:引擎与索引都不保证顺序,界面若自己不排,刚写的记忆就会跑到中间
549
+ // (2026-11-28 现场)。列表、浏览库、侧栏三处共用这一条口径。
550
+ const newestFirst = (a, b) => String(b.updatedAt || b.createdAt || '')
551
+ .localeCompare(String(a.updatedAt || a.createdAt || ''))
552
+ || String(a.id).localeCompare(String(b.id))
542
553
  try {
543
554
  const result = await privateList({ ...scope, preferIndex: true })
544
- const files = (result.files || []).map((f) => shape(f.libraryId || libraryId, f.name, f.entry, f.content, f.libraryName))
555
+ const files = (result.files || []).map((f) => shape(f.libraryId || libraryId, f.name, f.entry, f.content, f.libraryName)).sort(newestFirst)
545
556
  return {
546
557
  libraryId: result.libraryId,
547
558
  ...(result.libraries ? { libraries: result.libraries } : {}),
@@ -554,7 +565,7 @@ async function privateListView(scope, { limit = null, previewChars = 4000 } = {}
554
565
  return {
555
566
  libraryId,
556
567
  source: 'index',
557
- 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)),
568
+ 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)).sort(newestFirst),
558
569
  }
559
570
  }
560
571
  }
@@ -1638,8 +1649,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
1638
1649
  // empty global scope.
1639
1650
  try { collect(loadGlobalIndex(), null) } catch { errors.push({ libraryId: null, error: 'global index unavailable' }) }
1640
1651
  items.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')))
1641
- const limit = Math.max(1, Math.min(1000, Number(payload?.limit) || 300))
1642
- return { items: items.slice(0, limit), total: items.length, domains: [...domains].sort(), libraries, errors }
1652
+ // 分页:记忆墙按 offset 逐批取,不再在 300 条处截断。5000 只是防一次请求
1653
+ // 把整库塞进一个 JSON 的上限(当前最大库 417 条,一条流就能读完)。
1654
+ const limit = Math.max(1, Math.min(5000, Number(payload?.limit) || 300))
1655
+ const offset = Math.max(0, Math.floor(Number(payload?.offset) || 0))
1656
+ return { items: items.slice(offset, offset + limit), total: items.length, offset, domains: [...domains].sort(), libraries, errors }
1643
1657
  }
1644
1658
  case 'getGraph':
1645
1659
  // Reuse the private graph endpoint instead of adding a second read method:
package/lib/tools.js CHANGED
@@ -1064,3 +1064,28 @@ export function registerTools(ctx, { only = null } = {}) {
1064
1064
  disposeAll.requested = wanted
1065
1065
  return disposeAll
1066
1066
  }
1067
+
1068
+ /**
1069
+ * 工具规格快照,给无宿主调用方用(MCP server / 移植适配器 / 脚本)。
1070
+ *
1071
+ * 用一个只收集、不注册的假 ctx 跑一遍 `registerTools`,拿到的就是宿主本来会看到
1072
+ * 的那批 defineTool 对象:`name` / `description` / `parameters`(已是 JSON Schema)
1073
+ * / `execute(args, exec)`。MCP 侧把 `parameters` 直接当 `inputSchema`、`execute(args, {})`
1074
+ * 就能跑,不必重写三十个工具。
1075
+ *
1076
+ * 不碰任何既有注册路径;跑完把模块级 `registrationReport` 还原,所以 `memu_status`
1077
+ * 的注册清单不会因为「有人问了一次规格」而变。
1078
+ */
1079
+ export function collectToolSpecs() {
1080
+ const saved = registrationReport
1081
+ const collected = []
1082
+ try {
1083
+ registerTools({
1084
+ tools: { register: (tool) => { collected.push(tool); return () => {} } },
1085
+ logger: { warn() {} },
1086
+ })
1087
+ } finally {
1088
+ registrationReport = saved
1089
+ }
1090
+ return collected
1091
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.4.1",
4
+ "version": "1.4.2",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -37,6 +37,7 @@
37
37
  ".": "./lib/index.js",
38
38
  "./client": "./lib/client.js",
39
39
  "./integration": "./lib/inbound.js",
40
+ "./port": "./lib/port-surface.js",
40
41
  "./package.json": "./package.json"
41
42
  },
42
43
  "bin": {
@@ -63,6 +63,27 @@ test('browseLibrary degrades to the index while the engine is missing', async ()
63
63
  assert.match(item.content, /body of mem-3/)
64
64
  })
65
65
 
66
+ test('browseLibrary lists newest first', async () => {
67
+ const lib = createLibrary({ name: 'browser-order', cwd: path.join(home, 'browser-order') })
68
+ seed(lib.id, 'mem-old', { createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-02T00:00:00.000Z' })
69
+ seed(lib.id, 'mem-mid', { createdAt: '2026-10-03T00:00:00.000Z', updatedAt: '2026-10-03T00:00:00.000Z' })
70
+ seed(lib.id, 'mem-new', { createdAt: '2026-10-05T00:00:00.000Z', updatedAt: '2026-10-06T00:00:00.000Z' })
71
+ const view = await dispatch({}, 'browseLibrary', { libraryId: lib.id })
72
+ // 侧栏与浏览库共用同一条口径:新到旧(引擎与索引都不保证顺序)。
73
+ assert.deepEqual(view.files.map((file) => file.id), ['mem-new', 'mem-mid', 'mem-old'])
74
+ })
75
+
76
+ test('browseLibrary flags a truncated body instead of silently shortening it', async () => {
77
+ const lib = createLibrary({ name: 'browser-trunc', cwd: path.join(home, 'browser-trunc') })
78
+ seed(lib.id, 'mem-long', { content: 'x'.repeat(4100) })
79
+ const view = await dispatch({}, 'browseLibrary', { libraryId: lib.id })
80
+ const item = view.files.find((file) => file.id === 'mem-long')
81
+ assert.equal(item.content.length, 4000, 'the list keeps the preview cap')
82
+ assert.equal(item.truncated, true, 'the client must know it can fetch the rest')
83
+ const full = await dispatch({}, 'getMemory', { libraryId: lib.id, id: 'mem-long' })
84
+ assert.equal(full.entry.content.length, 4100, 'getMemory returns the whole body')
85
+ })
86
+
66
87
  test('local agent backend writes and recalls memory without an engine', async () => {
67
88
  const cwd = path.join(home, 'browser-local')
68
89
  const lib = createLibrary({ name: 'browser-local', cwd })
@@ -46,6 +46,7 @@ const React = {
46
46
  dirty = true
47
47
  }]
48
48
  },
49
+ memo: (component) => component,
49
50
  useCallback: (fn) => fn,
50
51
  useMemo: (fn) => fn(),
51
52
  useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
@@ -39,6 +39,7 @@ const React = {
39
39
  dirty = true
40
40
  }]
41
41
  },
42
+ memo: (component) => component,
42
43
  useCallback: (fn) => fn,
43
44
  useMemo: (fn) => fn(),
44
45
  useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
@@ -46,3 +46,63 @@ test('the macOS library-validation dlopen error is recognized for the signing re
46
46
  assert.equal(engine.isMacOSLibraryValidationError(''), false)
47
47
  assert.equal(engine.isMacOSLibraryValidationError(null), false)
48
48
  })
49
+
50
+ // ---- 中断安装的自愈(2026-11-28:rc.5 home 卡在 installing 两天) ----
51
+
52
+ function writeEngineState(patch) {
53
+ const dir = path.join(home, 'engine')
54
+ fs.mkdirSync(dir, { recursive: true })
55
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(patch), 'utf8')
56
+ return dir
57
+ }
58
+
59
+ const DEAD_INSTALL = {
60
+ status: 'installing',
61
+ version: '0.11.0b3',
62
+ step: 'installing-deps:python',
63
+ error: null,
64
+ startedAt: '2026-11-26T06:33:02.636Z',
65
+ updatedAt: '2026-11-26T06:33:05.838Z',
66
+ }
67
+
68
+ test('a dead install becomes failed and its venv.tmp is cleaned up', () => {
69
+ const dir = writeEngineState(DEAD_INSTALL)
70
+ const aborted = path.join(dir, '0.11.0b3', 'venv.tmp-37076-1795674785559')
71
+ const finished = path.join(dir, '0.11.0b3', 'venv-real')
72
+ fs.mkdirSync(aborted, { recursive: true })
73
+ fs.mkdirSync(finished, { recursive: true })
74
+
75
+ const status = engine.engineStatus()
76
+ assert.equal(status.status, 'failed', 'a stale installing state must not stay installing forever')
77
+ assert.equal(status.installed, false)
78
+ assert.equal(status.state.step, 'interrupted')
79
+ assert.match(String(status.state.error), /中断/, 'the reason must be readable in the UI')
80
+ assert.ok(!fs.existsSync(aborted), 'the aborted venv must be removed')
81
+ assert.ok(fs.existsSync(finished), 'a finished venv must never be touched')
82
+ })
83
+
84
+ test('a fresh install is left running', () => {
85
+ const now = new Date().toISOString()
86
+ writeEngineState({ ...DEAD_INSTALL, startedAt: now, updatedAt: now })
87
+ assert.equal(engine.engineStatus().status, 'installing', 'a live install must not be reconciled away')
88
+ })
89
+
90
+ test('a held lock means an install is still in flight', () => {
91
+ const dir = writeEngineState(DEAD_INSTALL)
92
+ fs.writeFileSync(path.join(dir, 'install.lock'), JSON.stringify({ pid: 1, startedAt: DEAD_INSTALL.startedAt }), 'utf8')
93
+ try {
94
+ assert.equal(engine.engineStatus().status, 'installing', 'the cross-process lock must veto reconciliation')
95
+ } finally {
96
+ fs.rmSync(path.join(dir, 'install.lock'), { force: true })
97
+ }
98
+ })
99
+
100
+ test('reconciliation is idempotent and leaves a ready engine alone', () => {
101
+ const dir = writeEngineState({ status: 'ready', version: '0.11.0b3', step: 'ready', error: null, updatedAt: '2026-11-26T06:33:05.838Z' })
102
+ fs.writeFileSync(path.join(dir, 'current.json'), JSON.stringify({ version: '0.11.0b3', venv: 'x', python: 'y' }), 'utf8')
103
+ try {
104
+ assert.equal(engine.engineStatus().status, 'ready', 'a ready engine must never be demoted')
105
+ } finally {
106
+ fs.rmSync(path.join(dir, 'current.json'), { force: true })
107
+ }
108
+ })
@@ -31,6 +31,7 @@ const React = {
31
31
  hooks[index] = typeof next === 'function' ? next(hooks[index]) : next
32
32
  }]
33
33
  },
34
+ memo: (component) => component,
34
35
  useCallback: (fn) => fn,
35
36
  useMemo: (fn) => fn(),
36
37
  useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
@@ -44,6 +44,7 @@ const React = {
44
44
  if (hooks[index] === undefined) hooks[index] = typeof initial === 'function' ? initial() : initial
45
45
  return [hooks[index], (next) => { hooks[index] = typeof next === 'function' ? next(hooks[index]) : next }]
46
46
  },
47
+ memo: (component) => component,
47
48
  useCallback(fn, deps) { return React.useMemo(() => fn, deps) },
48
49
  useMemo(fn, deps) {
49
50
  const index = cursor++
@@ -0,0 +1,138 @@
1
+ // 移植入口(lib/port-surface.js)的契约测试。
2
+ //
3
+ // 这里模拟的是「没有宿主」的调用方(MCP server / CLI):没有 ctx、没有会话、没有
4
+ // 注入钩子,只有 libraryId 和工具规格。任何一条挂掉都意味着移植方会踩坑,而这些
5
+ // 坑在宿主内是测不到的。
6
+ import test from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+
12
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-port-'))
13
+ process.env.DSH_MEMU_HOME = home
14
+
15
+ // 只从公开入口取能力:适配器就该这么用,测试顺带证明入口自洽。
16
+ const port = await import('../lib/port-surface.js')
17
+ const { createLibrary, ensureSession, loadPrivateIndex, savePrivateIndex, setWorkspacePolicy } = await import('../lib/state.js')
18
+
19
+ test.after(() => {
20
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
21
+ })
22
+
23
+ function seed(libraryId, id, entry) {
24
+ const index = loadPrivateIndex(libraryId)
25
+ index.entries[id] = {
26
+ layer: 'long_term', title: id, content: `body of ${id}`, status: 'active',
27
+ createdAt: '2026-11-01T00:00:00.000Z', ...entry,
28
+ }
29
+ savePrivateIndex(libraryId, index)
30
+ }
31
+
32
+ test('collectToolSpecs hands out every hosted tool as plain data', () => {
33
+ const specs = port.collectToolSpecs()
34
+ // 宿主实际挂的就是这 14 个(私有读写 + 词典 + 全局 + status);这个数字变了
35
+ // 说明工具面本身变了,移植方需要重新核对,所以守住它。
36
+ assert.ok(specs.length >= 14, `expected the full tool set, got ${specs.length}`)
37
+ const names = new Set(specs.map((spec) => spec.name))
38
+ for (const required of ['memu_private_recall', 'memu_private_remember', 'memu_private_list', 'memu_status']) {
39
+ assert.ok(names.has(required), `${required} must be part of the surface`)
40
+ }
41
+ for (const spec of specs) {
42
+ assert.equal(typeof spec.name, 'string')
43
+ assert.ok(spec.name.startsWith('memu_'), `unexpected tool name ${spec.name}`)
44
+ assert.equal(typeof spec.description, 'string')
45
+ assert.ok(spec.description.length > 0, `${spec.name} must carry a description`)
46
+ assert.equal(typeof spec.parameters, 'object')
47
+ assert.equal(typeof spec.execute, 'function')
48
+ }
49
+ // 幂等:再问一次不该多也不该少(内部会重跑一遍 registerTools)。
50
+ assert.equal(port.collectToolSpecs().length, specs.length, 'asking twice must not change the set')
51
+ })
52
+
53
+ test('toInputSchema lifts host required flags into a JSON Schema array', () => {
54
+ const specs = port.collectToolSpecs()
55
+ const recall = specs.find((spec) => spec.name === 'memu_private_recall')
56
+ assert.ok(recall, 'memu_private_recall must be part of the surface')
57
+ const schema = port.toInputSchema(recall.parameters)
58
+ assert.equal(schema.type, 'object')
59
+ assert.ok(Array.isArray(schema.required), 'required must be an array')
60
+ assert.ok(schema.required.includes('query'), 'query is a required parameter in the host DSL')
61
+ assert.equal(schema.properties.query.type, 'string')
62
+ // 宿主方言的 required 是属性上的布尔,不能漏进 JSON Schema。
63
+ assert.equal(schema.properties.query.required, undefined, 'per-property required must not survive')
64
+ })
65
+
66
+ test('privateRecall serves an explicit library with no session at all', async () => {
67
+ const lib = createLibrary({ name: 'port-recall', cwd: path.join(home, 'port-recall') })
68
+ seed(lib.id, 'mem-port-1', { title: '主题偏好', content: '用户偏好深色主题,讨厌弹窗。' })
69
+ const result = await port.privateRecall({ libraryId: lib.id, query: '深色主题' })
70
+ assert.ok(result && Array.isArray(result.files), 'recall must return a files array')
71
+ assert.ok(result.files.some((file) => file.name === 'mem-port-1'), 'the seeded memory must be recalled')
72
+ })
73
+
74
+ test('privateRecall without a session and without a library still refuses', async () => {
75
+ await assert.rejects(() => port.privateRecall({ query: 'x' }), /no bound session/)
76
+ })
77
+
78
+ test('an unknown libraryId is rejected instead of silently returning nothing', async () => {
79
+ // loadPrivateIndex 对未知库给的是空索引,不校验就会变成「静默零命中」——
80
+ // 对一个拼错的 libraryId 来说,安静的空结果比报错更难查。
81
+ await assert.rejects(
82
+ () => port.privateRecall({ libraryId: 'lib-does-not-exist', query: 'x' }),
83
+ /unknown library/,
84
+ )
85
+ })
86
+
87
+ test('an explicit library never pulls in a sibling library', async () => {
88
+ const a = createLibrary({ name: 'port-own-a', cwd: path.join(home, 'port-own-a') })
89
+ const b = createLibrary({ name: 'port-own-b', cwd: path.join(home, 'port-own-b') })
90
+ seed(a.id, 'mem-own', { content: '只在 A 库里的锚点词 蓝色钥匙' })
91
+ seed(b.id, 'mem-foreign', { content: '只在 B 库里的锚点词 蓝色钥匙' })
92
+ const result = await port.privateRecall({ libraryId: a.id, query: '蓝色钥匙' })
93
+ assert.ok(result.files.length > 0, 'the owning library must still answer')
94
+ assert.ok(
95
+ result.files.every((file) => (file.libraryId || a.id) === a.id),
96
+ 'no cross-library rows without a session',
97
+ )
98
+ })
99
+
100
+ test('a bound session keeps behaving as before', async () => {
101
+ const cwd = path.join(home, 'port-bound')
102
+ const lib = createLibrary({ name: 'port-bound', cwd })
103
+ seed(lib.id, 'mem-bound', { content: '会话里的锚点词 红色雨伞' })
104
+ ensureSession('port-session-1', { cwd, libraryId: lib.id })
105
+ const exec = { agent: { session: { header: { id: 'port-session-1', cwd } } } }
106
+ const result = await port.privateRecall({ exec, query: '红色雨伞' })
107
+ assert.ok(result.files.some((file) => file.name === 'mem-bound'), 'the bound session path must be unchanged')
108
+ })
109
+
110
+ test('privateRemember writes with only a libraryId', async () => {
111
+ const lib = createLibrary({ name: 'port-write', cwd: path.join(home, 'port-write') })
112
+ await port.privateRemember({ libraryId: lib.id, content: '无会话也能写,但必须显式给库。', title: '无会话写入' })
113
+ const listed = await port.privateList({ libraryId: lib.id })
114
+ // privateList 返回的是原始行(标题在 entry 里);privateListView 才做顶层投影。
115
+ assert.ok(
116
+ (listed.files || []).some((file) => (file.entry?.title || file.title) === '无会话写入'),
117
+ 'the written memory must be listed from the same library',
118
+ )
119
+ })
120
+
121
+ test('a folder that turned private memory off stays off for session-less callers', async () => {
122
+ const lib = createLibrary({ name: 'port-disabled', cwd: path.join(home, 'port-disabled') })
123
+ setWorkspacePolicy(lib.scopeKey, { useLibrary: false })
124
+ try {
125
+ await assert.rejects(
126
+ () => port.privateRemember({ libraryId: lib.id, content: 'x', title: 'x' }),
127
+ /disabled for this folder/,
128
+ 'a disabled folder must not accept writes just because the caller has no session',
129
+ )
130
+ await assert.rejects(
131
+ () => port.privateRecall({ libraryId: lib.id, query: 'x' }),
132
+ /disabled for this folder/,
133
+ 'a disabled folder must not serve reads either',
134
+ )
135
+ } finally {
136
+ setWorkspacePolicy(lib.scopeKey, { useLibrary: true })
137
+ }
138
+ })
@@ -6,6 +6,7 @@ const React = {
6
6
  createElement: (type, props, ...children) => typeof type === 'function' ? type({ ...props, children }) : { type, props, children },
7
7
  Fragment: Symbol('fragment'),
8
8
  useState: value => [typeof value === 'function' ? value() : value, () => {}],
9
+ memo: (component) => component,
9
10
  useMemo: fn => fn(), useCallback: fn => fn, useEffect: () => {}, useRef: value => ({ current: value }),
10
11
  useSyncExternalStore: (_subscribe, snapshot) => {
11
12
  const first = snapshot()