dsh-memu-memory 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -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 +2 -2
- package/lib/client.js +1412 -69
- package/lib/graph.js +269 -18
- package/lib/memory.js +11 -0
- package/lib/memu.js +7 -6
- package/lib/private-links.js +105 -137
- package/lib/private.js +138 -38
- package/lib/rpc.js +67 -7
- package/lib/state.js +7 -2
- package/lib/tools.js +4 -2
- 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-fork.test.mjs +148 -0
- package/tests/cycle.test.mjs +1 -1
- package/tests/graph-view.test.mjs +163 -21
- package/tests/graph.test.mjs +5 -0
- package/tests/help-page.test.mjs +3 -3
- package/tests/memu-resident-route.test.mjs +130 -0
- package/tests/private-links.test.mjs +81 -45
- package/tests/stubs/child-process-spy.mjs +14 -0
- package/tests/tools.test.mjs +24 -18
|
@@ -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'])
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { indexDir, isSafeId, readJsonStrict, writeJson, withFileLock, stamp } from '../paths.js'
|
|
3
|
+
|
|
4
|
+
// Negative feedback for the deterministic link layer. When the user removes an
|
|
5
|
+
// automatic edge (or revokes an entity, which collects its edges), the exact
|
|
6
|
+
// (from, to, kind, rule) key is written here so the next consolidation cannot
|
|
7
|
+
// resurrect it. One file per library, next to the index it protects.
|
|
8
|
+
|
|
9
|
+
const VERSION = 1
|
|
10
|
+
|
|
11
|
+
function suppressionFile(libraryId) {
|
|
12
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
13
|
+
return path.join(indexDir(), `${libraryId}.link-suppression.json`)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Canonical key for one edge. A legacy auto edge without a rule keeps its own key. */
|
|
17
|
+
export function suppressionKey(edge) {
|
|
18
|
+
const rule = String(edge?.rule || edge?.evidence?.rule || 'auto')
|
|
19
|
+
return `${String(edge?.from || '')}|${String(edge?.to || '')}|${String(edge?.kind || '')}|${rule}`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function tripleKey(edge) {
|
|
23
|
+
return `${String(edge?.from || '')}|${String(edge?.to || '')}|${String(edge?.kind || '')}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A user's removal is a negative label on the (from, to, kind) fact, not on the
|
|
28
|
+
* rule string that happened to be current. Legacy auto edges carry no rule, so a
|
|
29
|
+
* later deterministic edge with `entity-mention` must still be blocked. The
|
|
30
|
+
* wildcard key (`...|*`) is what makes "deleted never comes back" true across a
|
|
31
|
+
* rule upgrade; `...|auto` keeps older suppression files working.
|
|
32
|
+
*/
|
|
33
|
+
export function isSuppressed(suppression, edge) {
|
|
34
|
+
if (!suppression || suppression.size === 0) return false
|
|
35
|
+
return suppression.has(suppressionKey(edge))
|
|
36
|
+
|| suppression.has(`${tripleKey(edge)}|*`)
|
|
37
|
+
|| suppression.has(`${tripleKey(edge)}|auto`)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function readSuppression(libraryId) {
|
|
41
|
+
const file = suppressionFile(libraryId)
|
|
42
|
+
const result = readJsonStrict(file)
|
|
43
|
+
if (result.ok) {
|
|
44
|
+
const value = result.value
|
|
45
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('invalid link suppression store')
|
|
46
|
+
const entries = value.entries && typeof value.entries === 'object' && !Array.isArray(value.entries) ? value.entries : {}
|
|
47
|
+
return { version: VERSION, entries }
|
|
48
|
+
}
|
|
49
|
+
if (result.missing) return { version: VERSION, entries: {} }
|
|
50
|
+
throw new Error(`cannot read link suppression store: ${result.error?.message || 'invalid data'}`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Set of suppressed keys for the pure decision layer. A corrupt store throws. */
|
|
54
|
+
export function suppressionSet(libraryId) {
|
|
55
|
+
return new Set(Object.keys(readSuppression(libraryId).entries))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Persist suppression keys for removed edges. Idempotent: an existing key keeps
|
|
60
|
+
* its original timestamp. The caller has already removed the edges; a failure
|
|
61
|
+
* here must be reported by the caller, not silently repaired.
|
|
62
|
+
*/
|
|
63
|
+
export function addSuppression(libraryId, edges, { by = 'user' } = {}) {
|
|
64
|
+
const list = (Array.isArray(edges) ? edges : []).filter(edge => edge && edge.from && edge.to)
|
|
65
|
+
if (!list.length) return { added: 0, total: 0 }
|
|
66
|
+
const file = suppressionFile(libraryId)
|
|
67
|
+
return withFileLock(file, () => {
|
|
68
|
+
const store = readSuppression(libraryId)
|
|
69
|
+
let added = 0
|
|
70
|
+
const at = stamp()
|
|
71
|
+
for (const edge of list) {
|
|
72
|
+
const key = suppressionKey(edge)
|
|
73
|
+
const wildcard = `${tripleKey(edge)}|*`
|
|
74
|
+
// Write both the exact rule and the triple wildcard: the former documents
|
|
75
|
+
// what was removed, the latter keeps the fact suppressed after the rule
|
|
76
|
+
// that produced it changes (legacy 'auto' -> 'entity-mention').
|
|
77
|
+
for (const entryKey of [key, wildcard]) {
|
|
78
|
+
if (store.entries[entryKey]) continue
|
|
79
|
+
store.entries[entryKey] = {
|
|
80
|
+
at, by: String(by || 'user'),
|
|
81
|
+
from: String(edge.from), to: String(edge.to),
|
|
82
|
+
kind: String(edge.kind || ''), rule: entryKey === wildcard ? '*' : String(edge.rule || edge.evidence?.rule || 'auto'),
|
|
83
|
+
}
|
|
84
|
+
added += 1
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (added) writeJson(file, store)
|
|
88
|
+
return { added, total: Object.keys(store.entries).length }
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function clearSuppression(libraryId) {
|
|
93
|
+
const file = suppressionFile(libraryId)
|
|
94
|
+
return withFileLock(file, () => {
|
|
95
|
+
let entries = {}
|
|
96
|
+
try { entries = readSuppression(libraryId).entries } catch {}
|
|
97
|
+
const cleared = Object.keys(entries).length
|
|
98
|
+
writeJson(file, { version: VERSION, entries: {} })
|
|
99
|
+
return { cleared }
|
|
100
|
+
})
|
|
101
|
+
}
|