dsh-memu-memory 1.2.6 → 1.2.8

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 (68) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/contributing.md +1 -1
  5. package/docs/host-adaptation.md +1 -1
  6. package/docs/memory-semantics.md +26 -4
  7. package/docs/troubleshooting.md +3 -1
  8. package/lib/backup.js +1 -1
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/budget.js +31 -0
  11. package/lib/client.js +276 -28
  12. package/lib/commitment.js +138 -0
  13. package/lib/consolidation-receipt.js +2 -0
  14. package/lib/consolidation-worker.js +3 -0
  15. package/lib/curator-policy.js +98 -0
  16. package/lib/fork-model.js +312 -0
  17. package/lib/freshness.js +24 -0
  18. package/lib/inject.js +117 -10
  19. package/lib/lexicon.js +1 -1
  20. package/lib/local-vector-service.js +4 -1
  21. package/lib/memory.js +600 -43
  22. package/lib/memu.js +4 -0
  23. package/lib/private.js +49 -8
  24. package/lib/prompts/private-consolidation.mixed.md +3 -2
  25. package/lib/prompts/private-consolidation.rp.md +7 -1
  26. package/lib/prompts/private-policy.mixed.md +1 -0
  27. package/lib/prompts/private-policy.rp.md +5 -1
  28. package/lib/prompts/system-guide.rp.md +3 -0
  29. package/lib/recall-cache.js +212 -0
  30. package/lib/rpc.js +44 -6
  31. package/lib/snippet.js +25 -0
  32. package/lib/state.js +43 -1
  33. package/lib/temporal.js +329 -0
  34. package/lib/text-retrieval.js +292 -28
  35. package/lib/tokenizer-v2.js +295 -0
  36. package/lib/tools.js +81 -4
  37. package/lib/webui/standalone.css +17 -1
  38. package/package.json +1 -1
  39. package/scripts/bench-recall.mjs +142 -0
  40. package/scripts/check-seed-compat.mjs +118 -0
  41. package/tests/backup.test.mjs +2 -2
  42. package/tests/commitment.test.mjs +144 -0
  43. package/tests/consolidation-fork.test.mjs +122 -5
  44. package/tests/curator-clusters.test.mjs +7 -1
  45. package/tests/curator-pairing.test.mjs +52 -8
  46. package/tests/disclosure.test.mjs +34 -17
  47. package/tests/dynamic-rrf.test.mjs +179 -0
  48. package/tests/fact-version.test.mjs +128 -0
  49. package/tests/fork-model.test.mjs +345 -0
  50. package/tests/help-page.test.mjs +1 -1
  51. package/tests/inject-conflict.test.mjs +94 -0
  52. package/tests/inject-guide.test.mjs +5 -3
  53. package/tests/inject.test.mjs +2 -2
  54. package/tests/injection-intent-budget.test.mjs +92 -0
  55. package/tests/lexicon-frequency.test.mjs +1 -1
  56. package/tests/loader.mjs +3 -0
  57. package/tests/memory-chain.test.mjs +140 -0
  58. package/tests/memory-fields.test.mjs +134 -0
  59. package/tests/memu-resident.test.mjs +33 -0
  60. package/tests/negation-polarity.test.mjs +135 -0
  61. package/tests/prompt-semantics.test.mjs +51 -0
  62. package/tests/query-decompose.test.mjs +62 -0
  63. package/tests/recall-cache.test.mjs +292 -0
  64. package/tests/recall-intent.test.mjs +100 -0
  65. package/tests/speaker-provenance.test.mjs +120 -0
  66. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  67. package/tests/temporal.test.mjs +124 -0
  68. package/tests/tokenizer-v2.test.mjs +142 -0
package/lib/memory.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  updatePrivateIndex, updateGlobalIndex,
9
9
  newMemoryId, getSettings, effectiveVectorRoute, getActiveCue, consumeCue,
10
10
  getLibrary, setSessionBinding, setRecallError, effectiveScope, listLibrariesAll,
11
- listLibraries, listSessionBindings, getWorkspacePolicy,
11
+ listLibraries, listSessionBindings, getWorkspacePolicy, memoryRevision,
12
12
  } from './state.js'
13
13
  import { stamp, redactSecrets, retryStoreWrite, warn } from './paths.js'
14
14
  import { scopeGenerationOf } from './consolidation-ledger.js'
@@ -22,6 +22,16 @@ import { normalizeMemoryContext, contextVisible, sameFactContext } from './conte
22
22
  import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGeneration, enrollActiveLibrary, hasActiveVectorGeneration, isVectorStateError, readVectorState, withVectorWrite } from './vector-profile.js'
