dsh-memu-memory 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/graph.js CHANGED
@@ -2,6 +2,13 @@ import path from 'node:path'
2
2
  import { indexDir, readJsonStrict, writeJson, withFileLock, stamp, warn } from './paths.js'
3
3
  import { loadPrivateIndex, updatePrivateIndex, newMemoryId, listLibraries } from './state.js'
4
4
  import { resolveLibrary, sessionIdOf, visibleToSession, isMemoryEligible, decayStrength } from './memory.js'
5
+ import { record } from './activity-log.js'
6
+ // Entity merge suggestions reuse the exact folding rule auto-linking already
7
+ // uses (NFKC / case / whitespace / punctuation). This is a deliberate module
8
+ // cycle: private-links.js imports the entity writers from here, but both sides
9
+ // only touch each other's bindings in function bodies, and ESM hoists the
10
+ // function declarations before either module body runs.
11
+ import { normalizeEntityName } from './private-links.js'
5
12
 
6
13
  export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict']
7
14
  const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
@@ -155,10 +162,15 @@ export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
155
162
  * Remove every entity in one library that no entry links to and no relationship
156
163
  * snapshot references. Idempotent: on healthy data it writes nothing. Returns
157
164
  * `{ removed, total }` with the removed entity ids.
165
+ *
166
+ * `keep` names ids that must survive even while unreferenced — a merge passes
167
+ * its target, because folding sources into a row and then collecting that row
168
+ * would silently undo the merge when the pair had no edges yet.
158
169
  */
