dsh-memu-memory 1.2.8 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/backup.js +154 -25
  5. package/lib/binding-diagnostics.js +1 -2
  6. package/lib/budget.js +0 -9
  7. package/lib/client.js +221 -128
  8. package/lib/commitment.js +3 -3
  9. package/lib/consolidation-ledger.js +5 -2
  10. package/lib/curator-policy.js +23 -0
  11. package/lib/cycle.js +8 -4
  12. package/lib/embedding-download.js +168 -28
  13. package/lib/embedding-runtime.js +76 -17
  14. package/lib/engine.js +0 -6
  15. package/lib/freshness.js +2 -2
  16. package/lib/graph.js +139 -11
  17. package/lib/index.js +71 -20
  18. package/lib/inject.js +50 -7
  19. package/lib/lexicon.js +61 -16
  20. package/lib/local-vector-service.js +21 -1
  21. package/lib/media.js +49 -12
  22. package/lib/memory.js +662 -116
  23. package/lib/paths.js +0 -7
  24. package/lib/preset-scope.js +6 -1
  25. package/lib/private.js +45 -7
  26. package/lib/prompts.js +0 -7
  27. package/lib/rpc.js +95 -17
  28. package/lib/snippet.js +18 -2
  29. package/lib/state.js +109 -30
  30. package/lib/stats.js +2 -2
  31. package/lib/temporal.js +19 -0
  32. package/lib/text-retrieval.js +120 -44
  33. package/lib/text-similarity.js +205 -24
  34. package/lib/tokenizer-v2.js +0 -24
  35. package/lib/vector-migration.js +15 -0
  36. package/lib/vector-profile.js +81 -8
  37. package/lib/visibility.js +0 -4
  38. package/lib/webui/standalone.css +17 -22
  39. package/lib/webui/standalone.js +27 -9
  40. package/lib/webui.js +4 -4
  41. package/package.json +3 -2
  42. package/scripts/acceptance-local.mjs +2 -2
  43. package/scripts/check-all.mjs +3 -1
  44. package/scripts/check-i18n.mjs +35 -1
  45. package/scripts/migrate-visibility.mjs +3 -3
  46. package/scripts/prune-sessions.mjs +34 -0
  47. package/scripts/prune-vectors.mjs +24 -0
  48. package/tests/appendix-b.test.mjs +5 -4
  49. package/tests/audit-batch3.test.mjs +247 -0
  50. package/tests/audit-regression.test.mjs +2 -2
  51. package/tests/backup.test.mjs +83 -83
  52. package/tests/browser.test.mjs +6 -1
  53. package/tests/client-render.test.mjs +2 -2
  54. package/tests/curator-clusters.test.mjs +18 -0
  55. package/tests/curator-pairing.test.mjs +59 -16
  56. package/tests/dynamic-rrf.test.mjs +22 -19
  57. package/tests/dynamic-threshold.test.mjs +52 -0
  58. package/tests/fact-version.test.mjs +18 -0
  59. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  60. package/tests/graph-cascade.test.mjs +29 -0
  61. package/tests/graph.test.mjs +45 -0
  62. package/tests/inject-conflict.test.mjs +18 -0
  63. package/tests/lexical-bm25.test.mjs +171 -0
  64. package/tests/lexicon-frequency.test.mjs +16 -0
  65. package/tests/lexicon-inject.test.mjs +21 -0
  66. package/tests/lexicon-perf.test.mjs +37 -9
  67. package/tests/lexicon-scope.test.mjs +2 -2
  68. package/tests/lexicon-ui.test.mjs +1 -1
  69. package/tests/managed-memory.test.mjs +19 -0
  70. package/tests/ops-hardening.test.mjs +209 -0
  71. package/tests/package-shipping.test.mjs +4 -0
  72. package/tests/recall-intent.test.mjs +23 -0
  73. package/tests/slot-similarity.test.mjs +153 -0
  74. package/tests/state-gc.test.mjs +34 -0
  75. package/tests/state.test.mjs +2 -2
  76. package/tests/tokenizer-v2.test.mjs +1 -1
  77. package/tests/vector-gc.test.mjs +37 -0
  78. package/tests/webui.test.mjs +27 -0
package/lib/memory.js CHANGED
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto'
1
2
  import fs from 'node:fs'
2
3
  import os from 'node:os'
3
4
  import path from 'node:path'
@@ -10,23 +11,23 @@ import {
10
11
  getLibrary, setSessionBinding, setRecallError, effectiveScope, listLibrariesAll,
11
12
  listLibraries, listSessionBindings, getWorkspacePolicy, memoryRevision,
12
13
  } from './state.js'
13
- import { stamp, redactSecrets, retryStoreWrite, warn } from './paths.js'
14
+ import { stamp, redactSecrets, retryStoreWrite, warn, indexDir, readJson, writeJson } from './paths.js'
14
15
  import { scopeGenerationOf } from './consolidation-ledger.js'
15
16
  import { record } from './activity-log.js'
16
17
  import { BASE_AROUSAL, derivedValence, dominanceBias, emotionActive, maxShare, moodCongruence, moodDecay, normalizeEmotion, overlap, readMood } from './mood.js'
17
18
  import { commit, retrieve, listFiles, forget } from './memu.js'
18
19
  import { bumpStats } from './stats.js'
19
- import { recallRelations, pruneOrphanEntities } from './graph.js'
20
+ import { recallRelations, pruneOrphanEntities, revertGraphData } from './graph.js'
20
21
  import { attachmentRefs } from './media.js'
21
22
  import { normalizeMemoryContext, contextVisible, sameFactContext } from './context.js'
22
23
  import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGeneration, enrollActiveLibrary, hasActiveVectorGeneration, isVectorStateError, readVectorState, withVectorWrite } from './vector-profile.js'