23
23
  import { bigrams, dice, similarTexts, DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
24
24
  import { applyAbsorbIndexTransaction } from './curator.js'
25
+ import { recallCache, recallCacheKey } from './recall-cache.js'
26
+ import { parseAbsoluteDate, parseTemporalExpression, hasTemporalHint, resolveQueryDates, localDateKeyInZone, DEFAULT_TIME_ZONE } from './temporal.js'
27
+ import { validitySignals } from './freshness.js'
28
+ import { commitmentOf, commitmentDueDate, commitmentDueState, isOpenThread, normalizeCommitment } from './commitment.js'
29
+ import { detectQueryIntent, decomposeQuery } from './text-retrieval.js'
30
+ import { intentTopK } from './budget.js'
31
+
32
+ // P1-1 召回缓存。缓存自身出错时 fail-open,
33
+ // 但真实故障必须留痕(AGENTS.md §1 规则 10):把缓存内部的吞没错误接到 warn 上。
34
+ recallCache.setErrorHandler((info) => warn('recall cache failed open: ' + (info?.message || info)))
25
35
 
26
36
  const HALF_LIFE_DAYS = 14
27
37
  // A short-term entry is meant to live for the length of a conversation, not a
@@ -68,7 +78,10 @@ const VISIBILITIES = STORED_VISIBILITIES
68
78
  // quotable, everything else means they are our own reconstruction and must be hedged
69
79
  // when repeated. Defaulting to 'user_said' labelled every model-inferred memory as a
70
80
  // quote, which systematically inflated confidence in things nobody had said.
71
- const SOURCES = ['user_said', 'inferred', 'imagined', 'told']
81
+ // S3 追加 assistant_said / tool:助手自己说过的话、工具结果也必须可区分,不能混成
82
+ // 用户原话,也不能因为“只收用户消息”而丢掉。
83
+ const SOURCES = ['user_said', 'assistant_said', 'told', 'imagined', 'inferred', 'tool']
84
+ const SOURCE_KINDS = ['user_said', 'assistant_said', 'told', 'imagined', 'inferred', 'tool']
72
85
 
73
86
  function managedVectorIntent() {
74
87
  if (effectiveVectorRoute() !== 'managed-local') return { managed: false, route: effectiveVectorRoute(), state: null, error: null }
@@ -183,7 +196,7 @@ async function withManagedGlobalWrite(action) {
183
196
  return withVectorWrite(() => { assertVectorWriteAllowed(); return action() })
184
197
  }
185
198
 
186
- async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false }) {
199
+ async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
187
200
  const local = localRecall(index, query)
188
201
  try {
189
202
  if (intent.error) throw intent.error
@@ -191,14 +204,33 @@ async function managedRecall({ exec, index, query, topK, libraryId, automatic =
191
204
  if (byId) return { ...local, recallRoute: 'local' }
192
205
  const db = captured ? (libraryId ? captured.libraries[libraryId] : captured.global) : (libraryId ? memoryDbPath(libraryId) : globalDbPath())
193
206
  if (!db) throw new Error('managed vector generation has no database for library ' + libraryId)
194
- const semantic = await retrieveImpl({ query, db, route: intent.route, timeoutMs: HYBRID_SEMANTIC_TIMEOUT_MS })
195
- if (semantic?.parseWarning) throw new Error(semantic.parseWarning)
196
- if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
197
- if (captured) assertGeneration(captured)
198
- const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
199
- limit: hybridCandidateLimit(topK), automatic, sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
207
+ // P1-1 召回缓存:只缓存成功的语义召回——byId 与 local-fallback 都在上面短路或走
208
+ // catch,不会进入这里;producer 抛错不缓存,原样落到下面的 local-fallback。
209
+ // 键覆盖所有能改变融合结果的输入。失效三层:
210
+ // · revision = memoryRevision():state.js 在 savePrivateIndex/saveGlobalIndex/
211
+ // saveState/clearCaches 收敛处自增,本进程所有索引与状态写入(含 curator/
212
+ // graph/rpc/migrate 的写)写完键即变,无需逐写路径挂钩;
213
+ // · generation = captureGeneration() 的代数 token:向量代际切换(迁移/换档案)
214
+ // 后语义腿来自另一个向量库,键随之改变;
215
+ // · TTL(默认 120s)兜底跨进程写入、expiresAt 到点与一切漏网。
216
+ // recallCache.bumpGeneration() 是手动闸(测试/运维)。
217
+ const binding = peekBinding(exec)
218
+ const cacheKey = recallCacheKey({
219
+ query, topK, libraryId, byId, route: intent.route, generation: captured?.token ?? null,
220
+ revision: memoryRevision(), domain, automatic,
221
+ sessionId: memorySessionId(exec), context: binding?.memoryContext ?? null,
222
+ })
223
+ const result = await recallCache.wrap(cacheKey, async () => {
224
+ const semantic = await retrieveImpl({ query, db, route: intent.route, timeoutMs: HYBRID_SEMANTIC_TIMEOUT_MS })
225
+ if (semantic?.parseWarning) throw new Error(semantic.parseWarning)
226
+ if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
227
+ if (captured) assertGeneration(captured)
228
+ const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
229
+ limit: hybridCandidateLimit(topK), automatic, sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
230
+ return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug }
231
+ })
200
232
  clearRecallError(exec)
201
- return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug }
233
+ return result
202
234
  } catch (error) {
203
235
  const reason = rememberRecallError(exec, error)
204
236
  return { ...local, recallRoute: 'local-fallback', errors: ['semantic recall failed: ' + reason] }
@@ -225,6 +257,125 @@ function checkEnums({ disclosure, owner, visibility, source }) {
225
257
  throw new Error(`source must be ${SOURCES.join(', ')}`)
226
258
  }
227
259
  }
260
+
261
+ function checkSourceKind(value) {
262
+ if (value !== undefined && value !== null && !SOURCE_KINDS.includes(value)) {
263
+ throw new Error(`source_kind must be ${SOURCE_KINDS.join(', ')}`)
264
+ }
265
+ }
266
+
267
+ function normalizeQuoteSpan(value) {
268
+ if (value === undefined || value === null) return null
269
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error('quote_span must be an object like {seq, turn, textHash}')
270
+ const span = {}
271
+ for (const key of ['seq', 'turn']) {
272
+ if (value[key] === undefined || value[key] === null) continue
273
+ const number = Number(value[key])
274
+ if (!Number.isSafeInteger(number) || number < 0) throw new Error(`quote_span.${key} must be a non-negative integer`)
275
+ span[key] = number
276
+ }
277
+ if (value.textHash !== undefined && value.textHash !== null) {
278
+ const hash = String(value.textHash)
279
+ if (!hash || hash.length > 128) throw new Error('quote_span.textHash must be a short string')
280
+ span.textHash = hash
281
+ }
282
+ return Object.keys(span).length ? span : null
283
+ }
284
+
285
+ function normalizeKnownBy(value) {
286
+ if (value === undefined || value === null) return undefined
287
+ if (!Array.isArray(value) || value.length > 30) throw new Error('known_by must be an array of at most 30 identities')
288
+ const result = []
289
+ for (const item of value) {
290
+ if (typeof item !== 'string' || !item.trim() || item.length > 128) throw new Error('known_by entries must be non-empty strings up to 128 characters')
291
+ if (!result.includes(item.trim())) result.push(item.trim())
292
+ }
293
+ return result
294
+ }
295
+
296
+ function defaultSpeakerFor(kind) {
297
+ if (kind === 'user_said') return 'user'
298
+ if (kind === 'assistant_said') return 'assistant'
299
+ if (kind === 'tool') return 'tool'
300
+ return 'unknown'
301
+ }
302
+
303
+ /** Old entries have no speaker_id/source_kind; derive the closest honest answer. */
304
+ export function speakerOfEntry(entry) {
305
+ if (!entry || typeof entry !== 'object') return 'unknown'
306
+ if (typeof entry.speaker_id === 'string' && entry.speaker_id.trim()) return entry.speaker_id.trim()
307
+ return defaultSpeakerFor(entry.source_kind || entry.source)
308
+ }
309
+
310
+ export function sourceKindOfEntry(entry) {
311
+ if (!entry || typeof entry !== 'object') return 'inferred'
312
+ if (SOURCE_KINDS.includes(entry.source_kind)) return entry.source_kind
313
+ if (SOURCE_KINDS.includes(entry.source)) return entry.source
314
+ return 'inferred'
315
+ }
316
+
317
+ /**
318
+ * S3.2:查询里明确问“我说过/你说过/他说的”时,给召回一个说话人方向。
319
+ * 只排除“明确不是这个人”的条目;缺少 speaker 的旧条目保留,避免一次性清空召回。
320
+ */
321
+ export function detectSpeakerQuery(query) {
322
+ const text = String(query || '')
323
+ if (/(?:我(?:之前|先前)?(?:说过|说了|提过|讲过|问过|答应的?))/u.test(text)) return 'user'
324
+ if (/(?:你(?:之前|先前)?(?:说过|说了|提过|讲过|答应过|答应的?|承诺过))/u.test(text)) return 'assistant'
325
+ if (/(?:[他她](?:们)?(?:之前|先前)?(?:说过|说了|提过|讲到|讲了))/u.test(text)) return 'third'
326
+ return null
327
+ }
328
+
329
+ function speakerMatchesFilter(entry, filter) {
330
+ if (!filter) return true
331
+ const speaker = speakerOfEntry(entry)
332
+ if (speaker === 'unknown') return true
333
+ if (filter === 'user') return speaker === 'user'
334
+ if (filter === 'assistant') return speaker === 'assistant'
335
+ if (filter === 'third') return speaker !== 'user' && speaker !== 'assistant' && speaker !== 'tool'
336
+ return true
337
+ }
338
+
339
+ // S2:fact_key 是“同一条事实”的归一化键。显式键保留调用方的命名;没有显式键时
340
+ // 用 owner + 标题归一化,只用来给同一事实的多个版本编号,不改变旧的冲突判定。
341
+ export function normalizeFactKey(value) {
342
+ if (value === undefined || value === null) return null
343
+ const text = String(value).normalize('NFKC').trim().toLowerCase()
344
+ if (!text) return null
345
+ const cleaned = text.replace(/\s+/g, '_').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 200)
346
+ return cleaned || null
347
+ }
348
+
349
+ export function deriveFactKey({ owner = 'me', title = '', content = '' } = {}) {
350
+ const source = String(title || content || '').normalize('NFKC').toLowerCase()
351
+ const cleaned = source.replace(/[\s\p{P}\p{S}]+/gu, '').slice(0, 160)
352
+ if (!cleaned) return null
353
+ return `${String(owner || 'me').toLowerCase()}:${cleaned}`
354
+ }
355
+
356
+ function nextFactVersion(entries, factKey, context, excludeId = null) {
357
+ let max = 0
358
+ for (const [id, entry] of Object.entries(entries || {})) {
359
+ if (id === excludeId || !entry || entry.fact_key !== factKey) continue
360
+ if (!sameFactContext(entry.context, context)) continue
361
+ const version = Number(entry.version)
362
+ if (Number.isFinite(version)) max = Math.max(max, version)
363
+ }
364
+ return max + 1
365
+ }
366
+
367
+ function relationTarget(index, ref, { context, sessionId, label }) {
368
+ const targetId = resolveEntryId(index, ref)
369
+ const target = index.entries[targetId]
370
+ if (!target) throw new Error(`${label} target is missing: ${targetId}`)
371
+ if (['archived', 'suppressed', 'superseded', 'pending_review'].includes(target.status)) {
372
+ throw new Error(`${label} target ${targetId} is ${target.status}; only an active memory can be related to`)
373
+ }
374
+ if (!sameFactContext(target.context, context)) throw new Error(`${label} target belongs to another conversation scope`)
375
+ if (sessionId && !visibleForDedupe(target, sessionId)) throw new Error(`${label} target is not visible in this conversation`)
376
+ return { id: targetId, entry: target }
377
+ }
378
+
228
379
  // Below this, the present-mood read is noise and must not bend retrieval at all.
