dsh-memu-memory 1.3.1 → 1.3.2

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 (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +1412 -69
  17. package/lib/graph.js +269 -18
  18. package/lib/memory.js +11 -0
  19. package/lib/memu.js +7 -6
  20. package/lib/private-links.js +105 -137
  21. package/lib/private.js +138 -38
  22. package/lib/rpc.js +67 -7
  23. package/lib/state.js +7 -2
  24. package/lib/tools.js +4 -2
  25. package/lib/webui/graph-LICENSE.txt +1 -62
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +891 -124
  28. package/lib/webui/standalone.js +3 -3
  29. package/package.json +1 -2
  30. package/scripts/build-graph.mjs +3 -3
  31. package/scripts/check-graph-browser.mjs +106 -23
  32. package/scripts/rebuild-auto-links.mjs +252 -0
  33. package/tests/audit-regression.test.mjs +11 -8
  34. package/tests/auto-link-candidates.test.mjs +161 -0
  35. package/tests/auto-link-decide.test.mjs +512 -0
  36. package/tests/auto-link-migration.test.mjs +133 -0
  37. package/tests/client-render.test.mjs +7 -6
  38. package/tests/consolidation-fork.test.mjs +148 -0
  39. package/tests/cycle.test.mjs +1 -1
  40. package/tests/graph-view.test.mjs +163 -21
  41. package/tests/graph.test.mjs +5 -0
  42. package/tests/help-page.test.mjs +3 -3
  43. package/tests/memu-resident-route.test.mjs +130 -0
  44. package/tests/private-links.test.mjs +81 -45
  45. package/tests/stubs/child-process-spy.mjs +14 -0
  46. package/tests/tools.test.mjs +24 -18
package/lib/graph.js CHANGED
@@ -10,8 +10,11 @@ import { record } from './activity-log.js'
10
10
  // only touch each other's bindings in function bodies, and ESM hoists the
11
11
  // function declarations before either module body runs.
12
12
  import { normalizeEntityName } from './private-links.js'
13
+ import { refreshEntityMentions } from './auto-link/apply.js'
14
+ import { addSuppression, suppressionSet } from './auto-link/suppression.js'
15
+ import { ENTITY_STATUS } from './auto-link/policy.js'
13
16
 
14
- export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict']
17
+ export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict', 'supersede']
15
18
  const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
16
19
  // Relationship revisions are audit history, not an ever-growing data store. A
17
20
  // long-lived role-play can update one relation hundreds of times; keeping all of
@@ -102,7 +105,12 @@ export function listEntities(args) {
102
105
  }
103
106
  const items = Object.values(store.entities)
104
107
  .filter(entity => !sessionId || linked.has(entity.id))
105
- .map(entity => ({ ...entity, linked: linked.has(entity.id) }))
108
+ .map(entity => ({
109
+ ...entity,
110
+ // Legacy rows have no status; they read as provisional, never confirmed.
111
+ status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional',
112
+ linked: linked.has(entity.id),
113
+ }))
106
114
  return { items, total: items.length }
107
115
  }
108
116
 