23
- import { bigrams, dice, similarTexts, DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
24
+ import { similarTexts, similarityDetail, DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
24
25
  import { applyAbsorbIndexTransaction } from './curator.js'
25
26
  import { recallCache, recallCacheKey } from './recall-cache.js'
26
27
  import { parseAbsoluteDate, parseTemporalExpression, hasTemporalHint, resolveQueryDates, localDateKeyInZone, DEFAULT_TIME_ZONE } from './temporal.js'
27
28
  import { validitySignals } from './freshness.js'
28
29
  import { commitmentOf, commitmentDueDate, commitmentDueState, isOpenThread, normalizeCommitment } from './commitment.js'
29
- import { detectQueryIntent, decomposeQuery } from './text-retrieval.js'
30
+ import { detectQueryIntent, decomposeQuery, buildCorpus, bm25, longestSharedToken, polarityAt, tokenize } from './text-retrieval.js'
30
31
  import { intentTopK } from './budget.js'
31
32
 
32
33
  // P1-1 召回缓存。缓存自身出错时 fail-open,
@@ -64,6 +65,23 @@ const HYBRID_RRF_K = 60
64
65
  const HYBRID_CANDIDATE_MIN = 12
65
66
  const HYBRID_CANDIDATE_MAX = 40
66
67
  const HYBRID_SEMANTIC_TIMEOUT_MS = 15_000
68
+ // An empty query carries no lexical signal, so the only order available is recency.
69
+ // The caller still wants a page of it, never the whole library: every later stage
70
+ // (score, weak cut, MMR) is linear or worse in the pool size, and MMR compares each
71
+ // remaining candidate against everything it has already chosen.
72
+ const EMPTY_QUERY_SCAN_LIMIT = 200
73
+ // A query date and an entry's absolute_date agreeing is a tie-breaker, not a score of
74
+ // its own. Multiplicative so it can only reorder documents that already matched the
75
+ // text; a date-only match is placed strictly below every real hit. Global recall has
76
+ // always used 1.35 here — this is the lexical path catching up to it.
77
+ const DATE_MATCH_FACTOR = 1.35
78
+ const DATE_ONLY_RATIO = 1000
79
+ // MMR costs O(pool x limit) similarity calls, and the pool used to be "every document
80
+ // with a non-zero lexical score". With CJK unigram tokenisation one common character
81
+ // makes that the whole library (measured: 20000 entries x query 今天怎么样 is about
82
+ // 380k similarity calls). MMR only ever needs a few alternatives per seat.
83
+ const MMR_POOL_FACTOR = 4
84
+ const MMR_POOL_MIN = 24
67
85
  const LAYERS = ['long_term', 'short_term', 'must_remember']
68
86
  // These three are read back by the injector to decide how a memory may be spoken and
69
87
  // where it may appear. An unchecked typo would silently mean "no suffix at all", so
@@ -167,8 +185,32 @@ async function compensatePrivateCommit(error, { libraryId, id, route, db, expect
167
185
  throw error
168
186
  }
169
187
 
170
- async function withManagedPrivateWriteImpl(libraryId, action) {
171
- const intent = managedVectorIntent()
188
+ /**
189
+ * P2-3: a managed-local vector commit is an index accelerator, not the source of
190
+ * truth. If MemU is unavailable, the memory still lands in the JSON index with
191
+ * `vectorPending: true`; the next migration/switch backfills it. Remote-api
192
+ * routes keep the old fail-closed behavior because that backend is the store.
193
+ */
194
+ async function commitPrivatePayload({ payload, route, db, libraryId, id }) {
195
+ try {
196
+ const result = await commit({ payload, route, db })
197
+ return { result, committedDb: db, warning: null }
198
+ } catch (error) {
199
+ if (route !== 'managed-local') throw error
200
+ const warning = String(error?.message || error)
201
+ warn(`managed vector commit deferred for ${id}: ${warning}`)
202
+ try {
203
+ record({
204
+ kind: 'vector', level: 'warn', scope: 'private', libraryId,
205
+ message: '向量提交失败,已仅写索引(待迁移补向量)',
206
+ detail: { id, error: warning }, refs: [id],
207
+ })
208
+ } catch {}
209
+ return { result: { ok: false, deferred: true, error: warning }, committedDb: null, warning }
210
+ }
211
+ }
212
+
213
+ async function withManagedPrivateWriteImpl(libraryId, action) { const intent = managedVectorIntent()
172
214
  if (!intent.managed) return action()
173
215
  // 选了本地向量、但下载完模型后从没跑过迁移(vector-active 只有 requested):这里
174
216
  // 没有可对齐的代际,写入必须降级成索引 + 引擎,而不是把整次整理写死。召回侧一直是
@@ -197,7 +239,7 @@ async function withManagedGlobalWrite(action) {
197
239
  }
198
240
 
199
241
  async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
200
- const local = localRecall(index, query)
242
+ const local = localRecall(index, query, undefined, { cacheKey: libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`, topK })
201
243
  try {
202
244
  if (intent.error) throw intent.error
203
245
  const captured = intent.route === 'managed-local' ? captureGeneration() : null
@@ -300,6 +342,17 @@ function defaultSpeakerFor(kind) {
300
342
  return 'unknown'
301
343
  }
302
344
 
345
+ // Local, derived authority for the conflict card order. It is not a truth score:
346
+ // a direct quote outranks a reconstruction, a tool/relay sits between, and an
347
+ // imagined memory is last. The card still says "未确认哪版为准".
348
+ function factAuthorityOf(kind) {
349
+ if (kind === 'user_said') return 3
350
+ if (kind === 'tool' || kind === 'told') return 2
351
+ if (kind === 'inferred') return 1
352
+ if (kind === 'imagined') return 0
353
+ return 1
354
+ }
355
+
303
356
  /** Old entries have no speaker_id/source_kind; derive the closest honest answer. */
304
357
  export function speakerOfEntry(entry) {
305
358
  if (!entry || typeof entry !== 'object') return 'unknown'
@@ -307,13 +360,6 @@ export function speakerOfEntry(entry) {
307
360
  return defaultSpeakerFor(entry.source_kind || entry.source)
308
361
  }
309
362
 
310
- export function sourceKindOfEntry(entry) {
311
- if (!entry || typeof entry !== 'object') return 'inferred'
312
- if (SOURCE_KINDS.includes(entry.source_kind)) return entry.source_kind
313
- if (SOURCE_KINDS.includes(entry.source)) return entry.source
314
- return 'inferred'
315
- }
316
-
317
363
  /**
318
364
  * S3.2:查询里明确问“我说过/你说过/他说的”时,给召回一个说话人方向。
319
365
  * 只排除“明确不是这个人”的条目;缺少 speaker 的旧条目保留,避免一次性清空召回。
@@ -800,7 +846,6 @@ const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
800
846
  export function findConflict(entries, candidate) {
801
847
  const title = String(candidate?.title || '').trim().toLowerCase()
802
848
  const body = String(candidate?.content || '')
803
- const grams = bigrams(body)
804
849
  const candidateNegated = NEGATION_RE.test(body)
805
850
  for (const [id, entry] of Object.entries(entries || {})) {
806
851
  if (!entry || entry.status === 'archived' || entry.status === 'suppressed') continue
@@ -808,15 +853,33 @@ export function findConflict(entries, candidate) {
808
853
  if (entry.status === 'pending_review' || entry.status === 'superseded') continue
809
854
  const otherTitle = String(entry.title || '').trim().toLowerCase()
810
855
  const otherBody = String(entry.content || '')
856
+ // A bare dice() was wrong in both directions. A short claim and the 200-character
857
+ // rewrite of it share almost no bigrams once the lengths diverge — the gate prunes
858
+ // that pair to 0 by design — so a genuine contradiction went unnoticed; and a
859
+ // negation marker anywhere in the body, even in an unrelated trailing clause
860
+ // ("他喜欢喝茶,别忘了"), flipped one side's polarity and turned a plain restatement
861
+ // into a conflict. similarityDetail adds the containment probes and the slot test;
862
+ // polarityAt narrows the negation test to the clause that actually carries the
863
+ // shared claim. These are the same rulers the curator's global pre-screen uses, so
864
+ // a write and a later sweep cannot disagree about whether two memories contradict.
865
+ const detail = similarityDetail(body, otherBody)
866
+ const similarity = detail.raw
811
867
  if (title && title === otherTitle) {
812
- if (dice(grams, bigrams(otherBody)) < 0.95) return { id, entry, reason: 'same_title' }
868
+ // A same-title memory that only changed a number/date/time is a correction,
869
+ // not a duplicate: hold it for review instead of letting the duplicate gate
870
+ // swallow it. Non-slot rewrites keep the original 0.95 behaviour.
871
+ if (detail.slotConflict) return { id, entry, reason: 'slot_conflict' }
872
+ if (similarity < 0.95) return { id, entry, reason: 'same_title' }
813
873
  continue
814
874
  }
815
- const similarity = dice(grams, bigrams(otherBody))
816
875
  if (similarity < 0.55) continue
817
- if (candidateNegated !== NEGATION_RE.test(otherBody)) {
818
- return { id, entry, reason: 'negation' }
819
- }
876
+ // No shared anchor means nothing to scope the negation to; fall back to the whole
877
+ // body, which is the old behaviour and stays conservative there.
878
+ const anchor = longestSharedToken(body, otherBody)
879
+ const differs = anchor
880
+ ? polarityAt(body, anchor) !== polarityAt(otherBody, anchor)
881
+ : candidateNegated !== NEGATION_RE.test(otherBody)
882
+ if (differs) return { id, entry, reason: 'negation' }
820
883
  }
821
884
  return null
822
885
  }
@@ -940,9 +1003,13 @@ function assertEntryAccess(entry, exec) {
940
1003
  }
941
1004
 
942
1005
  // Local mode has no embedding service to rank candidates, so the index itself is
943
- // the retrieval source. The tokenizer is deliberately small and dependency-free:
944
- // Latin words plus CJK unigrams/bigrams, which is enough for the short, concrete
945
- // memories this plugin stores and works identically on every platform.
1006
+ // the retrieval source. The legacy scorer is kept behind
1007
+ // DSH_MEMU_RECALL_LEXICAL=includes for A/B and one-release rollback; the default
1008
+ // path is BM25 over the same corpus the curator already uses.
1009
+ function recallLexicalMode() {
1010
+ return process.env.DSH_MEMU_RECALL_LEXICAL === 'includes' ? 'includes' : 'bm25'
1011
+ }
1012
+
946
1013
  function queryTokens(query) {
947
1014
  const text = String(query || '').toLowerCase()
948
1015
  const tokens = new Set(text.match(/[a-z0-9_]+/g) || [])
@@ -955,6 +1022,9 @@ function queryTokens(query) {
955
1022
  return [...tokens].filter(Boolean)
956
1023
  }
957
1024
 
1025
+ // Legacy includes-count scorer: no IDF, no length normalisation. Only the
1026
+ // DSH_MEMU_RECALL_LEXICAL=includes path uses it now; it stays so an install can
1027
+ // be compared or rolled back without editing code.
958
1028
  function lexicalScore(entry, tokens, queryDates = []) {
959
1029
  if (!tokens.length && !queryDates.length) return 0
960
1030
  const title = String(entry?.title || '').toLowerCase()
@@ -973,6 +1043,70 @@ function lexicalScore(entry, tokens, queryDates = []) {
973
1043
  return tokens.length ? score / tokens.length : score
974
1044
  }
975
1045
 
1046
+ // Everything the old includes scorer could match must be in the BM25 document too:
1047
+ // title, body, tags and attachment captions. Dropping tags/captions here would be a
1048
+ // silent recall regression, not a ranking tweak.
1049
+ function lexicalDocumentText(entry) {
1050
+ const tags = Array.isArray(entry?.tags) ? entry.tags.join(' ') : ''
1051
+ const captions = (entry?.attachments || [])
1052
+ .map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`)
1053
+ .join(' ')
1054
+ return [entry?.content || '', tags, captions].filter(Boolean).join(' ')
1055
+ }
1056
+
1057
+ function byUpdatedDesc(a, b) {
1058
+ return String(b.entry?.updatedAt || b.entry?.createdAt || '')
1059
+ .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || ''))
1060
+ }
1061
+
1062
+ // Rebuilding the BM25 corpus tokenises every active entry. A dense chat recalls
1063
+ // every turn, so cache the corpus per scope.
1064
+ //
1065
+ // The key used to be `memoryRevision()`, which made the cache useless: injecting a
1066
+ // memory writes the index (injectCount / lastInjectAt), so the fixed rhythm
1067
+ // "recall -> inject -> write index -> revision++" invalidated the corpus on every
1068
+ // single turn and the TTL below never had a chance to apply. Fingerprint what the
1069
+ // corpus is actually built from — id, title, body — so a write that only touches
1070
+ // bookkeeping cannot throw away a corpus it did not change. The TTL stays, for
1071
+ // external editors that rewrite the file in a way this process cannot observe.
1072
+ const LEXICAL_CORPUS_CACHE_MAX = 32
1073
+ const LEXICAL_CORPUS_TTL_MS = 60_000
1074
+ const lexicalCorpusCache = new Map()
1075
+
1076
+ function corpusFingerprint(files) {
1077
+ const hash = crypto.createHash('sha1')
1078
+ for (const file of files) {
1079
+ hash.update(String(file.name))
1080
+ hash.update('\u0000')
1081
+ hash.update(String(file.entry?.title || ''))
1082
+ hash.update('\u0000')
1083
+ hash.update(lexicalDocumentText(file.entry))
1084
+ hash.update('\u0000')
1085
+ }
1086
+ return hash.digest('hex')
1087
+ }
1088
+
1089
+ function lexicalCorpusFor(files, cacheKey) {
1090
+ const now = Date.now()
1091
+ const fingerprint = cacheKey ? corpusFingerprint(files) : null
1092
+ if (cacheKey) {
1093
+ const cached = lexicalCorpusCache.get(cacheKey)
1094
+ if (cached && cached.fingerprint === fingerprint && cached.expiresAt > now) return cached.corpus
1095
+ }
1096
+ const corpus = buildCorpus(files.map((file) => ({
1097
+ id: file.name,
1098
+ title: file.entry?.title || '',
1099
+ content: lexicalDocumentText(file.entry),
1100
+ })))
1101
+ if (cacheKey) {
1102
+ if (lexicalCorpusCache.size >= LEXICAL_CORPUS_CACHE_MAX) {
1103
+ lexicalCorpusCache.delete(lexicalCorpusCache.keys().next().value)
1104
+ }
1105
+ lexicalCorpusCache.set(cacheKey, { fingerprint, expiresAt: now + LEXICAL_CORPUS_TTL_MS, corpus })
1106
+ }
1107
+ return corpus
1108
+ }
1109
+
976
1110
  function localIndexFiles(index) {
977
1111
  return Object.entries(index?.entries || {}).map(([name, entry]) => ({
978
1112
  name,
@@ -984,30 +1118,56 @@ function localIndexFiles(index) {
984
1118
  }))
985
1119
  }
986
1120
 
987
- function localRecall(index, query, filter = () => true) {
1121
+ function localRecall(index, query, filter = () => true, { cacheKey = null, topK = null } = {}) {
988
1122
  const files = localIndexFiles(index).filter((file) => isActive(file.entry) && filter(file))
989
1123
  if (/^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())) {
990
1124
  const id = resolveEntryId(index, String(query).trim())
991
1125
  return { files: files.filter(file => file.name === id).map(file => ({ ...file, lexical: 5 })), segments: [], resources: [], raw: null, parseWarning: null }
992
1126
  }
993
- const tokens = queryTokens(query)
994
1127
  const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
995
- const ordered = tokens.length === 0
996
- ? files.sort((a, b) => String(b.entry?.updatedAt || b.entry?.createdAt || '')
997
- .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
998
- : files
999
- .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates) }))
1000
- .filter((file) => file.lexical > 0)
1001
- .sort((a, b) => b.lexical - a.lexical
1002
- || String(b.entry?.updatedAt || b.entry?.createdAt || '')
1003
- .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
1004
- return {
1005
- files: ordered,
1006
- segments: [],
1007
- resources: [],
1008
- raw: null,
1009
- parseWarning: null,
1010
- }
1128
+ if (recallLexicalMode() === 'includes') {
1129
+ const tokens = queryTokens(query)
1130
+ const ordered = tokens.length === 0
1131
+ ? files.sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK))
1132
+ : files
1133
+ .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates) }))
1134
+ .filter((file) => file.lexical > 0)
1135
+ .sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
1136
+ return { files: ordered, segments: [], resources: [], raw: null, parseWarning: null }
1137
+ }
1138
+ const tokens = tokenize(query)
1139
+ if (tokens.length === 0) {
1140
+ return { files: files.sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), segments: [], resources: [], raw: null, parseWarning: null }
1141
+ }
1142
+ const corpus = lexicalCorpusFor(files, cacheKey)
1143
+ // The date boost came over from the includes scorer unchanged (+4), where it shared
1144
+ // a ruler with "title matches = 4". BM25 has no upper bound and its IDF depends on
1145
+ // the library (about 2.7 at N=21/df=1, a typical hit scoring 2-5), so an additive +4
1146
+ // could put an unrelated meeting note stamped with the queried date above the
1147
+ // document that actually described the work — and it pulled entries with no lexical
1148
+ // hit at all past the `lexical > 0` filter below, spending candidate slots on them.
1149
+ const scored = files.map((file) => {
1150
+ const doc = corpus.docs.get(file.name)
1151
+ return {
1152
+ file,
1153
+ lexical: doc ? bm25(tokens, doc, corpus) : 0,
1154
+ dateMatch: Boolean(file.entry?.absolute_date && queryDates.includes(file.entry.absolute_date)),
1155
+ }
1156
+ })
1157
+ const best = scored.reduce((max, item) => Math.max(max, item.lexical), 0)
1158
+ // With no text hit at all there is nothing to sit below, so a date match gets a
1159
+ // seat at all; otherwise it lands a thousandth of the best hit — present, last.
1160
+ const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
1161
+ const ordered = scored
1162
+ .map(({ file, lexical, dateMatch }) => ({
1163
+ ...file,
1164
+ lexical: lexical > 0
1165
+ ? lexical * (dateMatch ? DATE_MATCH_FACTOR : 1)
1166
+ : (dateMatch ? dateOnly : 0),
1167
+ }))
1168
+ .filter((file) => file.lexical > 0)
1169
+ .sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
1170
+ return { files: ordered, segments: [], resources: [], raw: null, parseWarning: null }
1011
1171
  }
