dsh-memu-memory 1.2.7 → 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 (49) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/memory-semantics.md +23 -3
  5. package/lib/backup.js +1 -1
  6. package/lib/budget.js +31 -0
  7. package/lib/commitment.js +138 -0
  8. package/lib/consolidation-receipt.js +2 -0
  9. package/lib/consolidation-worker.js +3 -0
  10. package/lib/freshness.js +24 -0
  11. package/lib/inject.js +117 -10
  12. package/lib/lexicon.js +1 -1
  13. package/lib/local-vector-service.js +4 -1
  14. package/lib/memory.js +565 -32
  15. package/lib/memu.js +4 -0
  16. package/lib/private.js +5 -3
  17. package/lib/prompts/private-consolidation.mixed.md +2 -2
  18. package/lib/prompts/private-consolidation.rp.md +6 -1
  19. package/lib/prompts/private-policy.rp.md +4 -0
  20. package/lib/prompts/system-guide.rp.md +3 -0
  21. package/lib/recall-cache.js +10 -2
  22. package/lib/rpc.js +9 -2
  23. package/lib/snippet.js +25 -0
  24. package/lib/temporal.js +329 -0
  25. package/lib/text-retrieval.js +71 -0
  26. package/lib/tools.js +81 -4
  27. package/package.json +1 -1
  28. package/scripts/bench-recall.mjs +2 -2
  29. package/scripts/check-seed-compat.mjs +1 -1
  30. package/tests/backup.test.mjs +2 -2
  31. package/tests/commitment.test.mjs +144 -0
  32. package/tests/consolidation-fork.test.mjs +3 -3
  33. package/tests/disclosure.test.mjs +34 -17
  34. package/tests/fact-version.test.mjs +128 -0
  35. package/tests/help-page.test.mjs +1 -1
  36. package/tests/inject-conflict.test.mjs +94 -0
  37. package/tests/inject-guide.test.mjs +5 -3
  38. package/tests/inject.test.mjs +2 -2
  39. package/tests/injection-intent-budget.test.mjs +92 -0
  40. package/tests/lexicon-frequency.test.mjs +1 -1
  41. package/tests/memory-chain.test.mjs +140 -0
  42. package/tests/memory-fields.test.mjs +134 -0
  43. package/tests/memu-resident.test.mjs +33 -0
  44. package/tests/prompt-semantics.test.mjs +51 -0
  45. package/tests/query-decompose.test.mjs +62 -0
  46. package/tests/recall-cache.test.mjs +4 -2
  47. package/tests/recall-intent.test.mjs +100 -0
  48. package/tests/speaker-provenance.test.mjs +120 -0
  49. package/tests/temporal.test.mjs +124 -0
package/lib/memory.js CHANGED
@@ -23,6 +23,11 @@ import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGe
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
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'
26
31
 
27
32
  // P1-1 召回缓存。缓存自身出错时 fail-open,
28
33
  // 但真实故障必须留痕(AGENTS.md §1 规则 10):把缓存内部的吞没错误接到 warn 上。
@@ -73,7 +78,10 @@ const VISIBILITIES = STORED_VISIBILITIES
73
78
  // quotable, everything else means they are our own reconstruction and must be hedged
74
79
  // when repeated. Defaulting to 'user_said' labelled every model-inferred memory as a
75
80
  // quote, which systematically inflated confidence in things nobody had said.
76
- 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']
77
85
 
