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
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// Review-queue builder (DESIGN §9). Candidate terms and legacy entity grades are
|
|
2
|
+
// derived data: they change no entity status and write no edge. The snapshot is
|
|
3
|
+
// persisted next to the index so the panel can render without recomputing, and
|
|
4
|
+
// it is safe to delete/recreate at any time.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { dataDir, indexDir, isSafeId, writeJson } from '../paths.js'
|
|
9
|
+
import { loadPrivateIndex } from '../state.js'
|
|
10
|
+
import { listEntities } from '../graph.js'
|
|
11
|
+
import { loadLexicon } from '../lexicon.js'
|
|
12
|
+
import { AUTOLINK_POLICY_V3, AUTOLINK_POLICY_VERSION } from './policy.js'
|
|
13
|
+
import { eligibleEntries, effectiveEntityStatus } from './decide.js'
|
|
14
|
+
import { buildTermStats, rankCandidates } from './terminology.js'
|
|
15
|
+
import { normalizeForIndex } from './normalize.js'
|
|
16
|
+
|
|
17
|
+
const CACHE = new Map()
|
|
18
|
+
|
|
19
|
+
export function candidatesFile(libraryId) {
|
|
20
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
21
|
+
return path.join(indexDir(), `${libraryId}.anchor-candidates.json`)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function statSignature(libraryId) {
|
|
25
|
+
const files = [
|
|
26
|
+
path.join(indexDir(), `${libraryId}.json`),
|
|
27
|
+
path.join(indexDir(), `${libraryId}.entities.json`),
|
|
28
|
+
path.join(dataDir(), 'lexicon', `${libraryId}.json`),
|
|
29
|
+
]
|
|
30
|
+
return files.map(file => {
|
|
31
|
+
try {
|
|
32
|
+
const stat = fs.statSync(file)
|
|
33
|
+
return `${stat.mtimeMs}:${stat.size}`
|
|
34
|
+
} catch { return '0:0' }
|
|
35
|
+
}).join('|')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lexiconSignals(libraryId) {
|
|
39
|
+
const user = new Set()
|
|
40
|
+
const model = new Set()
|
|
41
|
+
let terms = {}
|
|
42
|
+
try { terms = loadLexicon(libraryId).terms || {} } catch { return { user, model } }
|
|
43
|
+
for (const entry of Object.values(terms)) {
|
|
44
|
+
if (!entry || entry.status !== 'active') continue
|
|
45
|
+
const userOwned = entry.source === 'user' || Boolean(entry.reviewedBy)
|
|
46
|
+
const target = userOwned ? user : (entry.source === 'model-proposal' ? model : null)
|
|
47
|
+
if (!target) continue
|
|
48
|
+
for (const name of [entry.term, ...(Array.isArray(entry.aliases) ? entry.aliases : [])]) {
|
|
49
|
+
const key = normalizeForIndex(name)
|
|
50
|
+
if (key) target.add(key)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { user, model }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function entitySurfaceMap(entities) {
|
|
57
|
+
const map = new Map()
|
|
58
|
+
for (const entity of entities) {
|
|
59
|
+
for (const name of [entity.name, ...(Array.isArray(entity.aliases) ? entity.aliases : [])]) {
|
|
60
|
+
const key = normalizeForIndex(name)
|
|
61
|
+
if (key && !map.has(key)) map.set(key, entity)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return map
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Build (or reuse) one library's review queue. The snapshot never contains
|
|
69
|
+
* memory bodies: rows are terms plus statistics, which the UI already shows.
|
|
70
|
+
*/
|
|
71
|
+
export function generateAnchorCandidates({ libraryId, now = Date.now(), force = false, policy = AUTOLINK_POLICY_V3 } = {}) {
|
|
72
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
73
|
+
const signature = statSignature(libraryId)
|
|
74
|
+
const cached = CACHE.get(libraryId)
|
|
75
|
+
if (!force && cached && cached.signature === signature) return cached.value
|
|
76
|
+
const stored = readStored(libraryId)
|
|
77
|
+
if (!force && stored && stored.revision === signature && Array.isArray(stored?.tiers?.tier1)) {
|
|
78
|
+
CACHE.set(libraryId, { signature, value: stored })
|
|
79
|
+
return stored
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const index = loadPrivateIndex(libraryId)
|
|
83
|
+
const rows = eligibleEntries(index).map(item => ({
|
|
84
|
+
id: item.id,
|
|
85
|
+
title: String(item.entry?.title || ''),
|
|
86
|
+
text: `${item.entry?.title || ''}\n${item.entry?.content || ''}`,
|
|
87
|
+
}))
|
|
88
|
+
const stats = buildTermStats(rows, policy)
|
|
89
|
+
const { user, model } = lexiconSignals(libraryId)
|
|
90
|
+
const tiers = rankCandidates(rows, stats, { policy, lexiconUser: user, lexiconModel: model })
|
|
91
|
+
const entityItems = listEntities({ libraryId }).items
|
|
92
|
+
const bySurface = entitySurfaceMap(entityItems)
|
|
93
|
+
for (const tier of ['tier1', 'tier2']) {
|
|
94
|
+
for (const row of tiers[tier]) {
|
|
95
|
+
const entity = bySurface.get(normalizeForIndex(row.term))
|
|
96
|
+
if (!entity) continue
|
|
97
|
+
row.entityId = entity.id
|
|
98
|
+
row.entityName = entity.name
|
|
99
|
+
row.entityKind = entity.kind
|
|
100
|
+
row.entityStatus = effectiveEntityStatus(entity)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const provisional = entityItems
|
|
104
|
+
.filter(entity => effectiveEntityStatus(entity) === 'provisional')
|
|
105
|
+
.map(entity => ({
|
|
106
|
+
id: entity.id, name: entity.name, kind: entity.kind, linked: entity.linked === true,
|
|
107
|
+
origin: entity.origin || null,
|
|
108
|
+
terms: [...tiers.tier1, ...tiers.tier2].filter(row => row.entityId === entity.id).map(row => row.term),
|
|
109
|
+
}))
|
|
110
|
+
.sort((a, b) => (b.terms.length - a.terms.length) || a.name.localeCompare(b.name))
|
|
111
|
+
const confirmed = entityItems
|
|
112
|
+
.filter(entity => effectiveEntityStatus(entity) === 'confirmed')
|
|
113
|
+
.map(entity => ({ id: entity.id, name: entity.name, kind: entity.kind }))
|
|
114
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
115
|
+
|
|
116
|
+
const value = {
|
|
117
|
+
version: 1,
|
|
118
|
+
libraryId,
|
|
119
|
+
revision: signature,
|
|
120
|
+
policyVersion: AUTOLINK_POLICY_VERSION,
|
|
121
|
+
generatedAt: new Date(now).toISOString(),
|
|
122
|
+
totals: { memories: rows.length, entities: entityItems.length, tier1: tiers.tier1.length, tier2: tiers.tier2.length },
|
|
123
|
+
tiers,
|
|
124
|
+
entities: { provisional, confirmed },
|
|
125
|
+
}
|
|
126
|
+
CACHE.set(libraryId, { signature, value })
|
|
127
|
+
try { writeJson(candidatesFile(libraryId), value) } catch {}
|
|
128
|
+
return value
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function readStored(libraryId) {
|
|
132
|
+
try {
|
|
133
|
+
const raw = fs.readFileSync(candidatesFile(libraryId), 'utf8')
|
|
134
|
+
const value = JSON.parse(raw)
|
|
135
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : null
|
|
136
|
+
} catch {
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Test/ops helper: drop the in-process cache so the next read recomputes. */
|
|
142
|
+
export function resetAnchorCandidatesCache() {
|
|
143
|
+
CACHE.clear()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The candidate row for one confirmed-able term: the UI either confirms an
|
|
148
|
+
* existing provisional entity or creates a confirmed one. Returns a descriptor;
|
|
149
|
+
* the actual confirm/create stays an explicit user RPC.
|
|
150
|
+
*/
|
|
151
|
+
export function candidateConfirmationTarget(candidate) {
|
|
152
|
+
if (candidate?.entityId && candidate.entityStatus === 'provisional') return { kind: 'confirm', entityId: candidate.entityId }
|
|
153
|
+
if (candidate?.entityId && candidate.entityStatus === 'confirmed') return { kind: 'already-confirmed', entityId: candidate.entityId }
|
|
154
|
+
return { kind: 'create', name: String(candidate?.term || '') }
|
|
155
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// The only path that decides whether an automatic edge may exist. Pure: no IO,
|
|
2
|
+
// no clock, no randomness — the same index/entities/suppression always produce
|
|
3
|
+
// the same edge list.
|
|
4
|
+
//
|
|
5
|
+
// Two deterministic rules feed it:
|
|
6
|
+
// entity-mention : a memory mentions a CONFIRMED entity name/alias
|
|
7
|
+
// field evidence : conflicts_with / supersedes / the same fact_key+context
|
|
8
|
+
//
|
|
9
|
+
// Lexical similarity, shared tokens, vectors and statistics never reach this
|
|
10
|
+
// file. They may rank review candidates elsewhere; they cannot create an edge.
|
|
11
|
+
|
|
12
|
+
import { isMemoryEligible } from '../memory.js'
|
|
13
|
+
import { AUTOLINK_POLICY_V3, AUTOLINK_SCHEMA_VERSION } from './policy.js'
|
|
14
|
+
import { isSuppressed } from './suppression.js'
|
|
15
|
+
import { firstMention, isMentionSurface, mentionCount, normalizeForIndex } from './normalize.js'
|
|
16
|
+
|
|
17
|
+
const FACT_KEYS = ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId']
|
|
18
|
+
|
|
19
|
+
const RULE_ORDER = new Map(['entity-mention', 'conflict', 'supersede', 'fact-key', 'worker-quote'].map((rule, index) => [rule, index]))
|
|
20
|
+
|
|
21
|
+
export function contextSignature(context = {}) {
|
|
22
|
+
return FACT_KEYS.map(key => String(context?.[key] || '')).join('\u0000')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Only a confirmed entity may produce edges; missing/legacy status is not confirmed. */
|
|
26
|
+
export function isConfirmedEntity(entity) {
|
|
27
|
+
return Boolean(entity && typeof entity === 'object' && entity.id && entity.status === 'confirmed')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Effective status for display/grading without writing anything back. */
|
|
31
|
+
export function effectiveEntityStatus(entity) {
|
|
32
|
+
if (!entity) return 'provisional'
|
|
33
|
+
if (['provisional', 'confirmed', 'archived'].includes(entity.status)) return entity.status
|
|
34
|
+
return 'provisional'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Eligible memory rows in the shape the rules consume (no secret rows). */
|
|
38
|
+
export function eligibleEntries(index) {
|
|
39
|
+
return Object.entries(index?.entries || {})
|
|
40
|
+
.filter(([, entry]) => entry && entry.visibility !== 'secret' && isMemoryEligible(entry, { automatic: true }))
|
|
41
|
+
.map(([id, entry]) => ({ id: String(id), entry, text: `${entry.title || ''}\n${entry.content || ''}` }))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function entryText(entry) {
|
|
45
|
+
return `${entry?.title || ''}\n${entry?.content || ''}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One name per normalized key; longest first so the most specific surface wins. */
|
|
49
|
+
function entitySurfaces(entity) {
|
|
50
|
+
const seen = new Set()
|
|
51
|
+
const out = []
|
|
52
|
+
for (const raw of [entity?.name, ...(Array.isArray(entity?.aliases) ? entity.aliases : [])]) {
|
|
53
|
+
const name = String(raw || '').trim()
|
|
54
|
+
const key = normalizeForIndex(name)
|
|
55
|
+
if (!key || seen.has(key) || !isMentionSurface(key)) continue
|
|
56
|
+
seen.add(key)
|
|
57
|
+
out.push(name)
|
|
58
|
+
}
|
|
59
|
+
return out.sort((a, b) => normalizeForIndex(b).length - normalizeForIndex(a).length || a.localeCompare(b))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Character-bigram postings over the COMPACT text (punctuation/space removed),
|
|
64
|
+
* so the prefilter uses exactly the same normalization as `mentionCount`:
|
|
65
|
+
* 「小·柚」、小 柚 and 星宫雲-yuike all remain findable. It is only a prefilter —
|
|
66
|
+
* the authoritative boundary check is still `mentionCount` on the raw text.
|
|
67
|
+
*/
|
|
68
|
+
export function buildMentionIndex(entries) {
|
|
69
|
+
const bigrams = new Map()
|
|
70
|
+
const push = (key, index) => {
|
|
71
|
+
let set = bigrams.get(key)
|
|
72
|
+
if (!set) { set = new Set(); bigrams.set(key, set) }
|
|
73
|
+
set.add(index)
|
|
74
|
+
}
|
|
75
|
+
entries.forEach(({ text }, index) => {
|
|
76
|
+
const chars = [...normalizeForIndex(text)]
|
|
77
|
+
for (let i = 0; i + 1 < chars.length; i += 1) push(chars[i] + chars[i + 1], index)
|
|
78
|
+
})
|
|
79
|
+
return { bigrams }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Rarest posting set for one name, or null when the prefilter proves no hit. */
|
|
83
|
+
function mentionCandidates(mentionIndex, name) {
|
|
84
|
+
const key = normalizeForIndex(name)
|
|
85
|
+
if (!key) return null
|
|
86
|
+
const chars = [...key]
|
|
87
|
+
if (chars.length < 2) return null
|
|
88
|
+
let best = null
|
|
89
|
+
for (let i = 0; i + 1 < chars.length; i += 1) {
|
|
90
|
+
const set = mentionIndex.bigrams.get(chars[i] + chars[i + 1])
|
|
91
|
+
if (!set || set.size === 0) return new Set()
|
|
92
|
+
if (!best || set.size < best.size) best = set
|
|
93
|
+
}
|
|
94
|
+
return best || new Set()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function matchField(entry, name) {
|
|
98
|
+
const titleOffset = firstMention(entry?.title || '', name)
|
|
99
|
+
if (titleOffset >= 0) return { field: 'title', offset: titleOffset }
|
|
100
|
+
const contentOffset = firstMention(entry?.content || '', name)
|
|
101
|
+
if (contentOffset >= 0) return { field: 'content', offset: contentOffset }
|
|
102
|
+
return null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* memory→entity edges for every confirmed entity. One edge per (memory, entity);
|
|
107
|
+
* the longest matching alias supplies the evidence surface. `maxPerEntity` keeps
|
|
108
|
+
* a popular name from turning into an unbounded fan-out; the newest memories win.
|
|
109
|
+
*/
|
|
110
|
+
export function mentionEdges(entries, entities, { policy = AUTOLINK_POLICY_V3 } = {}) {
|
|
111
|
+
const confirmed = (Array.isArray(entities) ? entities : []).filter(isConfirmedEntity)
|
|
112
|
+
if (!confirmed.length || !entries.length) return []
|
|
113
|
+
const mentionIndex = buildMentionIndex(entries)
|
|
114
|
+
const cap = Math.max(1, Number(policy.maxMentionEdgesPerEntity) || 200)
|
|
115
|
+
const edges = []
|
|
116
|
+
for (const entity of confirmed) {
|
|
117
|
+
const surfaces = entitySurfaces(entity)
|
|
118
|
+
if (!surfaces.length) continue
|
|
119
|
+
const matched = new Map()
|
|
120
|
+
for (const name of surfaces) {
|
|
121
|
+
const candidates = mentionCandidates(mentionIndex, name)
|
|
122
|
+
if (!candidates) continue
|
|
123
|
+
for (const index of candidates) {
|
|
124
|
+
const item = entries[index]
|
|
125
|
+
if (!item || matched.has(item.id)) continue
|
|
126
|
+
if (mentionCount(item.text, name) === 0) continue
|
|
127
|
+
const at = matchField(item.entry, name)
|
|
128
|
+
if (!at) continue
|
|
129
|
+
matched.set(item.id, { item, name, ...at })
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (!matched.size) continue
|
|
133
|
+
const picked = [...matched.values()]
|
|
134
|
+
.sort((a, b) => String(b.item.entry?.updatedAt || b.item.entry?.createdAt || '').localeCompare(String(a.item.entry?.updatedAt || a.item.entry?.createdAt || ''))
|
|
135
|
+
|| a.item.id.localeCompare(b.item.id))
|
|
136
|
+
.slice(0, cap)
|
|
137
|
+
for (const hit of picked) {
|
|
138
|
+
edges.push({
|
|
139
|
+
from: hit.item.id,
|
|
140
|
+
to: entity.id,
|
|
141
|
+
kind: entity.kind === 'person' ? 'person' : 'relation',
|
|
142
|
+
rule: 'entity-mention',
|
|
143
|
+
confidence: 1,
|
|
144
|
+
schemaVersion: AUTOLINK_SCHEMA_VERSION,
|
|
145
|
+
evidence: { rule: 'entity-mention', entityId: entity.id, surface: hit.name, field: hit.field, offset: hit.offset },
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** All entries as link targets: field evidence may cite a superseded/archived row. */
|
|
153
|
+
function allEntries(index) {
|
|
154
|
+
return Object.entries(index?.entries || {}).map(([id, entry]) => ({ id: String(id), entry }))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* One O(N) pass that turns the pairwise field scans into lookups:
|
|
159
|
+
* reverseConflicts/Supersedes : target id -> rows that point AT it
|
|
160
|
+
* families : fact_key+context -> time-ordered versions
|
|
161
|
+
* The old shape scanned the whole library once per entry (O(N²), 6s at 10k).
|
|
162
|
+
*/
|
|
163
|
+
function buildFieldIndexes(rows) {
|
|
164
|
+
const byId = new Map()
|
|
165
|
+
const reverseConflicts = new Map()
|
|
166
|
+
const reverseSupersedes = new Map()
|
|
167
|
+
const families = new Map()
|
|
168
|
+
const pushTo = (map, key, value) => {
|
|
169
|
+
let list = map.get(key)
|
|
170
|
+
if (!list) { list = []; map.set(key, list) }
|
|
171
|
+
list.push(value)
|
|
172
|
+
}
|
|
173
|
+
for (const row of rows) {
|
|
174
|
+
const entry = row.entry
|
|
175
|
+
if (!entry) continue
|
|
176
|
+
byId.set(row.id, row)
|
|
177
|
+
if (entry.conflicts_with) pushTo(reverseConflicts, String(entry.conflicts_with), row)
|
|
178
|
+
if (entry.supersedes) pushTo(reverseSupersedes, String(entry.supersedes), row)
|
|
179
|
+
if (entry.fact_key) {
|
|
180
|
+
const key = `${entry.fact_key}\u0000${contextSignature(entry.context)}`
|
|
181
|
+
pushTo(families, key, row)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const positions = new Map()
|
|
185
|
+
for (const [key, rowsInFamily] of families) {
|
|
186
|
+
rowsInFamily.sort((a, b) => String(a.entry?.createdAt || '').localeCompare(String(b.entry?.createdAt || ''))
|
|
187
|
+
|| (Number(a.entry?.version) || 0) - (Number(b.entry?.version) || 0)
|
|
188
|
+
|| a.id.localeCompare(b.id))
|
|
189
|
+
rowsInFamily.forEach((row, index) => positions.set(`${key}\u0000${row.id}`, index))
|
|
190
|
+
}
|
|
191
|
+
return { byId, reverseConflicts, reverseSupersedes, families, positions }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function fieldEdge(from, to, kind, field, rule) {
|
|
195
|
+
return {
|
|
196
|
+
from, to, kind, rule, confidence: 1,
|
|
197
|
+
schemaVersion: AUTOLINK_SCHEMA_VERSION,
|
|
198
|
+
evidence: { rule, field },
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function relationFieldEdges(indexes, id) {
|
|
203
|
+
const self = indexes.byId.get(id)
|
|
204
|
+
const entry = self?.entry
|
|
205
|
+
if (!entry) return []
|
|
206
|
+
const out = []
|
|
207
|
+
const add = (from, to, kind, field, rule) => {
|
|
208
|
+
if (!from || !to || from === to) return
|
|
209
|
+
if (!indexes.byId.has(String(to))) return
|
|
210
|
+
out.push(fieldEdge(from, to, kind, field, rule))
|
|
211
|
+
}
|
|
212
|
+
if (entry.conflicts_with) add(id, entry.conflicts_with, 'conflict', 'conflicts_with', 'conflict')
|
|
213
|
+
if (entry.supersedes) add(id, entry.supersedes, 'supersede', 'supersedes', 'supersede')
|
|
214
|
+
// memory.js writes the reverse field in the same transaction; the reverse index
|
|
215
|
+
// makes both directed edges O(1) instead of a per-entry full scan.
|
|
216
|
+
for (const other of indexes.reverseConflicts.get(id) || []) add(other.id, id, 'conflict', 'conflicts_with', 'conflict')
|
|
217
|
+
for (const other of indexes.reverseSupersedes.get(id) || []) add(other.id, id, 'supersede', 'supersedes', 'supersede')
|
|
218
|
+
return out
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Same fact_key + context: chain the versions instead of building a clique. */
|
|
222
|
+
function factKeyEdge(indexes, id) {
|
|
223
|
+
const self = indexes.byId.get(id)
|
|
224
|
+
const entry = self?.entry
|
|
225
|
+
const key = entry?.fact_key
|
|
226
|
+
if (!key) return []
|
|
227
|
+
const familyKey = `${key}\u0000${contextSignature(entry.context)}`
|
|
228
|
+
const position = indexes.positions.get(`${familyKey}\u0000${id}`)
|
|
229
|
+
if (position === undefined || position <= 0) return []
|
|
230
|
+
const other = indexes.families.get(familyKey)[position - 1]
|
|
231
|
+
if (!other) return []
|
|
232
|
+
if (entry.conflicts_with === other.id || other.entry?.conflicts_with === id) return []
|
|
233
|
+
return [fieldEdge(id, other.id, 'relation', 'fact_key', 'fact-key')]
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function collectFieldEdges(indexes, ids) {
|
|
237
|
+
const out = []
|
|
238
|
+
const seen = new Set()
|
|
239
|
+
for (const raw of Array.isArray(ids) ? ids : []) {
|
|
240
|
+
const id = String(raw)
|
|
241
|
+
if (!indexes.byId.has(id)) continue
|
|
242
|
+
for (const edge of [...relationFieldEdges(indexes, id), ...factKeyEdge(indexes, id)]) {
|
|
243
|
+
const dedupe = `${edge.from}\u0000${edge.to}\u0000${edge.kind}\u0000${edge.rule}`
|
|
244
|
+
if (seen.has(dedupe)) continue
|
|
245
|
+
seen.add(dedupe)
|
|
246
|
+
out.push(edge)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return out
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Field-evidence edges for the given memory ids only. One O(N) index build, then
|
|
254
|
+
* O(|ids|) lookups — the incremental consolidation path stays well under 50 ms
|
|
255
|
+
* at 10k memories.
|
|
256
|
+
*/
|
|
257
|
+
export function fieldEvidenceEdgesFor(index, ids) {
|
|
258
|
+
const indexes = buildFieldIndexes(allEntries(index))
|
|
259
|
+
const eligible = new Set(eligibleEntries(index).map(item => item.id))
|
|
260
|
+
const wanted = (Array.isArray(ids) ? ids : []).map(id => String(id)).filter(id => eligible.has(id))
|
|
261
|
+
return collectFieldEdges(indexes, wanted)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Full-library field evidence, used by dry-run / migration / purity tests. */
|
|
265
|
+
export function fieldEvidenceEdges(index) {
|
|
266
|
+
const indexes = buildFieldIndexes(allEntries(index))
|
|
267
|
+
return collectFieldEdges(indexes, eligibleEntries(index).map(item => item.id))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function filterSuppressed(edges, suppression) {
|
|
271
|
+
if (!suppression || suppression.size === 0) return edges
|
|
272
|
+
return edges.filter(edge => !isSuppressed(suppression, edge))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function sortEdges(edges) {
|
|
276
|
+
return edges.sort((a, b) => (RULE_ORDER.get(a.rule) ?? 99) - (RULE_ORDER.get(b.rule) ?? 99)
|
|
277
|
+
|| a.from.localeCompare(b.from)
|
|
278
|
+
|| a.to.localeCompare(b.to)
|
|
279
|
+
|| a.kind.localeCompare(b.kind))
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Full deterministic decision over one library snapshot.
|
|
284
|
+
* @returns { entities: edges[], ... } — edges carry rule/evidence/confidence 1.0
|
|
285
|
+
*/
|
|
286
|
+
export function decideAutoLinks({ index, entities = [], policy = AUTOLINK_POLICY_V3, suppression = null } = {}) {
|
|
287
|
+
const entries = eligibleEntries(index)
|
|
288
|
+
const mention = mentionEdges(entries, entities, { policy })
|
|
289
|
+
const field = fieldEvidenceEdges(index)
|
|
290
|
+
return filterSuppressed(sortEdges([...mention, ...field]), suppression)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Incremental decision for the entries a consolidation just touched. */
|
|
294
|
+
export function decideAutoLinksFor({ index, entities = [], ids, policy = AUTOLINK_POLICY_V3, suppression = null } = {}) {
|
|
295
|
+
const all = eligibleEntries(index)
|
|
296
|
+
const wanted = new Set((Array.isArray(ids) ? ids : []).map(id => String(id)))
|
|
297
|
+
const entries = all.filter(item => wanted.has(item.id))
|
|
298
|
+
if (!entries.length) return []
|
|
299
|
+
const mention = mentionEdges(entries, entities, { policy })
|
|
300
|
+
const field = fieldEvidenceEdgesFor(index, [...wanted])
|
|
301
|
+
return filterSuppressed(sortEdges([...mention, ...field]), suppression)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export default { decideAutoLinks, decideAutoLinksFor, mentionEdges, fieldEvidenceEdges, fieldEvidenceEdgesFor, eligibleEntries, isConfirmedEntity, effectiveEntityStatus }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Text normalization shared by the deterministic auto-link rules. Language
|
|
2
|
+
// agnostic: NFKC + case fold + strip punctuation/symbols/format characters and
|
|
3
|
+
// whitespace. Kana and Latin diacritics survive because only P/S/Cf/space are
|
|
4
|
+
// removed, so the same rule serves CJK, Latin and code identifiers.
|
|
5
|
+
|
|
6
|
+
export function normalizeForIndex(text) {
|
|
7
|
+
return String(text || '')
|
|
8
|
+
.normalize('NFKC')
|
|
9
|
+
.toLowerCase()
|
|
10
|
+
.replace(/[\s\p{P}\p{S}\p{Cf}]+/gu, '')
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Same bytes as the index form; named for the substring rule it serves. */
|
|
14
|
+
export function compact(text) {
|
|
15
|
+
return normalizeForIndex(text)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const LATIN_WORD = /^[a-z0-9][a-z0-9._-]*$/i
|
|
19
|
+
const CJK_CHAR = /[\u3400-\u9fff\uf900-\ufaff]/
|
|
20
|
+
|
|
21
|
+
export function isLatinToken(token) {
|
|
22
|
+
return LATIN_WORD.test(String(token || ''))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function hasCjk(token) {
|
|
26
|
+
return CJK_CHAR.test(String(token || ''))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Compact form plus each output code unit's position in the normalized source.
|
|
31
|
+
* `firstMention` needs the raw offset, and the compact index alone is wrong as
|
|
32
|
+
* soon as punctuation is removed (「小·柚」 -> 小柚 shifts by two).
|
|
33
|
+
*/
|
|
34
|
+
export function compactWithMap(text) {
|
|
35
|
+
const normalized = String(text || '').normalize('NFKC').toLowerCase()
|
|
36
|
+
let out = ''
|
|
37
|
+
const map = []
|
|
38
|
+
for (const match of normalized.matchAll(/[^\s\p{P}\p{S}\p{Cf}]/gu)) {
|
|
39
|
+
out += match[0]
|
|
40
|
+
map.push(match.index)
|
|
41
|
+
}
|
|
42
|
+
return { text: out, map }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Count occurrences of `name` in `text`.
|
|
47
|
+
* - A name containing CJK is matched as a substring of the compact text, so
|
|
48
|
+
* 「小·柚」, 小 柚 and 小柚 are the same surface (§8.1 NFKC + 去标点/空白).
|
|
49
|
+
* - A Latin / identifier name is matched literally (dots, underscores and
|
|
50
|
+
* hyphens are part of it) on word boundaries, so `yuike` never matches
|
|
51
|
+
* `yuikeee`, while `yuike.dev` stays one identifier.
|
|
52
|
+
*/
|
|
53
|
+
export function mentionCount(text, name) {
|
|
54
|
+
const raw = String(name || '').normalize('NFKC').toLowerCase().trim()
|
|
55
|
+
const key = normalizeForIndex(raw)
|
|
56
|
+
if (!key) return 0
|
|
57
|
+
if (hasCjk(key)) {
|
|
58
|
+
const source = compact(text)
|
|
59
|
+
if (!source) return 0
|
|
60
|
+
let count = 0
|
|
61
|
+
let at = source.indexOf(key)
|
|
62
|
+
while (at !== -1) { count += 1; at = source.indexOf(key, at + key.length) }
|
|
63
|
+
return count
|
|
64
|
+
}
|
|
65
|
+
const source = String(text || '').normalize('NFKC').toLowerCase()
|
|
66
|
+
const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
67
|
+
if (!escaped) return 0
|
|
68
|
+
const re = new RegExp(`(?<![a-z0-9])${escaped}(?![a-z0-9])`, 'g')
|
|
69
|
+
return (source.match(re) || []).length
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Offset of the first mention in the raw text, or -1. */
|
|
73
|
+
export function firstMention(text, name) {
|
|
74
|
+
const raw = String(name || '').normalize('NFKC').toLowerCase().trim()
|
|
75
|
+
const key = normalizeForIndex(raw)
|
|
76
|
+
if (!key) return -1
|
|
77
|
+
if (hasCjk(key)) {
|
|
78
|
+
const { text: compacted, map } = compactWithMap(text)
|
|
79
|
+
const at = compacted.indexOf(key)
|
|
80
|
+
return at === -1 ? -1 : (map[at] ?? -1)
|
|
81
|
+
}
|
|
82
|
+
const source = String(text || '').normalize('NFKC').toLowerCase()
|
|
83
|
+
const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
84
|
+
if (!escaped) return -1
|
|
85
|
+
const match = new RegExp(`(?<![a-z0-9])${escaped}(?![a-z0-9])`).exec(source)
|
|
86
|
+
return match ? match.index : -1
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A mention surface must carry identifying power: CJK needs >= 2 characters and
|
|
91
|
+
* Latin needs >= 2 boundary-safe characters. Single-character aliases would
|
|
92
|
+
* match half the library, which is the noise this layer exists to remove.
|
|
93
|
+
*/
|
|
94
|
+
export function isMentionSurface(name) {
|
|
95
|
+
const key = normalizeForIndex(name)
|
|
96
|
+
if (!key) return false
|
|
97
|
+
if (hasCjk(key)) return [...key].length >= 2
|
|
98
|
+
return isLatinToken(key) && key.length >= 2
|
|
99
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Versioned constants for the auto-link pipeline. They are nomination/ranking
|
|
2
|
+
// bounds and write caps — never a "should this edge exist" threshold. Whether an
|
|
3
|
+
// edge is written is decided only by the deterministic rule table, so tuning
|
|
4
|
+
// these numbers cannot turn a lexical coincidence into a fact.
|
|
5
|
+
//
|
|
6
|
+
// Online code reads this frozen table; calibration happens offline and ships as
|
|
7
|
+
// a new table version.
|
|
8
|
+
|
|
9
|
+
export const AUTOLINK_POLICY_VERSION = 3
|
|
10
|
+
export const AUTOLINK_SCHEMA_VERSION = 2
|
|
11
|
+
|
|
12
|
+
export const AUTOLINK_POLICY_V3 = Object.freeze({
|
|
13
|
+
version: AUTOLINK_POLICY_VERSION,
|
|
14
|
+
schemaVersion: AUTOLINK_SCHEMA_VERSION,
|
|
15
|
+
|
|
16
|
+
// Nomination (S1): CJK n-grams and boundary-safe Latin tokens.
|
|
17
|
+
ngramCjkMin: 2,
|
|
18
|
+
ngramCjkMax: 4,
|
|
19
|
+
latinMin: 3,
|
|
20
|
+
latinMax: 24,
|
|
21
|
+
minDf: 2,
|
|
22
|
+
maxDfRatio: 0.35,
|
|
23
|
+
minAvEachSide: 2,
|
|
24
|
+
minLLR: 10.83,
|
|
25
|
+
minCohesion: 3.0,
|
|
26
|
+
minFreedom: 1.0,
|
|
27
|
+
minTitleDf: 2,
|
|
28
|
+
minCues: 2,
|
|
29
|
+
tier1Max: 40,
|
|
30
|
+
tier2Max: 100,
|
|
31
|
+
vectorLocalTopM: 200,
|
|
32
|
+
|
|
33
|
+
// Writes. entity-mention is a fact index and is not capped per memory; these
|
|
34
|
+
// caps bound optional related edges and the review queue.
|
|
35
|
+
maxAutoEdgesPerMemory: 6,
|
|
36
|
+
maxPerConsolidation: 3,
|
|
37
|
+
maxMentionEdgesPerEntity: 200,
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
export const EVIDENCE_RULES = Object.freeze(['entity-mention', 'conflict', 'supersede', 'fact-key', 'worker-quote'])
|
|
41
|
+
|
|
42
|
+
export const ENTITY_STATUS = Object.freeze(['provisional', 'confirmed', 'archived'])
|