dsh-memu-memory 1.2.7 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. 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,19 +11,24 @@ 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'
27
+ import { parseAbsoluteDate, parseTemporalExpression, hasTemporalHint, resolveQueryDates, localDateKeyInZone, DEFAULT_TIME_ZONE } from './temporal.js'
28
+ import { validitySignals } from './freshness.js'
29
+ import { commitmentOf, commitmentDueDate, commitmentDueState, isOpenThread, normalizeCommitment } from './commitment.js'
30
+ import { detectQueryIntent, decomposeQuery, buildCorpus, bm25, longestSharedToken, polarityAt, tokenize } from './text-retrieval.js'
31
+ import { intentTopK } from './budget.js'
26
32
 
27
33
  // P1-1 召回缓存。缓存自身出错时 fail-open,
28
34
  // 但真实故障必须留痕(AGENTS.md §1 规则 10):把缓存内部的吞没错误接到 warn 上。
@@ -59,6 +65,23 @@ const HYBRID_RRF_K = 60
59
65
  const HYBRID_CANDIDATE_MIN = 12
60
66
  const HYBRID_CANDIDATE_MAX = 40
61
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
62
85
  const LAYERS = ['long_term', 'short_term', 'must_remember']
63
86
  // These three are read back by the injector to decide how a memory may be spoken and
64
87
  // where it may appear. An unchecked typo would silently mean "no suffix at all", so
@@ -73,7 +96,10 @@ const VISIBILITIES = STORED_VISIBILITIES
73
96
  // quotable, everything else means they are our own reconstruction and must be hedged
74
97
  // when repeated. Defaulting to 'user_said' labelled every model-inferred memory as a
75
98
  // quote, which systematically inflated confidence in things nobody had said.
76
- const SOURCES = ['user_said', 'inferred', 'imagined', 'told']
99
+ // S3 追加 assistant_said / tool:助手自己说过的话、工具结果也必须可区分,不能混成
100
+ // 用户原话,也不能因为“只收用户消息”而丢掉。
101
+ const SOURCES = ['user_said', 'assistant_said', 'told', 'imagined', 'inferred', 'tool']
102
+ const SOURCE_KINDS = ['user_said', 'assistant_said', 'told', 'imagined', 'inferred', 'tool']
77
103
 