1012
1172
 
1013
1173
  /** The per-route candidate cap for a requested topK; bounded on both ends. */
@@ -1016,6 +1176,23 @@ export function hybridCandidateLimit(topK) {
1016
1176
  return Math.max(HYBRID_CANDIDATE_MIN, Math.min(HYBRID_CANDIDATE_MAX, wanted * 4))
1017
1177
  }
1018
1178
 
1179
+ /** How much of a recency-only result set is worth passing on. */
1180
+ function emptyQueryLimit(topK) {
1181
+ const wanted = Number(topK)
1182
+ return Number.isFinite(wanted) && wanted > 0 ? hybridCandidateLimit(wanted) : EMPTY_QUERY_SCAN_LIMIT
1183
+ }
1184
+
1185
+ /**
1186
+ * Cap the pool MMR is allowed to see. Order is preserved: the caller has already
1187
+ * sorted by score, so the head is exactly what MMR would have picked from first.
1188
+ */
1189
+ function mmrPool(items, max) {
1190
+ const limit = Number(max || 0)
1191
+ if (!(limit > 0)) return items
1192
+ const cap = Math.max(MMR_POOL_MIN, limit * MMR_POOL_FACTOR)
1193
+ return items.length <= cap ? items : items.slice(0, cap)
1194
+ }
1195
+
1019
1196
  /**
1020
1197
  * Reciprocal-rank fusion of lexical index hits and MemU vector hits.
1021
1198
  *
@@ -1058,22 +1235,22 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
1058
1235
  // Fact-level folding : id dedupe cannot see "same fact,
1059
1236
  // different id", so a paraphrase cluster would spend one candidate slot per
1060
1237
  // member and crowd real memories out before any ranking runs. A candidate that
1061
- // a accepted candidate already speaks for (dice ≥ DUP_DICE on title + body)
1062
- // is recorded and skipped: one cluster, one candidate slot.
1063
- const gramsCache = new Map()
1064
- const gramsOf = (item) => {
1065
- let set = gramsCache.get(item.id)
1066
- if (!set) {
1067
- set = bigrams(String(item.entry?.title || '') + ' ' + String(item.entry?.content || ''))
1068
- gramsCache.set(item.id, set)
1238
+ // an accepted candidate already speaks for (slot-aware score >= DUP_DICE on
1239
+ // title + body) is recorded and skipped: one cluster, one candidate slot.
1240
+ const textCache = new Map()
1241
+ const textOf = (item) => {
1242
+ let text = textCache.get(item.id)
1243
+ if (text === undefined) {
1244
+ text = `${item.entry?.title || ''} ${item.entry?.content || ''}`
1245
+ textCache.set(item.id, text)
1069
1246
  }
1070
- return set
1247
+ return text
1071
1248
  }
1072
1249
  for (const file of Array.isArray(files) ? files : []) {
1073
1250
  const item = eligible(file, route, picked.length + 1)
1074
1251
  if (!item || seen.has(item.id)) continue
1075
1252
  seen.add(item.id)
1076
- const twin = picked.find((accepted) => dice(gramsOf(item), gramsOf(accepted)) >= DUP_DICE)
1253
+ const twin = picked.find((accepted) => similarTexts(textOf(item), textOf(accepted)) >= DUP_DICE)
1077
1254
  if (twin) {
1078
1255
  collapsed.push({ kept: twin.id, dropped: item.id })
1079
1256
  continue
@@ -1109,18 +1286,18 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
1109
1286
  // diversity ceiling is set by a real spread of memories rather than a cluster.
1110
1287
  const fusionCollapsed = []
1111
1288
  const absorbed = new Set()
1112
- const rowGrams = new Map()
1113
- const gramsOfRow = (row) => {
1114
- let set = rowGrams.get(row.id)
1115
- if (!set) {
1116
- set = bigrams(String(row.entry?.title || '') + ' ' + String(row.entry?.content || ''))
1117
- rowGrams.set(row.id, set)
1289
+ const rowTexts = new Map()
1290
+ const textOfRow = (row) => {
1291
+ let text = rowTexts.get(row.id)
1292
+ if (text === undefined) {
1293
+ text = `${row.entry?.title || ''} ${row.entry?.content || ''}`
1294
+ rowTexts.set(row.id, text)
1118
1295
  }
1119
- return set
1296
+ return text
1120
1297
  }
1121
1298
  const hosts = []
1122
1299
  for (const row of rows.slice().sort((a, b) => b.rrf - a.rrf || a.id.localeCompare(b.id))) {
1123
- const host = hosts.find((kept) => dice(gramsOfRow(row), gramsOfRow(kept)) >= DUP_DICE)
1300
+ const host = hosts.find((kept) => similarTexts(textOfRow(row), textOfRow(kept)) >= DUP_DICE)
1124
1301
  if (host) {
1125
1302
  host.mergedTogether.push(row.id)
1126
1303
  absorbed.add(row.id)
@@ -1294,7 +1471,7 @@ function habituationFactor(entry, now = Date.now()) {
1294
1471
  // `retrievalFloor` is the absolute complement : whatever the
1295
1472
  // library looks like, a hit whose retrieval share never cleared the floor must not
1296
1473
  // pad a topK that a duplicate cluster emptied. 0 turns it off entirely.
1297
- function cutWeakScores(files, threshold, retrievalFloor = 0) {
1474
+ function cutWeakScores(files, threshold, retrievalFloor = 0, percentile = 0) {
1298
1475
  let out = files
1299
1476
  const cut = Number(threshold)
1300
1477
  if (Number.isFinite(cut) && cut > 0) {
@@ -1303,9 +1480,20 @@ function cutWeakScores(files, threshold, retrievalFloor = 0) {
1303
1480
  }
1304
1481
  const floor = Number(retrievalFloor)
1305
1482
  if (Number.isFinite(floor) && floor > 0) out = out.filter((f) => Number(f.retrieval ?? retrievalShare(f, 0)) >= floor)
1483
+ // P1-4: optional percentile cut, default off. It never pads to a minimum
1484
+ // result count — a clear no-match stays empty. Input is already score-desc.
1485
+ const p = Number(percentile)
1486
+ if (Number.isFinite(p) && p > 0 && p < 100 && out.length > 1) {
1487
+ const keep = Math.max(1, Math.ceil(out.length * (1 - p / 100)))
1488
+ out = out.slice(0, keep)
1489
+ }
1306
1490
  return out
1307
1491
  }
1308
1492
 
1493
+ function recallPercentile() {
1494
+ return process.env.DSH_MEMU_RECALL_PERCENTILE === '1' ? 75 : 0
1495
+ }
1496
+
1309
1497
  function privateWeighted(result, max, context = {}) {
1310
1498
  const ctx = {
1311
1499
  moodEnabled: false,
@@ -1333,13 +1521,13 @@ function privateWeighted(result, max, context = {}) {
1333
1521
  .filter((f) => visibleToSession(f.entry, ctx.sessionId))
1334
1522
  .filter((f) => !ctx.automatic || f.entry?.visibility !== 'secret')
1335
1523
  // S6:never_say 由 isMemoryEligible 挡掉;only_if_asked 只在 boundary 意图时放行。
1336
- .filter((f) => !ctx.automatic || f.entry?.disclosure !== 'only_if_asked' || ctx.disclosureAsked === true)
1524
+ .filter((f) => isDisclosureEligible(f.entry, { automatic: ctx.automatic === true, asked: ctx.disclosureAsked === true }))
1337
1525
  // S3.2:明确问“我说过/你说过/他说的”时,只留下说话人对得上的条目;
1338
1526
  // 没有 speaker 字段的旧条目保留,避免一次查询把历史记忆全清空。
1339
1527
  .filter((f) => speakerMatchesFilter(f.entry, ctx.speakerFilter))
1340
1528
  .map((f, i) => ({ ...f, score: recallScore(f, i, ctx), retrieval: retrievalShare(f, i) }))
1341
1529
  .sort((a, b) => b.score - a.score)
1342
- const { chosen, skipped } = mmrSelect(cutWeakScores(items, ctx.relevanceThreshold, ctx.retrievalFloor), max)
1530
+ const { chosen, skipped } = mmrSelect(mmrPool(cutWeakScores(items, ctx.relevanceThreshold, ctx.retrievalFloor, recallPercentile()), max), max)
1343
1531
  // Observation for the dedup thresholds : candidate folding
1344
1532
  // (①②) reports through result.fusion, the ranking-level hard skips (③) come back
1345
1533
  // from mmrSelect. One merged list — without it, a mistuned threshold eats real
@@ -1352,18 +1540,18 @@ function privateWeighted(result, max, context = {}) {
1352
1540
  /**
1353
1541
  * Greedy maximal marginal relevance over already-scored files.
1354
1542
  *
1355
- * Similarity is lexical on purpose (dice over title+body bigrams, the same shared
1356
- * ruler the write-side duplicate gate uses): it must be cheap enough to run on every
1357
- * recall and predictable enough to explain. An embedding version would need a second
1358
- * engine round trip just to de-duplicate four lines.
1543
+ * Similarity is lexical on purpose (slot-aware title+body similarity, the same
1544
+ * shared ruler the write-side duplicate gate uses): it must be cheap enough to run
1545
+ * on every recall and predictable enough to explain. An embedding version would
1546
+ * need a second engine round trip just to de-duplicate four lines.
1359
1547
  *
1360
1548
  * Two bands :
1361
- * · dice >= DUP_DICE — the candidate describes a fact something already chosen
1362
- * describes: it is never selected, only reported as `skipped`. A soft penalty
1363
- * cannot bound how many seats one fact takes; this can.
1364
- * · TOPIC_DICE <= dice < DUP_DICE — same topic, different fact: the existing soft
1549
+ * · score >= DUP_DICE — the candidate describes a fact something already chosen
1550
+ * describes: it is never selected, only reported as `skipped`.
1551
+ * · TOPIC_DICE <= score < DUP_DICE — same topic, different fact: the existing soft
1365
1552
  * penalty (lambda x overlap x ceiling) still applies.
1366
- * Below TOPIC_DICE the two memories do not interact.
1553
+ * Below TOPIC_DICE the two memories do not interact. A number/date/time/name change
1554
+ * caps the score below TOPIC_DICE, so a revised fact keeps its own seat.
1367
1555
  */
