dsh-memu-memory 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/private.js CHANGED
@@ -392,7 +392,25 @@ function snapshotMetaOf(snapshot) {
392
392
  // user's own chat — a queued draft until it runs, then a permanent resident of
393
393
  // that transcript — so the one visible difference between a live and a closed
394
394
  // session is that a closed one has to be read back from disk first.
395
- export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs = 180_000, force = false } = {}) {
395
+ // 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
396
+ // 开始写。实测(2026-11-02,935 条事件的会话):第一次 180 s 到点时刚写完 3 条、
397
+ // 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算,
398
+ // 并夹在 [180 s, 600 s]:小会话维持原来的 3 分钟,大会话不再必然撞墙,卡死的 fork
399
+ // 也仍会在 10 分钟内被收掉。显式传 maxWaitMs 的调用(含工具/测试)原样生效。
400
+ export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
401
+ baseMs: 120_000,
402
+ perEventMs: 350,
403
+ minMs: 180_000,
404
+ maxMs: 600_000,
405
+ })
406
+
407
+ export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_POLICY) {
408
+ const count = Number.isFinite(Number(eventCount)) ? Math.max(0, Math.floor(Number(eventCount))) : 0
409
+ const raw = policy.baseMs + count * policy.perEventMs
410
+ return Math.min(policy.maxMs, Math.max(policy.minMs, raw))
411
+ }
412
+
413
+ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs = null, force = false } = {}) {
396
414
  const binding = getSessionBinding(sessionId)
397
415
  if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
398
416
  if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
@@ -492,6 +510,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
492
510
  const snapshot = captured.snapshot
493
511
  const events = captured.events
494
512
  const snapshotMeta = snapshotMetaOf(snapshot)
513
+ // 范围大小决定等多久:显式给了就听调用方的,没给按这段转录的事件数推。
514
+ const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(events.length)
495
515
  const generationAtStart = scopeGenerationOf(binding)
496
516
  // 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
497
517
  safeLedger(() => noteEvidence({ sessionId, fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq }))
@@ -634,8 +654,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
634
654
  sessionId,
635
655
  libraryId: binding.libraryId || null,
636
656
  ok: true,
637
- message: '整理已开始 · ' + (force ? '手动' : '空闲') + ' · fork ' + childId.slice(-8) + ' · ' + events.length + ' 条事件 · 快照 ' + snapshot.hash,
638
- detail: { childId, jobId, force, events: events.length, phase: 'started', snapshot: snapshotMeta,
657
+ message: '整理已开始 · ' + (force ? '手动' : '空闲') + ' · fork ' + childId.slice(-8) + ' · ' + events.length + ' 条事件 · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
658
+ detail: { childId, jobId, force, events: events.length, budgetMs, phase: 'started', snapshot: snapshotMeta,
639
659
  probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
640
660
  ...workerToolsMeta(workerTools) },
641
661
  })
@@ -726,7 +746,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
726
746
  let timer = null
727
747
  let outcome
728
748
  try {
729
- const wait = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), maxWaitMs) })
749
+ const wait = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs) })
730
750
  outcome = await Promise.race([idle.then(() => 'done'), wait])
731
751
  } finally { clearTimeout(timer) }
732
752
 
@@ -819,7 +839,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, { maxWaitMs
819
839
  settled: false,
820
840
  timedOut: true,
821
841
  reasonCode: 'timeout',
822
- error: 'consolidation timed out after ' + Math.round(maxWaitMs / 1000) + 's; the fork was stopped (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
842
+ error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + events.length + ' events; the fork was stopped (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
823
843
  })
824
844
  }