78
104
  function managedVectorIntent() {
79
105
  if (effectiveVectorRoute() !== 'managed-local') return { managed: false, route: effectiveVectorRoute(), state: null, error: null }
@@ -159,8 +185,32 @@ async function compensatePrivateCommit(error, { libraryId, id, route, db, expect
159
185
  throw error
160
186
  }
161
187
 
162
- async function withManagedPrivateWriteImpl(libraryId, action) {
163
- 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()
164
214
  if (!intent.managed) return action()
165
215
  // 选了本地向量、但下载完模型后从没跑过迁移(vector-active 只有 requested):这里
166
216
  // 没有可对齐的代际,写入必须降级成索引 + 引擎,而不是把整次整理写死。召回侧一直是
@@ -189,7 +239,7 @@ async function withManagedGlobalWrite(action) {
189
239
  }
190
240
 
191
241
  async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
192
- const local = localRecall(index, query)
242
+ const local = localRecall(index, query, undefined, { cacheKey: libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`, topK })
193
243
  try {
194
244
  if (intent.error) throw intent.error
195
245
  const captured = intent.route === 'managed-local' ? captureGeneration() : null
@@ -249,6 +299,129 @@ function checkEnums({ disclosure, owner, visibility, source }) {
249
299
  throw new Error(`source must be ${SOURCES.join(', ')}`)
250
300
  }
251
301
  }
302
+
303
+ function checkSourceKind(value) {
304
+ if (value !== undefined && value !== null && !SOURCE_KINDS.includes(value)) {
305
+ throw new Error(`source_kind must be ${SOURCE_KINDS.join(', ')}`)
306
+ }
307
+ }
308
+
309
+ function normalizeQuoteSpan(value) {
310
+ if (value === undefined || value === null) return null
311
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error('quote_span must be an object like {seq, turn, textHash}')
312
+ const span = {}
313
+ for (const key of ['seq', 'turn']) {
314
+ if (value[key] === undefined || value[key] === null) continue
315
+ const number = Number(value[key])
316
+ if (!Number.isSafeInteger(number) || number < 0) throw new Error(`quote_span.${key} must be a non-negative integer`)
317
+ span[key] = number
318
+ }
319
+ if (value.textHash !== undefined && value.textHash !== null) {
320
+ const hash = String(value.textHash)
321
+ if (!hash || hash.length > 128) throw new Error('quote_span.textHash must be a short string')
322
+ span.textHash = hash
323
+ }
324
+ return Object.keys(span).length ? span : null
325
+ }
326
+
327
+ function normalizeKnownBy(value) {
328
+ if (value === undefined || value === null) return undefined
329
+ if (!Array.isArray(value) || value.length > 30) throw new Error('known_by must be an array of at most 30 identities')
330
+ const result = []
331
+ for (const item of value) {
332
+ if (typeof item !== 'string' || !item.trim() || item.length > 128) throw new Error('known_by entries must be non-empty strings up to 128 characters')
333
+ if (!result.includes(item.trim())) result.push(item.trim())
334
+ }
335
+ return result
336
+ }
337
+
338
+ function defaultSpeakerFor(kind) {
339
+ if (kind === 'user_said') return 'user'
340
+ if (kind === 'assistant_said') return 'assistant'
341
+ if (kind === 'tool') return 'tool'
342
+ return 'unknown'
343
+ }
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
+
356
+ /** Old entries have no speaker_id/source_kind; derive the closest honest answer. */
357
+ export function speakerOfEntry(entry) {
358
+ if (!entry || typeof entry !== 'object') return 'unknown'
359
+ if (typeof entry.speaker_id === 'string' && entry.speaker_id.trim()) return entry.speaker_id.trim()
360
+ return defaultSpeakerFor(entry.source_kind || entry.source)
361
+ }
362
+
363
+ /**
364
+ * S3.2:查询里明确问“我说过/你说过/他说的”时,给召回一个说话人方向。
365
+ * 只排除“明确不是这个人”的条目;缺少 speaker 的旧条目保留,避免一次性清空召回。
366
+ */
367
+ export function detectSpeakerQuery(query) {
368
+ const text = String(query || '')
369
+ if (/(?:我(?:之前|先前)?(?:说过|说了|提过|讲过|问过|答应的?))/u.test(text)) return 'user'
370
+ if (/(?:你(?:之前|先前)?(?:说过|说了|提过|讲过|答应过|答应的?|承诺过))/u.test(text)) return 'assistant'
371
+ if (/(?:[他她](?:们)?(?:之前|先前)?(?:说过|说了|提过|讲到|讲了))/u.test(text)) return 'third'
372
+ return null
373
+ }
374
+
375
+ function speakerMatchesFilter(entry, filter) {
376
+ if (!filter) return true
377
+ const speaker = speakerOfEntry(entry)
378
+ if (speaker === 'unknown') return true
379
+ if (filter === 'user') return speaker === 'user'
380
+ if (filter === 'assistant') return speaker === 'assistant'
381
+ if (filter === 'third') return speaker !== 'user' && speaker !== 'assistant' && speaker !== 'tool'
382
+ return true
383
+ }
384
+
385
+ // S2:fact_key 是“同一条事实”的归一化键。显式键保留调用方的命名;没有显式键时
386
+ // 用 owner + 标题归一化,只用来给同一事实的多个版本编号,不改变旧的冲突判定。
387
+ export function normalizeFactKey(value) {
388
+ if (value === undefined || value === null) return null
389
+ const text = String(value).normalize('NFKC').trim().toLowerCase()
390
+ if (!text) return null
391
+ const cleaned = text.replace(/\s+/g, '_').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 200)
392
+ return cleaned || null
393
+ }
394
+
395
+ export function deriveFactKey({ owner = 'me', title = '', content = '' } = {}) {
396
+ const source = String(title || content || '').normalize('NFKC').toLowerCase()
397
+ const cleaned = source.replace(/[\s\p{P}\p{S}]+/gu, '').slice(0, 160)
398
+ if (!cleaned) return null
399
+ return `${String(owner || 'me').toLowerCase()}:${cleaned}`
400
+ }
401
+
402
+ function nextFactVersion(entries, factKey, context, excludeId = null) {
403
+ let max = 0
404
+ for (const [id, entry] of Object.entries(entries || {})) {
405
+ if (id === excludeId || !entry || entry.fact_key !== factKey) continue
406
+ if (!sameFactContext(entry.context, context)) continue
407
+ const version = Number(entry.version)
408
+ if (Number.isFinite(version)) max = Math.max(max, version)
409
+ }
410
+ return max + 1
411
+ }
412
+
413
+ function relationTarget(index, ref, { context, sessionId, label }) {
414
+ const targetId = resolveEntryId(index, ref)
415
+ const target = index.entries[targetId]
416
+ if (!target) throw new Error(`${label} target is missing: ${targetId}`)
417
+ if (['archived', 'suppressed', 'superseded', 'pending_review'].includes(target.status)) {
418
+ throw new Error(`${label} target ${targetId} is ${target.status}; only an active memory can be related to`)
419
+ }
420
+ if (!sameFactContext(target.context, context)) throw new Error(`${label} target belongs to another conversation scope`)
421
+ if (sessionId && !visibleForDedupe(target, sessionId)) throw new Error(`${label} target is not visible in this conversation`)
422
+ return { id: targetId, entry: target }
423
+ }
424
+
252
425
  // Below this, the present-mood read is noise and must not bend retrieval at all.
253
426
  const MOOD_MIN_STRENGTH = 0.15
254
427
  // Long enough that the reason has to say what happened and why it can be let go,
@@ -461,6 +634,79 @@ export function reconcileSalientDate(value, text, now = new Date()) {
461
634
  return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}-${pad2(target.getDate())}`
462
635
  }
463
636
 
637
+ function parseExplicitInstant(value, label) {
638
+ if (value === undefined || value === null || String(value).trim() === '') return null
639
+ const at = Date.parse(String(value))
640
+ if (!Number.isFinite(at)) throw new Error(`${label} must be an explicit ISO date/time`)
641
+ return new Date(at)
642
+ }
643
+
644
+ // The turn's logical time is the only clock a relative date may be resolved
645
+ // against. A user saying "明天" in a scene set in 1998 must not get the wall
646
+ // clock's tomorrow. Order: an explicit per-write stamp, the context's occurredAt,
647
+ // then the conversation's sceneTime, and only then the wall clock.
648
+ function sceneTimeOf({ binding, context, observedAt } = {}) {
649
+ return parseExplicitInstant(observedAt, 'observed_at')
650
+ || parseExplicitInstant(context?.occurredAt, 'occurred_at')
651
+ || parseExplicitInstant(binding?.sceneTime, 'scene_time')
652
+ || new Date()
653
+ }
654
+
655
+ function dateOnlyField(value, label) {
656
+ if (value === undefined) return undefined
657
+ if (value === null || String(value).trim() === '') return null
658
+ const normalized = parseAbsoluteDate(value)
659
+ if (!normalized) throw new Error(`${label} must be YYYY-MM-DD`)
660
+ return normalized
661
+ }
662
+
663
+ const DATE_PRECISIONS = ['day', 'month', 'year', 'unknown']
664
+
665
+ /**
666
+ * S1 的写入字段:event_time / observed_at / absolute_date / date_precision /
667
+ * valid_from / valid_to / date_source。原文不改写,日期只作为可检索的结构化字段。
668
+ * 解析失败不猜;只有确实出现相对时间词时才标 date_precision=unknown。
669
+ */
670
+ function temporalFieldsOf({ title, content, scene, salientDate, absoluteDate, validFrom, validTo, datePrecision }) {
671
+ if (datePrecision !== undefined && datePrecision !== null && !DATE_PRECISIONS.includes(datePrecision)) {
672
+ throw new Error(`date_precision must be ${DATE_PRECISIONS.join(', ')}`)
673
+ }
674
+ const fields = {
675
+ event_time: scene.toISOString(),
676
+ observed_at: scene.toISOString(),
677
+ }
678
+ const explicit = dateOnlyField(absoluteDate, 'absolute_date')
679
+ const fromSalient = isDatedSalientDate(salientDate) ? salientDate : null
680
+ if (explicit) {
681
+ fields.absolute_date = explicit
682
+ fields.date_precision = datePrecision || 'day'
683
+ fields.date_source = 'explicit'
684
+ } else if (fromSalient) {
685
+ fields.absolute_date = fromSalient
686
+ fields.date_precision = datePrecision || 'day'
687
+ fields.date_source = 'explicit'
688
+ } else {
689
+ const text = `${title || ''}\n${content || ''}`
690
+ const parsed = parseTemporalExpression(text, { now: scene, timeZone: DEFAULT_TIME_ZONE })
691
+ if (parsed) {
692
+ fields.absolute_date = parsed.absoluteDate
693
+ fields.date_precision = datePrecision || parsed.precision
694
+ fields.date_source = parsed.dateSource
695
+ } else if (hasTemporalHint(text)) {
696
+ fields.date_precision = 'unknown'
697
+ fields.date_source = 'relative'
698
+ }
699
+ }
700
+ const from = dateOnlyField(validFrom, 'valid_from')
701
+ const to = dateOnlyField(validTo, 'valid_to')
702
+ if (from) fields.valid_from = from
703
+ if (to) fields.valid_to = to
704
+ if (fields.valid_from && fields.valid_to && fields.valid_from > fields.valid_to) {
705
+ throw new Error('valid_from must not be after valid_to')
706
+ }
707
+ return fields
708
+ }
709
+
464
710
  // How many days ahead today is from a dated memory (0 = due today, negative =
465
711
  // already past). An anniversary has no distance: it is true every year.
466
712
  export function salientDaysAhead(salientDate, now = new Date()) {
@@ -600,7 +846,6 @@ const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
600
846
  export function findConflict(entries, candidate) {
601
847
  const title = String(candidate?.title || '').trim().toLowerCase()
602
848
  const body = String(candidate?.content || '')
603
- const grams = bigrams(body)
604
849
  const candidateNegated = NEGATION_RE.test(body)
605
850
  for (const [id, entry] of Object.entries(entries || {})) {
606
851
  if (!entry || entry.status === 'archived' || entry.status === 'suppressed') continue
@@ -608,15 +853,33 @@ export function findConflict(entries, candidate) {
608
853
  if (entry.status === 'pending_review' || entry.status === 'superseded') continue
609
854
  const otherTitle = String(entry.title || '').trim().toLowerCase()
610
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
611
867
  if (title && title === otherTitle) {
612
- 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' }
613
873
  continue
614
874
  }
615
- const similarity = dice(grams, bigrams(otherBody))
616
875
  if (similarity < 0.55) continue
617
- if (candidateNegated !== NEGATION_RE.test(otherBody)) {
618
- return { id, entry, reason: 'negation' }
619
- }
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' }
620
883
  }
621
884
  return null
622
885
  }
@@ -714,7 +977,20 @@ export function isMemoryEligible(entry, { automatic = false, now = Date.now() }
714
977
  // deadline itself has to be authoritative. An expired draft must never reach a
715
978
  // prompt just because the cleaner has not run yet.
716
979
  if (entry.expiresAt && (Date.parse(entry.expiresAt) || 0) <= now) return false
980
+ // S1 有效窗口:只有显式写下的 valid_from/valid_to 才参与;缺字段的旧数据照常召回。
981
+ if (!validitySignals(entry, { now }).valid) return false
717
982
  if (automatic && entry.visibility === 'secret') return false
983
+ // S6:never_say 不自动进入任何注入面(召回、锚点、提醒);显式工具召回仍可读。
984
+ if (automatic && entry.disclosure === 'never_say') return false
985
+ return true
986
+ }
987
+
988
+ /** S6 的 disclosure 门:only_if_asked 只在用户明确问到时才自动注入。 */
989
+ export function isDisclosureEligible(entry, { automatic = false, asked = false } = {}) {
990
+ if (!automatic) return true
991
+ const disclosure = entry?.disclosure || 'can_tell'
992
+ if (disclosure === 'never_say') return false
993
+ if (disclosure === 'only_if_asked') return asked === true
718
994
  return true
719
995
  }
720
996
 
@@ -727,9 +1003,13 @@ function assertEntryAccess(entry, exec) {
727
1003
  }
728
1004
 
729
1005
  // Local mode has no embedding service to rank candidates, so the index itself is
730
- // the retrieval source. The tokenizer is deliberately small and dependency-free:
731
- // Latin words plus CJK unigrams/bigrams, which is enough for the short, concrete
732
- // 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
+
733
1013
  function queryTokens(query) {
734
1014
  const text = String(query || '').toLowerCase()
735
1015
  const tokens = new Set(text.match(/[a-z0-9_]+/g) || [])
@@ -742,8 +1022,11 @@ function queryTokens(query) {
742
1022
  return [...tokens].filter(Boolean)
743
1023
  }
744
1024
 
745
- function lexicalScore(entry, tokens) {
746
- if (!tokens.length) return 0
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.
1028
+ function lexicalScore(entry, tokens, queryDates = []) {
1029
+ if (!tokens.length && !queryDates.length) return 0
747
1030
  const title = String(entry?.title || '').toLowerCase()
748
1031
  const content = [entry?.content || '', ...(entry?.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`)].join(' ').toLowerCase()
749
1032
  const tags = (Array.isArray(entry?.tags) ? entry.tags : []).join(' ').toLowerCase()
@@ -753,9 +1036,75 @@ function lexicalScore(entry, tokens) {
753
1036
  if (tags.includes(token)) score += 2
754
1037
  if (content.includes(token)) score += 1
755
1038
  }
1039
+ // S1:日期是结构化字段,不在正文里也要能被检索到(“那天发生了什么”)。
1040
+ if (entry?.absolute_date && queryDates.includes(entry.absolute_date)) score += 4
756
1041
  // Longer queries should not win just by having more tokens in common; the
757
1042
  // average keeps scores comparable across one-word and sentence queries.
758
- return score / tokens.length
1043
+ return tokens.length ? score / tokens.length : score
1044
+ }
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
759
1108
  }
760
1109
 
761
1110
  function localIndexFiles(index) {
@@ -769,29 +1118,56 @@ function localIndexFiles(index) {
769
1118
  }))
770
1119
  }
771
1120
 
772
- function localRecall(index, query, filter = () => true) {
1121
+ function localRecall(index, query, filter = () => true, { cacheKey = null, topK = null } = {}) {
773
1122
  const files = localIndexFiles(index).filter((file) => isActive(file.entry) && filter(file))
774
1123
  if (/^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())) {
775
1124
  const id = resolveEntryId(index, String(query).trim())
776
1125
  return { files: files.filter(file => file.name === id).map(file => ({ ...file, lexical: 5 })), segments: [], resources: [], raw: null, parseWarning: null }
777
1126
  }
778
- const tokens = queryTokens(query)
779
- const ordered = tokens.length === 0
780
- ? files.sort((a, b) => String(b.entry?.updatedAt || b.entry?.createdAt || '')
781
- .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
782
- : files
783
- .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens) }))
784
- .filter((file) => file.lexical > 0)
785
- .sort((a, b) => b.lexical - a.lexical
786
- || String(b.entry?.updatedAt || b.entry?.createdAt || '')
787
- .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
788
- return {
789
- files: ordered,
790
- segments: [],
791
- resources: [],
792
- raw: null,
793
- parseWarning: null,
1127
+ const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
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 }
794
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 }
795
1171
  }
796
1172
 
797
1173
  /** The per-route candidate cap for a requested topK; bounded on both ends. */
@@ -800,6 +1176,23 @@ export function hybridCandidateLimit(topK) {
800
1176
  return Math.max(HYBRID_CANDIDATE_MIN, Math.min(HYBRID_CANDIDATE_MAX, wanted * 4))
801
1177
  }
802
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
+
803
1196
  /**
804
1197
  * Reciprocal-rank fusion of lexical index hits and MemU vector hits.
805
1198
  *
@@ -842,22 +1235,22 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
842
1235
  // Fact-level folding : id dedupe cannot see "same fact,
843
1236
  // different id", so a paraphrase cluster would spend one candidate slot per
844
1237
  // member and crowd real memories out before any ranking runs. A candidate that
845
- // a accepted candidate already speaks for (dice ≥ DUP_DICE on title + body)
846
- // is recorded and skipped: one cluster, one candidate slot.
847
- const gramsCache = new Map()
848
- const gramsOf = (item) => {
849
- let set = gramsCache.get(item.id)
850
- if (!set) {
851
- set = bigrams(String(item.entry?.title || '') + ' ' + String(item.entry?.content || ''))
852
- 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)
853
1246
  }
854
- return set
1247
+ return text
855
1248
  }
856
1249
  for (const file of Array.isArray(files) ? files : []) {
857
1250
  const item = eligible(file, route, picked.length + 1)
858
1251
  if (!item || seen.has(item.id)) continue
859
1252
  seen.add(item.id)
860
- 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)
861
1254
  if (twin) {
862
1255
  collapsed.push({ kept: twin.id, dropped: item.id })
863
1256
  continue
@@ -893,18 +1286,18 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
893
1286
  // diversity ceiling is set by a real spread of memories rather than a cluster.
894
1287
  const fusionCollapsed = []
895
1288
  const absorbed = new Set()
896
- const rowGrams = new Map()
897
- const gramsOfRow = (row) => {
898
- let set = rowGrams.get(row.id)
899
- if (!set) {
900
- set = bigrams(String(row.entry?.title || '') + ' ' + String(row.entry?.content || ''))
901
- 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)
902
1295
  }
903
- return set
1296
+ return text
904
1297
  }
905
1298
  const hosts = []
906
1299
  for (const row of rows.slice().sort((a, b) => b.rrf - a.rrf || a.id.localeCompare(b.id))) {
907
- 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)
908
1301
  if (host) {
909
1302
  host.mergedTogether.push(row.id)
910
1303
  absorbed.add(row.id)
@@ -1014,8 +1407,11 @@ function recallScore(file, rank, context) {
1014
1407
  // ride the same touch/decay loop as the original and could outlive it in rank —
1015
1408
  // the "duplicates age better than the truth" loop this closes.
1016
1409
  const duplicateFactor = entry.duplicateOf ? 0.7 : 1
1410
+ // S1:查询里点了具体日期时,日期命中是强信号;只做温和提升,不盖过语义匹配。
1411
+ const temporalFactor = Array.isArray(context.queryDates) && entry.absolute_date
1412
+ && context.queryDates.includes(entry.absolute_date) ? 1.35 : 1
1017
1413
 
1018
- return retrieval * strengthTerm * marginal * moodBias * peakEnd * primacy * openLoopBias * habituation * arousalTerm * dominanceTerm * duplicateFactor
1414
+ return retrieval * strengthTerm * marginal * moodBias * peakEnd * primacy * openLoopBias * habituation * arousalTerm * dominanceTerm * duplicateFactor * temporalFactor
1019
1415
  }
1020
1416
 
1021
1417
  /**
@@ -1075,7 +1471,7 @@ function habituationFactor(entry, now = Date.now()) {
1075
1471
  // `retrievalFloor` is the absolute complement : whatever the
1076
1472
  // library looks like, a hit whose retrieval share never cleared the floor must not
1077
1473
  // pad a topK that a duplicate cluster emptied. 0 turns it off entirely.
1078
- function cutWeakScores(files, threshold, retrievalFloor = 0) {
1474
+ function cutWeakScores(files, threshold, retrievalFloor = 0, percentile = 0) {
1079
1475
  let out = files
1080
1476
  const cut = Number(threshold)
1081
1477
  if (Number.isFinite(cut) && cut > 0) {
@@ -1084,9 +1480,20 @@ function cutWeakScores(files, threshold, retrievalFloor = 0) {
1084
1480
  }
1085
1481
  const floor = Number(retrievalFloor)
1086
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
+ }
1087
1490
  return out
1088
1491
  }
1089
1492
 
1493
+ function recallPercentile() {
1494
+ return process.env.DSH_MEMU_RECALL_PERCENTILE === '1' ? 75 : 0
1495
+ }
1496
+
1090
1497
  function privateWeighted(result, max, context = {}) {
1091
1498
  const ctx = {
1092
1499
  moodEnabled: false,
@@ -1098,6 +1505,10 @@ function privateWeighted(result, max, context = {}) {
1098
1505
  lastCreatedAt: null,
1099
1506
  sessionId: null,
1100
1507
  now: Date.now(),
1508
+ queryDates: [],
1509
+ speakerFilter: null,
1510
+ intent: 'general',
1511
+ disclosureAsked: false,
1101
1512
  retrievalFloor: RETRIEVAL_FLOOR,
1102
1513
  ...context,
1103
1514
  }
@@ -1109,9 +1520,14 @@ function privateWeighted(result, max, context = {}) {
1109
1520
  // memories. Filtering here keeps the anchor and the recall block in agreement.
1110
1521
  .filter((f) => visibleToSession(f.entry, ctx.sessionId))
1111
1522
  .filter((f) => !ctx.automatic || f.entry?.visibility !== 'secret')
1523
+ // S6:never_say 由 isMemoryEligible 挡掉;only_if_asked 只在 boundary 意图时放行。
1524
+ .filter((f) => isDisclosureEligible(f.entry, { automatic: ctx.automatic === true, asked: ctx.disclosureAsked === true }))
1525
+ // S3.2:明确问“我说过/你说过/他说的”时,只留下说话人对得上的条目;
1526
+ // 没有 speaker 字段的旧条目保留,避免一次查询把历史记忆全清空。
1527
+ .filter((f) => speakerMatchesFilter(f.entry, ctx.speakerFilter))
1112
1528
  .map((f, i) => ({ ...f, score: recallScore(f, i, ctx), retrieval: retrievalShare(f, i) }))
1113
1529
  .sort((a, b) => b.score - a.score)
1114
- 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)
1115
1531
  // Observation for the dedup thresholds : candidate folding
1116
1532
  // (①②) reports through result.fusion, the ranking-level hard skips (③) come back
1117
1533
  // from mmrSelect. One merged list — without it, a mistuned threshold eats real
@@ -1124,18 +1540,18 @@ function privateWeighted(result, max, context = {}) {
1124
1540
  /**
1125
1541
  * Greedy maximal marginal relevance over already-scored files.
1126
1542
  *
1127
- * Similarity is lexical on purpose (dice over title+body bigrams, the same shared
1128
- * ruler the write-side duplicate gate uses): it must be cheap enough to run on every
1129
- * recall and predictable enough to explain. An embedding version would need a second
1130
- * 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.
1131
1547
  *
1132
1548
  * Two bands :
1133
- * · dice >= DUP_DICE — the candidate describes a fact something already chosen
1134
- * describes: it is never selected, only reported as `skipped`. A soft penalty
1135
- * cannot bound how many seats one fact takes; this can.
1136
- * · 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
1137
1552
  * penalty (lambda x overlap x ceiling) still applies.
1138
- * 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.
1139
1555
  */
1140
1556
  function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1141
1557
  const limit = Number(max || 0)
@@ -1143,13 +1559,21 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1143
1559
  if (items.length <= 1) return { chosen: items.slice(0, limit), skipped: [] }
1144
1560
  const chosen = []
1145
1561
  const pool = items.slice()
1146
- const gramsCache = new Map()
1147
- const gramsOf = (file) => {
1562
+ const textCache = new Map()
1563
+ const textOf = (file) => {
1148
1564
  const key = file.name
1149
- if (gramsCache.has(key)) return gramsCache.get(key)
1150
- const set = bigrams(String(file.entry?.title || '') + ' ' + String(file.entry?.content || ''))
1151
- gramsCache.set(key, set)
1152
- 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
1153
1577
  }
1154
1578
  // Anchor the penalty to the best raw score so the diversity term is on the same
1155
1579
  // scale as relevance instead of being dominated by it.
@@ -1164,7 +1588,7 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
1164
1588
  let overlap = 0
1165
1589
  let twin = null
1166
1590
  for (const picked of chosen) {
1167
- const similarity = dice(gramsOf(pool[i]), gramsOf(picked))
1591
+ const similarity = similarityOf(pool[i], picked)
1168
1592
  if (similarity >= DUP_DICE) { twin = picked.name; break }
1169
1593
  if (similarity >= TOPIC_DICE) overlap = Math.max(overlap, similarity)
1170
1594
  }
@@ -1274,6 +1698,20 @@ async function privateRememberImpl({
1274
1698
  emotion = undefined, dominance = undefined, emotionSource = null,
1275
1699
  attachments, track = 'memory',
1276
1700
  context,
1701
+ // S1 time normalization. observed_at defaults to the turn's logical time; the
1702
+ // explicit date fields exist so a caller that already knows the absolute date
1703
+ // does not have to make the parser re-derive it from prose.
1704
+ observedAt = null, absoluteDate = null, validFrom = null, validTo = null, datePrecision = null,
1705
+ // S3 provenance: who said it and how we know.
1706
+ speakerId = null, sourceKind = null, quoteSpan = null,
1707
+ storylineId = null, branchId = null, knownBy = null,
1708
+ // S4 commitment. `open_loop` stays as a compatibility flag; when a commitment
1709
+ // object exists its status is authoritative.
1710
+ commitment = null,
1711
+ // S2 versioned facts. An explicit fact_key declares "this is the same fact";
1712
+ // conflicts_with keeps both versions active and cross-linked, supersedes retires
1713
+ // the old row without deleting its text.
1714
+ factKey = null, conflictsWith = null, supersedes = null,
1277
1715
  // Escape hatch for the duplicate gate : two genuine
1278
1716
  // observations of the same fact on the same day are a legal write. Off by
1279
1717
  // default — the model must say it looked, not default past the gate.
@@ -1281,6 +1719,7 @@ async function privateRememberImpl({
1281
1719
  }) {
1282
1720
  const scope = resolveLibrary({ exec, libraryId })
1283
1721
  const binding = scope.binding
1722
+ const scene = sceneTimeOf({ binding, context, observedAt })
1284
1723
  const memoryContext = normalizeMemoryContext({ ...binding?.memoryContext, ...context })
1285
1724
  if (sessionIdOf(exec) && ['channelId', 'characterId', 'worldId', 'branchId'].some(key => binding?.memoryContext?.[key] && memoryContext[key] !== binding.memoryContext[key])) throw new Error('memory context cannot widen or change the bound conversation')
1286
1725
  if (sessionIdOf(exec) && !contextVisible({ ...memoryContext, knownBy: [] }, binding?.memoryContext)) {
@@ -1304,7 +1743,7 @@ async function privateRememberImpl({
1304
1743
  // An unreadable date is refused instead of dropped. Dropping it looked like
1305
1744
  // success to the caller while losing the only part of the memory it asked for:
1306
1745
  // a date that never fires is indistinguishable from no date at all.
1307
- let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`)
1746
+ let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`, scene)
1308
1747
  // 模型常把日期写进正文却漏填 salient_date(详情页日期栏因此为空)。只有显式传了
1309
1748
  // 非法值才报错;什么都没传时,从文本取唯一的 YYYY-MM-DD 作为兜底。
1310
1749
  const explicitDate = salientDate !== null && salientDate !== undefined && String(salientDate).trim()
@@ -1318,6 +1757,48 @@ async function privateRememberImpl({
1318
1757
  if (title !== undefined) title = redactSecrets(title)
1319
1758
  if (!LAYERS.includes(layer)) throw new Error(`unknown layer: ${layer}; use ${LAYERS.join(', ')}`)
1320
1759
  checkEnums({ disclosure, owner, visibility, source })
1760
+ const temporal = temporalFieldsOf({
1761
+ title, content, scene, salientDate: normalizedSalientDate,
1762
+ absoluteDate, validFrom, validTo, datePrecision,
1763
+ })
1764
+ checkSourceKind(sourceKind)
1765
+ if (sourceKind && source !== 'inferred' && source !== sourceKind) {
1766
+ throw new Error('source and source_kind disagree; send one provenance for this memory')
1767
+ }
1768
+ if (sourceKind) source = sourceKind
1769
+ const effectiveSourceKind = SOURCE_KINDS.includes(source) ? source : 'inferred'
1770
+ const explicitSpeaker = speakerId === null || speakerId === undefined ? null : String(speakerId).trim()
1771
+ if (explicitSpeaker !== null && (!explicitSpeaker || explicitSpeaker.length > 128)) {
1772
+ throw new Error('speaker_id must be a non-empty string up to 128 characters')
1773
+ }
1774
+ const effectiveSpeaker = explicitSpeaker || memoryContext.speakerId || defaultSpeakerFor(effectiveSourceKind)
1775
+ const explicitStoryline = storylineId === null || storylineId === undefined ? null : String(storylineId).trim()
1776
+ if (explicitStoryline !== null && (!explicitStoryline || explicitStoryline.length > 128)) {
1777
+ throw new Error('storyline_id must be a non-empty string up to 128 characters')
1778
+ }
1779
+ const explicitBranch = branchId === null || branchId === undefined ? null : String(branchId).trim()
1780
+ if (explicitBranch !== null && (!explicitBranch || explicitBranch.length > 128)) {
1781
+ throw new Error('branch_id must be a non-empty string up to 128 characters')
1782
+ }
1783
+ const quote = normalizeQuoteSpan(quoteSpan)
1784
+ const known = normalizeKnownBy(knownBy)
1785
+ const provenance = {
1786
+ speaker_id: effectiveSpeaker,
1787
+ source_kind: effectiveSourceKind,
1788
+ ...(quote ? { quote_span: quote } : {}),
1789
+ ...(explicitStoryline ? { storyline_id: explicitStoryline } : {}),
1790
+ branch_id: explicitBranch || memoryContext.branchId || null,
1791
+ ...(known !== undefined
1792
+ ? { known_by: known }
1793
+ : (memoryContext.knownBy?.length ? { known_by: memoryContext.knownBy } : {})),
1794
+ }
1795
+ // S4:显式承诺优先;open_loop=true 的旧调用也落一条 open 承诺,due_at 取本轮
1796
+ // 已解析出的日期(没有就为空)。commitment.status 从这里开始就是权威。
1797
+ const commitmentDue = temporal.absolute_date || (isDatedSalientDate(normalizedSalientDate) ? normalizedSalientDate : null)
1798
+ const explicitCommitment = normalizeCommitment(commitment, { fallbackDueAt: commitmentDue })
1799
+ const derivedCommitment = explicitCommitment || (openLoop
1800
+ ? normalizeCommitment({ status: 'open', action: title || content, due_at: commitmentDue }, { fallbackAction: title || content })
1801
+ : null)
1321
1802
  // A short-term entry is a draft with a deadline. With the layer switched off the
1322
1803
  // write is refused rather than quietly upgraded to permanent memory, because the
1323
1804
  // model asked for something disposable and would otherwise pollute the durable
@@ -1355,6 +1836,37 @@ async function privateRememberImpl({
1355
1836
  && (item.attachments || []).some(attachment => media.some(candidate => candidate.sha256 === attachment.sha256)))
1356
1837
  : null
1357
1838
  const id = previousHabit?.[0] || newMemoryId('mem')
1839
+ // S2:显式 conflicts_with / supersedes 先解析目标;显式 fact_key 且没有显式关系时,
1840
+ // 同一 fact_key 的最近一个 active 条目自动成为冲突对(两条都保留、互指)。
1841
+ const memorySession = memorySessionId(exec)
1842
+ const requestedFactKey = normalizeFactKey(factKey)
1843
+ if (factKey !== null && factKey !== undefined && !requestedFactKey) throw new Error('fact_key must be a non-empty string')
1844
+ if (conflictsWith && supersedes) throw new Error('a memory cannot both conflict with and supersede another memory')
1845
+ let relation = null
1846
+ if (conflictsWith) {
1847
+ relation = { kind: 'conflict', ...relationTarget(index, conflictsWith, { context: memoryContext, sessionId: memorySession, label: 'conflicts_with' }) }
1848
+ } else if (supersedes) {
1849
+ relation = { kind: 'supersede', ...relationTarget(index, supersedes, { context: memoryContext, sessionId: memorySession, label: 'supersedes' }) }
1850
+ }
1851
+ if (!relation && requestedFactKey) {
1852
+ const candidates = Object.entries(index.entries)
1853
+ .filter(([otherId, other]) => otherId !== id && other && isMemoryEligible(other)
1854
+ && other.fact_key === requestedFactKey && sameFactContext(other.context, memoryContext)
1855
+ && visibleForDedupe(other, memorySession))
1856
+ .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || ''))
1857
+ || a[0].localeCompare(b[0]))
1858
+ if (candidates.length) relation = { kind: 'conflict', id: candidates[0][0], entry: candidates[0][1] }
1859
+ }
1860
+ const factKeyValue = requestedFactKey || relation?.entry?.fact_key
1861
+ || deriveFactKey({ owner, title: title || content, content })
1862
+ const relationId = relation?.id || null
1863
+ const relationKind = relation?.kind || null
1864
+ const relationEntry = relation?.entry || null
1865
+ const version = relationId
1866
+ ? Math.max(1, Number(relationEntry?.version) || 1) + 1
1867
+ : (previousHabit?.[1]?.fact_key === factKeyValue
1868
+ ? Math.max(1, Number(previousHabit[1].version) || 1)
1869
+ : nextFactVersion(index.entries, factKeyValue, memoryContext, id))
1358
1870
  // A malformed share is refused here rather than clamped later: a negative or
1359
1871
  // non-finite composition is a caller bug, and repairing it silently would keep the
1360
1872
  // bug alive while the entry looks fine.
@@ -1384,7 +1896,8 @@ async function privateRememberImpl({
1384
1896
  accessCount: previousHabit?.[1]?.accessCount || 0,
1385
1897
  strength: layer === 'must_remember' ? 1 : 0.8,
1386
1898
  marginalized: false,
1387
- openLoop: !!openLoop,
1899
+ openLoop: derivedCommitment ? derivedCommitment.status === 'open' : !!openLoop,
1900
+ ...(derivedCommitment ? { commitment: derivedCommitment } : {}),
1388
1901
  disclosure,
1389
1902
  owner,
1390
1903
  visibility,
@@ -1414,6 +1927,16 @@ async function privateRememberImpl({
1414
1927
  : Math.max(0, Math.min(1, Number(arousal) || 0)),
1415
1928
  peak: peak === true,
1416
1929
  salientDate: normalizedSalientDate,
1930
+ ...temporal,
1931
+ ...provenance,
1932
+ ...(factKeyValue ? {
1933
+ fact_key: factKeyValue,
1934
+ version,
1935
+ fact_authority: factAuthorityOf(effectiveSourceKind),
1936
+ ...(quote ? { fact_evidence: quote } : {}),
1937
+ } : {}),
1938
+ ...(relationKind === 'conflict' && relationId ? { conflicts_with: relationId } : {}),
1939
+ ...(relationKind === 'supersede' && relationId ? { supersedes: relationId } : {}),
1417
1940
  }
1418
1941
  // Flashbulb memory: store vividness and accuracy separately. `confidence` is
1419
1942
  // what the model claims; `accuracy` is what a charged moment is actually worth.
@@ -1424,14 +1947,18 @@ async function privateRememberImpl({
1424
1947
  // true. Same mechanism the global curator uses; until now the private side had none.
1425
1948
  // Hidden rows are excluded (5.1): otherwise a visible write could learn an id
1426
1949
  // through conflictingWith, and a hidden claim could hold an unrelated new one.
1427
- const memorySession = memorySessionId(exec)
1428
- const conflict = findConflict(Object.fromEntries(Object.entries(index.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1950
+ // S2 的显式冲突对/取代链已经由关系字段表达,不再走旧的 pending_review 兜底。
1951
+ const conflict = relationId
1952
+ ? null
1953
+ : findConflict(Object.fromEntries(Object.entries(index.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1429
1954
  if (conflict) {
1430
1955
  entry.status = 'pending_review'
1431
1956
  entry.conflictingWith = conflict.id
1432
1957
  entry.reviewReason = conflict.reason === 'same_title'
1433
1958
  ? `与已有记忆「${clampText(conflict.entry.title || conflict.id, 60)}」同题但内容不同`
1434
- : `与已有记忆「${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)}」说法相反`
1435
1962
  }
1436
1963
  // Fact-level duplicate gate . Strictly AFTER the conflict
1437
1964
  // check — in the same-title band a contradictory rewording must land as
@@ -1442,7 +1969,7 @@ async function privateRememberImpl({
1442
1969
  // it duplicateOf so recall can keep one seat per fact.
1443
1970
  let duplicate = null
1444
1971
  let hiddenDuplicate = null
1445
- if (!conflict && allowDuplicate !== true) {
1972
+ if (!conflict && !relationId && allowDuplicate !== true) {
1446
1973
  const text = `${entry.title || ''} ${content || ''}`
1447
1974
  for (const [otherId, other] of Object.entries(index.entries)) {
1448
1975
  if (otherId === id || !isMemoryEligible(other)) continue
@@ -1511,10 +2038,13 @@ async function privateRememberImpl({
1511
2038
  // the review later is what commits it (see resolveReview → privateUpdate).
1512
2039
  const route = engineRoute()
1513
2040
  const db = route !== 'lexical' && !conflict ? memoryDbPath(scope.libraryId) : null
1514
- const result = db
1515
- ? await commit({ payload, route, db })
1516
- : { 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
1517
2045
  try {
2046
+ if (commitOutcome.warning) entry.vectorPending = true
2047
+ else delete entry.vectorPending
1518
2048
  // 记下"这条进没进向量库":只有真的带代际提交成功才写,冲突暂扣/降级都不写。
1519
2049
  // 之前没有任何字段能回答"哪条记忆进向量库了",只能靠猜。
1520
2050
  if (route !== 'lexical' && !conflict && result?.ok !== false && !result?.parseWarning) {
@@ -1527,9 +2057,11 @@ async function privateRememberImpl({
1527
2057
  if (sessionIdOf(exec) && (!currentBinding || currentBinding.libraryId !== scope.libraryId)) throw new Error('memory scope changed during write; retry')
1528
2058
  if (currentBinding) assertScopeEnabled(currentBinding)
1529
2059
  if (previousHabit && JSON.stringify(fresh.entries[id]) !== JSON.stringify(previousHabit[1])) throw new Error('habit changed concurrently; recall and retry')
1530
- const latestConflict = findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
2060
+ const latestConflict = relationId
2061
+ ? null
2062
+ : findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1531
2063
  if (latestConflict && !conflict) {
1532
- 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')
1533
2065
  entry.status = 'pending_review'
1534
2066
  entry.conflictingWith = latestConflict.id
1535
2067
  entry.reviewReason = 'concurrent conflicting memory; review required'
@@ -1537,13 +2069,13 @@ async function privateRememberImpl({
1537
2069
  // 5.4:预检在 await 之前,提交期间另一个 turn 可能刚写入同事实。临界区用同一
1538
2070
  // 尺子重扫;命中就 retry(有向量则 throw 让 compensation 撤掉刚提交的行),
1539
2071
  // lexical 路由直接暂扣为 near_duplicate,不双写也不丢文本。
1540
- const latestDuplicate = allowDuplicate
2072
+ const latestDuplicate = allowDuplicate || relationId
1541
2073
  ? { duplicate: null, hidden: false }
1542
2074
  : findNearDuplicate(fresh.entries, {
1543
2075
  id, title: entry.title, content: entry.content, context: entry.context, sessionId: memorySession,
1544
2076
  })
1545
2077
  if (latestDuplicate.hidden || (latestDuplicate.duplicate && latestDuplicate.duplicate.similarity >= DUP_REJECT_DICE)) {
1546
- if (db) throw new Error('memory duplicate changed during write; retry')
2078
+ if (commitOutcome.committedDb) throw new Error('memory duplicate changed during write; retry')
1547
2079
  entry.status = 'pending_review'
1548
2080
  entry.reviewReason = 'near_duplicate'
1549
2081
  entry.conflictingWith = latestDuplicate.duplicate?.id || null
@@ -1553,23 +2085,40 @@ async function privateRememberImpl({
1553
2085
  if (pinned >= Number(getSettings().mustRememberCap || 12)) throw new Error('must_remember soft cap reached; retry as long_term')
1554
2086
  }
1555
2087
  fresh.entries[id] = entry
2088
+ // S2:关系是双向的,且在同一个索引事务里落地,避免只写一半。
2089
+ if (relationId && relationKind === 'conflict') {
2090
+ const target = fresh.entries[relationId]
2091
+ if (!target) throw new Error('conflict target disappeared during write; retry')
2092
+ target.conflicts_with = id
2093
+ target.conflictAt = stamp()
2094
+ }
2095
+ if (relationId && relationKind === 'supersede') {
2096
+ const target = fresh.entries[relationId]
2097
+ if (!target) throw new Error('supersede target disappeared during write; retry')
2098
+ target.status = 'superseded'
2099
+ target.supersededBy = id
2100
+ // 旧正文保留,只落下有效期终点;validTo 兼容旧 UI/复核字段。
2101
+ const endedAt = localDateKeyInZone(scene, DEFAULT_TIME_ZONE)
2102
+ target.valid_to = endedAt
2103
+ target.validTo = endedAt
2104
+ }
1556
2105
  }))
1557
2106
  } catch (error) {
1558
- 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 })
1559
2108
  throw error
1560
2109
  }
1561
2110
  if (!previousHabit) bumpStats(scope.libraryId, 'written')
1562
2111
  if (layer === 'must_remember' && pinSource === 'side_event') {
1563
2112
  consumeCue(sessionIdOf(exec), sideEventId)
1564
2113
  }
1565
- return { id, entry, result, conflict: entry.conflictingWith || null }
2114
+ return { id, entry, result, conflict: entry.conflictingWith || null, conflictsWith: entry.conflicts_with || null, supersedes: entry.supersedes || null }
1566
2115
  }
1567
2116
 
1568
2117
  // Bulk restore of an exported library. This is a *restore*, not a decision, so it
1569
2118
  // writes the index directly instead of going through privateRemember: the pin cap,
1570
2119
  // the short-term deadline and the "no duplicate text" check would otherwise turn a
1571
2120
  // faithful restore into a pile of downgrades.
1572
- async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now = Date.now() }) {
2121
+ async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now = Date.now(), importBatchId = null }) {
1573
2122
  const library = getLibrary(libraryId)
1574
2123
  if (!library) throw new Error('library not found')
1575
2124
  const list = Array.isArray(memories) ? memories : []
@@ -1669,6 +2218,7 @@ async function importMemoriesImpl({ libraryId, memories, maxFiles = 2000, now =
1669
2218
  source: typeof item.source === "string" && item.source ? item.source : "imported",
1670
2219
  confidence: Number.isFinite(Number(item.confidence)) ? Math.max(0, Math.min(1, Number(item.confidence))) : 0.8,
1671
2220
  status: "active",
2221
+ ...(importBatchId ? { importedBundle: String(importBatchId) } : {}),
1672
2222
  moodValence: Number.isFinite(Number(item.moodValence)) ? Math.max(-1, Math.min(1, Number(item.moodValence))) : 0,
1673
2223
  arousal: Number.isFinite(Number(item.arousal)) ? Math.max(0, Math.min(1, Number(item.arousal))) : 0.35,
1674
2224
  peak: item.peak === true,
@@ -1780,7 +2330,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
1780
2330
  for (const source of sources) {
1781
2331
  const scoped = source.primary ? source.index : domainScopedIndex(source.index, domain)
1782
2332
  if (route === 'lexical' || byId) {
1783
- 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 })
1784
2334
  continue
1785
2335
  }
1786
2336
  const managed = await managedRecall({
@@ -1841,8 +2391,15 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1841
2391
  const settings = getSettings()
1842
2392
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
1843
2393
  const byId = /^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())
2394
+ // S1:相对日期在召回前先落到绝对日期;sceneTime 是这一轮的逻辑时间。
2395
+ // S5:同一处识别意图并抽取日期/实体,意图决定候选数与过滤策略。
2396
+ const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
2397
+ const recallIntent = detectQueryIntent(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2398
+ const decomposed = decomposeQuery(query, recallIntent, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2399
+ const queryDates = decomposed.dates
2400
+ const searchQuery = decomposed.expanded
1844
2401
  const route = effectiveVectorRoute(settings)
1845
- const wanted = Number(topK || settings.privateTopK || 4)
2402
+ const wanted = intentTopK(recallIntent, Number(topK || settings.privateTopK || 4))
1846
2403
  const domain = domainOf(binding)
1847
2404
  const sources = (settings.crossLibraryRecall === true
1848
2405
  ? crossLibrarySources(binding, domain)
@@ -1852,9 +2409,9 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1852
2409
  // exists when another qualifying library is actually present.
1853
2410
  const result = sources.length === 1
1854
2411
  ? (route === 'lexical' || byId
1855
- ? { ...localRecall(sources[0].index, query), recallRoute: 'local' }
1856
- : await managedRecall({ exec, index: sources[0].index, query, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
1857
- : await recallCrossLibrary({ exec, sources, query, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
2412
+ ? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK: wanted }), recallRoute: 'local' }
2413
+ : await managedRecall({ exec, index: sources[0].index, query: searchQuery, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2414
+ : await recallCrossLibrary({ exec, sources, query: searchQuery, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
1858
2415
  const current = peekBinding(exec)
1859
2416
  if (!current || current.libraryId !== binding.libraryId) throw new Error('memory scope changed during recall; retry')
1860
2417
  assertScopeEnabled(current)
@@ -1882,7 +2439,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1882
2439
  (source.libraryId === binding.libraryId ? index : source.index).entries || {},
1883
2440
  ).map((entry) => ({ entry }))))
1884
2441
  const mood = moodDecay(binding.mood)
1885
- const scored = privateWeighted(enriched, Number(topK || settings.privateTopK || 4), {
2442
+ const scored = privateWeighted(enriched, wanted, {
1886
2443
  // Three independent legs: a clear composition, an arousal away from rest, or a
1887
2444
  // clear sense of control. A null composition only closes the first one — a tense
1888
2445
  // room with no clear good/bad reading still changes which memories come up.
@@ -1894,11 +2451,71 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1894
2451
  firstCreatedAt: span.first,
1895
2452
  lastCreatedAt: span.last,
1896
2453
  relevanceThreshold: threshold,
2454
+ queryDates,
2455
+ intent: recallIntent,
2456
+ disclosureAsked: recallIntent === 'boundary',
2457
+ speakerFilter: detectSpeakerQuery(query),
1897
2458
  // The asking conversation's context is what memories are filtered against; the id is
1898
2459
  // only how that context is looked up.
1899
2460
  sessionId: memorySessionId(exec),
1900
2461
  automatic: purpose === 'automatic',
1901
2462
  })
2463
+ // S2:命中冲突的一侧时,把另一侧也带上。两条都保留、都 active,注入层会把
2464
+ // 它们渲染成一张“未确认哪版为准”的冲突卡;这里只保证成对出现。
2465
+ //
2466
+ // 座位是共享的,不是白送的:一半的矛盾读起来像一条已定论的事实,比不召回更糟,
2467
+ // 所以配对优先于「最后一条边缘记忆」。追加完之后按需从尾部挤掉**没有配对**的
2468
+ // 条目,让 files.length 回到 wanted。只剩配对时挤不动——那时配对更重要,并且
2469
+ // 会留下一条可观测记录,而不是让「不变量」在无人知晓的地方破掉。
2470
+ const paired = new Set((scored.files || []).map((file) => file.name))
2471
+ const conflictPairs = []
2472
+ for (const file of (scored.files || []).slice()) {
2473
+ const otherId = file.entry?.conflicts_with
2474
+ if (!otherId || paired.has(otherId)) continue
2475
+ const other = index.entries[otherId]
2476
+ if (!other || !isMemoryEligible(other, { automatic: purpose === 'automatic', now: Date.now() })) continue
2477
+ if (!visibleToSession(other, memorySessionId(exec))) continue
2478
+ file.conflictPair = otherId
2479
+ scored.files.push({
2480
+ name: otherId,
2481
+ description: other.title || '',
2482
+ content: String(other.content || ''),
2483
+ entry: other,
2484
+ strength: decayStrength(other),
2485
+ createdAtIdentity: other.createdAt || null,
2486
+ conflictPair: file.name,
2487
+ })
2488
+ paired.add(otherId)
2489
+ conflictPairs.push({ a: file.name, b: otherId })
2490
+ }
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
+ }
1902
2519
  // Being recalled is being used, and a memory that keeps being used should not fade
1903
2520
  // like one nobody ever touches. Group by the library each hit came from so a
1904
2521
  // cross-library recall touches the owning index, not the bound one.
@@ -1937,6 +2554,46 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1937
2554
  }
1938
2555
  try { file.related = recallRelations(fileLibraryId, fileIndex, file.name, memorySessionId(exec)) } catch { file.related = [] }
1939
2556
  }
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)
2562
+ const knownIds = new Set(scored.files.map((file) => file.name))
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
2570
+ for (const file of scored.files.slice()) {
2571
+ if (expanded.length >= expansionLimit) break
2572
+ for (const link of file.related || []) {
2573
+ if (!link?.id || link.missing || knownIds.has(link.id)) continue
2574
+ if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
2575
+ const fileLibraryId = file.libraryId || binding.libraryId
2576
+ const fileIndex = indexByLibrary.get(fileLibraryId) || index
2577
+ const target = fileIndex.entries[link.id]
2578
+ if (!target) continue
2579
+ if (!isMemoryEligible(target, { automatic: purpose === 'automatic' })) continue
2580
+ if (!visibleToSession(target, memorySessionId(exec))) continue
2581
+ knownIds.add(link.id)
2582
+ scored.files.push({
2583
+ name: link.id,
2584
+ description: target.title || '',
2585
+ content: String(target.content || ''),
2586
+ entry: target,
2587
+ strength: decayStrength(target),
2588
+ createdAtIdentity: target.createdAt || null,
2589
+ relatedTo: file.name,
2590
+ relationKind: link.kind || 'related',
2591
+ })
2592
+ expanded.push({ from: file.name, to: link.id, kind: link.kind || 'related' })
2593
+ if (expanded.length >= expansionLimit) break
2594
+ }
2595
+ }
2596
+ if (expanded.length) scored.expanded = expanded
1940
2597
  if (sources.length > 1) scored.libraries = sources.map((source) => source.libraryId)
1941
2598
  return scored
1942
2599
  }
@@ -2028,12 +2685,14 @@ export async function privateList({ exec, libraryId, preferIndex = false }) {
2028
2685
  // mood lens and the attachment list all change how an entry is scored, aggregated or
2029
2686
  // rendered, so a wrong value in any of them was a permanent mis-filing that could
2030
2687
  // only be undone by archiving the memory and writing it again.
2031
- async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, status, openLoop, disclosure, confidence, layer, owner, visibility, source, salientDate, track, peak, moodValence, arousal, emotion, dominance, attachments, context }) {
2688
+ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, status, openLoop, disclosure, confidence, layer, owner, visibility, source, salientDate, track, peak, moodValence, arousal, emotion, dominance, attachments, context, validFrom, validTo, absoluteDate, observedAt, speakerId, sourceKind, quoteSpan, storylineId, branchId, knownBy, commitment }) {
2032
2689
  // `source` is editable because it is a claim about provenance, and claims get
2033
2690
  // corrected: a memory the model first filed as `inferred` may turn out to be
2034
2691
  // something the user actually said. Enum-checked like the rest — a typo here
2035
2692
  // silently downgrades a quote into an inference.
2036
2693
  checkEnums({ disclosure, owner, visibility, source })
2694
+ checkSourceKind(sourceKind)
2695
+ if (sourceKind && source !== undefined && source !== sourceKind) throw new Error('source and source_kind disagree; send one provenance for this memory')
2037
2696
  const scope = resolveLibrary({ exec, libraryId })
2038
2697
  if (scope.binding) assertScopeEnabled(scope.binding)
2039
2698
  const index = loadPrivateIndex(scope.libraryId)
@@ -2041,6 +2700,7 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2041
2700
  const id_ = resolveEntryId(index, id)
2042
2701
  const entry = index.entries[id_]
2043
2702
  assertEntryAccess(entry, exec)
2703
+ const scene = sceneTimeOf({ binding: scope.binding, context: entry.context, observedAt })
2044
2704
  if (layer !== undefined && (!LAYERS.includes(layer) || layer === 'must_remember' && entry.layer !== layer)) throw new Error('invalid layer update; must_remember needs a pin_reason')
2045
2705
  if (status !== undefined && !['active', 'archived', 'fragment', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(status)) throw new Error('invalid memory status')
2046
2706
  if (status === 'active' && ['pending_review', 'superseded'].includes(entry.status)) throw new Error('held or superseded memories require review')
@@ -2114,6 +2774,8 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2114
2774
  const route = engineRoute()
2115
2775
  const managed = route === 'managed-local'
2116
2776
  let committedDb = null
2777
+ let commitWarning = null
2778
+ let commitAttempted = false
2117
2779
  if ((nextContent !== undefined || managed) && entry.status !== 'pending_review' && status !== 'pending_review') {
2118
2780
  const payload = {
2119
2781
  recall_files: [{
@@ -2127,8 +2789,10 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2127
2789
  }
2128
2790
  if (route !== 'lexical') {
2129
2791
  const db = memoryDbPath(scope.libraryId)
2130
- await commit({ payload, route, db })
2131
- 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
2132
2796
  }
2133
2797
  }
2134
2798
  let updated
@@ -2167,9 +2831,79 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2167
2831
  }
2168
2832
  if (tags !== undefined) target.tags = Array.isArray(tags) ? tags.slice(0, 20) : target.tags
2169
2833
  if (status !== undefined) target.status = status
2170
- if (openLoop !== undefined) target.openLoop = !!openLoop
2834
+ if (openLoop !== undefined) {
2835
+ target.openLoop = !!openLoop
2836
+ const current = commitmentOf(target)
2837
+ if (current && openLoop && current.status !== 'open') {
2838
+ target.commitment = { ...current, status: 'open', closed_by: null }
2839
+ } else if (current && !openLoop && current.status === 'open') {
2840
+ // 旧布尔值关闭一条承诺时也要关闭 commitment.status,否则 S4 的权威字段
2841
+ // 会让这条“已关闭”的欠账继续出现在到期提醒里。
2842
+ target.commitment = { ...current, status: 'done' }
2843
+ } else if (!current && openLoop) {
2844
+ target.commitment = normalizeCommitment({
2845
+ status: 'open', action: target.title || target.content, due_at: target.absolute_date || null,
2846
+ })
2847
+ }
2848
+ }
2849
+ if (commitment !== undefined) {
2850
+ if (commitment === null) {
2851
+ delete target.commitment
2852
+ } else {
2853
+ const normalized = normalizeCommitment(commitment, {
2854
+ fallbackDueAt: target.absolute_date || null,
2855
+ })
2856
+ target.commitment = normalized
2857
+ target.openLoop = normalized.status === 'open'
2858
+ }
2859
+ }
2171
2860
  if (disclosure !== undefined) target.disclosure = disclosure
2172
2861
  if (source !== undefined) target.source = source
2862
+ if (sourceKind !== undefined) {
2863
+ target.source_kind = sourceKind
2864
+ if (source === undefined) target.source = sourceKind
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)
2873
+ }
2874
+ if (speakerId !== undefined) {
2875
+ const speaker = speakerId === null ? null : String(speakerId).trim()
2876
+ if (speaker !== null && (!speaker || speaker.length > 128)) throw new Error('speaker_id must be a non-empty string up to 128 characters')
2877
+ if (speaker) target.speaker_id = speaker
2878
+ else delete target.speaker_id
2879
+ }
2880
+ if (quoteSpan !== undefined) {
2881
+ const span = normalizeQuoteSpan(quoteSpan)
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
+ }
2889
+ }
2890
+ if (storylineId !== undefined) {
2891
+ const storyline = storylineId === null ? null : String(storylineId).trim()
2892
+ if (storyline !== null && (!storyline || storyline.length > 128)) throw new Error('storyline_id must be a non-empty string up to 128 characters')
2893
+ if (storyline) target.storyline_id = storyline
2894
+ else delete target.storyline_id
2895
+ }
2896
+ if (branchId !== undefined) {
2897
+ const branch = branchId === null ? null : String(branchId).trim()
2898
+ if (branch !== null && (!branch || branch.length > 128)) throw new Error('branch_id must be a non-empty string up to 128 characters')
2899
+ if (branch) target.branch_id = branch
2900
+ else delete target.branch_id
2901
+ }
2902
+ if (knownBy !== undefined) {
2903
+ const known = normalizeKnownBy(knownBy)
2904
+ if (known && known.length) target.known_by = known
2905
+ else delete target.known_by
2906
+ }
2173
2907
  if (salientDate !== undefined) {
2174
2908
  // undefined leaves it alone, null or '' clears it, a value re-dates it. Re-
2175
2909
  // dating has to be possible: before this, a memory filed as an anniversary
@@ -2182,9 +2916,38 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2182
2916
  // Re-dating goes through the same settlement as a fresh write. A repair that
2183
2917
  // re-submits "10-29" for a body that says 明天 would otherwise re-create the
2184
2918
  // annual entry it was meant to fix.
2185
- target.salientDate = reconcileSalientDate(normalized, `${target.title || ''} ${target.content || ''}`)
2919
+ target.salientDate = reconcileSalientDate(normalized, `${target.title || ''} ${target.content || ''}`, scene)
2186
2920
  }
2187
2921
  }
2922
+ // S1:改写正文等于产生一次新的说法;重算日期字段,旧日期没有依据就删掉。
2923
+ if (textChanged || absoluteDate !== undefined) {
2924
+ const temporal = temporalFieldsOf({
2925
+ title: nextTitle,
2926
+ content: nextContent === undefined ? entry.content : nextContent,
2927
+ scene,
2928
+ salientDate: target.salientDate,
2929
+ absoluteDate,
2930
+ })
2931
+ for (const key of ['absolute_date', 'date_precision', 'date_source']) {
2932
+ if (temporal[key] === undefined) delete target[key]
2933
+ else target[key] = temporal[key]
2934
+ }
2935
+ target.event_time = temporal.event_time
2936
+ target.observed_at = temporal.observed_at
2937
+ }
2938
+ if (validFrom !== undefined) {
2939
+ const from = dateOnlyField(validFrom, 'valid_from')
2940
+ if (from) target.valid_from = from
2941
+ else delete target.valid_from
2942
+ }
2943
+ if (validTo !== undefined) {
2944
+ const to = dateOnlyField(validTo, 'valid_to')
2945
+ if (to) target.valid_to = to
2946
+ else delete target.valid_to
2947
+ }
2948
+ if (target.valid_from && target.valid_to && target.valid_from > target.valid_to) {
2949
+ throw new Error('valid_from must not be after valid_to')
2950
+ }
2188
2951
  if (context !== undefined) {
2189
2952
  const nextContext = normalizeMemoryContext(context)
2190
2953
  if (sessionIdOf(exec) && ['channelId', 'characterId', 'worldId', 'branchId'].some(key => (target.context?.[key] || '') !== (nextContext[key] || ''))) throw new Error('only the user can change a stored memory boundary')
@@ -2216,6 +2979,8 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2216
2979
  if (nextAttachments !== undefined) target.attachments = nextAttachments
2217
2980
  // 受管路由下这次更新把这一行重新提交进了当前向量空间(managed 时 commit 无条件发生)。
2218
2981
  // 戳要跟着刷新:它现在描述的是"这条在当前代际的空间里",membership 的戳腿靠它计数。
2982
+ if (commitWarning) target.vectorPending = true
2983
+ else if (commitAttempted && committedDb) delete target.vectorPending
2219
2984
  if (committedDb) {
2220
2985
  const vector = activeEntryStamp(route)
2221
2986
  if (vector) target.vector = vector
@@ -2556,6 +3321,132 @@ export function privateArchive({ exec, libraryId, id }) {
2556
3321
  * is still in the index and no longer in the engine — visible in the browser, still
2557
3322
  * deletable, never recalled from a ghost row.
2558
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
+
2559
3450
  async function privateDeleteImpl({ exec, libraryId, id }) {
2560
3451
  const scope = resolveLibrary({ exec, libraryId })
2561
3452
  if (scope.binding) assertScopeEnabled(scope.binding)
@@ -2585,8 +3476,22 @@ async function privateDeleteImpl({ exec, libraryId, id }) {
2585
3476
  if (Array.isArray(other.links) && other.links.some(link => link.to === id_)) {
2586
3477
  other.links = other.links.filter(link => link.to !== id_)
2587
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
2588
3483
  }
2589
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
+ }
2590
3495
  // Collect entities this row was the last thing keeping alive. Cleanup after
2591
3496
  // the fact, not a correctness step: if it fails (lock contention, a store
2592
3497
  // another writer holds) the delete stands, and the startup sweep gets the
@@ -2722,6 +3627,126 @@ export async function importMemories(args) {
2722
3627
  return result
2723
3628
  }
2724
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
+
2725
3750
  export async function resolveMemoryReview(args) {
2726
3751
  const action = () => resolveMemoryReviewImpl(args)
2727
3752
  const result = args.libraryId ? await withManagedPrivateWrite(args.libraryId, action) : await withManagedGlobalWrite(action)
@@ -2764,14 +3789,18 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2764
3789
  if (peeked) assertScopeEnabled(peeked, { layer: 'global' })
2765
3790
  const settings = getSettings()
2766
3791
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
3792
+ const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
3793
+ const queryDates = resolveQueryDates(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
3794
+ const searchQuery = queryDates.length ? `${query} ${queryDates.join(' ')}` : query
3795
+ const wanted = Number(topK || settings.globalTopK || 3)
2767
3796
  let index = loadGlobalIndex()
2768
3797
  const intent = managedVectorIntent()
2769
3798
  const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
2770
3799
  .filter(([, entry]) => appliesToDomain(entry, binding))) }
2771
3800
  const result = effectiveVectorRoute() !== 'lexical'
2772
- ? await managedRecall({ exec, index: domainIndex, query, topK: topK || settings.globalTopK || 3,
3801
+ ? await managedRecall({ exec, index: domainIndex, query: searchQuery, topK: wanted,
2773
3802
  libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
2774
- : localRecall(index, query, (file) => appliesToDomain(file.entry, binding))
3803
+ : localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding), { cacheKey: `global:${domainOf(binding)}`, topK: wanted })
2775
3804
  if (peeked) {
2776
3805
  const current = peekBinding(exec)
2777
3806
  if (!current) throw new Error('memory binding changed during recall; retry')
@@ -2782,22 +3811,38 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2782
3811
  if (result?.recallRoute) enriched.recallRoute = result.recallRoute
2783
3812
  if (result?.errors) enriched.errors = result.errors.slice()
2784
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)
2785
3820
  const filtered = enriched.files
2786
3821
  .filter((f) => isMemoryEligible(f.entry, { automatic: true }))
2787
3822
  .filter((f) => appliesToDomain(f.entry, binding))
2788
- .map((f, i) => ({
2789
- ...f,
2790
- // Local lexical rank is already meaningful; confidence still nudges ties, and
2791
- // a cross-session fact that has been injected three turns running gets the same
2792
- // wear penalty as a private one. `retrieval` mirrors the retrieval term of the
2793
- // score so the absolute floor cut sees the same number the score was built from.
2794
- retrieval: Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1),
2795
- score: (Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1))
2796
- * (0.85 + 0.15 * Number(f.entry.confidence ?? 0.5))
2797
- * habituationFactor(f.entry),
2798
- }))
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
+ })
2799
3844
  .sort((a, b) => b.score - a.score)
2800
- 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)
2801
3846
  return {
2802
3847
  ...enriched,
2803
3848
  files: ranked.chosen,
@@ -2947,7 +3992,11 @@ export function noteInjected({ libraryId, ids = [], at = stamp() }) {
2947
3992
  entry.lastInjectAt = at
2948
3993
  touched += 1
2949
3994
  }
2950
- 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 })
2951
4000
  if (touched > 0) bumpStats(libraryId, 'injected', touched)
2952
4001
  return touched
2953
4002
  }
@@ -2964,7 +4013,7 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
2964
4013
  entry.lastInjectAt = at
2965
4014
  touched += 1
2966
4015
  }
2967
- if (touched > 0) saveGlobalIndex(index)
4016
+ if (touched > 0) saveGlobalIndex(index, { bumpRevision: false })
2968
4017
  return touched
2969
4018
  }
2970
4019
 
@@ -2985,10 +4034,11 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
2985
4034
  return rows
2986
4035
  .filter(([id, entry]) => {
2987
4036
  if (!entry || excludeIds.has(id)) return false
2988
- if (!entry.openLoop || entry.marginalized) return false
2989
- // 'MM-DD' is an anniversary: it recurs on its own and is not a slipped promise.
2990
- if (!isDatedSalientDate(entry.salientDate)) return false
2991
- const ahead = salientDaysAhead(entry.salientDate, today)
4037
+ if (!isOpenThread(entry) || entry.marginalized) return false
4038
+ // commitment.due_at 是 S4 的权威到期日;旧数据回落到 salientDate。
4039
+ const dueDate = commitmentDueDate(entry) || (isDatedSalientDate(entry.salientDate) ? entry.salientDate : null)
4040
+ if (!dueDate) return false
4041
+ const ahead = salientDaysAhead(dueDate, today)
2992
4042
  if (ahead === null || ahead >= 0) return false
2993
4043
  // One gate for archived / suppressed / expired / pending_review / superseded and
2994
4044
  // for secret bodies: same rule as every other automatic injection surface.
@@ -3002,7 +4052,7 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
3002
4052
  })
3003
4053
  // Oldest date first: the promise that has been overdue longest is the one that
3004
4054
  // matters most. Ties fall back to age, then id, so the pick is deterministic.
3005
- .sort((a, b) => String(a[1].salientDate).localeCompare(String(b[1].salientDate))
4055
+ .sort((a, b) => String(commitmentDueDate(a[1]) || a[1].salientDate).localeCompare(String(commitmentDueDate(b[1]) || b[1].salientDate))
3006
4056
  || String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || ''))
3007
4057
  || a[0].localeCompare(b[0]))
3008
4058
  .map(([id, entry]) => ({ id, entry, recurring: true }))
@@ -3044,7 +4094,8 @@ export function dueOpenLoops({
3044
4094
  const regular = rows
3045
4095
  .filter(([id, entry]) => {
3046
4096
  if (!entry || skip.has(id) || excluded.has(id)) return false
3047
- if (!entry.openLoop || entry.marginalized) return false
4097
+ // S4:有 commitment 时 status 是权威;legacy openLoop 只在没有承诺对象时生效。
4098
+ if (!isOpenThread(entry) || entry.marginalized) return false
3048
4099
  if (!isActive(entry)) return false
3049
4100
  if (!visible(entry)) return false
3050
4101
  const age = daysSince(entry.updatedAt || entry.createdAt, now)
@@ -3060,6 +4111,33 @@ export function dueOpenLoops({
3060
4111
  return [...overdue, ...regular].slice(0, Math.max(0, Number(limit) || 0))
3061
4112
  }
3062
4113
 
4114
+ /**
4115
+ * S4.3:到期/临期(逾期、今天、明天)的未完成承诺,按 due_at 升序,最多 limit 条。
4116
+ * 只有显式 commitment 对象才走这里;legacy openLoop 仍由 dueOpenLoops 负责,
4117
+ * 两条通道不会把同一条欠账说两遍(调用方用 skipIds 去重)。
4118
+ */
4119
+ export function dueCommitments({ libraryId, now = Date.now(), sessionId = null, limit = 3, skipIds = [] } = {}) {
4120
+ if (!libraryId) return []
4121
+ const index = loadPrivateIndex(libraryId)
4122
+ const skip = new Set(skipIds || [])
4123
+ const reminders = []
4124
+ for (const [id, entry] of Object.entries(index.entries || {})) {
4125
+ if (!entry || skip.has(id) || entry.marginalized) continue
4126
+ if (!entry.commitment || typeof entry.commitment !== 'object') continue
4127
+ const commitment = commitmentOf(entry)
4128
+ if (!commitment || commitment.status !== 'open') continue
4129
+ if (!isMemoryEligible(entry, { automatic: true, now })) continue
4130
+ if (sessionId && !visibleToSession(entry, sessionId)) continue
4131
+ const due = commitmentDueState(commitment, { now })
4132
+ if (!due.dueAt || !due.dueSoon) continue
4133
+ reminders.push({ id, entry, commitment, ...due })
4134
+ }
4135
+ reminders.sort((a, b) => String(a.dueAt).localeCompare(String(b.dueAt))
4136
+ || String(a.entry.updatedAt || a.entry.createdAt || '').localeCompare(String(b.entry.updatedAt || b.entry.createdAt || ''))
4137
+ || a.id.localeCompare(b.id))
4138
+ return reminders.slice(0, Math.max(0, Number(limit) || 0))
4139
+ }
4140
+
3063
4141
  /**
3064
4142
  * Memories a sensory cue may be derived from.
3065
4143
  *
@@ -3085,7 +4163,8 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
3085
4163
  if (!isActive(entry)) return false
3086
4164
  if (!visibleToSession(entry, sessionId)) return false
3087
4165
  if (entry.sideEventId || entry.pinSource === 'side_event') return false
3088
- if (entry.disclosure === 'never_say') return false
4166
+ // S6:cue 是自动浮现;only_if_asked / never_say 都要等用户先问。
4167
+ if (!isDisclosureEligible(entry, { automatic: true, asked: false })) return false
3089
4168
  if (entry.visibility === 'secret') return false
3090
4169
  if (!String(entry.content || '').trim()) return false
3091
4170
  const at = Date.parse(entry.updatedAt || entry.createdAt || '')