dsh-memu-memory 1.4.4 → 1.4.5
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 +3 -1
- package/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.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/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +30 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +93 -10
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
package/lib/inbound.js
CHANGED
|
@@ -18,6 +18,11 @@ function identity(value, label) {
|
|
|
18
18
|
return value
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
function imageReference(ref = {}) {
|
|
22
|
+
return { attachmentId: ref.attachmentId, mediaType: ref.mediaType, bytes: ref.bytes, width: ref.width, height: ref.height,
|
|
23
|
+
...(typeof ref.name === 'string' ? { name: ref.name.slice(0, 120) } : {}) }
|
|
24
|
+
}
|
|
25
|
+
|
|
21
26
|
export function normalizeInboundBatch(batch) {
|
|
22
27
|
if (!batch || batch.type !== INBOUND_TYPE || batch.version !== 1) throw new Error('unsupported inbound message protocol')
|
|
23
28
|
const batchId = identity(batch.batchId, 'batchId')
|
|
@@ -39,10 +44,7 @@ export function normalizeInboundBatch(batch) {
|
|
|
39
44
|
if (!['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(ref.mediaType)
|
|
40
45
|
|| !Number.isSafeInteger(ref.bytes) || ref.bytes <= 0
|
|
41
46
|
|| !Number.isSafeInteger(ref.width) || ref.width <= 0 || !Number.isSafeInteger(ref.height) || ref.height <= 0) throw new Error('image must use a host-admitted attachment reference')
|
|
42
|
-
return { type: 'image', attachment:
|
|
43
|
-
attachmentId: ref.attachmentId, mediaType: ref.mediaType, bytes: ref.bytes, width: ref.width, height: ref.height,
|
|
44
|
-
...(typeof ref.name === 'string' ? { name: ref.name.slice(0, 120) } : {}),
|
|
45
|
-
} }
|
|
47
|
+
return { type: 'image', attachment: imageReference(ref) }
|
|
46
48
|
}
|
|
47
49
|
throw new Error('inbound content only accepts text and host image references, not paths, URLs, tool logs or instructions')
|
|
48
50
|
})
|
|
@@ -71,7 +73,8 @@ export function nativeInboundMessage(message) {
|
|
|
71
73
|
let images = 0
|
|
72
74
|
const content = (message?.content || []).filter(block => block?.type === 'text' || block?.type === 'image')
|
|
73
75
|
.filter(block => block.type !== 'image' || ++images <= 8).slice(0, 16)
|
|
74
|
-
.map(block => block.type === 'text' ? { type: 'text', text: redactSecrets(String(block.text || '').slice(0, MAX_TEXT)) }
|
|
76
|
+
.map(block => block.type === 'text' ? { type: 'text', text: redactSecrets(String(block.text || '').slice(0, MAX_TEXT)) }
|
|
77
|
+
: { type: 'image', attachment: imageReference(block.attachment) })
|
|
75
78
|
return content.some(block => block.type === 'image' || block.text.trim()) ? { id: message.id, role: 'user', content } : null
|
|
76
79
|
}
|
|
77
80
|
|
|
@@ -155,6 +158,12 @@ export function noteNativeUserMessages(sessionId, messages, { now = Date.now(),
|
|
|
155
158
|
})
|
|
156
159
|
const outcome = getSessionBinding(sessionId)?.lastInboundOutcome
|
|
157
160
|
if (outcome?.keys?.length) finishInbound(sessionId, outcome.keys, outcome.clock, outcome)
|
|
161
|
+
// A newer batch may have replaced lastInboundOutcome before this human event
|
|
162
|
+
// arrived. Its own accepted memory receipt still proves that recall is done.
|
|
163
|
+
for (const item of getSessionBinding(sessionId)?.inbound?.pending || []) {
|
|
164
|
+
if (item.nativeAdmitted && item.memoryAdmission) finishInbound(sessionId, [item.key],
|
|
165
|
+
item.memoryAdmission.clock, item.memoryAdmission.outcome)
|
|
166
|
+
}
|
|
158
167
|
}
|
|
159
168
|
|
|
160
169
|
export function hasPendingInbound(sessionId) {
|
|
@@ -162,17 +171,29 @@ export function hasPendingInbound(sessionId) {
|
|
|
162
171
|
return Boolean(inbound?.pending?.length) && !(Date.parse(inbound.retryAt || '') > Date.now())
|
|
163
172
|
}
|
|
164
173
|
|
|
174
|
+
/** Only current native proposals or history-admitted humans can start recall. */
|
|
175
|
+
export function selectRecallableInbound(binding, messages = []) {
|
|
176
|
+
const native = new Map(messages.filter(message => message?.role === 'user' && message?.source?.kind === 'user')
|
|
177
|
+
.map(message => [message.id, nativeInboundMessage(message)]))
|
|
178
|
+
return (binding?.inbound?.pending || []).filter(item => {
|
|
179
|
+
if (item.producer !== 'host.user') return true
|
|
180
|
+
const current = native.get(item.id)
|
|
181
|
+
if (!item.nativeAdmitted && (!current || JSON.stringify(current.content) !== JSON.stringify(item.content))) return false
|
|
182
|
+
return !item.memoryAdmission || Boolean(item.mediaScope
|
|
183
|
+
&& selectMediaOccurrences(binding.pendingMedia, [item], item.mediaScope).length)
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
165
187
|
/**
|
|
166
|
-
*
|
|
188
|
+
* 本轮真实用户消息的纯文本,取自可召回的 inbound journal(pending 队列)。
|
|
167
189
|
*
|
|
168
190
|
* 词典命中的唯一文本源(docs/memory-semantics.md §8.13):队列里的每一条都是
|
|
169
191
|
* ingestInboundBatch 校验过的显式人类消息,所以插件通知、工具结果、assistant
|
|
170
192
|
* 自言自语结构上进不来。调用方要在 noteNativeUserMessages 把原生消息从 pending
|
|
171
193
|
* 摘走**之前**取(inject.js 的顺序就是这样的)。
|
|
172
194
|
*/
|
|
173
|
-
export function inboundUserTexts(binding) {
|
|
174
|
-
|
|
175
|
-
return pending
|
|
195
|
+
export function inboundUserTexts(binding, messages = []) {
|
|
196
|
+
return selectRecallableInbound(binding, messages).filter(item => !item.memoryAdmission)
|
|
176
197
|
.map(item => (Array.isArray(item?.content) ? item.content : [])
|
|
177
198
|
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
178
199
|
.map(block => block.text.trim())
|
|
@@ -192,25 +213,33 @@ export async function pendingInbound(sessionId, ctx, session) {
|
|
|
192
213
|
|
|
193
214
|
export function finishInbound(sessionId, keys, clock, outcome) {
|
|
194
215
|
const binding = getSessionBinding(sessionId)
|
|
195
|
-
if (!binding) return
|
|
216
|
+
if (!binding) return []
|
|
196
217
|
const before = journal(binding)
|
|
197
218
|
const done = new Set(keys)
|
|
198
|
-
const
|
|
199
|
-
|
|
219
|
+
const pending = before.pending.map(item => done.has(item.key) && item.producer === 'host.user' && outcome?.admitted === true
|
|
220
|
+
? { ...item, memoryAdmission: { clock, outcome: { reason: outcome.reason, injectedCount: outcome.injectedCount, admitted: true } } } : item)
|
|
221
|
+
const matched = pending.filter(item => done.has(item.key))
|
|
222
|
+
if (!matched.length) return []
|
|
200
223
|
const ready = matched.filter(item => (item.producer === 'host.user' ? item.nativeAdmitted === true : outcome?.admitted === true)
|
|
201
224
|
&& !selectMediaOccurrences(binding.pendingMedia, [item], item.mediaScope || mediaSessionScope(currentSession(sessionId), binding)).length)
|
|
202
225
|
if (ready.length !== matched.length) {
|
|
203
|
-
setSessionBinding(sessionId, { lastInboundOutcome: { ...structuredClone(outcome), status: 'proposed',
|
|
226
|
+
setSessionBinding(sessionId, { inbound: { ...before, pending }, lastInboundOutcome: { ...structuredClone(outcome), status: 'proposed',
|
|
204
227
|
keys: [...keys], clock, at: new Date().toISOString(), count: matched.length } })
|
|
205
228
|
}
|
|
206
|
-
if (!ready.length)
|
|
229
|
+
if (!ready.length) {
|
|
230
|
+
if (outcome?.admitted === true) flushState()
|
|
231
|
+
return []
|
|
232
|
+
}
|
|
207
233
|
const readyKeys = new Set(ready.map(item => item.key))
|
|
208
234
|
const claims = ready.map(item => deliveryClaim({ producer: item.producer, batchId: item.batchId }))
|
|
209
235
|
setSessionBinding(sessionId, {
|
|
210
|
-
inbound: { ...before, seen: [...new Set([...before.seen, ...readyKeys])].slice(-MAX_SEEN), claimed: [...new Set([...before.claimed, ...claims])].slice(-MAX_SEEN), pending:
|
|
236
|
+
inbound: { ...before, seen: [...new Set([...before.seen, ...readyKeys])].slice(-MAX_SEEN), claimed: [...new Set([...before.claimed, ...claims])].slice(-MAX_SEEN), pending: pending.filter(item => !readyKeys.has(item.key)), clock: Math.max(Number(before.clock || 0), Number(clock) || 0), retryAt: null },
|
|
211
237
|
lastInboundOutcome: { ...structuredClone(outcome), keys: [...keys], clock, at: new Date().toISOString(), count: ready.length },
|
|
212
238
|
})
|
|
213
239
|
flushState()
|
|
240
|
+
// The caller uses this to decide which process-local "already served" marks may be
|
|
241
|
+
// dropped. Keys that stayed pending must keep theirs, or the next step re-injects them.
|
|
242
|
+
return [...readyKeys]
|
|
214
243
|
}
|
|
215
244
|
|
|
216
245
|
export function nextMemoryClock(binding, turn) {
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import crypto from 'node:crypto'
|
|
2
|
+
import { indexReadRevision } from './state.js'
|
|
3
|
+
import { createBoundedCache } from './bounded-cache.js'
|
|
4
|
+
|
|
5
|
+
// Only ids and sort/filter heads are retained; bodies stay in the authoritative
|
|
6
|
+
// index. A page is hydrated after selection, never for the whole library.
|
|
7
|
+
const pages = createBoundedCache({ name: 'indexPages', maxBytes: 24 * 1024 * 1024, maxEntries: 32, ttlMs: 60000 })
|
|
8
|
+
|
|
9
|
+
export function memoryChanged() {
|
|
10
|
+
const error = new Error('MEMORY_CHANGED: memory changed between pages; restart from offset 0')
|
|
11
|
+
error.code = 'MEMORY_CHANGED'
|
|
12
|
+
return error
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function pageIndexSources({ sources, offset = 0, limit = null, snapshotRevision = null, viewKey = '', filter = null, domain = null, status = null, query = '' }) {
|
|
16
|
+
const revisions = sources.map(source => [source.scope || 'private', source.libraryId || null, indexReadRevision(source.index)])
|
|
17
|
+
const fingerprint = JSON.stringify([revisions, viewKey, domain || null, status || null, query || ''])
|
|
18
|
+
const revision = crypto.createHash('sha256').update(fingerprint).digest('hex')
|
|
19
|
+
if (snapshotRevision != null && snapshotRevision !== revision) throw memoryChanged()
|
|
20
|
+
// Unknown (non-admitted) objects must never share a cached directory.
|
|
21
|
+
const cacheable = revisions.every(row => row[2] !== null)
|
|
22
|
+
let directory = cacheable ? pages.get(revision) : null
|
|
23
|
+
if (!directory) {
|
|
24
|
+
const rows = []
|
|
25
|
+
const domains = new Set()
|
|
26
|
+
const counts = { active: 0, archived: 0 }
|
|
27
|
+
const needle = String(query || '').normalize('NFKC').toLowerCase()
|
|
28
|
+
for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) {
|
|
29
|
+
const source = sources[sourceIndex]
|
|
30
|
+
for (const id in source.index.entries || {}) {
|
|
31
|
+
const entry = source.index.entries[id]
|
|
32
|
+
if (filter && !filter(entry, source, id)) continue
|
|
33
|
+
const entryDomain = String(entry.domain || (source.scope === 'global' ? 'unknown' : 'general')).normalize('NFKC').trim().toLowerCase()
|
|
34
|
+
domains.add(entryDomain)
|
|
35
|
+
if (domain && entryDomain !== domain) continue
|
|
36
|
+
const entryStatus = entry.status || 'active'
|
|
37
|
+
if (status && entryStatus !== status) continue
|
|
38
|
+
if (needle && ![id, entry.title, entry.content, ...(entry.tags || [])].join(' ').normalize('NFKC').toLowerCase().includes(needle)) continue
|
|
39
|
+
counts[entryStatus === 'archived' ? 'archived' : 'active']++
|
|
40
|
+
rows.push({ id, sourceIndex, at: String(entry.updatedAt || entry.createdAt || '') })
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
rows.sort((a, b) => b.at.localeCompare(a.at) || a.id.localeCompare(b.id)
|
|
44
|
+
|| String(sources[a.sourceIndex].libraryId || '').localeCompare(String(sources[b.sourceIndex].libraryId || '')))
|
|
45
|
+
directory = { rows, domains: [...domains].sort(), counts }
|
|
46
|
+
if (cacheable) pages.set(revision, directory)
|
|
47
|
+
}
|
|
48
|
+
const start = Math.max(0, Math.floor(Number(offset) || 0))
|
|
49
|
+
const size = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.min(5000, Math.floor(Number(limit))) : null
|
|
50
|
+
return {
|
|
51
|
+
rows: directory.rows.slice(start, size ? start + size : undefined).map(({ id, sourceIndex }) => ({
|
|
52
|
+
id, source: sources[sourceIndex], entry: sources[sourceIndex].index.entries[id],
|
|
53
|
+
})),
|
|
54
|
+
total: directory.rows.length, offset: start, snapshotRevision: revision,
|
|
55
|
+
domains: directory.domains.slice(), counts: { ...directory.counts },
|
|
56
|
+
}
|
|
57
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -17,6 +17,8 @@ import { setWarnSink, warn } from './paths.js'
|
|
|
17
17
|
import { recordDiagnostic, recordErrorDiagnostic } from './diagnostics.js'
|
|
18
18
|
import { autoRepairEnvironment, runEnvironmentCheck } from './environment-check.js'
|
|
19
19
|
import { planAllRepairs, applyRepairGroups } from './entity-repair.js'
|
|
20
|
+
import { startRtIndexService } from './rt-index-service.js'
|
|
21
|
+
import { startLexiconRt } from './lexicon-rt.js'
|
|
20
22
|
|
|
21
23
|
export const name = 'dsh-memu-memory'
|
|
22
24
|
// `timer` backs ctx.interval, used by the idle/auto-curation sweep. Reading an
|
|
@@ -148,7 +150,7 @@ function startOrphanEntitySweep(ctx) {
|
|
|
148
150
|
// · attested(可证明)——窗口首尾重叠重建出的完整名**在正文里出现过**,或短名在全库正文里
|
|
149
151
|
// 从未独立于某个更长名字出现 → 自动合并。
|
|
150
152
|
// · similar(只是相似)——编辑距离 ≤2 或名字核重合(`顾清欢` 与 `顾清悦` 就是这么撞上的)→
|
|
151
|
-
//
|
|
153
|
+
// **不自动合并**,在图管理展示并由人逐个核对,诊断保留信号。
|
|
152
154
|
//
|
|
153
155
|
// 只跑一次:标记写进 `state.cycle.entityRepairVersion`(与 lastCurateAt 同族,不新造机制)。
|
|
154
156
|
// 幂等:合过的库第二次规划不出 attested 组;no-op 时一个字节都不写。
|
|
@@ -171,6 +173,22 @@ export async function runEntityRepairPass({ note = () => {}, warn = () => {}, di
|
|
|
171
173
|
return { skipped: 'setting' }
|
|
172
174
|
}
|
|
173
175
|
const plan = planAllRepairs({ listLibraries, loadPrivateIndex })
|
|
176
|
+
if (plan.partial || plan.deferred) {
|
|
177
|
+
warn(`entity repair deferred: incomplete plan (${plan.scanned}/${plan.totalEntities} entities, limit ${plan.entityLimit})`)
|
|
178
|
+
diagnose({
|
|
179
|
+
level: 'warn', scope: 'graph', code: 'ENTITY_REPAIR_DEFERRED', alert: false,
|
|
180
|
+
message: '实体碎片规划未完成,未自动合并,也未标记升级修复完成',
|
|
181
|
+
hint: '请到「图管理」按批核对候选;大库或证据不完整时不会自动合并,不能据此判断没有碎片。',
|
|
182
|
+
detail: { partial: true, deferred: true, totalEntities: plan.totalEntities,
|
|
183
|
+
totalEntitiesExact: plan.totalEntitiesExact, scanned: plan.scanned, entityLimit: plan.entityLimit,
|
|
184
|
+
deferredLibraries: plan.plans.filter((entry) => entry.deferred).length, failures: plan.failures.length },
|
|
185
|
+
source: 'entity-repair',
|
|
186
|
+
})
|
|
187
|
+
for (const failure of plan.failures) warn(`entity repair skipped ${failure.libraryId}: ${failure.error}`)
|
|
188
|
+
return { merged: 0, created: 0, protectedRows: 0, similar: plan.similar, failures: plan.failures,
|
|
189
|
+
partial: true, deferred: true, totalEntities: plan.totalEntities, totalEntitiesExact: plan.totalEntitiesExact,
|
|
190
|
+
scanned: plan.scanned, entityLimit: plan.entityLimit }
|
|
191
|
+
}
|
|
174
192
|
if (!plan.attested && !plan.similar && !plan.failures.length) {
|
|
175
193
|
setCycleState({ entityRepairVersion: ENTITY_REPAIR_VERSION, entityRepairAt: new Date().toISOString() })
|
|
176
194
|
return { skipped: 'clean', plan }
|
|
@@ -190,7 +208,7 @@ export async function runEntityRepairPass({ note = () => {}, warn = () => {}, di
|
|
|
190
208
|
diagnose({
|
|
191
209
|
level: 'warn', scope: 'graph', code: 'ENTITY_REPAIR_DEFERRED', alert: false,
|
|
192
210
|
message: '实体碎片修复顺延:图备份没成功',
|
|
193
|
-
hint: '
|
|
211
|
+
hint: '备份可用后可在下一次启动重试,或到「图管理」核对候选;本次没有写入任何改动。',
|
|
194
212
|
detail: { attested: plan.attested, similar: plan.similar },
|
|
195
213
|
source: 'entity-repair',
|
|
196
214
|
})
|
|
@@ -206,6 +224,7 @@ export async function runEntityRepairPass({ note = () => {}, warn = () => {}, di
|
|
|
206
224
|
const created = results.reduce((total, row) => total + row.created, 0)
|
|
207
225
|
const protectedRows = results.reduce((total, row) => total + row.restored, 0)
|
|
208
226
|
const failures = [...plan.failures, ...results.flatMap((row) => row.failures || [])]
|
|
227
|
+
if (failures.length) deferred = true
|
|
209
228
|
if (!deferred) {
|
|
210
229
|
setCycleState({
|
|
211
230
|
entityRepairVersion: ENTITY_REPAIR_VERSION,
|
|
@@ -227,9 +246,9 @@ export async function runEntityRepairPass({ note = () => {}, warn = () => {}, di
|
|
|
227
246
|
if (plan.similar > 0) {
|
|
228
247
|
diagnose({
|
|
229
248
|
level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_SUSPECTED', alert: true, manual: true,
|
|
230
|
-
repair:
|
|
249
|
+
repair: null,
|
|
231
250
|
message: `另有 ${plan.similar} 组实体只是名字相似,未自动合并`,
|
|
232
|
-
hint: '
|
|
251
|
+
hint: '相似不等于同一人:请到「图管理」逐个核对候选,确认后再合并。',
|
|
233
252
|
detail: { similar: plan.similar, libraries: plan.plans.filter((entry) => entry.ambiguous.length).length },
|
|
234
253
|
source: 'entity-repair',
|
|
235
254
|
})
|
|
@@ -388,7 +407,9 @@ export function apply(ctx, config) {
|
|
|
388
407
|
try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {}
|
|
389
408
|
// 同一条 warn 也进诊断档案:活动日志记的是"记忆活动",插件内部故障需要集中取证。
|
|
390
409
|
// recordDiagnostic 自己做 60 秒去重,反复出现的同一句只累加 count。
|
|
391
|
-
recordDiagnostic({ level: 'warn', scope: 'plugin', code: 'MEMU_WARNING', message, source: 'warn-sink'
|
|
410
|
+
recordDiagnostic({ level: 'warn', scope: 'plugin', code: 'MEMU_WARNING', message, source: 'warn-sink',
|
|
411
|
+
// 维护日志读不了时,诊断页要能直接给出一键修复,而不是让用户对着警告干等。
|
|
412
|
+
...(/DSH_MEMU_MAINTENANCE_JOURNAL_INVALID/.test(String(message)) ? { repair: 'repair-maintenance-journal' } : {}) })
|
|
392
413
|
})
|
|
393
414
|
|
|
394
415
|
// worker 启动失败时记录 stderr 尾部、模型目录与运行时目录,
|
|
@@ -406,7 +427,12 @@ export function apply(ctx, config) {
|
|
|
406
427
|
|
|
407
428
|
// Bookkeeping writes are coalesced on a 50ms timer. Anything still
|
|
408
429
|
// pending has to reach disk before the process goes away.
|
|
409
|
-
const flush = () => {
|
|
430
|
+
const flush = () => {
|
|
431
|
+
try { flushState() } catch (error) {
|
|
432
|
+
try { ctx.logger?.warn?.(`dsh-memu-memory: final flush failed: ${error?.message || error}`) } catch {}
|
|
433
|
+
recordErrorDiagnostic(error, { code: 'STATE_FINAL_FLUSH_FAILED', source: 'state-flush', operation: 'write', alert: false })
|
|
434
|
+
}
|
|
435
|
+
}
|
|
410
436
|
try { process.once('beforeExit', flush) } catch {}
|
|
411
437
|
if (typeof ctx.effect === 'function') {
|
|
412
438
|
ctx.effect(() => () => {
|
|
@@ -417,6 +443,7 @@ export function apply(ctx, config) {
|
|
|
417
443
|
|
|
418
444
|
try { syncPromptDefaults() } catch (error) {
|
|
419
445
|
try { ctx.logger?.warn?.(`dsh-memu-memory: prompt default sync failed: ${error?.message || error}`) } catch {}
|
|
446
|
+
recordErrorDiagnostic(error, { code: 'PROMPT_DEFAULT_SYNC_FAILED', source: 'prompt-sync', operation: 'write', alert: false })
|
|
420
447
|
}
|
|
421
448
|
|
|
422
449
|
if (typeof ctx.inject === 'function') {
|
|
@@ -451,6 +478,7 @@ export function apply(ctx, config) {
|
|
|
451
478
|
startOrphanEntitySweep(ctx),
|
|
452
479
|
startEntityRepairPass(ctx),
|
|
453
480
|
startEnvironmentHealthCheck(ctx),
|
|
481
|
+
startRtIndexService(),
|
|
454
482
|
].filter(Boolean)
|
|
455
483
|
if (typeof ctx.effect === 'function') {
|
|
456
484
|
ctx.effect(() => () => {
|
|
@@ -465,6 +493,14 @@ export function apply(ctx, config) {
|
|
|
465
493
|
// that owns the process-global surfaces may close it. Recall degrades to lexical
|
|
466
494
|
// afterwards instead of failing.
|
|
467
495
|
if (!inPreset && typeof ctx.effect === 'function') {
|
|
496
|
+
ctx.effect(() => {
|
|
497
|
+
const close = startLexiconRt()
|
|
498
|
+
return async () => {
|
|
499
|
+
try { await close() } catch {
|
|
500
|
+
try { ctx.logger?.warn?.('dsh-memu-memory: closing lexicon RT failed') } catch {}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}, 'dsh-memu-memory: lexicon RT')
|
|
468
504
|
ctx.effect(() => () => { closeEmbeddingWorkers() }, 'dsh-memu-memory: embedding workers')
|
|
469
505
|
// The resident interpreter is also process-global; leaving it behind would keep
|
|
470
506
|
// a Python process (and its sqlite handles) alive after this plugin unloads.
|
|
@@ -489,6 +525,7 @@ export function apply(ctx, config) {
|
|
|
489
525
|
ctx.effect(() => registerTurnLogRecorder(ctx), 'dsh-memu-memory: turn-log recorder')
|
|
490
526
|
} catch (error) {
|
|
491
527
|
try { ctx.logger?.warn?.(`dsh-memu-memory: turn-log recorder unavailable: ${error?.message || error}`) } catch {}
|
|
528
|
+
recordErrorDiagnostic(error, { code: 'TURN_LOG_RECORDER_FAILED', scope: 'state', source: 'turn-log-recorder', operation: 'start', alert: false })
|
|
492
529
|
}
|
|
493
530
|
}
|
|
494
531
|
|
|
@@ -502,5 +539,6 @@ export function apply(ctx, config) {
|
|
|
502
539
|
)
|
|
503
540
|
} catch (error) {
|
|
504
541
|
try { ctx.logger?.warn?.(`dsh-memu-memory: startup summary failed: ${error?.message || error}`) } catch {}
|
|
542
|
+
recordErrorDiagnostic(error, { code: 'PLUGIN_STARTUP_SUMMARY_FAILED', source: 'startup-summary', operation: 'read', alert: false })
|
|
505
543
|
}
|
|
506
544
|
}
|