159
- export function pruneOrphanEntities(libraryId) {
170
+ export function pruneOrphanEntities(libraryId, keep = []) {
160
171
  const scope = scopeFor({ libraryId })
161
172
  const file = entitiesPath(scope.libraryId)
173
+ const protectedIds = new Set(Array.isArray(keep) ? keep : [])
162
174
  return withFileLock(file, () => {
163
175
  const store = readEntities(scope.libraryId)
164
176
  const ids = Object.keys(store.entities)
@@ -171,7 +183,7 @@ export function pruneOrphanEntities(libraryId) {
171
183
  referenced.add(relationship.fromId)
172
184
  referenced.add(relationship.toId)
173
185
  }
174
- const removed = ids.filter(id => !referenced.has(id))
186
+ const removed = ids.filter(id => !referenced.has(id) && !protectedIds.has(id))
175
187
  // Write only when something actually goes, so the common case never touches
176
188
  // the file (mtime-based caches, backups and concurrent readers all benefit).
177
189
  if (removed.length) {
@@ -254,6 +266,236 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
254
266
  })
255
267
  }
256
268
 
269
+ /**
270
+ * Merge one or more source entities into a target entity inside the same
271
+ * library. This is graph bookkeeping, not a memory write: no memory text or
272
+ * vector is touched, links only change the entity id they point at.
273
+ *
274
+ * Lock order follows deleteEntity exactly: the entity file lock is taken first
275
+ * and the private index lock is nested inside it (withFileLock is re-entrant,
276
+ * and no path takes the index lock before the entity lock, so this order cannot
277
+ * deadlock). The index remap is written *before* the source rows are deleted:
278
+ * a crash between the two writes leaves at worst collectable entities behind,
279
+ * never a surviving link that points at an entity that is already gone.
280
+ *
281
+ * Dedupe after remapping keeps the edge that already pointed at the target (or,
282
+ * with no such edge, the first remapped one), and carries an `auto` marker over
283
+ * from a dropped duplicate so the graph view keeps its badge. Relationship
284
+ * snapshots are re-keyed on the target; an existing target-side snapshot wins
285
+ * and the discarded source key is reported in `relationships.conflicts`.
286
+ */
287
+ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
288
+ const scope = scopeFor({ exec, libraryId })
289
+ if (typeof targetId !== 'string' || !targetId.trim()) throw new Error('targetId is required')
290
+ const target = targetId.trim()
291
+ if (!Array.isArray(sourceIds) || !sourceIds.length) throw new Error('sourceIds must be a non-empty array of entity ids')
292
+ const sources = []
293
+ const seen = new Set()
294
+ for (const raw of sourceIds) {
295
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('sourceIds must contain entity ids')
296
+ const id = raw.trim()
297
+ if (id === target) throw new Error('target entity cannot be one of its own sources')
298
+ if (seen.has(id)) continue
299
+ seen.add(id)
300
+ sources.push(id)
301
+ }
302
+ if (!sources.length) throw new Error('sourceIds must name at least one entity')
303
+ const file = entitiesPath(scope.libraryId)
304
+ let targetName = target
305
+ const result = withFileLock(file, () => {
306
+ const store = readEntities(scope.libraryId)
307
+ const targetEntity = store.entities[target]
308
+ if (!targetEntity || typeof targetEntity !== 'object') throw new Error(`unknown entity: ${target}`)
309
+ targetName = String(targetEntity.name || target)
310
+ const sourceEntities = []
311
+ for (const id of sources) {
312
+ const entity = store.entities[id]
313
+ if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
314
+ if (entity.kind !== targetEntity.kind) {
315
+ throw new Error(`cannot merge entities of different kinds: ${targetEntity.kind || 'unknown'} vs ${entity.kind || 'unknown'}`)
316
+ }
317
+ sourceEntities.push(entity)
318
+ }
319
+
320
+ // Union of names: the target's own name stays the display name, every
321
+ // source name becomes an alias, and the shared normalizer trims, dedupes
322
+ // and caps at 30. Anything beyond the cap is reported, not silently lost.
323
+ const rawAliases = [
324
+ ...(Array.isArray(targetEntity.aliases) ? targetEntity.aliases : []),
325
+ ...sourceEntities.flatMap(entity => [entity.name, ...(Array.isArray(entity.aliases) ? entity.aliases : [])]),
326
+ ].filter(alias => typeof alias === 'string')
327
+ const aliasUnion = [...new Set(rawAliases.map(alias => alias.trim()).filter(Boolean))]
328
+ const aliases = normalizeAliases(aliasUnion)
329
+ const droppedAliases = aliasUnion.slice(aliases.length)
330
+
331
+ const sourceSet = new Set(sources)
332
+ let remappedLinks = 0
333
+ let duplicateLinks = 0
334
+ updatePrivateIndex(scope.libraryId, index => {
335
+ for (const entry of Object.values(index.entries || {})) {
336
+ const links = Array.isArray(entry.links) ? entry.links : null
337
+ if (!links || !links.some(link => link && sourceSet.has(link.to))) continue
338
+ // Kinds already present on the target win the dedupe; every remapped
339
+ // edge of such a kind is a duplicate, and an `auto` marker survives on
340
+ // the retained edge even when the dropped copy was the auto one.
341
+ const targetKinds = new Set()
342
+ for (const link of links) if (link && link.to === target) targetKinds.add(link.kind)
343
+ const autoKinds = new Set()
344
+ const nextLinks = []
345
+ for (const link of links) {
346
+ if (!link || !sourceSet.has(link.to)) { nextLinks.push(link); continue }
347
+ remappedLinks += 1
348
+ if (targetKinds.has(link.kind)) {
349
+ duplicateLinks += 1
350
+ if (link.source === 'auto') autoKinds.add(link.kind)
351
+ continue
352
+ }
353
+ targetKinds.add(link.kind)
354
+ nextLinks.push({ ...link, to: target })
355
+ }
356
+ for (const kind of autoKinds) {
357
+ const at = nextLinks.findIndex(item => item && item.to === target && item.kind === kind)
358
+ if (at >= 0 && !nextLinks[at].source) nextLinks[at] = { ...nextLinks[at], source: 'auto' }
359
+ }
360
+ entry.links = nextLinks
361
+ }
362
+ })
363
+
364
+ // Re-key snapshots: replace source endpoints with the target, keep an
365
+ // existing target-side snapshot untouched (it is the history written under
366
+ // the real pair), and drop self-loops a merge would create. The whole
367
+ // snapshot object, history included, moves unchanged.
368
+ const relationships = { moved: 0, conflicts: [] }
369
+ for (const key of Object.keys(store.relationships || {})) {
370
+ const snapshot = store.relationships[key]
371
+ if (!snapshot || typeof snapshot !== 'object') continue
372
+ let endpoints
373
+ try { endpoints = JSON.parse(key) } catch { continue }
374
+ if (!Array.isArray(endpoints) || endpoints.length !== 2) continue
375
+ const [fromId, toId] = endpoints
376
+ if (!sourceSet.has(fromId) && !sourceSet.has(toId)) continue
377
+ const nextFrom = sourceSet.has(fromId) ? target : fromId
378
+ const nextTo = sourceSet.has(toId) ? target : toId
379
+ delete store.relationships[key]
380
+ if (nextFrom === nextTo) {
381
+ relationships.conflicts.push({ key, reason: 'self' })
382
+ continue
383
+ }
384
+ const nextKey = JSON.stringify([nextFrom, nextTo])
385
+ if (store.relationships[nextKey]) {
386
+ relationships.conflicts.push({ key, reason: 'existing-target', keptKey: nextKey })
387
+ continue
388
+ }
389
+ store.relationships[nextKey] = { ...snapshot, fromId: nextFrom, toId: nextTo }
390
+ relationships.moved += 1
391
+ }
392
+
393
+ targetEntity.aliases = aliases
394
+ targetEntity.updatedAt = stamp()
395
+ for (const id of sources) delete store.entities[id]
396
+ writeJson(file, store)
397
+ // Safety net: a source may have been kept alive only by a snapshot that the
398
+ // merge dropped. The same lock is re-entered, so this cannot race the write
399
+ // above; a prune failure must not turn a completed merge into an error. The
400
+ // target is protected — an unreferenced pair is still a legitimate merge and
401
+ // collecting the row it just merged into would undo it.
402
+ try { pruneOrphanEntities(scope.libraryId, [target]) } catch (error) {
403
+ warn(`orphan entity prune after entity merge skipped: ${error?.message || error}`)
404
+ }
405
+ return { targetId: target, merged: sources, aliases, droppedAliases, remappedLinks, duplicateLinks, relationships }
406
+ })
407
+
408
+ // The merge is already durable; the activity log is diagnostics and is
409
+ // fail-open by design, so it must never decide the result.
410
+ try {
411
+ record({
412
+ kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
413
+ message: `实体合并:「${targetName}」并入完成(${sources.length} 个来源)`,
414
+ detail: {
415
+ op: 'entity-merge', targetId: target, merged: sources,
416
+ remappedLinks: result.remappedLinks, duplicateLinks: result.duplicateLinks,
417
+ movedRelationships: result.relationships.moved,
418
+ relationshipConflicts: result.relationships.conflicts.length,
419
+ aliases: result.aliases.length, droppedAliases: result.droppedAliases.length,
420
+ },
421
+ refs: [target, ...sources],
422
+ })
423
+ } catch {}
424
+ return result
425
+ }
426
+
427
+ const SUGGEST_LIMIT = 20
428
+
429
+ function compareText(a, b) { return a < b ? -1 : a > b ? 1 : 0 }
430
+
431
+ // Bounded Levenshtein. Row minima never decrease, so once a row's best cell is
432
+ // already above the budget the remaining rows cannot recover; scanning stops.
433
+ function withinEditDistance(a, b, max) {
434
+ if (a === b) return true
435
+ if (Math.abs(a.length - b.length) > max) return false
436
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index)
437
+ for (let i = 1; i <= a.length; i += 1) {
438
+ const current = [i]
439
+ let best = i
440
+ for (let j = 1; j <= b.length; j += 1) {
441
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
442
+ const value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost)
443
+ current[j] = value
444
+ if (value < best) best = value
445
+ }
446
+ if (best > max) return false
447
+ previous = current
448
+ }
449
+ return previous[b.length] <= max
450
+ }
451
+
452
+ /**
453
+ * Pure read: candidate entity merges inside one library. Never writes and never
454
+ * merges — the caller shows the pair and the user confirms.
455
+ *
456
+ * Names are folded with normalizeEntityName (NFKC / case / whitespace /
457
+ * punctuation), identical folded names are skipped (that duplicate is handled by
458
+ * createEntity or an explicit merge), and only same-kind pairs qualify. A pair
459
+ * is a candidate when the shorter normalized name is contained in the longer one
460
+ * and has >= 2 characters, or when both names have >= 3 characters and sit at
461
+ * most 2 edits apart. The longer name is the target (the hub the shorter one
462
+ * folds into); on equal length the older id wins, which keeps the direction
463
+ * stable across calls. Results are sorted by reason then names then ids, and
464
+ * capped at 20.
465
+ */
466
+ export function suggestEntityMerges({ libraryId } = {}) {
467
+ const scope = scopeFor({ libraryId })
468
+ const store = readEntities(scope.libraryId)
469
+ const rows = Object.values(store.entities || {})
470
+ .filter(entity => entity && typeof entity === 'object' && entity.id)
471
+ .map(entity => ({ id: String(entity.id), kind: String(entity.kind || ''), key: normalizeEntityName(entity.name) }))
472
+ .filter(row => row.key)
473
+ const found = []
474
+ for (let i = 0; i < rows.length; i += 1) {
475
+ for (let j = i + 1; j < rows.length; j += 1) {
476
+ const a = rows[i]
477
+ const b = rows[j]
478
+ if (a.kind !== b.kind || a.key === b.key) continue
479
+ const aIsLonger = a.key.length > b.key.length || (a.key.length === b.key.length && a.id < b.id)
480
+ const longer = aIsLonger ? a : b
481
+ const shorter = aIsLonger ? b : a
482
+ let reason = null
483
+ if (shorter.key.length >= 2 && longer.key.includes(shorter.key)) reason = 'containment'
484
+ else if (shorter.key.length >= 3
485
+ && longer.key.length - shorter.key.length <= 2
486
+ && withinEditDistance(shorter.key, longer.key, 2)) reason = 'edit-distance'
487
+ if (!reason) continue
488
+ found.push({ sourceId: shorter.id, targetId: longer.id, reason, sourceKey: shorter.key, targetKey: longer.key })
489
+ }
490
+ }
491
+ found.sort((x, y) => (x.reason === y.reason ? 0 : x.reason === 'containment' ? -1 : 1)
492
+ || compareText(x.targetKey, y.targetKey)
493
+ || compareText(x.sourceKey, y.sourceKey)
494
+ || compareText(x.targetId, y.targetId)
495
+ || compareText(x.sourceId, y.sourceId))
496
+ return { items: found.slice(0, SUGGEST_LIMIT).map(item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason })) }
497
+ }
498
+
257
499
  /**
258
500
  * Write one directed link from a memory to a memory or entity.
259
501
  *
package/lib/inject.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  getSettings, ensureSession, loadPrivateIndex, loadGlobalIndex,
5
5
  markInjected, releaseInjected, markReinjectPending, clearReinjectPending,
6
6
  armCue, getActiveCue, setSessionMood, wasAnniversaryShown, markAnniversaryShown,
7
+ markOpenLoopReminded, DEFAULT_SETTINGS,
7
8
  touchSession, getSessionBinding, setSessionBinding, setRecallError, effectiveScope,
8
9
  } from './state.js'
9
10
  import {
@@ -16,8 +17,9 @@ import { record, clipQuery } from './activity-log.js'
16
17
  import { readMood } from './mood.js'
17
18
  import { loadPromptForDomain } from './prompts.js'
18
19
  import { estTokens, packToBudget, truncateToTokens } from './budget.js'
20
+ import { freshnessSignals } from './freshness.js'
19
21
  import { imageTurn, captureMediaEvent } from './media.js'
20
- import { redactSecrets } from './paths.js'
22
+ import { redactSecrets, warn } from './paths.js'
21
23
  import {
22
24
  INBOUND_TYPE, ingestInboundBatch, observeInboundEvent, hasPendingInbound, pendingInbound,
23
25
  noteNativeUserMessages, finishInbound, nextMemoryClock, advanceMemoryClock, releaseInboundSession,
@@ -395,6 +397,14 @@ export function buildAnniversary(sessionId, binding, now = new Date()) {
395
397
  lines.push('<memory-due>', '这些是你记下的带日期的约定或安排,时间到了,可以主动提一句;已经过去的不必再反复提起。')
396
398
  for (const [id, entry] of dated) {
397
399
  const ahead = salientDaysAhead(entry.salientDate, now)
400
+ // A promise reads differently from an appointment. "明天要考驾照" is a thing
401
+ // that happens; "我答应过要回电话" is a thing someone owes. The body stays out
402
+ // of the promise line: quoting a broken promise back at length sounds like an
403
+ // accusation, and the title is enough to recall the rest by id.
404
+ if (entry.openLoop === true && (ahead === 0 || ahead === 1)) {
405
+ lines.push(`- [${id}] 你之前答应过的「${entry.title || '(untitled)'}」,就是${ahead === 0 ? '今天' : '明天'}。`)
406
+ continue
407
+ }
398
408
  const when = ahead === 0 ? '就是今天' : ahead === 1 ? '就是明天' : `还有 ${ahead} 天`
399
409
  lines.push(`- [${id}] ${when}(${entry.salientDate})${entry.title || '(untitled)'}${entry.content ? `:${clip(entry.content, 200)}` : ''}`)
400
410
  }
@@ -680,27 +690,64 @@ export function buildReplay(binding, settings = getSettings(), sessionId = null)
680
690
  // what a person opens with. Retrieving it quietly among four other lines is not
681
691
  // resurfacing it, so it gets its own small block, one entry at a time, and only until
682
692
  // it has been mentioned (after which the id sits in injectedIds and is skipped).
693
+ //
694
+ // A dated promise that slipped its day is the exception: it comes back on its own
695
+ // interval (`openLoopRemindDays`) instead of vanishing after one mention, because
696
+ // "we said we would" is not resolved by having said it once. That leg is dated
697
+ // promises first (dueOpenLoops), then the ordinary 3-day loop.
683
698
  const OPEN_LOOP_DAYS = 3
684
699
  const OPEN_LOOP_TOKENS = 110
685
700
  const OPEN_LOOP_CLIP = 120
686
701
 
687
- export function buildOpenLoopNudge(binding, settings = getSettings(), sessionId = null) {
688
- if (!binding?.libraryId || binding.useLibrary === false) return { text: '', ids: [] }
702
+ // Local calendar day, matching how "today" is read everywhere else (the anniversary
703
+ // dayKey and the reminder clock both compare local days, not UTC days).
704
+ function localDayKey(now = new Date()) {
705
+ const date = now instanceof Date ? now : new Date(now)
706
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
707
+ }
708
+
709
+ /**
710
+ * The `[open loop]` block, or an empty result.
711
+ *
712
+ * `skipIds` carries same-turn ids: memories another block (the anniversary) already
713
+ * put in front of the model this turnaround. `recurringIds` reports which of the
714
+ * emitted ids came from the overdue-dated leg, and only those are recorded in
715
+ * `openLoopRemindedAt` — the caller does that after the text is really sent.
716
+ */
717
+ export function buildOpenLoopNudge(binding, settings = getSettings(), sessionId = null, { skipIds = [], now = new Date() } = {}) {
718
+ const at = now instanceof Date ? now : new Date(now)
719
+ const empty = { text: '', ids: [], recurringIds: [], dayKey: localDayKey(at) }
720
+ if (!binding?.libraryId || binding.useLibrary === false) return empty
689
721
  const due = dueOpenLoops({
690
722
  libraryId: binding.libraryId,
691
723
  days: OPEN_LOOP_DAYS,
692
724
  limit: 1,
725
+ now: at.getTime(),
726
+ // The regular leg forgets an id once this conversation pushed it; the overdue leg
727
+ // only obeys its own reminder clock (see dueOpenLoops).
693
728
  skipIds: (binding.injectedIds || []).filter((id) => id !== ANCHOR_SENTINEL),
729
+ // Same-turn ids apply to both legs: the anniversary block already said this one.
730
+ excludeIds: skipIds,
731
+ remindDays: Number(settings?.openLoopRemindDays ?? DEFAULT_SETTINGS.openLoopRemindDays),
732
+ remindedAt: binding.openLoopRemindedAt || {},
733
+ includeOverdueDated: true,
734
+ sessionId,
694
735
  }).filter(({ entry }) => isAnchorEligible(entry) && visibleToSession(entry, sessionId))
695
- if (due.length === 0) return { text: '', ids: [] }
736
+ if (due.length === 0) return empty
737
+ const recurring = new Set(due.filter((item) => item.recurring).map((item) => item.id))
696
738
  const pack = packToBudget(due.map(({ id, entry }) => [id, entry]), OPEN_LOOP_TOKENS, (entry, id) => {
697
739
  const ago = relativeTime(entry.updatedAt || entry.createdAt)
698
- return `- [${id}] ${ownerPrefix(entry)}${entry.title || '(untitled)'}:${clip(entry.content || '', OPEN_LOOP_CLIP)}${ago ? ` · ${ago} 没下文了` : ''}${disclosureTag(entry)}`
740
+ // The date is what makes this leg re-raise itself; showing it lets the model say
741
+ // how late it is instead of inventing a time.
742
+ const slipped = recurring.has(id) && entry.salientDate ? ` · date=${entry.salientDate} 已经过了` : ''
743
+ return `- [${id}] ${ownerPrefix(entry)}${entry.title || '(untitled)'}${slipped}:${clip(entry.content || '', OPEN_LOOP_CLIP)}${ago ? ` · ${ago} 没下文了` : ''}${disclosureTag(entry)}`
699
744
  })
700
- if (pack.lines.length === 0) return { text: '', ids: [] }
745
+ if (pack.lines.length === 0) return empty
701
746
  return {
702
747
  text: ['[open loop] 有件事你一直没放下;合适的时候可以自己提一句,不必现在说。', ...pack.lines].join('\n'),
703
748
  ids: pack.ids,
749
+ recurringIds: pack.ids.filter((id) => recurring.has(id)),
750
+ dayKey: localDayKey(at),
704
751
  }
705
752
  }