78
86
  function managedVectorIntent() {
79
87
  if (effectiveVectorRoute() !== 'managed-local') return { managed: false, route: effectiveVectorRoute(), state: null, error: null }
@@ -249,6 +257,125 @@ function checkEnums({ disclosure, owner, visibility, source }) {
249
257
  throw new Error(`source must be ${SOURCES.join(', ')}`)
250
258
  }
251
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
+
252
379
  // Below this, the present-mood read is noise and must not bend retrieval at all.
253
380
  const MOOD_MIN_STRENGTH = 0.15
254
381
  // Long enough that the reason has to say what happened and why it can be let go,
@@ -461,6 +588,79 @@ export function reconcileSalientDate(value, text, now = new Date()) {
461
588
  return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}-${pad2(target.getDate())}`
462
589
  }
463
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
+
464
664
  // How many days ahead today is from a dated memory (0 = due today, negative =
465
665
  // already past). An anniversary has no distance: it is true every year.
466
666
  export function salientDaysAhead(salientDate, now = new Date()) {
@@ -714,7 +914,20 @@ export function isMemoryEligible(entry, { automatic = false, now = Date.now() }
714
914
  // deadline itself has to be authoritative. An expired draft must never reach a
715
915
  // prompt just because the cleaner has not run yet.
716
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
717
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
718
931
  return true
719
932
  }
720
933
 
@@ -742,8 +955,8 @@ function queryTokens(query) {
742
955
  return [...tokens].filter(Boolean)
743
956
  }
744
957
 
745
- function lexicalScore(entry, tokens) {
746
- if (!tokens.length) return 0
958
+ function lexicalScore(entry, tokens, queryDates = []) {
959
+ if (!tokens.length && !queryDates.length) return 0
747
960
  const title = String(entry?.title || '').toLowerCase()
748
961
  const content = [entry?.content || '', ...(entry?.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`)].join(' ').toLowerCase()
749
962
  const tags = (Array.isArray(entry?.tags) ? entry.tags : []).join(' ').toLowerCase()
@@ -753,9 +966,11 @@ function lexicalScore(entry, tokens) {
753
966
  if (tags.includes(token)) score += 2
754
967
  if (content.includes(token)) score += 1
755
968
  }
969
+ // S1:日期是结构化字段,不在正文里也要能被检索到(“那天发生了什么”)。
970
+ if (entry?.absolute_date && queryDates.includes(entry.absolute_date)) score += 4
756
971
  // Longer queries should not win just by having more tokens in common; the
757
972
  // average keeps scores comparable across one-word and sentence queries.
758
- return score / tokens.length
973
+ return tokens.length ? score / tokens.length : score
759
974
  }
760
975
 
761
976
  function localIndexFiles(index) {
@@ -776,11 +991,12 @@ function localRecall(index, query, filter = () => true) {
776
991
  return { files: files.filter(file => file.name === id).map(file => ({ ...file, lexical: 5 })), segments: [], resources: [], raw: null, parseWarning: null }
777
992
  }
778
993
  const tokens = queryTokens(query)
994
+ const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
779
995
  const ordered = tokens.length === 0
780
996
  ? files.sort((a, b) => String(b.entry?.updatedAt || b.entry?.createdAt || '')
781
997
  .localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
782
998
  : files
783
- .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens) }))
999
+ .map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates) }))
784
1000
  .filter((file) => file.lexical > 0)
