dsh-memu-memory 1.3.0 → 1.3.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +3 -3
  16. package/lib/client.js +1435 -70
  17. package/lib/consolidation-receipt.js +81 -5
  18. package/lib/consolidation-worker.js +57 -25
  19. package/lib/curator.js +91 -11
  20. package/lib/engine.js +13 -3
  21. package/lib/graph.js +326 -39
  22. package/lib/inject.js +35 -15
  23. package/lib/media.js +8 -1
  24. package/lib/memory.js +27 -1
  25. package/lib/memu.js +26 -12
  26. package/lib/private-links.js +105 -137
  27. package/lib/private.js +280 -53
  28. package/lib/prompts/global-curator.md +6 -3
  29. package/lib/prompts/system-guide.md +4 -5
  30. package/lib/prompts.js +27 -1
  31. package/lib/rpc.js +69 -9
  32. package/lib/state.js +23 -4
  33. package/lib/tools.js +199 -67
  34. package/lib/webui/graph-LICENSE.txt +1 -62
  35. package/lib/webui/graph-view.bundle.js +1 -1
  36. package/lib/webui/graph-view.js +891 -124
  37. package/lib/webui/standalone.js +3 -3
  38. package/package.json +1 -2
  39. package/scripts/build-graph.mjs +3 -3
  40. package/scripts/check-graph-browser.mjs +106 -23
  41. package/scripts/rebuild-auto-links.mjs +252 -0
  42. package/tests/audit-regression.test.mjs +11 -8
  43. package/tests/auto-link-candidates.test.mjs +161 -0
  44. package/tests/auto-link-decide.test.mjs +512 -0
  45. package/tests/auto-link-migration.test.mjs +133 -0
  46. package/tests/client-render.test.mjs +7 -6
  47. package/tests/consolidation-credential.test.mjs +2 -2
  48. package/tests/consolidation-fork.test.mjs +188 -9
  49. package/tests/consolidation-ledger.test.mjs +31 -0
  50. package/tests/consolidation-snapshot.test.mjs +9 -8
  51. package/tests/curator-probe.test.mjs +32 -2
  52. package/tests/cycle.test.mjs +1 -1
  53. package/tests/graph-view.test.mjs +163 -21
  54. package/tests/graph.test.mjs +26 -0
  55. package/tests/help-page.test.mjs +3 -3
  56. package/tests/inject-conflict.test.mjs +1 -1
  57. package/tests/inject.test.mjs +1 -1
  58. package/tests/injection-chain.test.mjs +2 -2
  59. package/tests/injection-rollback.test.mjs +1 -1
  60. package/tests/memory-chain.test.mjs +28 -0
  61. package/tests/memu-resident-route.test.mjs +130 -0
  62. package/tests/mock-llm.test.mjs +1 -1
  63. package/tests/private-links.test.mjs +81 -45
  64. package/tests/prompts.test.mjs +1 -1
  65. package/tests/stubs/child-process-spy.mjs +14 -0
  66. package/tests/tool-schema.test.mjs +2 -1
  67. package/tests/tools.test.mjs +49 -21
package/lib/rpc.js CHANGED
@@ -20,7 +20,11 @@ import { recallCacheStats } from './recall-cache.js'
20
20
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
21
21
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
22
22
  import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
23
- import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
23
+ import { getGraph, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
24
+ import { generateAnchorCandidates, resetAnchorCandidatesCache } from './auto-link/candidates.js'
25
+ import { refreshPrivateAutoLinks } from './private-links.js'
26
+ import { refreshEntityMentions } from './auto-link/apply.js'
27
+ import { clearSuppression, suppressionSet } from './auto-link/suppression.js'
24
28
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
25
29
  import { listEvents, logStats, clearEvents } from './activity-log.js'
26
30
  import { redactSecrets, warn } from './paths.js'
@@ -80,6 +84,8 @@ const LIBRARY_ROUTE_OPERATIONS = new Map([
80
84
  ['importMemories', 'import'], ['exportLibrary', 'export'], ['getAttachment', 'attachment.read'],
81
85
  ['browseWall', 'read'], ['getGraph', 'read'], ['listEntities', 'read'], ['createEntity', 'write'], ['renameEntity', 'write'],
82
86
  ['deleteEntity', 'write'], ['mergeEntities', 'write'], ['suggestEntityMerges', 'read'],
87
+ // 自动关联的候选队列与实体确认同样按库鉴权:未登记的端点会被直接放行。
88
+ ['getAnchorCandidates', 'read'], ['confirmEntities', 'write'], ['purgeAutoLinks', 'write'], ['clearLinkSuppression', 'write'],
83
89
  ['linkEntries', 'write'], ['unlinkEntry', 'write'], ['getRelationship', 'read'], ['updateRelationship', 'write'],
84
90
  ['listReviews', 'read'], ['resolveReview', 'write'], ['lexiconList', 'read'], ['lexiconSearch', 'read'], ['lexiconAdd', 'write'],
85
91
  ['lexiconUpdate', 'write'], ['lexiconDelete', 'write'], ['lexiconArchive', 'write'], ['lexiconRestore', 'write'],
@@ -1030,8 +1036,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1030
1036
  'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
1031
1037
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1032
1038
  // 整理 fork 的模型选择(三模式):恢复默认 = 回到 inherit,不留 host/custom 残配置。
1033
- 'consolidationModelMode', 'consolidationModel',
1039
+ 'consolidationModelMode', 'consolidationModel', 'consolidationReasoningEffort',
1034
1040
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1041
+ // 自动关联:恢复默认 = 回到 suggest(只出候选、不写边)。
1042
+ 'autoLinkMode', 'allowWorkerAssertion',
1035
1043
  ]) patch[key] = DEFAULT_SETTINGS[key]
1036
1044
  return redactConsolidationSettings(updateSettings(patch))
1037
1045
  }