1368
1556
  function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1369
1557
  const limit = Number(max || 0)
@@ -1371,13 +1559,21 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1371
1559
  if (items.length <= 1) return { chosen: items.slice(0, limit), skipped: [] }
1372
1560
  const chosen = []
1373
1561
  const pool = items.slice()
1374
- const gramsCache = new Map()
1375
- const gramsOf = (file) => {
1562
+ const textCache = new Map()
1563
+ const textOf = (file) => {
1376
1564
  const key = file.name
1377
- if (gramsCache.has(key)) return gramsCache.get(key)
1378
- const set = bigrams(String(file.entry?.title || '') + ' ' + String(file.entry?.content || ''))
1379
- gramsCache.set(key, set)
1380
- return set
1565
+ if (textCache.has(key)) return textCache.get(key)
1566
+ const text = `${file.entry?.title || ''} ${file.entry?.content || ''}`
1567
+ textCache.set(key, text)
1568
+ return text
1569
+ }
1570
+ const pairCache = new Map()
1571
+ const similarityOf = (a, b) => {
1572
+ const key = a.name < b.name ? `${a.name}\u0000${b.name}` : `${b.name}\u0000${a.name}`
1573
+ if (pairCache.has(key)) return pairCache.get(key)
1574
+ const value = similarTexts(textOf(a), textOf(b))
1575
+ pairCache.set(key, value)
1576
+ return value
1381
1577
  }
1382
1578
  // Anchor the penalty to the best raw score so the diversity term is on the same
1383
1579
  // scale as relevance instead of being dominated by it.
@@ -1392,7 +1588,7 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1392
1588
  let overlap = 0
1393
1589
  let twin = null
1394
1590
  for (const picked of chosen) {
1395
- const similarity = dice(gramsOf(pool[i]), gramsOf(picked))
1591
+ const similarity = similarityOf(pool[i], picked)
1396
1592
  if (similarity >= DUP_DICE) { twin = picked.name; break }
1397
1593
  if (similarity >= TOPIC_DICE) overlap = Math.max(overlap, similarity)
1398
1594
  }
@@ -1733,7 +1929,12 @@ async function privateRememberImpl({
1733
1929
  salientDate: normalizedSalientDate,
1734
1930
  ...temporal,
1735
1931
  ...provenance,
1736
- ...(factKeyValue ? { fact_key: factKeyValue, version } : {}),
1932
+ ...(factKeyValue ? {
1933
+ fact_key: factKeyValue,
1934
+ version,
1935
+ fact_authority: factAuthorityOf(effectiveSourceKind),
1936
+ ...(quote ? { fact_evidence: quote } : {}),
1937
+ } : {}),
1737
1938
  ...(relationKind === 'conflict' && relationId ? { conflicts_with: relationId } : {}),
1738
1939
  ...(relationKind === 'supersede' && relationId ? { supersedes: relationId } : {}),
1739
1940
  }
@@ -1755,7 +1956,9 @@ async function privateRememberImpl({
1755
1956
  entry.conflictingWith = conflict.id
1756
1957
  entry.reviewReason = conflict.reason === 'same_title'
1757
1958
  ? `与已有记忆「${clampText(conflict.entry.title || conflict.id, 60)}」同题但内容不同`
1758
- : `与已有记忆「${clampText(conflict.entry.title || conflict.id, 60)}」说法相反`
1959
+ : conflict.reason === 'slot_conflict'
1960
+ ? `与已有记忆「${clampText(conflict.entry.title || conflict.id, 60)}」同题但数字/日期/时间或专名发生了变化`
1961
+ : `与已有记忆「${clampText(conflict.entry.title || conflict.id, 60)}」说法相反`
1759
1962
  }
1760
1963
  // Fact-level duplicate gate . Strictly AFTER the conflict
1761
1964
  // check — in the same-title band a contradictory rewording must land as
@@ -1835,10 +2038,13 @@ async function privateRememberImpl({
1835
2038
  // the review later is what commits it (see resolveReview → privateUpdate).
1836
2039
  const route = engineRoute()
1837
2040
  const db = route !== 'lexical' && !conflict ? memoryDbPath(scope.libraryId) : null
1838
- const result = db
1839
- ? await commit({ payload, route, db })
1840
- : { ok: true, backend: route, held: conflict ? true : undefined }
2041
+ const commitOutcome = db
2042
+ ? await commitPrivatePayload({ payload, route, db, libraryId: scope.libraryId, id })
2043
+ : { result: { ok: true, backend: route, held: conflict ? true : undefined }, committedDb: null, warning: null }
2044
+ const result = commitOutcome.result
1841
2045
  try {
2046
+ if (commitOutcome.warning) entry.vectorPending = true
2047
+ else delete entry.vectorPending
1842
2048
  // 记下"这条进没进向量库":只有真的带代际提交成功才写,冲突暂扣/降级都不写。
1843
2049
  // 之前没有任何字段能回答"哪条记忆进向量库了",只能靠猜。
1844
2050
  if (route !== 'lexical' && !conflict && result?.ok !== false && !result?.parseWarning) {
@@ -1855,7 +2061,7 @@ async function privateRememberImpl({
1855
2061
  ? null
1856
2062
  : findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1857
2063
  if (latestConflict && !conflict) {
1858
- if (db) throw new Error('memory conflict changed during write; retry for review')
2064
+ if (commitOutcome.committedDb) throw new Error('memory conflict changed during write; retry for review')
1859
2065
  entry.status = 'pending_review'
1860
2066
  entry.conflictingWith = latestConflict.id
1861
2067
  entry.reviewReason = 'concurrent conflicting memory; review required'
@@ -1869,7 +2075,7 @@ async function privateRememberImpl({
1869
2075
  id, title: entry.title, content: entry.content, context: entry.context, sessionId: memorySession,
1870
2076
  })
1871
2077
  if (latestDuplicate.hidden || (latestDuplicate.duplicate && latestDuplicate.duplicate.similarity >= DUP_REJECT_DICE)) {
1872
- if (db) throw new Error('memory duplicate changed during write; retry')
2078
+ if (commitOutcome.committedDb) throw new Error('memory duplicate changed during write; retry')
1873
2079
  entry.status = 'pending_review'
1874
2080
  entry.reviewReason = 'near_duplicate'
1875
2081
  entry.conflictingWith = latestDuplicate.duplicate?.id || null
@@ -1898,7 +2104,7 @@ async function privateRememberImpl({
1898
2104
  }
1899
2105
  }))
1900
2106
  } catch (error) {
1901
- if (db) await compensatePrivateCommit(error, { libraryId: scope.libraryId, id, route, db, expectedEntry: previousHabit?.[1] || null })
2107
+ if (commitOutcome.committedDb) await compensatePrivateCommit(error, { libraryId: scope.libraryId, id, route, db: commitOutcome.committedDb, expectedEntry: previousHabit?.[1] || null })
1902
2108
  throw error
1903
2109
  }
1904
2110
  if (!previousHabit) bumpStats(scope.libraryId, 'written')
@@ -1912,7 +2118,7 @@ async function privateRememberImpl({
1912
2118
  // writes the index directly instead of going through privateRemember: the pin cap,
1913
2119
  // the short-term deadline and the "no duplicate text" check would otherwise turn a
1914
2120
  // faithful restore into a pile of downgrades.
1915
- async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now = Date.now() }) {
2121
+ async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now = Date.now(), importBatchId = null }) {
1916
2122
  const library = getLibrary(libraryId)
1917
2123
  if (!library) throw new Error('library not found')
1918
2124
  const list = Array.isArray(memories) ? memories : []
@@ -2012,6 +2218,7 @@ async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now =
2012
2218
  source: typeof item.source === "string" && item.source ? item.source : "imported",
2013
2219
  confidence: Number.isFinite(Number(item.confidence)) ? Math.max(0, Math.min(1, Number(item.confidence))) : 0.8,
2014
2220
  status: "active",
2221
+ ...(importBatchId ? { importedBundle: String(importBatchId) } : {}),
2015
2222
  moodValence: Number.isFinite(Number(item.moodValence)) ? Math.max(-1, Math.min(1, Number(item.moodValence))) : 0,
2016
2223
  arousal: Number.isFinite(Number(item.arousal)) ? Math.max(0, Math.min(1, Number(item.arousal))) : 0.35,
2017
2224
  peak: item.peak === true,
@@ -2123,7 +2330,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
2123
2330
  for (const source of sources) {
2124
2331
  const scoped = source.primary ? source.index : domainScopedIndex(source.index, domain)
2125
2332
  if (route === 'lexical' || byId) {
2126
- lists.push({ libraryId: source.libraryId, files: localRecall(scoped, query).files })
2333
+ lists.push({ libraryId: source.libraryId, files: localRecall(scoped, query, undefined, { cacheKey: `lib:${source.libraryId}:${domain || 'all'}`, topK }).files })
2127
2334
  continue
2128
2335
  }
2129
2336
  const managed = await managedRecall({
@@ -2202,7 +2409,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2202
2409
  // exists when another qualifying library is actually present.
2203
2410
  const result = sources.length === 1
2204
2411
  ? (route === 'lexical' || byId
2205
- ? { ...localRecall(sources[0].index, searchQuery), recallRoute: 'local' }
2412
+ ? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK: wanted }), recallRoute: 'local' }
2206
2413
  : await managedRecall({ exec, index: sources[0].index, query: searchQuery, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2207
2414
  : await recallCrossLibrary({ exec, sources, query: searchQuery, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
2208
2415
  const current = peekBinding(exec)
@@ -2255,6 +2462,11 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2255
2462
  })
2256
2463
  // S2:命中冲突的一侧时,把另一侧也带上。两条都保留、都 active,注入层会把
2257
2464
  // 它们渲染成一张“未确认哪版为准”的冲突卡;这里只保证成对出现。
2465
+ //
2466
+ // 座位是共享的,不是白送的:一半的矛盾读起来像一条已定论的事实,比不召回更糟,
2467
+ // 所以配对优先于「最后一条边缘记忆」。追加完之后按需从尾部挤掉**没有配对**的
2468
+ // 条目,让 files.length 回到 wanted。只剩配对时挤不动——那时配对更重要,并且
2469
+ // 会留下一条可观测记录,而不是让「不变量」在无人知晓的地方破掉。
2258
2470
  const paired = new Set((scored.files || []).map((file) => file.name))
2259
2471
  const conflictPairs = []
2260
2472
  for (const file of (scored.files || []).slice()) {
@@ -2276,7 +2488,34 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2276
2488
  paired.add(otherId)
2277
2489
  conflictPairs.push({ a: file.name, b: otherId })
2278
2490
  }
2279
- if (conflictPairs.length) scored.conflictPairs = conflictPairs
2491
+ if (conflictPairs.length) {
2492
+ scored.conflictPairs = conflictPairs
2493
+ const seatBudget = Math.max(1, Number(wanted) || scored.files.length)
2494
+ while (scored.files.length > seatBudget) {
2495
+ let victim = -1
2496
+ for (let i = scored.files.length - 1; i >= 0; i -= 1) {
2497
+ if (scored.files[i]?.conflictPair) continue
2498
+ victim = i
2499
+ break
2500
+ }
2501
+ if (victim === -1) break
2502
+ scored.files.splice(victim, 1)
2503
+ }
2504
+ // Everything left is a half of a pair: the block is bigger than topK and the user
2505
+ // is about to pay for it. Say so once, with numbers, instead of letting it look
2506
+ // like a rounding error in the token budget.
2507
+ if (scored.files.length > seatBudget) {
2508
+ record({
2509
+ kind: 'recall',
2510
+ scope: 'private',
2511
+ sessionId: memorySessionId(exec),
2512
+ libraryId: binding.libraryId,
2513
+ message: `冲突对超出座位预算:${scored.files.length} 条 > topK ${seatBudget}`,
2514
+ detail: { wanted: seatBudget, delivered: scored.files.length, pairs: conflictPairs.length },
2515
+ refs: conflictPairs.map((pair) => pair.a).slice(0, 20),
2516
+ })
2517
+ }
2518
+ }
2280
2519
  // Being recalled is being used, and a memory that keeps being used should not fade
2281
2520
  // like one nobody ever touches. Group by the library each hit came from so a
2282
2521
  // cross-library recall touches the owning index, not the bound one.
@@ -2315,14 +2554,24 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2315
2554
  }
2316
2555
  try { file.related = recallRelations(fileLibraryId, fileIndex, file.name, memorySessionId(exec)) } catch { file.related = [] }
2317
2556
  }
2318
- // S5 多跳:沿显式 links 扩展一跳(人物/事件/时间线索),最多 2 条;实体题放宽到 3 条。
2319
- // 只沿已经存在的链接走,不按文本相似度猜关系。
2320
- const expansionLimit = recallIntent === 'entity' ? 3 : 2
2557
+ // S5 多跳:沿显式 links 扩展一跳(人物/事件/时间线索),但只补 topK 的空位。
2558
+ // 已经选满时不再追加:图扩展不额外占用注入预算。冲突对(S2)在更早一步成对
2559
+ // 带回,它们属于既有语义,不计入这里的扩展额度。
2560
+ const expansionRoom = Math.max(0, Number(wanted) - scored.files.length)
2561
+ const expansionLimit = Math.min(recallIntent === 'entity' ? 3 : 2, expansionRoom)
2321
2562
  const knownIds = new Set(scored.files.map((file) => file.name))
2322
2563
  const expanded = []
2564
+ // One hop is a guess: "the query hit this, and this is linked to it". A relation
2565
+ // whose retention has decayed below the floor is a guess about something the user
2566
+ // stopped caring about, and spending one of the two expansion seats on it costs a
2567
+ // memory that actually matched. The floor is deliberately low — this filters dead
2568
+ // edges, it does not rank friendships.
2569
+ const EXPANSION_RETENTION_FLOOR = 0.2
2323
2570
  for (const file of scored.files.slice()) {
2571
+ if (expanded.length >= expansionLimit) break
2324
2572
  for (const link of file.related || []) {
2325
2573
  if (!link?.id || link.missing || knownIds.has(link.id)) continue
2574
+ if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
2326
2575
  const fileLibraryId = file.libraryId || binding.libraryId
2327
2576
  const fileIndex = indexByLibrary.get(fileLibraryId) || index
2328
2577
  const target = fileIndex.entries[link.id]
@@ -2343,7 +2592,6 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2343
2592
  expanded.push({ from: file.name, to: link.id, kind: link.kind || 'related' })
2344
2593
  if (expanded.length >= expansionLimit) break
2345
2594
  }
2346
- if (expanded.length >= expansionLimit) break
2347
2595
  }
2348
2596
  if (expanded.length) scored.expanded = expanded
2349
2597
  if (sources.length > 1) scored.libraries = sources.map((source) => source.libraryId)
@@ -2526,6 +2774,8 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2526
2774
  const route = engineRoute()
2527
2775
  const managed = route === 'managed-local'
2528
2776
  let committedDb = null
2777
+ let commitWarning = null
2778
+ let commitAttempted = false
2529
2779
  if ((nextContent !== undefined || managed) && entry.status !== 'pending_review' && status !== 'pending_review') {
2530
2780
  const payload = {
2531
2781
  recall_files: [{
@@ -2539,8 +2789,10 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2539
2789
  }
2540
2790
  if (route !== 'lexical') {
2541
2791
  const db = memoryDbPath(scope.libraryId)
2542
- await commit({ payload, route, db })
2543
- committedDb = db
2792
+ commitAttempted = true
2793
+ const outcome = await commitPrivatePayload({ payload, route, db, libraryId: scope.libraryId, id: id_ })
2794
+ committedDb = outcome.committedDb
2795
+ commitWarning = outcome.warning
2544
2796
  }
2545
2797
  }
2546
2798
  let updated
@@ -2611,6 +2863,13 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2611
2863
  target.source_kind = sourceKind
2612
2864
  if (source === undefined) target.source = sourceKind
2613
2865
  if (speakerId === undefined && target.speaker_id === undefined) target.speaker_id = defaultSpeakerFor(sourceKind)
2866
+ } else if (source !== undefined) {
2867
+ // Correcting only `source` must not leave the old source_kind (and its
2868
+ // authority) behind: the two fields are the same provenance claim.
2869
+ target.source_kind = source
2870
+ }
2871
+ if (source !== undefined || sourceKind !== undefined) {
2872
+ target.fact_authority = factAuthorityOf(target.source_kind ?? target.source)
2614
2873
  }
2615
2874
  if (speakerId !== undefined) {
2616
2875
  const speaker = speakerId === null ? null : String(speakerId).trim()
@@ -2620,8 +2879,13 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2620
2879
  }
2621
2880
  if (quoteSpan !== undefined) {
2622
2881
  const span = normalizeQuoteSpan(quoteSpan)
2623
- if (span) target.quote_span = span
2624
- else delete target.quote_span
2882
+ if (span) {
2883
+ target.quote_span = span
2884
+ target.fact_evidence = span
2885
+ } else {
2886
+ delete target.quote_span
2887
+ delete target.fact_evidence
2888
+ }
2625
2889
  }
2626
2890
  if (storylineId !== undefined) {
2627
2891
  const storyline = storylineId === null ? null : String(storylineId).trim()
@@ -2715,6 +2979,8 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2715
2979
  if (nextAttachments !== undefined) target.attachments = nextAttachments
2716
2980
  // 受管路由下这次更新把这一行重新提交进了当前向量空间(managed 时 commit 无条件发生)。
2717
2981
  // 戳要跟着刷新:它现在描述的是"这条在当前代际的空间里",membership 的戳腿靠它计数。
2982
+ if (commitWarning) target.vectorPending = true
2983
+ else if (commitAttempted && committedDb) delete target.vectorPending
2718
2984
  if (committedDb) {
2719
2985
  const vector = activeEntryStamp(route)
2720
2986
  if (vector) target.vector = vector
@@ -3055,6 +3321,132 @@ export function privateArchive({ exec, libraryId, id }) {
3055
3321
  * is still in the index and no longer in the engine — visible in the browser, still
3056
3322
  * deletable, never recalled from a ghost row.
3057
3323
  */
3324
+ const DELETED_KEEP = 50
3325
+ // A permanent delete keeps a short, local undo buffer. It is not an archive: the
3326
+ // body must not live forever on disk or travel into backups. Entries without a
3327
+ // usable deletedAt (or older than the TTL) are dropped on every read and write.
3328
+ const DELETED_TTL_MS = 7 * 24 * 60 * 60 * 1000
3329
+ function liveDeletedItems(items, now = Date.now()) {
3330
+ return Object.fromEntries(Object.entries(items || {}).filter(([, item]) => {
3331
+ const at = Date.parse(item?.deletedAt || '')
3332
+ return Number.isFinite(at) && now - at < DELETED_TTL_MS && item?.entry
3333
+ }))
3334
+ }
3335
+ function deletedStorePath(libraryId) {
3336
+ return path.join(indexDir(), `${libraryId}.deleted.json`)
3337
+ }
3338
+
3339
+ function readDeletedStore(libraryId) {
3340
+ try {
3341
+ const value = readJson(deletedStorePath(libraryId), { items: {} })
3342
+ if (!value?.items || typeof value.items !== 'object' || Array.isArray(value.items)) return { items: {} }
3343
+ return { items: liveDeletedItems(value.items) }
3344
+ } catch {
3345
+ return { items: {} }
3346
+ }
3347
+ }
3348
+
3349
+ function writeDeletedStore(libraryId, store) {
3350
+ const kept = Object.entries(liveDeletedItems(store.items))
3351
+ .sort((a, b) => String(a[1]?.deletedAt || '').localeCompare(String(b[1]?.deletedAt || '')) || a[0].localeCompare(b[0]))
3352
+ .slice(-DELETED_KEEP)
3353
+ writeJson(deletedStorePath(libraryId), { items: Object.fromEntries(kept) })
3354
+ }
3355
+
3356
+ /** Sweep expired undo buffers across every library. Called by the startup
3357
+ * sweep, so a library that is never deleted from still gets its stash cleaned. */
3358
+ export function pruneDeletedStores({ now = Date.now() } = {}) {
3359
+ const result = { scanned: 0, removed: 0, failed: [] }
3360
+ let names = []
3361
+ try { names = fs.readdirSync(indexDir()).filter(name => name.endsWith('.deleted.json')) } catch { return result }
3362
+ for (const name of names) {
3363
+ const id = name.slice(0, -'.deleted.json'.length)
3364
+ try {
3365
+ const file = path.join(indexDir(), name)
3366
+ const raw = readJson(file, { items: {} })
3367
+ const before = Object.keys(raw?.items || {}).length
3368
+ const items = liveDeletedItems(raw?.items, now)
3369
+ result.scanned += 1
3370
+ result.removed += before - Object.keys(items).length
3371
+ if (before !== Object.keys(items).length) writeJson(file, { items })
3372
+ } catch (error) {
3373
+ result.failed.push({ libraryId: id, error: String(error?.message || error) })
3374
+ }
3375
+ }
3376
+ return result
3377
+ }
3378
+
3379
+ /** P2-4: a read-only delete plan; the browser can show what would be swept. */
3380
+ export function previewDelete({ exec, libraryId, id }) {
3381
+ const scope = resolveLibrary({ exec, libraryId, readOnly: true })
3382
+ const index = loadPrivateIndex(scope.libraryId)
3383
+ const id_ = resolveEntryId(index, id)
3384
+ const entry = index.entries[id_]
3385
+ if (!entry) throw new Error(`unknown memory: ${id_}`)
3386
+ if (sessionIdOf(exec)) assertEntryAccess(entry, exec)
3387
+ const inboundLinks = Object.values(index.entries).filter((other) => other
3388
+ && (other.links || []).some((link) => link?.to === id_)).length
3389
+ const deletable = ['archived', 'suppressed', 'expired'].includes(entry.status)
3390
+ return {
3391
+ id: id_, libraryId: scope.libraryId, title: entry.title || '', status: entry.status,
3392
+ deletable,
3393
+ reason: deletable ? null : 'only archived memories can be deleted permanently; archive it first',
3394
+ attachments: Array.isArray(entry.attachments) ? entry.attachments.length : 0,
3395
+ inboundLinks,
3396
+ plan: { deleteFromIndex: true, forgetFromVector: engineRoute() !== 'lexical', cascadeLinks: inboundLinks },
3397
+ }
3398
+ }
3399
+
3400
+ /** P2-4: restore the most recent permanently deleted version kept in the local stash. */
3401
+ export async function restoreDeleted({ exec, libraryId, id }) {
3402
+ const scope = resolveLibrary({ exec, libraryId })
3403
+ if (scope.binding) assertScopeEnabled(scope.binding)
3404
+ const id_ = String(id || '').trim()
3405
+ if (!id_) throw new Error('memory id is required')
3406
+ return withManagedPrivateWrite(scope.libraryId, async () => {
3407
+ const store = readDeletedStore(scope.libraryId)
3408
+ const item = store.items[id_]
3409
+ if (!item?.entry) throw new Error('no deleted memory with that id')
3410
+ const index = loadPrivateIndex(scope.libraryId)
3411
+ if (index.entries[id_]) throw new Error('a memory with that id already exists')
3412
+ const route = engineRoute()
3413
+ const restored = {
3414
+ ...item.entry,
3415
+ status: 'active',
3416
+ restoredAt: stamp(),
3417
+ updatedAt: stamp(),
3418
+ ...(route !== 'lexical' ? { vectorPending: true } : {}),
3419
+ }
3420
+ await retryStoreWrite(() => updatePrivateIndex(scope.libraryId, (fresh) => {
3421
+ if (fresh.entries[id_]) throw new Error('memory id was restored concurrently; retry')
3422
+ fresh.entries[id_] = restored
3423
+ }))
3424
+ if (route !== 'lexical') {
3425
+ const outcome = await commitPrivatePayload({
3426
+ payload: {
3427
+ recall_files: [{ name: id_, track: restored.track || 'memory', description: clampText(restored.title, 180), content: restored.content }],
3428
+ resource: [], user: {},
3429
+ },
3430
+ route, db: memoryDbPath(scope.libraryId), libraryId: scope.libraryId, id: id_,
3431
+ })
3432
+ await retryStoreWrite(() => updatePrivateIndex(scope.libraryId, (fresh) => {
3433
+ const target = fresh.entries[id_]
3434
+ if (!target) return
3435
+ if (outcome.warning) target.vectorPending = true
3436
+ else {
3437
+ delete target.vectorPending
3438
+ const vector = activeEntryStamp(route)
3439
+ if (vector) target.vector = vector
3440
+ }
3441
+ }))
3442
+ }
3443
+ delete store.items[id_]
3444
+ try { writeDeletedStore(scope.libraryId, store) } catch (error) { warn(`restore deleted: stash rewrite skipped: ${error?.message || error}`) }
3445
+ record({ kind: 'write', scope: 'private', libraryId: scope.libraryId, message: '恢复已删除记忆 ' + id_, detail: { id: id_ }, refs: [id_] })
3446
+ return { id: id_, libraryId: scope.libraryId, entry: loadPrivateIndex(scope.libraryId).entries[id_] || restored }
3447
+ })
3448
+ }
3449
+
3058
3450
  async function privateDeleteImpl({ exec, libraryId, id }) {
3059
3451
  const scope = resolveLibrary({ exec, libraryId })
3060
3452
  if (scope.binding) assertScopeEnabled(scope.binding)
@@ -3084,8 +3476,22 @@ async function privateDeleteImpl({ exec, libraryId, id }) {
3084
3476
  if (Array.isArray(other.links) && other.links.some(link => link.to === id_)) {
3085
3477
  other.links = other.links.filter(link => link.to !== id_)
3086
3478
  }
3479
+ // duplicateOf is a soft penalty on one row that points at another. Without
3480
+ // this, permanently deleting the host leaves the copy paying ×0.7 forever
3481
+ // with no UI path to clear the dangling tag.
3482
+ if (other.duplicateOf === id_) delete other.duplicateOf
3087
3483
  }
3088
3484
  }))
3485
+ // Keep a small local stash so a permanent delete is reversible from the browser
3486
+ // without restoring a whole backup. The entry is already out of the index; a
3487
+ // stash write failure is only a lost undo, not a failed delete.
3488
+ try {
3489
+ const store = readDeletedStore(scope.libraryId)
3490
+ store.items[id_] = { entry, deletedAt: stamp() }
3491
+ writeDeletedStore(scope.libraryId, store)
3492
+ } catch (error) {
3493
+ warn(`deleted memory stash skipped: ${error?.message || error}`)
3494
+ }
3089
3495
  // Collect entities this row was the last thing keeping alive. Cleanup after
3090
3496
  // the fact, not a correctness step: if it fails (lock contention, a store
3091
3497
  // another writer holds) the delete stands, and the startup sweep gets the
@@ -3221,6 +3627,126 @@ export async function importMemories(args) {
3221
3627
  return result
3222
3628
  }
3223
3629
 
3630
+ // ------------------------------------------------------------- import batches
3631
+ //
3632
+ // One import can create memories, graph entities and lexicon terms. "Undo the package"
3633
+ // has to undo all three, and the index tag alone cannot do it: entities and terms live
3634
+ // in other stores and carry no memory id. This ledger is the batch's manifest of what
3635
+ // it created — written once per import, and the only reason a revert can promise
3636
+ // "exactly this package" instead of "whatever happens to be tagged".
3637
+ //
3638
+ // `pendingForget` is the other half. The engine (MemU) is a separate store with no
3639
+ // transactions of its own, so a forget that fails there leaves a row the index no
3640
+ // longer knows about. It is recorded here rather than only warned about: a warn in a
3641
+ // log nobody reads is not a cleanup strategy, and the next revert (or the startup
3642
+ // sweep) retries it.
3643
+ const importLedgerFile = (libraryId) => path.join(indexDir(), `${libraryId}.imports.json`)
3644
+
3645
+ function readImportLedger(libraryId) {
3646
+ const raw = readJson(importLedgerFile(libraryId), null)
3647
+ const batches = raw && typeof raw === 'object' && raw.batches && typeof raw.batches === 'object' && !Array.isArray(raw.batches)
3648
+ ? raw.batches
3649
+ : {}
3650
+ return { version: 1, batches }
3651
+ }
3652
+
3653
+ function writeImportLedger(libraryId, ledger) {
3654
+ try {
3655
+ writeJson(importLedgerFile(libraryId), { version: 1, batches: ledger.batches || {} })
3656
+ return true
3657
+ } catch (error) {
3658
+ // Fail-open on purpose: the memories still revert from the index tag, and losing
3659
+ // the ledger costs the graph/lexicon half, not the whole undo.
3660
+ warn(`import ledger for ${libraryId} could not be written: ${error?.message || error}`)
3661
+ return false
3662
+ }
3663
+ }
3664
+
3665
+ /** Remember what one import batch created, so it can be undone precisely. */
3666
+ export function recordImportBatch({ libraryId, batchId, memories = [], entities = [], lexicon = [] }) {
3667
+ const id = String(batchId || '').trim()
3668
+ if (!libraryId || !id) return false
3669
+ const ledger = readImportLedger(libraryId)
3670
+ ledger.batches[id] = {
3671
+ at: stamp(),
3672
+ memories: memories.map(String).slice(0, 20000),
3673
+ entities: entities.map(String).slice(0, 4000),
3674
+ lexicon: lexicon.map(String).slice(0, 10000),
3675
+ }
3676
+ return writeImportLedger(libraryId, ledger)
3677
+ }
3678
+
3679
+ /**
3680
+ * P2-2: undo one import batch.
3681
+ *
3682
+ * Memories are found by their `importedBundle` tag, which a later user edit does not
3683
+ * strip, so the whole installed package rolls back without touching pre-existing
3684
+ * memories. Entities and lexicon terms come from the ledger. Attachment blobs are
3685
+ * content-addressed and shared, so they are left to the normal orphan/GC path rather
3686
+ * than deleted here — a revert that removed a blob another memory still points at
3687
+ * would be data loss disguised as cleanup. No text is injected anywhere.
3688
+ */
3689
+ export async function revertImportBatch({ libraryId, batchId }) {
3690
+ if (!libraryId || !getLibrary(libraryId)) throw new Error('library not found')
3691
+ const id = String(batchId || '').trim()
3692
+ if (!id) throw new Error('revertBatchId is required')
3693
+ return withManagedPrivateWrite(libraryId, async () => {
3694
+ const ledger = readImportLedger(libraryId)
3695
+ const batch = ledger.batches[id] || null
3696
+ const index = loadPrivateIndex(libraryId)
3697
+ const ids = Object.entries(index.entries || {})
3698
+ .filter(([, entry]) => entry?.importedBundle === id)
3699
+ .map(([memoryId]) => memoryId)
3700
+ // A previous revert may have left engine rows behind. Retrying them here keeps the
3701
+ // leak bounded by "one failed attempt between sweeps" instead of "forever".
3702
+ const deferredBefore = Array.isArray(batch?.pendingForget) ? batch.pendingForget : []
3703
+ const pendingForget = []
3704
+ if (engineRoute() !== 'lexical') {
3705
+ const route = engineRoute()
3706
+ const db = memoryDbPath(libraryId)
3707
+ for (const memoryId of [...new Set([...ids, ...deferredBefore])]) {
3708
+ try { await forget({ route, db, name: memoryId }) } catch (error) {
3709
+ pendingForget.push(memoryId)
3710
+ warn(`revert import: backend forget deferred for ${memoryId}: ${error?.message || error}`)
3711
+ }
3712
+ }
3713
+ }
3714
+ if (ids.length) {
3715
+ await retryStoreWrite(() => updatePrivateIndex(libraryId, (fresh) => {
3716
+ for (const memoryId of ids) {
3717
+ if (fresh.entries[memoryId]?.importedBundle === id) delete fresh.entries[memoryId]
3718
+ }
3719
+ }))
3720
+ }
3721
+ const entityIds = Array.isArray(batch?.entities) ? batch.entities : []
3722
+ const graph = entityIds.length ? revertGraphData({ libraryId, entityIds }) : { removed: [], failed: [] }
3723
+ // Keep the record only while it still has work left in it; anything fully undone is
3724
+ // dropped so the ledger cannot grow one entry per import forever.
3725
+ const leftover = { ...(batch || { at: stamp(), memories: [], lexicon: [] }), pendingForget, entities: graph.failed.map((item) => item.entityId) }
3726
+ if (!pendingForget.length && !leftover.entities.length) delete ledger.batches[id]
3727
+ else ledger.batches[id] = leftover
3728
+ writeImportLedger(libraryId, ledger)
3729
+ record({
3730
+ kind: 'write', scope: 'private', libraryId,
3731
+ message: `回滚导入批次 ${id}:移除 ${ids.length} 条记忆、${graph.removed.length} 个实体`,
3732
+ detail: { batchId: id, removed: ids.length, entities: graph.removed.length, pendingForget: pendingForget.length },
3733
+ refs: ids.slice(0, 20),
3734
+ })
3735
+ return {
3736
+ libraryId,
3737
+ batchId: id,
3738
+ removed: ids.length,
3739
+ ids,
3740
+ entities: graph.removed,
3741
+ entityFailures: graph.failed,
3742
+ // The caller owns the lexicon module (it is loaded lazily there), so the ids go
3743
+ // back in the response instead of memory.js reaching across for them.
3744
+ lexiconTermIds: Array.isArray(batch?.lexicon) ? batch.lexicon : [],
3745
+ pendingForget,
3746
+ }
3747
+ })
3748
+ }
3749
+
3224
3750
  export async function resolveMemoryReview(args) {
3225
3751
  const action = () => resolveMemoryReviewImpl(args)
3226
3752
  const result = args.libraryId ? await withManagedPrivateWrite(args.libraryId, action) : await withManagedGlobalWrite(action)
@@ -3266,14 +3792,15 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
3266
3792
  const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
3267
3793
  const queryDates = resolveQueryDates(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
3268
3794
  const searchQuery = queryDates.length ? `${query} ${queryDates.join(' ')}` : query
3795
+ const wanted = Number(topK || settings.globalTopK || 3)
3269
3796
  let index = loadGlobalIndex()
3270
3797
  const intent = managedVectorIntent()
3271
3798
  const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
3272
3799
  .filter(([, entry]) => appliesToDomain(entry, binding))) }
3273
3800
  const result = effectiveVectorRoute() !== 'lexical'
3274
- ? await managedRecall({ exec, index: domainIndex, query: searchQuery, topK: topK || settings.globalTopK || 3,
3801
+ ? await managedRecall({ exec, index: domainIndex, query: searchQuery, topK: wanted,
3275
3802
  libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
3276
- : localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding))
3803
+ : localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding), { cacheKey: `global:${domainOf(binding)}`, topK: wanted })
3277
3804
  if (peeked) {
3278
3805
  const current = peekBinding(exec)
3279
3806
  if (!current) throw new Error('memory binding changed during recall; retry')
@@ -3284,23 +3811,38 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
3284
3811
  if (result?.recallRoute) enriched.recallRoute = result.recallRoute
3285
3812
  if (result?.errors) enriched.errors = result.errors.slice()
3286
3813
  if (result?.fusion) enriched.fusion = result.fusion
3814
+ // Same ruler as private recall: `retrieval` is a share in (0, 1], never a raw BM25
3815
+ // score. Global's lexical leg returned the latter, so with relevanceThreshold = 0.8
3816
+ // a private runner-up at 0.75 survived while a global best of 5.4 and runner-up of
3817
+ // 0.9 had the runner-up cut outright — the same setting meant two different things
3818
+ // depending on which layer asked. Normalise against the best hit of this query.
3819
+ const bestLexical = enriched.files.reduce((max, f) => Math.max(max, Number(f.lexical) || 0), 0)
3287
3820
  const filtered = enriched.files
3288
3821
  .filter((f) => isMemoryEligible(f.entry, { automatic: true }))
3289
3822
  .filter((f) => appliesToDomain(f.entry, binding))
3290
- .map((f, i) => ({
3291
- ...f,
3292
- // Local lexical rank is already meaningful; confidence still nudges ties, and
3293
- // a cross-session fact that has been injected three turns running gets the same
3294
- // wear penalty as a private one. `retrieval` mirrors the retrieval term of the
3295
- // score so the absolute floor cut sees the same number the score was built from.
3296
- retrieval: Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1),
3297
- score: (Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1))
3298
- * (0.85 + 0.15 * Number(f.entry.confidence ?? 0.5))
3299
- * habituationFactor(f.entry)
3300
- * (queryDates.length && f.entry.absolute_date && queryDates.includes(f.entry.absolute_date) ? 1.35 : 1),
3301
- }))
3823
+ .map((f, i) => {
3824
+ const fused = Number(f.retrievalScore)
3825
+ const lexical = Number(f.lexical) || 0
3826
+ // Confidence still nudges ties, and a cross-session fact that has been injected
3827
+ // three turns running gets the same wear penalty as a private one. `retrieval`
3828
+ // mirrors the retrieval term of the score, so the absolute floor cut sees the
3829
+ // same number the score was built from.
3830
+ const retrieval = Number.isFinite(fused)
3831
+ ? Math.max(0, Math.min(1, fused))
3832
+ : lexical > 0 && bestLexical > 0
3833
+ ? lexical / bestLexical
3834
+ : 1 / (i + 1)
3835
+ return {
3836
+ ...f,
3837
+ retrieval,
3838
+ score: retrieval
3839
+ * (0.85 + 0.15 * Number(f.entry.confidence ?? 0.5))
3840
+ * habituationFactor(f.entry)
3841
+ * (queryDates.length && f.entry.absolute_date && queryDates.includes(f.entry.absolute_date) ? DATE_MATCH_FACTOR : 1),
3842
+ }
3843
+ })
3302
3844
  .sort((a, b) => b.score - a.score)
3303
- const ranked = mmrSelect(cutWeakScores(filtered, threshold, RETRIEVAL_FLOOR), Number(topK || settings.globalTopK || 3))
3845
+ const ranked = mmrSelect(mmrPool(cutWeakScores(filtered, threshold, RETRIEVAL_FLOOR, recallPercentile()), wanted), wanted)
3304
3846
  return {
3305
3847
  ...enriched,
3306
3848
  files: ranked.chosen,
@@ -3450,7 +3992,11 @@ export function noteInjected({ libraryId, ids = [], at = stamp() }) {
3450
3992
  entry.lastInjectAt = at
3451
3993
  touched += 1
3452
3994
  }
3453
- if (touched > 0) savePrivateIndex(libraryId, index)
3995
+ // Quiet write: being injected does not change what the next recall would find, and
3996
+ // the injector runs right after every successful recall. A revision bump here made
3997
+ // "recall -> inject -> write -> revision++ -> both recall caches miss" the steady
3998
+ // state of a dense conversation.
3999
+ if (touched > 0) savePrivateIndex(libraryId, index, { bumpRevision: false })
3454
4000
  if (touched > 0) bumpStats(libraryId, 'injected', touched)
3455
4001
  return touched
3456
4002
  }
@@ -3467,7 +4013,7 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
3467
4013
  entry.lastInjectAt = at
3468
4014
  touched += 1
3469
4015
  }
3470
- if (touched > 0) saveGlobalIndex(index)
4016
+ if (touched > 0) saveGlobalIndex(index, { bumpRevision: false })
3471
4017
  return touched
3472
4018
  }
3473
4019
 
@@ -3618,7 +4164,7 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
3618
4164
  if (!visibleToSession(entry, sessionId)) return false
3619
4165
  if (entry.sideEventId || entry.pinSource === 'side_event') return false
3620
4166
  // S6:cue 是自动浮现;only_if_asked / never_say 都要等用户先问。
3621
- if (entry.disclosure === 'never_say' || entry.disclosure === 'only_if_asked') return false
4167
+ if (!isDisclosureEligible(entry, { automatic: true, asked: false })) return false
3622
4168
  if (entry.visibility === 'secret') return false
3623
4169
  if (!String(entry.content || '').trim()) return false
3624
4170
  const at = Date.parse(entry.updatedAt || entry.createdAt || '')