825
845
  return finish({
package/lib/rpc.js CHANGED
@@ -1691,7 +1691,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1691
1691
  case 'getLocalVectorState':
1692
1692
  return getLocalVectorState()
1693
1693
  case 'downloadLocalVectorModel':
1694
- return await downloadLocalVectorModel(String(payload?.id || ''), { confirmed: payload?.confirmed === true })
1694
+ return await downloadLocalVectorModel(String(payload?.id || ''), {
1695
+ confirmed: payload?.confirmed === true,
1696
+ ...(payload?.provider ? { provider: String(payload.provider) } : {}),
1697
+ })
1695
1698
  case 'selectLocalVectorModel':
1696
1699
  return selectLocalVectorModel(String(payload?.id || ''))
1697
1700
  case 'installLocalVectorRuntime':
package/lib/state.js CHANGED
@@ -1044,6 +1044,87 @@ export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
1044
1044
  return setSessionBinding(sessionId, { openLoopRemindedAt: reminded })
1045
1045
  }
1046
1046
 
1047
+ /**
1048
+ * 记下"这一回合投放了哪些一次性内容",供宿主把整轮回滚时撤销记账(§3.24)。
1049
+ * 同一个 hostTurn 多次调用会把 ids 并起来:一步里可能同时投了锚点、纪念日与 nudge。
1050
+ */
1051
+ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKey = null, nudgeIds = [], anniversaryIds = [] } = {}) {
1052
+ const turn = Number(hostTurn)
1053
+ if (!sessionId || !Number.isSafeInteger(turn) || turn < 0) return null
1054
+ if (!getSessionBinding(sessionId)) return null
1055
+ return updateState((state) => {
1056
+ const binding = state.sessions[sessionId]
1057
+ if (!binding) return state
1058
+ const previous = binding.injectionRollback
1059
+ const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
1060
+ binding.injectionRollback = {
1061
+ hostTurn: turn,
1062
+ ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
1063
+ nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
1064
+ anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
1065
+ guideKey: guideKey || same.guideKey || null,
1066
+ }
1067
+ return state
1068
+ }).sessions[sessionId].injectionRollback
1069
+ }
1070
+
1071
+ /**
1072
+ * §3.24 —— 宿主会把「请求根本没发出去」的整轮回滚(连用户消息都不留在转录里,真机实测如此),
1073
+ * 可插件在"消息交回决策"之后就记账了:于是 guide 与锚点这类一次性内容**再也不会投**,整段对话
1074
+ * 直到下次压缩都没有记忆总览,且一声不吭。回合失败时把那一轮写下的记账撤回来。
1075
+ * 只有与 `recordInjectionRollback` 记的同一个 hostTurn 对得上才生效;「该不该撤」由调用方按
1076
+ * 转录实证判定(inject.js 的 injectionAdmissions),所以走到这里的内容确实没进转录,
1077
+ * 下一轮重投不会出现第二份。返回撤回了什么,供活动日志留信号。
1078
+ */
1079
+ export function rollbackInjectionForTurn(sessionId, hostTurn) {
1080
+ const turn = Number(hostTurn)
1081
+ if (!sessionId || !Number.isSafeInteger(turn)) return null
1082
+ let rolled = null
1083
+ updateState((state) => {
1084
+ const binding = state.sessions[sessionId]
1085
+ const record = binding?.injectionRollback
1086
+ if (!binding || !record || record.hostTurn !== turn) return state
1087
+ const ids = new Set(record.ids || [])
1088
+ if (ids.size) {
1089
+ binding.injectedIds = (binding.injectedIds || []).filter((id) => !ids.has(id))
1090
+ if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1091
+ }
1092
+ if (record.guideKey && binding.guideRulesKey === record.guideKey) {
1093
+ delete binding.guideRulesKey
1094
+ delete binding.guideMessageAt
1095
+ }
1096
+ if (binding.anniversariesShown) for (const id of record.anniversaryIds || []) delete binding.anniversariesShown[id]
1097
+ if (binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) delete binding.openLoopRemindedAt[id]
1098
+ rolled = {
1099
+ ids: [...ids],
1100
+ guideKey: record.guideKey || null,
1101
+ anniversaries: (record.anniversaryIds || []).length,
1102
+ nudges: (record.nudgeIds || []).length,
1103
+ }
1104
+ delete binding.injectionRollback
1105
+ return state
1106
+ })
1107
+ return rolled
1108
+ }
1109
+
1110
+ /**
1111
+ * 回合收尾、但那份记账不该作废时消费掉它(正常完成,或失败时注入的消息其实已经进了转录):
1112
+ * 东西已经投出去了,之后再来一条迟到的 error 事件也不该把它撤回(否则就是凭空的第二次锚点/规则消息)。
1113
+ */
1114
+ export function consumeInjectionRollback(sessionId, hostTurn) {
1115
+ const turn = Number(hostTurn)
1116
+ if (!sessionId || !Number.isSafeInteger(turn)) return false
1117
+ let consumed = false
1118
+ updateState((state) => {
1119
+ const binding = state.sessions[sessionId]
1120
+ if (!binding?.injectionRollback || binding.injectionRollback.hostTurn !== turn) return state
1121
+ delete binding.injectionRollback
1122
+ consumed = true
1123
+ return state
1124
+ })
1125
+ return consumed
1126
+ }
1127
+
1047
1128
  export function memoryDbPath(libraryId) {
1048
1129
  ensureDir(librariesDir())
1049
1130
  return effectiveVectorRoute() === 'managed-local' ? memuDbFor(libraryId) : path.join(librariesDir(), `${libraryId}.sqlite3`)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.2.3",
4
+ "version": "1.2.4",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -62,7 +62,8 @@
62
62
  "setup": "node scripts/setup.mjs",
63
63
  "test": "node --import ./tests/loader-register.mjs --test tests/*.test.mjs",
64
64
  "test:chain": "node scripts/chain-matrix.mjs",
65
- "replay": "node --import ./tests/loader-register.mjs scripts/replay.mjs"
65
+ "replay": "node --import ./tests/loader-register.mjs scripts/replay.mjs",
66
+ "simulate:injection": "node scripts/simulate-injection.mjs"
66
67
  },