@@ -125,7 +133,13 @@ export function restoreGraphData(libraryId, data, memoryIdMap, { origin = null }
125
133
  const createdEntityIds = []
126
134
  for (const [oldId, entity] of Object.entries(data.entities).slice(0, 2000)) {
127
135
  if (!/^ent[-_][a-z0-9_-]+$/i.test(oldId)) continue
128
- const restored = createEntity({ libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [], origin })
136
+ // An import is a user action: rows without a status come back confirmed, and
137
+ // an explicit status travels with the backup unchanged.
138
+ const restored = createEntity({
139
+ libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [], origin,
140
+ status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'confirmed',
141
+ confirmedBy: entity.confirmedBy || 'user',
142
+ })
129
143
  entityMap[oldId] = restored.id
130
144
  if (origin && restored.origin === origin) createdEntityIds.push(restored.id)
131
145
  }
@@ -183,10 +197,17 @@ export function revertGraphData({ libraryId, entityIds = [] }) {
183
197
  * imported memory package, say. It exists so the import can be undone: an entity
184
198
  * that already existed before the import is returned as-is and stays untagged, so a
185
199
  * revert can never delete a person the user had added themselves.
200
+ *
201
+ * `status` is the auto-link assertion state (DESIGN §6.1). The default is
202
+ * `provisional`: creation alone never proves a name is real, so a new row
203
+ * produces no mention edges until a user / agent / worker confirms it. Explicit
204
+ * creation paths (UI, import) pass `confirmed`; worker tools keep provisional
205
+ * and let the review queue decide.
186
206
  */
187
- export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [], origin = null }) {
207
+ export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [], origin = null, status = 'provisional', confirmedBy = null }) {
188
208
  const scope = scopeFor({ exec, libraryId })
189
209
  if (!ENTITY_KINDS.includes(kind)) throw new Error(`entity kind must be ${ENTITY_KINDS.join(', ')}`)
210
+ if (!ENTITY_STATUS.includes(status)) throw new Error(`entity status must be ${ENTITY_STATUS.join(', ')}`)
190
211
  const clean = String(name || '').trim()
191
212
  if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
192
213
  const file = entitiesPath(scope.libraryId)
@@ -195,13 +216,114 @@ export function createEntity({ exec, libraryId, name, kind = 'person', aliases =
195
216
  const existing = Object.values(store.entities).find(entity => entity.name === clean && entity.kind === kind)
196
217
  if (existing) return existing
197
218
  const id = newMemoryId('ent')
198
- const entity = { id, name: clean, kind, aliases: normalizeAliases(aliases), createdAt: stamp(), updatedAt: stamp(), ...(origin ? { origin: String(origin) } : {}) }
219
+ const at = stamp()
220
+ const entity = {
221
+ id, name: clean, kind, aliases: normalizeAliases(aliases), status,
222
+ createdAt: at, updatedAt: at,
223
+ ...(origin ? { origin: String(origin) } : {}),
224
+ ...(status === 'confirmed' ? { confirmedAt: at, confirmedBy: String(confirmedBy || 'user') } : {}),
225
+ }
199
226
  store.entities[id] = entity
200
227
  writeJson(file, store)
201
228
  return entity
202
229
  })
203
230
  }
204
231
 