706
753
 
@@ -753,11 +800,59 @@ function seenRecently(binding, id, turn, dedupeTurns) {
753
800
  return Number(turn) - Number(at) < Number(dedupeTurns || 8)
754
801
  }
755
802
 
803
+ // Work order D: one conditional footnote after the recall, not a second memory
804
+ // surface. It only says "if your session has a search tool, verify" — it must not
805
+ // claim that web_search exists, and it must never touch the guide or rulesKey.
806
+ function freshnessHintText(count) {
807
+ return [
808
+ '<memory-freshness>',
809
+ `上面有 ${count} 条记忆带时间敏感信号(写于较久前或提到「最新」等)。若你的会话里有可用的搜索工具,回答当前状态前先核实;没有就如实说明可能过时。`,
810
+ '</memory-freshness>',
811
+ ].join('\n')
812
+ }
813
+
814
+ function staleRecallCount(recalled, freshnessDays) {
815
+ const now = Date.now()
816
+ let stale = 0
817
+ for (const entry of recalled.values()) {
818
+ try {
819
+ if (freshnessSignals(entry, { now, freshnessDays }).stale) stale += 1
820
+ } catch (error) {
821
+ // Classification is decoration around a recall that already succeeded. A
822
+ // signal error drops at most this entry's vote, never the recall itself.
823
+ warn(`freshness hint: signal computation skipped: ${error?.message || error}`)
824
+ }
825
+ }
826
+ return stale
827
+ }
828
+
829
+ // Appended only when a non-empty <memory-context> block already exists, the query
830
+ // is long enough to have been a real ask, and the hint still fits the recall's own
831
+ // turnTokens ceiling. The ids counted are exactly the cards that reached the text.
832
+ function appendFreshnessHint(text, query, recalled, settings, budget) {
833
+ if (!text || settings.freshnessHint === false) return text
834
+ if (settings.autoInject === 'off' || settings.autoInject === 'anchor-only') return text
835
+ if (String(query ?? '').trim().length < Number(settings.minUserChars || 6)) return text
836
+ try {
837
+ const days = Number(settings.freshnessDays)
838
+ const freshnessDays = Number.isFinite(days) && days >= 1 ? days : 30
839
+ const stale = staleRecallCount(recalled, freshnessDays)
840
+ if (stale <= 0) return text
841
+ const hint = freshnessHintText(stale)
842
+ if (estTokens(`${text}\n\n${hint}`) > budget) return text
843
+ return `${text}\n\n${hint}`
844
+ } catch (error) {
845
+ warn(`freshness hint skipped: ${error?.message || error}`)
846
+ return text
847
+ }
848
+ }
849
+
756
850
  export async function buildRecall(binding, query, turn, settings = getSettings(), exec = null, sessionId = null) {
757
851
  if (!binding || !query) return { text: '', ids: [], errors: [] }
758
852
  const ids = []
759
853
  const pieces = []
760
854
  const errors = []
855
+ const recalled = new Map()
761
856
  let candidateCount = 0
762
857
  let privateRoute = null
763
858
  let globalRoute = null
@@ -864,11 +959,13 @@ export async function buildRecall(binding, query, turn, settings = getSettings()
864
959
  if (!line.includes(`[${file.name}]`)) continue
865
960
  lines.push(line)
866
961
  ids.push(file.name)
962
+ if (!recalled.has(file.name)) recalled.set(file.name, entry)
867
963
  }
868
964
  if (lines.length) blocks.push([open, intro, ...lines, close].join('\n'))
869
965
  }
