dsh-memu-memory 1.3.14 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +50 -1
  3. package/docs/binding-lifecycle.md +1 -1
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/host-adaptation.md +58 -16
  6. package/docs/host-versions.md +120 -0
  7. package/docs/memory-semantics.md +4 -1
  8. package/docs/pending-work.md +51 -0
  9. package/docs/troubleshooting.md +16 -3
  10. package/lib/auto-link/candidates.js +4 -1
  11. package/lib/auto-link/decide.js +1 -1
  12. package/lib/auto-link/normalize.js +2 -2
  13. package/lib/auto-link/terminology.js +31 -1
  14. package/lib/binding-diagnostics.js +1 -1
  15. package/lib/client.js +53 -6
  16. package/lib/consolidation-snapshot.js +37 -1
  17. package/lib/curator.js +1 -1
  18. package/lib/cycle.js +5 -0
  19. package/lib/diagnostics.js +10 -0
  20. package/lib/entity-repair.js +285 -0
  21. package/lib/environment-check.js +72 -3
  22. package/lib/global-graph.js +11 -2
  23. package/lib/graph.js +32 -8
  24. package/lib/host-surface.js +30 -0
  25. package/lib/index.js +116 -1
  26. package/lib/inject.js +428 -32
  27. package/lib/private-links.js +12 -0
  28. package/lib/rpc.js +78 -11
  29. package/lib/state.js +78 -1
  30. package/package.json +16 -1
  31. package/scripts/chain-matrix.mjs +4 -0
  32. package/scripts/check-doc-drift.mjs +194 -0
  33. package/scripts/entity-dedupe.mjs +110 -0
  34. package/tests/auto-link-candidates.test.mjs +22 -9
  35. package/tests/auto-link-decide.test.mjs +59 -59
  36. package/tests/auto-link-migration.test.mjs +4 -4
  37. package/tests/client-render.test.mjs +112 -1
  38. package/tests/cue.test.mjs +2 -1
  39. package/tests/cycle.test.mjs +2 -2
  40. package/tests/diagnostics.test.mjs +21 -0
  41. package/tests/doc-drift.test.mjs +122 -2
  42. package/tests/entity-merge.test.mjs +17 -0
  43. package/tests/environment-check.test.mjs +28 -0
  44. package/tests/global-graph.test.mjs +16 -0
  45. package/tests/global-lifecycle.test.mjs +24 -4
  46. package/tests/graph-cascade.test.mjs +111 -0
  47. package/tests/hybrid-recall.test.mjs +1 -1
  48. package/tests/inject.test.mjs +7 -7
  49. package/tests/injection-chain.test.mjs +40 -2
  50. package/tests/injection-rollback.test.mjs +4 -3
  51. package/tests/managed-memory.test.mjs +7 -7
  52. package/tests/media.test.mjs +4 -1
  53. package/tests/memory-chain.test.mjs +4 -3
  54. package/tests/pending-injection.test.mjs +107 -0
  55. package/tests/private-links.test.mjs +12 -0
  56. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  57. package/tests/settings-plumbing.test.mjs +2 -0
  58. package/tests/tools.test.mjs +1 -1
  59. package/tests/webui-auth.test.mjs +58 -0
@@ -286,7 +286,19 @@ export function suggestPrivateLinks({
286
286
  }
287
287
  }
288
288
  const analyses = new Map()
289
+ // A sliding window must not name an entity while the longer window it lives in
290
+ // groups at least as many memories: `南宫晚` and `宫晚晴` point at exactly the same
291
+ // pair as `南宫晚晴`, and only the 4-char form is a name. `星港` survives because the
292
+ // longer `星港夜班` appears in a single memory.
293
+ const hubGroups = [...groups.values()]
294
+ const subsumed = new Set(hubGroups
295
+ .filter(group => hubGroups.some(other => other !== group
296
+ && other.token.length > group.token.length
297
+ && other.entries.length >= group.entries.length
298
+ && other.token.includes(group.token)))
299
+ .map(group => group.token))
289
300
  for (const [key, group] of groups) {
301
+ if (subsumed.has(group.token)) continue
290
302
  if (group.entries.length < 2) continue
291
303
  if (!group.entries.some(item => wantedSet.has(item.id))) continue
292
304
  const kind = inferEntityKind(group.entries.map(item => item.entry), group.token)
package/lib/rpc.js CHANGED
@@ -12,7 +12,9 @@ import { privateList, privateUpdate, privateRemember, privateRecall, privateArch
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'
15
- import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb } from './curator.js'
15
+ import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb, activationUsesFlatSpec } from './curator.js'
16
+ import { scheduleFlavor } from './salient-wake.js'
17
+ import { hostSurface, noteHostSurface } from './host-surface.js'
16
18
  import { maybeMigrateLibraries } from './migrate.js'