67
68
  "engines": {
68
69
  "node": ">=20.9.0",
@@ -27,7 +27,7 @@
27
27
  * "type": "client-request",
28
28
  * "rpcId": "<connection correlation id>",
29
29
  * "method": "session/prompt",
30
- * "payload": { "args": { <SessionPromptRequest> } }
30
+ * "payload": { "args": { "request": <SessionPromptRequest> } }
31
31
  * }
32
32
  * ->
33
33
  * { "type": "server-response", "rpcId": "<same>", "result": { "ok": true, "value": { "accepted": true } } }
@@ -614,15 +614,25 @@ function joinUrl(base, suffix) {
614
614
  return String(base).replace(/\/+$/, '') + suffix
615
615
  }
616
616
 
617
- async function sendPrompt({ base, request, timeoutMs, cookie }) {
618
- const url = joinUrl(base, '/api/session/prompt')
619
- const rpcId = crypto.randomUUID()
620
- const envelope = {
617
+ /**
618
+ * The Connection RPC carrier wraps each Remote method parameter by **name**, so a
619
+ * single-argument remote must go out as `{ args: { request: <SessionPromptRequest> } }`.
620
+ * Sending the request fields directly is rejected before the host ever sees them
621
+ * (`gateway/arguments-invalid: missing "request"`) — which is what this file did until it
622
+ * actually met a real host.
623
+ */
624
+ export function buildPromptEnvelope(request, rpcId = crypto.randomUUID()) {
625
+ return {
621
626
  type: 'client-request',
622
627
  rpcId,
623
628
  method: 'session/prompt',
624
- payload: { args: request },
629
+ payload: { args: { request } },
625
630
  }
631
+ }
632
+
633
+ async function sendPrompt({ base, request, timeoutMs, cookie }) {
634
+ const url = joinUrl(base, '/api/session/prompt')
635
+ const envelope = buildPromptEnvelope(request)
626
636
  const headers = { 'content-type': 'application/json' }
627
637
  if (cookie) headers.cookie = cookie
628
638
  let response
@@ -649,7 +659,7 @@ async function sendPrompt({ base, request, timeoutMs, cookie }) {
649
659
  } catch {
650
660
  throw new Error('response is not JSON (expected a Connection RPC envelope)')
651
661
  }
652
- if (!body || body.type !== 'server-response' || body.rpcId !== rpcId) {
662
+ if (!body || body.type !== 'server-response' || body.rpcId !== envelope.rpcId) {
653
663
  throw new Error('response is not the matching Connection RPC envelope')
654
664
  }
655
665
  if (!body.result || body.result.ok !== true) {
@@ -659,7 +669,7 @@ async function sendPrompt({ base, request, timeoutMs, cookie }) {
659
669
  if (body.result.value?.accepted !== true) {
660
670
  throw new Error('session/prompt did not return { accepted: true }')
661
671
  }
662
- return { rpcId }
672
+ return { rpcId: envelope.rpcId }
663
673
  }
664
674
 
665
675
  function isLoopbackHost(hostname) {
@@ -848,6 +858,7 @@ export {
848
858
  promptClaimIndex,
849
859
  readSessionEvents,
850
860
  scanZstdFrames,
861
+ sendPrompt,
851
862
  textOfPromptItem,
852
863
  waitForTurn,
853
864
  }
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EVALUATION ONLY — 离线注入模拟器(工单 B 量具的一半,与 mock-llm 配套)。
4
+ *
5
+ * 它回答的问题:注入管线**在当前设置下**每回合真的往模型请求里新加了哪些块、加了几次。
6
+ * 与真机跑(scripts/drive-session.mjs)的分工:这里用真实的 lib/inject.js、真实的
7
+ * registerInjection('agent/pre-step') 与真实的 lib/state.js 索引,但宿主侧的消息组装、
8
+ * 真实模型的 tool 轮**不在**覆盖范围内。产数是"插件自己决定了什么",不是"真实装机上
9
+ * 模型收到了什么";两者对不上时以真机为准。
10
+ *
11
+ * 为什么不碰真实数据:记忆库写进一个临时 DSH_MEMU_HOME(或 --home 指定的空目录),模型请求
12
+ * 打到只监听 127.0.0.1 的 mock-llm,日志仍只有长度/哈希/标记计数。
13
+ *
14
+ * 转录是累积的(和宿主一样把已发过的插件消息留在上下文里)。这不是偷懒的反面:
15
+ * ensureUnifiedGuide 会检查 decision.messages 里有没有当前规则的 guide,历史里没有 guide
16
+ * 就每轮重投一条,guide 计数会变成 50/50 而不是 1/50 —— 那种数只能证明驱动错了。
17
+ *
18
+ * Usage:
19
+ * node scripts/simulate-injection.mjs # 50 轮,cue 概率置 0 便于复现
20
+ * node scripts/simulate-injection.mjs --turns 20 --out ./sim-run
21
+ * node scripts/simulate-injection.mjs --cue 0.02 --home ./sim-home
22
+ *
23
+ * Options:
24
+ * --turns <n> 轮数,1..500。默认 50。
25
+ * --home <p> 当 DSH_MEMU_HOME 用的目录(不存在则创建)。默认临时目录。
26
+ * --out <p> 产物目录(report.md / mock-llm.jsonl / settings-snapshot.json)。默认临时目录。
27
+ * --port <n> 伪端点端口,0 = 系统分配。默认 0。
28
+ * --cue <p> 覆盖 settings.randomCueChance。默认 0(出货默认是 0.02,随机会让跑数不可复现)。
29
+ * --json 只打印一行 JSON 摘要。
30
+ *
31
+ * Exit codes: 0 ok / 2 usage error / 3 注入链路报了 warn(模拟器把 warn 当失败,不当噪声)。
32
+ */
33
+ import fs from 'node:fs'
34
+ import os from 'node:os'
35
+ import path from 'node:path'
36
+ import { registerHooks } from 'node:module'
37
+
38
+ const REPO_URL = new URL('../', import.meta.url)
39
+
40
+ function parseArgs(argv) {
41
+ const options = { turns: 50, home: null, out: null, port: 0, cue: 0, json: false }
42
+ const take = (index) => {
43
+ const value = argv[index]
44
+ if (value === undefined || value.startsWith('--')) throw new Error('missing value')
45
+ return value
46
+ }
47
+ for (let i = 0; i < argv.length; i += 1) {
48
+ const arg = argv[i]
49
+ switch (arg) {
50
+ case '--turns': options.turns = Number(take(++i)); break
51
+ case '--home': options.home = path.resolve(take(++i)); break
52
+ case '--out': options.out = path.resolve(take(++i)); break
53
+ case '--port': options.port = Number(take(++i)); break
54
+ case '--cue': options.cue = Number(take(++i)); break
55
+ case '--json': options.json = true; break
56
+ case '-h':
57
+ case '--help':
58
+ console.log(`EVALUATION ONLY — offline injection simulator (pairs with scripts/mock-llm.mjs).
59
+
60
+ node scripts/simulate-injection.mjs [--turns 50] [--home <dir>] [--out <dir>]
61
+ [--port <n>] [--cue <chance>] [--json]
62
+
63
+ Drives the real lib/inject.js through registerInjection('agent/pre-step') against a seeded
64
+ library in a throwaway DSH_MEMU_HOME, and posts every assembled request to a loopback mock
65
+ LLM. Writes report.md, mock-llm.jsonl and settings-snapshot.json under --out, plus a JSON
66
+ summary on stdout. Not real-engine evidence: host-side assembly and real tool rounds are
67
+ out of scope.`)
68
+ process.exit(0)
69
+ break
70
+ default: throw new Error('unknown option ' + arg)
71
+ }
72
+ }
73
+ if (!Number.isInteger(options.turns) || options.turns < 1 || options.turns > 500) throw new Error('--turns must be 1..500')
74
+ if (!Number.isFinite(options.cue) || options.cue < 0 || options.cue > 1) throw new Error('--cue must be 0..1')
75
+ return options
76
+ }
77
+
78
+ let parsed
79
+ try {
80
+ parsed = parseArgs(process.argv.slice(2))
81
+ } catch (error) {
82
+ console.error('simulate-injection: ' + error.message)
83
+ process.exit(2)
84
+ }
85
+
86
+ const work = parsed.home || fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-sim-'))
87
+ const outDir = parsed.out || fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-sim-out-'))
88
+ fs.mkdirSync(work, { recursive: true })
89
+ fs.mkdirSync(outDir, { recursive: true })
90
+ process.env.DSH_MEMU_HOME = work
91
+ process.env.DSH_MEMU_MEMORY_HOME = work
92
+
93
+ // lib/inject.js imports the host's createUserMessage; reuse the test stubs so this runs
94
+ // straight from a checkout with no host present.
95
+ registerHooks({
96
+ resolve(specifier, context, nextResolve) {
97
+ if (specifier === '@deepseek-ai/dsh-llm') return { url: new URL('tests/stubs/dsh-llm.js', REPO_URL).href, shortCircuit: true }
98
+ if (specifier === '@deepseek-ai/dsh-tools') return { url: new URL('tests/stubs/dsh-tools.js', REPO_URL).href, shortCircuit: true }
99
+ if (specifier === '@deepseek-ai/dsh-session') return { url: new URL('tests/stubs/dsh-session.js', REPO_URL).href, shortCircuit: true }
100
+ return nextResolve(specifier, context)
101
+ },
102
+ })
103
+
104
+ const state = await import(new URL('lib/state.js', REPO_URL))
105
+ const inject = await import(new URL('lib/inject.js', REPO_URL))
106
+ const mock = await import(new URL('scripts/mock-llm.mjs', REPO_URL))
107
+
108
+ const SESSION = 'sim-session'
109
+ const cwd = path.join(work, 'project')
110
+ const binding = state.ensureSession(SESSION, { cwd, agentPreset: 'rp' })
111
+ const libraryId = binding.libraryId
112
+ state.setSessionBinding(SESSION, { useLibrary: true, useGlobal: false })
113
+ state.updateSettings({ randomCueChance: parsed.cue })
114
+
115
+ const day = (offset, hour = 12) => {
116
+ const value = new Date()
117
+ value.setDate(value.getDate() + offset)
118
+ value.setHours(hour, 0, 0, 0)
119
+ return value
120
+ }
121
+ const ymd = (value) => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
122
+ const mmdd = (value) => `${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
123
+
124
+ let seeded = 0
125
+ function seed(patch) {
126
+ const id = `mem-sim-${String(++seeded).padStart(2, '0')}`
127
+ state.updatePrivateIndex(libraryId, (index) => {
128
+ index.entries[id] = {
129
+ id,
130
+ track: 'memory',
131
+ layer: 'long_term',
132
+ title: id,
133
+ content: `${id} 的正文,涉及林眠、老周与城南那家咖啡店。`,
134
+ status: 'active',
135
+ disclosure: 'can_tell',
136
+ visibility: 'shared',
137
+ owner: 'me',
138
+ createdAt: day(-40).toISOString(),
139
+ updatedAt: day(-40).toISOString(),
140
+ ...patch,
141
+ }
142
+ })
143
+ return id
144
+ }
145
+
146
+ // 播种库是量具,不是任何人生活的样本:每种可注入的块都刻意放一条,报告里出现 0 才意味着
147
+ // "管线这次没选它",而不是"库里没有可说的"。
148
+ function seedScenario() {
149
+ seed({ title: '明天要还给林眠的相机镜头', salientDate: ymd(day(1)), openLoop: true, updatedAt: day(-2).toISOString(), createdAt: day(-2).toISOString() })
150
+ seed({ title: '今天答应陪老周体检', salientDate: ymd(day(0)), openLoop: true, updatedAt: day(-1).toISOString(), createdAt: day(-1).toISOString() })
151
+ seed({ title: '上周说过要回复的合同修改意见', salientDate: ymd(day(-6)), openLoop: true, updatedAt: day(-7).toISOString(), createdAt: day(-7).toISOString() })
152
+ seed({ title: '答应给林眠带城南的咖啡豆,一直没做', openLoop: true, updatedAt: day(-5).toISOString(), createdAt: day(-5).toISOString() })
153
+ seed({ title: '答应陪林眠去看海,日期未定', openLoop: true, updatedAt: day(-9).toISOString(), createdAt: day(-9).toISOString() })
154
+ seed({ title: '一起看海的纪念日', salientDate: mmdd(day(0)), updatedAt: day(-200).toISOString(), createdAt: day(-200).toISOString() })
155
+ seed({ title: '林眠说她的最新版本渲染器会崩', content: '林眠反馈最新版本渲染器崩溃,日志里是显存不足。', updatedAt: day(-3).toISOString(), createdAt: day(-3).toISOString() })
156
+ seed({ title: '城南咖啡店最近的豆子价格', content: '城南咖啡店最近的豆子价格:半磅 88 元,现在是活动价。', updatedAt: day(-4).toISOString(), createdAt: day(-4).toISOString() })
157
+ seed({ title: '老周现在的治疗方案的最新结论', content: '老周目前的治疗方案,医生给的最新结论是保守观察。', updatedAt: day(-8).toISOString(), createdAt: day(-8).toISOString() })
158
+ seed({ title: '四个月前记下的相机型号对比', content: '四个月前对比过两台机器的宽容度与价格。', updatedAt: day(-120).toISOString(), createdAt: day(-120).toISOString() })
159
+ seed({ title: '林眠讨厌在别人讲故事时看手机', updatedAt: day(-60).toISOString(), createdAt: day(-60).toISOString() })
160
+ seed({ title: '老周的女儿今年高考', updatedAt: day(-30).toISOString(), createdAt: day(-30).toISOString() })
161
+ // 近似重复的一对主题:该只回一次,不该连着推两次。
162
+ seed({ title: '林眠的相机镜头跑焦问题', updatedAt: day(-15).toISOString(), createdAt: day(-15).toISOString() })
163
+ seed({ title: '林眠镜头跑焦的维修报价', updatedAt: day(-16).toISOString(), createdAt: day(-16).toISOString() })
164
+ for (let index = 15; index <= 26; index += 1) {
165
+ seed({ title: `日常片段 ${index}:和老周下棋、给植物浇水、整理书架`, updatedAt: day(-index).toISOString(), createdAt: day(-index).toISOString() })
166
+ }
167
+ }
168
+ seedScenario()
169
+
170
+ const PROMPTS = [
171
+ '我们上次说到哪儿了?',
172
+ '你还记得林眠的相机吗?',
173
+ '明天有什么我要办的事?',
174
+ '嗯',
175
+ '城南那家店现在豆子多少钱?',
176
+ '老周最近怎么样?',
177
+ '帮我理一下今天要做的事。',
178
+ '我是不是答应过你什么事没做?',
179
+ '林眠说的渲染器最新版本靠谱吗?',
180
+ '聊聊别的,比如我最近在读的书。',
181
+ '体检那件事后来怎么处理的?',
182
+ '你还记得我们约好看海吗?',
183
+ '把上次那个合同的事再说一遍。',
184
+ '今天有点累,随便聊聊吧。',
185
+ ]
186
+
187
+ const SYSTEM_PROMPT = '你是这个角色扮演与陪伴对话里的助手。请按用户的请求自然回应,必要时使用记忆。'
188
+ const REPLY = mock.DEFAULT_REPLY
189
+
190
+ const warns = []
191
+ const handlers = new Map()
192
+ const ctx = {
193
+ on: (topic, handler) => { handlers.set(topic, handler); return () => {} },
194
+ get: () => undefined,
195
+ logger: { warn: (message) => warns.push(String(message)), info: () => {}, error: (message) => warns.push(String(message)) },
196
+ effect: (fn) => { try { fn() } catch {} },
197
+ slots: { inject: () => {} },
198
+ webServer: { register: () => {} },
199
+ }
200
+ const disposeInjection = inject.registerInjection(ctx)
201
+ const preStep = handlers.get('agent/pre-step')
202
+ if (typeof preStep !== 'function') throw new Error('agent/pre-step handler was not registered')
203
+
204
+ const logPath = path.join(outDir, 'mock-llm.jsonl')
205
+ const instance = await mock.startMockLlm({ port: parsed.port, log: logPath, reply: REPLY })
206
+
207
+ const agent = { session: { header: { id: SESSION, cwd, agentPreset: 'rp', origin: 'user' } } }
208
+ const textOf = (message) => (typeof message?.content === 'string'
209
+ ? message.content
210
+ : (message?.content || []).map((part) => part?.text || '').join(''))
211
+
212
+ const deltaTotals = Object.fromEntries(mock.MARKER_KEYS.map((key) => [key, 0]))
213
+ const roundsWithBlock = Object.fromEntries(mock.MARKER_KEYS.map((key) => [key, 0]))
214
+ let roundsWithInjection = 0
215
+ let titleCardBodyLineMax = 0
216
+ let sendFailures = 0
217
+
218
+ let history = []
219
+ for (let turn = 1; turn <= parsed.turns; turn += 1) {
220
+ const known = new Set(history)
221
+ history = [...history, {
222
+ id: `u-${turn}`,
223
+ role: 'user',
224
+ source: { kind: 'user' },
225
+ content: [{ type: 'text', text: PROMPTS[(turn - 1) % PROMPTS.length] }],
226
+ }]
227
+ const out = await preStep({ agent, turn, step: 1, signal: { aborted: false } }, async () => ({ kind: 'enter', messages: history }))
228
+ const messages = Array.isArray(out?.messages) ? out.messages : history
229
+ if (messages.length > history.length) roundsWithInjection += 1
230
+ for (const message of messages.filter((item) => !known.has(item))) {
231
+ const analysis = mock.analyzeMessage({ role: 'user', content: textOf(message) })
232
+ for (const key of mock.MARKER_KEYS) {
233
+ const count = Number(analysis.markers?.[key] || 0)
234
+ if (!count) continue
235
+ deltaTotals[key] += count
236
+ roundsWithBlock[key] += 1
237
+ }
238
+ titleCardBodyLineMax = Math.max(titleCardBodyLineMax, Number(analysis.context?.bodyLines || 0))
239
+ }
240
+ history = messages
241
+ const payload = [
242
+ { role: 'system', content: SYSTEM_PROMPT },
243
+ ...messages.map((message) => ({ role: message.role === 'assistant' ? 'assistant' : 'user', content: textOf(message) })),
244
+ ]
245
+ const response = await fetch(`${instance.url}/v1/chat/completions`, {
246
+ method: 'POST',
247
+ headers: { 'content-type': 'application/json' },
248
+ body: JSON.stringify({ model: instance.model, stream: true, messages: payload }),
249
+ })
250
+ if (!response.ok) sendFailures += 1
251
+ await response.text()
252
+ history = [...history, { id: `a-${turn}`, role: 'assistant', content: [{ type: 'text', text: REPLY }] }]
253
+ }
254
+
255
+ instance.close()
256
+ try { disposeInjection() } catch {}
257
+
258
+ const settings = state.getSettings()
259
+ const finalBinding = state.getSessionBinding(SESSION)
260
+ const uniqueInjected = (finalBinding?.injectedIds || []).filter((id) => id !== inject.ANCHOR_SENTINEL).length
261
+ const snapshotPath = path.join(outDir, 'settings-snapshot.json')
262
+ fs.writeFileSync(snapshotPath, JSON.stringify({
263
+ takenAt: new Date().toISOString(),
264
+ note: '报告证明不了设置值,这份快照就是读数口径',
265
+ run: { turns: parsed.turns, entries: seeded, session: SESSION, agentPreset: 'rp', driver: "registerInjection('agent/pre-step')" },
266
+ settings: {
267
+ autoInject: settings.autoInject, privateTopK: settings.privateTopK, globalTopK: settings.globalTopK,
268
+ anchorTokens: settings.anchorTokens, turnTokens: settings.turnTokens, injectionTotalTokens: settings.injectionTotalTokens,
269
+ dedupeTurns: settings.dedupeTurns, minUserChars: settings.minUserChars, randomCueChance: settings.randomCueChance,
270
+ openLoopRemindDays: settings.openLoopRemindDays, freshnessHint: settings.freshnessHint, freshnessDays: settings.freshnessDays,
271
+ salientWake: settings.salientWake,
272
+ },
273
+ }, null, 2))
274
+
275
+ const reportPath = path.join(outDir, 'report.md')
276
+ fs.writeFileSync(reportPath, mock.renderReport(fs.readFileSync(logPath, 'utf8'), { logPath }))
277
+
278
+ const summary = {
279
+ turns: parsed.turns,
280
+ roundsWithInjection,
281
+ injectionRate: Math.round((roundsWithInjection / parsed.turns) * 100) / 100,
282
+ deltaTotals,
283
+ roundsWithBlock,
284
+ titleCardBodyLineMax,
285
+ uniqueInjectedIds: uniqueInjected,
286
+ sendFailures,
287
+ warnCount: warns.length,
288
+ firstWarns: warns.slice(0, 3),
289
+ entries: seeded,
290
+ home: work,
291
+ out: outDir,
292
+ reportPath,
293
+ logPath,
294
+ snapshotPath,
295
+ }
296
+ console.log(parsed.json ? JSON.stringify(summary) : JSON.stringify(summary, null, 2))
297
+
298
+ if (warns.length > 0) process.exitCode = 3
@@ -278,9 +278,16 @@ test('the memory UI renders the read-only arousal/dominance/emotionSource line',
278
278
 
279
279
  test('the sidebar run log keeps five rows and links its header to the WebUI logs page', () => {
280
280
  const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
281
- assert.match(src, /runLog\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
281
+ // 侧栏只显示正常流水(失败由「整理提醒」负责),列表仍是最近 5 条。
282
+ assert.match(src, /runLog\.filter\(\(row\) => logRowState\(row\) !== 'failed'\)/, 'the sidebar run log must drop failed rows')
283
+ assert.match(src, /sidebarRuns\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
282
284
  assert.match(src, /openWebUiPage\('logs'\)/, 'the run-log header must open the WebUI logs page')
283
285
  assert.match(src, /runLogOpen/, 'the jump needs a visible label')
286
+ // 红色只属于 WebUI 的总日志页:侧栏整段不过 logRowClass(失败行已被过滤),
287
+ // 判据仍集中在 logRowState 一处,改口径只改那一处。
288
+ assert.equal((src.match(/className: logRowClass\(row\)/g) || []).length, 1, 'only the WebUI logs page marks row state')
289
+ assert.ok(src.includes('const sidebarRuns = runLog.filter('), 'the sidebar must filter failed rows before rendering')
290
+ assert.ok(!/tone: row\.level === 'error' \? 'warn'/.test(src), 'the old level-only predicate must not come back')
284
291
  })
285
292
 
286
293
  // The browser row is the only place a human can see that a memory is marked
@@ -863,6 +870,54 @@ test('API vector settings render provider fields and hide the managed local cata
863
870
  assert.ok(!nodes.some((node) => node.type === 'progress'))
864
871
  })
865
872
 
873
+ // 日志行的三档视觉状态。真实读数里整理超时记的是 level=warn + ok=false
874
+ //(lib/private.js 的超时路径),所以「只看 level==='error'」会把它显示成正常行——
875
+ // 用户看到的就是「失败长得好普通」。这条钉的是行为:哪一行该红、哪一行该橙、
876
+ // 哪一行什么都不该标。
877
+ test('failed and degraded activity rows are visually distinguished from normal rows', async () => {
878
+ const failed = {
879
+ id: 'act-failed', at: '2026-11-02T07:58:29.775Z', kind: 'consolidate', level: 'warn',
880
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1', ok: false,
881
+ message: '整理超时 · 空闲 · fork f-7535be · timeout:consolidation timed out after 180s', detail: null, refs: [],
882
+ }
883
+ const degraded = {
884
+ id: 'act-degraded', at: '2026-11-02T07:59:00.000Z', kind: 'vector', level: 'warn',
885
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
886
+ message: '向量未激活,写入已降级为索引+引擎', detail: { reason: 'no active vector generation' }, refs: [],
887
+ }
888
+ const normal = {
889
+ id: 'act-normal', at: '2026-11-02T08:02:40.988Z', kind: 'consolidate', level: 'info',
890
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
891
+ message: '整理完成 · 空闲 · fork 1-2b16be · 索引 +1', detail: null, refs: [],
892
+ }
893
+ const ctx = fakeCtx({
894
+ answers: { getActivityLog: { events: [failed, degraded, normal], stats: { total: 3, capped: 2000, bytes: 1024 } } },
895
+ })
896
+ globalThis.__dshMemuExports.apply(ctx)
897
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
898
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
899
+ collectPageHook()
900
+ for (const effect of first.effects) effect.fn()
901
+ await new Promise((resolve) => setTimeout(resolve, 0))
902
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
903
+ for (const effect of mid.effects) effect.fn()
904
+ await new Promise((resolve) => setTimeout(resolve, 0))
905
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
906
+ const rows = new Map()
907
+ const labels = []
908
+ walkNodes(tree, (node) => {
909
+ if (typeof node.props?.key === 'string' && node.props.key.startsWith('act-')) rows.set(node.props.key, node.props)
910
+ if (node.props?.children === 'logStateFailed' || node.props?.children === 'logDegraded') labels.push(node.props)
911
+ })
912
+ assert.equal(rows.size, 3, 'the log page rendered none of the fixture rows')
913
+ assert.match(String(rows.get('act-failed')?.className), /dshm-logrow is-failed/, 'the timeout row must carry the failed state class')
914
+ assert.match(String(rows.get('act-degraded')?.className), /dshm-logrow is-degraded/, 'a fallback-path row is degraded, not failed')
915
+ assert.equal(rows.get('act-normal')?.className, 'dshm-logrow', 'normal rows must not pick up any state class')
916
+ assert.ok(labels.some((props) => props.children === 'logStateFailed'), 'the failed row needs a 失败 label, not only colour')
917
+ assert.ok(labels.some((props) => props.children === 'logDegraded'), 'degraded rows need their own word')
918
+ assert.ok(labels.every((props) => typeof props.title === 'string' && props.title.length > 0), 'every state tag must explain itself on hover')
919
+ })
920
+
866
921
  test('clicking the API source tab sends the explicit setEmbeddingSource RPC only', async (t) => {
867
922
  const { nodes, rpcCalls } = await renderVectorSettings(t, {
868
923
  settings: { memoryBackend: 'api', vectorSource: 'local' },
@@ -9,7 +9,7 @@ process.env.DSH_MEMU_HOME = home
9
9
 
10
10
  const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
- const { requestPrivateConsolidation, isConsolidating } = await import('../lib/private.js')
12
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY } = await import('../lib/private.js')
13
13
 
14
14
  test.after(() => {
15
15
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
@@ -489,3 +489,16 @@ test('a non-PTC header without write tools still refuses to fork', async () => {
489
489
  assert.equal(result.reasonCode, 'worker-tools-missing')
490
490
  assert.equal(ctx.rec.created.length, 0, 'no fork when the model surface provably lacks the write tools')
491
491
  })
492
+
493
+ // 超时预算按范围大小推:935 条事件那次实测「180 s 到点只写了 3 条,退避重试 131 s 完成」,
494
+ // 约 0.14–0.2 s/事件;政策取 0.35 s/事件(≈2 倍余量)并夹在 [180 s, 600 s]。
495
+ test('the consolidation wait budget scales with the transcript, not a fixed 180 s', () => {
496
+ assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the old floor')
497
+ assert.equal(consolidationWaitBudget(100), 180_000, 'small sessions keep the original three minutes')
498
+ assert.equal(consolidationWaitBudget(200), 190_000)
499
+ assert.equal(consolidationWaitBudget(935), 447_250, 'the session that timed out gets ~7.5 minutes')
500
+ assert.equal(consolidationWaitBudget(5_000), CONSOLIDATION_WAIT_POLICY.maxMs, 'a wedged fork still dies inside ten minutes')
501
+ assert.equal(consolidationWaitBudget(undefined), CONSOLIDATION_WAIT_POLICY.minMs)
502
+ assert.equal(consolidationWaitBudget('not-a-number'), CONSOLIDATION_WAIT_POLICY.minMs)
503
+ assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
504
+ })