870
- const text = blocks.join('\n\n')
966
+ let text = blocks.join('\n\n')
871
967
  if (!text) errors.push('recall omitted: token budget cannot fit a memory entry')
968
+ else text = appendFreshnessHint(text, query, recalled, settings, budget)
872
969
  return finish({ text, ids, errors, outcome: text ? 'injected' : 'budget', candidateCount })
873
970
  }
874
971
 
@@ -1304,22 +1401,30 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1304
1401
  }
1305
1402
  }
1306
1403
 
1404
+ // Same-turn dedup (工单 C / R1): the anniversary block and the open-loop nudge can
1405
+ // name the same memory, and saying it twice in one message reads like a glitch.
1406
+ // Only an anniversary that actually reached `parts` may suppress the nudge — one
1407
+ // the budget dropped must not silence it, because then the turn says nothing.
1408
+ let anniversaryIds = []
1307
1409
  if (!reinject) {
1308
1410
  const anniversary = buildAnniversary(sessionId, effective)
1309
1411
  if (anniversary.text && estTokens(anniversary.text) <= totalRoom()) {
1310
1412
  parts.push(anniversary.text)
1311
1413
  ids.push(...anniversary.ids)
1414
+ anniversaryIds = anniversary.ids
1312
1415
  for (const id of anniversary.fired) markAnniversaryShown(sessionId, id, anniversary.dayKey)
1313
1416
  }
1314
1417
  }