229
380
  const MOOD_MIN_STRENGTH = 0.15
230
381
  // Long enough that the reason has to say what happened and why it can be let go,
@@ -437,6 +588,79 @@ export function reconcileSalientDate(value, text, now = new Date()) {
437
588
  return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}-${pad2(target.getDate())}`
438
589
  }
439
590
 
591
+ function parseExplicitInstant(value, label) {
592
+ if (value === undefined || value === null || String(value).trim() === '') return null
593
+ const at = Date.parse(String(value))
594
+ if (!Number.isFinite(at)) throw new Error(`${label} must be an explicit ISO date/time`)
595
+ return new Date(at)
596
+ }
597
+
598
+ // The turn's logical time is the only clock a relative date may be resolved
599
+ // against. A user saying "明天" in a scene set in 1998 must not get the wall
600
+ // clock's tomorrow. Order: an explicit per-write stamp, the context's occurredAt,
601
+ // then the conversation's sceneTime, and only then the wall clock.
602
+ function sceneTimeOf({ binding, context, observedAt } = {}) {
603
+ return parseExplicitInstant(observedAt, 'observed_at')
604
+ || parseExplicitInstant(context?.occurredAt, 'occurred_at')
605
+ || parseExplicitInstant(binding?.sceneTime, 'scene_time')
606
+ || new Date()
607
+ }
608
+
609
+ function dateOnlyField(value, label) {
610
+ if (value === undefined) return undefined
611
+ if (value === null || String(value).trim() === '') return null
612
+ const normalized = parseAbsoluteDate(value)
613
+ if (!normalized) throw new Error(`${label} must be YYYY-MM-DD`)
614
+ return normalized
615
+ }
616
+
617
+ const DATE_PRECISIONS = ['day', 'month', 'year', 'unknown']
618
+
619
+ /**
620
+ * S1 的写入字段:event_time / observed_at / absolute_date / date_precision /
621
+ * valid_from / valid_to / date_source。原文不改写,日期只作为可检索的结构化字段。
622
+ * 解析失败不猜;只有确实出现相对时间词时才标 date_precision=unknown。
623
+ */
624
+ function temporalFieldsOf({ title, content, scene, salientDate, absoluteDate, validFrom, validTo, datePrecision }) {
625
+ if (datePrecision !== undefined && datePrecision !== null && !DATE_PRECISIONS.includes(datePrecision)) {
626
+ throw new Error(`date_precision must be ${DATE_PRECISIONS.join(', ')}`)
627
+ }
628
+ const fields = {
629
+ event_time: scene.toISOString(),
630
+ observed_at: scene.toISOString(),
631
+ }
632
+ const explicit = dateOnlyField(absoluteDate, 'absolute_date')
633
+ const fromSalient = isDatedSalientDate(salientDate) ? salientDate : null
634
+ if (explicit) {
635
+ fields.absolute_date = explicit
636
+ fields.date_precision = datePrecision || 'day'
637
+ fields.date_source = 'explicit'
638
+ } else if (fromSalient) {
639
+ fields.absolute_date = fromSalient
640
+ fields.date_precision = datePrecision || 'day'
641
+ fields.date_source = 'explicit'
642
+ } else {
643
+ const text = `${title || ''}\n${content || ''}`
644
+ const parsed = parseTemporalExpression(text, { now: scene, timeZone: DEFAULT_TIME_ZONE })
645
+ if (parsed) {
646
+ fields.absolute_date = parsed.absoluteDate
647
+ fields.date_precision = datePrecision || parsed.precision
648
+ fields.date_source = parsed.dateSource
649
+ } else if (hasTemporalHint(text)) {
650
+ fields.date_precision = 'unknown'
651
+ fields.date_source = 'relative'
652
+ }
653
+ }
654
+ const from = dateOnlyField(validFrom, 'valid_from')
655
+ const to = dateOnlyField(validTo, 'valid_to')
656
+ if (from) fields.valid_from = from
657
+ if (to) fields.valid_to = to
658
+ if (fields.valid_from && fields.valid_to && fields.valid_from > fields.valid_to) {
659
+ throw new Error('valid_from must not be after valid_to')
660
+ }
661
+ return fields
662
+ }
663
+
440
664
  // How many days ahead today is from a dated memory (0 = due today, negative =
441
665
  // already past). An anniversary has no distance: it is true every year.
442
666
  export function salientDaysAhead(salientDate, now = new Date()) {
@@ -690,7 +914,20 @@ export function isMemoryEligible(entry, { automatic = false, now = Date.now() }
690
914
  // deadline itself has to be authoritative. An expired draft must never reach a
691
915
  // prompt just because the cleaner has not run yet.
692
916
  if (entry.expiresAt && (Date.parse(entry.expiresAt) || 0) <= now) return false
917
+ // S1 有效窗口:只有显式写下的 valid_from/valid_to 才参与;缺字段的旧数据照常召回。
918
+ if (!validitySignals(entry, { now }).valid) return false
693
919
  if (automatic && entry.visibility === 'secret') return false
920
+ // S6:never_say 不自动进入任何注入面(召回、锚点、提醒);显式工具召回仍可读。
921
+ if (automatic && entry.disclosure === 'never_say') return false
922
+ return true
923
+ }
924
+
925
+ /** S6 的 disclosure 门:only_if_asked 只在用户明确问到时才自动注入。 */
926
+ export function isDisclosureEligible(entry, { automatic = false, asked = false } = {}) {
927
+ if (!automatic) return true
928
+ const disclosure = entry?.disclosure || 'can_tell'
929
+ if (disclosure === 'never_say') return false
930
+ if (disclosure === 'only_if_asked') return asked === true
694
931
  return true
695
932
  }
696
933
 
@@ -718,8 +955,8 @@ function queryTokens(query) {
718
955
  return [...tokens].filter(Boolean)
719
956
  }
720
957
 
721
- function lexicalScore(entry, tokens) {
722
- if (!tokens.length) return 0
958
+ function lexicalScore(entry, tokens, queryDates = []) {
959
+ if (!tokens.length && !queryDates.length) return 0
723
960
  const title = String(entry?.title || '').toLowerCase()
724
961
  const content = [entry?.content || '', ...(entry?.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`)].join(' ').toLowerCase()
725
962
  const tags = (Array.isArray(entry?.tags) ? entry.tags : []).join(' ').toLowerCase()
@@ -729,9 +966,11 @@ function lexicalScore(entry, tokens) {
729
966
  if (tags.includes(token)) score += 2
730
967
  if (content.includes(token)) score += 1
731
968
  }
969
+ // S1:日期是结构化字段,不在正文里也要能被检索到(“那天发生了什么”)。
970
+ if (entry?.absolute_date && queryDates.includes(entry.absolute_date)) score += 4
732
971
  // Longer queries should not win just by having more tokens in common; the
733
972
  // average keeps scores comparable across one-word and sentence queries.
734
- return score / tokens.length
973
+ return tokens.length ? score / tokens.length : score
735
974
  }
736
975
 
737
976
  function localIndexFiles(index) {
@@ -752,11 +991,12 @@ function localRecall(index, query, filter = () => true) {
752
991
  return { files: files.filter(file => file.name === id).map(file => ({ ...file, lexical: 5 })), segments: [], resources: [], raw: null, parseWarning: null }
753
992
  }
754
993
  const tokens = queryTokens(query)
994
+ const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
755
995
  const ordered = tokens.length === 0
756
996
  ? files.sort((a, b) => String(b.entry?.updatedAt || b.entry?.createdAt || '')
757
997
  .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
758
998
  : files
759
- .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens) }))
999
+ .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates) }))
760
1000
  .filter((file) => file.lexical > 0)