232
+ /**
233
+ * Explicit confirmation is the only way an entity becomes `confirmed`. The write
234
+ * is followed by one incremental mention pass for that entity, so existing
235
+ * memories gain their edges immediately instead of waiting for the next
236
+ * consolidation.
237
+ */
238
+ export function confirmEntities({ exec, libraryId, entityIds, by = 'user' }) {
239
+ const scope = scopeFor({ exec, libraryId })
240
+ const ids = [...new Set((Array.isArray(entityIds) ? entityIds : []).map(id => String(id || '').trim()).filter(Boolean))]
241
+ if (!ids.length) throw new Error('entityIds must name at least one entity')
242
+ if (!['user', 'agent', 'worker'].includes(by)) throw new Error('confirmation actor must be user, agent or worker')
243
+ const file = entitiesPath(scope.libraryId)
244
+ const confirmed = []
245
+ // Already-confirmed rows are refreshed too: if they were confirmed while the
246
+ // mode was 'off', status changed but no edge was written. Re-confirming (or the
247
+ // deterministic switch below) must be able to backfill, idempotently.
248
+ const refreshTargets = []
249
+ withFileLock(file, () => {
250
+ const store = readEntities(scope.libraryId)
251
+ const at = stamp()
252
+ for (const id of ids) {
253
+ const entity = store.entities[id]
254
+ if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
255
+ if (entity.status === 'archived') continue
256
+ if (entity.status === 'confirmed') { refreshTargets.push(entity); continue }
257
+ entity.status = 'confirmed'
258
+ entity.origin = by
259
+ entity.confirmedAt = at
260
+ entity.confirmedBy = by
261
+ entity.updatedAt = at
262
+ confirmed.push(entity)
263
+ refreshTargets.push(entity)
264
+ }
265
+ if (confirmed.length) writeJson(file, store)
266
+ })
267
+ let suppression = null
268
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
269
+ let entities = 0
270
+ for (const entity of refreshTargets) {
271
+ try {
272
+ const result = refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression })
273
+ entities += result.added + result.updated
274
+ } catch (error) {
275
+ warn(`mention refresh after entity confirmation skipped: ${error?.message || error}`)
276
+ }
277
+ }
278
+ return { confirmed: confirmed.map(entity => entity.id), skipped: ids.length - confirmed.length, entities }
279
+ }
280
+
281
+ /**
282
+ * One-time grading of pre-status entity rows (DESIGN §9.3). It never confirms on
283
+ * statistical evidence: an old row is `confirmed` only when somebody had already
284
+ * asserted it (origin user/agent/worker, or a non-auto link points at it), and
285
+ * everything else becomes `provisional`. Callers pass `apply:false` for dry runs.
286
+ */
287
+ export function gradeLegacyEntities({ libraryId, apply = false } = {}) {
288
+ const scope = scopeFor({ libraryId })
289
+ const file = entitiesPath(scope.libraryId)
290
+ return withFileLock(file, () => {
291
+ const store = readEntities(scope.libraryId)
292
+ const asserted = new Set()
293
+ try {
294
+ for (const entry of Object.values(loadPrivateIndex(scope.libraryId).entries || {})) {
295
+ for (const link of entry.links || []) {
296
+ if (link?.to && link.source !== 'auto') asserted.add(link.to)
297
+ }
298
+ }
299
+ } catch {}
300
+ const result = { scanned: 0, changed: 0, provisional: 0, confirmed: 0, applied: apply === true }
301
+ const at = stamp()
302
+ for (const entity of Object.values(store.entities || {})) {
303
+ result.scanned += 1
304
+ if (!ENTITY_STATUS.includes(entity.status)) {
305
+ const protectedRow = ['user', 'agent', 'worker'].includes(entity.origin) || asserted.has(entity.id)
306
+ const status = protectedRow ? 'confirmed' : 'provisional'
307
+ result[status] += 1
308
+ if (apply) {
309
+ entity.status = status
310
+ if (status === 'confirmed') {
311
+ entity.confirmedAt = entity.confirmedAt || at
312
+ entity.confirmedBy = entity.confirmedBy || (['user', 'agent', 'worker'].includes(entity.origin) ? entity.origin : 'user')
313
+ }
314
+ entity.updatedAt = at
315
+ result.changed += 1
316
+ }
317
+ continue
318
+ }
319
+ if (entity.status === 'confirmed') result.confirmed += 1
320
+ if (entity.status === 'provisional') result.provisional += 1
321
+ }
322
+ if (apply && result.changed) writeJson(file, store)
323
+ return result
324
+ })
325
+ }
326
+
205
327
  function normalizeAliases(aliases) {
206
328
  if (!Array.isArray(aliases) || aliases.some(alias => typeof alias !== 'string')) throw new Error('aliases must be an array of strings')
207
329
  return [...new Set(aliases.map(alias => alias.trim()).filter(Boolean))].slice(0, 30).map(alias => alias.slice(0, 120))
@@ -212,16 +334,28 @@ export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
212
334
  const clean = String(name || '').trim()
213
335
  if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
214
336
  const file = entitiesPath(scope.libraryId)
215
- return withFileLock(file, () => {
337
+ const entity = withFileLock(file, () => {
216
338
  const store = readEntities(scope.libraryId)
217
- const entity = store.entities[entityId]
218
- if (!entity) throw new Error('unknown entity')
219
- entity.name = clean
220
- entity.aliases = normalizeAliases(aliases)
221
- entity.updatedAt = stamp()
339
+ const row = store.entities[entityId]
340
+ if (!row) throw new Error('unknown entity')
341
+ row.name = clean
342
+ row.aliases = normalizeAliases(aliases)
343
+ row.updatedAt = stamp()
222
344
  writeJson(file, store)
223
- return entity
345
+ return row
224
346
  })
347
+ // A confirmed entity's mention edges cite surfaces by name; rename/alias edits
348
+ // must collect the stale ones and attach the new ones immediately.
349
+ if (entity.status === 'confirmed') {
350
+ let suppression = null
351
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
352
+ try {
353
+ refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, operation: 'auto-link-rename' })
354
+ } catch (error) {
355
+ warn(`mention refresh after entity rename skipped: ${error?.message || error}`)
356
+ }
357
+ }
358
+ return entity
225
359
  }