1315
1418
 
1419
+ let recurringNudgeIds = []
1316
1420
  if (!reinject) {
1317
1421
  // Independent of retrieval: a loop can be worth raising in a conversation that
1318
1422
  // shares no vocabulary with it, which is exactly the case lexical recall misses.
1319
- const nudge = buildOpenLoopNudge(effective, settings, sessionId)
1423
+ const nudge = buildOpenLoopNudge(effective, settings, sessionId, { skipIds: anniversaryIds })
1320
1424
  if (nudge.text && estTokens(nudge.text) <= totalRoom()) {
1321
1425
  parts.push(nudge.text)
1322
1426
  ids.push(...nudge.ids)
1427
+ recurringNudgeIds = nudge.recurringIds
1323
1428
  }
1324
1429
  }
1325
1430
 
@@ -1401,6 +1506,12 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1401
1506
  if (index < 0) return decision
1402
1507
  rewritten.splice(index, 0, message)
1403
1508
  markInjected(sessionId, ids, memoryClock)
1509
+ // An overdue dated promise is repeated on its own interval; that clock only starts
1510
+ // once the text is really published. Everything above this line (budget, snapshot
1511
+ // re-check) can still drop the block, and a dropped reminder must not count.
1512
+ for (const id of recurringNudgeIds) {
1513
+ try { markOpenLoopReminded(sessionId, id) } catch {}
1514
+ }
1404
1515
  if (reinject) {
1405
1516
  clearReinjectPending(sessionId)
1406
1517
  // The replay has been paid for; it must not ride along on the next compaction too.
package/lib/memory.js CHANGED
@@ -2770,6 +2770,46 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
2770
2770
  return touched
2771
2771
  }
