dsh-memu-memory 1.3.6 → 1.3.8
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/AGENTS.md +2 -1
- package/CHANGELOG.md +87 -0
- package/README.md +7 -7
- package/README.zh.md +7 -7
- package/docs/client-conventions.md +4 -0
- package/docs/contributing.md +2 -2
- package/docs/memory-semantics.md +10 -7
- package/docs/troubleshooting.md +132 -7
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +296 -122
- package/lib/consolidation-ledger.js +6 -2
- package/lib/consolidation-worker.js +7 -0
- package/lib/inbound.js +24 -9
- package/lib/inject.js +379 -215
- package/lib/lexicon.js +5 -0
- package/lib/local-embedding-manager.js +4 -0
- package/lib/local-vector-service.js +65 -1
- package/lib/memory.js +711 -175
- package/lib/paths.js +24 -0
- package/lib/private.js +284 -127
- package/lib/rpc.js +144 -45
- package/lib/snippet.js +49 -28
- package/lib/state.js +185 -26
- package/lib/tools.js +150 -31
- package/lib/webui/standalone.css +28 -1
- package/lib/webui.js +25 -1
- package/lib/worker-pool.js +260 -26
- package/package.json +1 -1
- package/scripts/check-i18n.mjs +19 -0
- package/scripts/recall-bench.mjs +4 -4
- package/scripts/simulate-injection.mjs +3 -0
- package/tests/activity-wiring.test.mjs +52 -0
- package/tests/client-render.test.mjs +207 -0
- package/tests/consolidation-feed.test.mjs +26 -0
- package/tests/consolidation-fork.test.mjs +618 -33
- package/tests/consolidation-snapshot.test.mjs +2 -1
- package/tests/cross-library-recall.test.mjs +156 -0
- package/tests/cue.test.mjs +15 -2
- package/tests/hybrid-recall.test.mjs +488 -0
- package/tests/inbound.test.mjs +49 -4
- package/tests/inject-conflict.test.mjs +70 -9
- package/tests/inject-guide.test.mjs +13 -1
- package/tests/inject.test.mjs +10 -0
- package/tests/injection-budget.test.mjs +101 -0
- package/tests/injection-chain.test.mjs +37 -0
- package/tests/injection-rollback.test.mjs +172 -9
- package/tests/issue2-chain.test.mjs +169 -0
- package/tests/lexicon-inject.test.mjs +33 -5
- package/tests/lexicon-ui.test.mjs +99 -2
- package/tests/managed-memory.test.mjs +625 -1
- package/tests/media.test.mjs +1 -1
- package/tests/new-session-gate.test.mjs +280 -25
- package/tests/open-loop-date.test.mjs +11 -1
- package/tests/recall-intent.test.mjs +52 -3
- package/tests/simulate-injection.test.mjs +4 -4
- package/tests/snippet.test.mjs +33 -1
- package/tests/state.test.mjs +8 -3
- package/tests/tool-schema.test.mjs +52 -0
- package/tests/tools.test.mjs +394 -0
- package/tests/webui.test.mjs +16 -2
- package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/state.js
CHANGED
|
@@ -2,7 +2,7 @@ import fs from 'node:fs'
|
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import crypto from 'node:crypto'
|
|
4
4
|
import {
|
|
5
|
-
dataDir, librariesDir, indexDir, backupsDir,
|
|
5
|
+
dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
|
|
6
6
|
ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
|
|
7
7
|
} from './paths.js'
|
|
8
8
|
import {
|
|
@@ -822,7 +822,16 @@ export function getSessionBinding(sessionId) {
|
|
|
822
822
|
export function setSessionBinding(sessionId, patch) {
|
|
823
823
|
return updateState((state) => {
|
|
824
824
|
const previous = state.sessions[sessionId] || {}
|
|
825
|
-
|
|
825
|
+
const next = { ...previous, ...(patch || {}) }
|
|
826
|
+
for (const key of ['lastInjectedUserMessageId', 'guideRulesKey', 'guideMessageAt', 'anchorPushed']) {
|
|
827
|
+
if (!Object.hasOwn(patch || {}, key)) continue
|
|
828
|
+
next.injectionOwners = { ...(next.injectionOwners || {}), [key]: `legacy:${crypto.randomUUID()}` }
|
|
829
|
+
}
|
|
830
|
+
const scopeFields = ['libraryId', 'scopeKey', 'memoryContext', 'useLibrary', 'useGlobal', 'domainOverride']
|
|
831
|
+
if (scopeFields.some(key => Object.hasOwn(patch || {}, key) && JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) {
|
|
832
|
+
next.scopeGeneration = Number(previous.scopeGeneration || 0) + 1
|
|
833
|
+
}
|
|
834
|
+
state.sessions[sessionId] = next
|
|
826
835
|
return state
|
|
827
836
|
}).sessions[sessionId]
|
|
828
837
|
}
|
|
@@ -887,10 +896,11 @@ export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, c
|
|
|
887
896
|
useGlobal: wantsGlobal,
|
|
888
897
|
scopeKey,
|
|
889
898
|
domain: existing?.domain || detectDomain({ agentPreset, cwd }),
|
|
890
|
-
//
|
|
891
|
-
//
|
|
892
|
-
//
|
|
893
|
-
domainOverride: existing?.domainOverride ??
|
|
899
|
+
// 未被问过的新会话不再硬编码 RP 兜底(issue #2 缺陷 2):领域跟随 detectDomain
|
|
900
|
+
// 的文件夹/预设判定,与上方 domain 字段同一口径。弹窗或侧栏写下的显式答案会
|
|
901
|
+
// 覆盖这里,并留下 domainSource:'chosen' 作为「已答」的凭据。
|
|
902
|
+
domainOverride: existing?.domainOverride ?? detectDomain({ agentPreset, cwd }),
|
|
903
|
+
domainSource: existing?.domainSource ?? 'auto',
|
|
894
904
|
injectedIds: existing?.injectedIds || [],
|
|
895
905
|
injectedAt: existing?.injectedAt || {},
|
|
896
906
|
lastInjectedTurn: existing?.lastInjectedTurn ?? 0,
|
|
@@ -912,6 +922,91 @@ export function deleteSessionBinding(sessionId) {
|
|
|
912
922
|
})
|
|
913
923
|
}
|
|
914
924
|
|
|
925
|
+
// Only typed, host-admitted records prove content identity. Legacy bare ids do not.
|
|
926
|
+
export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
|
|
927
|
+
const window = Number(dedupeTurns)
|
|
928
|
+
const clock = Number(memoryClock)
|
|
929
|
+
if (!(window > 0) || !Number.isFinite(clock)) return []
|
|
930
|
+
const latest = new Map()
|
|
931
|
+
const revoked = new Set(binding?.revokedInjectionMessages || [])
|
|
932
|
+
for (const record of binding?.acceptedMemoryMessages || []) {
|
|
933
|
+
if (record.generation !== Number(binding.scopeGeneration || 0)
|
|
934
|
+
|| record.epoch !== Number(binding.injectionEpoch || 0) || revoked.has(record.messageId)) continue
|
|
935
|
+
for (const ref of record.refs || []) {
|
|
936
|
+
const key = memoryRefKey(ref)
|
|
937
|
+
const previous = latest.get(key)
|
|
938
|
+
if (!previous || record.memoryClock >= previous.clock) latest.set(key, { ref, clock: record.memoryClock })
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
return [...latest.values()].filter(item => item.clock <= clock && clock - item.clock < window)
|
|
942
|
+
.map(item => ({ ...item.ref }))
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** Commit one immutable message after its exact body entered host history. No entry bodies. */
|
|
946
|
+
export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
|
|
947
|
+
if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
|
|
948
|
+
let committed = null
|
|
949
|
+
updateState(state => {
|
|
950
|
+
const binding = state.sessions[sessionId]
|
|
951
|
+
if (!binding) return state
|
|
952
|
+
const records = binding.acceptedMemoryMessages || []
|
|
953
|
+
if (records.some(record => record.messageId === options.messageId)) return state
|
|
954
|
+
const generation = Number(options.generation ?? binding.scopeGeneration ?? 0)
|
|
955
|
+
const epoch = Number(options.epoch ?? binding.injectionEpoch ?? 0)
|
|
956
|
+
if (generation !== Number(binding.scopeGeneration || 0) || epoch !== Number(binding.injectionEpoch || 0)) return state
|
|
957
|
+
const typed = (refs || []).filter(ref => ref && ['private', 'global'].includes(ref.scope)
|
|
958
|
+
&& typeof ref.id === 'string' && typeof ref.revision === 'string'
|
|
959
|
+
&& (ref.scope === 'global' || typeof ref.libraryId === 'string'))
|
|
960
|
+
.map(ref => ({ scope: ref.scope, libraryId: ref.libraryId ?? null, id: ref.id, revision: ref.revision,
|
|
961
|
+
...(ref.groupKey !== undefined ? { groupKey: ref.groupKey } : {}),
|
|
962
|
+
...(ref.groupRevision !== undefined ? { groupRevision: ref.groupRevision } : {}) }))
|
|
963
|
+
committed = { messageId: options.messageId, hostTurn: options.hostTurn ?? null, generation, epoch,
|
|
964
|
+
memoryClock: Number(memoryClock), refs: typed, admittedAt: stamp() }
|
|
965
|
+
const next = [...records, committed]
|
|
966
|
+
let count = next.reduce((sum, record) => sum + record.refs.length, 0)
|
|
967
|
+
while (next.length > 1 && (count > 400 || next.length > 400)) count -= next.shift().refs.length
|
|
968
|
+
if (count > 400) committed.refs = committed.refs.slice(-400)
|
|
969
|
+
binding.acceptedMemoryMessages = next
|
|
970
|
+
// Old anchor consumers retain their compatibility view, never a typed cooldown.
|
|
971
|
+
const ids = typed.map(ref => ref.id)
|
|
972
|
+
if ((binding.injectedIds || []).includes('__anchor__')) binding.anchorPushed = true
|
|
973
|
+
binding.injectedIds = [...new Set([...(binding.injectedIds || []).filter(id => id !== '__anchor__'), ...ids])].slice(-400)
|
|
974
|
+
binding.injectedAt = { ...(binding.injectedAt || {}) }
|
|
975
|
+
binding.injectionOwners = { ...(binding.injectionOwners || {}) }
|
|
976
|
+
binding.injectionOwnerClocks = { ...(binding.injectionOwnerClocks || {}) }
|
|
977
|
+
committed.effects = {}
|
|
978
|
+
const applyEffect = (key, value, field = key, id = null) => {
|
|
979
|
+
const owner = binding.injectionOwners[key]
|
|
980
|
+
const priorClock = typeof owner === 'string' && owner.startsWith('legacy:')
|
|
981
|
+
? Math.max(Number(binding.lastInjectedTurn || 0), Number(binding.inbound?.clock || 0), Number(binding.injectionOwnerClocks[key] || 0))
|
|
982
|
+
: binding.injectionOwnerClocks[key] ?? records.find(record => record.messageId === owner)?.memoryClock ?? -1
|
|
983
|
+
if (Number(priorClock) > Number(memoryClock)) return
|
|
984
|
+
const previous = id === null ? binding[field] : binding[field]?.[id]
|
|
985
|
+
committed.effects[key] = { value: structuredClone(previous), owner: binding.injectionOwners[key] ?? null,
|
|
986
|
+
clock: binding.injectionOwnerClocks[key] ?? null, field, id }
|
|
987
|
+
if (id === null) binding[field] = structuredClone(value)
|
|
988
|
+
else binding[field] = { ...(binding[field] || {}), [id]: structuredClone(value) }
|
|
989
|
+
binding.injectionOwners[key] = options.messageId
|
|
990
|
+
binding.injectionOwnerClocks[key] = Number(memoryClock)
|
|
991
|
+
}
|
|
992
|
+
for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
|
|
993
|
+
const actions = structuredClone(options.actions || {})
|
|
994
|
+
const patch = actions.patch || {}
|
|
995
|
+
if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
|
|
996
|
+
if (actions.cue) patch.activeCue = { id: String(actions.cue.id), text: String(actions.cue.text || '').slice(0, 500),
|
|
997
|
+
sourceId: actions.cue.sourceId ? String(actions.cue.sourceId) : null,
|
|
998
|
+
recallQuery: actions.cue.recallQuery ? String(actions.cue.recallQuery).slice(0, 200) : null, createdAt: stamp() }
|
|
999
|
+
if (actions.lexicon?.selected?.length) patch.lexiconInjectionClock = Number(memoryClock)
|
|
1000
|
+
for (const [key, value] of Object.entries(patch)) applyEffect(key, value)
|
|
1001
|
+
for (const [id, day] of Object.entries(actions.anniversaries || {})) applyEffect(`anniversary:${id}`, day, 'anniversariesShown', id)
|
|
1002
|
+
for (const id of actions.nudgeIds || []) applyEffect(`nudge:${id}`, stamp(), 'openLoopRemindedAt', id)
|
|
1003
|
+
binding.lastInjectedTurn = Math.max(Number(binding.lastInjectedTurn || 0), Number(memoryClock))
|
|
1004
|
+
if (typed.length || actions.anchor) binding.lastInjectedAt = stamp()
|
|
1005
|
+
return state
|
|
1006
|
+
})
|
|
1007
|
+
return committed ? structuredClone(committed) : null
|
|
1008
|
+
}
|
|
1009
|
+
|
|
915
1010
|
export function markInjected(sessionId, ids, turn) {
|
|
916
1011
|
if (!sessionId) return
|
|
917
1012
|
return updateState((state) => {
|
|
@@ -927,9 +1022,14 @@ export function markInjected(sessionId, ids, turn) {
|
|
|
927
1022
|
...incoming.filter((id) => id !== '__anchor__'),
|
|
928
1023
|
])]
|
|
929
1024
|
binding.injectedIds = merged.slice(-400)
|
|
930
|
-
|
|
1025
|
+
const owner = `legacy:${crypto.randomUUID()}`
|
|
1026
|
+
binding.injectionOwners = { ...(binding.injectionOwners || {}) }
|
|
1027
|
+
if (anchor) { binding.anchorPushed = true; binding.injectionOwners.anchorPushed = owner }
|
|
931
1028
|
const at = { ...(binding.injectedAt || {}) }
|
|
932
|
-
for (const id of incoming)
|
|
1029
|
+
for (const id of incoming) {
|
|
1030
|
+
at[id] = turn ?? Date.now()
|
|
1031
|
+
binding.injectionOwners[`id:${id}`] = owner
|
|
1032
|
+
}
|
|
933
1033
|
binding.injectedAt = at
|
|
934
1034
|
binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
|
|
935
1035
|
// 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
|
|
@@ -969,13 +1069,15 @@ export function releaseInjected(sessionId) { return updateState((state) => {
|
|
|
969
1069
|
if (binding) {
|
|
970
1070
|
binding.injectedIds = []
|
|
971
1071
|
binding.injectedAt = {}
|
|
1072
|
+
binding.injectionEpoch = Number(binding.injectionEpoch || 0) + 1
|
|
972
1073
|
}
|
|
973
1074
|
return state
|
|
974
1075
|
})
|
|
975
1076
|
}
|
|
976
1077
|
|
|
977
1078
|
export function markReinjectPending(sessionId) {
|
|
978
|
-
|
|
1079
|
+
const binding = getSessionBinding(sessionId)
|
|
1080
|
+
return setSessionBinding(sessionId, { reinjectPending: true, injectionEpoch: Number(binding?.injectionEpoch || 0) + 1 })
|
|
979
1081
|
}
|
|
980
1082
|
|
|
981
1083
|
export function clearReinjectPending(sessionId) {
|
|
@@ -1072,7 +1174,8 @@ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
|
|
|
1072
1174
|
// Keep only the current day's keys so the map cannot grow without bound.
|
|
1073
1175
|
const fresh = Object.fromEntries(Object.entries(shown).filter(([, v]) => v === dayKey))
|
|
1074
1176
|
fresh[memoryId] = dayKey
|
|
1075
|
-
return setSessionBinding(sessionId, { anniversariesShown: fresh
|
|
1177
|
+
return setSessionBinding(sessionId, { anniversariesShown: fresh,
|
|
1178
|
+
injectionOwners: { ...(binding?.injectionOwners || {}), [`anniversary:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
|
|
1076
1179
|
}
|
|
1077
1180
|
|
|
1078
1181
|
// ── repeated open loops ────────────────────────────────────────────────────────
|
|
@@ -1127,7 +1230,8 @@ export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
|
|
|
1127
1230
|
const when = at instanceof Date ? at : new Date(at)
|
|
1128
1231
|
const reminded = prunedOpenLoopReminded(sessionId, when)
|
|
1129
1232
|
reminded[memoryId] = when.toISOString()
|
|
1130
|
-
return setSessionBinding(sessionId, { openLoopRemindedAt: reminded
|
|
1233
|
+
return setSessionBinding(sessionId, { openLoopRemindedAt: reminded,
|
|
1234
|
+
injectionOwners: { ...(getSessionBinding(sessionId)?.injectionOwners || {}), [`nudge:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
|
|
1131
1235
|
}
|
|
1132
1236
|
|
|
1133
1237
|
/**
|
|
@@ -1145,6 +1249,11 @@ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKe
|
|
|
1145
1249
|
const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
|
|
1146
1250
|
binding.injectionRollback = {
|
|
1147
1251
|
hostTurn: turn,
|
|
1252
|
+
epoch: Number(binding.injectionEpoch || 0),
|
|
1253
|
+
generation: Number(binding.scopeGeneration || 0),
|
|
1254
|
+
snapshot: { owners: { ...binding.injectionOwners }, injectedAt: { ...binding.injectedAt }, anchorPushed: binding.anchorPushed,
|
|
1255
|
+
lastInjectedUserMessageId: binding.lastInjectedUserMessageId, guideMessageAt: binding.guideMessageAt,
|
|
1256
|
+
anniversariesShown: { ...binding.anniversariesShown }, openLoopRemindedAt: { ...binding.openLoopRemindedAt } },
|
|
1148
1257
|
ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
|
|
1149
1258
|
nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
|
|
1150
1259
|
anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
|
|
@@ -1162,30 +1271,80 @@ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKe
|
|
|
1162
1271
|
* 转录实证判定(inject.js 的 injectionAdmissions),所以走到这里的内容确实没进转录,
|
|
1163
1272
|
* 下一轮重投不会出现第二份。返回撤回了什么,供活动日志留信号。
|
|
1164
1273
|
*/
|
|
1165
|
-
export function rollbackInjectionForTurn(sessionId, hostTurn) {
|
|
1274
|
+
export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [], epoch = null } = {}) {
|
|
1166
1275
|
const turn = Number(hostTurn)
|
|
1167
1276
|
if (!sessionId || !Number.isSafeInteger(turn)) return null
|
|
1168
1277
|
let rolled = null
|
|
1169
1278
|
updateState((state) => {
|
|
1170
1279
|
const binding = state.sessions[sessionId]
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1280
|
+
if (!binding) return state
|
|
1281
|
+
// Explicit host rollback evidence can revoke individual accepted messages. A model
|
|
1282
|
+
// request failure alone must never call this branch. Preserve immutable records.
|
|
1283
|
+
const targets = (binding.acceptedMemoryMessages || []).filter(record => record.hostTurn === turn
|
|
1284
|
+
&& messageIds.includes(record.messageId) && (epoch === null || record.epoch === epoch))
|
|
1285
|
+
for (const accepted of targets.reverse()) {
|
|
1286
|
+
binding.revokedInjectionMessages = [...new Set([...(binding.revokedInjectionMessages || []), accepted.messageId])].slice(-400)
|
|
1287
|
+
if (accepted.epoch !== Number(binding.injectionEpoch || 0) || accepted.generation !== Number(binding.scopeGeneration || 0)) continue
|
|
1288
|
+
for (const [key, saved] of Object.entries(accepted.effects || {})) {
|
|
1289
|
+
if (binding.injectionOwners?.[key] !== accepted.messageId) continue
|
|
1290
|
+
let previous = saved
|
|
1291
|
+
const visited = new Set()
|
|
1292
|
+
while (previous.owner && binding.revokedInjectionMessages.includes(previous.owner) && !visited.has(previous.owner)) {
|
|
1293
|
+
visited.add(previous.owner)
|
|
1294
|
+
const revoked = (binding.acceptedMemoryMessages || []).find(record => record.messageId === previous.owner)
|
|
1295
|
+
previous = revoked?.effects?.[key] || { ...previous, value: undefined, owner: null, clock: null }
|
|
1296
|
+
}
|
|
1297
|
+
const field = previous.field || key
|
|
1298
|
+
if (previous.id !== undefined && previous.id !== null) {
|
|
1299
|
+
if (previous.value === undefined) delete binding[field]?.[previous.id]
|
|
1300
|
+
else binding[field] = { ...(binding[field] || {}), [previous.id]: structuredClone(previous.value) }
|
|
1301
|
+
if (field === 'injectedAt' && previous.value === undefined) binding.injectedIds = (binding.injectedIds || []).filter(id => id !== previous.id)
|
|
1302
|
+
} else if (previous.value === undefined) delete binding[field]
|
|
1303
|
+
else binding[field] = structuredClone(previous.value)
|
|
1304
|
+
if (previous.owner) binding.injectionOwners[key] = previous.owner
|
|
1305
|
+
else delete binding.injectionOwners[key]
|
|
1306
|
+
if (previous.clock !== undefined && previous.clock !== null) binding.injectionOwnerClocks[key] = previous.clock
|
|
1307
|
+
else delete binding.injectionOwnerClocks?.[key]
|
|
1308
|
+
}
|
|
1309
|
+
for (const ref of accepted.refs) {
|
|
1310
|
+
if (accepted.effects?.[`id:${ref.id}`] || binding.injectionOwners?.[`id:${ref.id}`] !== accepted.messageId) continue
|
|
1311
|
+
delete binding.injectedAt?.[ref.id]
|
|
1312
|
+
binding.injectedIds = (binding.injectedIds || []).filter(id => id !== ref.id)
|
|
1313
|
+
delete binding.injectionOwners[`id:${ref.id}`]
|
|
1314
|
+
}
|
|
1315
|
+
for (const key of Object.keys(binding.injectionOwners || {})) {
|
|
1316
|
+
if (binding.injectionOwners[key] !== accepted.messageId) continue
|
|
1317
|
+
if (key.startsWith('anniversary:')) delete binding.anniversariesShown?.[key.slice(12)]
|
|
1318
|
+
if (key.startsWith('nudge:')) delete binding.openLoopRemindedAt?.[key.slice(6)]
|
|
1319
|
+
delete binding.injectionOwners[key]
|
|
1320
|
+
}
|
|
1177
1321
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1322
|
+
if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
|
|
1323
|
+
const record = binding.injectionRollback
|
|
1324
|
+
if (!record || record.hostTurn !== turn) return state
|
|
1325
|
+
const snapshot = record.snapshot || {}
|
|
1326
|
+
const owners = binding.injectionOwners || {}
|
|
1327
|
+
const sameEpoch = record.epoch === Number(binding.injectionEpoch || 0)
|
|
1328
|
+
&& Number(record.generation || 0) === Number(binding.scopeGeneration || 0)
|
|
1329
|
+
const owns = key => owners[key] === snapshot.owners?.[key] && (!owners[key] || owners[key].startsWith('legacy:'))
|
|
1330
|
+
const ids = new Set((record.ids || []).filter(id => sameEpoch && owns(`id:${id}`)
|
|
1331
|
+
&& binding.injectedAt?.[id] === snapshot.injectedAt?.[id]))
|
|
1332
|
+
binding.injectedIds = (binding.injectedIds || []).filter(id => !ids.has(id))
|
|
1333
|
+
if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
|
|
1334
|
+
if (sameEpoch && ids.has('__anchor__') && owns('anchorPushed') && binding.anchorPushed === snapshot.anchorPushed) delete binding.anchorPushed
|
|
1335
|
+
if (sameEpoch && snapshot.lastInjectedUserMessageId !== undefined && owns('lastInjectedUserMessageId')
|
|
1336
|
+
&& binding.lastInjectedUserMessageId === snapshot.lastInjectedUserMessageId) delete binding.lastInjectedUserMessageId
|
|
1337
|
+
if (sameEpoch && owns('guideRulesKey') && record.guideKey && binding.guideRulesKey === record.guideKey
|
|
1338
|
+
&& binding.guideMessageAt === snapshot.guideMessageAt) {
|
|
1184
1339
|
delete binding.guideRulesKey
|
|
1185
1340
|
delete binding.guideMessageAt
|
|
1186
1341
|
}
|
|
1187
|
-
if (binding.anniversariesShown) for (const id of record.anniversaryIds || [])
|
|
1188
|
-
|
|
1342
|
+
if (sameEpoch && binding.anniversariesShown) for (const id of record.anniversaryIds || []) {
|
|
1343
|
+
if (owns(`anniversary:${id}`) && binding.anniversariesShown[id] === snapshot.anniversariesShown?.[id]) delete binding.anniversariesShown[id]
|
|
1344
|
+
}
|
|
1345
|
+
if (sameEpoch && binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) {
|
|
1346
|
+
if (owns(`nudge:${id}`) && binding.openLoopRemindedAt[id] === snapshot.openLoopRemindedAt?.[id]) delete binding.openLoopRemindedAt[id]
|
|
1347
|
+
}
|
|
1189
1348
|
rolled = {
|
|
1190
1349
|
ids: [...ids],
|
|
1191
1350
|
guideKey: record.guideKey || null,
|
package/lib/tools.js
CHANGED
|
@@ -2,10 +2,11 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
|
2
2
|
import {
|
|
3
3
|
privateRemember, privateRecall, privateList, privateUpdate, privateArchive,
|
|
4
4
|
privateUnpin, globalRecall, globalList, bindingFor, peekBinding, sessionIdOf, domainOf, relativeTime,
|
|
5
|
-
isDatedSalientDate,
|
|
5
|
+
isDatedSalientDate, readMemoryByRef,
|
|
6
6
|
} from './memory.js'
|
|
7
7
|
import { engineStatus, ENGINE_VERSION } from './engine.js'
|
|
8
|
-
import {
|
|
8
|
+
import { getMissingVectorLibraries } from './local-vector-service.js'
|
|
9
|
+
import { centeredSnippetWindow } from './snippet.js'
|
|
9
10
|
import { redactSecrets } from './paths.js'
|
|
10
11
|
import { linkEntries, createEntity, listEntities, updateRelationship } from './graph.js'
|
|
11
12
|
import { normalizeEntityName } from './private-links.js'
|
|
@@ -33,7 +34,97 @@ function errorText(error) {
|
|
|
33
34
|
if (error?.code === 'MEMU_COMMAND_FAILED') {
|
|
34
35
|
return `MemU 命令失败:${message}`
|
|
35
36
|
}
|
|
36
|
-
|
|
37
|
+
const code = typeof error?.code === 'string' && /^[A-Z][A-Z0-9_]{0,79}$/.test(error.code) ? ` [${error.code}]` : ''
|
|
38
|
+
return `dsh-memu-memory error${code}: ${redactSecrets(message)}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function recallError(code, message) {
|
|
42
|
+
throw Object.assign(new Error(message), { code })
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// The host's value-schema DSL has no minimum/maximum or cross-field rules.
|
|
46
|
+
// Validate before any memory access; natural searches cannot target a library.
|
|
47
|
+
function parseRecallRequest(args, scope) {
|
|
48
|
+
if (typeof args.query !== 'string' || !args.query.trim()) recallError('INVALID_RECALL_ARGUMENT', 'query is required')
|
|
49
|
+
const exact = !/\s/.test(args.query) && /^g?mem[-_][a-z0-9_-]+(?:\.md)?$/i.test(args.query)
|
|
50
|
+
const view = args.view === undefined ? 'auto' : args.view
|
|
51
|
+
if (!['auto', 'snippet', 'full'].includes(view)) recallError('INVALID_RECALL_ARGUMENT', 'view must be auto, snippet or full')
|
|
52
|
+
if (args.topK !== undefined && (!Number.isInteger(args.topK) || args.topK < 1 || args.topK > 20)) {
|
|
53
|
+
recallError('INVALID_RECALL_ARGUMENT', 'topK must be an integer in 1..20')
|
|
54
|
+
}
|
|
55
|
+
if (!exact && view === 'full') recallError('EXACT_ID_REQUIRED', 'view=full requires an exact memory id (no whitespace)')
|
|
56
|
+
if (!exact && ['libraryId', 'offset', 'limitChars', 'revision'].some((key) => Object.hasOwn(args, key))) {
|
|
57
|
+
recallError('INVALID_RECALL_ARGUMENT', 'libraryId/offset/limitChars/revision require an exact memory id, not a natural-language query')
|
|
58
|
+
}
|
|
59
|
+
if (Object.hasOwn(args, 'libraryId') && (scope !== 'private' || typeof args.libraryId !== 'string' || !args.libraryId.trim())) {
|
|
60
|
+
recallError('INVALID_RECALL_ARGUMENT', 'libraryId is a nonempty string for private exact reads only')
|
|
61
|
+
}
|
|
62
|
+
const offset = args.offset === undefined ? 0 : args.offset
|
|
63
|
+
const limitChars = args.limitChars === undefined ? 2000 : args.limitChars
|
|
64
|
+
if (!Number.isSafeInteger(offset) || offset < 0) recallError('INVALID_RECALL_ARGUMENT', 'offset must be an integer >= 0')
|
|
65
|
+
if (!Number.isInteger(limitChars) || limitChars < 1 || limitChars > 8000) recallError('INVALID_RECALL_ARGUMENT', 'limitChars must be an integer in 1..8000')
|
|
66
|
+
if (args.revision !== undefined && (typeof args.revision !== 'string' || !args.revision)) recallError('INVALID_RECALL_ARGUMENT', 'revision must be a nonempty string')
|
|
67
|
+
if (offset > 0 && !args.revision) recallError('REVISION_REQUIRED', 'offset > 0 requires revision from the first page')
|
|
68
|
+
return { exact, query: args.query, view: view === 'auto' ? (exact ? 'full' : 'snippet') : view,
|
|
69
|
+
topK: args.topK, libraryId: args.libraryId ?? null, offset, limitChars, revision: args.revision ?? null }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function recallReadParameters() {
|
|
73
|
+
return {
|
|
74
|
+
view: { type: 'string', enum: ['auto', 'snippet', 'full'], default: 'auto', description: 'auto: exact id reads full, natural query returns a snippet. full requires an exact id; snippet stays short.' },
|
|
75
|
+
offset: { type: 'integer', description: 'Exact id only: 0-based offset in redacted Unicode code points, integer >= 0. Continuing requires revision.' },
|
|
76
|
+
limitChars: { type: 'integer', description: 'Exact id only: page size in redacted Unicode code points, 1..8000; default 2000.' },
|
|
77
|
+
revision: { type: 'string', description: 'Exact id only: redacted body SHA256 from the first page; required when offset > 0. Changed bodies return MEMORY_CHANGED.' },
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function refText(scope, libraryId, id) {
|
|
82
|
+
return `scope=${scope} libraryId=${JSON.stringify(libraryId ?? null)} id=${JSON.stringify(id)}`
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Only the read API's redacted page and whitelisted metadata are rendered. No
|
|
86
|
+
// entry/raw body fallback, second body read or conflict expansion is permitted.
|
|
87
|
+
function renderMemoryPage(page, request) {
|
|
88
|
+
const ref = page.ref
|
|
89
|
+
const provenance = page.provenance || {}
|
|
90
|
+
const restrictions = page.restrictions || {}
|
|
91
|
+
let body = page.body
|
|
92
|
+
let pagination = page.pagination
|
|
93
|
+
if (request.view === 'snippet') {
|
|
94
|
+
const snippet = centeredSnippetWindow(body, request.query)
|
|
95
|
+
const offset = pagination.offset + snippet.start
|
|
96
|
+
const end = pagination.offset + snippet.end
|
|
97
|
+
pagination = { offset, returnedChars: snippet.returnedChars, totalChars: pagination.totalChars,
|
|
98
|
+
truncated: offset > 0 || end < pagination.totalChars, nextOffset: end < pagination.totalChars ? end : null }
|
|
99
|
+
body = snippet.body
|
|
100
|
+
}
|
|
101
|
+
const lines = [
|
|
102
|
+
`${ref.scope === 'private' ? '私有' : '全局'}记忆 [${ref.id}] ${redactSecrets(page.title || '(untitled)')}`,
|
|
103
|
+
`library=${ref.libraryId ?? 'global'} · source=${provenance.source || 'inferred'} · source_kind=${provenance.sourceKind || provenance.source || 'inferred'} · speaker_id=${provenance.speakerId ?? '?'} · view=${request.view}`,
|
|
104
|
+
`ref: ${refText(ref.scope, ref.libraryId, ref.id)}`,
|
|
105
|
+
`visibility=${restrictions.visibility || 'shared'} · disclosure=${restrictions.disclosure || 'can_tell'} · status=${restrictions.status || 'active'} · layer=${restrictions.layer || 'long_term'}`,
|
|
106
|
+
`domain=${page.domain || 'unknown'} · unbound=${page.unbound === true}`,
|
|
107
|
+
`pagination: unit=codepoint · offset=${pagination.offset} · returned_chars=${pagination.returnedChars} · total_chars=${pagination.totalChars} · truncated=${pagination.truncated} · next_offset=${pagination.nextOffset ?? 'null'}`,
|
|
108
|
+
`revision=${page.revision}`,
|
|
109
|
+
]
|
|
110
|
+
const header = redactSecrets(lines.join('\n'))
|
|
111
|
+
const footer = []
|
|
112
|
+
if (pagination.nextOffset !== null) {
|
|
113
|
+
footer.push(`next: memu_${ref.scope}_recall query=${JSON.stringify(ref.id)} view="full"${ref.scope === 'private' ? ` libraryId=${JSON.stringify(ref.libraryId)}` : ''} offset=${pagination.nextOffset} limitChars=${request.limitChars} revision=${JSON.stringify(page.revision)}`)
|
|
114
|
+
}
|
|
115
|
+
for (const related of page.related || []) {
|
|
116
|
+
if (related.kind === 'conflict') footer.push(`conflict: [${related.id}] ${refText(ref.scope, related.libraryId, related.id)}· available=${related.available !== false}(尚未读取另一版,不能据此裁决)`)
|
|
117
|
+
}
|
|
118
|
+
return `${header}\nbody:\n${body}${footer.length ? '\n' + redactSecrets(footer.join('\n')) : ''}`
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function searchSnippet(item, query) {
|
|
122
|
+
// Redact before cutting: a key split at the snippet boundary must not leak.
|
|
123
|
+
return centeredSnippetWindow(redactSecrets(item.content || ''), query)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function searchRefLine(scope, item, snippet, homeLibraryId = null) {
|
|
127
|
+
return ` view=snippet · ref: ${refText(scope, scope === 'private' ? (item.libraryId || homeLibraryId) : null, item.name)} · unit=codepoint · offset=${snippet.start} · returned_chars=${snippet.returnedChars} · total_chars=${snippet.totalChars} · truncated=${snippet.truncated}`
|
|
37
128
|
}
|
|
38
129
|
|
|
39
130
|
// 词典核心(lib/lexicon.js)按需加载:工具注册面不能被一个
|
|
@@ -123,7 +214,7 @@ function formatPrivateItem(item, index, options = {}) {
|
|
|
123
214
|
const layer = entry.layer || 'long_term'
|
|
124
215
|
const status = entry.status || 'active'
|
|
125
216
|
const source = entry.source || 'inferred'
|
|
126
|
-
// B7
|
|
217
|
+
// B7:默认 layer/status 不逐条重写;显式读取始终标明来源,避免把推断当引文。
|
|
127
218
|
const flags = [
|
|
128
219
|
layer !== 'long_term' ? `layer=${layer}` : '',
|
|
129
220
|
status !== 'active' ? `status=${status}` : '',
|
|
@@ -132,7 +223,9 @@ function formatPrivateItem(item, index, options = {}) {
|
|
|
132
223
|
].filter(Boolean).join(' ')
|
|
133
224
|
const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
|
|
134
225
|
if (flags) lines.push(` ${flags}`)
|
|
135
|
-
|
|
226
|
+
lines.push(` source=${source}`)
|
|
227
|
+
if (entry.source_kind) lines.push(` source_kind=${entry.source_kind}`)
|
|
228
|
+
if (entry.speaker_id) lines.push(` speaker_id=${entry.speaker_id}`)
|
|
136
229
|
// Same relative phrasing as the injected block: one memory must not read as
|
|
137
230
|
// "2026-10-20" in a tool result and "8 天前" in the prompt.
|
|
138
231
|
const when = relativeTime(entry.updatedAt || entry.createdAt)
|
|
@@ -163,13 +256,13 @@ function formatPrivateItem(item, index, options = {}) {
|
|
|
163
256
|
const brief = emotionBrief(entry)
|
|
164
257
|
if (brief) lines.push(` emo=${brief}`)
|
|
165
258
|
else if (typeof entry.moodValence === 'number' && entry.moodValence !== 0) lines.push(` mood=${entry.moodValence.toFixed(2)}`)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
lines.push(
|
|
259
|
+
const snippet = searchSnippet(item, options.query)
|
|
260
|
+
lines.push(searchRefLine('private', item, snippet, options.homeLibraryId))
|
|
261
|
+
if (snippet.body) lines.push(' ' + snippet.body.replace(/\n/g, '\n '))
|
|
262
|
+
for (const related of item.related || []) {
|
|
263
|
+
if (related.kind === 'conflict') lines.push(` conflict: ${refText('private', related.libraryId || item.libraryId || options.homeLibraryId, related.id)} · conflictComplete=${related.complete === true} · available=${related.available !== false}(关系指针,不包含另一版正文)`)
|
|
264
|
+
else lines.push(` related: [${related.id}] ${related.title} (${related.kind})`)
|
|
171
265
|
}
|
|
172
|
-
for (const related of item.related || []) lines.push(` related: [${related.id}] ${related.title} (${related.kind})`)
|
|
173
266
|
for (const image of entry.attachments || []) lines.push(` image: ${image.sha256} ${image.caption || '[图片]'}${image.missing ? ' [missing]' : ''} (${image.captionBy || 'none'})`)
|
|
174
267
|
return redactSecrets(lines.join('\n'))
|
|
175
268
|
}
|
|
@@ -187,12 +280,13 @@ function formatGlobalItem(item, index, options = {}) {
|
|
|
187
280
|
const when = relativeTime(entry.updatedAt || entry.createdAt)
|
|
188
281
|
if (when) lines.push(` updated=${when}`)
|
|
189
282
|
if (Array.isArray(entry.appliesTo) && entry.appliesTo.length > 0) lines.push(` applies_to=${entry.appliesTo.join(',')}`)
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
283
|
+
lines.push(` source=${entry.source || 'inferred'} · source_kind=${entry.source_kind || entry.source || 'inferred'}`)
|
|
284
|
+
if (entry.speaker_id) lines.push(` speaker_id=${entry.speaker_id}`)
|
|
285
|
+
if (entry.visibility) lines.push(` visibility=${entry.visibility}`)
|
|
286
|
+
if (entry.disclosure) lines.push(` disclosure=${entry.disclosure}`)
|
|
287
|
+
const snippet = searchSnippet(item, options.query)
|
|
288
|
+
lines.push(searchRefLine('global', item, snippet))
|
|
289
|
+
if (snippet.body) lines.push(' ' + snippet.body.replace(/\n/g, '\n '))
|
|
196
290
|
return redactSecrets(lines.join('\n'))
|
|
197
291
|
}
|
|
198
292
|
|
|
@@ -276,11 +370,11 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
276
370
|
if (!only) registrationReport = { attempted: 0, registered: 0, failures: [] }
|
|
277
371
|
tools.push(toolBase(
|
|
278
372
|
'memu_private_link',
|
|
279
|
-
'Connect two existing memories or a memory and an existing entity in the bound library. kind is relation, commitment, event, person or
|
|
373
|
+
'Connect two existing memories or a memory and an existing entity in the bound library. kind is relation, commitment, event, person, conflict or supersede. Requires an evidence note of 8-500 characters; confidence defaults to 0.7. This is also the adjudication tool for memu_private_link_suggest candidates: link a pair only when the note cites concrete evidence of the same entity or event, and pass entity {name, kind} to create or reuse that named entity. Cannot delete links or cross conversation visibility boundaries. When to use it: a new memory supersedes an older statement of the same fact → link to the old entry (supersede); several memories about the same person/thing → link them to a named entity; a promise or commitment was made → commitment; two memories contradict each other → conflict. When link_suggest returns candidates, adjudicate every one explicitly — link with evidence or discard; never leave candidates unjudged.',
|
|
280
374
|
{
|
|
281
375
|
from: { type: 'string', description: 'Exact source memory id; required unless updating a relationship snapshot.' },
|
|
282
376
|
to: { type: 'string', description: 'Exact target memory or entity id; required unless entity or relationship is supplied.' },
|
|
283
|
-
kind: { type: 'string', description: 'relation, commitment, event, person or
|
|
377
|
+
kind: { type: 'string', description: 'relation, commitment, event, person, conflict or supersede; required when linking. supersede marks a newer version replacing an older statement of the same fact.' },
|
|
284
378
|
note: { type: 'string', required: true, description: '8-500 character reason grounded in the conversation, not a guess. For a memu_private_link_suggest candidate, quote the transcript line that proves the same entity or event.' },
|
|
285
379
|
confidence: { type: 'number', description: '0-1 confidence, default 0.7.' },
|
|
286
380
|
entity: { type: 'object', properties: { name: { type: 'string' }, kind: { type: 'string' } }, additionalProperties: true, description: 'Optional named entity to create and link to instead of to; an entity with the same normalized name is reused (case/width-insensitive). Use only an explicit identity, never infer a person from an ambiguous pronoun.' },
|
|
@@ -321,7 +415,7 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
321
415
|
|
|
322
416
|
tools.push(toolBase(
|
|
323
417
|
'memu_private_link_suggest',
|
|
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.',
|
|
418
|
+
'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. Every returned pair must be adjudicated explicitly in this turn: link with memu_private_link (note quoting the transcript evidence) or discard — silence is not adjudication.',
|
|
325
419
|
{
|
|
326
420
|
ids: {
|
|
327
421
|
type: 'array',
|
|
@@ -538,13 +632,21 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
538
632
|
|
|
539
633
|
tools.push(toolBase(
|
|
540
634
|
'memu_private_recall',
|
|
541
|
-
'Retrieve relevant private memories from the library bound to this conversation.
|
|
635
|
+
'Retrieve relevant private memories from the library bound to this conversation. Natural queries return short snippets; exact mem- ids (or unique prefixes, optionally .md, no whitespace) read one redacted body page with auto/full. Secret memories remain explicitly readable with disclosure restrictions. Use libraryId only to disambiguate an allowed exact reference, never to widen scope.',
|
|
542
636
|
{
|
|
543
|
-
query: { type: 'string', required: true, description: 'Natural-language
|
|
544
|
-
topK: { type: 'integer', description: '
|
|
637
|
+
query: { type: 'string', required: true, description: 'Natural-language search or exact mem- id / unique prefix (optional .md, no whitespace).' },
|
|
638
|
+
topK: { type: 'integer', description: 'Search row limit, integer 1..20; default from settings. Exact reads return one entry.' },
|
|
639
|
+
...recallReadParameters(),
|
|
640
|
+
libraryId: { type: 'string', description: 'Private exact id only: owning library from a returned ref; must be in the allowed library set.' },
|
|
545
641
|
},
|
|
546
642
|
async (args, exec) => {
|
|
547
|
-
const
|
|
643
|
+
const request = parseRecallRequest(args, 'private')
|
|
644
|
+
if (request.exact) {
|
|
645
|
+
const page = readMemoryByRef({ exec, scope: 'private', id: request.query, libraryId: request.libraryId,
|
|
646
|
+
offset: request.offset, limitChars: request.limitChars, revision: request.revision })
|
|
647
|
+
return renderMemoryPage(page, request)
|
|
648
|
+
}
|
|
649
|
+
const result = await privateRecall({ exec, query: request.query, topK: request.topK, purpose: 'explicit' })
|
|
548
650
|
// Surface a degraded semantic leg on the explicit tool path too; silently
|
|
549
651
|
// returning fewer hits would make a failed backend look like an empty library.
|
|
550
652
|
const warning = (result.errors || []).length ? `\n注意:本次召回已降级:${(result.errors || []).join('; ')}` : ''
|
|
@@ -802,18 +904,26 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
802
904
|
|
|
803
905
|
tools.push(toolBase(
|
|
804
906
|
'memu_global_recall',
|
|
805
|
-
'Retrieve cross-session global memories applicable to the current domain. Global memory
|
|
907
|
+
'Retrieve cross-session global memories applicable to the current domain. Natural queries return snippets; exact gmem- ids (or unique prefixes, optionally .md, no whitespace) read one redacted body page with auto/full. Global memory stays read-only with existing automatic/domain eligibility.',
|
|
806
908
|
{
|
|
807
|
-
query: { type: 'string', required: true },
|
|
808
|
-
topK: { type: 'integer' },
|
|
909
|
+
query: { type: 'string', required: true, description: 'Natural-language search or exact gmem- id / unique prefix (optional .md, no whitespace).' },
|
|
910
|
+
topK: { type: 'integer', description: 'Search row limit, integer 1..20; default from settings. Exact reads return one entry.' },
|
|
911
|
+
...recallReadParameters(),
|
|
809
912
|
},
|
|
810
913
|
async (args, exec) => {
|
|
811
|
-
const
|
|
812
|
-
if (
|
|
914
|
+
const request = parseRecallRequest(args, 'global')
|
|
915
|
+
if (request.exact) {
|
|
916
|
+
const page = readMemoryByRef({ exec, scope: 'global', id: request.query,
|
|
917
|
+
offset: request.offset, limitChars: request.limitChars, revision: request.revision })
|
|
918
|
+
return renderMemoryPage(page, request)
|
|
919
|
+
}
|
|
920
|
+
const result = await globalRecall({ exec, query: request.query, topK: request.topK, purpose: 'explicit' })
|
|
921
|
+
const warning = (result.errors || []).length ? `\n注意:本次召回已降级:${(result.errors || []).join('; ')}` : ''
|
|
922
|
+
if (!result.files?.length) return `全局记忆(domain=${result.domain})没有命中。${warning}`
|
|
813
923
|
return [
|
|
814
924
|
`全局记忆(domain=${result.domain})`,
|
|
815
|
-
...result.files.map((f, i) => formatGlobalItem(f, i + 1, { query:
|
|
816
|
-
].join('\n\n')
|
|
925
|
+
...result.files.map((f, i) => formatGlobalItem(f, i + 1, { query: request.query })),
|
|
926
|
+
].join('\n\n') + warning
|
|
817
927
|
},
|
|
818
928
|
{ isConcurrencySafe: () => true },
|
|
819
929
|
))
|
|
@@ -867,6 +977,14 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
867
977
|
// Separates "nothing was written" from "the panes were never told": a write
|
|
868
978
|
// with no heartbeat means no surface is polling; a heartbeat after a write
|
|
869
979
|
// means the write was visible within one beat.
|
|
980
|
+
// 2026-11-15 扫雷:向量代际缺库显式化——no-database 降级后给出可行动线索
|
|
981
|
+
let vectorMissingLine = ''
|
|
982
|
+
try {
|
|
983
|
+
const vectorMissing = getMissingVectorLibraries()
|
|
984
|
+
if (vectorMissing.length) {
|
|
985
|
+
vectorMissingLine = `vector_missing: ${vectorMissing.join(', ')} — semantic recall is local-only for these libraries; a forced vector rebuild (Settings → MemU → 本地向量 · force 切换) will backfill them`
|
|
986
|
+
}
|
|
987
|
+
} catch { }
|
|
870
988
|
const sync = syncActivity()
|
|
871
989
|
const ago = (at) => {
|
|
872
990
|
if (!at) return 'never'
|
|
@@ -891,6 +1009,7 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
891
1009
|
`libraries: ${libraries.length}`,
|
|
892
1010
|
...storageLines,
|
|
893
1011
|
...recallLines,
|
|
1012
|
+
...(vectorMissingLine ? [vectorMissingLine] : []),
|
|
894
1013
|
syncLine,
|
|
895
1014
|
binding?.inbound || binding?.lastInboundOutcome ? `inbound: pending=${binding.inbound?.pending?.length || 0}, logical=${binding.inbound?.clock || 0}, last=${binding.lastInboundOutcome?.reason || 'none'}` : '',
|
|
896
1015
|
binding?.lastInboundError ? `inbound_error: ${redactSecrets(binding.lastInboundError)}` : '',
|
package/lib/webui/standalone.css
CHANGED
|
@@ -1007,7 +1007,10 @@ html[data-standalone] .dshm-drawer {
|
|
|
1007
1007
|
width: min(560px, 100%);
|
|
1008
1008
|
padding: 26px;
|
|
1009
1009
|
gap: 12px;
|
|
1010
|
-
|
|
1010
|
+
/* 详情/编辑抽屉必须不透明(与嵌入壳 client.js 的 .dshm-drawer 同口径):
|
|
1011
|
+
--dshm-panel-strong 是 .87/.84 的半透明霜面,拿它做抽屉底板会透出背后页面。
|
|
1012
|
+
独立壳的 --dsw-alias-bg-layer-1 是实色(#fff / #171a23),用它做不透明底板。 */
|
|
1013
|
+
background: var(--dsw-alias-bg-layer-1, #fff);
|
|
1011
1014
|
border-left-color: var(--dshm-line);
|
|
1012
1015
|
box-shadow: -30px 0 80px -40px rgba(0, 0, 0, .55);
|
|
1013
1016
|
}
|
|
@@ -1038,6 +1041,30 @@ html[data-standalone] .dshm-drawer-label {
|
|
|
1038
1041
|
color: var(--dshm-muted);
|
|
1039
1042
|
white-space: nowrap;
|
|
1040
1043
|
}
|
|
1044
|
+
/* 2026-11-16 扫雷修复:纵向表单字段不再拉伸(抽屉下半空白)、标签左对齐、
|
|
1045
|
+
开关行底对齐输入行、抽屉高度自适应内容。覆盖上面 inline-flex/center 的旧口径。 */
|
|
1046
|
+
/* 2026-11-16 复盘:抽屉保持全高(嵌入壳里缩成小浮卡下面空一大块,更难看);
|
|
1047
|
+
「太空」的真凶是字段纵向拉伸,已在下方字段规则里修掉。 */
|
|
1048
|
+
html[data-standalone] .dshm-drawer-form .dshm-drawer-field {
|
|
1049
|
+
display: flex;
|
|
1050
|
+
flex-direction: column;
|
|
1051
|
+
align-items: stretch;
|
|
1052
|
+
gap: 5px;
|
|
1053
|
+
flex: 0 0 auto;
|
|
1054
|
+
}
|
|
1055
|
+
html[data-standalone] .dshm-drawer-form > input,
|
|
1056
|
+
html[data-standalone] .dshm-drawer-form > textarea {
|
|
1057
|
+
flex: 0 0 auto;
|
|
1058
|
+
}
|
|
1059
|
+
html[data-standalone] .dshm-drawer-form .dshm-drawer-inline {
|
|
1060
|
+
align-items: flex-end;
|
|
1061
|
+
}
|
|
1062
|
+
html[data-standalone] .dshm-drawer-form .dshm-drawer-inline .dshm-drawer-field {
|
|
1063
|
+
flex: 1 1 160px;
|
|
1064
|
+
}
|
|
1065
|
+
html[data-standalone] .dshm-drawer-form .dshm-drawer-inline .dshm-drawer-field.is-narrow {
|
|
1066
|
+
flex: 0 1 150px;
|
|
1067
|
+
}
|
|
1041
1068
|
html[data-standalone] .dshm-drawer-actions {
|
|
1042
1069
|
border-top-color: var(--dshm-line);
|
|
1043
1070
|
}
|