761
1001
  .sort((a, b) => b.lexical - a.lexical
762
1002
  || String(b.entry?.updatedAt || b.entry?.createdAt || '')
@@ -990,8 +1230,11 @@ function recallScore(file, rank, context) {
990
1230
  // ride the same touch/decay loop as the original and could outlive it in rank —
991
1231
  // the "duplicates age better than the truth" loop this closes.
992
1232
  const duplicateFactor = entry.duplicateOf ? 0.7 : 1
1233
+ // S1:查询里点了具体日期时,日期命中是强信号;只做温和提升,不盖过语义匹配。
1234
+ const temporalFactor = Array.isArray(context.queryDates) && entry.absolute_date
1235
+ && context.queryDates.includes(entry.absolute_date) ? 1.35 : 1
993
1236
 
994
- return retrieval * strengthTerm * marginal * moodBias * peakEnd * primacy * openLoopBias * habituation * arousalTerm * dominanceTerm * duplicateFactor
1237
+ return retrieval * strengthTerm * marginal * moodBias * peakEnd * primacy * openLoopBias * habituation * arousalTerm * dominanceTerm * duplicateFactor * temporalFactor
995
1238
  }
996
1239
 
997
1240
  /**
@@ -1074,6 +1317,10 @@ function privateWeighted(result, max, context = {}) {
1074
1317
  lastCreatedAt: null,
1075
1318
  sessionId: null,
1076
1319
  now: Date.now(),
1320
+ queryDates: [],
1321
+ speakerFilter: null,
1322
+ intent: 'general',
1323
+ disclosureAsked: false,
1077
1324
  retrievalFloor: RETRIEVAL_FLOOR,
1078
1325
  ...context,
1079
1326
  }
@@ -1085,6 +1332,11 @@ function privateWeighted(result, max, context = {}) {
1085
1332
  // memories. Filtering here keeps the anchor and the recall block in agreement.
1086
1333
  .filter((f) => visibleToSession(f.entry, ctx.sessionId))
1087
1334
  .filter((f) => !ctx.automatic || f.entry?.visibility !== 'secret')
1335
+ // S6:never_say 由 isMemoryEligible 挡掉;only_if_asked 只在 boundary 意图时放行。
1336
+ .filter((f) => !ctx.automatic || f.entry?.disclosure !== 'only_if_asked' || ctx.disclosureAsked === true)
1337
+ // S3.2:明确问“我说过/你说过/他说的”时,只留下说话人对得上的条目;
1338
+ // 没有 speaker 字段的旧条目保留,避免一次查询把历史记忆全清空。
1339
+ .filter((f) => speakerMatchesFilter(f.entry, ctx.speakerFilter))
1088
1340
  .map((f, i) => ({ ...f, score: recallScore(f, i, ctx), retrieval: retrievalShare(f, i) }))
1089
1341
  .sort((a, b) => b.score - a.score)
1090
1342
  const { chosen, skipped } = mmrSelect(cutWeakScores(items, ctx.relevanceThreshold, ctx.retrievalFloor), max)
@@ -1250,6 +1502,20 @@ async function privateRememberImpl({
1250
1502
  emotion = undefined, dominance = undefined, emotionSource = null,
1251
1503
  attachments, track = 'memory',
1252
1504
  context,
1505
+ // S1 time normalization. observed_at defaults to the turn's logical time; the
1506
+ // explicit date fields exist so a caller that already knows the absolute date
1507
+ // does not have to make the parser re-derive it from prose.
1508
+ observedAt = null, absoluteDate = null, validFrom = null, validTo = null, datePrecision = null,
1509
+ // S3 provenance: who said it and how we know.
1510
+ speakerId = null, sourceKind = null, quoteSpan = null,
1511
+ storylineId = null, branchId = null, knownBy = null,
1512
+ // S4 commitment. `open_loop` stays as a compatibility flag; when a commitment
1513
+ // object exists its status is authoritative.
1514
+ commitment = null,
1515
+ // S2 versioned facts. An explicit fact_key declares "this is the same fact";
1516
+ // conflicts_with keeps both versions active and cross-linked, supersedes retires
1517
+ // the old row without deleting its text.
1518
+ factKey = null, conflictsWith = null, supersedes = null,
1253
1519
  // Escape hatch for the duplicate gate : two genuine
1254
1520
  // observations of the same fact on the same day are a legal write. Off by
1255
1521
  // default — the model must say it looked, not default past the gate.
@@ -1257,6 +1523,7 @@ async function privateRememberImpl({
1257
1523
  }) {
1258
1524
  const scope = resolveLibrary({ exec, libraryId })
1259
1525
  const binding = scope.binding
1526
+ const scene = sceneTimeOf({ binding, context, observedAt })
1260
1527
  const memoryContext = normalizeMemoryContext({ ...binding?.memoryContext, ...context })
1261
1528
  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')
1262
1529
  if (sessionIdOf(exec) && !contextVisible({ ...memoryContext, knownBy: [] }, binding?.memoryContext)) {
@@ -1280,7 +1547,7 @@ async function privateRememberImpl({
1280
1547
  // An unreadable date is refused instead of dropped. Dropping it looked like
1281
1548
  // success to the caller while losing the only part of the memory it asked for:
1282
1549
  // a date that never fires is indistinguishable from no date at all.
1283
- let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`)
1550
+ let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`, scene)
1284
1551
  // 模型常把日期写进正文却漏填 salient_date(详情页日期栏因此为空)。只有显式传了
1285
1552
  // 非法值才报错;什么都没传时,从文本取唯一的 YYYY-MM-DD 作为兜底。
1286
1553
  const explicitDate = salientDate !== null && salientDate !== undefined && String(salientDate).trim()
@@ -1294,6 +1561,48 @@ async function privateRememberImpl({
1294
1561
  if (title !== undefined) title = redactSecrets(title)
1295
1562
  if (!LAYERS.includes(layer)) throw new Error(`unknown layer: ${layer}; use ${LAYERS.join(', ')}`)
1296
1563
  checkEnums({ disclosure, owner, visibility, source })
1564
+ const temporal = temporalFieldsOf({
1565
+ title, content, scene, salientDate: normalizedSalientDate,
1566
+ absoluteDate, validFrom, validTo, datePrecision,
1567
+ })
1568
+ checkSourceKind(sourceKind)
1569
+ if (sourceKind && source !== 'inferred' && source !== sourceKind) {
1570
+ throw new Error('source and source_kind disagree; send one provenance for this memory')
1571
+ }
1572
+ if (sourceKind) source = sourceKind
1573
+ const effectiveSourceKind = SOURCE_KINDS.includes(source) ? source : 'inferred'
1574
+ const explicitSpeaker = speakerId === null || speakerId === undefined ? null : String(speakerId).trim()
1575
+ if (explicitSpeaker !== null && (!explicitSpeaker || explicitSpeaker.length > 128)) {
1576
+ throw new Error('speaker_id must be a non-empty string up to 128 characters')
1577
+ }
1578
+ const effectiveSpeaker = explicitSpeaker || memoryContext.speakerId || defaultSpeakerFor(effectiveSourceKind)
1579
+ const explicitStoryline = storylineId === null || storylineId === undefined ? null : String(storylineId).trim()
1580
+ if (explicitStoryline !== null && (!explicitStoryline || explicitStoryline.length > 128)) {
1581
+ throw new Error('storyline_id must be a non-empty string up to 128 characters')
1582
+ }
1583
+ const explicitBranch = branchId === null || branchId === undefined ? null : String(branchId).trim()
1584
+ if (explicitBranch !== null && (!explicitBranch || explicitBranch.length > 128)) {
1585
+ throw new Error('branch_id must be a non-empty string up to 128 characters')
1586
+ }
1587
+ const quote = normalizeQuoteSpan(quoteSpan)
1588
+ const known = normalizeKnownBy(knownBy)
1589
+ const provenance = {
1590
+ speaker_id: effectiveSpeaker,
1591
+ source_kind: effectiveSourceKind,
1592
+ ...(quote ? { quote_span: quote } : {}),
1593
+ ...(explicitStoryline ? { storyline_id: explicitStoryline } : {}),
1594
+ branch_id: explicitBranch || memoryContext.branchId || null,
1595
+ ...(known !== undefined
1596
+ ? { known_by: known }
1597
+ : (memoryContext.knownBy?.length ? { known_by: memoryContext.knownBy } : {})),
1598
+ }
1599
+ // S4:显式承诺优先;open_loop=true 的旧调用也落一条 open 承诺,due_at 取本轮
1600
+ // 已解析出的日期(没有就为空)。commitment.status 从这里开始就是权威。
1601
+ const commitmentDue = temporal.absolute_date || (isDatedSalientDate(normalizedSalientDate) ? normalizedSalientDate : null)
1602
+ const explicitCommitment = normalizeCommitment(commitment, { fallbackDueAt: commitmentDue })
1603
+ const derivedCommitment = explicitCommitment || (openLoop
1604
+ ? normalizeCommitment({ status: 'open', action: title || content, due_at: commitmentDue }, { fallbackAction: title || content })
1605
+ : null)
1297
1606
  // A short-term entry is a draft with a deadline. With the layer switched off the
1298
1607
  // write is refused rather than quietly upgraded to permanent memory, because the
1299
1608
  // model asked for something disposable and would otherwise pollute the durable
@@ -1331,6 +1640,37 @@ async function privateRememberImpl({
1331
1640
  && (item.attachments || []).some(attachment => media.some(candidate => candidate.sha256 === attachment.sha256)))
1332
1641
  : null
1333
1642
  const id = previousHabit?.[0] || newMemoryId('mem')
1643
+ // S2:显式 conflicts_with / supersedes 先解析目标;显式 fact_key 且没有显式关系时,
1644
+ // 同一 fact_key 的最近一个 active 条目自动成为冲突对(两条都保留、互指)。
1645
+ const memorySession = memorySessionId(exec)
1646
+ const requestedFactKey = normalizeFactKey(factKey)
1647
+ if (factKey !== null && factKey !== undefined && !requestedFactKey) throw new Error('fact_key must be a non-empty string')
1648
+ if (conflictsWith && supersedes) throw new Error('a memory cannot both conflict with and supersede another memory')
1649
+ let relation = null
1650
+ if (conflictsWith) {
1651
+ relation = { kind: 'conflict', ...relationTarget(index, conflictsWith, { context: memoryContext, sessionId: memorySession, label: 'conflicts_with' }) }
1652
+ } else if (supersedes) {
1653
+ relation = { kind: 'supersede', ...relationTarget(index, supersedes, { context: memoryContext, sessionId: memorySession, label: 'supersedes' }) }
1654
+ }
1655
+ if (!relation && requestedFactKey) {
1656
+ const candidates = Object.entries(index.entries)
1657
+ .filter(([otherId, other]) => otherId !== id && other && isMemoryEligible(other)
1658
+ && other.fact_key === requestedFactKey && sameFactContext(other.context, memoryContext)
1659
+ && visibleForDedupe(other, memorySession))
1660
+ .sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || ''))
1661
+ || a[0].localeCompare(b[0]))
1662
+ if (candidates.length) relation = { kind: 'conflict', id: candidates[0][0], entry: candidates[0][1] }
1663
+ }
1664
+ const factKeyValue = requestedFactKey || relation?.entry?.fact_key
1665
+ || deriveFactKey({ owner, title: title || content, content })
1666
+ const relationId = relation?.id || null
1667
+ const relationKind = relation?.kind || null
1668
+ const relationEntry = relation?.entry || null
1669
+ const version = relationId
1670
+ ? Math.max(1, Number(relationEntry?.version) || 1) + 1
1671
+ : (previousHabit?.[1]?.fact_key === factKeyValue
1672
+ ? Math.max(1, Number(previousHabit[1].version) || 1)
1673
+ : nextFactVersion(index.entries, factKeyValue, memoryContext, id))
1334
1674
  // A malformed share is refused here rather than clamped later: a negative or
1335
1675
  // non-finite composition is a caller bug, and repairing it silently would keep the
1336
1676
  // bug alive while the entry looks fine.
@@ -1360,7 +1700,8 @@ async function privateRememberImpl({
1360
1700
  accessCount: previousHabit?.[1]?.accessCount || 0,
1361
1701
  strength: layer === 'must_remember' ? 1 : 0.8,
1362
1702
  marginalized: false,
1363
- openLoop: !!openLoop,
1703
+ openLoop: derivedCommitment ? derivedCommitment.status === 'open' : !!openLoop,
1704
+ ...(derivedCommitment ? { commitment: derivedCommitment } : {}),
1364
1705
  disclosure,
1365
1706
  owner,
1366
1707
  visibility,
@@ -1390,6 +1731,11 @@ async function privateRememberImpl({
1390
1731
  : Math.max(0, Math.min(1, Number(arousal) || 0)),
1391
1732
  peak: peak === true,
1392
1733
  salientDate: normalizedSalientDate,
1734
+ ...temporal,
1735
+ ...provenance,
1736
+ ...(factKeyValue ? { fact_key: factKeyValue, version } : {}),
1737
+ ...(relationKind === 'conflict' && relationId ? { conflicts_with: relationId } : {}),
1738
+ ...(relationKind === 'supersede' && relationId ? { supersedes: relationId } : {}),
1393
1739
  }
1394
1740
  // Flashbulb memory: store vividness and accuracy separately. `confidence` is
1395
1741
  // what the model claims; `accuracy` is what a charged moment is actually worth.
@@ -1400,8 +1746,10 @@ async function privateRememberImpl({
1400
1746
  // true. Same mechanism the global curator uses; until now the private side had none.
1401
1747
  // Hidden rows are excluded (5.1): otherwise a visible write could learn an id
1402
1748
  // through conflictingWith, and a hidden claim could hold an unrelated new one.
1403
- const memorySession = memorySessionId(exec)
1404
- const conflict = findConflict(Object.fromEntries(Object.entries(index.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1749
+ // S2 的显式冲突对/取代链已经由关系字段表达,不再走旧的 pending_review 兜底。
1750
+ const conflict = relationId
1751
+ ? null
1752
+ : findConflict(Object.fromEntries(Object.entries(index.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1405
1753
  if (conflict) {
1406
1754
  entry.status = 'pending_review'
1407
1755
  entry.conflictingWith = conflict.id
@@ -1418,7 +1766,7 @@ async function privateRememberImpl({
1418
1766
  // it duplicateOf so recall can keep one seat per fact.
1419
1767
  let duplicate = null
1420
1768
  let hiddenDuplicate = null
1421
- if (!conflict && allowDuplicate !== true) {
1769
+ if (!conflict && !relationId && allowDuplicate !== true) {
1422
1770
  const text = `${entry.title || ''} ${content || ''}`
1423
1771
  for (const [otherId, other] of Object.entries(index.entries)) {
1424
1772
  if (otherId === id || !isMemoryEligible(other)) continue
@@ -1503,7 +1851,9 @@ async function privateRememberImpl({
1503
1851
  if (sessionIdOf(exec) && (!currentBinding || currentBinding.libraryId !== scope.libraryId)) throw new Error('memory scope changed during write; retry')
1504
1852
  if (currentBinding) assertScopeEnabled(currentBinding)
1505
1853
  if (previousHabit && JSON.stringify(fresh.entries[id]) !== JSON.stringify(previousHabit[1])) throw new Error('habit changed concurrently; recall and retry')
1506
- const latestConflict = findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1854
+ const latestConflict = relationId
1855
+ ? null
1856
+ : findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1507
1857
  if (latestConflict && !conflict) {
1508
1858
  if (db) throw new Error('memory conflict changed during write; retry for review')
1509
1859
  entry.status = 'pending_review'
@@ -1513,7 +1863,7 @@ async function privateRememberImpl({
1513
1863
  // 5.4:预检在 await 之前,提交期间另一个 turn 可能刚写入同事实。临界区用同一
1514
1864
  // 尺子重扫;命中就 retry(有向量则 throw 让 compensation 撤掉刚提交的行),
1515
1865
  // lexical 路由直接暂扣为 near_duplicate,不双写也不丢文本。
1516
- const latestDuplicate = allowDuplicate
1866
+ const latestDuplicate = allowDuplicate || relationId
1517
1867
  ? { duplicate: null, hidden: false }
1518
1868
  : findNearDuplicate(fresh.entries, {
1519
1869
  id, title: entry.title, content: entry.content, context: entry.context, sessionId: memorySession,
@@ -1529,6 +1879,23 @@ async function privateRememberImpl({
1529
1879
  if (pinned >= Number(getSettings().mustRememberCap || 12)) throw new Error('must_remember soft cap reached; retry as long_term')
1530
1880
  }
1531
1881
  fresh.entries[id] = entry
1882
+ // S2:关系是双向的,且在同一个索引事务里落地,避免只写一半。
1883
+ if (relationId && relationKind === 'conflict') {
1884
+ const target = fresh.entries[relationId]
1885
+ if (!target) throw new Error('conflict target disappeared during write; retry')
1886
+ target.conflicts_with = id
1887
+ target.conflictAt = stamp()
1888
+ }
1889
+ if (relationId && relationKind === 'supersede') {
1890
+ const target = fresh.entries[relationId]
1891
+ if (!target) throw new Error('supersede target disappeared during write; retry')
1892
+ target.status = 'superseded'
1893
+ target.supersededBy = id
1894
+ // 旧正文保留,只落下有效期终点;validTo 兼容旧 UI/复核字段。
1895
+ const endedAt = localDateKeyInZone(scene, DEFAULT_TIME_ZONE)
1896
+ target.valid_to = endedAt
1897
+ target.validTo = endedAt
1898
+ }
1532
1899
  }))
1533
1900
  } catch (error) {
1534
1901
  if (db) await compensatePrivateCommit(error, { libraryId: scope.libraryId, id, route, db, expectedEntry: previousHabit?.[1] || null })
@@ -1538,7 +1905,7 @@ async function privateRememberImpl({
1538
1905
  if (layer === 'must_remember' && pinSource === 'side_event') {
1539
1906
  consumeCue(sessionIdOf(exec), sideEventId)
1540
1907
  }
1541
- return { id, entry, result, conflict: entry.conflictingWith || null }
1908
+ return { id, entry, result, conflict: entry.conflictingWith || null, conflictsWith: entry.conflicts_with || null, supersedes: entry.supersedes || null }
1542
1909
  }
1543
1910
 
1544
1911
  // Bulk restore of an exported library. This is a *restore*, not a decision, so it
@@ -1761,7 +2128,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
1761
2128
  }
1762
2129
  const managed = await managedRecall({
1763
2130
  exec, index: scoped, query, topK, libraryId: source.libraryId,
1764
- automatic, intent, retrieveImpl, byId,
2131
+ automatic, intent, retrieveImpl, byId, domain,
1765
2132
  })
1766
2133
  lists.push({ libraryId: source.libraryId, files: managed.files || [], errors: managed.errors || [] })
1767
2134
  }
@@ -1817,8 +2184,15 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1817
2184
  const settings = getSettings()
1818
2185
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
1819
2186
  const byId = /^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())
2187
+ // S1:相对日期在召回前先落到绝对日期;sceneTime 是这一轮的逻辑时间。
2188
+ // S5:同一处识别意图并抽取日期/实体,意图决定候选数与过滤策略。
2189
+ const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
2190
+ const recallIntent = detectQueryIntent(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2191
+ const decomposed = decomposeQuery(query, recallIntent, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
2192
+ const queryDates = decomposed.dates
2193
+ const searchQuery = decomposed.expanded
1820
2194
  const route = effectiveVectorRoute(settings)
1821
- const wanted = Number(topK || settings.privateTopK || 4)
2195
+ const wanted = intentTopK(recallIntent, Number(topK || settings.privateTopK || 4))
1822
2196
  const domain = domainOf(binding)
1823
2197
  const sources = (settings.crossLibraryRecall === true
1824
2198
  ? crossLibrarySources(binding, domain)
@@ -1828,9 +2202,9 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1828
2202
  // exists when another qualifying library is actually present.
1829
2203
  const result = sources.length === 1
1830
2204
  ? (route === 'lexical' || byId
1831
- ? { ...localRecall(sources[0].index, query), recallRoute: 'local' }
1832
- : await managedRecall({ exec, index: sources[0].index, query, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId }))
1833
- : await recallCrossLibrary({ exec, sources, query, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
2205
+ ? { ...localRecall(sources[0].index, searchQuery), recallRoute: 'local' }
2206
+ : await managedRecall({ exec, index: sources[0].index, query: searchQuery, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2207
+ : await recallCrossLibrary({ exec, sources, query: searchQuery, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
1834
2208
  const current = peekBinding(exec)
1835
2209
  if (!current || current.libraryId !== binding.libraryId) throw new Error('memory scope changed during recall; retry')
1836
2210
  assertScopeEnabled(current)
@@ -1858,7 +2232,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1858
2232
  (source.libraryId === binding.libraryId ? index : source.index).entries || {},
1859
2233
  ).map((entry) => ({ entry }))))
1860
2234
  const mood = moodDecay(binding.mood)
1861
- const scored = privateWeighted(enriched, Number(topK || settings.privateTopK || 4), {
2235
+ const scored = privateWeighted(enriched, wanted, {
1862
2236
  // Three independent legs: a clear composition, an arousal away from rest, or a
1863
2237
  // clear sense of control. A null composition only closes the first one — a tense
1864
2238
  // room with no clear good/bad reading still changes which memories come up.
@@ -1870,11 +2244,39 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1870
2244
  firstCreatedAt: span.first,
1871
2245
  lastCreatedAt: span.last,
1872
2246
  relevanceThreshold: threshold,
2247
+ queryDates,
2248
+ intent: recallIntent,
2249
+ disclosureAsked: recallIntent === 'boundary',
2250
+ speakerFilter: detectSpeakerQuery(query),
1873
2251
  // The asking conversation's context is what memories are filtered against; the id is
1874
2252
  // only how that context is looked up.
1875
2253
  sessionId: memorySessionId(exec),
1876
2254
  automatic: purpose === 'automatic',
1877
2255
  })
2256
+ // S2:命中冲突的一侧时,把另一侧也带上。两条都保留、都 active,注入层会把
2257
+ // 它们渲染成一张“未确认哪版为准”的冲突卡;这里只保证成对出现。
2258
+ const paired = new Set((scored.files || []).map((file) => file.name))
2259
+ const conflictPairs = []
2260
+ for (const file of (scored.files || []).slice()) {
2261
+ const otherId = file.entry?.conflicts_with
2262
+ if (!otherId || paired.has(otherId)) continue
2263
+ const other = index.entries[otherId]
2264
+ if (!other || !isMemoryEligible(other, { automatic: purpose === 'automatic', now: Date.now() })) continue
2265
+ if (!visibleToSession(other, memorySessionId(exec))) continue
2266
+ file.conflictPair = otherId
2267
+ scored.files.push({
2268
+ name: otherId,
2269
+ description: other.title || '',
2270
+ content: String(other.content || ''),
2271
+ entry: other,
2272
+ strength: decayStrength(other),
2273
+ createdAtIdentity: other.createdAt || null,
2274
+ conflictPair: file.name,
2275
+ })
2276
+ paired.add(otherId)
2277
+ conflictPairs.push({ a: file.name, b: otherId })
2278
+ }
2279
+ if (conflictPairs.length) scored.conflictPairs = conflictPairs
1878
2280
  // Being recalled is being used, and a memory that keeps being used should not fade
1879
2281
  // like one nobody ever touches. Group by the library each hit came from so a
1880
2282
  // cross-library recall touches the owning index, not the bound one.
@@ -1913,6 +2315,37 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1913
2315
  }
1914
2316
  try { file.related = recallRelations(fileLibraryId, fileIndex, file.name, memorySessionId(exec)) } catch { file.related = [] }
1915
2317
  }
2318
+ // S5 多跳:沿显式 links 扩展一跳(人物/事件/时间线索),最多 2 条;实体题放宽到 3 条。
2319
+ // 只沿已经存在的链接走,不按文本相似度猜关系。
2320
+ const expansionLimit = recallIntent === 'entity' ? 3 : 2
2321
+ const knownIds = new Set(scored.files.map((file) => file.name))
2322
+ const expanded = []
2323
+ for (const file of scored.files.slice()) {
2324
+ for (const link of file.related || []) {
2325
+ if (!link?.id || link.missing || knownIds.has(link.id)) continue
2326
+ const fileLibraryId = file.libraryId || binding.libraryId
2327
+ const fileIndex = indexByLibrary.get(fileLibraryId) || index
2328
+ const target = fileIndex.entries[link.id]
2329
+ if (!target) continue
2330
+ if (!isMemoryEligible(target, { automatic: purpose === 'automatic' })) continue
2331
+ if (!visibleToSession(target, memorySessionId(exec))) continue
2332
+ knownIds.add(link.id)
2333
+ scored.files.push({
2334
+ name: link.id,
2335
+ description: target.title || '',
2336
+ content: String(target.content || ''),
2337
+ entry: target,
2338
+ strength: decayStrength(target),
2339
+ createdAtIdentity: target.createdAt || null,
2340
+ relatedTo: file.name,
2341
+ relationKind: link.kind || 'related',
2342
+ })
2343
+ expanded.push({ from: file.name, to: link.id, kind: link.kind || 'related' })
2344
+ if (expanded.length >= expansionLimit) break
2345
+ }
2346
+ if (expanded.length >= expansionLimit) break
2347
+ }
2348
+ if (expanded.length) scored.expanded = expanded
1916
2349
  if (sources.length > 1) scored.libraries = sources.map((source) => source.libraryId)
1917
2350
  return scored
1918
2351
  }
@@ -2004,12 +2437,14 @@ export async function privateList({ exec, libraryId, preferIndex = false }) {
2004
2437
  // mood lens and the attachment list all change how an entry is scored, aggregated or
2005
2438
  // rendered, so a wrong value in any of them was a permanent mis-filing that could
2006
2439
  // only be undone by archiving the memory and writing it again.
2007
- 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 }) {
2440
+ 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 }) {
2008
2441
  // `source` is editable because it is a claim about provenance, and claims get
2009
2442
  // corrected: a memory the model first filed as `inferred` may turn out to be
2010
2443
  // something the user actually said. Enum-checked like the rest — a typo here
2011
2444
  // silently downgrades a quote into an inference.
2012
2445
  checkEnums({ disclosure, owner, visibility, source })
2446
+ checkSourceKind(sourceKind)
2447
+ if (sourceKind && source !== undefined && source !== sourceKind) throw new Error('source and source_kind disagree; send one provenance for this memory')
2013
2448
  const scope = resolveLibrary({ exec, libraryId })
2014
2449
  if (scope.binding) assertScopeEnabled(scope.binding)
2015
2450
  const index = loadPrivateIndex(scope.libraryId)
@@ -2017,6 +2452,7 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2017
2452
  const id_ = resolveEntryId(index, id)
2018
2453
  const entry = index.entries[id_]
2019
2454
  assertEntryAccess(entry, exec)
2455
+ const scene = sceneTimeOf({ binding: scope.binding, context: entry.context, observedAt })
2020
2456
  if (layer !== undefined && (!LAYERS.includes(layer) || layer === 'must_remember' && entry.layer !== layer)) throw new Error('invalid layer update; must_remember needs a pin_reason')
2021
2457
  if (status !== undefined && !['active', 'archived', 'fragment', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(status)) throw new Error('invalid memory status')
2022
2458
  if (status === 'active' && ['pending_review', 'superseded'].includes(entry.status)) throw new Error('held or superseded memories require review')
@@ -2143,9 +2579,67 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2143
2579
  }
2144
2580
  if (tags !== undefined) target.tags = Array.isArray(tags) ? tags.slice(0, 20) : target.tags
2145
2581
  if (status !== undefined) target.status = status
2146
- if (openLoop !== undefined) target.openLoop = !!openLoop
2582
+ if (openLoop !== undefined) {
2583
+ target.openLoop = !!openLoop
2584
+ const current = commitmentOf(target)
2585
+ if (current && openLoop && current.status !== 'open') {
2586
+ target.commitment = { ...current, status: 'open', closed_by: null }
2587
+ } else if (current && !openLoop && current.status === 'open') {
2588
+ // 旧布尔值关闭一条承诺时也要关闭 commitment.status,否则 S4 的权威字段
2589
+ // 会让这条“已关闭”的欠账继续出现在到期提醒里。
2590
+ target.commitment = { ...current, status: 'done' }
2591
+ } else if (!current && openLoop) {
2592
+ target.commitment = normalizeCommitment({
2593
+ status: 'open', action: target.title || target.content, due_at: target.absolute_date || null,
2594
+ })
2595
+ }
2596
+ }
2597
+ if (commitment !== undefined) {
2598
+ if (commitment === null) {
2599
+ delete target.commitment
2600
+ } else {
2601
+ const normalized = normalizeCommitment(commitment, {
2602
+ fallbackDueAt: target.absolute_date || null,
2603
+ })
2604
+ target.commitment = normalized
2605
+ target.openLoop = normalized.status === 'open'
2606
+ }
2607
+ }
2147
2608
  if (disclosure !== undefined) target.disclosure = disclosure
2148
2609
  if (source !== undefined) target.source = source
2610
+ if (sourceKind !== undefined) {
2611
+ target.source_kind = sourceKind
2612
+ if (source === undefined) target.source = sourceKind
2613
+ if (speakerId === undefined && target.speaker_id === undefined) target.speaker_id = defaultSpeakerFor(sourceKind)
2614
+ }
2615
+ if (speakerId !== undefined) {
2616
+ const speaker = speakerId === null ? null : String(speakerId).trim()
2617
+ if (speaker !== null && (!speaker || speaker.length > 128)) throw new Error('speaker_id must be a non-empty string up to 128 characters')
2618
+ if (speaker) target.speaker_id = speaker
2619
+ else delete target.speaker_id
2620
+ }
2621
+ if (quoteSpan !== undefined) {
2622
+ const span = normalizeQuoteSpan(quoteSpan)
2623
+ if (span) target.quote_span = span
2624
+ else delete target.quote_span
2625
+ }
2626
+ if (storylineId !== undefined) {
2627
+ const storyline = storylineId === null ? null : String(storylineId).trim()
2628
+ if (storyline !== null && (!storyline || storyline.length > 128)) throw new Error('storyline_id must be a non-empty string up to 128 characters')
2629
+ if (storyline) target.storyline_id = storyline
2630
+ else delete target.storyline_id
2631
+ }
2632
+ if (branchId !== undefined) {
2633
+ const branch = branchId === null ? null : String(branchId).trim()
2634
+ if (branch !== null && (!branch || branch.length > 128)) throw new Error('branch_id must be a non-empty string up to 128 characters')
2635
+ if (branch) target.branch_id = branch
2636
+ else delete target.branch_id
2637
+ }
2638
+ if (knownBy !== undefined) {
2639
+ const known = normalizeKnownBy(knownBy)
2640
+ if (known && known.length) target.known_by = known
2641
+ else delete target.known_by
2642
+ }
2149
2643
  if (salientDate !== undefined) {
2150
2644
  // undefined leaves it alone, null or '' clears it, a value re-dates it. Re-
2151
2645
  // dating has to be possible: before this, a memory filed as an anniversary
@@ -2158,8 +2652,37 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2158
2652
  // Re-dating goes through the same settlement as a fresh write. A repair that
2159
2653
  // re-submits "10-29" for a body that says 明天 would otherwise re-create the
2160
2654
  // annual entry it was meant to fix.
2161
- target.salientDate = reconcileSalientDate(normalized, `${target.title || ''} ${target.content || ''}`)
2655
+ target.salientDate = reconcileSalientDate(normalized, `${target.title || ''} ${target.content || ''}`, scene)
2656
+ }
2657
+ }
2658
+ // S1:改写正文等于产生一次新的说法;重算日期字段,旧日期没有依据就删掉。
2659
+ if (textChanged || absoluteDate !== undefined) {
2660
+ const temporal = temporalFieldsOf({
2661
+ title: nextTitle,
2662
+ content: nextContent === undefined ? entry.content : nextContent,
2663
+ scene,
2664
+ salientDate: target.salientDate,
2665
+ absoluteDate,
2666
+ })
2667
+ for (const key of ['absolute_date', 'date_precision', 'date_source']) {
2668
+ if (temporal[key] === undefined) delete target[key]
2669
+ else target[key] = temporal[key]
2162
2670
  }
2671
+ target.event_time = temporal.event_time
2672
+ target.observed_at = temporal.observed_at
2673
+ }
2674
+ if (validFrom !== undefined) {
2675
+ const from = dateOnlyField(validFrom, 'valid_from')
2676
+ if (from) target.valid_from = from
2677
+ else delete target.valid_from
2678
+ }
2679
+ if (validTo !== undefined) {
2680
+ const to = dateOnlyField(validTo, 'valid_to')
2681
+ if (to) target.valid_to = to
2682
+ else delete target.valid_to
2683
+ }
2684
+ if (target.valid_from && target.valid_to && target.valid_from > target.valid_to) {
2685
+ throw new Error('valid_from must not be after valid_to')
2163
2686
  }
2164
2687
  if (context !== undefined) {
2165
2688
  const nextContext = normalizeMemoryContext(context)
@@ -2740,14 +3263,17 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2740
3263
  if (peeked) assertScopeEnabled(peeked, { layer: 'global' })
2741
3264
  const settings = getSettings()
2742
3265
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
3266
+ const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
3267
+ const queryDates = resolveQueryDates(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
3268
+ const searchQuery = queryDates.length ? `${query} ${queryDates.join(' ')}` : query
2743
3269
  let index = loadGlobalIndex()
2744
3270
  const intent = managedVectorIntent()
2745
3271
  const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
2746
3272
  .filter(([, entry]) => appliesToDomain(entry, binding))) }
2747
3273
  const result = effectiveVectorRoute() !== 'lexical'
2748
- ? await managedRecall({ exec, index: domainIndex, query, topK: topK || settings.globalTopK || 3,
2749
- libraryId: null, automatic: true, intent, retrieveImpl })
2750
- : localRecall(index, query, (file) => appliesToDomain(file.entry, binding))
3274
+ ? await managedRecall({ exec, index: domainIndex, query: searchQuery, topK: topK || settings.globalTopK || 3,
3275
+ libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
3276
+ : localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding))
2751
3277
  if (peeked) {
2752
3278
  const current = peekBinding(exec)
2753
3279
  if (!current) throw new Error('memory binding changed during recall; retry')
@@ -2770,7 +3296,8 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2770
3296
  retrieval: Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1),
2771
3297
  score: (Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1))
2772
3298
  * (0.85 + 0.15 * Number(f.entry.confidence ?? 0.5))
2773
- * habituationFactor(f.entry),
3299
+ * habituationFactor(f.entry)
3300
+ * (queryDates.length && f.entry.absolute_date && queryDates.includes(f.entry.absolute_date) ? 1.35 : 1),
2774
3301
  }))
2775
3302
  .sort((a, b) => b.score - a.score)
2776
3303
  const ranked = mmrSelect(cutWeakScores(filtered, threshold, RETRIEVAL_FLOOR), Number(topK || settings.globalTopK || 3))
@@ -2961,10 +3488,11 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
2961
3488
  return rows
2962
3489
  .filter(([id, entry]) => {
2963
3490
  if (!entry || excludeIds.has(id)) return false
2964
- if (!entry.openLoop || entry.marginalized) return false
2965
- // 'MM-DD' is an anniversary: it recurs on its own and is not a slipped promise.
2966
- if (!isDatedSalientDate(entry.salientDate)) return false
2967
- const ahead = salientDaysAhead(entry.salientDate, today)
3491
+ if (!isOpenThread(entry) || entry.marginalized) return false
3492
+ // commitment.due_at 是 S4 的权威到期日;旧数据回落到 salientDate。
3493
+ const dueDate = commitmentDueDate(entry) || (isDatedSalientDate(entry.salientDate) ? entry.salientDate : null)
3494
+ if (!dueDate) return false
3495
+ const ahead = salientDaysAhead(dueDate, today)
2968
3496
  if (ahead === null || ahead >= 0) return false
2969
3497
  // One gate for archived / suppressed / expired / pending_review / superseded and
2970
3498
  // for secret bodies: same rule as every other automatic injection surface.
@@ -2978,7 +3506,7 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
2978
3506
  })
2979
3507
  // Oldest date first: the promise that has been overdue longest is the one that
2980
3508
  // matters most. Ties fall back to age, then id, so the pick is deterministic.
2981
- .sort((a, b) => String(a[1].salientDate).localeCompare(String(b[1].salientDate))
3509
+ .sort((a, b) => String(commitmentDueDate(a[1]) || a[1].salientDate).localeCompare(String(commitmentDueDate(b[1]) || b[1].salientDate))
2982
3510
  || String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || ''))
2983
3511
  || a[0].localeCompare(b[0]))
2984
3512
  .map(([id, entry]) => ({ id, entry, recurring: true }))
@@ -3020,7 +3548,8 @@ export function dueOpenLoops({
3020
3548
  const regular = rows
3021
3549
  .filter(([id, entry]) => {
3022
3550
  if (!entry || skip.has(id) || excluded.has(id)) return false
3023
- if (!entry.openLoop || entry.marginalized) return false
3551
+ // S4:有 commitment 时 status 是权威;legacy openLoop 只在没有承诺对象时生效。
3552
+ if (!isOpenThread(entry) || entry.marginalized) return false
3024
3553
  if (!isActive(entry)) return false
3025
3554
  if (!visible(entry)) return false
3026
3555
  const age = daysSince(entry.updatedAt || entry.createdAt, now)
@@ -3036,6 +3565,33 @@ export function dueOpenLoops({
3036
3565
  return [...overdue, ...regular].slice(0, Math.max(0, Number(limit) || 0))
3037
3566
  }
3038
3567
 
3568
+ /**
3569
+ * S4.3:到期/临期(逾期、今天、明天)的未完成承诺,按 due_at 升序,最多 limit 条。
3570
+ * 只有显式 commitment 对象才走这里;legacy openLoop 仍由 dueOpenLoops 负责,
3571
+ * 两条通道不会把同一条欠账说两遍(调用方用 skipIds 去重)。
3572
+ */
3573
+ export function dueCommitments({ libraryId, now = Date.now(), sessionId = null, limit = 3, skipIds = [] } = {}) {
3574
+ if (!libraryId) return []
3575
+ const index = loadPrivateIndex(libraryId)
3576
+ const skip = new Set(skipIds || [])
3577
+ const reminders = []
3578
+ for (const [id, entry] of Object.entries(index.entries || {})) {
3579
+ if (!entry || skip.has(id) || entry.marginalized) continue
3580
+ if (!entry.commitment || typeof entry.commitment !== 'object') continue
3581
+ const commitment = commitmentOf(entry)
3582
+ if (!commitment || commitment.status !== 'open') continue
3583
+ if (!isMemoryEligible(entry, { automatic: true, now })) continue
3584
+ if (sessionId && !visibleToSession(entry, sessionId)) continue
3585
+ const due = commitmentDueState(commitment, { now })
3586
+ if (!due.dueAt || !due.dueSoon) continue
3587
+ reminders.push({ id, entry, commitment, ...due })
3588
+ }
3589
+ reminders.sort((a, b) => String(a.dueAt).localeCompare(String(b.dueAt))
3590
+ || String(a.entry.updatedAt || a.entry.createdAt || '').localeCompare(String(b.entry.updatedAt || b.entry.createdAt || ''))
3591
+ || a.id.localeCompare(b.id))
3592
+ return reminders.slice(0, Math.max(0, Number(limit) || 0))
3593
+ }
3594
+
3039
3595
  /**
3040
3596
  * Memories a sensory cue may be derived from.
3041
3597
  *
@@ -3061,7 +3617,8 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
3061
3617
  if (!isActive(entry)) return false
3062
3618
  if (!visibleToSession(entry, sessionId)) return false
3063
3619
  if (entry.sideEventId || entry.pinSource === 'side_event') return false
3064
- if (entry.disclosure === 'never_say') return false
3620
+ // S6:cue 是自动浮现;only_if_asked / never_say 都要等用户先问。
3621
+ if (entry.disclosure === 'never_say' || entry.disclosure === 'only_if_asked') return false
3065
3622
  if (entry.visibility === 'secret') return false
3066
3623
  if (!String(entry.content || '').trim()) return false
3067
3624
  const at = Date.parse(entry.updatedAt || entry.createdAt || '')