dsh-memu-memory 1.2.7 → 1.2.9
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 +1 -1
- package/CHANGELOG.md +472 -0
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/memory-semantics.md +23 -3
- package/lib/backup.js +155 -26
- package/lib/binding-diagnostics.js +1 -2
- package/lib/budget.js +31 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +138 -0
- package/lib/consolidation-ledger.js +5 -2
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +24 -0
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +167 -17
- package/lib/lexicon.js +62 -17
- package/lib/local-vector-service.js +25 -2
- package/lib/media.js +49 -12
- package/lib/memory.js +1202 -123
- package/lib/memu.js +4 -0
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +50 -10
- package/lib/prompts/private-consolidation.mixed.md +2 -2
- package/lib/prompts/private-consolidation.rp.md +6 -1
- package/lib/prompts/private-policy.rp.md +4 -0
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/prompts.js +0 -7
- package/lib/recall-cache.js +10 -2
- package/lib/rpc.js +104 -19
- package/lib/snippet.js +41 -0
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +348 -0
- package/lib/text-retrieval.js +191 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/tools.js +81 -4
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/bench-recall.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/check-seed-compat.mjs +1 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +85 -85
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +3 -3
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +146 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +112 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +17 -1
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +4 -2
- package/tests/recall-intent.test.mjs +123 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
package/lib/memu.js
CHANGED
|
@@ -178,6 +178,10 @@ for _line in sys.stdin:
|
|
|
178
178
|
const RESIDENT_READY_TIMEOUT_MS = 30_000
|
|
179
179
|
const RESIDENT_LINE_LIMIT = 8 << 20
|
|
180
180
|
|
|
181
|
+
// 常驻引擎的进程级单例。之前漏了这个声明:所有更新点都在写它,第一次真正 spawn
|
|
182
|
+
// 时直接 ReferenceError(MEMU_SPAWN_FAILED: residentRecord is not defined)。
|
|
183
|
+
let residentRecord = null
|
|
184
|
+
|
|
181
185
|
function residentKey(current) {
|
|
182
186
|
return `${current.python}\u0000${String(current.version || '')}`
|
|
183
187
|
}
|
package/lib/paths.js
CHANGED
|
@@ -267,13 +267,6 @@ export function windowsSystemEnv(platform = process.platform, env = process.env)
|
|
|
267
267
|
return overlay
|
|
268
268
|
}
|
|
269
269
|
|
|
270
|
-
export function safeSegment(value, fallback = 'unknown') {
|
|
271
|
-
const text = String(value ?? '').trim()
|
|
272
|
-
if (!text) return fallback
|
|
273
|
-
const cleaned = text.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')
|
|
274
|
-
return cleaned || fallback
|
|
275
|
-
}
|
|
276
|
-
|
|
277
270
|
export function isSafeId(value) {
|
|
278
271
|
return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value) && value !== '.' && value !== '..'
|
|
279
272
|
}
|
package/lib/preset-scope.js
CHANGED
|
@@ -114,8 +114,13 @@ export function registerPresetAttachment(ctx, { log = () => {}, intervalMs = ATT
|
|
|
114
114
|
timer.unref?.()
|
|
115
115
|
return () => {
|
|
116
116
|
clearInterval(timer)
|
|
117
|
-
for (const [, dispose] of attached.entries()) {
|
|
117
|
+
for (const [agentCtx, dispose] of attached.entries()) {
|
|
118
118
|
try { dispose?.() } catch {}
|
|
119
|
+
// S-5: this Map is a strong reference. Detaching without deleting left every
|
|
120
|
+
// disposed agent context reachable for the life of the process, and a context
|
|
121
|
+
// that ever came back through the same key would still read as "attached" and
|
|
122
|
+
// never be registered again.
|
|
123
|
+
attached.delete(agentCtx)
|
|
119
124
|
}
|
|
120
125
|
}
|
|
121
126
|
}
|
package/lib/private.js
CHANGED
|
@@ -533,9 +533,14 @@ function workerToolsMeta(workerTools) {
|
|
|
533
533
|
}
|
|
534
534
|
|
|
535
535
|
const inFlight = new Map()
|
|
536
|
+
// How long a cancelled fork gets to finish the tool call it was in the middle of.
|
|
537
|
+
// Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
|
|
538
|
+
// the alternative — disposing immediately — is what let a write land after the range
|
|
539
|
+
// was already handed back to pending.
|
|
540
|
+
const WORKER_STOP_GRACE_MS = 5_000
|
|
536
541
|
|
|
537
542
|
// 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
|
|
538
|
-
// 的 file:line 当成诊断契约(当前 lib/private.js:
|
|
543
|
+
// 的 file:line 当成诊断契约(当前 lib/private.js:535),修改位置时同步更新该诊断映射,
|
|
539
544
|
// 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
|
|
540
545
|
import { warn } from './paths.js'
|
|
541
546
|
import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
|
|
@@ -584,12 +589,14 @@ function snapshotMetaOf(snapshot) {
|
|
|
584
589
|
// 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
|
|
585
590
|
// 开始写。实测(2026-11-02,935 条事件的会话):第一次 180 s 到点时刚写完 3 条、
|
|
586
591
|
// 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算,
|
|
587
|
-
// 并夹在 [
|
|
588
|
-
//
|
|
592
|
+
// 并夹在 [420 s, 600 s]:慢推理模型(GLM-5.3-Flash 实测)单次 worker 回合就能吃满
|
|
593
|
+
// 180 s 旧下限且一个工具都没调(1.2.7 后内部评测复现),下限抬到 7 分钟给长思考留
|
|
594
|
+
// 余量;600 s 封顶不变,卡死的 fork 仍会在 10 分钟内被收掉。显式传 maxWaitMs 的
|
|
595
|
+
// 调用(含工具/测试)原样生效。
|
|
589
596
|
export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
|
|
590
597
|
baseMs: 120_000,
|
|
591
598
|
perEventMs: 350,
|
|
592
|
-
minMs:
|
|
599
|
+
minMs: 420_000,
|
|
593
600
|
maxMs: 600_000,
|
|
594
601
|
})
|
|
595
602
|
|
|
@@ -613,6 +620,34 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
613
620
|
inFlight.set(sessionId, abort)
|
|
614
621
|
let handle = null
|
|
615
622
|
let offSession = null
|
|
623
|
+
let idle = null
|
|
624
|
+
// Stopped once, callable twice: the timeout path and `finally` both need it.
|
|
625
|
+
let stopped = false
|
|
626
|
+
// The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
|
|
627
|
+
// wait for a tool call in flight, and this fork writes memories *through tools*, so
|
|
628
|
+
// "the fork was stopped" was not true when the timeout path returned: failJob had
|
|
629
|
+
// already handed the range back and the next pass could fork the same window while
|
|
630
|
+
// the old child was still writing. Bounded, because a child that ignores the cancel
|
|
631
|
+
// must not hang the sweep.
|
|
632
|
+
const stopWorker = async () => {
|
|
633
|
+
if (stopped) return
|
|
634
|
+
stopped = true
|
|
635
|
+
try { abort.abort() } catch {}
|
|
636
|
+
try { offSession?.() } catch {}
|
|
637
|
+
if (idle) {
|
|
638
|
+
try {
|
|
639
|
+
await Promise.race([
|
|
640
|
+
idle.then(() => {}, () => {}),
|
|
641
|
+
// Deliberately NOT unref'd: this promise is what we are awaiting, so an
|
|
642
|
+
// unref'd timer lets the event loop drain while the await is still pending
|
|
643
|
+
// and the caller (or the test runner) is left holding a promise that can
|
|
644
|
+
// never settle. A <=5s hold on the loop is the correct trade.
|
|
645
|
+
new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
|
|
646
|
+
])
|
|
647
|
+
} catch {}
|
|
648
|
+
}
|
|
649
|
+
try { await handle?.dispose?.() } catch {}
|
|
650
|
+
}
|
|
616
651
|
let turnEnd = null
|
|
617
652
|
let jobId = null
|
|
618
653
|
let scopeChanged = null
|
|
@@ -1022,7 +1057,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1022
1057
|
handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
|
|
1023
1058
|
// followup only queues. whenIdle says the driver stopped; turn/end says
|
|
1024
1059
|
// whether that turn actually succeeded, so both are checked below.
|
|
1025
|
-
|
|
1060
|
+
idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
|
|
1026
1061
|
let timer = null
|
|
1027
1062
|
let outcome
|
|
1028
1063
|
try {
|
|
@@ -1111,7 +1146,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1111
1146
|
// `result.error` and an empty string there is indistinguishable from a click
|
|
1112
1147
|
// that did nothing at all (observed: two clicks, no feedback, no memories).
|
|
1113
1148
|
if (outcome === 'timeout') {
|
|
1114
|
-
|
|
1149
|
+
// Stop the writer before releasing the range, not after. Waiting matters here
|
|
1150
|
+
// because a tool call already in flight can still land a memory on disk, and the
|
|
1151
|
+
// range going back to pending is what lets the next pass redo this window.
|
|
1152
|
+
await stopWorker()
|
|
1153
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'timeout', error: 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written' }))
|
|
1115
1154
|
return finish({
|
|
1116
1155
|
ok: false,
|
|
1117
1156
|
sessionId,
|
|
@@ -1119,7 +1158,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1119
1158
|
settled: false,
|
|
1120
1159
|
timedOut: true,
|
|
1121
1160
|
reasonCode: 'timeout',
|
|
1122
|
-
|
|
1161
|
+
// The next pass must not assume this window left nothing behind: the range is
|
|
1162
|
+
// pending again and some writes may already have landed.
|
|
1163
|
+
partialWritesPossible: true,
|
|
1164
|
+
error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
|
|
1123
1165
|
})
|
|
1124
1166
|
}
|
|
1125
1167
|
return finish({
|
|
@@ -1151,10 +1193,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1151
1193
|
return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
|
|
1152
1194
|
} finally {
|
|
1153
1195
|
inFlight.delete(sessionId)
|
|
1154
|
-
|
|
1155
|
-
try { offSession?.() } catch {}
|
|
1196
|
+
try { await stopWorker() } catch {}
|
|
1156
1197
|
try { workerTools?.dispose?.() } catch {}
|
|
1157
|
-
try { await handle?.dispose?.() } catch {}
|
|
1158
1198
|
try { if (childId) deleteSessionBinding(childId) } catch {}
|
|
1159
1199
|
}
|
|
1160
1200
|
}
|
|
@@ -13,9 +13,9 @@
|
|
|
13
13
|
- 对方现实生活的具体事实(作息、行程、口味、健康、家人朋友、在忙的事)单独成条:`owner=about_user`,平实短条,不装进瞬间或技术模板,也不与剧情、技术条目合并;单次提及压低 confidence 或用 `short_term`,重复出现才升级,一次客套不推导长期偏好。
|
|
14
14
|
- 两边都出现时分成两条,不要混成一条。
|
|
15
15
|
- 技术侧用中性工程笔记,人物侧用角色自己的话,不打关系分、不写抒情流水账;OOC 写作偏好和剧情经历分开。
|
|
16
|
-
-
|
|
16
|
+
- 仅按实际提供或成功检索到的旧条目去重;兼容内容可合并,矛盾留证据与时间供复核,不抹旧事实或自行宣布取代。同一件事前后有两种说法时,两种说法必须各自成条(写清轮次或时间和说话人),不得合并;用户先前说过的话不能记成助手说的,也不能因后面改口删掉先前那条。
|
|
17
17
|
- tags 可标 coding/rp/ooc 辅助检索,不代替说话人、角色、世界线、分支与 knownBy 边界。工具 waiting/sleep 不算人物经历,角色喜好不推导现实用户属性。
|
|
18
|
-
- 最多新增
|
|
18
|
+
- 最多新增 10 条。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)即使琐碎也要独立写入;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。
|
|
19
19
|
|
|
20
20
|
字段:
|
|
21
21
|
- title:8–40 字,写具体事实(项目/模块/人物/事件/结论的关键词)。锚点/召回只显示标题、不显示正文,所以标题就是目录项;
|
|
@@ -11,7 +11,12 @@
|
|
|
11
11
|
- 这轮真实发生了什么?谁答应了什么?谁知道了什么?哪些只是气氛?
|
|
12
12
|
- 事实、约定、知情这三层要准;感受层允许模糊。
|
|
13
13
|
- 只和实际提供或成功检索到的旧条目比对;同一事件的兼容细节可合并,矛盾说法保留各自来源、时间和视角供复核,不覆写旧事实,不自行宣布取代。
|
|
14
|
-
-
|
|
14
|
+
- 同一件事前后有两种说法时,两种说法必须各自成条(写清轮次或时间和说话人),不得合并成一条;用户先前说过的话不能记成助手说的,也不能因为后面改口就删掉先前那条。
|
|
15
|
+
- 写库前先落 `speaker_id`、`source_kind`、`absolute_date`;相对日期不能只留原文。
|
|
16
|
+
- 同一件事有两种说法:各写一条,`conflicts_with` 互指;不要合并成一条,也不要自行裁决。
|
|
17
|
+
- 承诺/约定写 `commitment`(对谁/做什么/`due_at`/`status`);梦、假设、转述标 `source_kind`。
|
|
18
|
+
- 助手说过的承诺和计划同样要写;不要只收用户消息。
|
|
19
|
+
- 每轮最多新增 10 条。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)即使琐碎也要独立写入;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。
|
|
15
20
|
|
|
16
21
|
写什么(活人感):
|
|
17
22
|
- 用角色的口吻、第一人称写,像在回想,不像在归档。
|
|
@@ -25,6 +25,10 @@
|
|
|
25
25
|
三条纪律:
|
|
26
26
|
- 写之前先 `memu_private_recall` 查一眼。对方提到以前的事、问你记不记得、要许下什么承诺之前都先查;凭印象编比记不清糟得多。
|
|
27
27
|
- 新印象和旧记忆冲突时,写新条进入待复核,保留旧版本的事实与时间;不要用 update 抹掉旧说法。角色的误解写清 `source: inferred/imagined`,低置信不是随意改史的许可;关系、承诺与事件可用带理由的 `memu_private_link` 连接。
|
|
28
|
+
- 相对日期写入时落 `absolute_date`;无法解析就标 `date_precision=unknown`,不要猜。
|
|
29
|
+
- 同一事实的两种说法各写一条,用 `conflicts_with` 互指;明确取代才用 `supersedes`,旧正文不删。
|
|
30
|
+
- 承诺/约定写成 `commitment`:对谁、做什么、`due_at`、`status`;到期未完成要能被后续注入看到。
|
|
31
|
+
- 助手说过的承诺、计划、事实也要写;`source_kind=assistant_said`,不能记成用户说的。
|
|
28
32
|
- 出戏的话(换写法、停一下、补充设定)不是剧情里发生的事。要记就记成「关于我们怎么写这个故事的约定」,别混进故事。
|
|
29
33
|
- 回忆在回应中多体现为自然的称呼、选择或分寸,不每轮翻旧账、重复口头禅或解释机制。工具 waiting/sleep 的时长与日志不是剧情事件,不据此制造冷落、好感变化或时间跳跃。
|
|
30
34
|
|
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
- 群聊先辨认当前说话人、被回应的人和话题归属;不同人的称呼、承诺、私聊秘密不能混在一起,不把所有消息都理解成在对你说话。长时间 waiting、工具 sleep 或日志本身不是人物被冷落、时间跳跃或关系变化的证据。
|
|
10
10
|
|
|
11
11
|
- 先查再开口:对方提到以前的事、问你记不记得、或者要许下什么之前,先用 `memu_private_recall` 找一找。想不起细节时可以说想不起来——但只有在真的查过之后,说不记得才是可信的。
|
|
12
|
+
- 相对日期先按这一轮的时间换算:昨天、明天、下周X、月底都要落到具体日期;算不出来就说不知道,不要把旧计划当现在。
|
|
13
|
+
- 记忆里有两版说法时,先把两版按时间摆出来再回答;不要替对方裁决哪版为准,也不要用后一版悄悄覆盖前一版。
|
|
14
|
+
- 分清是谁说的:对方说的、我说过的、听别人说的、我脑补的,不能混成一句。
|
|
12
15
|
- 允许想不起细节、感受偏心或理解改变;事实不能为了人味而记错。不确定就说明未知并降低 confidence,不能用低置信度给改写历史开许可。内心猜测与梦境标明 inferred/imagined,不当成对方真实的想法。
|
|
13
16
|
- 一致性优先于戏剧性:宁可平淡,也不要为了好看改掉已经发生过的事。
|
|
14
17
|
- 正常入戏时不主动报数据库、注入或工具日志;用户出戏询问机制、来源或是否记得时如实回答,不假装查过、一直记得或经历过没有发生的事。
|
package/lib/prompts.js
CHANGED
|
@@ -302,11 +302,4 @@ export function syncPromptDefaults() {
|
|
|
302
302
|
return getPromptStates()
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
-
export function promptDefaultsVersion() {
|
|
306
|
-
return allDefs().map((def) => {
|
|
307
|
-
const text = readText(defaultPath(def)) || ''
|
|
308
|
-
return `${def.key}:${hash(text)}`
|
|
309
|
-
}).join(',')
|
|
310
|
-
}
|
|
311
|
-
|
|
312
305
|
export { DEFAULT_DIR }
|
package/lib/recall-cache.js
CHANGED
|
@@ -35,6 +35,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
|
|
|
35
35
|
let misses = 0
|
|
36
36
|
let evictions = 0
|
|
37
37
|
let errors = 0
|
|
38
|
+
let staleSkipped = 0
|
|
38
39
|
let lastError = null
|
|
39
40
|
|
|
40
41
|
const fail = (op, error, key = null) => {
|
|
@@ -55,6 +56,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
|
|
|
55
56
|
if (expired(entry)) {
|
|
56
57
|
map.delete(ck)
|
|
57
58
|
evictions += 1
|
|
59
|
+
staleSkipped += 1
|
|
58
60
|
return null
|
|
59
61
|
}
|
|
60
62
|
// LRU 新鲜度:命中即挪到 Map 尾部(删除再插入)。
|
|
@@ -101,7 +103,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
|
|
|
101
103
|
try {
|
|
102
104
|
gen += 1
|
|
103
105
|
for (const [ck, entry] of map) {
|
|
104
|
-
if (entry.gen !== gen) { map.delete(ck); evictions += 1 }
|
|
106
|
+
if (entry.gen !== gen) { map.delete(ck); evictions += 1; staleSkipped += 1 }
|
|
105
107
|
}
|
|
106
108
|
} catch (error) { fail('bumpGeneration', error) }
|
|
107
109
|
},
|
|
@@ -117,6 +119,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
|
|
|
117
119
|
map.delete(ck)
|
|
118
120
|
removed += 1
|
|
119
121
|
evictions += 1
|
|
122
|
+
staleSkipped += 1
|
|
120
123
|
}
|
|
121
124
|
} catch {}
|
|
122
125
|
}
|
|
@@ -163,7 +166,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
|
|
|
163
166
|
return run
|
|
164
167
|
},
|
|
165
168
|
stats() {
|
|
166
|
-
return { size: map.size, hits, misses, evictions, generations: gen, errors, lastError, inflight: inflight.size }
|
|
169
|
+
return { size: map.size, hits, misses, evictions, staleSkipped, generations: gen, errors, lastError, inflight: inflight.size }
|
|
167
170
|
},
|
|
168
171
|
/** 接错误观察者(memory.js 接 warn,规则 10 的可观测信号)。 */
|
|
169
172
|
setErrorHandler(handler) {
|
|
@@ -202,3 +205,8 @@ export function recallCacheKey({ query, topK, libraryId, byId, route, generation
|
|
|
202
205
|
|
|
203
206
|
/** 模块级默认单例:memory.js 直接使用。 */
|
|
204
207
|
export const recallCache = createRecallCache()
|
|
208
|
+
|
|
209
|
+
/** S10:只读统计快照(RPC/运维用);调用方不持有缓存内部状态。 */
|
|
210
|
+
export function recallCacheStats() {
|
|
211
|
+
return recallCache.stats()
|
|
212
|
+
}
|
package/lib/rpc.js
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
|
|
9
9
|
} from './state.js'
|
|
10
10
|
import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
|
|
11
|
-
import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
|
|
11
|
+
import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, previewDelete, restoreDeleted, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, recordImportBatch, revertImportBatch, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
|
|
12
12
|
import { normalizeMemoryContext } from './context.js'
|
|
13
13
|
import { requestPrivateConsolidation } from './private.js'
|
|
14
14
|
import { listHostModelOptions, discoverForkModels, redactConsolidationSettings, disposeConsolidationRoute } from './fork-model.js'
|
|
@@ -16,13 +16,14 @@ import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJob
|
|
|
16
16
|
import { maybeMigrateLibraries } from './migrate.js'
|
|
17
17
|
import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
|
|
18
18
|
import { statsView } from './stats.js'
|
|
19
|
+
import { recallCacheStats } from './recall-cache.js'
|
|
19
20
|
import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
|
|
20
21
|
import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
|
|
21
22
|
import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
|
|
22
23
|
import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
|
|
23
24
|
import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
|
|
24
25
|
import { listEvents, logStats, clearEvents } from './activity-log.js'
|
|
25
|
-
import { warn } from './paths.js'
|
|
26
|
+
import { redactSecrets, warn } from './paths.js'
|
|
26
27
|
import { GLOBAL_LEXICON_ID } from './lexicon.js'
|
|
27
28
|
import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
|
|
28
29
|
|
|
@@ -99,6 +100,21 @@ function routeLibraryId(endpoint, payload) {
|
|
|
99
100
|
|
|
100
101
|
let capabilityAbsentWarned = false
|
|
101
102
|
|
|
103
|
+
// Everything that leaves this file as an error string goes through here.
|
|
104
|
+
//
|
|
105
|
+
// The RPC boundary is the one place a message reaches a renderer, a log file and a
|
|
106
|
+
// bug report at once, and the errors that flow through it are not all ours: a
|
|
107
|
+
// provider SDK quotes the request URL and sometimes the Authorization header, a
|
|
108
|
+
// Python traceback can echo a connection string, and a config error can print the
|
|
109
|
+
// key it choked on. `memu.js` already redacts per command line; this is the same rule
|
|
110
|
+
// applied once at the exit, so no single forgotten path can leak. The length cap
|
|
111
|
+
// keeps a wall of traceback out of the UI as well.
|
|
112
|
+
const RPC_ERROR_MAX_CHARS = 600
|
|
113
|
+
function rpcErrorMessage(error) {
|
|
114
|
+
const raw = String(error?.message || error || 'unknown error')
|
|
115
|
+
try { return redactSecrets(raw).slice(0, RPC_ERROR_MAX_CHARS) } catch { return raw.slice(0, RPC_ERROR_MAX_CHARS) }
|
|
116
|
+
}
|
|
117
|
+
|
|
102
118
|
// One capability gate for both routes: absent callback falls back to the HTTP
|
|
103
119
|
// boundary (requestRejection) and warns once; a present callback is strict true.
|
|
104
120
|
// Keeping one helper makes the session-first / capability-second order identical
|
|
@@ -295,7 +311,10 @@ async function mergeLexiconImport(libraryId, member) {
|
|
|
295
311
|
if (!byKey.has(key)) byKey.set(key, { termId, entry: e })
|
|
296
312
|
}
|
|
297
313
|
}
|
|
298
|
-
|
|
314
|
+
// `addedTermIds` is what makes the import reversible: a term created by this package
|
|
315
|
+
// has no memory id to find it by later, and an updated one must not be deleted on
|
|
316
|
+
// revert (it existed before). Only creations are recorded.
|
|
317
|
+
const report = { version: 1, applied: 0, added: 0, updated: 0, revisions: 0, addedTermIds: [], skipped: [], failed: [] }
|
|
299
318
|
for (const raw of member.terms) {
|
|
300
319
|
const label = typeof raw?.term === 'string' ? raw.term : ''
|
|
301
320
|
try {
|
|
@@ -358,11 +377,15 @@ async function mergeLexiconImport(libraryId, member) {
|
|
|
358
377
|
})
|
|
359
378
|
report.applied += 1
|
|
360
379
|
if (out?.created === false) report.updated += 1
|
|
361
|
-
else
|
|
380
|
+
else {
|
|
381
|
+
report.added += 1
|
|
382
|
+
const termId = out?.term?.id || out?.term?.termId || null
|
|
383
|
+
if (termId) report.addedTermIds.push(String(termId))
|
|
384
|
+
}
|
|
362
385
|
// revisions 在当前生命周期恒为 0(§2.1 不再生成 pending revision);字段保留只为报告
|
|
363
386
|
// 形状稳定,旧客户端继续拿到一个数字。
|
|
364
387
|
} catch (error) {
|
|
365
|
-
report.failed.push({ term: label, reason:
|
|
388
|
+
report.failed.push({ term: label, reason: rpcErrorMessage(error).slice(0, 300) })
|
|
366
389
|
}
|
|
367
390
|
}
|
|
368
391
|
return report
|
|
@@ -698,6 +721,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
698
721
|
pinnedCount: privateEntries.filter((e) => e.layer === 'must_remember' && e.status !== 'archived').length,
|
|
699
722
|
globalCount: globalEntries.filter((e) => (e.status || 'active') === 'active').length,
|
|
700
723
|
jobs: listCurationJobs().slice(-10),
|
|
724
|
+
recallCache: recallCacheStats(),
|
|
701
725
|
}
|
|
702
726
|
}
|
|
703
727
|
case 'diagnoseSession': {
|
|
@@ -1160,7 +1184,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1160
1184
|
const id = String(payload?.libraryId || '')
|
|
1161
1185
|
if (!getLibrary(id)) throw new Error('library not found')
|
|
1162
1186
|
if (getLibrary(id).archived !== true) throw new Error('archive the library before deleting it')
|
|
1163
|
-
const safety = backupDatabases()
|
|
1187
|
+
const safety = await backupDatabases()
|
|
1164
1188
|
const result = deleteLibrary(id)
|
|
1165
1189
|
if (!result.ok) throw new Error(result.error)
|
|
1166
1190
|
return { ok: true, safety, archived: archivedLibraryView() }
|
|
@@ -1274,16 +1298,37 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1274
1298
|
case 'importMemories': {
|
|
1275
1299
|
const id = String(payload?.libraryId || '')
|
|
1276
1300
|
if (!getLibrary(id)) throw new Error('library not found')
|
|
1301
|
+
if (payload?.revertBatchId) {
|
|
1302
|
+
const reverted = await revertImportBatch({ libraryId: id, batchId: String(payload.revertBatchId) })
|
|
1303
|
+
// Lexicon terms live behind a lazily loaded module that memory.js must not
|
|
1304
|
+
// reach across for, so the undo happens here, where the api already exists.
|
|
1305
|
+
let lexiconReverted = 0
|
|
1306
|
+
if (reverted.lexiconTermIds?.length) {
|
|
1307
|
+
try {
|
|
1308
|
+
const lexicon = await lexiconApi()
|
|
1309
|
+
for (const termId of reverted.lexiconTermIds) {
|
|
1310
|
+
try { lexicon.deleteLexiconTerm({ libraryId: id, termId }); lexiconReverted += 1 } catch (error) {
|
|
1311
|
+
warn(`revert import: lexicon term ${termId} kept: ${error?.message || error}`)
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
warn(`revert import: lexicon module unavailable, terms kept: ${error?.message || error}`)
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
return { ...reverted, lexiconReverted }
|
|
1319
|
+
}
|
|
1277
1320
|
// The payload may be the parsed export (memories array) or the raw file text.
|
|
1278
1321
|
let memories = payload?.memories
|
|
1279
1322
|
let graphData = payload?.graph || null
|
|
1280
1323
|
let lexiconData = payload?.lexicon && typeof payload.lexicon === 'object' && !Array.isArray(payload.lexicon) ? payload.lexicon : null
|
|
1281
1324
|
let missingAttachments = 0
|
|
1325
|
+
let bundleId = payload?.bundleId ? String(payload.bundleId) : null
|
|
1282
1326
|
if (payload?.archiveBase64) {
|
|
1283
1327
|
const archive = importMediaBundle(id, Buffer.from(String(payload.archiveBase64), 'base64'))
|
|
1284
1328
|
memories = archive.memories
|
|
1285
1329
|
graphData = archive.graph
|
|
1286
1330
|
missingAttachments = archive.missing
|
|
1331
|
+
bundleId = bundleId || archive.bundleId || null
|
|
1287
1332
|
}
|
|
1288
1333
|
if (typeof memories === 'string') {
|
|
1289
1334
|
let parsed = null
|
|
@@ -1292,6 +1337,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1292
1337
|
if (Array.isArray(parsed.memories)) {
|
|
1293
1338
|
memories = parsed.memories
|
|
1294
1339
|
graphData = parsed.graph || null
|
|
1340
|
+
bundleId = bundleId || (parsed.bundleId ? String(parsed.bundleId) : null)
|
|
1295
1341
|
lexiconData = lexiconData || (parsed.lexicon && typeof parsed.lexicon === 'object' && !Array.isArray(parsed.lexicon) ? parsed.lexicon : null)
|
|
1296
1342
|
}
|
|
1297
1343
|
else throw new Error('this JSON has no "memories" array')
|
|
@@ -1299,13 +1345,25 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1299
1345
|
else throw new Error('this JSON has no "memories" array')
|
|
1300
1346
|
}
|
|
1301
1347
|
if (!Array.isArray(memories)) throw new Error('memories must be an array')
|
|
1302
|
-
|
|
1303
|
-
|
|
1348
|
+
// One batch id per install: every entry created by this import carries it, so
|
|
1349
|
+
// `revertBatchId` can undo exactly this package without touching old rows.
|
|
1350
|
+
const importBatchId = bundleId || (payload?.importBatchId ? String(payload.importBatchId) : `bnd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`)
|
|
1351
|
+
const result = await importMemories({ libraryId: id, memories, importBatchId })
|
|
1352
|
+
const graphRestore = graphData && result.idMap ? restoreGraphData(id, graphData, result.idMap, { origin: importBatchId }) : null
|
|
1304
1353
|
// 词典是版本化 member(§4.4):包里带了才合并恢复;term 冲突(规范化后同词)
|
|
1305
1354
|
// 更新既有词条,active+sensitive 一律跳过并上报,超长字段按核心 clip 落地、
|
|
1306
1355
|
// term 本身越界/归一化为空才进 failed。
|
|
1307
1356
|
const lexiconReport = lexiconData ? await mergeLexiconImport(id, lexiconData) : null
|
|
1308
|
-
|
|
1357
|
+
// Record the manifest before answering: an import whose ledger is missing still
|
|
1358
|
+
// reverts its memories (index tag), but loses the graph and lexicon halves.
|
|
1359
|
+
recordImportBatch({
|
|
1360
|
+
libraryId: id,
|
|
1361
|
+
batchId: importBatchId,
|
|
1362
|
+
memories: result.ids || [],
|
|
1363
|
+
entities: graphRestore?.createdEntityIds || [],
|
|
1364
|
+
lexicon: lexiconReport?.addedTermIds || [],
|
|
1365
|
+
})
|
|
1366
|
+
const value = { libraryId: id, ...result, missingAttachments, importBatchId }
|
|
1309
1367
|
return lexiconReport ? { ...value, lexicon: lexiconReport } : value
|
|
1310
1368
|
}
|
|
1311
1369
|
case 'exportLibrary': {
|
|
@@ -1321,10 +1379,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1321
1379
|
const data = lexicon.loadLexicon(id)
|
|
1322
1380
|
lexiconMember = { version: 1, terms: Object.entries(data.terms || {}).map(([termId, e]) => ({ id: termId, ...e })) }
|
|
1323
1381
|
} catch (error) {
|
|
1324
|
-
lexiconMember.unavailable =
|
|
1382
|
+
lexiconMember.unavailable = rpcErrorMessage(error).slice(0, 300)
|
|
1325
1383
|
}
|
|
1326
1384
|
const exported = {
|
|
1327
1385
|
format: 'dsh-memu-memory-library@1',
|
|
1386
|
+
bundleId: `bnd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1328
1387
|
exportedAt: new Date().toISOString(),
|
|
1329
1388
|
library: { id: lib.id, name: lib.name, scopeKey: lib.scopeKey || null, domain: lib.domain || null },
|
|
1330
1389
|
memories: Object.entries(index.entries || {}).map(([memId, e]) => ({ id: memId, ...e })),
|
|
@@ -1724,7 +1783,12 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1724
1783
|
const sessionId = requireSessionId(payload)
|
|
1725
1784
|
// Explicit button press: the user already decided this conversation is worth
|
|
1726
1785
|
// summarizing, so the automatic "is there anything in it" gate does not apply.
|
|
1727
|
-
|
|
1786
|
+
// 评测/联调可显式指定 trigger:trigger='backlog' + force=false 时走积压口径
|
|
1787
|
+
// (事件 ≥200 或人类回合 ≥10 才放行),用来验证水位触发本身。
|
|
1788
|
+
return requestPrivateConsolidation(ctx, sessionId, {
|
|
1789
|
+
force: payload?.force !== false,
|
|
1790
|
+
...(payload?.trigger ? { trigger: String(payload.trigger) } : {}),
|
|
1791
|
+
})
|
|
1728
1792
|
}
|
|
1729
1793
|
case 'generateGlobal': {
|
|
1730
1794
|
const sessionId = requireSessionId(payload)
|
|
@@ -1760,9 +1824,17 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1760
1824
|
const libraryId = String(payload?.libraryId || '')
|
|
1761
1825
|
if (!libraryId) throw new Error('libraryId is required')
|
|
1762
1826
|
if (!getLibrary(libraryId)) throw new Error('library not found')
|
|
1827
|
+
if (payload?.preview === true) return previewDelete({ libraryId, id })
|
|
1828
|
+
if (payload?.restore === true) return restoreDeleted({ libraryId, id })
|
|
1763
1829
|
const entry = loadPrivateIndex(libraryId).entries[id]
|
|
1764
1830
|
if (!entry || !['archived', 'suppressed', 'expired'].includes(entry.status)) throw new Error('only archived memories can be deleted permanently; archive it first')
|
|
1765
|
-
|
|
1831
|
+
// Same gate every other irreversible operation in this file uses. The status check
|
|
1832
|
+
// above is a lifecycle rule, not consent: a caller that reached this line by
|
|
1833
|
+
// accident should not be able to erase a memory just because it happened to be
|
|
1834
|
+
// archived. Order matters — keeping this after the status check preserves the
|
|
1835
|
+
// "archive it first" refusal old callers depend on.
|
|
1836
|
+
if (payload?.confirmed !== true) throw new Error('permanently deleting a memory requires explicit confirmation')
|
|
1837
|
+
const safety = await backupDatabases()
|
|
1766
1838
|
return { ...await privateDelete({ libraryId, id }), safety }
|
|
1767
1839
|
}
|
|
1768
1840
|
case 'setup': {
|
|
@@ -1802,7 +1874,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1802
1874
|
return { ...result, backups: listBackups() }
|
|
1803
1875
|
}
|
|
1804
1876
|
case 'restoreBackup': {
|
|
1805
|
-
const result = restoreBackup(String(payload?.name || ''), {
|
|
1877
|
+
const result = await restoreBackup(String(payload?.name || ''), {
|
|
1806
1878
|
// Take a fresh backup of the live data before anything is replaced, so a
|
|
1807
1879
|
// mistaken restore is itself reversible.
|
|
1808
1880
|
beforeRestore: () => backupDatabases(),
|
|
@@ -1885,7 +1957,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1885
1957
|
})
|
|
1886
1958
|
case 'switchLocalVectorProfile':
|
|
1887
1959
|
if (payload?.confirmed !== true) throw new Error('switching the local vector profile requires explicit confirmation')
|
|
1888
|
-
return await switchLocalVectorProfile({ id: payload?.id })
|
|
1960
|
+
return await switchLocalVectorProfile({ id: payload?.id, force: payload?.force === true })
|
|
1889
1961
|
case 'rollbackLocalVectorProfile':
|
|
1890
1962
|
if (payload?.confirmed !== true) throw new Error('rolling back the local vector profile requires explicit confirmation')
|
|
1891
1963
|
return await rollbackLocalVectorProfile()
|
|
@@ -1933,6 +2005,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1933
2005
|
return { cleared: cleared.removed, feed: await consolidationFeed(ctx, payload) }
|
|
1934
2006
|
}
|
|
1935
2007
|
case 'clearActivityLog':
|
|
2008
|
+
// Bulk diagnostic evidence removal is destructive; the adjacent delete /
|
|
2009
|
+
// archive paths require an explicit confirmation and this one used to be a
|
|
2010
|
+
// single accidental click away.
|
|
2011
|
+
if (payload?.confirmed !== true) throw new Error('clearing the activity log requires explicit confirmation')
|
|
1936
2012
|
return clearEvents()
|
|
1937
2013
|
default:
|
|
1938
2014
|
throw new Error(`unknown endpoint: ${endpoint}`)
|
|
@@ -1948,10 +2024,19 @@ export function registerRpc(ctx) {
|
|
|
1948
2024
|
kind: 'prefix',
|
|
1949
2025
|
path: ENDPOINT,
|
|
1950
2026
|
handler: async (req, res) => {
|
|
1951
|
-
|
|
2027
|
+
// Capability probe, not a version check: `requestRejection` exists on
|
|
2028
|
+
// 0.1.2-rc.x and later of dsh-client-connection and not at all on the rc.8
|
|
2029
|
+
// / 0.1.1-rc.2 copies, where the service only exposes
|
|
2030
|
+
// `isTrustedApiRequest`. Calling it blindly threw a TypeError out of the
|
|
2031
|
+
// request handler, which the host turns into a 500 — an unauthenticated
|
|
2032
|
+
// caller then learned the route exists instead of being refused.
|
|
2033
|
+
const rejection = typeof c.connection?.requestRejection === 'function'
|
|
2034
|
+
? c.connection.requestRejection(req)
|
|
2035
|
+
: undefined
|
|
1952
2036
|
if (rejection !== undefined) {
|
|
1953
|
-
|
|
1954
|
-
res.
|
|
2037
|
+
const status = rejection === 401 ? 401 : 403
|
|
2038
|
+
res.writeHead(status)
|
|
2039
|
+
res.end(status === 401 ? 'unauthorized' : 'forbidden')
|
|
1955
2040
|
return
|
|
1956
2041
|
}
|
|
1957
2042
|
const requestUrl = new URL(req.url || '/', 'http://dsh.internal')
|
|
@@ -1990,7 +2075,7 @@ export function registerRpc(ctx) {
|
|
|
1990
2075
|
res.end(JSON.stringify({ ok: true, value: { ...value, missingAttachments: bundle.missing } }))
|
|
1991
2076
|
} catch (error) {
|
|
1992
2077
|
res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
|
|
1993
|
-
res.end(JSON.stringify({ ok: false, error: { message:
|
|
2078
|
+
res.end(JSON.stringify({ ok: false, error: { message: rpcErrorMessage(error) } }))
|
|
1994
2079
|
}
|
|
1995
2080
|
return
|
|
1996
2081
|
}
|
|
@@ -2096,7 +2181,7 @@ export function registerRpc(ctx) {
|
|
|
2096
2181
|
ok: false,
|
|
2097
2182
|
error: {
|
|
2098
2183
|
code: error?.code || 'dsh-memu-memory/error',
|
|
2099
|
-
message:
|
|
2184
|
+
message: rpcErrorMessage(error),
|
|
2100
2185
|
details: {},
|
|
2101
2186
|
},
|
|
2102
2187
|
}
|
package/lib/snippet.js
CHANGED
|
@@ -61,3 +61,44 @@ export function centeredSnippet(text, query, { before = 40, after = 120 } = {})
|
|
|
61
61
|
const tail = end < body.length ? ELLIPSIS : ''
|
|
62
62
|
return head + body.slice(start, end) + tail
|
|
63
63
|
}
|
|
64
|
+
|
|
65
|
+
function clip(value, max) {
|
|
66
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim()
|
|
67
|
+
return text.length <= max ? text : text.slice(0, Math.max(0, max - 1)) + ELLIPSIS
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* S2/S6 冲突卡:两条对同一事实的不同说法并排,不替模型裁决。
|
|
72
|
+
* 单卡 200 字以内;两个 id 都必须出现,否则调用方应丢弃这张卡。
|
|
73
|
+
* P1-2: A/B 顺序只按本地 fact_authority + 时间排,不增加任何文字。
|
|
74
|
+
*/
|
|
75
|
+
const FACT_AUTHORITY = { user_said: 3, tool: 2, told: 2, inferred: 1, imagined: 0 }
|
|
76
|
+
|
|
77
|
+
function authorityOf(entry) {
|
|
78
|
+
const explicit = Number(entry?.fact_authority)
|
|
79
|
+
if (Number.isFinite(explicit)) return explicit
|
|
80
|
+
return FACT_AUTHORITY[entry?.source_kind || entry?.source] ?? 0
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function observedOf(entry) {
|
|
84
|
+
return String(entry?.observed_at || entry?.updatedAt || entry?.createdAt || '')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function conflictCard({ factKey, left, right } = {}) {
|
|
88
|
+
if (!left?.id || !right?.id) return ''
|
|
89
|
+
const side = (item, label) => {
|
|
90
|
+
const entry = item.entry || {}
|
|
91
|
+
const title = entry.title || entry.content || '(untitled)'
|
|
92
|
+
const date = entry.absolute_date ? `(${entry.absolute_date})` : ''
|
|
93
|
+
return `- ${label} [${item.id}] ${clip(title, 40)}${date}`
|
|
94
|
+
}
|
|
95
|
+
const ordered = [left, right].sort((a, b) => authorityOf(b.entry) - authorityOf(a.entry)
|
|
96
|
+
|| observedOf(b.entry).localeCompare(observedOf(a.entry))
|
|
97
|
+
|| String(a.id).localeCompare(String(b.id)))
|
|
98
|
+
return clip([
|
|
99
|
+
`冲突 · ${clip(factKey || '同一事实', 60)}`,
|
|
100
|
+
side(ordered[0], 'A'),
|
|
101
|
+
side(ordered[1], 'B'),
|
|
102
|
+
'- 未确认哪版为准',
|
|
103
|
+
].join('\n'), 200)
|
|
104
|
+
}
|