dsh-memu-memory 1.2.2 → 1.2.4
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/AGENTS.md +4 -1
- package/README.md +12 -16
- package/README.zh.md +13 -17
- package/docs/client-conventions.md +2 -0
- package/docs/contributing.md +7 -6
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +63 -1
- package/docs/host-api.md +19 -0
- package/docs/memory-semantics.md +10 -1
- package/docs/troubleshooting.md +77 -3
- package/lib/activity-log.js +1 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +223 -19
- package/lib/cycle.js +9 -1
- package/lib/embedding-catalog.js +416 -138
- package/lib/embedding-download.js +36 -11
- package/lib/freshness.js +97 -0
- package/lib/graph.js +244 -2
- package/lib/inject.js +218 -11
- package/lib/local-embedding-manager.js +3 -2
- package/lib/local-embedding-protocol.js +40 -3
- package/lib/local-embedding-worker.js +36 -6
- package/lib/local-vector-service.js +18 -4
- package/lib/memory.js +83 -17
- package/lib/memu.js +15 -7
- package/lib/private.js +25 -5
- package/lib/rpc.js +17 -3
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +173 -1
- package/package.json +3 -2
- package/scripts/drive-session.mjs +864 -0
- package/scripts/mock-llm.mjs +903 -0
- package/scripts/simulate-injection.mjs +298 -0
- package/tests/client-render.test.mjs +69 -2
- package/tests/consolidation-fork.test.mjs +14 -1
- package/tests/drive-session.test.mjs +152 -0
- package/tests/embedding-catalog.test.mjs +116 -8
- package/tests/embedding-download.test.mjs +97 -2
- package/tests/embedding-runtime.test.mjs +21 -13
- package/tests/entity-merge.test.mjs +261 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/help-page.test.mjs +4 -4
- package/tests/injection-chain.test.mjs +176 -0
- package/tests/injection-rollback.test.mjs +230 -0
- package/tests/local-embedding-env.test.mjs +51 -0
- package/tests/local-embedding-manager.test.mjs +18 -0
- package/tests/local-embedding-protocol.test.mjs +28 -2
- package/tests/local-embedding-worker.test.mjs +94 -0
- package/tests/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/simulate-injection.test.mjs +76 -0
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/vector-profile.test.mjs +28 -4
- package/tests/webui-auth.test.mjs +4 -0
|
@@ -4,6 +4,7 @@ import crypto from 'node:crypto'
|
|
|
4
4
|
import {
|
|
5
5
|
getEmbeddingCatalog,
|
|
6
6
|
getEmbeddingModel,
|
|
7
|
+
PROVIDERS,
|
|
7
8
|
readOnnxGraphHeader,
|
|
8
9
|
resolveEmbeddingSources,
|
|
9
10
|
validateEmbeddingManifest,
|
|
@@ -23,7 +24,9 @@ export const DOWNLOAD_STATES = Object.freeze(['unknown', 'absent', 'downloading'
|
|
|
23
24
|
const INSTALL_RECORD = 'installed.json'
|
|
24
25
|
const STAGING_DIR = '.staging'
|
|
25
26
|
const TRASH_DIR = '.trash'
|
|
26
|
-
|
|
27
|
+
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
|
+
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
|
+
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
27
30
|
|
|
28
31
|
function fail(code, message, extra) {
|
|
29
32
|
const error = new Error(message)
|
|
@@ -99,10 +102,13 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
99
102
|
const config = JSON.parse(configBytes.toString('utf8'))
|
|
100
103
|
if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
|
|
101
104
|
checks.push('config.hidden_size=' + config.hidden_size)
|
|
102
|
-
|
|
103
|
-
|
|
105
|
+
// 分窗不能超过制品自己声明的位置上限——超过就是必炸的输入;比它小是刻意的策略
|
|
106
|
+
// (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
|
|
107
|
+
// 而这个选择本来就在 profile 指纹里,可复现。
|
|
108
|
+
if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
|
|
109
|
+
throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
|
|
104
110
|
}
|
|
105
|
-
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings)
|
|
111
|
+
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
|
|
106
112
|
|
|
107
113
|
const vocabBytes = bytesOf('vocab')
|
|
108
114
|
if (vocabBytes && Number.isInteger(config.vocab_size)) {
|
|
@@ -123,6 +129,10 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
123
129
|
if (poolingBytes) {
|
|
124
130
|
const pooling = JSON.parse(poolingBytes.toString('utf8'))
|
|
125
131
|
if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
|
|
132
|
+
if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
|
|
133
|
+
// 因果 LM 的卡片最容易踩的坑:目录写着 last、制品其实是 mean。lasttoken 是基座自己
|
|
134
|
+
// 声明的字段,能对得上才继续。
|
|
135
|
+
if (entry.pooling === 'last' && pooling.pooling_mode_lasttoken !== true) throw new Error('pooling config is not last-token pooling')
|
|
126
136
|
if (Number.isInteger(pooling.word_embedding_dimension) && pooling.word_embedding_dimension !== entry.dimension) {
|
|
127
137
|
throw new Error(`pooling word_embedding_dimension ${pooling.word_embedding_dimension} does not match dimension ${entry.dimension}`)
|
|
128
138
|
}
|
|
@@ -149,7 +159,12 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
149
159
|
const actualOutput = header.outputs[0]
|
|
150
160
|
if (!actualOutput) throw new Error('graph has no outputs')
|
|
151
161
|
if (declaredOutput && actualOutput.name !== declaredOutput.name) throw new Error(`graph output ${actualOutput.name} does not match manifest ${declaredOutput.name}`)
|
|
152
|
-
|
|
162
|
+
// float32 与 float16 都能被 worker 池化(fp16 走 Number() 取值),但别的 dtype
|
|
163
|
+
// (int8 输出、string)不是 embedding worker 该假装能吃的东西。声明与实际必须一致。
|
|
164
|
+
if (!['float32', 'float16'].includes(actualOutput.dtype)) throw new Error(`graph output dtype ${actualOutput.dtype} is not float32/float16`)
|
|
165
|
+
if (declaredOutput && declaredOutput.dtype && actualOutput.dtype !== declaredOutput.dtype) {
|
|
166
|
+
throw new Error(`graph output dtype ${actualOutput.dtype} does not match manifest ${declaredOutput.dtype}`)
|
|
167
|
+
}
|
|
153
168
|
const lastDim = Array.isArray(actualOutput.shape) ? actualOutput.shape[actualOutput.shape.length - 1] : null
|
|
154
169
|
if (lastDim !== entry.dimension) throw new Error(`graph output last dim ${lastDim} does not match dimension ${entry.dimension}`)
|
|
155
170
|
checks.push('graph.output=' + actualOutput.name + ':' + actualOutput.dtype + '[' + lastDim + ']')
|
|
@@ -271,9 +286,12 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
271
286
|
}
|
|
272
287
|
|
|
273
288
|
async function download(id, downloadOptions = {}) {
|
|
274
|
-
const { confirmed = false, signal } = downloadOptions || {}
|
|
289
|
+
const { confirmed = false, signal, provider = null } = downloadOptions || {}
|
|
275
290
|
const entry = lookup(typeof id === 'string' ? id : String(id || ''))
|
|
276
291
|
if (!entry) throw fail('EMBEDDING_MODEL_UNKNOWN', `unknown embedding model: ${id}`)
|
|
292
|
+
if (provider !== null && !PROVIDERS[provider]) {
|
|
293
|
+
throw fail('EMBEDDING_PROVIDER_UNKNOWN', `unknown download provider: ${String(provider)}`)
|
|
294
|
+
}
|
|
277
295
|
const report = validateEmbeddingManifest(entry)
|
|
278
296
|
if (!report.ok) {
|
|
279
297
|
throw fail('EMBEDDING_MANIFEST_INVALID', `${entry.id} manifest is not installable: ${report.errors.map(item => item.code).join(', ')}`, { errors: report.errors })
|
|
@@ -286,9 +304,13 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
286
304
|
}
|
|
287
305
|
if (jobs.has(entry.id)) throw fail('EMBEDDING_DOWNLOAD_BUSY', `${entry.id} is already downloading`)
|
|
288
306
|
if (signal?.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted before it started`)
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
307
|
+
// 默认取目录顺序里第一个已固定的来源(Qwen3 卡片因此默认 hf-mirror);显式传
|
|
308
|
+
// provider 时只解析那一个,解析不出可用来源就如实报错,绝不回退到别的源去下载。
|
|
309
|
+
const resolved = provider ? resolveEmbeddingSources(entry, { providers: [provider] }) : resolveEmbeddingSources(entry)
|
|
310
|
+
const source = provider ? resolved.sources.find(item => item.provider === provider) || null : resolved.primary
|
|
311
|
+
if (!source) {
|
|
312
|
+
throw fail('EMBEDDING_SOURCE_UNAVAILABLE', `no source with a pinned revision is available for ${entry.id}${provider ? ' on ' + provider : ''}`, { skipped: resolved.skipped })
|
|
313
|
+
}
|
|
292
314
|
|
|
293
315
|
const controller = new AbortController()
|
|
294
316
|
const onAbort = () => controller.abort()
|
|
@@ -328,8 +350,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
328
350
|
if (!response || !response.ok) {
|
|
329
351
|
throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
|
|
330
352
|
}
|
|
331
|
-
|
|
332
|
-
|
|
353
|
+
// 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
|
|
354
|
+
// 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
|
|
355
|
+
const declaredHeader = response.headers?.get?.('content-length')
|
|
356
|
+
const declaredLength = Number(declaredHeader)
|
|
357
|
+
if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== file.bytes) {
|
|
333
358
|
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the pinned ${file.bytes} bytes`)
|
|
334
359
|
}
|
|
335
360
|
const hash = crypto.createHash('sha256')
|
package/lib/freshness.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Freshness signals for a recalled memory (work order D).
|
|
2
|
+
//
|
|
3
|
+
// The hint that buildRecall appends is only as good as this classification, so the
|
|
4
|
+
// rules stay small and local:
|
|
5
|
+
// 1. a one-off salient date (YYYY-MM-DD) has already passed;
|
|
6
|
+
// 2. the title or body names something time-sensitive (最新 / 价格 / ...);
|
|
7
|
+
// 3. the entry itself is old enough (`updatedAt || createdAt` >= freshnessDays),
|
|
8
|
+
// except project facts, whose staleness is better judged against the code.
|
|
9
|
+
//
|
|
10
|
+
// An annual MM-DD date is a birthday, not an expiry: it never goes stale by itself.
|
|
11
|
+
// The word list is fixed on purpose — exposing it as a setting would create a second
|
|
12
|
+
// vocabulary system, and this is a nudge, not a filter.
|
|
13
|
+
|
|
14
|
+
const DAY_MS = 86_400_000
|
|
15
|
+
const DEFAULT_FRESHNESS_DAYS = 30
|
|
16
|
+
// Fixed first-version vocabulary (plan D.2). Keep it separate from the lexicon.
|
|
17
|
+
const FRESHNESS_TERMS = ['最新', '最近', '现在', '目前', '今年', '版本', '价格', '天气', '新闻', '比分', '汇率']
|
|
18
|
+
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
19
|
+
|
|
20
|
+
// `now` accepts a Date, epoch milliseconds or a parsable stamp. Anything invalid
|
|
21
|
+
// falls back to the wall clock so a caller mistake cannot crash a recall.
|
|
22
|
+
function baseTime(now) {
|
|
23
|
+
let date
|
|
24
|
+
if (now instanceof Date) date = now
|
|
25
|
+
else if (typeof now === 'number') date = new Date(now)
|
|
26
|
+
else date = new Date(now ?? Date.now())
|
|
27
|
+
const time = date instanceof Date ? date.getTime() : NaN
|
|
28
|
+
return Number.isFinite(time) ? time : Date.now()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Strict `YYYY-MM-DD` in local time. Returns null for MM-DD (annual), malformed
|
|
32
|
+
// strings and impossible dates such as 2026-02-30; those must never read as expired.
|
|
33
|
+
function datedValue(value) {
|
|
34
|
+
const text = String(value ?? '').trim()
|
|
35
|
+
const match = DATE_RE.exec(text)
|
|
36
|
+
if (!match) return null
|
|
37
|
+
const year = Number(match[1])
|
|
38
|
+
const month = Number(match[2])
|
|
39
|
+
const day = Number(match[3])
|
|
40
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) return null
|
|
41
|
+
const date = new Date(0)
|
|
42
|
+
date.setFullYear(year, month - 1, day)
|
|
43
|
+
date.setHours(0, 0, 0, 0)
|
|
44
|
+
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null
|
|
45
|
+
return { text: `${match[1]}-${match[2]}-${match[3]}`, time: date.getTime() }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function timestampMs(value) {
|
|
49
|
+
if (value === undefined || value === null || value === '') return null
|
|
50
|
+
const at = typeof value === 'number' ? value : Date.parse(String(value))
|
|
51
|
+
return Number.isFinite(at) ? at : null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function thresholdDays(value) {
|
|
55
|
+
const days = Number(value)
|
|
56
|
+
return Number.isFinite(days) && days >= 0 ? days : DEFAULT_FRESHNESS_DAYS
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Classify one recalled entry.
|
|
61
|
+
*
|
|
62
|
+
* @param {object} entry memory entry; `title`/`content` are scanned for terms.
|
|
63
|
+
* @param {{now?: Date|number, freshnessDays?: number}} [options]
|
|
64
|
+
* @returns {{stale: boolean, reasons: string[]}}
|
|
65
|
+
*/
|
|
66
|
+
export function freshnessSignals(entry, { now = Date.now(), freshnessDays = DEFAULT_FRESHNESS_DAYS } = {}) {
|
|
67
|
+
const reasons = []
|
|
68
|
+
if (!entry || typeof entry !== 'object') return { stale: false, reasons }
|
|
69
|
+
const nowMs = baseTime(now)
|
|
70
|
+
const todayStart = new Date(nowMs)
|
|
71
|
+
todayStart.setHours(0, 0, 0, 0)
|
|
72
|
+
const todayMs = todayStart.getTime()
|
|
73
|
+
|
|
74
|
+
// (a) A one-off date strictly before local today. Today itself still counts as
|
|
75
|
+
// current; only tomorrow and later are future.
|
|
76
|
+
const dated = datedValue(entry.salientDate)
|
|
77
|
+
if (dated && dated.time < todayMs) reasons.push(`dated-past:${dated.text}`)
|
|
78
|
+
|
|
79
|
+
// (b) Time-sensitive wording in the title or body. Every matched term is kept so
|
|
80
|
+
// the reason list is auditable instead of a single opaque boolean.
|
|
81
|
+
const text = `${entry.title ?? ''}\n${entry.content ?? ''}`
|
|
82
|
+
for (const term of FRESHNESS_TERMS) if (text.includes(term)) reasons.push(`freshness-term:${term}`)
|
|
83
|
+
|
|
84
|
+
// (c) Age since the last edit. `updatedAt` wins over `createdAt`; missing or
|
|
85
|
+
// invalid stamps contribute nothing, and future stamps are not "old". Project
|
|
86
|
+
// facts are excluded on purpose — most coding memories would otherwise always
|
|
87
|
+
// trip this leg.
|
|
88
|
+
if (entry.owner !== 'about_project') {
|
|
89
|
+
const at = timestampMs(entry.updatedAt || entry.createdAt)
|
|
90
|
+
if (at !== null) {
|
|
91
|
+
const age = (nowMs - at) / DAY_MS
|
|
92
|
+
if (Number.isFinite(age) && age >= thresholdDays(freshnessDays)) reasons.push(`age-days:${Math.floor(age)}`)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { stale: reasons.length > 0, reasons }
|
|
97
|
+
}
|
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
|
*
|