17
19
  import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
18
20
  import { statsView } from './stats.js'
@@ -20,7 +22,7 @@ import { recallCacheStats } from './recall-cache.js'
20
22
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
21
23
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
22
24
  import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAssetResponse, SETTINGS_PATH } from './webui.js'
23
- import { getGraph, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
25
+ import { getGraph, graphDomain, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
24
26
  import { generateAnchorCandidates, resetAnchorCandidatesCache } from './auto-link/candidates.js'
25
27
  import { refreshPrivateAutoLinks } from './private-links.js'
26
28
  import { refreshEntityMentions } from './auto-link/apply.js'
@@ -36,6 +38,34 @@ import { runEnvironmentCheck, repairEnvironment, SAFE_REPAIRS, MANUAL_REPAIRS, R
36
38
  import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
37
39
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
38
40
 
41
+ let rejectionGuardWarned = false
42
+
43
+ function requestRejectionOf(connection, req) {
44
+ try {
45
+ if (typeof connection?.requestRejection === 'function') return connection.requestRejection(req)
46
+ // 0.2.3-alpha.1 起 requestRejection 从 connection 服务上移除,公开面换成
47
+ // `admit(request): { peer } | { rejection }`。上一版这里只试 isTrustedApiRequest,
48
+ // 而它是模块级函数、不挂在服务上,所以两级探测在新宿主上同时落空,守卫静默失效。
49
+ if (typeof connection?.admit === 'function') {
50
+ const admission = connection.admit(req)
51
+ return admission && typeof admission === 'object' && 'rejection' in admission ? admission.rejection : undefined
52
+ }
53
+ if (typeof connection?.isTrustedApiRequest === 'function') {
54
+ return connection.isTrustedApiRequest(req) === true ? undefined : 401
55
+ }
56
+ } catch { return 403 }
57
+ if (!rejectionGuardWarned) {
58
+ rejectionGuardWarned = true
59
+ try {
60
+ warn('dsh-memu-memory: host exposes no request-admission guard on connection (neither requestRejection nor admit); RPC routes stay open and rely on per-library authorization only')
61
+ } catch {}
62
+ }
63
+ // 没有守卫能力时保持原语义(放行):仓库的取舍是「宁可降级并留一行日志,也不 fail
64
+ // closed」。逐条库授权只在宿主实现 authorizeLibrary 时才生效,而它在任何已核对的宿主上
65
+ // 都不存在——所以这一行 warn 是本插件唯一的越权信号,不能省。
66
+ return undefined
67
+ }
68
+
39
69
  const ENDPOINT = '/dsh-memu-memory'
40
70
 
41
71
  function bindingView(binding) {
@@ -129,15 +159,16 @@ function rpcErrorMessage(error) {
129
159
  try { return redactSecrets(raw).slice(0, RPC_ERROR_MAX_CHARS) } catch { return raw.slice(0, RPC_ERROR_MAX_CHARS) }
130
160
  }
131
161
 
132
- // One capability gate for both routes: absent callback falls back to the HTTP
133
- // boundary (requestRejection) and warns once; a present callback is strict true.
134
- // Keeping one helper makes the session-first / capability-second order identical
135
- // in the global queue and the library routes.
162
+ // One capability gate for both routes: an absent callback returns true and warns once —
163
+ // the HTTP boundary (requestRejection / admit) is what actually rejects then. Keeping one
164
+ // helper makes the session-first / capability-second order identical in the global queue
165
+ // and the library routes. No verified host implements authorizeLibrary, so this is a
166
+ // forward-looking hook, not a guard the plugin can count on.
136
167
  async function authorizeWithCapability(connection, req, { libraryId, operation, label }) {
137
168
  if (typeof connection?.authorizeLibrary !== 'function') {
138
169
  if (!capabilityAbsentWarned) {
139
170
  capabilityAbsentWarned = true
140
- try { warn(`dsh-memu-memory: host does not implement connection.authorizeLibrary; ${label} falls back to the HTTP boundary (requestRejection)`) } catch {}
171
+ try { warn(`dsh-memu-memory: host does not implement connection.authorizeLibrary; ${label} relies on the HTTP admission guard alone (requestRejection or admit)`) } catch {}
141
172
  }
142
173
  return true
143
174
  }
@@ -468,6 +499,7 @@ async function privateListView(scope, { limit = null, previewChars = 4000 } = {}
468
499
  libraryId: fileLibraryId,
469
500
  ...(libraryName ? { libraryName } : {}),
470
501
  title: e?.title || '',
502
+ domain: graphDomain(e?.domain) || 'general',
471
503
  layer: e?.layer || 'long_term',
472
504
  status: e?.status || 'active',
473
505
  marginalized: e?.marginalized === true,
@@ -810,6 +842,8 @@ async function dispatch(ctx, endpoint, payload = {}) {
810
842
  globalCount: globalEntries.filter((e) => (e.status || 'active') === 'active').length,
811
843
  jobs: listCurationJobs().slice(-10),
812
844
  recallCache: recallCacheStats(),
845
+ // docs/host-versions.md §13.6:真机核对台账指纹用的旁证,不参与任何判断。
846
+ hostSurface: hostSurface(),
813
847
  }
814
848
  }
815
849
  case 'diagnoseSession': {
@@ -1126,6 +1160,8 @@ async function dispatch(ctx, endpoint, payload = {}) {
1126
1160
  'consolidationTurnLog', 'consolidationTurnLogTools',
1127
1161
  // 整理执行器(T1 §10.2):恢复默认 = 回到 'fork'(现状每窗新 fork)。
1128
1162
  'consolidationRunner',
1163
+ // 升级后的一次性实体碎片自愈:恢复默认 = 开(只合可证明的那一类)。
1164
+ 'autoRepairEntityFragments',
1129
1165
  ]) patch[key] = DEFAULT_SETTINGS[key]
1130
1166
  return redactConsolidationSettings(updateSettings(patch))
1131
1167
  }
@@ -1142,6 +1178,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1142
1178
  'sleepConsolidation', 'sleepAfterIdleMinutes', 'autoCurateEveryHours', 'autoCurateSessionLimit',
1143
1179
  'memoryMode', 'memoryBackend', 'habitsInjection', 'purgeArchivedAfterDays',
1144
1180
  'shortTermTtlHours',
1181
+ // 回合中途补充召回的开关与阈值(lib/inject.js midTurnPolicy):不在名单里
1182
+ // 的 patch 会被静默丢弃,「midTurnRecall: false 可关」必须是可写的。
1183
+ 'midTurnRecall', 'midTurnMinSteps', 'midTurnMinUnits', 'midTurnMinChars',
1184
+ 'midTurnMaxPerTurn', 'midTurnCooldownMs', 'midTurnTokens', 'midTurnFullUnits', 'midTurnFullChars',
1145
1185
  'sidebarSettings', 'visionCaptionEnabled', 'inboundToolNames',
1146
1186
  // 全局提炼的审核模式(spec §6.1):不进 allowlist 的 patch 会被静默丢弃。
1147
1187
  'curatorReviewMode',
@@ -1158,6 +1198,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1158
1198
  'consolidationTurnLog', 'consolidationTurnLogTools',
1159
1199
  // 整理执行器(T1 §10.2):'fork'(默认,现状)/ 'worker'(持久整理 worker)。
1160
1200
  'consolidationRunner',
1201
+ // 升级自愈的可写 kill switch:不在名单里,设置页那句「可关」就是空头承诺
1202
+ // (1.3.15 的 midTurnRecall 教训)。
1203
+ 'autoRepairEntityFragments',
1161
1204
  ])
1162
1205
  const clean = {}
1163
1206
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
@@ -1546,13 +1589,22 @@ async function dispatch(ctx, endpoint, payload = {}) {
1546
1589
  const libraryId = payload?.libraryId ? String(payload.libraryId) : null
1547
1590
  const libraries = libraryId ? [getLibrary(libraryId)] : listLibraries()
1548
1591
  if (libraries.some(library => !library)) throw new Error('library not found')
1592
+ const domainFilter = graphDomain(payload?.domain)
1549
1593
  const items = []
1594
+ const domains = new Set()
1550
1595
  const errors = []
1551
1596
  const collect = (index, lib) => {
1552
1597
  for (const [id, entry] of Object.entries(index.entries || {})) {
1598
+ // An unstamped legacy entry reads as `general` in the private graph and
1599
+ // `unknown` in the global one (graph.js / listGlobal). The wall shows both
1600
+ // scopes side by side, so it keeps that split instead of inventing a third.
1601
+ const domain = graphDomain(entry.domain) || (lib ? 'general' : 'unknown')
1602
+ domains.add(domain)
1603
+ if (domainFilter && domain !== domainFilter) continue
1553
1604
  items.push({
1554
1605
  id, title: entry.title || '', preview: String(entry.content || '').slice(0, 180),
1555
1606
  libraryId: lib?.id || null, libraryName: lib?.name || 'global',
1607
+ domain,
1556
1608
  layer: entry.layer || 'long_term', status: entry.status || 'active',
1557
1609
  source: entry.source || 'inferred', confidence: entry.confidence ?? null,
1558
1610
  accuracy: entry.accuracy ?? null, createdAt: entry.createdAt || null, updatedAt: entry.updatedAt || null,
@@ -1587,7 +1639,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1587
1639
  try { collect(loadGlobalIndex(), null) } catch { errors.push({ libraryId: null, error: 'global index unavailable' }) }
1588
1640
  items.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')))
1589
1641
  const limit = Math.max(1, Math.min(1000, Number(payload?.limit) || 300))
1590
- return { items: items.slice(0, limit), total: items.length, libraries, errors }
1642
+ return { items: items.slice(0, limit), total: items.length, domains: [...domains].sort(), libraries, errors }
1591
1643
  }
1592
1644
  case 'getGraph':
1593
1645
  // Reuse the private graph endpoint instead of adding a second read method:
@@ -2246,21 +2298,36 @@ async function dispatch(ctx, endpoint, payload = {}) {
2246
2298
  export function registerRpc(ctx) {
2247
2299
  try {
2248
2300
  ctx.inject(['connection', 'webServer'], (c) => {
2301
+ // §13.6 结构指纹:把这次装载实际命中的宿主形状记一行,供真机核对台账
2302
+ // (docs/host-versions.md §13.1)。全部来自既有探测,不做判断、不比版本号。
2303
+ try {
2304
+ noteHostSurface('rpcGuard', typeof c.connection?.requestRejection === 'function' ? 'requestRejection'
2305
+ : typeof c.connection?.admit === 'function' ? 'admit'
2306
+ : typeof c.connection?.isTrustedApiRequest === 'function' ? 'isTrustedApiRequest' : 'none')
2307
+ noteHostSurface('schedule', scheduleFlavor(typeof ctx.get === 'function' ? ctx.get('schedule') : null) || 'none')
2308
+ const subagents = typeof ctx.get === 'function' ? ctx.get('subagents') : null
2309
+ noteHostSurface('activation', subagents?.startActivation ? (activationUsesFlatSpec(subagents) ? 'flat' : 'nested') : 'none')
2310
+ } catch { /* 指纹只是旁证,探测失败不得影响装载 */ }
2249
2311
  c.effect(
2250
2312
  () => {
2251
2313
  const route = {
2252
2314
  kind: 'prefix',
2253
2315
  path: ENDPOINT,
2254
2316
  handler: async (req, res) => {
2317
+ // 入口守卫的能力探测(不写版本比较):
2318
+ // 1) 0.2.x:`connection.requestRejection(req)`;
2319
+ // 2) 更早的 rc.8 / 0.1.1:只有 `connection.isTrustedApiRequest(req)`;
2320
+ // 3) 0.2.3-alpha.2:两者都不在 connection 服务上(源码核对:只剩模块级
2321
+ // `isTrustedApiRequest(request, trustedHosts, bindHost, protocol)`)。
2322
+ // 第 3 种没有可用守卫:保持放行(仓库取舍:不 fail closed),但 warn 一次,
2323
+ // 免得「守卫在宿主升级后消失」这件事没人发现。
2255
2324
  // Capability probe, not a version check: `requestRejection` exists on
2256
2325
  // 0.1.2-rc.x and later of dsh-client-connection and not at all on the rc.8
2257
2326
  // / 0.1.1-rc.2 copies, where the service only exposes
2258
2327
  // `isTrustedApiRequest`. Calling it blindly threw a TypeError out of the
2259
2328
  // request handler, which the host turns into a 500 — an unauthenticated
2260
2329
  // caller then learned the route exists instead of being refused.
2261
- const rejection = typeof c.connection?.requestRejection === 'function'
2262
- ? c.connection.requestRejection(req)
2263
- : undefined
2330
+ const rejection = requestRejectionOf(c.connection, req)
2264
2331
  if (rejection !== undefined) {
2265
2332
  const status = rejection === 401 ? 401 : 403
2266
2333
  res.writeHead(status)
package/lib/state.js CHANGED
@@ -165,6 +165,22 @@ export const DEFAULT_SETTINGS = {
165
165
  consolidationTurnLogTools: 'none',
166
166
  // A positive age marks cleanup candidates; deletion always needs a user action.
167
167
  purgeArchivedAfterDays: 0,
168
+ // 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
169
+ // 可证明的那一类(窗口片段重建出正文里出现过的完整名);"只是相似"的候选永远等人工确认。
170
+ // 关掉它 = 连可证明的也不动,全部留在诊断页的手动按钮上。写入前一律先备份。
171
+ autoRepairEntityFragments: true,
172
+ // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
173
+ // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
174
+ // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
175
+ midTurnRecall: true,
176
+ midTurnMinSteps: 4,
177
+ midTurnMinUnits: 3,
178
+ midTurnMinChars: 6000,
179
+ midTurnMaxPerTurn: 2,
180
+ midTurnCooldownMs: 60000,
181
+ midTurnTokens: 400,
182
+ midTurnFullUnits: 6,
183
+ midTurnFullChars: 15000,
168
184
  }
169
185
 
170
186
  function defaultState() {
@@ -421,6 +437,9 @@ export function updateSettings(patch) {
421
437
  autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
422
438
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
423
439
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
440
+ midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
441
+ midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
442
+ midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
424
443
  }
425
444
  const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
426
445
  for (const [key, value] of Object.entries(patch || {})) {
@@ -672,7 +691,7 @@ export function deleteLibrary(id, { force = false } = {}) {
672
691
  if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
673
692
  // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
674
693
  // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
675
- // 冷数据的旧归档同理放行,否则本机 rp / ai中转站 这类库会变成"永远删不掉"。
694
+ // 冷数据的旧归档同理放行,否则本机 rp / 另一个工作区库 这类库会变成"永远删不掉"。
676
695
  if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
677
696
  return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
678
697
  }
@@ -1076,6 +1095,64 @@ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
1076
1095
  return committed ? structuredClone(committed) : null
1077
1096
  }
1078
1097
 
1098
+ /**
1099
+ * 待接纳提案的**落盘**副本(2026-11-23)。
1100
+ *
1101
+ * `injectionAdmissions` 是进程内 Map:宿主重启、或同一个 home 被另一个进程观察时,
1102
+ * 提案会凭空消失,于是接纳永远不会发生——qq-dm 会话 333 个回合里
1103
+ * `acceptedMemoryMessages` 一次都没出现过,就是这么来的(同库的 qq-group 正常)。
1104
+ * 这里只存最小的提交凭据(按消息内容 digest 匹配),观察端换进程也能补完接纳。
1105
+ * 只保留最近 8 条:同一消息重投会被 digest 覆盖,过期条目自然被挤掉。
1106
+ */
1107
+ const PENDING_INJECTION_MAX = 8
1108
+ // 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
1109
+ // 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
1110
+ // 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
1111
+ const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
1112
+
1113
+ function pendingInjectionFresh(item, now = Date.now()) {
1114
+ const at = Date.parse(item?.at || '')
1115
+ return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
1116
+ }
1117
+
1118
+ export function rememberPendingInjection(sessionId, record = {}) {
1119
+ if (!sessionId || !record.digest || !record.messageId) return null
1120
+ return updateState((state) => {
1121
+ const binding = state.sessions[sessionId]
1122
+ if (!binding) return state
1123
+ const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
1124
+ kept.push({
1125
+ digest: String(record.digest), messageId: String(record.messageId),
1126
+ turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
1127
+ generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
1128
+ refs: Array.isArray(record.refs) ? record.refs : [],
1129
+ actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
1130
+ at: stamp(),
1131
+ })
1132
+ binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
1133
+ return state
1134
+ })
1135
+ }
1136
+
1137
+ export function findPendingInjection(sessionId, digest) {
1138
+ if (!sessionId || !digest) return null
1139
+ const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
1140
+ .filter(item => item?.digest === digest && pendingInjectionFresh(item))
1141
+ return rows[rows.length - 1] || null
1142
+ }
1143
+
1144
+ export function forgetPendingInjection(sessionId, messageId) {
1145
+ if (!sessionId || !messageId) return null
1146
+ return updateState((state) => {
1147
+ const binding = state.sessions[sessionId]
1148
+ if (!binding?.pendingInjections) return state
1149
+ const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
1150
+ if (kept.length) binding.pendingInjections = kept
1151
+ else delete binding.pendingInjections
1152
+ return state
1153
+ })
1154
+ }
1155
+
1079
1156
  export function markInjected(sessionId, ids, turn) {
1080
1157
  if (!sessionId) return
1081
1158
  return updateState((state) => {
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.3.14",
4
+ "version": "1.4.0",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -71,6 +71,21 @@
71
71
  "dsh": ">=0.2.0-rc.1"
72
72
  },
73
73
  "dsh": {
74
+ "compatibility": {
75
+ "dshReleases": [
76
+ "0.2.0-rc.1",
77
+ "0.2.1-rc.3",
78
+ "0.2.1-rc.5",
79
+ "0.2.2-alpha.3",
80
+ "0.2.2-rc.1",
81
+ "0.2.2-rc.2",
82
+ "0.2.2-rc.3",
83
+ "0.2.2-rc.4",
84
+ "0.2.2-rc.5",
85
+ "0.2.3-alpha.1",
86
+ "0.2.3-alpha.2"
87
+ ]
88
+ },
74
89
  "bundle": {
75
90
  "patch": "./cordis.patch.yml"
76
91
  },
@@ -88,6 +88,10 @@ const engineSource = [
88
88
  'export const retrieve = (...a) => b.retrieve(...a);',
89
89
  'export const forget = (...a) => b.forget(...a);',
90
90
  'export const listFiles = (...a) => b.listFiles(...a);',
91
+ // lib/rpc.js imports the resident-engine hooks from the same module: without
92
+ // these two exports the whole matrix dies at import time (1.3.15 regression).
93
+ 'export const closeMemuResident = () => 0;',
94
+ 'export const prewarmMemuResident = async () => false;',
91
95
  ].join(' ')
92
96
  const engineUrl = 'data:text/javascript,' + encodeURIComponent(engineSource)
93
97
  const hooks = registerHooks({
@@ -288,11 +288,205 @@ export function checkLoaderStubs(root) {
288
288
  return outcome(label, 'ok', REQUIRED_FILES.length + ' required loader/stub file(s) present; ' + testCount + ' *.test.mjs file(s)', [])
289
289
  }
290
290
 
291
+ // Gate 4 — the cross-version host ledger (docs/host-versions.md §13).
292
+ //
293
+ // Why this exists: per-build host facts used to live in three places at once
294
+ // (host-adaptation §2 column, §5 record, §7 table). §7 stopped at 0.2.2-rc.1 and §2
295
+ // still claimed `connection.requestRejection` was "未变" after the host removed it in
296
+ // 0.2.3-alpha.1. The ledger is now the single owner, and this gate is what keeps it
297
+ // from rotting the same way: a build named anywhere in the docs must have a ledger row,
298
+ // every row must state how it was verified, and every probe site it points at must still
299
+ // exist in lib/.
300
+ const HOST_DOC = 'docs/host-versions.md'
301
+ const HOST_BUILD_RE = /\b0\.2\.\d+-(?:rc|alpha|beta)\.\d+\b/g
302
+ const LEDGER_ROW_RE = /^\|\s*`(0\.2\.\d+(?:-(?:rc|alpha|beta)\.\d+)?)`\s*\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|/
303
+ const SURFACE_ROW_RE = /^\|\s*`([a-z][A-Za-z0-9]*)`\s*\|(.*)$/
304
+ const PROBE_SITE_RE = /(lib\/[\w./-]+\.js):([A-Za-z_$][\w$]*)/g
305
+ const LEDGER_VERDICTS = new Set(['真机', '源码', '未测'])
306
+ const LEDGER_GRADES = new Set(['exact', 'line', 'nearest'])
307
+
308
+ // Fenced code blocks are examples, not claims about the docs.
309
+ const stripFences = (text) => String(text || '').replace(/```[\s\S]*?```/g, '')
310
+
311
+ // Comment-free view of a JS file. Line-based on purpose: a character scanner has to
312
+ // know regex literals well enough not to mistake `/x/ // note` for a string, and a
313
+ // wrong guess makes this gate permanently red — which is worse than its blind spot
314
+ // (a version literal tucked into a trailing comment). Documentation lines are the
315
+ // place host versions legitimately get named, so those are what this exempts.
316
+ function stripJsComments(source) {
317
+ return String(source || '').split(/\r?\n/)
318
+ .map((line) => (/^[ \t]*(\/\/|\/?\*|\/\*)/.test(line) ? '' : line))
319
+ .join('\n')
320
+ }
321
+
322
+ function libSources(root) {
323
+ const out = []
324
+ const walk = (dir, rel) => {
325
+ let entries = []
326
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
327
+ for (const entry of entries) {
328
+ const abs = path.join(dir, entry.name)
329
+ const nextRel = rel ? rel + '/' + entry.name : entry.name
330
+ if (entry.isDirectory()) walk(abs, nextRel)
331
+ else if (entry.isFile() && entry.name.endsWith('.js')) out.push({ rel: 'lib/' + nextRel, abs })
332
+ }
333
+ }
334
+ walk(path.join(root, 'lib'), '')
335
+ return out
336
+ }
337
+
338
+ // Markdown table cells are usually written inline-code styled; unwrap them before
339
+ // comparing against the grammar the gate enforces.
340
+ const ledgerCell = (value) => String(value || '').replace(/`/g, '').trim()
341
+
342
+ function checkHostVersionRows(lines) {
343
+ const rows = []
344
+ for (const line of lines) {
345
+ const match = LEDGER_ROW_RE.exec(line)
346
+ if (!match) continue
347
+ rows.push({
348
+ build: match[1],
349
+ commit: ledgerCell(match[2]),
350
+ verdict: ledgerCell(match[3]),
351
+ grade: ledgerCell(match[4]),
352
+ date: ledgerCell(match[5]),
353
+ fingerprint: ledgerCell(match[6]),
354
+ })
355
+ }
356
+ return rows
357
+ }
358
+
359
+ export function checkHostVersions(root = DEFAULT_ROOT) {
360
+ const label = 'host-versions'
361
+ let text = ''
362
+ try {
363
+ text = fs.readFileSync(path.join(root, HOST_DOC), 'utf8')
364
+ } catch (error) {
365
+ if (!fs.existsSync(path.join(root, 'docs'))) {
366
+ return outcome(label, 'skipped', 'no docs/ directory - skipped, not applicable (npm package install)', [])
367
+ }
368
+ return outcome(label, 'fail', HOST_DOC + ' is missing or unreadable', [
369
+ firstLine(error.message),
370
+ 'the per-build ledger owns every host-version fact (docs/host-adaptation.md §7 points here)',
371
+ ])
372
+ }
373
+
374
+ const problems = []
375
+ const lines = text.split(/\r?\n/)
376
+
377
+ // 4b — ledger rows carry commit / verdict / grade / date.
378
+ const rows = checkHostVersionRows(lines)
379
+ if (rows.length === 0) {
380
+ problems.push('§13.1 has no ledger rows (expected one `| `0.2.x-rc.y` | commit | 核对方式 | 判定 | 日期 | 指纹 | … |` row per build)')
381
+ }
382
+ for (const row of rows) {
383
+ if (!/^[0-9a-f]{7,12}$/.test(row.commit)) {
384
+ problems.push(`§13.1 ${row.build}: commit "${row.commit}" is not a short sha (use git rev-parse --short <tag>^{commit})`)
385
+ }
386
+ if (!LEDGER_VERDICTS.has(row.verdict)) problems.push(`§13.1 ${row.build}: 核对方式 "${row.verdict}" must be one of 真机 / 源码 / 未测`)
387
+ if (!LEDGER_GRADES.has(row.grade)) problems.push(`§13.1 ${row.build}: 判定 "${row.grade}" must be one of exact / line / nearest`)
388
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(row.date)) problems.push(`§13.1 ${row.build}: date "${row.date}" must be ISO YYYY-MM-DD`)
389
+ }
390
+
391
+ // 4c + 4e — registered surfaces and their probe sites.
392
+ const surfaces = new Map()
393
+ for (const line of lines) {
394
+ const match = SURFACE_ROW_RE.exec(line)
395
+ if (!match) continue
396
+ const sites = [...String(match[2]).matchAll(PROBE_SITE_RE)].map((site) => ({ file: site[1], symbol: site[2] }))
397
+ if (sites.length === 0) {
398
+ problems.push(`§13.2 ${match[1]}: no probe site written as lib/<file>.js:<symbol>`)
399
+ continue
400
+ }
401
+ surfaces.set(match[1], sites)
402
+ }
403
+ if (surfaces.size === 0) problems.push('§13.2 has no surface rows (expected `| \\`面ID\\` | … |`)')
404
+ for (const [slug, sites] of surfaces) {
405
+ for (const site of sites) {
406
+ let source = ''
407
+ try {
408
+ source = fs.readFileSync(path.join(root, site.file), 'utf8')
409
+ } catch {
410
+ problems.push(`§13.2 ${slug}: ${site.file} does not exist (renamed? update the ledger in the same commit)`)
411
+ continue
412
+ }
413
+ if (!new RegExp(`\\b${site.symbol.replace(/\$/g, '\\$')}\\b`).test(source)) {
414
+ problems.push(`§13.2 ${slug}: symbol ${site.symbol} not found in ${site.file} (renamed? update the ledger in the same commit)`)
415
+ }
416
+ }
417
+ }
418
+ for (const row of rows) {
419
+ const pairs = String(row.fingerprint || '').split(';').map((part) => part.trim()).filter(Boolean)
420
+ if (pairs.length < 3) problems.push(`§13.1 ${row.build}: fingerprint "${row.fingerprint}" must list at least 3 key=value pairs`)
421
+ for (const pair of pairs) {
422
+ const key = pair.split('=')[0].trim()
423
+ if (!pair.includes('=') || !surfaces.has(key)) problems.push(`§13.1 ${row.build}: fingerprint key "${key}" is not a surface registered in §13.2`)
424
+ }
425
+ }
426
+
427
+ // 4a — every host build named anywhere in the docs needs a ledger row.
428
+ const documented = new Map()
429
+ for (const rel of docFiles(root)) {
430
+ if (rel === HOST_DOC) continue
431
+ let body = ''
432
+ try {
433
+ body = stripFences(fs.readFileSync(path.join(root, rel), 'utf8'))
434
+ } catch {
435
+ continue
436
+ }
437
+ for (const match of body.matchAll(HOST_BUILD_RE)) {
438
+ if (!documented.has(match[0])) documented.set(match[0], rel)
439
+ }
440
+ }
441
+ const ledger = new Set(rows.map((row) => row.build))
442
+ for (const [build, rel] of documented) {
443
+ if (!ledger.has(build)) problems.push(`${rel} mentions ${build} but §13.1 has no row for it (newest row: ${[...ledger].sort().pop() || 'none'})`)
444
+ }
445
+
446
+ // 4d — no host version literals in running code (AGENTS.md 硬规则 1).
447
+ for (const { rel, abs } of libSources(root)) {
448
+ let source = ''
449
+ try {
450
+ source = fs.readFileSync(abs, 'utf8')
451
+ } catch {
452
+ continue
453
+ }
454
+ // DSH builds always carry a prerelease tag (`0.2.3-alpha.1`); a bare `0.2.0` in
455
+ // this repo is some other artifact (the tokenizers crate), and flagging it would
456
+ // make the gate permanently red.
457
+ const code = stripJsComments(source)
458
+ const hit = /\b0\.2\.\d+-(?:rc|alpha|beta)\.\d+\b/.exec(code)
459
+ if (hit) problems.push(`${rel}: host version "${hit[0]}" sits in running code — probe the shape instead (AGENTS.md 硬规则 1)`)
460
+ }
461
+
462
+ // 4f — package.json dshReleases must agree with the verified rows.
463
+ let manifest = null
464
+ try {
465
+ manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
466
+ } catch {
467
+ manifest = null
468
+ }
469
+ const declared = manifest?.dsh?.compatibility?.dshReleases
470
+ if (Array.isArray(declared)) {
471
+ const expected = rows.filter((row) => row.grade === 'exact' || row.grade === 'line').map((row) => row.build).sort()
472
+ const got = [...declared].map((value) => String(value)).sort()
473
+ if (expected.join('|') !== got.join('|')) {
474
+ problems.push('package.json dsh.compatibility.dshReleases disagrees with §13.1: declared ' + (got.join(', ') || '(none)')
475
+ + ' vs ledger ' + (expected.join(', ') || '(none)'))
476
+ }
477
+ }
478
+
479
+ if (problems.length > 0) return outcome(label, 'fail', 'host ledger drift: ' + problems.length + ' problem(s)', problems)
480
+ return outcome(label, 'ok', rows.length + ' verified build(s), ' + surfaces.size
481
+ + ' registered host surface(s), no undocumented build reference', [])
482
+ }
483
+
291
484
  export function runChecks(root = DEFAULT_ROOT) {
292
485
  const checks = [
293
486
  ['rpc-method-count', checkRpcMethodCount],
294
487
  ['test-tracking', checkTestTracking],
295
488
  ['loader-stubs', checkLoaderStubs],
489
+ ['host-versions', checkHostVersions],
296
490
  ]
297
491
  return checks.map(([label, run]) => {
298
492
  try {