dsh-memu-memory 1.3.10 → 1.3.12

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/memory.js CHANGED
@@ -305,8 +305,12 @@ async function withManagedGlobalWrite(action) {
305
305
  return withVectorWrite(() => { assertVectorWriteAllowed(); return action() })
306
306
  }
307
307
 
308
- async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
309
- const local = localRecall(index, query, undefined, { cacheKey: libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`, topK })
308
+ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null, disclosureAsked = false, speakerFilter = null }) {
309
+ // Private lexical statistics must use the same eligible corpus as final fusion.
310
+ // Exact-id reads and the global domain-scoped route keep their existing contract.
311
+ const gate = { automatic, sessionId: memorySessionId(exec), disclosureAsked, speakerFilter }
312
+ const filter = libraryId && !byId ? (file) => crossLibraryEligible(file.entry, gate) : undefined
313
+ const local = localRecall(index, query, filter, { cacheKey: libraryId ? `lib:${libraryId}:${gateCacheSuffix(gate)}` : `global:${domain || 'all'}`, topK })
310
314
  try {
311
315
  if (intent.error) throw intent.error
312
316
  const captured = intent.route === 'managed-local' ? captureGeneration() : null
@@ -355,8 +359,8 @@ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId,
355
359
  if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
356
360
  if (captured) assertGeneration(captured)
357
361
  const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
358
- limit: hybridCandidateLimit(topK), automatic, disclosureAsked: detectQueryIntent(query) === 'boundary',
359
- speakerFilter: detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
362
+ limit: hybridCandidateLimit(topK), automatic, disclosureAsked: libraryId ? disclosureAsked : detectQueryIntent(query) === 'boundary',
363
+ speakerFilter: libraryId ? speakerFilter : detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
360
364
  return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug, vectorGeneration: captured?.token ?? null }
361
365
  })
362
366
  clearRecallError(exec)
@@ -2593,6 +2597,11 @@ function crossLibraryEligible(entry, { automatic, sessionId, disclosureAsked, sp
2593
2597
  && speakerMatchesFilter(entry, speakerFilter)
2594
2598
  }
2595
2599
 
2600
+ // 资格标志进缓存 key:自动/显式的授权语料不同,共用 key 会让交替召回每次指纹失配重建。
2601
+ function gateCacheSuffix({ automatic, disclosureAsked, speakerFilter }) {
2602
+ return `${automatic ? 'auto' : 'explicit'}:${disclosureAsked ? 'asked' : 'plain'}${speakerFilter ? `:${speakerFilter}` : ''}`
2603
+ }
2604
+
2596
2605
  // R4:跨库统一词法评分。文档身份是复合 [libraryId,id] key,两库同 id 是两份
2597
2606
  // 文档而不是同一份;语料指纹含复合 id,任一成员库内容变化都会失效共享语料。
2598
2607
  // 评分规则与 localRecall 的 BM25 分支一致(日期加成、证据分离、date-only 末位),
@@ -2662,7 +2671,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
2662
2671
  }
2663
2672
  const managed = await managedRecall({
2664
2673
  exec, index: scoped, sourceEmpty: Object.keys(source.index.entries || {}).length === 0,
2665
- query, topK, libraryId: source.libraryId, automatic, intent, retrieveImpl, byId, domain,
2674
+ query, topK, libraryId: source.libraryId, automatic, intent, retrieveImpl, byId, domain, disclosureAsked, speakerFilter,
2666
2675
  })
2667
2676
  lists.push({
2668
2677
  libraryId: source.libraryId,
@@ -2689,7 +2698,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
2689
2698
  return { ...base, files, fusion: { crossLibraryLexical: 'exact-id' } }
2690
2699
  }
2691
2700
  if (route === 'lexical') {
2692
- const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${automatic ? 'auto' : 'explicit'}:${disclosureAsked ? 'asked' : 'plain'}`
2701
+ const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${gateCacheSuffix(gate)}`
2693
2702
  const unified = crossLibraryLexical(lists.flatMap((list) => list.files), query, { cacheKey, topK })
2694
2703
  if (unified.mode === 'recency') {
2695
2704
  return { ...base, files: unified.files, fusion: { crossLibraryLexical: 'recency' } }
@@ -2880,14 +2889,17 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2880
2889
  if (excludedCount) candidateK = Math.min(HYBRID_CANDIDATE_MAX, candidateK + excludedCount)
2881
2890
  }
2882
2891
  const generationAtStart = scopeGenerationOf(binding)
2883
- // Single source keeps the old path byte-for-byte; the cross-library merge only
2892
+ // Single-source lexical scoring uses the same eligibility gate as the cross-library corpus.
2893
+ const gate = { automatic: purpose === 'automatic', sessionId: memorySessionId(exec),
2894
+ disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) }
2895
+ // The cross-library merge only
2884
2896
  // exists when another qualifying library is actually present.
2885
2897
  const retrievalStarted = performance.now()
2886
2898
  const result = sources.length === 1
2887
2899
  ? (route === 'lexical' || byId
2888
- ? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK: candidateK }), recallRoute: 'local' }
2900
+ ? { ...localRecall(sources[0].index, searchQuery, byId ? undefined : (file) => crossLibraryEligible(file.entry, gate), { cacheKey: `lib:${sources[0].libraryId}:${gateCacheSuffix(gate)}`, topK: candidateK }), recallRoute: 'local' }
2889
2901
  : await managedRecall({ exec, index: sources[0].index, sourceEmpty: Object.keys(sources[0].index.entries || {}).length === 0,
2890
- query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2902
+ query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, ...gate, intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2891
2903
  : await recallCrossLibrary({ exec, sources, query: searchQuery, topK: candidateK, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain,
2892
2904
  disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) })
2893
2905
  const retrievalMs = performance.now() - retrievalStarted
@@ -4579,6 +4591,87 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
4579
4591
  return touched
4580
4592
  }
4581
4593
 
4594
+ // 全局生命周期是用户管理面动作(与 resolveReview 的全局元数据动作同鉴权口径),
4595
+ // 不是 curator 的内容写入:只改 status。召回/锚点/注入都过 isMemoryEligible,
4596
+ // archived 立即自动排除,向量行无需改动(与 privateArchive 同口径)。
4597
+ export async function globalSetStatus({ id, status }) {
4598
+ const target = String(id || '').trim()
4599
+ if (!target) throw new Error('memory id is required')
4600
+ if (!['active', 'archived'].includes(status)) throw new Error('global lifecycle only supports active and archived')
4601
+ let result = null
4602
+ let changed = false
4603
+ await retryStoreWrite(() => updateGlobalIndex((index) => {
4604
+ const entry = index.entries[target]
4605
+ if (!entry) throw new Error(`unknown global memory: ${target}`)
4606
+ if (status === 'archived') {
4607
+ if (entry.status === 'pending_review') throw new Error('a pending global memory must be resolved in the review queue first')
4608
+ if (entry.status === 'archived') { result = { id: target, entry }; return }
4609
+ } else if (entry.status !== 'archived') {
4610
+ throw new Error('only archived global memories can be restored')
4611
+ }
4612
+ entry.status = status
4613
+ entry.updatedAt = stamp()
4614
+ changed = true
4615
+ result = { id: target, entry }
4616
+ }))
4617
+ if (changed) {
4618
+ record({
4619
+ kind: 'write', scope: 'global', libraryId: null,
4620
+ message: status === 'archived' ? '全局记忆归档(管理面)' : '全局记忆恢复(管理面)',
4621
+ detail: { id: target, status }, refs: [target],
4622
+ })
4623
+ }
4624
+ return result
4625
+ }
4626
+
4627
+ /**
4628
+ * 全局永久删除,与 privateDeleteImpl 同序:先删引擎/向量行(引擎拒绝则索引不动),
4629
+ * 再在单事务里删行并级联清掉他条指向它的 links 与指针字段。合并稿与活跃合并的
4630
+ * 来源拒删——absorbSnapshot 是撤销合并的唯一依据,删掉成员会让撤销悬空。
4631
+ * 安全网是 RPC 层的两段确认 + backupDatabases,与私有单条删除一致。
4632
+ */
4633
+ export async function globalDelete({ id }) {
4634
+ const target = String(id || '').trim()
4635
+ if (!target) throw new Error('memory id is required')
4636
+ const index = loadGlobalIndex()
4637
+ const entry = index.entries[target]
4638
+ if (!entry) throw new Error(`unknown global memory: ${target}`)
4639
+ if (!['archived', 'suppressed', 'expired'].includes(entry.status)) {
4640
+ throw new Error('only archived memories can be deleted permanently; archive it first')
4641
+ }
4642
+ if (Array.isArray(entry.absorbedFrom) && entry.absorbedFrom.length) {
4643
+ throw new Error('this merged memory still carries its absorb snapshot; undo the merge first')
4644
+ }
4645
+ const merged = Object.entries(index.entries).find(([otherId, other]) => otherId !== target
4646
+ && other?.status === 'active' && Array.isArray(other.absorbedFrom) && other.absorbedFrom.includes(target))
4647
+ if (merged) throw new Error(`this memory is a source of merged memory ${merged[0]}; undo the merge first`)
4648
+ const backend = engineRoute()
4649
+ let engine = null
4650
+ if (backend !== 'lexical') {
4651
+ engine = await forget({ route: backend, db: globalDbPath(), name: target })
4652
+ }
4653
+ await retryStoreWrite(() => updateGlobalIndex((fresh) => {
4654
+ if (JSON.stringify(fresh.entries[target]) !== JSON.stringify(entry)) throw new Error('memory changed during deletion; reload and retry')
4655
+ delete fresh.entries[target]
4656
+ for (const other of Object.values(fresh.entries)) {
4657
+ if (Array.isArray(other.links) && other.links.some(link => link?.to === target)) {
4658
+ other.links = other.links.filter(link => link?.to !== target)
4659
+ }
4660
+ if (other.duplicateOf === target) delete other.duplicateOf
4661
+ if (other.relatedTo === target) delete other.relatedTo
4662
+ if (other.conflictingWith === target) delete other.conflictingWith
4663
+ if (other.supersededBy === target) delete other.supersededBy
4664
+ if (other.absorbedBy === target) delete other.absorbedBy
4665
+ }
4666
+ }))
4667
+ record({
4668
+ kind: 'write', scope: 'global', libraryId: null,
4669
+ message: '全局记忆永久删除(管理面)',
4670
+ detail: { id: target, backend }, refs: [target],
4671
+ })
4672
+ return { id: target, libraryId: null, deleted: true, backend, engine }
4673
+ }
4674
+
4582
4675
  // Local calendar day (not UTC): "today" for a reminder is the user's today, the same
4583
4676
  // unit `salientDaysAhead` measures in.
4584
4677
  function localDateKey(date) {
package/lib/private.js CHANGED
@@ -567,34 +567,48 @@ export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
567
567
  return rows.slice(0, Math.max(1, Number(max) || 8))
568
568
  }
569
569
 
570
- const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*[月日号]/
571
- // 这些 bigram 到处出现,不能证明候选被写进库;命中两个以上才算覆盖。
570
+ const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*月\s*\d{1,2}\s*[日号]?|\d{1,2}\s*[月日号]/g
572
571
  const COVER_STOP = new Set([
573
572
  '我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
574
573
  '时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
575
574
  ])
575
+ const COVER_TOKEN_RECALL = 0.55
576
+ function coverText(text) {
577
+ return String(text || '').normalize('NFKC').toLowerCase().replace(COVER_DATE_RE, ' ')
578
+ }
576
579
  function coverTokens(text) {
577
- return new Set(tokenize(String(text || ''))
578
- .filter((token) => typeof token === 'string' && token.length >= 2 && !COVER_STOP.has(token)))
580
+ return new Set(tokenize(text)
581
+ .filter((token) => typeof token === 'string' && token.length >= 2 && !/\d/.test(token) && !COVER_STOP.has(token)))
582
+ }
583
+ function coverAtoms(text) {
584
+ return new Set(text.match(/[\p{Script=Han}]|[a-z]+/gu) || [])
579
585
  }
580
- /** 本地零 Token 核验:候选里的关键事实是否真的出现在本窗新增/更新的条目里。 */
586
+ /** Conservative local evidence check; uncertainty keeps the candidate in carry. */
581
587
  export function candidateCovered(candidate, writtenIds, index) {
582
588
  const entries = index?.entries || {}
583
589
  const text = String(candidate?.text || '')
584
590
  if (!text) return true
585
- const date = (text.match(COVER_DATE_RE) || [])[0] || null
586
- const wanted = coverTokens(text)
587
- if (wanted.size === 0 && !date) return true
591
+ const normalized = coverText(text)
592
+ const wanted = coverTokens(normalized)
593
+ const atoms = coverAtoms(normalized)
594
+ const values = numericSet(text)
595
+ // A date or an uninformative fragment cannot prove a fact was written.
596
+ if (wanted.size < 2 || atoms.size === 0) return false
588
597
  for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
589
598
  const entry = entries[id]
590
599
  if (!entry) continue
591
600
  const body = String(entry.title || '') + ' ' + String(entry.content || '')
592
- if (date && body.includes(date)) return true
593
- const have = coverTokens(body)
594
- let shared = 0
595
- for (const token of wanted) {
596
- if (have.has(token) && (shared += 1) >= 2) return true
597
- }
601
+ const haveValues = numericSet(body)
602
+ if ([...values].some((value) => !haveValues.has(value))) continue
603
+ const normalizedBody = coverText(body)
604
+ const haveAtoms = coverAtoms(normalizedBody)
605
+ // Missing names, actions or objects are not covered by a matching topic/date.
606
+ if ([...atoms].some((atom) => !haveAtoms.has(atom))) continue
607
+ const have = coverTokens(normalizedBody)
608
+ const shared = [...wanted].filter((token) => have.has(token))
609
+ if (shared.length < Math.min(3, wanted.size) || shared.length / wanted.size < COVER_TOKEN_RECALL) continue
610
+ if (shared.some((token) => polarityAt(text, token) !== polarityAt(body, token))) continue
611
+ return true
598
612
  }
599
613
  return false
600
614
  }
@@ -1037,7 +1051,7 @@ import {
1037
1051
  recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
1038
1052
  resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
1039
1053
  } from './worker-pool.js'
1040
- import { tokenize, buildCorpus, bm25 } from './text-retrieval.js'
1054
+ import { tokenize, buildCorpus, bm25, numericSet, polarityAt } from './text-retrieval.js'
1041
1055
  import { isGoneSessionError } from './cycle.js'
1042
1056
  import { autoLinkPrivateMemories } from './private-links.js'
1043
1057
  import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
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, previewDelete, restoreDeleted, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, recordImportBatch, revertImportBatch, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
11
+ import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, previewDelete, restoreDeleted, globalList, globalRecall, globalSetStatus, globalDelete, 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'
@@ -73,7 +73,10 @@ function requireSessionId(payload) {
73
73
  // entry's dispatch consumes `payload.libraryId` — or, for updateMemory and
74
74
  // archiveMemory, falls back to the same persisted session binding that
75
75
  // `routeLibraryId` resolves — so the target authorized here is exactly the
76
- // target dispatch works on. Endpoints that are session- or host-scoped
76
+ // target dispatch works on. updateMemory/archiveMemory/deleteMemory are
77
+ // additionally dual-scope: an explicit `scope:'global'` addresses the global
78
+ // store and is authorized by authorizeGlobalReviewRoute, never as a library.
79
+ // Endpoints that are session- or host-scoped
77
80
  // (getState, getSidebarState, initSession, setLibrary, setFolderPolicy, engine
78
81
  // and settings management, …) are not library-addressed: their credential is
79
82
  // the host's own requestRejection plus, for session-scoped reads, the session
@@ -172,6 +175,13 @@ async function authorizeGlobalLexiconRoute(connection, req, endpoint, payload) {
172
175
  }
173
176
 
174
177
  async function authorizeLibraryRoute(connection, req, endpoint, payload, libraryId = routeLibraryId(endpoint, payload)) {
178
+ // Global lifecycle (archive/restore/delete via scope:'global') is management-plane
179
+ // like the global review queue, never a private-library target: it follows the
180
+ // same credential model, and naming a library alongside it is a scope conflict.
181
+ if (payload?.scope === 'global' && ['archiveMemory', 'updateMemory', 'deleteMemory'].includes(endpoint)) {
182
+ if (String(payload?.libraryId || '').trim()) return false
183
+ return authorizeGlobalReviewRoute(connection, req, endpoint, payload)
184
+ }
175
185
  // Review endpoints are dual-scope: without an explicit libraryId they address
176
186
  // the global curator queue, which follows its own management model.
177
187
  if ((endpoint === 'listReviews' || endpoint === 'resolveReview') && !String(payload?.libraryId || '').trim()) {
@@ -1389,6 +1399,16 @@ async function dispatch(ctx, endpoint, payload = {}) {
1389
1399
  const id = String(payload?.id || '')
1390
1400
  if (!id) throw new Error('id is required')
1391
1401
  const patch = payload?.patch || {}
1402
+ // 全局条目内容仍由 curator 写(硬规则 2):管理面这里只开放「从归档恢复」,
1403
+ // 其余字段一律拒绝,不做静默丢弃。
1404
+ if (payload?.scope === 'global') {
1405
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
1406
+ const keys = Object.keys(patch)
1407
+ if (keys.length !== 1 || keys[0] !== 'status' || patch.status !== 'active') {
1408
+ throw new Error('global memories only support restoring to active here; content stays curator-written')
1409
+ }
1410
+ return globalSetStatus({ id, status: 'active' })
1411
+ }
1392
1412
  // `layer` is here so the browser can promote a short_term draft to long_term,
1393
1413
  // which is the one upgrade path memory.js supports in place.
1394
1414
  // `source` is writable: correcting provenance is the point of showing it.
@@ -1975,6 +1995,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1975
1995
  case 'archiveMemory': {
1976
1996
  const id = String(payload?.id || '')
1977
1997
  if (!id) throw new Error('memory id is required')
1998
+ if (payload?.scope === 'global') {
1999
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
2000
+ return globalSetStatus({ id, status: 'archived' })
2001
+ }
1978
2002
  if (payload?.libraryId) return privateArchive({ libraryId: String(payload.libraryId), id })
1979
2003
  return privateArchive({ exec: execFor(requireSessionId(payload)), id })
1980
2004
  }
@@ -1984,6 +2008,15 @@ async function dispatch(ctx, endpoint, payload = {}) {
1984
2008
  // hallucinated id away from erasing a memory it never read.
1985
2009
  const id = String(payload?.id || '')
1986
2010
  if (!id) throw new Error('memory id is required')
2011
+ // 全局删除走显式 scope:'global'(管理面鉴权):没有私有库目标,也没有
2012
+ // preview/restore 撤销缓冲——安全网是两段确认 + 删除前整库备份。
2013
+ if (payload?.scope === 'global') {
2014
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
2015
+ if (payload?.preview === true || payload?.restore === true) throw new Error('global delete has no preview/restore buffer; it is guarded by two-step confirmation and a fresh backup')
2016
+ if (payload?.confirmed !== true) throw new Error('permanently deleting a memory requires explicit confirmation')
2017
+ const safety = await backupDatabases()
2018
+ return { ...await globalDelete({ id }), safety }
2019
+ }
1987
2020
  const libraryId = String(payload?.libraryId || '')
1988
2021
  if (!libraryId) throw new Error('libraryId is required')
1989
2022
  if (!getLibrary(libraryId)) throw new Error('library not found')
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.10",
4
+ "version": "1.3.12",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -282,6 +282,8 @@ function top3Of(ids) {
282
282
  * Definitions and empty-set rules:
283
283
  * - Recall@3 denominator = answerable samples only. A sample counts as a hit if
284
284
  * at least one expected id is in the first three positions.
285
+ * - allExpectedAt3 denominator = answerable samples only; all expected ids must
286
+ * appear in top-3 (sets larger than three cannot score a complete hit).
285
287
  * - MRR@3 denominator = answerable samples only. The reciprocal rank is 0 when no
286
288
  * expected id appears in the first three positions.
287
289
  * - No-answer false-recall denominator = no-answer samples only. It is the fraction
@@ -294,6 +296,7 @@ function top3Of(ids) {
294
296
  export function computeMetrics(records) {
295
297
  let answerable = 0
296
298
  let hits = 0
299
+ let completeHits = 0
297
300
  let reciprocalRankSum = 0
298
301
  let noAnswer = 0
299
302
  let noAnswerFalseRecall = 0
@@ -306,6 +309,8 @@ export function computeMetrics(records) {
306
309
  if (top3.length > 0) noAnswerFalseRecall += 1
307
310
  } else {
308
311
  answerable += 1
312
+ const expected = [...new Set(record.expectedIds || [])]
313
+ if (expected.length > 0 && expected.every(id => top3.includes(id))) completeHits += 1
309
314
  let rank = 0
310
315
  for (let index = 0; index < top3.length; index += 1) {
311
316
  if (record.expectedIds?.includes(top3[index])) {
@@ -325,6 +330,7 @@ export function computeMetrics(records) {
325
330
  }
326
331
  return {
327
332
  recallAt3: answerable === 0 ? 0 : round(hits / answerable),
333
+ allExpectedAt3: answerable === 0 ? 0 : round(completeHits / answerable),
328
334
  mrrAt3: answerable === 0 ? 0 : round(reciprocalRankSum / answerable),
329
335
  noAnswerFalseRecallRate: noAnswer === 0 ? 0 : round(noAnswerFalseRecall / noAnswer),
330
336
  isolationViolations: violations.length,
@@ -335,6 +341,7 @@ export function computeMetrics(records) {
335
341
  },
336
342
  emptySet: {
337
343
  recallAt3: answerable === 0,
344
+ allExpectedAt3: answerable === 0,
338
345
  mrrAt3: answerable === 0,
339
346
  noAnswerFalseRecallRate: noAnswer === 0,
340
347
  isolationViolations: forbiddenChecked === 0,
@@ -40,6 +40,8 @@ export const commit = async ({ payload, db }) => {
40
40
  for (const row of payload.recall_files) rows.set(db + '|' + row.name, row)
41
41
  return { ok: true }
42
42
  }
43
+ export const closeMemuResident = () => 0
44
+ export const prewarmMemuResident = async () => false
43
45
  export const retrieve = async () => ({ files: [] })
44
46
  export const forget = async ({ db, name }) => {
45
47
  calls.forget.push({ db, name })
@@ -1391,3 +1391,113 @@ test('the log page renders rows with copy, download and locate actions', async (
1391
1391
  assert.match(text, /logKindCheck/, 'the activity log labels wake-up checks')
1392
1392
  assert.match(text, /large-transcript-thin/, 'the check row keeps its reason and score visible')
1393
1393
  })
1394
+
1395
+ test('the memory wall global block bulk-archives and the drawer deletes global entries two-step', async () => {
1396
+ const rpcCalls = []
1397
+ const ctx = fakeCtx({ rpcCalls })
1398
+ const originalGetState = RPC_ANSWERS.getState
1399
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
1400
+ const loaded = {
1401
+ ...EMPTY_STATE,
1402
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 0 }],
1403
+ }
1404
+ RPC_ANSWERS.getState = loaded
1405
+ RPC_ANSWERS.getSettingsState = loaded
1406
+ RPC_ANSWERS.browseWall = {
1407
+ total: 2,
1408
+ items: [
1409
+ { id: 'mem-g-active', libraryId: null, libraryName: 'global', title: 'global active', preview: 'active body', layer: 'long_term', status: 'active', source: 'inferred', decay: 0.5, tags: [] },
1410
+ { id: 'mem-g-archived', libraryId: null, libraryName: 'global', title: 'global archived', preview: 'archived body', layer: 'long_term', status: 'archived', source: 'inferred', decay: 0.5, tags: [] },
1411
+ ],
1412
+ }
1413
+ RPC_ANSWERS.listGlobal = {
1414
+ files: [
1415
+ { id: 'mem-g-active', title: 'global active', content: 'active body', status: 'active', domain: 'general' },
1416
+ { id: 'mem-g-archived', title: 'global archived', content: 'archived body', status: 'archived', domain: 'general' },
1417
+ ],
1418
+ }
1419
+ RPC_ANSWERS.archiveMemory = { id: 'mem-g-active', entry: { status: 'archived' } }
1420
+ RPC_ANSWERS.deleteMemory = { id: 'mem-g-archived', libraryId: null, deleted: true }
1421
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
1422
+ // harness 的 hook 游标是全局的:同一棵树只能展开一次,二次 walk 会把子组件
1423
+ // 的 useState 重新初始化。所以每次 renderPage 后只 walk 一遍,收齐所有节点。
1424
+ const collect = (tree) => {
1425
+ const labels = new Map()
1426
+ const cards = []
1427
+ const tabs = []
1428
+ walkNodes(tree, (node) => {
1429
+ if (typeof node.type === 'function' && typeof node.props?.children === 'string' && !labels.has(node.props.children)) {
1430
+ labels.set(node.props.children, node)
1431
+ }
1432
+ if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
1433
+ if (node.type === 'button' && node.props?.role === 'tab') tabs.push(node)
1434
+ })
1435
+ return { labels, cards, tabs }
1436
+ }
1437
+ try {
1438
+ globalThis.__dshMemuExports.apply(ctx)
1439
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1440
+ const props = { ctx, t: (key) => key }
1441
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
1442
+ collectPageHook()
1443
+ for (const effect of first.effects) effect.fn()
1444
+ await tick(); await tick()
1445
+ let view = collect((await renderPage(settings.component, props, 9)).tree)
1446
+ for (const effect of effects) effect.fn()
1447
+ await tick(); await tick()
1448
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1449
+
1450
+ // 切到全局块:多选开关必须存在(旧版全局块没有)。
1451
+ const scopeTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('wallScopeGlobal'))
1452
+ assert.ok(scopeTab, 'the global scope tab did not render')
1453
+ scopeTab.props.onClick()
1454
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1455
+ assert.ok(view.labels.has('multiSelect'), 'the global block offers multi-select')
1456
+ view.labels.get('multiSelect').props.onClick()
1457
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1458
+ assert.equal(view.cards.length, 1, 'the active pool shows the active global card')
1459
+ view.cards[0].props.onClick()
1460
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1461
+ assert.ok(view.labels.has('archive (1)'), 'selecting one global card arms the bulk archive button')
1462
+ view.labels.get('archive (1)').props.onClick()
1463
+ await tick(); await tick()
1464
+ const archived = rpcCalls.filter((call) => call.endpoint === 'archiveMemory')
1465
+ assert.equal(archived.length, 1)
1466
+ assert.equal(archived[0].payload.scope, 'global')
1467
+ assert.equal(archived[0].payload.id, 'mem-g-active')
1468
+ assert.equal(archived[0].payload.libraryId, undefined, 'global bulk writes never name a private library')
1469
+
1470
+ // 已归档池开抽屉:恢复与两段删除都在,删除第一段只武装、第二段才发请求。
1471
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1472
+ view.labels.get('wallMultiExit').props.onClick()
1473
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1474
+ const archivedTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('browseArchivedTab'))
1475
+ archivedTab.props.onClick()
1476
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1477
+ assert.equal(view.cards.length, 1)
1478
+ view.cards[0].props.onClick()
1479
+ await tick(); await tick()
1480
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1481
+ assert.ok(view.labels.has('restore'), 'the archived global drawer offers restore')
1482
+ assert.ok(view.labels.has('deleteForever'), 'the archived global drawer offers permanent delete')
1483
+ assert.ok(!view.labels.has('save'), 'global content stays curator-written')
1484
+ view.labels.get('deleteForever').props.onClick()
1485
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1486
+ assert.equal(rpcCalls.filter((call) => call.endpoint === 'deleteMemory').length, 0, 'the first click only arms')
1487
+ assert.ok(view.labels.has('confirmDelete'))
1488
+ view.labels.get('confirmDelete').props.onClick()
1489
+ await tick(); await tick()
1490
+ const deleted = rpcCalls.filter((call) => call.endpoint === 'deleteMemory')
1491
+ assert.equal(deleted.length, 1)
1492
+ assert.equal(deleted[0].payload.scope, 'global')
1493
+ assert.equal(deleted[0].payload.id, 'mem-g-archived')
1494
+ assert.equal(deleted[0].payload.confirmed, true)
1495
+ } finally {
1496
+ RPC_ANSWERS.getState = originalGetState
1497
+ RPC_ANSWERS.getSettingsState = originalSettingsState
1498
+ delete RPC_ANSWERS.browseWall
1499
+ delete RPC_ANSWERS.listGlobal
1500
+ delete RPC_ANSWERS.archiveMemory
1501
+ delete RPC_ANSWERS.deleteMemory
1502
+ }
1503
+ })
@@ -564,6 +564,20 @@ test('a candidate is covered only when a written entry carries the fact', () =>
564
564
  assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
565
565
  })
566
566
 
567
+ test('coverage does not discard facts for matching dates, polarity, values, or generic overlap', () => {
568
+ const covered = (text, content, title = '') => candidateCovered({ text }, ['mem-written'], { entries: { 'mem-written': { title, content } } })
569
+ assert.equal(covered('11月20日阿兰取伞', '11月20日小林去医院'), false, 'same date is not the same event')
570
+ assert.equal(covered('父亲不吃芹菜', '父亲爱吃芹菜'), false, 'opposite polarity is not coverage')
571
+ assert.equal(covered('父亲周末去图书馆还书', '父亲周末去图书馆借书'), false, 'shared topic must retain the action')
572
+ assert.equal(covered('父亲生日是11月20日', '父亲生日是11月21日'), false, 'different date is not coverage')
573
+ assert.equal(covered('项目预算是1200元', '项目预算是1500元'), false, 'different value is not coverage')
574
+ assert.equal(covered('11月20日', '11月20日小林去医院'), false, 'date alone is insufficient evidence')
575
+ assert.equal(covered('父亲不吃芹菜', '父亲不吃芹菜,母亲喜欢白菜'), true)
576
+ assert.equal(covered('父亲喜欢芹菜', '父亲喜欢芹菜,母亲不吃白菜'), true, 'unrelated negation does not alter the fact')
577
+ assert.equal(covered('11月20日阿兰取伞', '11月20日阿兰取伞,记得提前联系'), true)
578
+ assert.equal(covered('项目预算是1200元', '项目预算是1200元'), true)
579
+ })
580
+
567
581
  test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
568
582
  state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
569
583
  const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused max-tokens argument' } } })