dsh-memu-memory 1.3.1 → 1.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +6 -3
- package/CHANGELOG.md +57 -0
- package/README.md +8 -7
- package/README.zh.md +8 -5
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/stats.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +11 -0
- package/docs/contributing.md +6 -4
- package/docs/env-and-commands.md +12 -1
- package/docs/memory-semantics.md +8 -2
- package/docs/troubleshooting.md +24 -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 +1509 -72
- 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 +73 -8
- 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 +921 -126
- package/lib/webui/standalone.js +3 -3
- package/package.json +1 -2
- package/scripts/build-graph.mjs +35 -7
- package/scripts/check-all.mjs +2 -0
- package/scripts/check-graph-browser.mjs +106 -23
- package/scripts/make-readme-shots.mjs +59 -0
- 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/browser.test.mjs +27 -0
- package/tests/client-render.test.mjs +178 -6
- package/tests/consolidation-fork.test.mjs +148 -0
- package/tests/cycle.test.mjs +1 -1
- package/tests/graph-view.test.mjs +221 -22
- 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,249 @@
|
|
|
1
|
+
// Write side of the deterministic link layer. All decisions come from decide.js;
|
|
2
|
+
// this module only persists them (idempotently) and keeps the activity log
|
|
3
|
+
// honest. A failing pass must never fail the consolidation that triggered it —
|
|
4
|
+
// the caller catches and warns.
|
|
5
|
+
|
|
6
|
+
import { getSettings, updatePrivateIndex } from '../state.js'
|
|
7
|
+
import { stamp } from '../paths.js'
|
|
8
|
+
import { record } from '../activity-log.js'
|
|
9
|
+
import { isMemoryEligible } from '../memory.js'
|
|
10
|
+
import { AUTOLINK_SCHEMA_VERSION, EVIDENCE_RULES } from './policy.js'
|
|
11
|
+
import { decideAutoLinksFor, eligibleEntries, mentionEdges } from './decide.js'
|
|
12
|
+
import { isSuppressed } from './suppression.js'
|
|
13
|
+
|
|
14
|
+
// Rules this layer owns. worker-quote edges come from the explicit tool and must
|
|
15
|
+
// survive a recompute; anything else auto-generated is replaced, not appended.
|
|
16
|
+
export const AUTO_RULES = Object.freeze(['entity-mention', 'conflict', 'supersede', 'fact-key'])
|
|
17
|
+
|
|
18
|
+
function isEligibleEntry(entry) {
|
|
19
|
+
return Boolean(entry) && entry.visibility !== 'secret' && isMemoryEligible(entry, { automatic: true })
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function noteFor(edge) {
|
|
23
|
+
if (edge.rule === 'entity-mention') {
|
|
24
|
+
const surface = edge.evidence?.surface ? `「${edge.evidence.surface}」` : ''
|
|
25
|
+
const field = edge.evidence?.field === 'title' ? '标题' : '正文'
|
|
26
|
+
return `提及已确认实体${surface}(${field})。`
|
|
27
|
+
}
|
|
28
|
+
if (edge.rule === 'conflict') return '字段证据:conflicts_with 指向这条记忆,两者是同一事实的不同版本。'
|
|
29
|
+
if (edge.rule === 'supersede') return '字段证据:supersedes 指向被取代的旧记忆。'
|
|
30
|
+
if (edge.rule === 'fact-key') return '字段证据:同一 fact_key 且上下文一致的相邻版本。'
|
|
31
|
+
return `确定性关联:${edge.rule}。`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function recordFor(edge, existing) {
|
|
35
|
+
return {
|
|
36
|
+
to: edge.to,
|
|
37
|
+
kind: edge.kind,
|
|
38
|
+
note: noteFor(edge),
|
|
39
|
+
confidence: 1,
|
|
40
|
+
createdAt: existing?.createdAt || stamp(),
|
|
41
|
+
source: 'auto',
|
|
42
|
+
schemaVersion: edge.schemaVersion || AUTOLINK_SCHEMA_VERSION,
|
|
43
|
+
evidence: { ...(edge.evidence || {}), rule: edge.rule },
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A repeated decision over unchanged content must not look like a write: same
|
|
48
|
+
// target, rule, note and evidence means the edge already says exactly this.
|
|
49
|
+
function sameAsRecord(existing, edge) {
|
|
50
|
+
if (!existing || existing.source !== 'auto') return false
|
|
51
|
+
const record_ = recordFor(edge, existing)
|
|
52
|
+
return existing.kind === record_.kind
|
|
53
|
+
&& existing.note === record_.note
|
|
54
|
+
&& existing.confidence === 1
|
|
55
|
+
&& existing.schemaVersion === record_.schemaVersion
|
|
56
|
+
&& JSON.stringify(existing.evidence || null) === JSON.stringify(record_.evidence)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Apply decided edges inside one index transaction. Existing manual/user edges
|
|
61
|
+
* with the same (to, kind) win — an automatic fact never overwrites what a
|
|
62
|
+
* person or the worker asserted. Returns counts plus the applied edge list.
|
|
63
|
+
*/
|
|
64
|
+
export function applyAutoEdges({ libraryId, edges, entities = [], sessionId = null, operation = 'auto-link-apply' } = {}) {
|
|
65
|
+
const counts = { added: 0, updated: 0, skippedManual: 0, skippedCap: 0, skipped: 0, memory: 0, entity: 0 }
|
|
66
|
+
const applied = []
|
|
67
|
+
if (!libraryId || !Array.isArray(edges) || edges.length === 0) return { ...counts, applied }
|
|
68
|
+
const entityIds = new Set((Array.isArray(entities) ? entities : []).map(entity => entity?.id).filter(Boolean))
|
|
69
|
+
updatePrivateIndex(libraryId, index => {
|
|
70
|
+
for (const edge of edges) {
|
|
71
|
+
// The write layer only accepts the declared evidence vocabulary; an
|
|
72
|
+
// unknown rule is a caller bug, never a new edge category.
|
|
73
|
+
if (!EVIDENCE_RULES.includes(edge?.rule)) { counts.skipped += 1; continue }
|
|
74
|
+
const from = index.entries[edge?.from]
|
|
75
|
+
if (!from || !isEligibleEntry(from)) { counts.skipped += 1; continue }
|
|
76
|
+
const isMemoryTarget = Boolean(index.entries[edge.to])
|
|
77
|
+
if (!isMemoryTarget && !entityIds.has(edge.to)) { counts.skipped += 1; continue }
|
|
78
|
+
const links = Array.isArray(from.links) ? from.links : []
|
|
79
|
+
const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
|
|
80
|
+
if (at >= 0 && links[at].source !== 'auto') { counts.skippedManual += 1; continue }
|
|
81
|
+
if (at >= 0 && sameAsRecord(links[at], edge)) continue
|
|
82
|
+
if (at < 0 && links.length >= 100) { counts.skippedCap += 1; continue }
|
|
83
|
+
const record_ = recordFor(edge, at >= 0 ? links[at] : null)
|
|
84
|
+
if (at >= 0) {
|
|
85
|
+
links[at] = record_
|
|
86
|
+
counts.updated += 1
|
|
87
|
+
} else {
|
|
88
|
+
links.push(record_)
|
|
89
|
+
counts.added += 1
|
|
90
|
+
}
|
|
91
|
+
from.links = links
|
|
92
|
+
counts[isMemoryTarget ? 'memory' : 'entity'] += 1
|
|
93
|
+
applied.push({ from: edge.from, to: edge.to, kind: edge.kind, rule: edge.rule })
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
if (counts.added || counts.updated) {
|
|
97
|
+
try {
|
|
98
|
+
record({
|
|
99
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
|
|
100
|
+
message: `自动关联写入 ${counts.added + counts.updated} 条(新增 ${counts.added} / 更新 ${counts.updated})`,
|
|
101
|
+
detail: {
|
|
102
|
+
op: operation, added: counts.added, updated: counts.updated,
|
|
103
|
+
skippedManual: counts.skippedManual, skippedCap: counts.skippedCap, skipped: counts.skipped,
|
|
104
|
+
memory: counts.memory, entity: counts.entity,
|
|
105
|
+
},
|
|
106
|
+
refs: [...new Set(applied.map(edge => edge.from))].slice(0, 20),
|
|
107
|
+
})
|
|
108
|
+
} catch {}
|
|
109
|
+
}
|
|
110
|
+
return { ...counts, applied }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Incremental refresh for the memories a consolidation touched: drop the auto
|
|
115
|
+
* edges this layer generated for them, then re-add today's deterministic ones.
|
|
116
|
+
* Removal and addition share one index lock, so a crash cannot leave the entry
|
|
117
|
+
* with half a rule set.
|
|
118
|
+
*/
|
|
119
|
+
export function refreshMemoryAutoLinks({ libraryId, ids, entities = [], suppression = null, sessionId = null, operation = 'auto-link-apply' } = {}) {
|
|
120
|
+
const wanted = [...new Set((Array.isArray(ids) ? ids : []).map(id => String(id)).filter(Boolean))]
|
|
121
|
+
const counts = { added: 0, updated: 0, removed: 0, skippedManual: 0, skippedCap: 0, skipped: 0, memory: 0, entity: 0 }
|
|
122
|
+
const applied = []
|
|
123
|
+
if (!libraryId || !wanted.length) return { ...counts, applied }
|
|
124
|
+
const entityIds = new Set((Array.isArray(entities) ? entities : []).map(entity => entity?.id).filter(Boolean))
|
|
125
|
+
updatePrivateIndex(libraryId, index => {
|
|
126
|
+
const decided = decideAutoLinksFor({ index, entities, ids: wanted, suppression })
|
|
127
|
+
// Diff instead of wipe-and-rebuild: an unchanged edge keeps its createdAt and
|
|
128
|
+
// counts as no write, so a repeat pass over the same window is a no-op.
|
|
129
|
+
const byMemory = new Map()
|
|
130
|
+
for (const edge of decided) {
|
|
131
|
+
if (!byMemory.has(edge.from)) byMemory.set(edge.from, new Map())
|
|
132
|
+
byMemory.get(edge.from).set(`${edge.to}\u0000${edge.kind}`, edge)
|
|
133
|
+
}
|
|
134
|
+
for (const id of wanted) {
|
|
135
|
+
const entry = index.entries[id]
|
|
136
|
+
if (!entry || !Array.isArray(entry.links)) continue
|
|
137
|
+
const candidates = byMemory.get(id) || new Map()
|
|
138
|
+
const next = []
|
|
139
|
+
let changed = false
|
|
140
|
+
for (const link of entry.links) {
|
|
141
|
+
// Rule-owned edges plus marker-less legacy auto edges: both are this
|
|
142
|
+
// layer's noise and are replaced by today's decision.
|
|
143
|
+
const owned = link && link.source === 'auto' && (AUTO_RULES.includes(link.evidence?.rule) || !link.evidence?.rule)
|
|
144
|
+
if (!owned) { next.push(link); continue }
|
|
145
|
+
const key = `${link.to}\u0000${link.kind}`
|
|
146
|
+
const edge = candidates.get(key)
|
|
147
|
+
if (edge && sameAsRecord(link, edge)) { candidates.delete(key); next.push(link); continue }
|
|
148
|
+
counts.removed += 1
|
|
149
|
+
changed = true
|
|
150
|
+
}
|
|
151
|
+
if (changed) entry.links = next
|
|
152
|
+
}
|
|
153
|
+
for (const [fromId, candidates] of byMemory) {
|
|
154
|
+
const from = index.entries[fromId]
|
|
155
|
+
if (!from || !isEligibleEntry(from)) { counts.skipped += candidates.size; continue }
|
|
156
|
+
const links = Array.isArray(from.links) ? from.links : []
|
|
157
|
+
for (const edge of candidates.values()) {
|
|
158
|
+
const isMemoryTarget = Boolean(index.entries[edge.to])
|
|
159
|
+
if (!isMemoryTarget && !entityIds.has(edge.to)) { counts.skipped += 1; continue }
|
|
160
|
+
const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
|
|
161
|
+
if (at >= 0 && links[at].source !== 'auto') { counts.skippedManual += 1; continue }
|
|
162
|
+
if (at < 0 && links.length >= 100) { counts.skippedCap += 1; continue }
|
|
163
|
+
const record_ = recordFor(edge, at >= 0 ? links[at] : null)
|
|
164
|
+
if (at >= 0) { links[at] = record_; counts.updated += 1 }
|
|
165
|
+
else { links.push(record_); counts.added += 1 }
|
|
166
|
+
counts[isMemoryTarget ? 'memory' : 'entity'] += 1
|
|
167
|
+
applied.push({ from: edge.from, to: edge.to, kind: edge.kind, rule: edge.rule })
|
|
168
|
+
}
|
|
169
|
+
from.links = links
|
|
170
|
+
}
|
|
171
|
+
})
|
|
172
|
+
const written = counts.added + counts.updated
|
|
173
|
+
if (written || counts.removed) {
|
|
174
|
+
try {
|
|
175
|
+
record({
|
|
176
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
|
|
177
|
+
message: `自动关联重算 ${written} 条(新增 ${counts.added} / 更新 ${counts.updated} / 清理 ${counts.removed})`,
|
|
178
|
+
detail: {
|
|
179
|
+
op: operation, added: counts.added, updated: counts.updated, removed: counts.removed,
|
|
180
|
+
skippedManual: counts.skippedManual, skippedCap: counts.skippedCap, skipped: counts.skipped,
|
|
181
|
+
memory: counts.memory, entity: counts.entity,
|
|
182
|
+
},
|
|
183
|
+
refs: [...new Set(applied.map(edge => edge.from))].slice(0, 20),
|
|
184
|
+
})
|
|
185
|
+
} catch {}
|
|
186
|
+
}
|
|
187
|
+
return { ...counts, applied }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Recompute one entity's mention edges across the whole library. Used when an
|
|
192
|
+
* entity is confirmed, renamed, merged or revoked; field edges are untouched.
|
|
193
|
+
*/
|
|
194
|
+
export function refreshEntityMentions({ libraryId, entity, suppression = null, sessionId = null, operation = 'auto-link-entity' } = {}) {
|
|
195
|
+
const counts = { added: 0, updated: 0, removed: 0, skipped: 0 }
|
|
196
|
+
if (!libraryId || !entity?.id) return counts
|
|
197
|
+
// 'off' means every automatic edge path is closed, including the ones explicit
|
|
198
|
+
// UI actions used to trigger (create/confirm/rename/merge). 'suggest' still
|
|
199
|
+
// maintains edges on an explicit confirmation: the §14 S4 migration flow
|
|
200
|
+
// confirms while the automatic pass is still held back.
|
|
201
|
+
if (getSettings().autoLinkMode === 'off') return counts
|
|
202
|
+
updatePrivateIndex(libraryId, index => {
|
|
203
|
+
const decided = entity.status === 'confirmed'
|
|
204
|
+
? mentionEdges(eligibleEntries(index), [entity]).filter(edge => !isSuppressed(suppression, edge))
|
|
205
|
+
: []
|
|
206
|
+
const byLink = new Map(decided.map(edge => [`${edge.from}\u0000${edge.to}\u0000${edge.kind}`, edge]))
|
|
207
|
+
for (const [fromId, entry] of Object.entries(index.entries || {})) {
|
|
208
|
+
if (!entry || !Array.isArray(entry.links)) continue
|
|
209
|
+
const next = []
|
|
210
|
+
let changed = false
|
|
211
|
+
for (const link of entry.links) {
|
|
212
|
+
const owned = link && link.source === 'auto' && link.evidence?.rule === 'entity-mention'
|
|
213
|
+
&& link.evidence?.entityId === entity.id
|
|
214
|
+
if (!owned) { next.push(link); continue }
|
|
215
|
+
const key = `${fromId}\u0000${link.to}\u0000${link.kind}`
|
|
216
|
+
const edge = byLink.get(key)
|
|
217
|
+
if (edge && sameAsRecord(link, edge)) { byLink.delete(key); next.push(link); continue }
|
|
218
|
+
counts.removed += 1
|
|
219
|
+
changed = true
|
|
220
|
+
}
|
|
221
|
+
if (changed) entry.links = next
|
|
222
|
+
}
|
|
223
|
+
for (const edge of byLink.values()) {
|
|
224
|
+
const from = index.entries[edge.from]
|
|
225
|
+
if (!from) continue
|
|
226
|
+
const links = Array.isArray(from.links) ? from.links : []
|
|
227
|
+
const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
|
|
228
|
+
if (at >= 0 && links[at].source !== 'auto') { counts.skipped += 1; continue }
|
|
229
|
+
if (at < 0 && links.length >= 100) { counts.skipped += 1; continue }
|
|
230
|
+
const record_ = recordFor(edge, at >= 0 ? links[at] : null)
|
|
231
|
+
if (at >= 0) { links[at] = record_; counts.updated += 1 }
|
|
232
|
+
else { links.push(record_); counts.added += 1 }
|
|
233
|
+
from.links = links
|
|
234
|
+
}
|
|
235
|
+
})
|
|
236
|
+
if (counts.added || counts.updated || counts.removed) {
|
|
237
|
+
try {
|
|
238
|
+
record({
|
|
239
|
+
kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
|
|
240
|
+
message: `实体提及边重算「${entity.name || entity.id}」:新增 ${counts.added} / 更新 ${counts.updated} / 清理 ${counts.removed}`,
|
|
241
|
+
detail: { op: operation, entityId: entity.id, status: entity.status || null, ...counts },
|
|
242
|
+
refs: [entity.id],
|
|
243
|
+
})
|
|
244
|
+
} catch {}
|
|
245
|
+
}
|
|
246
|
+
return counts
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export default { applyAutoEdges, refreshMemoryAutoLinks, refreshEntityMentions, AUTO_RULES }
|
|
@@ -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
|
+
}
|