@@ -1056,12 +1064,27 @@ async function dispatch(ctx, endpoint, payload = {}) {
1056
1064
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1057
1065
  // 整理 fork 的模型选择:三模式开关 + host 指名 + custom 连接面(含明文 key 的
1058
1066
  // 写入;回包经 redactConsolidationSettings 打码,明文只落 state.json)。
1059
- 'consolidationModelMode', 'consolidationModel',
1067
+ 'consolidationModelMode', 'consolidationModel', 'consolidationReasoningEffort',
1060
1068
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1069
+ // 自动关联的写入门控(DESIGN §6.4):suggest / deterministic / off。
1070
+ 'autoLinkMode', 'allowWorkerAssertion',
1061
1071
  ])
1062
1072
  const clean = {}
1063
1073
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
1064
- return redactConsolidationSettings(updateSettings(clean))
1074
+ const beforeMode = getSettings().autoLinkMode
1075
+ const saved = redactConsolidationSettings(updateSettings(clean))
1076
+ // 切换到确定性写边时补一次全量重算:off/suggest 期间确认过的实体状态已是
1077
+ // confirmed,日常按 ids 的增量不会碰它们,否则提及边会永久缺失。
1078
+ if (clean.autoLinkMode === 'deterministic' && beforeMode !== 'deterministic') {
1079
+ try {
1080
+ for (const lib of listLibraries()) {
1081
+ await refreshPrivateAutoLinks({ libraryId: lib.id, full: true })
1082
+ }
1083
+ } catch (error) {
1084
+ try { warn('auto-link rebuild after mode switch skipped: ' + (error?.message || error)) } catch {}
1085
+ }
1086
+ }
1087
+ return saved
1065
1088
  }
