dsh-memu-memory 1.3.0 → 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.
- package/CHANGELOG.md +50 -0
- package/README.md +3 -3
- package/README.zh.md +3 -1
- package/docs/contributing.md +2 -2
- package/docs/env-and-commands.md +12 -1
- package/docs/memory-semantics.md +8 -2
- package/docs/troubleshooting.md +9 -6
- package/lib/auto-link/apply.js +249 -0
- package/lib/auto-link/candidates.js +155 -0
- package/lib/auto-link/decide.js +304 -0
- package/lib/auto-link/normalize.js +99 -0
- package/lib/auto-link/policy.js +42 -0
- package/lib/auto-link/suppression.js +101 -0
- package/lib/auto-link/terminology.js +265 -0
- package/lib/binding-diagnostics.js +3 -3
- package/lib/client.js +1435 -70
- package/lib/consolidation-receipt.js +81 -5
- package/lib/consolidation-worker.js +57 -25
- package/lib/curator.js +91 -11
- package/lib/engine.js +13 -3
- package/lib/graph.js +326 -39
- package/lib/inject.js +35 -15
- package/lib/media.js +8 -1
- package/lib/memory.js +27 -1
- package/lib/memu.js +26 -12
- package/lib/private-links.js +105 -137
- package/lib/private.js +280 -53
- package/lib/prompts/global-curator.md +6 -3
- package/lib/prompts/system-guide.md +4 -5
- package/lib/prompts.js +27 -1
- package/lib/rpc.js +69 -9
- package/lib/state.js +23 -4
- package/lib/tools.js +199 -67
- package/lib/webui/graph-LICENSE.txt +1 -62
- package/lib/webui/graph-view.bundle.js +1 -1
- package/lib/webui/graph-view.js +891 -124
- package/lib/webui/standalone.js +3 -3
- package/package.json +1 -2
- package/scripts/build-graph.mjs +3 -3
- package/scripts/check-graph-browser.mjs +106 -23
- package/scripts/rebuild-auto-links.mjs +252 -0
- package/tests/audit-regression.test.mjs +11 -8
- package/tests/auto-link-candidates.test.mjs +161 -0
- package/tests/auto-link-decide.test.mjs +512 -0
- package/tests/auto-link-migration.test.mjs +133 -0
- package/tests/client-render.test.mjs +7 -6
- package/tests/consolidation-credential.test.mjs +2 -2
- package/tests/consolidation-fork.test.mjs +188 -9
- package/tests/consolidation-ledger.test.mjs +31 -0
- package/tests/consolidation-snapshot.test.mjs +9 -8
- package/tests/curator-probe.test.mjs +32 -2
- package/tests/cycle.test.mjs +1 -1
- package/tests/graph-view.test.mjs +163 -21
- package/tests/graph.test.mjs +26 -0
- package/tests/help-page.test.mjs +3 -3
- package/tests/inject-conflict.test.mjs +1 -1
- package/tests/inject.test.mjs +1 -1
- package/tests/injection-chain.test.mjs +2 -2
- package/tests/injection-rollback.test.mjs +1 -1
- package/tests/memory-chain.test.mjs +28 -0
- package/tests/memu-resident-route.test.mjs +130 -0
- package/tests/mock-llm.test.mjs +1 -1
- package/tests/private-links.test.mjs +81 -45
- package/tests/prompts.test.mjs +1 -1
- package/tests/stubs/child-process-spy.mjs +14 -0
- package/tests/tool-schema.test.mjs +2 -1
- package/tests/tools.test.mjs +49 -21
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
|
|
|
@@ -2598,7 +2604,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
2598
2604
|
return scored
|
|
2599
2605
|
}
|
|
2600
2606
|
|
|
2601
|
-
|
|
2607
|
+
async function privateListRaw({ exec, libraryId, preferIndex = false }) {
|
|
2602
2608
|
const scope = resolveLibrary({ exec, libraryId, readOnly: true })
|
|
2603
2609
|
if (scope.binding) assertScopeEnabled(scope.binding)
|
|
2604
2610
|
const index = loadPrivateIndex(scope.libraryId)
|
|
@@ -2681,6 +2687,21 @@ export async function privateList({ exec, libraryId, preferIndex = false }) {
|
|
|
2681
2687
|
}
|
|
2682
2688
|
}
|
|
2683
2689
|
|
|
2690
|
+
/** 分页只切返回值;不传 limit 保持全量(现有 UI/RPC 调用方行为不变)。 */
|
|
2691
|
+
export async function privateList({ exec, libraryId, preferIndex = false, limit = null, offset = 0 }) {
|
|
2692
|
+
const result = await privateListRaw({ exec, libraryId, preferIndex })
|
|
2693
|
+
const files = Array.isArray(result.files) ? result.files : []
|
|
2694
|
+
const total = files.length
|
|
2695
|
+
const start = Math.max(0, Math.floor(Number(offset) || 0))
|
|
2696
|
+
const size = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.floor(Number(limit)) : null
|
|
2697
|
+
return {
|
|
2698
|
+
...result,
|
|
2699
|
+
total,
|
|
2700
|
+
offset: start,
|
|
2701
|
+
files: size ? files.slice(start, start + size) : files,
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2684
2705
|
// Everything a memory *is* stays editable, not only its words: `track`, `peak`, the
|
|
2685
2706
|
// mood lens and the attachment list all change how an entry is scored, aggregated or
|
|
2686
2707
|
// rendered, so a wrong value in any of them was a permanent mis-filing that could
|
|
@@ -3136,6 +3157,11 @@ async function resolveMemoryReviewImpl({ libraryId = null, id, action, resolutio
|
|
|
3136
3157
|
}
|
|
3137
3158
|
await retryStoreWrite(() => libraryId ? updatePrivateIndex(libraryId, mutate) : updateGlobalIndex(mutate))
|
|
3138
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
|
+
}
|
|
3139
3165
|
return { id, status: next.status, resolution }
|
|
3140
3166
|
}
|
|
3141
3167
|
|
package/lib/memu.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
3
4
|
import { spawn } from 'node:child_process'
|
|
4
5
|
import { dataDir, ensureDir, redactSecrets, warn, windowsSystemEnv } from './paths.js'
|
|
5
6
|
import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
|
|
@@ -8,6 +9,9 @@ import { activeProfile, captureVectorGeneration, assertVectorGeneration, assertP
|
|
|
8
9
|
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
9
10
|
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
10
11
|
|
|
12
|
+
// 单次命令捕获上限:工具输出异常放大时不能把整个进程内存吃光;超限只标 truncated。
|
|
13
|
+
const MAX_CAPTURE_CHARS = 8 * 1024 * 1024
|
|
14
|
+
|
|
11
15
|
// MemU's own storage mode. 'local' keeps every row in this plugin's sqlite files;
|
|
12
16
|
// 'cloud' hands storage to MemU's backend and needs the vendor credentials in
|
|
13
17
|
// ~/.memu/config.env. Read per call, never cached, so toggling it takes effect on
|
|
@@ -51,13 +55,21 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
|
|
|
51
55
|
})
|
|
52
56
|
let stdout = ''
|
|
53
57
|
let stderr = ''
|
|
58
|
+
let truncated = false
|
|
54
59
|
let timedOut = false
|
|
55
60
|
const timer = setTimeout(() => {
|
|
56
61
|
timedOut = true
|
|
57
62
|
try { child.kill() } catch {}
|
|
58
63
|
}, timeoutMs)
|
|
59
|
-
child.stdout?.on('data', (d) => {
|
|
60
|
-
|
|
64
|
+
child.stdout?.on('data', (d) => {
|
|
65
|
+
const text = d.toString()
|
|
66
|
+
if (stdout.length + text.length > MAX_CAPTURE_CHARS) { truncated = true; return }
|
|
67
|
+
stdout += text
|
|
68
|
+
})
|
|
69
|
+
child.stderr?.on('data', (d) => {
|
|
70
|
+
if (stderr.length >= 64 * 1024) return
|
|
71
|
+
stderr += d.toString()
|
|
72
|
+
})
|
|
61
73
|
child.on('error', (error) => {
|
|
62
74
|
clearTimeout(timer)
|
|
63
75
|
reject(new MemuError(`failed to start memu: ${error.message}`, 'MEMU_SPAWN_FAILED', { error }))
|
|
@@ -65,7 +77,7 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
|
|
|
65
77
|
child.on('close', (code) => {
|
|
66
78
|
clearTimeout(timer)
|
|
67
79
|
if (code === 0) {
|
|
68
|
-
resolve({ stdout, stderr, code })
|
|
80
|
+
resolve({ stdout, stderr, code, truncated })
|
|
69
81
|
return
|
|
70
82
|
}
|
|
71
83
|
const secrets = Object.entries({ ...process.env, ...(env || {}) }).filter(([key]) => /(?:API_KEY|TOKEN|SECRET)$/.test(key)).map(([, value]) => value)
|
|
@@ -345,7 +357,7 @@ async function runResident(args, { env, timeoutMs = 90_000 } = {}) {
|
|
|
345
357
|
const failure = new MemuError(
|
|
346
358
|
`memu ${label} failed (timeout): the resident engine did not answer in ${Math.round(timeoutMs / 1000)}s`,
|
|
347
359
|
'MEMU_COMMAND_FAILED',
|
|
348
|
-
{ code: null, stdout: '', stderr: '', timedOut: true },
|
|
360
|
+
{ code: null, stdout: '', stderr: '', timedOut: true, killed: true },
|
|
349
361
|
)
|
|
350
362
|
reject(failure)
|
|
351
363
|
// A Python command cannot be cancelled from the outside, so a stuck command
|
|
@@ -404,12 +416,13 @@ async function runConfigured(args, options = {}) {
|
|
|
404
416
|
const env = await envFor({ ...options, route })
|
|
405
417
|
if (generation) assertVectorGeneration(generation)
|
|
406
418
|
if (migration) assertMigrationProfile(migration)
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
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 })
|
|
413
426
|
if (generation) assertVectorGeneration(generation)
|
|
414
427
|
if (migration) assertMigrationProfile(migration)
|
|
415
428
|
return result
|
|
@@ -494,9 +507,10 @@ export async function listFiles({ db, provider, embedModel, baseUrl, apiKey, vec
|
|
|
494
507
|
|
|
495
508
|
export async function commit({ payload, db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs = 180_000 }) {
|
|
496
509
|
const tmpDir = ensureDir(path.join(dataDir(), 'tmp'))
|
|
497
|
-
|
|
510
|
+
// 临时文件名不可预测(旧版 pid+Date.now 可被并行进程猜到),并收紧权限。
|
|
511
|
+
const file = path.join(tmpDir, `commit-${crypto.randomUUID()}.json`)
|
|
498
512
|
try {
|
|
499
|
-
fs.writeFileSync(file, JSON.stringify(payload,
|
|
513
|
+
fs.writeFileSync(file, JSON.stringify(payload), { encoding: 'utf8', mode: 0o600 })
|
|
500
514
|
const res = await runConfigured(['commit', file, '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs, role: 'document' })
|
|
501
515
|
const data = parseJson(res.stdout)
|
|
502
516
|
if (data === null) {
|
package/lib/private-links.js
CHANGED
|
@@ -1,35 +1,18 @@
|
|
|
1
|
-
// Private auto-association
|
|
1
|
+
// Private auto-association, split into a legacy candidate pass and the
|
|
2
|
+
// deterministic write layer (DESIGN v3).
|
|
2
3
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
4
|
+
// * suggestPrivateLinks — PURE legacy candidate suggestion. It still finds
|
|
5
|
+
// statistically name-like pairs, but its output is only a review hint. It
|
|
6
|
+
// never decides that an edge exists.
|
|
7
|
+
// * autoLinkPrivateMemories — MODE GATED. In the default 'suggest' mode it
|
|
8
|
+
// returns candidates and writes nothing. In 'deterministic' mode it refreshes
|
|
9
|
+
// the edges that lib/auto-link/ decided: memory→confirmed-entity mentions and
|
|
10
|
+
// explicit field evidence. Lexical similarity, shared tokens and vectors are
|
|
11
|
+
// never written as edges.
|
|
5
12
|
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
// relation links and entity hubs. Uncertain pairs are returned as candidates
|
|
10
|
-
// for the current consolidation worker to adjudicate (it already has the
|
|
11
|
-
// transcript in hand; starting another consolidation would re-read everything).
|
|
12
|
-
//
|
|
13
|
-
// The high-precision signals:
|
|
14
|
-
// * both entries are eligible (active, not expired, not automatic-secret),
|
|
15
|
-
// visible to the conversation, share the same fact context and the same track;
|
|
16
|
-
// * their titles share a RARE token (df <= max(2, ceil(0.15·N))): a Latin token
|
|
17
|
-
// of >= 3 chars, or a CJK bigram. These are the "name-like" tokens;
|
|
18
|
-
// * pairScore < 0.82 — at/above that band it is a duplicate/merge problem, not
|
|
19
|
-
// a link; findConflict must find no contradiction; an existing relation/person
|
|
20
|
-
// link in either direction means it is already handled (idempotent);
|
|
21
|
-
// * a name-like shared token whose entity kind is resolved (person cue, or a
|
|
22
|
-
// Latin token with no cue → thing) becomes a hub: >= 2 memories sharing the
|
|
23
|
-
// stable name are linked to one entity, and the memory pair is auto-linked.
|
|
24
|
-
// A CJK token with no person cue has an uncertain kind (null) and a token
|
|
25
|
-
// that contradicts an existing entity kind is a mismatch: neither creates a
|
|
26
|
-
// hub or a memory link; the pair becomes one uncertain candidate with a
|
|
27
|
-
// suggestedEntity for this consolidation's worker.
|
|
28
|
-
//
|
|
29
|
-
// Non-name-like shared tokens never auto-link. They surface as uncertain
|
|
30
|
-
// candidates only when 0.55 <= pairScore < 0.82. A pair appears in exactly one
|
|
31
|
-
// output: auto-linked pairs are never duplicated into candidates, and uncertain
|
|
32
|
-
// pairs are never auto-linked.
|
|
13
|
+
// The write layer is incremental: the consolidation hands over the ids it just
|
|
14
|
+
// created/updated, and only those rows are recomputed (O(Δ)). Rebuilding the
|
|
15
|
+
// whole library is the migration script's job.
|
|
33
16
|
//
|
|
34
17
|
// Links are metadata only: they never touch the vector store, never delete
|
|
35
18
|
// memory, and can be removed from the relationship graph. A failed association
|
|
@@ -37,11 +20,14 @@
|
|
|
37
20
|
// caught and only a warning is logged; the top-level index load is caught too.
|
|
38
21
|
|
|
39
22
|
import { sameFactContext } from './context.js'
|
|
40
|
-
import {
|
|
23
|
+
import { listEntities } from './graph.js'
|
|
41
24
|
import { findConflict, isMemoryEligible, visibleToSession } from './memory.js'
|
|
42
25
|
import { pairFeatures, pairScore, tokenize } from './text-retrieval.js'
|
|
43
|
-
import { loadPrivateIndex } from './state.js'
|
|
26
|
+
import { getSettings, loadPrivateIndex } from './state.js'
|
|
44
27
|
import { record } from './activity-log.js'
|
|
28
|
+
import { applyAutoEdges, refreshMemoryAutoLinks } from './auto-link/apply.js'
|
|
29
|
+
import { decideAutoLinks } from './auto-link/decide.js'
|
|
30
|
+
import { suppressionSet } from './auto-link/suppression.js'
|
|
45
31
|
|
|
46
32
|
const DEFAULT_PER_ENTRY = 2
|
|
47
33
|
const DEFAULT_TOTAL = 5
|
|
@@ -51,7 +37,6 @@ const SCORE_CANDIDATE_MIN = 0.55
|
|
|
51
37
|
const SCORE_DUPLICATE = 0.82
|
|
52
38
|
const DF_RATIO = 0.15
|
|
53
39
|
const LATIN_NAME_MIN_LENGTH = 3
|
|
54
|
-
const ENTITY_CONFIDENCE = 0.65
|
|
55
40
|
// findConflict compares the same five identity keys; grouping hubs by the same
|
|
56
41
|
// key keeps "not across context" true for the entity side too.
|
|
57
42
|
const FACT_KEYS = ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId']
|
|
@@ -426,28 +411,21 @@ export function suggestPrivateLinks({
|
|
|
426
411
|
}
|
|
427
412
|
}
|
|
428
413
|
|
|
429
|
-
function autoLinkNote(link) {
|
|
430
|
-
return `自动关联:两条记忆共享稳定称谓「${link.token}」;内容相似度 ${link.score.toFixed(2)}。算法自动建立,可在关系图移除。`
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
function hubNote(hub) {
|
|
434
|
-
return `自动实体枢纽:多条记忆共享稳定称谓「${hub.token}」。`
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
function execFor(sessionId) {
|
|
438
|
-
return sessionId ? { agent: { session: { header: { id: sessionId } } } } : undefined
|
|
439
|
-
}
|
|
440
|
-
|
|
441
414
|
/**
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
415
|
+
* Mode-gated entry point used by the consolidation settle path and the worker
|
|
416
|
+
* tool. `ids` are the entries created/updated by the finished consolidation.
|
|
417
|
+
*
|
|
418
|
+
* * 'suggest' (default): compute the legacy review candidates, write nothing.
|
|
419
|
+
* * 'deterministic': additionally refresh this layer's edges in lib/auto-link/
|
|
420
|
+
* for those ids — mention edges to confirmed entities and explicit field
|
|
421
|
+
* evidence. Legacy statistical pairs remain candidates only.
|
|
422
|
+
* * 'off': no candidates, no writes.
|
|
445
423
|
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
424
|
+
* A consolidation must never fail because of this module: the index load, the
|
|
425
|
+
* suggestion pass and the deterministic write are each caught and logged at warn
|
|
426
|
+
* level. Return counts: `linked` = memory↔memory evidence edges written,
|
|
427
|
+
* `entities` = memory→confirmed-entity edges written, `suggested` = candidate
|
|
428
|
+
* count handed to the worker.
|
|
451
429
|
*/
|
|
452
430
|
export async function autoLinkPrivateMemories({
|
|
453
431
|
libraryId,
|
|
@@ -460,6 +438,10 @@ export async function autoLinkPrivateMemories({
|
|
|
460
438
|
} = {}) {
|
|
461
439
|
const result = { linked: 0, entities: 0, suggested: 0, candidates: [], autoLinked: [] }
|
|
462
440
|
if (!libraryId) return result
|
|
441
|
+
// S0 止血:默认的 'suggest' 只出候选、不写边;'off' 连候选都不算。
|
|
442
|
+
// 误连的代价远高于漏连,迁移期间先停写,再按 DESIGN 的确定性判定层重建。
|
|
443
|
+
const mode = getSettings().autoLinkMode
|
|
444
|
+
if (mode === 'off') return result
|
|
463
445
|
const idList = (Array.isArray(ids) ? ids : []).map(id => String(id)).filter(Boolean)
|
|
464
446
|
if (!idList.length) return result
|
|
465
447
|
|
|
@@ -494,94 +476,80 @@ export async function autoLinkPrivateMemories({
|
|
|
494
476
|
}
|
|
495
477
|
result.suggested = suggestion.candidates.length
|
|
496
478
|
result.candidates = suggestion.candidates
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
note: autoLinkNote(link),
|
|
508
|
-
confidence: link.confidence,
|
|
509
|
-
source: 'auto',
|
|
510
|
-
})
|
|
511
|
-
result.linked += 1
|
|
512
|
-
result.autoLinked.push({ from: link.from, to: link.to, kind: 'relation' })
|
|
513
|
-
record({
|
|
514
|
-
kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
|
|
515
|
-
message: `自动关联 ${link.from} → ${link.to}(「${link.token}」)`,
|
|
516
|
-
detail: {
|
|
517
|
-
op: 'auto-link', from: link.from, to: link.to, kind: 'relation',
|
|
518
|
-
score: link.score, token: link.token, confidence: link.confidence, source: 'auto',
|
|
519
|
-
},
|
|
520
|
-
refs: [link.from, link.to],
|
|
521
|
-
})
|
|
522
|
-
} catch (error) {
|
|
523
|
-
record({
|
|
524
|
-
kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
|
|
525
|
-
message: `自动关联跳过 ${link.from} → ${link.to}:${String(error?.message || error)}`,
|
|
526
|
-
detail: { op: 'auto-link', from: link.from, to: link.to, error: String(error?.message || error) },
|
|
527
|
-
refs: [link.from, link.to],
|
|
528
|
-
})
|
|
529
|
-
}
|
|
479
|
+
// Only deterministic mode writes edges. suggest/off stop here with the candidates.
|
|
480
|
+
if (mode !== 'deterministic') return result
|
|
481
|
+
|
|
482
|
+
// Deterministic pass: only confirmed-entity mentions and explicit field
|
|
483
|
+
// evidence are written; the legacy statistical pairs stay candidates.
|
|
484
|
+
const refreshed = await refreshPrivateAutoLinks({ libraryId, sessionId, ids: idList, entities: entityList })
|
|
485
|
+
if (refreshed.applied) {
|
|
486
|
+
result.linked = refreshed.applied.memory
|
|
487
|
+
result.entities = refreshed.applied.entity
|
|
488
|
+
result.autoLinked = refreshed.applied.applied.map(({ from, to, kind }) => ({ from, to, kind }))
|
|
530
489
|
}
|
|
490
|
+
return result
|
|
491
|
+
}
|
|
531
492
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
493
|
+
/**
|
|
494
|
+
* Deterministic-only incremental refresh, shared by every write path that can
|
|
495
|
+
* change what the edges should be: consolidation settle, the worker tool, a
|
|
496
|
+
* private write carrying conflicts_with / supersedes / a fact_key pair, and a
|
|
497
|
+
* review accept that turns a claim into a supersede. Returns `{ skipped, applied }`
|
|
498
|
+
* and never throws — a failure is logged and the caller's write stays valid.
|
|
499
|
+
*/
|
|
500
|
+
export async function refreshPrivateAutoLinks({ libraryId, sessionId = null, ids, entities = null, full = false } = {}) {
|
|
501
|
+
const mode = getSettings().autoLinkMode
|
|
502
|
+
if (mode !== 'deterministic') return { skipped: mode || 'suggest', applied: null }
|
|
503
|
+
const idList = [...new Set((Array.isArray(ids) ? ids : []).map(id => String(id ?? '').trim()).filter(Boolean))]
|
|
504
|
+
if (!libraryId || (!full && !idList.length)) return { skipped: 'no-ids', applied: null }
|
|
505
|
+
let entityList
|
|
506
|
+
try {
|
|
507
|
+
entityList = Array.isArray(entities) ? entities : listEntities({ libraryId }).items
|
|
508
|
+
} catch (error) {
|
|
509
|
+
record({
|
|
510
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
|
|
511
|
+
message: `私有自动关联跳过:实体表不可读(${String(error?.message || error)})`,
|
|
512
|
+
detail: { op: 'auto-link', phase: 'entities', error: String(error?.message || error) },
|
|
513
|
+
refs: [],
|
|
514
|
+
})
|
|
515
|
+
return { skipped: 'entities', applied: null }
|
|
516
|
+
}
|
|
517
|
+
let suppression
|
|
518
|
+
try {
|
|
519
|
+
suppression = suppressionSet(libraryId)
|
|
520
|
+
} catch (error) {
|
|
521
|
+
record({
|
|
522
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
|
|
523
|
+
message: `私有自动关联跳过:抑制表不可读(${String(error?.message || error)})`,
|
|
524
|
+
detail: { op: 'auto-link', phase: 'suppression', error: String(error?.message || error) },
|
|
525
|
+
refs: [],
|
|
526
|
+
})
|
|
527
|
+
return { skipped: 'suppression', applied: null }
|
|
528
|
+
}
|
|
529
|
+
try {
|
|
530
|
+
// `full` recomputes the whole library in one transaction. It is the catch-up
|
|
531
|
+
// path for entities confirmed while the mode was off: their status is already
|
|
532
|
+
// confirmed, so a later per-id refresh has nothing to trigger.
|
|
533
|
+
if (full) {
|
|
534
|
+
const edges = decideAutoLinks({ index: loadPrivateIndex(libraryId), entities: entityList, suppression })
|
|
535
|
+
const applied = applyAutoEdges({
|
|
536
|
+
libraryId, edges, entities: entityList, sessionId, operation: 'auto-link-rebuild',
|
|
544
537
|
})
|
|
545
|
-
|
|
546
|
-
}
|
|
547
|
-
for (const memoryId of hub.memoryIds) {
|
|
548
|
-
try {
|
|
549
|
-
const fresh = loadPrivateIndex(libraryId).entries[memoryId]
|
|
550
|
-
if (!fresh) throw new Error('memory is gone')
|
|
551
|
-
if ((fresh.links || []).some(link => link?.to === entity.id)) continue
|
|
552
|
-
linkEntries({
|
|
553
|
-
exec,
|
|
554
|
-
libraryId,
|
|
555
|
-
fromId: memoryId,
|
|
556
|
-
toId: entity.id,
|
|
557
|
-
kind: hub.kind === 'person' ? 'person' : 'relation',
|
|
558
|
-
note: hubNote(hub),
|
|
559
|
-
confidence: ENTITY_CONFIDENCE,
|
|
560
|
-
source: 'auto',
|
|
561
|
-
})
|
|
562
|
-
result.entities += 1
|
|
563
|
-
result.autoLinked.push({ from: memoryId, to: entity.id, kind: hub.kind === 'person' ? 'person' : 'relation' })
|
|
564
|
-
record({
|
|
565
|
-
kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
|
|
566
|
-
message: `自动实体枢纽 ${memoryId} → ${entity.id}(「${hub.name}」)`,
|
|
567
|
-
detail: {
|
|
568
|
-
op: 'auto-entity', memory: memoryId, entity: entity.id, name: hub.name,
|
|
569
|
-
kind: hub.kind, token: hub.token, confidence: ENTITY_CONFIDENCE, source: 'auto',
|
|
570
|
-
},
|
|
571
|
-
refs: [memoryId, entity.id],
|
|
572
|
-
})
|
|
573
|
-
} catch (error) {
|
|
574
|
-
record({
|
|
575
|
-
kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
|
|
576
|
-
message: `自动实体枢纽跳过 ${memoryId} → 「${hub.name}」:${String(error?.message || error)}`,
|
|
577
|
-
detail: { op: 'auto-entity', memory: memoryId, entity: entity?.id || null, name: hub.name, error: String(error?.message || error) },
|
|
578
|
-
refs: [memoryId],
|
|
579
|
-
})
|
|
580
|
-
}
|
|
538
|
+
return { skipped: null, applied, full: true }
|
|
581
539
|
}
|
|
540
|
+
const applied = refreshMemoryAutoLinks({
|
|
541
|
+
libraryId, ids: idList, entities: entityList, suppression, sessionId,
|
|
542
|
+
})
|
|
543
|
+
return { skipped: null, applied }
|
|
544
|
+
} catch (error) {
|
|
545
|
+
record({
|
|
546
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
|
|
547
|
+
message: `私有自动关联写入失败:${String(error?.message || error)}`,
|
|
548
|
+
detail: { op: 'auto-link', phase: 'apply', error: String(error?.message || error) },
|
|
549
|
+
refs: [],
|
|
550
|
+
})
|
|
551
|
+
return { skipped: 'apply', applied: null }
|
|
582
552
|
}
|
|
583
|
-
|
|
584
|
-
return result
|
|
585
553
|
}
|
|
586
554
|
|
|
587
|
-
export default { suggestPrivateLinks, autoLinkPrivateMemories, normalizeEntityName, inferEntityKind }
|
|
555
|
+
export default { suggestPrivateLinks, autoLinkPrivateMemories, refreshPrivateAutoLinks, normalizeEntityName, inferEntityKind }
|