dsh-memu-memory 1.2.1 → 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.
Files changed (105) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +23 -8
  3. package/README.zh.md +16 -6
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/contributing.md +18 -4
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +20 -0
  8. package/docs/host-api.md +22 -1
  9. package/docs/memory-semantics.md +30 -2
  10. package/docs/troubleshooting.md +76 -5
  11. package/lib/activity-log.js +1 -1
  12. package/lib/backup.js +24 -2
  13. package/lib/binding-diagnostics.js +2 -2
  14. package/lib/client.js +1511 -153
  15. package/lib/consolidation-worker.js +30 -8
  16. package/lib/curator-evidence.js +131 -0
  17. package/lib/curator-policy.js +81 -0
  18. package/lib/curator.js +1252 -91
  19. package/lib/cycle.js +12 -1
  20. package/lib/embedding-download.js +39 -4
  21. package/lib/engine.js +6 -3
  22. package/lib/freshness.js +97 -0
  23. package/lib/global-graph.js +282 -0
  24. package/lib/graph.js +295 -11
  25. package/lib/inbound.js +19 -0
  26. package/lib/inject.js +396 -25
  27. package/lib/lexicon.js +1115 -0
  28. package/lib/local-vector-service.js +8 -6
  29. package/lib/managed-runtime.js +33 -2
  30. package/lib/memory.js +365 -34
  31. package/lib/memu.js +2 -2
  32. package/lib/migrate.js +83 -2
  33. package/lib/private-links.js +587 -0
  34. package/lib/private.js +32 -3
  35. package/lib/prompts/global-curator.md +76 -19
  36. package/lib/prompts/private-consolidation.coding.md +4 -1
  37. package/lib/prompts/private-consolidation.md +3 -1
  38. package/lib/prompts/private-consolidation.mixed.md +3 -1
  39. package/lib/prompts/private-consolidation.rp.md +3 -1
  40. package/lib/prompts.js +1 -1
  41. package/lib/rpc.js +589 -10
  42. package/lib/salient-wake.js +402 -0
  43. package/lib/state.js +95 -1
  44. package/lib/text-retrieval.js +661 -0
  45. package/lib/text-similarity.js +36 -18
  46. package/lib/tools.js +168 -10
  47. package/lib/webui/standalone.css +17 -0
  48. package/lib/webui/standalone.js +2 -0
  49. package/package.json +1 -1
  50. package/scripts/acceptance-local.mjs +8 -5
  51. package/scripts/curator-pair-calibrate.mjs +259 -0
  52. package/scripts/drive-session.mjs +853 -0
  53. package/scripts/lexicon-calibrate.mjs +230 -0
  54. package/scripts/lexicon-dedupe.mjs +318 -0
  55. package/scripts/mock-llm.mjs +903 -0
  56. package/tests/absorb-review.test.mjs +353 -0
  57. package/tests/appendix-b2.test.mjs +2 -2
  58. package/tests/client-export.test.mjs +520 -0
  59. package/tests/client-render.test.mjs +32 -4
  60. package/tests/consolidation-fork.test.mjs +14 -12
  61. package/tests/consolidation-snapshot.test.mjs +39 -0
  62. package/tests/curator-absorb.test.mjs +443 -0
  63. package/tests/curator-calibrate.test.mjs +173 -0
  64. package/tests/curator-clusters.test.mjs +281 -0
  65. package/tests/curator-commit.test.mjs +52 -5
  66. package/tests/curator-evidence.test.mjs +102 -0
  67. package/tests/curator-link.test.mjs +316 -0
  68. package/tests/curator-pairing.test.mjs +252 -0
  69. package/tests/curator-probe.test.mjs +15 -6
  70. package/tests/curator-review-mode.test.mjs +314 -0
  71. package/tests/disclosure.test.mjs +2 -1
  72. package/tests/entity-merge.test.mjs +261 -0
  73. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
  74. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
  75. package/tests/fixtures/lexicon-stub.mjs +284 -0
  76. package/tests/fixtures/mock-llm/reply.txt +1 -0
  77. package/tests/freshness.test.mjs +140 -0
  78. package/tests/graph-cascade.test.mjs +35 -2
  79. package/tests/graph.test.mjs +96 -0
  80. package/tests/help-page.test.mjs +415 -0
  81. package/tests/inbound.test.mjs +6 -3
  82. package/tests/inject-guide.test.mjs +28 -0
  83. package/tests/inject.test.mjs +157 -5
  84. package/tests/injection-chain.test.mjs +176 -0
  85. package/tests/lexicon-calibrate.test.mjs +48 -0
  86. package/tests/lexicon-dedupe.test.mjs +171 -0
  87. package/tests/lexicon-frequency.test.mjs +179 -0
  88. package/tests/lexicon-inject.test.mjs +410 -0
  89. package/tests/lexicon-perf.test.mjs +436 -0
  90. package/tests/lexicon-ui.test.mjs +547 -0
  91. package/tests/lexicon.test.mjs +922 -0
  92. package/tests/managed-runtime.test.mjs +32 -0
  93. package/tests/mock-llm.test.mjs +225 -0
  94. package/tests/open-loop-date.test.mjs +406 -0
  95. package/tests/private-links.test.mjs +445 -0
  96. package/tests/prompts.test.mjs +35 -0
  97. package/tests/recall-dedup.test.mjs +33 -4
  98. package/tests/salient-wake.test.mjs +362 -0
  99. package/tests/settings-plumbing.test.mjs +76 -0
  100. package/tests/sidebar.test.mjs +5 -1
  101. package/tests/stubs/dsh-schedule.js +105 -0
  102. package/tests/tool-schema.test.mjs +1 -1
  103. package/tests/tools.test.mjs +112 -3
  104. package/tests/webui-auth.test.mjs +352 -2
  105. package/tests/webui.test.mjs +188 -0
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']
@@ -22,13 +29,42 @@ function allowed(entry, exec) {
22
29
  return !sessionIdOf(exec) || (isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, sessionIdOf(exec)))