2772
2772
 
2773
+ // Local calendar day (not UTC): "today" for a reminder is the user's today, the same
2774
+ // unit `salientDaysAhead` measures in.
2775
+ function localDateKey(date) {
2776
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
2777
+ }
2778
+
2779
+ // The overdue leg: dated promises that already slipped their day. Kept out of the
2780
+ // regular filter because it answers a different question (see dueOpenLoops).
2781
+ function overdueDatedOpenLoops(rows, { now, remindDays = 0, remindedAt = {}, excludeIds = new Set() }) {
2782
+ const nowMs = Number(now) || Date.now()
2783
+ const today = new Date(nowMs)
2784
+ const todayKey = localDateKey(today)
2785
+ const remindMs = Math.max(0, Number(remindDays) || 0) * 86_400_000
2786
+ const reminded = remindedAt && typeof remindedAt === 'object' ? remindedAt : {}
2787
+ return rows
2788
+ .filter(([id, entry]) => {
2789
+ if (!entry || excludeIds.has(id)) return false
2790
+ if (!entry.openLoop || entry.marginalized) return false
2791
+ // 'MM-DD' is an anniversary: it recurs on its own and is not a slipped promise.
2792
+ if (!isDatedSalientDate(entry.salientDate)) return false
2793
+ const ahead = salientDaysAhead(entry.salientDate, today)
2794
+ if (ahead === null || ahead >= 0) return false
2795
+ // One gate for archived / suppressed / expired / pending_review / superseded and
2796
+ // for secret bodies: same rule as every other automatic injection surface.
2797
+ if (!isMemoryEligible(entry, { automatic: true, now: nowMs })) return false
2798
+ const last = Date.parse(String(reminded[id] || ''))
2799
+ if (Number.isFinite(last)) {
2800
+ if (localDateKey(new Date(last)) === todayKey) return false
2801
+ if (remindMs > 0 && nowMs - last < remindMs) return false
2802
+ }
2803
+ return true
2804
+ })
2805
+ // Oldest date first: the promise that has been overdue longest is the one that
2806
+ // matters most. Ties fall back to age, then id, so the pick is deterministic.
2807
+ .sort((a, b) => String(a[1].salientDate).localeCompare(String(b[1].salientDate))
2808
+ || String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || ''))
2809
+ || a[0].localeCompare(b[0]))
2810
+ .map(([id, entry]) => ({ id, entry, recurring: true }))
2811
+ }
2812
+
2773
2813
  /**
2774
2814
  * Unfinished threads old enough to be worth raising.
2775
2815
  *
@@ -2778,7 +2818,50 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
2778
2818
  * retrieving it among four other lines is not the same as resurfacing it, so the
2779
2819
  * injector gets its own small query for this — sorted oldest-first, and never the ones
2780
2820
  * that were already pushed this session.
2821
+ *
2822
+ * Two legs share the result, in this order:
2823
+ *
2824
+ * 1. `includeOverdueDated` adds dated promises that already slipped their day
2825
+ * (`YYYY-MM-DD`, date < local today, `openLoop`). They are *not* subject to the
2826
+ * 3-day age threshold — being a day late is exactly when it matters — and they
2827
+ * are *not* silenced by `skipIds`/`injectedIds`: a promise that was mentioned
2828
+ * once and never closed has to come back. Their own clock is `remindedAt`
2829
+ * (memoryId -> ISO) plus `remindDays`: already repeated today → skip, last
2830
+ * repeat younger than the interval → skip.
2831
+ * 2. The regular leg, unchanged: `openLoop`, not marginalized, eligible, at least
2832
+ * `days` old, not in `skipIds`, not repeated this same turn (`excludeIds`).
2781
2833
  */