1066
1089
  case 'listForkModelOptions': {
1067
1090
  // 整理 fork 模型选择器的数据源:宿主已激活 route 的 provider/model 目录 +
@@ -1456,8 +1479,19 @@ async function dispatch(ctx, endpoint, payload = {}) {
1456
1479
  return getGraph(payload || {})
1457
1480
  case 'listEntities':
1458
1481
  return listEntities(payload || {})
1459
- case 'createEntity':
1460
- return createEntity(payload || {})
1482
+ case 'createEntity': {
1483
+ // 手工创建就是一次用户断言:直接 confirmed,并立刻挂上提及边。
1484
+ const entity = createEntity({ ...(payload || {}), status: 'confirmed', confirmedBy: 'user', origin: 'user' })
1485
+ if (entity?.status === 'confirmed') {
1486
+ let suppression = null
1487
+ try { suppression = suppressionSet(payload?.libraryId) } catch {}
1488
+ try {
1489
+ refreshEntityMentions({ libraryId: payload?.libraryId, entity, suppression, operation: 'auto-link-create' })
1490
+ } catch {}
1491
+ resetAnchorCandidatesCache()
1492
+ }
1493
+ return entity
1494
+ }
1461
1495
  case 'renameEntity':
1462
1496
  return renameEntity(payload || {})
1463
1497
  case 'deleteEntity':
@@ -1466,6 +1500,33 @@ async function dispatch(ctx, endpoint, payload = {}) {
1466
1500
  return mergeEntities(payload || {})
1467
1501
  case 'suggestEntityMerges':
1468
1502
  return suggestEntityMerges(payload || {})
1503
+ case 'getAnchorCandidates':
1504
+ // 派生数据:只读记忆/实体/词典,生成本库的待确认队列快照。
1505
+ return generateAnchorCandidates({ libraryId: payload?.libraryId, force: payload?.force === true })
1506
+ case 'confirmEntities': {
1507
+ // 人工确认是唯一入口:确认后同步补挂提及边(增量 R1),不等下次整理。
1508
+ const result = confirmEntities({ libraryId: payload?.libraryId, entityIds: payload?.entityIds, by: 'user' })
1509
+ resetAnchorCandidatesCache()
1510
+ return result
1511
+ }
1512
+ case 'purgeAutoLinks': {
1513
+ // 关系图的“删除全部自动边”:只删 source:'auto',并写抑制键防复活。
1514
+ const result = purgeAutoLinks({ libraryId: payload?.libraryId })
1515
+ resetAnchorCandidatesCache()
1516
+ return result
1517
+ }
1518
+ case 'clearLinkSuppression': {
1519
+ // 反向操作:清除本库的删除标记;deterministic 模式下顺带全量重算一次。
1520
+ const result = clearSuppression(payload?.libraryId)
1521
+ let rebuilt = null
1522
+ try {
1523
+ rebuilt = await refreshPrivateAutoLinks({ libraryId: payload?.libraryId, full: true })
1524
+ } catch (error) {
1525
+ try { warn('auto-link rebuild after suppression clear skipped: ' + (error?.message || error)) } catch {}
1526
+ }
1527
+ resetAnchorCandidatesCache()
1528
+ return { ...result, rebuilt: rebuilt?.applied ? (rebuilt.applied.added + rebuilt.applied.updated) : 0, skipped: rebuilt?.skipped || null }
1529
+ }
1469
1530
  case 'linkEntries':
1470
1531
  return linkEntries(payload || {})
1471
1532
  case 'unlinkEntry':
@@ -1915,10 +1976,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1915
1976
  return getMemuConfig()
1916
1977
  case 'setEmbeddingSource': {
1917
1978
  const config = setEmbeddingSource(String(payload?.source || ''))
1918
- // Local mode is the resident route: warm it as soon as the switch flips, and
1919
- // release it when the user goes back to the remote API route.
1979
+ // 两条向量路线现在共用同一个常驻解释器:切回远程 API 不应释放它,
1980
+ // 否则下一次召回又会重新付一遍 Python 导入链的冷启动。
1920
1981
  if (config?.source === 'local') void prewarmMemuResident()
1921
- else closeMemuResident()
1922
1982
  return config
1923
1983
  }
1924
1984
  case 'saveMemuConfig':
package/lib/state.js CHANGED
@@ -27,6 +27,11 @@ export const DEFAULT_SETTINGS = {
27
27
  // Producer-owned tool meta is the preferred integration and needs no allowlist.
28
28
  inboundToolNames: [],
29
29
  autoInject: 'smart',
30
+ // 自动关联(DESIGN §6.4):'suggest' 只出候选、不写任何边(迁移期默认),
31
+ // 'deterministic' 只写由已确认实体或字段证据推出的确定性边,'off' 完全关闭。
32
+ // allowWorkerAssertion 是 v3 的预留开关(worker 确认实体),本版不读取。
33
+ autoLinkMode: 'suggest',
34
+ allowWorkerAssertion: false,
30
35
  // These defaults are tuned for high-density chat — a QQ-style group where many
31
36
  // short messages arrive per minute, in fragments rather than sentences, and the
32
37
  // topic drifts every few of them. Under that cadence the failure mode is not
@@ -141,6 +146,9 @@ export const DEFAULT_SETTINGS = {
141
146
  // 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
142
147
  consolidationModelMode: 'inherit',
143
148
  consolidationModel: null,
149
+ // 1.3.1:整理 fork 的思考强度独立于父会话。'inherit' 保持旧行为;'off' /
150
+ // 'medium' / 'low' / 'high' 直接覆盖,用于成本/质量的 A/B。
151
+ consolidationReasoningEffort: 'medium',
144
152
  consolidationCustomBaseURL: '',
145
153
  consolidationCustomApiKey: '',
146
154
  consolidationCustomModel: '',
@@ -404,7 +412,7 @@ export function updateSettings(patch) {
404
412
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
405
413
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
406
414
  }
407
- const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
415
+ const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
408
416
  for (const [key, value] of Object.entries(patch || {})) {
409
417
  if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
410
418
  if (enums[key]) {
@@ -660,7 +668,7 @@ export function deleteLibrary(id) {
660
668
  const vectorGenerationFiles = fs.existsSync(librariesDir())
661
669
  ? fs.readdirSync(librariesDir()).filter(name => name.startsWith(vectorPrefix) && name.endsWith('.sqlite3')).map(name => path.join(librariesDir(), name))
662
670
  : []
663
- for (const file of [activeVectorDb, legacyVectorDb, ...vectorGenerationFiles, ...['json', 'entities.json', 'media.json', 'stats.json'].map(suffix => path.join(indexDir(), `${id}.${suffix}`))]) {
671
+ for (const file of [activeVectorDb, legacyVectorDb, ...vectorGenerationFiles, ...['json', 'entities.json', 'media.json', 'stats.json', 'link-suppression.json', 'anchor-candidates.json'].map(suffix => path.join(indexDir(), `${id}.${suffix}`))]) {
664
672
  if (!file) continue
665
673
  try {
666
674
  if (fs.existsSync(file)) { fs.rmSync(file, { force: true }); removed.push(file) }
@@ -899,10 +907,19 @@ export function markInjected(sessionId, ids, turn) {
899
907
  return updateState((state) => {
900
908
  const binding = state.sessions[sessionId]
901
909
  if (!binding) return state
902
- const merged = [...new Set([...(binding.injectedIds || []), ...(ids || [])])]
910
+ // 锚点哨兵不进 injectedIds:它是一份常驻提示,不是会被 400 条上限挤掉的记忆 id。
911
+ // 单独记 anchorPushed,避免长会话里周期性把 ~800 token 的锚点当新消息重投。
912
+ const incoming = ids || []
913
+ // 旧 binding 可能把哨兵存在 injectedIds 里:迁移为 anchorPushed,之后只按标记判断。
914
+ const anchor = incoming.includes('__anchor__') || (binding.injectedIds || []).includes('__anchor__')
915
+ const merged = [...new Set([
916
+ ...(binding.injectedIds || []).filter((id) => id !== '__anchor__'),
917
+ ...incoming.filter((id) => id !== '__anchor__'),
918
+ ])]
903
919
  binding.injectedIds = merged.slice(-400)
920
+ if (anchor) binding.anchorPushed = true
904
921
  const at = { ...(binding.injectedAt || {}) }
905
- for (const id of ids || []) at[id] = turn ?? Date.now()
922
+ for (const id of incoming) at[id] = turn ?? Date.now()
906
923
  binding.injectedAt = at
907
924
  binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
908
925
  // 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
@@ -1148,6 +1165,8 @@ export function rollbackInjectionForTurn(sessionId, hostTurn) {
1148
1165
  binding.injectedIds = (binding.injectedIds || []).filter((id) => !ids.has(id))
1149
1166
  if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1150
1167
  }
1168
+ // 哨兵已不再进 injectedIds,必须单独撤掉它的"已投"标记,否则回滚后锚点不再重投。
1169
+ if (ids.has('__anchor__')) delete binding.anchorPushed
1151
1170
  if (record.guideKey && binding.guideRulesKey === record.guideKey) {
1152
1171
  delete binding.guideRulesKey
1153
1172
  delete binding.guideMessageAt
package/lib/tools.js CHANGED
@@ -120,11 +120,19 @@ function emotionBrief(entry) {
120
120
 
121
121
  function formatPrivateItem(item, index, options = {}) {
122
122
  const entry = item.entry || {}
123
- const lines = [
124
- `${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`,
125
- ` layer=${entry.layer || 'long_term'} status=${entry.status || 'active'}${entry.marginalized ? ' marginalized' : ''}${entry.openLoop ? ' open_loop' : ''}`,
126
- ` source=${entry.source || 'inferred'}`,
127
- ]
123
+ const layer = entry.layer || 'long_term'
124
+ const status = entry.status || 'active'
125
+ const source = entry.source || 'inferred'
126
+ // B7:默认值不逐条重写(guide 已说明缺省口径),非默认 layer/status/source 仍必须输出。
127
+ const flags = [
128
+ layer !== 'long_term' ? `layer=${layer}` : '',
129
+ status !== 'active' ? `status=${status}` : '',
130
+ entry.marginalized ? 'marginalized' : '',
131
+ entry.openLoop ? 'open_loop' : '',
132
+ ].filter(Boolean).join(' ')
133
+ const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
134
+ if (flags) lines.push(` ${flags}`)
135
+ if (source !== 'inferred') lines.push(` source=${source}`)
128
136
  // Same relative phrasing as the injected block: one memory must not read as
129
137
  // "2026-10-20" in a tool result and "8 天前" in the prompt.
130
138
  const when = relativeTime(entry.updatedAt || entry.createdAt)
@@ -168,10 +176,14 @@ function formatPrivateItem(item, index, options = {}) {
168
176
 
169
177
  function formatGlobalItem(item, index, options = {}) {
170
178
  const entry = item.entry || {}
171
- const lines = [
172
- `${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`,
173
- ` domain=${entry.domain || 'unknown'} confidence=${entry.confidence ?? '?'}`,
174
- ]
179
+ const domain = entry.domain || 'unknown'
180
+ // B7:unknown 域是默认值,省略后模型仍能按 guide 的缺省口径理解;confidence 保留。
181
+ const head = [
182
+ domain !== 'unknown' ? `domain=${domain}` : '',
183
+ entry.confidence !== undefined ? `confidence=${entry.confidence}` : '',
184
+ ].filter(Boolean).join(' ')
185
+ const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
186
+ if (head) lines.push(` ${head}`)
175
187
  const when = relativeTime(entry.updatedAt || entry.createdAt)
176
188
  if (when) lines.push(` updated=${when}`)
177
189
  if (Array.isArray(entry.appliesTo) && entry.appliesTo.length > 0) lines.push(` applies_to=${entry.appliesTo.join(',')}`)
@@ -181,9 +193,80 @@ function formatGlobalItem(item, index, options = {}) {
181
193
  : truncate(item.content, 1200)
182
194
  lines.push(' ' + body.replace(/\n/g, '\n '))
183
195
  }
184
- return lines.join('\n')
196
+ return redactSecrets(lines.join('\n'))
197
+ }
198
+
199
+ /**
200
+ * 1.3.1:单条 remember 与批量 remember_batch 共用同一套参数映射,避免两处字段漂移。
201
+ * 批量工具把重复率最高的公共字段放在 defaults 里,每条 item 只补差异字段。
202
+ */
203
+ async function rememberFromArgs(exec, args = {}) {
204
+ return privateRemember({
205
+ exec,
206
+ content: args.content,
207
+ title: args.title,
208
+ layer: args.layer,
209
+ track: args.track,
210
+ attachments: args.attachments,
211
+ context: args.context,
212
+ pinReason: args.pin_reason,
213
+ pinSource: args.pin_source,
214
+ sideEventId: args.side_event_id,
215
+ tags: args.tags,
216
+ openLoop: args.open_loop,
217
+ commitment: args.commitment,
218
+ factKey: args.fact_key ?? null,
219
+ conflictsWith: args.conflicts_with ?? null,
220
+ supersedes: args.supersedes ?? null,
221
+ disclosure: args.disclosure,
222
+ owner: args.owner,
223
+ visibility: args.visibility,
224
+ source: args.source,
225
+ sourceKind: args.source_kind,
226
+ speakerId: args.speaker_id ?? null,
227
+ quoteSpan: args.quote_span ?? null,
228
+ storylineId: args.storyline_id,
229
+ branchId: args.branch_id,
230
+ knownBy: args.known_by,
231
+ confidence: args.confidence,
232
+ moodValence: args.mood_valence ?? null,
233
+ arousal: args.arousal ?? null,
234
+ emotion: args.emotion,
235
+ dominance: args.dominance ?? null,
236
+ peak: args.peak === true,
237
+ salientDate: args.salient_date ?? null,
238
+ observedAt: args.observed_at ?? null,
239
+ absoluteDate: args.absolute_date ?? null,
240
+ validFrom: args.valid_from,
241
+ validTo: args.valid_to,
242
+ datePrecision: args.date_precision,
243
+ allowDuplicate: args.allow_duplicate === true,
244
+ })
245
+ }
246
+
247
+ /** 把 privateRemember 的结果压成 worker 能直接读的一行/一段;去重与冲突必须显式说。 */
248
+ function describeRememberResult(result, label = '') {
249
+ const prefix = label ? label + ': ' : ''
250
+ if (result?.deduped === true) {
251
+ return `${prefix}未写入:库内已有几乎相同的记忆 [${result.existingId}](相似度 ${(Number(result.similarity) || 0).toFixed(2)});要补充请用 memu_private_update id=${result.existingId}。`
252
+ }
253
+ const entry = result?.entry
254
+ if (result?.conflict) {
255
+ return `${prefix}已记录但与 [${result.conflict}] 冲突,进入待复核(id=${entry?.id});复核前不会出现在召回或注入里。`
256
+ }
257
+ return `${prefix}已写入私有记忆:${result?.id} · layer=${entry?.layer || 'long_term'} · title=${entry?.title || ''}`
258
+ }
259
+
260
+ async function rememberOneOutcome(exec, args) {
261
+ try {
262
+ const result = await rememberFromArgs(exec, args)
263
+ return { ok: true, result, text: describeRememberResult(result) }
264
+ } catch (error) {
265
+ return { ok: false, text: '未写入:' + errorText(error).replace(/\n/g, ' ') }
266
+ }
185
267
  }
186
268
 
269
+
187
270
  export function registerTools(ctx, { only = null } = {}) {
188
271
  const tools = []
189
272
  // 全量注册(宿主装载)才更新全局 registrationReport:整理 worker 的按需挂载
@@ -211,7 +294,10 @@ export function registerTools(ctx, { only = null } = {}) {
211
294
  (args, exec) => {
212
295
  if (args.relationship) {
213
296
  const relation = args.relationship
214
- return JSON.stringify(updateRelationship({ exec, fromId: relation.fromEntity, toId: relation.toEntity, state: relation.state, evidenceIds: relation.evidenceIds, reason: args.note }))
297
+ const updated = updateRelationship({ exec, fromId: relation.fromEntity, toId: relation.toEntity, state: relation.state, evidenceIds: relation.evidenceIds, reason: args.note })
298
+ const r = updated?.relationship || updated || {}
299
+ // 完整 history(≤50 版)不进模型上下文:只回一行,需要细节时再查。
300
+ return `已更新关系 ${r.fromId ?? relation.fromEntity}→${r.toId ?? relation.toEntity} · revision ${r.revision ?? '?'} · evidence ${Array.isArray(r.evidenceIds) ? r.evidenceIds.length : 0}`
215
301
  }
216
302
  let toId = args.to
217
303
  if (args.entity) {
@@ -224,7 +310,9 @@ export function registerTools(ctx, { only = null } = {}) {
224
310
  if (existing.kind !== kind) throw new Error(`entity "${name}" already exists as ${existing.kind}; use that kind instead of ${kind}`)
225
311
  toId = existing.id
226
312
  } else {
227
- toId = createEntity({ exec, name, kind }).id
313
+ // worker 显式点名只创建实体与一条非 auto 边,不等于确认:
314
+ // allowWorkerAssertion 在 v3 是预留开关,确认仍由用户完成。
315
+ toId = createEntity({ exec, name, kind, status: 'provisional', origin: 'worker' }).id
228
316
  }
229
317
  }
230
318
  return JSON.stringify(linkEntries({ exec, fromId: args.from, toId, kind: args.kind, note: args.note, confidence: args.confidence }))
@@ -233,7 +321,7 @@ export function registerTools(ctx, { only = null } = {}) {
233
321
 
234
322
  tools.push(toolBase(
235
323
  'memu_private_link_suggest',
236
- 'Local algorithm pass over the memories this consolidation just wrote. It applies the high-confidence memory↔memory links and entity hubs itself and returns ONLY the uncertain candidate pairs for you to adjudicate with memu_private_link. Call it once after writing, with the ids you created or updated; it needs no extra transcript read and never returns full memory bodies.',
324
+ 'Local algorithm pass over the memories this consolidation just wrote. It refreshes only deterministic evidence edges (mentions of confirmed entities, conflicts_with / supersedes / same fact_key) and returns uncertain statistical pairs for you to adjudicate with memu_private_link. Similarity and shared tokens never create an edge. Call it once after writing, with the ids you created or updated; it needs no extra transcript read and never returns full memory bodies.',
237
325
  {
238
326
  ids: {
239
327
  type: 'array',
@@ -338,50 +426,8 @@ export function registerTools(ctx, { only = null } = {}) {
338
426
  }, additionalProperties: true, description: 'Stable identities only; scope inherits the conversation and cannot widen it.' },
339
427
  },
340
428
  async (args, exec) => {
341
- const result = await privateRemember({
342
- exec,
343
- content: args.content,
344
- title: args.title,
345
- layer: args.layer,
346
- track: args.track,
347
- attachments: args.attachments,
348
- context: args.context,
349
- pinReason: args.pin_reason,
350
- pinSource: args.pin_source,
351
- sideEventId: args.side_event_id,
352
- tags: args.tags,
353
- openLoop: args.open_loop,
354
- commitment: args.commitment,
355
- factKey: args.fact_key ?? null,
356
- conflictsWith: args.conflicts_with ?? null,
357
- supersedes: args.supersedes ?? null,
358
- disclosure: args.disclosure,
359
- owner: args.owner,
360
- visibility: args.visibility,
361
- source: args.source,
362
- sourceKind: args.source_kind,
363
- speakerId: args.speaker_id ?? null,
364
- quoteSpan: args.quote_span ?? null,
365
- storylineId: args.storyline_id,
366
- branchId: args.branch_id,
367
- knownBy: args.known_by,
368
- confidence: args.confidence,
369
- moodValence: args.mood_valence ?? null,
370
- arousal: args.arousal ?? null,
371
- // `undefined` means "the model said nothing" and is allowed to inherit the
372
- // turn's mood; `null` means "explicitly neutral" and must survive as such. Using
373
- // `?? null` here would erase that difference and re-inherit on a neutral call.
374
- emotion: args.emotion,
375
- dominance: args.dominance ?? null,
376
- peak: args.peak === true,
377
- salientDate: args.salient_date ?? null,
378
- observedAt: args.observed_at ?? null,
379
- absoluteDate: args.absolute_date ?? null,
380
- validFrom: args.valid_from,
381
- validTo: args.valid_to,
382
- datePrecision: args.date_precision,
383
- allowDuplicate: args.allow_duplicate === true,
384
- })
429
+ // D4:与 remember_batch 共用同一套参数映射,避免两处字段漂移。
430
+ const result = await rememberFromArgs(exec, args)
385
431
  // 事实级去重:几乎相同的重写被拒,返回的是
386
432
  // { deduped, existingId, hint },没有 entry——必须先接住,否则 result.entry.layer 抛错。
387
433
  if (result.deduped === true) {
@@ -411,6 +457,85 @@ export function registerTools(ctx, { only = null } = {}) {
411
457
  { timeoutMs: 180_000 },
412
458
  ))
413
459
 
460
+ tools.push(toolBase(
461
+ 'memu_private_remember_batch',
462
+ 'Write several private memories in one call. Put shared fields in defaults and only per-item differences in items; each item is one fact. Use this instead of calling memu_private_remember once per entry. Items that dedupe or conflict are reported per line.',
463
+ {
464
+ defaults: {
465
+ type: 'object',
466
+ properties: {
467
+ speaker_id: { type: 'string' },
468
+ source_kind: { type: 'string' },
469
+ source: { type: 'string' },
470
+ owner: { type: 'string' },
471
+ confidence: { type: 'number' },
472
+ observed_at: { type: 'string' },
473
+ absolute_date: { type: 'string' },
474
+ date_precision: { type: 'string' },
475
+ tags: { type: 'array', items: { type: 'string' } },
476
+ layer: { type: 'string' },
477
+ },
478
+ additionalProperties: true,
479
+ description: 'Shared fields for every item; per-item values override these.',
480
+ },
481
+ items: {
482
+ type: 'array',
483
+ description: '1-8 facts. Each item needs title + content; only include fields that differ from defaults.',
484
+ items: {
485
+ type: 'object',
486
+ properties: {
487
+ title: { type: 'string', required: true },
488
+ content: { type: 'string', required: true },
489
+ observed_at: { type: 'string' },
490
+ absolute_date: { type: 'string' },
491
+ date_precision: { type: 'string' },
492
+ speaker_id: { type: 'string' },
493
+ source_kind: { type: 'string' },
494
+ source: { type: 'string' },
495
+ owner: { type: 'string' },
496
+ confidence: { type: 'number' },
497
+ tags: { type: 'array', items: { type: 'string' } },
498
+ emotion: {
499
+ type: 'object',
500
+ properties: { joy: { type: 'number' }, anger: { type: 'number' }, sorrow: { type: 'number' }, fear: { type: 'number' } },
501
+ additionalProperties: false,
502
+ },
503
+ commitment: { type: 'object', additionalProperties: true },
504
+ conflicts_with: { type: 'string' },
505
+ salient_date: { type: 'string' },
506
+ open_loop: { type: 'boolean' },
507
+ layer: { type: 'string' },
508
+ },
509
+ additionalProperties: true,
510
+ },
511
+ },
512
+ },
513
+ async (args, exec) => {
514
+ const defaults = args?.defaults && typeof args.defaults === 'object' ? args.defaults : {}
515
+ const items = Array.isArray(args?.items) ? args.items.slice(0, 8) : []
516
+ if (items.length === 0) return '未写入:items 为空;每条至少需要 title 和 content。'
517
+ const lines = []
518
+ let written = 0
519
+ let deduped = 0
520
+ let held = 0
521
+ for (let index = 0; index < items.length; index += 1) {
522
+ const item = items[index]
523
+ if (!item || typeof item !== 'object') {
524
+ lines.push(`${index + 1}. 未写入:item 不是对象`)
525
+ continue
526
+ }
527
+ const outcome = await rememberOneOutcome(exec, { ...defaults, ...item })
528
+ lines.push(`${index + 1}. ${outcome.text}`)
529
+ if (!outcome.ok) continue
530
+ if (outcome.result?.deduped === true) deduped += 1
531
+ else if (outcome.result?.entry?.status === 'pending_review' || outcome.result?.conflict) held += 1
532
+ else written += 1
533
+ }
534
+ return [`批量写入完成:新增 ${written} · 去重 ${deduped} · 待复核 ${held}`, ...lines].join('\n')
535
+ },
536
+ { timeoutMs: 300_000 },
537
+ ))
538
+
414
539
  tools.push(toolBase(
415
540
  'memu_private_recall',
416
541
  'Retrieve relevant private memories from the library bound to this conversation. Use it when the user refers to something from before, asks you to remember, or the current task may depend on earlier context.',
@@ -435,18 +560,25 @@ export function registerTools(ctx, { only = null } = {}) {
435
560
 
436
561
  tools.push(toolBase(
437
562
  'memu_private_list',
438
- '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.',
439
- {},
440
- async (_args, exec) => {
563
+ '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. Paged: default 50 rows, use offset to continue.',
564
+ {
565
+ limit: { type: 'number', description: 'Rows in this page; default 50, max 200.' },
566
+ offset: { type: 'number', description: '0-based row offset; for the next page pass the last returned offset + count.' },
567
+ },
568
+ async (args, exec) => {
441
569
  // A list is a pure read: if the conversation has no binding yet, say so
442
570
  // instead of ensureSession() silently creating a placeholder library.
443
571
  if (!peekBinding(exec)?.libraryId) return '当前对话没有绑定记忆库。'
444
- const result = await privateList({ exec })
572
+ const limit = Math.min(200, Math.max(1, Math.floor(Number(args?.limit) || 50)))
573
+ const offset = Math.max(0, Math.floor(Number(args?.offset) || 0))
574
+ const result = await privateList({ exec, limit, offset })
445
575
  const warning = result.warning ? `\n注意:${result.warning}` : ''
446
576
  const foreign = (result.libraries || []).filter((library) => library.id !== result.libraryId)
447
577
  const scopeNote = foreign.length ? `,跨库=${foreign.map((library) => library.name || library.id).join(',')}` : ''
448
- if (!result.files?.length) return `私有记忆库 ${result.libraryId} 为空${scopeNote}。${warning}`
449
- const lines = [`私有记忆库 ${result.libraryId}(${result.files.length} 条${scopeNote})`]
578
+ const total = Number.isFinite(result.total) ? result.total : (result.files?.length || 0)
579
+ if (!total) return `私有记忆库 ${result.libraryId} 为空${scopeNote}。${warning}`
580
+ const pageEnd = offset + (result.files?.length || 0)
581
+ const lines = [`私有记忆库 ${result.libraryId}(共 ${total} 条,本页 ${offset + 1}-${pageEnd}${scopeNote})`]
450
582
  for (const file of result.files) {
451
583
  const e = file.entry || {}
452
584
  const tag = salientTag(e)
@@ -455,7 +587,8 @@ export function registerTools(ctx, { only = null } = {}) {
455
587
  : ''
456
588
  lines.push(`- [${file.name}] ${e.title || file.description || '(untitled)'} · ${e.layer || 'long_term'} · ${e.status || 'active'}${e.marginalized ? ' · marginalized' : ''}${tag ? ` · ${tag}` : ''}${owner}`)
457
589
  }
458
- return lines.join('\n') + warning
590
+ const more = pageEnd < total ? `\n还有 ${total - pageEnd} 条:用 offset=${pageEnd} 继续。` : ''
591
+ return redactSecrets(lines.join('\n')) + more + warning
459
592
  },
460
593
  { isConcurrencySafe: () => true },
461
594
  ))
@@ -599,7 +732,7 @@ export function registerTools(ctx, { only = null } = {}) {
599
732
  evidence ? ` evidence=${truncate(evidence, 200)}` : '',
600
733
  ].filter(Boolean).join('\n'))
601
734
  }
602
- return lines.join('\n') + warning
735
+ return redactSecrets(lines.join('\n')) + warning
603
736
  },
604
737
  { isConcurrencySafe: () => true },
605
738
  ))
@@ -719,7 +852,6 @@ export function registerTools(ctx, { only = null } = {}) {
719
852
  const pinned = Object.values(privateIndex.entries || {}).filter((e) => e.layer === 'must_remember' && e.status !== 'archived').length
720
853
  const activeEntries = Object.values(privateIndex.entries || {}).filter((e) => !['archived', 'suppressed', 'expired'].includes(e.status))
721
854
  const shortCount = activeEntries.filter((e) => e.layer === 'short_term').length
722
- const privateCount = Object.keys(privateIndex.entries || {}).filter((id) => privateIndex.entries[id].status !== 'archived').length
723
855
  const globalCount = Object.keys(globalIndex.entries || {}).filter((id) => ['active'].includes(globalIndex.entries[id].status || 'active')).length
724
856
  const health = storageHealth()
725
857
  const storageLines = []
@@ -753,7 +885,7 @@ export function registerTools(ctx, { only = null } = {}) {
753
885
  `library: ${library ? `${library.name} (${library.id})` : 'none'}`,
754
886
  `domain: ${domainOf(binding)}`,
755
887
  `useLibrary=${binding?.useLibrary !== false} useGlobal=${binding?.useGlobal !== false} autoInject=${settings.autoInject}`,
756
- `private: ${privateCount} active, ${pinned}/${settings.mustRememberCap} pinned`,
888
+ `private: ${activeEntries.length} active, ${pinned}/${settings.mustRememberCap} pinned`,
757
889
  `short_term: ${shortCount} active (ttl ${Number(settings.shortTermTtlHours) || 0}h)`,
758
890
  `global: ${globalCount} active`,
759
891
  `libraries: ${libraries.length}`,
@@ -1,62 +1 @@
1
- d3-force
2
- Copyright 2010-2021 Mike Bostock
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any purpose
5
- with or without fee is hereby granted, provided that the above copyright notice
6
- and this permission notice appear in all copies.
7
-
8
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
10
- FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
11
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
12
- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
13
- TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
14
- THIS SOFTWARE.
15
-
16
-
17
- d3-dispatch
18
- Copyright 2010-2021 Mike Bostock
19
-
20
- Permission to use, copy, modify, and/or distribute this software for any purpose
21
- with or without fee is hereby granted, provided that the above copyright notice
22
- and this permission notice appear in all copies.
23
-
24
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
25
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
26
- FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
27
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
28
- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
29
- TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
30
- THIS SOFTWARE.
31
-
32
-
33
- d3-quadtree
34
- Copyright 2010-2021 Mike Bostock
35
-
36
- Permission to use, copy, modify, and/or distribute this software for any purpose
37
- with or without fee is hereby granted, provided that the above copyright notice
38
- and this permission notice appear in all copies.
39
-
40
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
41
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
42
- FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
43
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
44
- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
45
- TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
46
- THIS SOFTWARE.
47
-
48
-
49
- d3-timer
50
- Copyright 2010-2021 Mike Bostock
51
-
52
- Permission to use, copy, modify, and/or distribute this software for any purpose
53
- with or without fee is hereby granted, provided that the above copyright notice
54
- and this permission notice appear in all copies.
55
-
56
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
57
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
58
- FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
59
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
60
- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
61
- TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
62
- THIS SOFTWARE.
1
+ graph-view.bundle.js: 本 bundle 无第三方运行时依赖(自研力导向引擎)。