226
360
 
227
361
  // What keeps an entity alive. Edges only live in one direction: an entry's
@@ -308,7 +442,8 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
308
442
  const scope = scopeFor({ exec, libraryId })
309
443
  if (!entityId || typeof entityId !== 'string') throw new Error('entityId is required')
310
444
  const file = entitiesPath(scope.libraryId)
311
- return withFileLock(file, () => {
445
+ const removedAuto = []
446
+ const result = withFileLock(file, () => {
312
447
  const store = readEntities(scope.libraryId)
313
448
  if (!store.entities[entityId]) throw new Error('unknown entity')
314
449
  const index = loadPrivateIndex(scope.libraryId)
@@ -337,9 +472,18 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
337
472
  let removedLinks = 0
338
473
  if (inbound) {
339
474
  updatePrivateIndex(scope.libraryId, fresh => {
340
- for (const entry of Object.values(fresh.entries)) {
475
+ for (const [fromId, entry] of Object.entries(fresh.entries)) {
341
476
  if (!Array.isArray(entry.links) || !entry.links.some(link => link.to === entityId)) continue
342
- const kept = entry.links.filter(link => link.to !== entityId)
477
+ const kept = entry.links.filter(link => {
478
+ if (link.to !== entityId) return true
479
+ if (link.source === 'auto') {
480
+ removedAuto.push({
481
+ from: fromId, to: entityId, kind: link.kind,
482
+ rule: link.evidence?.rule || 'auto',
483
+ })
484
+ }
485
+ return false
486
+ })
343
487
  removedLinks += entry.links.length - kept.length
344
488
  entry.links = kept
345
489
  }
@@ -350,6 +494,14 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
350
494
  writeJson(file, store)
351
495
  return { entityId, deleted: true, removedLinks, removedRelationships: relationshipKeys.length }
352
496
  })
497
+ // Revoking an entity must not let the next consolidation resurrect its auto
498
+ // edges; the exact edge keys go into the suppression table.
499
+ if (removedAuto.length) {
500
+ try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
501
+ warn(`link suppression after entity delete skipped: ${error?.message || error}`)
502
+ }
503
+ }
504
+ return result
353
505
  }
354
506
 
355
507
  /**
@@ -388,6 +540,7 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
388
540
  if (!sources.length) throw new Error('sourceIds must name at least one entity')
389
541
  const file = entitiesPath(scope.libraryId)
390
542
  let targetName = target
543
+ let mergedEntity = null
391
544
  const result = withFileLock(file, () => {
392
545
  const store = readEntities(scope.libraryId)
393
546
  const targetEntity = store.entities[target]
@@ -437,7 +590,13 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
437
590
  continue
438
591
  }
439
592
  targetKinds.add(link.kind)
440
- nextLinks.push({ ...link, to: target })
593
+ // An auto mention edge cites the entity it was built for; the merged
594
+ // row inherits those citations so a later refresh can find them.
595
+ const remapped = { ...link, to: target }
596
+ if (remapped.evidence && sourceSet.has(remapped.evidence.entityId)) {
597
+ remapped.evidence = { ...remapped.evidence, entityId: target }
598
+ }
599
+ nextLinks.push(remapped)
441
600
  }
442
601
  for (const kind of autoKinds) {
443
602
  const at = nextLinks.findIndex(item => item && item.to === target && item.kind === kind)
@@ -477,6 +636,18 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
477
636
  }
478
637
 
479
638
  targetEntity.aliases = aliases
639
+ // A merge is an assertion union: folding a confirmed source into a
640
+ // provisional target confirms the surviving row. An archived target keeps
641
+ // its archived state — the user retired that identity on purpose.
642
+ const confirmedSource = sourceEntities.find(entity => entity.status === 'confirmed')
643
+ if (confirmedSource && (!targetEntity.status || targetEntity.status === 'provisional')) {
644
+ targetEntity.status = 'confirmed'
645
+ targetEntity.confirmedAt = confirmedSource.confirmedAt || stamp()
646
+ targetEntity.confirmedBy = confirmedSource.confirmedBy || 'user'
647
+ if (!targetEntity.origin) targetEntity.origin = confirmedSource.origin || 'user'
648
+ } else if (!ENTITY_STATUS.includes(targetEntity.status)) {
649
+ targetEntity.status = 'provisional'
650
+ }
480
651
  targetEntity.updatedAt = stamp()
481
652
  for (const id of sources) delete store.entities[id]
482
653
  writeJson(file, store)
@@ -488,9 +659,23 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
488
659
  try { pruneOrphanEntities(scope.libraryId, [target]) } catch (error) {
489
660
  warn(`orphan entity prune after entity merge skipped: ${error?.message || error}`)
490
661
  }
662
+ mergedEntity = targetEntity
491
663
  return { targetId: target, merged: sources, aliases, droppedAliases, remappedLinks, duplicateLinks, relationships }
492
664
  })
493
665
 
666
+ // The merged row now owns the union of names; recompute its mention edges so
667
+ // citations point at the surviving entity and new aliases take effect.
668
+ if (mergedEntity?.status === 'confirmed') {
669
+ let suppression = null
670
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
671
+ try {
672
+ result.mentionRefresh = refreshEntityMentions({
673
+ libraryId: scope.libraryId, entity: mergedEntity, suppression, operation: 'auto-link-merge',
674
+ })
675
+ } catch (error) {
676
+ warn(`mention refresh after entity merge skipped: ${error?.message || error}`)
677
+ }
678
+ }
494
679
  // The merge is already durable; the activity log is diagnostics and is
495
680
  // fail-open by design, so it must never decide the result.
496
681
  try {
@@ -621,18 +806,70 @@ export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confide
621
806
  return { from: fromId, ...result }
622
807
  }
623
808
 
809
+ /**
810
+ * Remove every automatic edge in one library. Manual / worker edges are kept
811
+ * byte-for-byte, and each removed (from,to,kind) is suppressed so the
812
+ * deterministic layer cannot recreate it (P6). Used by the graph page's
813
+ * "remove all auto edges" action and by operators cleaning a legacy library.
814
+ */
815
+ export function purgeAutoLinks({ libraryId } = {}) {
816
+ const scope = scopeFor({ libraryId })
817
+ const removed = []
818
+ updatePrivateIndex(scope.libraryId, index => {
819
+ for (const [fromId, entry] of Object.entries(index.entries || {})) {
820
+ if (!Array.isArray(entry.links)) continue
821
+ const kept = []
822
+ for (const link of entry.links) {
823
+ if (link && link.source === 'auto') {
824
+ removed.push({ from: fromId, to: link.to, kind: link.kind, rule: link.evidence?.rule || 'auto' })
825
+ continue
826
+ }
827
+ kept.push(link)
828
+ }
829
+ if (kept.length !== entry.links.length) entry.links = kept
830
+ }
831
+ })
832
+ if (removed.length) {
833
+ try { addSuppression(scope.libraryId, removed, { by: 'user' }) } catch (error) {
834
+ warn(`link suppression after auto purge skipped: ${error?.message || error}`)
835
+ }
836
+ }
837
+ try {
838
+ record({
839
+ kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
840
+ message: `批量删除自动边:${removed.length} 条`,
841
+ detail: { op: 'auto-link-purge', removed: removed.length },
842
+ refs: [...new Set(removed.map(edge => edge.from))].slice(0, 20),
843
+ })
844
+ } catch {}
845
+ return { removed: removed.length }
846
+ }
847
+
624
848
  export function unlinkEntry({ libraryId, fromId, toId, kind }) {
625
849
  const scope = scopeFor({ libraryId })
626
850
  let removed = 0
851
+ const removedAuto = []
627
852
  updatePrivateIndex(scope.libraryId, index => {
628
853
  const entry = index.entries[fromId]
629
854
  if (!entry) throw new Error('unknown memory')
630
855
  entry.links = (entry.links || []).filter(link => {
631
856
  const drop = link.to === toId && (!kind || link.kind === kind)
632
- if (drop) removed += 1
857
+ if (drop) {
858
+ removed += 1
859
+ if (link.source === 'auto') {
860
+ removedAuto.push({ from: fromId, to: toId, kind: link.kind, rule: link.evidence?.rule || 'auto' })
861
+ }
862
+ }
633
863
  return !drop
634
864
  })
635
865
  })
866
+ // Deleting an auto edge is a negative label: the deterministic layer must not
867
+ // add it back on the next consolidation.
868
+ if (removedAuto.length) {
869
+ try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
870
+ warn(`link suppression after auto edge removal skipped: ${error?.message || error}`)
871
+ }
872
+ }
636
873
  return { removed }
637
874
  }
638
875
 
@@ -652,7 +889,17 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
652
889
  if (index.entries[link.to] && !visible.has(link.to)) continue
653
890
  // source is display metadata only ('auto' edges get a badge in the graph
654
891
  // view); an older link without the field reports null instead of undefined.
655
- const edge = { from, to: link.to, kind: link.kind, note: link.note, confidence: link.confidence ?? 0.7, source: link.source || null }
892
+ // evidence.rule / surface / field let the graph say WHY an edge exists.
893
+ // Legacy auto edges written before the rule schema carry no evidence.rule:
894
+ // report them under the stable 'auto' bucket so the WebUI rule filter still
895
+ // works on old data. New writes always record the real rule
896
+ // (auto-link/apply.js) — this fallback is read-only display metadata.
897
+ const edge = {
898
+ from, to: link.to, kind: link.kind, note: link.note,
899
+ confidence: link.confidence ?? 0.7, source: link.source || null,
900
+ rule: link.evidence?.rule || (link.source === 'auto' ? 'auto' : null),
901
+ evidence: link.evidence || null,
902
+ }
656
903
  edges.push(edge)
657
904
  for (const [a, b] of [[from, link.to], [link.to, from]]) {
658
905
  if (!adjacency.has(a)) adjacency.set(a, new Set())
@@ -754,6 +1001,10 @@ export function recallRelations(libraryId, index, id, sessionId) {
754
1001
  const entry = index.entries?.[from]
755
1002
  if (!entry) continue
756
1003
  if (!isMemoryEligible(entry, { automatic: true }) || !visibleToSession(entry, sessionId)) continue
1004
+ // entity-mention is a fact index, not a relationship: its confidence is 1.0
1005
+ // by construction, and letting it into the top-2 would crowd out the manual /
1006
+ // field-evidence edges this expansion exists to surface.
1007
+ if (link.evidence?.rule === 'entity-mention') continue
757
1008
  const to = from === id ? link.to : from
758
1009
  const target = index.entries[to]
759
1010
  if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
package/lib/memory.js CHANGED
@@ -18,6 +18,7 @@ import { BASE_AROUSAL, derivedValence, dominanceBias, emotionActive, maxShare, m
18
18
  import { commit, retrieve, listFiles, forget } from './memu.js'
19
19
  import { bumpStats } from './stats.js'
20
20
  import { recallRelations, pruneOrphanEntities, revertGraphData } from './graph.js'
21
+ import { refreshPrivateAutoLinks } from './private-links.js'
21
22
  import { attachmentRefs } from './media.js'
22
23
  import { normalizeMemoryContext, contextVisible, sameFactContext } from './context.js'
23
24
  import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGeneration, enrollActiveLibrary, hasActiveVectorGeneration, isVectorStateError, readVectorState, withVectorWrite } from './vector-profile.js'
@@ -2111,6 +2112,11 @@ async function privateRememberImpl({
2111
2112
  if (layer === 'must_remember' && pinSource === 'side_event') {
2112
2113
  consumeCue(sessionIdOf(exec), sideEventId)
2113
2114
  }
2115
+ // 这条写入带着字段证据(显式 conflicts_with / supersedes,或同 fact_key 配对)时,
2116
+ // 立即把确定性边同步到图上,不等下一次整理;失败只 warn,写入已经成功。
2117
+ if (relationId) {
2118
+ await refreshPrivateAutoLinks({ libraryId: scope.libraryId, sessionId: memorySession, ids: [id, relationId] })
2119
+ }
2114
2120
  return { id, entry, result, conflict: entry.conflictingWith || null, conflictsWith: entry.conflicts_with || null, supersedes: entry.supersedes || null }
2115
2121
  }
2116
2122
 
@@ -3151,6 +3157,11 @@ async function resolveMemoryReviewImpl({ libraryId = null, id, action, resolutio
3151
3157
  }
3152
3158
  await retryStoreWrite(() => libraryId ? updatePrivateIndex(libraryId, mutate) : updateGlobalIndex(mutate))
3153
3159
  if (libraryId && action === 'reject') bumpStats(libraryId, 'archived')
3160
+ // accept+replace 会把旧条目标成 superseded、给新条目写 supersedes 字段:这是
3161
+ // 字段证据的变化,立即重算两端的确定性边,避免图上还挂着“已不成立”的旧关系。
3162
+ if (libraryId && action === 'accept' && resolution === 'replace' && entry.conflictingWith) {
3163
+ await refreshPrivateAutoLinks({ libraryId, sessionId, ids: [id, entry.conflictingWith] })
3164
+ }
3154
3165
  return { id, status: next.status, resolution }
3155
3166
  }
3156
3167
 
package/lib/memu.js CHANGED
@@ -416,12 +416,13 @@ async function runConfigured(args, options = {}) {
416
416
  const env = await envFor({ ...options, route })
417
417
  if (generation) assertVectorGeneration(generation)
418
418
  if (migration) assertMigrationProfile(migration)
419
- // Local vector mode is the only route this plugin can reach without a vendor key,
420
- // so it is where a cold Python import is paid most often. Keep one interpreter warm
421
- // there; the remote API path keeps the one-process-per-command behavior.
422
- const result = useManagedLocal
423
- ? await runResident(args, { env, timeoutMs: options.timeoutMs })
424
- : await runRaw(['-m', 'memu', ...args], { env, timeoutMs: options.timeoutMs })
419
+ // The cost is the Python import chain, not the embedding call, and every route
420
+ // pays it once per command. The resident worker already takes its env (base URL,
421
+ // key, model, db) per command and releases sqlite handles after each one, so the
422
+ // remote API route reuses the same warm interpreter. One process per command made
423
+ // every recall pay a cold start, which is exactly the "send a message, wait ten
424
+ // seconds" latency users saw in API mode.
425
+ const result = await runResident(args, { env, timeoutMs: options.timeoutMs })
425
426
  if (generation) assertVectorGeneration(generation)
426
427
  if (migration) assertMigrationProfile(migration)
427
428
  return result