23
30
  }
24
31
 
32
+ /**
33
+ * Entity listing with the derived `linked` flag (§6.4 包 D). The visibility rule
34
+ * is unchanged: without a session every entity comes back (GraphPanel calls it
35
+ * exactly that way), with a session only entities reachable from visible memory
36
+ * links are listed. What is new is the classification:
37
+ * * `linked` = referenced by an entry's links[] OR by a relationship snapshot.
38
+ * A snapshot counts — an entity with only a relationship and no memory link
39
+ * is history, not an orphan, and must not be misjudged as one.
40
+ * * With a session, a snapshot only counts when its evidenceIds include a
41
+ * memory visible in this conversation; without a session every snapshot
42
+ * counts (there is nobody to hide it from).
43
+ * `linked` is derived on the fly and never written back to the entities file —
44
+ * the startup prune (pruneOrphanEntitiesAll) stays the sole collector.
45
+ */
25
46
  export function listEntities(args) {
26
47
  const scope = scopeFor(args)
27
48
  const store = readEntities(scope.libraryId)
28
49
  const index = loadPrivateIndex(scope.libraryId)
29
- const visible = new Set(Object.values(index.entries)
30
- .filter(entry => allowed(entry, args.exec)).flatMap(entry => (entry.links || []).map(link => link.to)))
31
- const items = Object.values(store.entities).filter(entity => !sessionIdOf(args.exec) || visible.has(entity.id))
50
+ const sessionId = sessionIdOf(args.exec)
51
+ const linked = new Set()
52
+ for (const entry of Object.values(index.entries)) {
53
+ if (!allowed(entry, args.exec)) continue
54
+ for (const link of entry.links || []) linked.add(link.to)
55
+ }
56
+ for (const rel of Object.values(store.relationships || {})) {
57
+ if (sessionId) {
58
+ const evidenceVisible = (Array.isArray(rel?.evidenceIds) ? rel.evidenceIds : [])
59
+ .some(id => { const entry = index.entries[id]; return Boolean(entry) && allowed(entry, args.exec) })
60
+ if (!evidenceVisible) continue
61
+ }
62
+ if (rel?.fromId) linked.add(rel.fromId)
63
+ if (rel?.toId) linked.add(rel.toId)
64
+ }
65
+ const items = Object.values(store.entities)
66
+ .filter(entity => !sessionId || linked.has(entity.id))
67
+ .map(entity => ({ ...entity, linked: linked.has(entity.id) }))
32
68
  return { items, total: items.length }
33
69
  }
34
70
 
@@ -126,10 +162,15 @@ export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
126
162
  * Remove every entity in one library that no entry links to and no relationship
127
163
  * snapshot references. Idempotent: on healthy data it writes nothing. Returns
128
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.
129
169
  */