2834
+ export function dueOpenLoops({
2835
+ libraryId, days = 3, limit = 1, now = Date.now(), skipIds = [],
2836
+ remindDays = 0, remindedAt = {}, includeOverdueDated = false, excludeIds = [], sessionId = null,
2837
+ }) {
2838
+ if (!libraryId) return []
2839
+ const index = loadPrivateIndex(libraryId)
2840
+ const skip = new Set(skipIds || [])
2841
+ const excluded = new Set(excludeIds || [])
2842
+ // Filtered before the limit, not after: otherwise an entry this conversation may
2843
+ // not see would eat the single slot and leave the block empty.
2844
+ const visible = (entry) => (sessionId ? visibleToSession(entry, sessionId) : true)
2845
+ const rows = Object.entries(index.entries || {})
2846
+ const regular = rows
2847
+ .filter(([id, entry]) => {
2848
+ if (!entry || skip.has(id) || excluded.has(id)) return false
2849
+ if (!entry.openLoop || entry.marginalized) return false
2850
+ if (!isActive(entry)) return false
2851
+ if (!visible(entry)) return false
2852
+ const age = daysSince(entry.updatedAt || entry.createdAt, now)
2853
+ return age !== null && age >= days
2854
+ })
2855
+ .sort((a, b) => String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || '')) || a[0].localeCompare(b[0]))
2856
+ .map(([id, entry]) => ({ id, entry, recurring: false }))
2857
+ const overdue = includeOverdueDated
2858
+ ? overdueDatedOpenLoops(rows, { now, remindDays, remindedAt, excludeIds: excluded }).filter(({ entry }) => visible(entry))
2859
+ : []
2860
+ // A dated promise that already slipped outranks a vague 3-day-old loop: the date
2861
+ // is a commitment, the other one is just unfinished.
2862
+ return [...overdue, ...regular].slice(0, Math.max(0, Number(limit) || 0))
2863
+ }
2864
+
2782
2865
  /**
2783
2866
  * Memories a sensory cue may be derived from.
2784
2867
  *
@@ -2822,20 +2905,3 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
2822
2905
  .localeCompare(String(a.entry.updatedAt || a.entry.createdAt || '')))
2823
2906
  .slice(0, Math.max(0, Number(limit) || 0))
2824
2907
  }
2825
-
2826
- export function dueOpenLoops({ libraryId, days = 3, limit = 1, now = Date.now(), skipIds = [] }) {
2827
- if (!libraryId) return []
2828
- const index = loadPrivateIndex(libraryId)
2829
- const skip = new Set(skipIds || [])
2830
- return Object.entries(index.entries || {})
2831
- .filter(([id, entry]) => {
2832
- if (!entry || skip.has(id)) return false
2833
- if (!entry.openLoop || entry.marginalized) return false
2834
- if (!isActive(entry)) return false
2835
- const age = daysSince(entry.updatedAt || entry.createdAt, now)
2836
- return age !== null && age >= days
2837
- })
2838
- .sort((a, b) => String(a[1].updatedAt || a[1].createdAt || '').localeCompare(String(b[1].updatedAt || b[1].createdAt || '')))
2839
- .slice(0, Math.max(0, Number(limit) || 0))
2840
- .map(([id, entry]) => ({ id, entry }))
2841
- }
package/lib/rpc.js CHANGED
@@ -18,7 +18,7 @@ import { statsView } from './stats.js'
18
18
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
19
19
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
20
20
  import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
21
- import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
21
+ import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
22
22
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
23
23
  import { listEvents, logStats, clearEvents } from './activity-log.js'
24
24
  import { warn } from './paths.js'
@@ -75,7 +75,8 @@ const LIBRARY_ROUTE_OPERATIONS = new Map([
75
75
  ['browseLibrary', 'read'], ['getMemory', 'read'], ['getStats', 'read'], ['addMemory', 'write'], ['updateMemory', 'write'],
76
76
  ['importMemories', 'import'], ['exportLibrary', 'export'], ['getAttachment', 'attachment.read'],
77
77
  ['browseWall', 'read'], ['getGraph', 'read'], ['listEntities', 'read'], ['createEntity', 'write'], ['renameEntity', 'write'],
78
- ['deleteEntity', 'write'], ['linkEntries', 'write'], ['unlinkEntry', 'write'], ['getRelationship', 'read'], ['updateRelationship', 'write'],
78
+ ['deleteEntity', 'write'], ['mergeEntities', 'write'], ['suggestEntityMerges', 'read'],
79
+ ['linkEntries', 'write'], ['unlinkEntry', 'write'], ['getRelationship', 'read'], ['updateRelationship', 'write'],
79
80
  ['listReviews', 'read'], ['resolveReview', 'write'], ['lexiconList', 'read'], ['lexiconSearch', 'read'], ['lexiconAdd', 'write'],
80
81
  ['lexiconUpdate', 'write'], ['lexiconDelete', 'write'], ['lexiconArchive', 'write'], ['lexiconRestore', 'write'],
81
82
  ['archiveMemory', 'archive'], ['deleteMemory', 'delete'],
@@ -890,6 +891,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
890
891
  'inboundToolNames',
891
892
  // 全局提炼的审核模式(spec §6.1):恢复默认 = 回到 auto,不保留全审状态。
892
893
  'curatorReviewMode',
894
+ // 工单 C/D/E 的调参:没进这张表的 key 会被静默丢弃,设置页就成了死控件。
895
+ 'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
896
+ 'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
893
897
  ]) patch[key] = DEFAULT_SETTINGS[key]
894
898
  return updateSettings(patch)
895
899
  }
@@ -909,6 +913,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
909
913
  'sidebarSettings', 'visionCaptionEnabled', 'inboundToolNames',
910
914
  // 全局提炼的审核模式(spec §6.1):不进 allowlist 的 patch 会被静默丢弃。
911
915
  'curatorReviewMode',
916
+ // 工单 C/D/E:未了之事复提节奏、时效提示、日期唤醒。缺一个就是设置页写了不生效。
917
+ 'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
918
+ 'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
912
919
  ])
913
920
  const clean = {}
914
921
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
@@ -1242,6 +1249,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1242
1249
  return renameEntity(payload || {})
1243
1250
  case 'deleteEntity':
1244
1251
  return deleteEntity(payload || {})
1252
+ case 'mergeEntities':
1253
+ return mergeEntities(payload || {})
1254
+ case 'suggestEntityMerges':
1255
+ return suggestEntityMerges(payload || {})
1245
1256
  case 'linkEntries':
1246
1257
  return linkEntries(payload || {})
1247
1258
  case 'unlinkEntry':