785
1001
  .sort((a, b) => b.lexical - a.lexical
786
1002
  || String(b.entry?.updatedAt || b.entry?.createdAt || '')
@@ -1014,8 +1230,11 @@ function recallScore(file, rank, context) {
1014
1230
  // ride the same touch/decay loop as the original and could outlive it in rank —
1015
1231
  // the "duplicates age better than the truth" loop this closes.
1016
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
1017
1236
 
1018
- 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
1019
1238
  }
1020
1239
 
1021
1240
  /**
@@ -1098,6 +1317,10 @@ function privateWeighted(result, max, context = {}) {
1098
1317
  lastCreatedAt: null,
1099
1318
  sessionId: null,
1100
1319
  now: Date.now(),
1320
+ queryDates: [],
1321
+ speakerFilter: null,
1322
+ intent: 'general',
1323
+ disclosureAsked: false,
1101
1324
  retrievalFloor: RETRIEVAL_FLOOR,
1102
1325
  ...context,
1103
1326
  }
@@ -1109,6 +1332,11 @@ function privateWeighted(result, max, context = {}) {
1109
1332
  // memories. Filtering here keeps the anchor and the recall block in agreement.
1110
1333
  .filter((f) => visibleToSession(f.entry, ctx.sessionId))
1111
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))
1112
1340
  .map((f, i) => ({ ...f, score: recallScore(f, i, ctx), retrieval: retrievalShare(f, i) }))
1113
1341
  .sort((a, b) => b.score - a.score)
1114
1342
  const { chosen, skipped } = mmrSelect(cutWeakScores(items, ctx.relevanceThreshold, ctx.retrievalFloor), max)
@@ -1274,6 +1502,20 @@ async function privateRememberImpl({
1274
1502
  emotion = undefined, dominance = undefined, emotionSource = null,
1275
1503
  attachments, track = 'memory',
1276
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,
1277
1519
  // Escape hatch for the duplicate gate : two genuine
1278
1520
  // observations of the same fact on the same day are a legal write. Off by
1279
1521
  // default — the model must say it looked, not default past the gate.
@@ -1281,6 +1523,7 @@ async function privateRememberImpl({
1281
1523
  }) {
1282
1524
  const scope = resolveLibrary({ exec, libraryId })
1283
1525
  const binding = scope.binding
1526
+ const scene = sceneTimeOf({ binding, context, observedAt })
1284
1527
  const memoryContext = normalizeMemoryContext({ ...binding?.memoryContext, ...context })
1285
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')
1286
1529
  if (sessionIdOf(exec) && !contextVisible({ ...memoryContext, knownBy: [] }, binding?.memoryContext)) {
@@ -1304,7 +1547,7 @@ async function privateRememberImpl({
1304
1547
  // An unreadable date is refused instead of dropped. Dropping it looked like
1305
1548
  // success to the caller while losing the only part of the memory it asked for:
1306
1549
  // a date that never fires is indistinguishable from no date at all.
1307
- let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`)
1550
+ let normalizedSalientDate = reconcileSalientDate(normalizeSalientDate(salientDate), `${title || ''} ${content || ''}`, scene)
1308
1551
  // 模型常把日期写进正文却漏填 salient_date(详情页日期栏因此为空)。只有显式传了
1309
1552
  // 非法值才报错;什么都没传时,从文本取唯一的 YYYY-MM-DD 作为兜底。
1310
1553
  const explicitDate = salientDate !== null && salientDate !== undefined && String(salientDate).trim()
@@ -1318,6 +1561,48 @@ async function privateRememberImpl({
1318
1561
  if (title !== undefined) title = redactSecrets(title)
1319
1562
  if (!LAYERS.includes(layer)) throw new Error(`unknown layer: ${layer}; use ${LAYERS.join(', ')}`)
1320
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)
1321
1606
  // A short-term entry is a draft with a deadline. With the layer switched off the
1322
1607
  // write is refused rather than quietly upgraded to permanent memory, because the
1323
1608
  // model asked for something disposable and would otherwise pollute the durable
@@ -1355,6 +1640,37 @@ async function privateRememberImpl({
1355
1640
  && (item.attachments || []).some(attachment => media.some(candidate => candidate.sha256 === attachment.sha256)))
1356
1641
  : null
1357
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))
1358
1674
  // A malformed share is refused here rather than clamped later: a negative or
1359
1675
  // non-finite composition is a caller bug, and repairing it silently would keep the
1360
1676
  // bug alive while the entry looks fine.
@@ -1384,7 +1700,8 @@ async function privateRememberImpl({
1384
1700
  accessCount: previousHabit?.[1]?.accessCount || 0,
1385
1701
  strength: layer === 'must_remember' ? 1 : 0.8,
1386
1702
  marginalized: false,
1387
- openLoop: !!openLoop,
1703
+ openLoop: derivedCommitment ? derivedCommitment.status === 'open' : !!openLoop,
1704
+ ...(derivedCommitment ? { commitment: derivedCommitment } : {}),
1388
1705
  disclosure,
1389
1706
  owner,
1390
1707
  visibility,
@@ -1414,6 +1731,11 @@ async function privateRememberImpl({
1414
1731
  : Math.max(0, Math.min(1, Number(arousal) || 0)),
1415
1732
  peak: peak === true,
1416
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 } : {}),
1417
1739
  }
1418
1740
  // Flashbulb memory: store vividness and accuracy separately. `confidence` is
1419
1741
  // what the model claims; `accuracy` is what a charged moment is actually worth.
@@ -1424,8 +1746,10 @@ async function privateRememberImpl({
1424
1746
  // true. Same mechanism the global curator uses; until now the private side had none.
1425
1747
  // Hidden rows are excluded (5.1): otherwise a visible write could learn an id
1426
1748
  // 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)
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)
1429
1753
  if (conflict) {
1430
1754
  entry.status = 'pending_review'
1431
1755
  entry.conflictingWith = conflict.id
@@ -1442,7 +1766,7 @@ async function privateRememberImpl({
1442
1766
  // it duplicateOf so recall can keep one seat per fact.
1443
1767
  let duplicate = null
1444
1768
  let hiddenDuplicate = null
1445
- if (!conflict && allowDuplicate !== true) {
1769
+ if (!conflict && !relationId && allowDuplicate !== true) {
1446
1770
  const text = `${entry.title || ''} ${content || ''}`
1447
1771
  for (const [otherId, other] of Object.entries(index.entries)) {
1448
1772
  if (otherId === id || !isMemoryEligible(other)) continue
@@ -1527,7 +1851,9 @@ async function privateRememberImpl({
1527
1851
  if (sessionIdOf(exec) && (!currentBinding || currentBinding.libraryId !== scope.libraryId)) throw new Error('memory scope changed during write; retry')
1528
1852
  if (currentBinding) assertScopeEnabled(currentBinding)
1529
1853
  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)
1854
+ const latestConflict = relationId
1855
+ ? null
1856
+ : findConflict(Object.fromEntries(Object.entries(fresh.entries).filter(([key, other]) => key !== id && visibleForDedupe(other, memorySession))), entry)
1531
1857
  if (latestConflict && !conflict) {
1532
1858
  if (db) throw new Error('memory conflict changed during write; retry for review')
1533
1859
  entry.status = 'pending_review'
@@ -1537,7 +1863,7 @@ async function privateRememberImpl({
1537
1863
  // 5.4:预检在 await 之前,提交期间另一个 turn 可能刚写入同事实。临界区用同一
1538
1864
  // 尺子重扫;命中就 retry(有向量则 throw 让 compensation 撤掉刚提交的行),
1539
1865
  // lexical 路由直接暂扣为 near_duplicate,不双写也不丢文本。
1540
- const latestDuplicate = allowDuplicate
1866
+ const latestDuplicate = allowDuplicate || relationId
1541
1867
  ? { duplicate: null, hidden: false }
1542
1868
  : findNearDuplicate(fresh.entries, {
1543
1869
  id, title: entry.title, content: entry.content, context: entry.context, sessionId: memorySession,
@@ -1553,6 +1879,23 @@ async function privateRememberImpl({
1553
1879
  if (pinned >= Number(getSettings().mustRememberCap || 12)) throw new Error('must_remember soft cap reached; retry as long_term')
1554
1880
  }
1555
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
+ }
1556
1899
  }))
1557
1900
  } catch (error) {
1558
1901
  if (db) await compensatePrivateCommit(error, { libraryId: scope.libraryId, id, route, db, expectedEntry: previousHabit?.[1] || null })
@@ -1562,7 +1905,7 @@ async function privateRememberImpl({
1562
1905
  if (layer === 'must_remember' && pinSource === 'side_event') {
1563
1906
  consumeCue(sessionIdOf(exec), sideEventId)
1564
1907
  }
1565
- 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 }
1566
1909
  }
1567
1910
 
1568
1911
  // Bulk restore of an exported library. This is a *restore*, not a decision, so it
@@ -1841,8 +2184,15 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1841
2184
  const settings = getSettings()
1842
2185
  const threshold = relevanceThreshold === undefined ? settings.relevanceThreshold : relevanceThreshold
1843
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
1844
2194
  const route = effectiveVectorRoute(settings)
1845
- const wanted = Number(topK || settings.privateTopK || 4)
2195
+ const wanted = intentTopK(recallIntent, Number(topK || settings.privateTopK || 4))
1846
2196
  const domain = domainOf(binding)
1847
2197
  const sources = (settings.crossLibraryRecall === true
1848
2198
  ? crossLibrarySources(binding, domain)
@@ -1852,9 +2202,9 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1852
2202
  // exists when another qualifying library is actually present.
1853
2203
  const result = sources.length === 1
1854
2204
  ? (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 })
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 })
1858
2208
  const current = peekBinding(exec)
1859
2209
  if (!current || current.libraryId !== binding.libraryId) throw new Error('memory scope changed during recall; retry')
1860
2210
  assertScopeEnabled(current)
@@ -1882,7 +2232,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1882
2232
  (source.libraryId === binding.libraryId ? index : source.index).entries || {},
1883
2233
  ).map((entry) => ({ entry }))))
1884
2234
  const mood = moodDecay(binding.mood)
1885
- const scored = privateWeighted(enriched, Number(topK || settings.privateTopK || 4), {
2235
+ const scored = privateWeighted(enriched, wanted, {
1886
2236
  // Three independent legs: a clear composition, an arousal away from rest, or a
1887
2237
  // clear sense of control. A null composition only closes the first one — a tense
1888
2238
  // room with no clear good/bad reading still changes which memories come up.
@@ -1894,11 +2244,39 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1894
2244
  firstCreatedAt: span.first,
1895
2245
  lastCreatedAt: span.last,
1896
2246
  relevanceThreshold: threshold,
2247
+ queryDates,
2248
+ intent: recallIntent,
2249
+ disclosureAsked: recallIntent === 'boundary',
2250
+ speakerFilter: detectSpeakerQuery(query),
1897
2251
  // The asking conversation's context is what memories are filtered against; the id is
1898
2252
  // only how that context is looked up.
1899
2253
  sessionId: memorySessionId(exec),
1900
2254
  automatic: purpose === 'automatic',
1901
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
1902
2280
  // Being recalled is being used, and a memory that keeps being used should not fade
1903
2281
  // like one nobody ever touches. Group by the library each hit came from so a
1904
2282
  // cross-library recall touches the owning index, not the bound one.
@@ -1937,6 +2315,37 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
1937
2315
  }
1938
2316
  try { file.related = recallRelations(fileLibraryId, fileIndex, file.name, memorySessionId(exec)) } catch { file.related = [] }
1939
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
1940
2349
  if (sources.length > 1) scored.libraries = sources.map((source) => source.libraryId)
1941
2350
  return scored
1942
2351
  }
@@ -2028,12 +2437,14 @@ export async function privateList({ exec, libraryId, preferIndex = false }) {
2028
2437
  // mood lens and the attachment list all change how an entry is scored, aggregated or
2029
2438
  // rendered, so a wrong value in any of them was a permanent mis-filing that could
2030
2439
  // 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 }) {
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 }) {
2032
2441
  // `source` is editable because it is a claim about provenance, and claims get
2033
2442
  // corrected: a memory the model first filed as `inferred` may turn out to be
2034
2443
  // something the user actually said. Enum-checked like the rest — a typo here
2035
2444
  // silently downgrades a quote into an inference.
2036
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')
2037
2448
  const scope = resolveLibrary({ exec, libraryId })
2038
2449
  if (scope.binding) assertScopeEnabled(scope.binding)
2039
2450
  const index = loadPrivateIndex(scope.libraryId)
@@ -2041,6 +2452,7 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2041
2452
  const id_ = resolveEntryId(index, id)
2042
2453
  const entry = index.entries[id_]
2043
2454
  assertEntryAccess(entry, exec)
2455
+ const scene = sceneTimeOf({ binding: scope.binding, context: entry.context, observedAt })
2044
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')
2045
2457
  if (status !== undefined && !['active', 'archived', 'fragment', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(status)) throw new Error('invalid memory status')
2046
2458
  if (status === 'active' && ['pending_review', 'superseded'].includes(entry.status)) throw new Error('held or superseded memories require review')
@@ -2167,9 +2579,67 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2167
2579
  }
2168
2580
  if (tags !== undefined) target.tags = Array.isArray(tags) ? tags.slice(0, 20) : target.tags
2169
2581
  if (status !== undefined) target.status = status
2170
- 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
+ }
2171
2608
  if (disclosure !== undefined) target.disclosure = disclosure
2172
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
+ }
2173
2643
  if (salientDate !== undefined) {
2174
2644
  // undefined leaves it alone, null or '' clears it, a value re-dates it. Re-
2175
2645
  // dating has to be possible: before this, a memory filed as an anniversary
@@ -2182,8 +2652,37 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
2182
2652
  // Re-dating goes through the same settlement as a fresh write. A repair that
2183
2653
  // re-submits "10-29" for a body that says 明天 would otherwise re-create the
2184
2654
  // annual entry it was meant to fix.
2185
- 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]
2186
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')
2187
2686
  }
2188
2687
  if (context !== undefined) {
2189
2688
  const nextContext = normalizeMemoryContext(context)
@@ -2764,14 +3263,17 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2764
3263
  if (peeked) assertScopeEnabled(peeked, { layer: 'global' })
2765
3264
  const settings = getSettings()
2766
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
2767
3269
  let index = loadGlobalIndex()
2768
3270
  const intent = managedVectorIntent()
2769
3271
  const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
2770
3272
  .filter(([, entry]) => appliesToDomain(entry, binding))) }
2771
3273
  const result = effectiveVectorRoute() !== 'lexical'
2772
- ? await managedRecall({ exec, index: domainIndex, query, topK: topK || settings.globalTopK || 3,
3274
+ ? await managedRecall({ exec, index: domainIndex, query: searchQuery, topK: topK || settings.globalTopK || 3,
2773
3275
  libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
2774
- : localRecall(index, query, (file) => appliesToDomain(file.entry, binding))
3276
+ : localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding))
2775
3277
  if (peeked) {
2776
3278
  const current = peekBinding(exec)
2777
3279
  if (!current) throw new Error('memory binding changed during recall; retry')
@@ -2794,7 +3296,8 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
2794
3296
  retrieval: Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1),
2795
3297
  score: (Number.isFinite(f.retrievalScore) ? f.retrievalScore : f.lexical > 0 ? f.lexical : 1 / (i + 1))
2796
3298
  * (0.85 + 0.15 * Number(f.entry.confidence ?? 0.5))
2797
- * habituationFactor(f.entry),
3299
+ * habituationFactor(f.entry)
3300
+ * (queryDates.length && f.entry.absolute_date && queryDates.includes(f.entry.absolute_date) ? 1.35 : 1),
2798
3301
  }))
2799
3302
  .sort((a, b) => b.score - a.score)
2800
3303
  const ranked = mmrSelect(cutWeakScores(filtered, threshold, RETRIEVAL_FLOOR), Number(topK || settings.globalTopK || 3))
@@ -2985,10 +3488,11 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
2985
3488
  return rows
2986
3489
  .filter(([id, entry]) => {
2987
3490
  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)
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)
2992
3496
  if (ahead === null || ahead >= 0) return false
2993
3497
  // One gate for archived / suppressed / expired / pending_review / superseded and
2994
3498
  // for secret bodies: same rule as every other automatic injection surface.
@@ -3002,7 +3506,7 @@ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, exc
3002
3506
  })
3003
3507
  // Oldest date first: the promise that has been overdue longest is the one that
3004
3508
  // 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))
3509
+ .sort((a, b) => String(commitmentDueDate(a[1]) || a[1].salientDate).localeCompare(String(commitmentDueDate(b[1]) || b[1].salientDate))
3006
3510
  || String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || ''))
3007
3511
  || a[0].localeCompare(b[0]))
3008
3512
  .map(([id, entry]) => ({ id, entry, recurring: true }))
@@ -3044,7 +3548,8 @@ export function dueOpenLoops({
3044
3548
  const regular = rows
3045
3549
  .filter(([id, entry]) => {
3046
3550
  if (!entry || skip.has(id) || excluded.has(id)) return false
3047
- if (!entry.openLoop || entry.marginalized) return false
3551
+ // S4:有 commitment 时 status 是权威;legacy openLoop 只在没有承诺对象时生效。
3552
+ if (!isOpenThread(entry) || entry.marginalized) return false
3048
3553
  if (!isActive(entry)) return false
3049
3554
  if (!visible(entry)) return false
3050
3555
  const age = daysSince(entry.updatedAt || entry.createdAt, now)
@@ -3060,6 +3565,33 @@ export function dueOpenLoops({
3060
3565
  return [...overdue, ...regular].slice(0, Math.max(0, Number(limit) || 0))
3061
3566
  }
3062
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
+
3063
3595
  /**
3064
3596
  * Memories a sensory cue may be derived from.
3065
3597
  *
@@ -3085,7 +3617,8 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
3085
3617
  if (!isActive(entry)) return false
3086
3618
  if (!visibleToSession(entry, sessionId)) return false
3087
3619
  if (entry.sideEventId || entry.pinSource === 'side_event') return false
3088
- 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
3089
3622
  if (entry.visibility === 'secret') return false
3090
3623
  if (!String(entry.content || '').trim()) return false
3091
3624
  const at = Date.parse(entry.updatedAt || entry.createdAt || '')