130
- export function pruneOrphanEntities(libraryId) {
170
+ export function pruneOrphanEntities(libraryId, keep = []) {
131
171
  const scope = scopeFor({ libraryId })
132
172
  const file = entitiesPath(scope.libraryId)
173
+ const protectedIds = new Set(Array.isArray(keep) ? keep : [])
133
174
  return withFileLock(file, () => {
134
175
  const store = readEntities(scope.libraryId)
135
176
  const ids = Object.keys(store.entities)
@@ -142,7 +183,7 @@ export function pruneOrphanEntities(libraryId) {
142
183
  referenced.add(relationship.fromId)
143
184
  referenced.add(relationship.toId)
144
185
  }
145
- const removed = ids.filter(id => !referenced.has(id))
186
+ const removed = ids.filter(id => !referenced.has(id) && !protectedIds.has(id))
146
187
  // Write only when something actually goes, so the common case never touches
147
188
  // the file (mtime-based caches, backups and concurrent readers all benefit).
148
189
  if (removed.length) {
@@ -225,30 +266,271 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
225
266
  })
226
267
  }
227
268
 
228
- export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7 }) {
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
+
499
+ /**
500
+ * Write one directed link from a memory to a memory or entity.
501
+ *
502
+ * `source` records who made the edge: 'auto' (private auto-association / entity
503
+ * hub, §5.3–5.5) or 'user'. Anything else is omitted rather than stored, so the
504
+ * field never turns into a free-form label and an old link without it keeps
505
+ * reading as a model/user link. Replacement stays idempotent: the same
506
+ * (to, kind) pair is overwritten in place instead of appended.
507
+ */
508
+ export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7, source }) {
229
509
  const scope = scopeFor({ exec, libraryId })
230
510
  if (!LINK_KINDS.includes(kind)) throw new Error(`link kind must be ${LINK_KINDS.join(', ')}`)
231
511
  const reason = String(note || '').trim()
232
512
  if (reason.replace(/\s/g, '').length < 8 || reason.length > 500) throw new Error('link note must contain 8-500 characters explaining the evidence')
233
513
  if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('link confidence must be between 0 and 1')
234
514
  if (fromId === toId) throw new Error('a memory cannot link to itself')
515
+ const linkSource = source === 'auto' || source === 'user' ? source : null
235
516
  const entities = readEntities(scope.libraryId).entities
236
517
  let result
237
518
  updatePrivateIndex(scope.libraryId, index => {
238
- const source = index.entries[fromId]
519
+ const origin = index.entries[fromId]
239
520
  const target = index.entries[toId]
240
- if (!source || !allowed(source, exec) || target && !allowed(target, exec)) throw new Error('unknown or inaccessible memory')
521
+ if (!origin || !allowed(origin, exec) || target && !allowed(target, exec)) throw new Error('unknown or inaccessible memory')
241
522
  if (!target && !entities[toId]) throw new Error('link target must be an existing memory or entity')
242
523
  if (kind === 'person' && entities[toId]?.kind !== 'person') throw new Error('person links must target a person entity')
243
- const links = Array.isArray(source.links) ? source.links : []
524
+ const links = Array.isArray(origin.links) ? origin.links : []
244
525
  result = { to: toId, kind, note: reason, confidence, createdAt: stamp() }
526
+ if (linkSource) result.source = linkSource
245
527
  const found = links.findIndex(link => link.to === toId && link.kind === kind)
246
528
  if (found >= 0) links[found] = result
247
529
  else {
248
530
  if (links.length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
249
531
  links.push(result)
250
532
  }
251
- source.links = links
533
+ origin.links = links
252
534
  })
253
535
  return { from: fromId, ...result }
254
536
  }
@@ -282,7 +564,9 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
282
564
  if (!LINK_KINDS.includes(link.kind)) continue
283
565
  // A deleted target gets a placeholder; an inaccessible target gets no hint.
284
566
  if (index.entries[link.to] && !visible.has(link.to)) continue
285
- const edge = { from, to: link.to, kind: link.kind, note: link.note, confidence: link.confidence ?? 0.7 }
567
+ // source is display metadata only ('auto' edges get a badge in the graph
568
+ // view); an older link without the field reports null instead of undefined.
569
+ const edge = { from, to: link.to, kind: link.kind, note: link.note, confidence: link.confidence ?? 0.7, source: link.source || null }
286
570
  edges.push(edge)
287
571
  for (const [a, b] of [[from, link.to], [link.to, from]]) {
288
572
  if (!adjacency.has(a)) adjacency.set(a, new Set())
package/lib/inbound.js CHANGED
@@ -155,6 +155,25 @@ export function hasPendingInbound(sessionId) {
155
155
  return Boolean(inbound?.pending?.length) && !(Date.parse(inbound.retryAt || '') > Date.now())
156
156
  }
157
157
 
158
+ /**
159
+ * 本轮真实用户消息的纯文本,直接取自持久化的 inbound journal(pending 队列)。
160
+ *
161
+ * 词典命中的唯一文本源(docs/memory-semantics.md §8.13):队列里的每一条都是
162
+ * ingestInboundBatch 校验过的显式人类消息,所以插件通知、工具结果、assistant
163
+ * 自言自语结构上进不来。调用方要在 noteNativeUserMessages 把原生消息从 pending
164
+ * 摘走**之前**取(inject.js 的顺序就是这样的)。
165
+ */
166
+ export function inboundUserTexts(binding) {
167
+ const pending = Array.isArray(binding?.inbound?.pending) ? binding.inbound.pending : []
168
+ return pending
169
+ .map(item => (Array.isArray(item?.content) ? item.content : [])
170
+ .filter(block => block?.type === 'text' && typeof block.text === 'string')
171
+ .map(block => block.text.trim())
172
+ .filter(Boolean)
173
+ .join(' '))
174
+ .filter(Boolean)
175
+ }
176
+
158
177
  export async function pendingInbound(sessionId, ctx, session) {
159
178
  const first = journal(getSessionBinding(sessionId)).pending
160
179
  // Persisted queues can recover media collection after a restart.