dsh-memu-memory 1.2.1 → 1.2.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 +3 -1
- package/README.md +23 -8
- package/README.zh.md +16 -6
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +18 -4
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +20 -0
- package/docs/host-api.md +22 -1
- package/docs/memory-semantics.md +30 -2
- package/docs/troubleshooting.md +76 -5
- package/lib/activity-log.js +1 -1
- package/lib/backup.js +24 -2
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +1511 -153
- package/lib/consolidation-worker.js +30 -8
- package/lib/curator-evidence.js +131 -0
- package/lib/curator-policy.js +81 -0
- package/lib/curator.js +1252 -91
- package/lib/cycle.js +12 -1
- package/lib/embedding-download.js +39 -4
- package/lib/engine.js +6 -3
- package/lib/freshness.js +97 -0
- package/lib/global-graph.js +282 -0
- package/lib/graph.js +295 -11
- package/lib/inbound.js +19 -0
- package/lib/inject.js +396 -25
- package/lib/lexicon.js +1115 -0
- package/lib/local-vector-service.js +8 -6
- package/lib/managed-runtime.js +33 -2
- package/lib/memory.js +365 -34
- package/lib/memu.js +2 -2
- package/lib/migrate.js +83 -2
- package/lib/private-links.js +587 -0
- package/lib/private.js +32 -3
- package/lib/prompts/global-curator.md +76 -19
- package/lib/prompts/private-consolidation.coding.md +4 -1
- package/lib/prompts/private-consolidation.md +3 -1
- package/lib/prompts/private-consolidation.mixed.md +3 -1
- package/lib/prompts/private-consolidation.rp.md +3 -1
- package/lib/prompts.js +1 -1
- package/lib/rpc.js +589 -10
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +95 -1
- package/lib/text-retrieval.js +661 -0
- package/lib/text-similarity.js +36 -18
- package/lib/tools.js +168 -10
- package/lib/webui/standalone.css +17 -0
- package/lib/webui/standalone.js +2 -0
- package/package.json +1 -1
- package/scripts/acceptance-local.mjs +8 -5
- package/scripts/curator-pair-calibrate.mjs +259 -0
- package/scripts/drive-session.mjs +853 -0
- package/scripts/lexicon-calibrate.mjs +230 -0
- package/scripts/lexicon-dedupe.mjs +318 -0
- package/scripts/mock-llm.mjs +903 -0
- package/tests/absorb-review.test.mjs +353 -0
- package/tests/appendix-b2.test.mjs +2 -2
- package/tests/client-export.test.mjs +520 -0
- package/tests/client-render.test.mjs +32 -4
- package/tests/consolidation-fork.test.mjs +14 -12
- package/tests/consolidation-snapshot.test.mjs +39 -0
- package/tests/curator-absorb.test.mjs +443 -0
- package/tests/curator-calibrate.test.mjs +173 -0
- package/tests/curator-clusters.test.mjs +281 -0
- package/tests/curator-commit.test.mjs +52 -5
- package/tests/curator-evidence.test.mjs +102 -0
- package/tests/curator-link.test.mjs +316 -0
- package/tests/curator-pairing.test.mjs +252 -0
- package/tests/curator-probe.test.mjs +15 -6
- package/tests/curator-review-mode.test.mjs +314 -0
- package/tests/disclosure.test.mjs +2 -1
- package/tests/entity-merge.test.mjs +261 -0
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
- package/tests/fixtures/lexicon-stub.mjs +284 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/graph-cascade.test.mjs +35 -2
- package/tests/graph.test.mjs +96 -0
- package/tests/help-page.test.mjs +415 -0
- package/tests/inbound.test.mjs +6 -3
- package/tests/inject-guide.test.mjs +28 -0
- package/tests/inject.test.mjs +157 -5
- package/tests/injection-chain.test.mjs +176 -0
- package/tests/lexicon-calibrate.test.mjs +48 -0
- package/tests/lexicon-dedupe.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +179 -0
- package/tests/lexicon-inject.test.mjs +410 -0
- package/tests/lexicon-perf.test.mjs +436 -0
- package/tests/lexicon-ui.test.mjs +547 -0
- package/tests/lexicon.test.mjs +922 -0
- package/tests/managed-runtime.test.mjs +32 -0
- package/tests/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/private-links.test.mjs +445 -0
- package/tests/prompts.test.mjs +35 -0
- package/tests/recall-dedup.test.mjs +33 -4
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/tool-schema.test.mjs +1 -1
- package/tests/tools.test.mjs +112 -3
- package/tests/webui-auth.test.mjs +352 -2
- package/tests/webui.test.mjs +188 -0
package/lib/rpc.js
CHANGED
|
@@ -11,16 +11,17 @@ import { commit } from './memu.js'
|
|
|
11
11
|
import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
|
|
12
12
|
import { normalizeMemoryContext } from './context.js'
|
|
13
13
|
import { requestPrivateConsolidation } from './private.js'
|
|
14
|
-
import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs } from './curator.js'
|
|
14
|
+
import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb } from './curator.js'
|
|
15
15
|
import { maybeMigrateLibraries } from './migrate.js'
|
|
16
16
|
import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
|
|
17
17
|
import { statsView } from './stats.js'
|
|
18
18
|
import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
|
|
19
19
|
import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
|
|
20
20
|
import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
|
|
21
|
-
import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
|
|
21
|
+
import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
|
|
22
22
|
import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
|
|
23
23
|
import { listEvents, logStats, clearEvents } from './activity-log.js'
|
|
24
|
+
import { warn } from './paths.js'
|
|
24
25
|
|
|
25
26
|
const ENDPOINT = '/dsh-memu-memory'
|
|
26
27
|
|
|
@@ -54,6 +55,293 @@ function requireSessionId(payload) {
|
|
|
54
55
|
return id.trim()
|
|
55
56
|
}
|
|
56
57
|
|
|
58
|
+
// Browser-facing library routes are authorized at the HTTP boundary. Direct
|
|
59
|
+
// dispatch callers intentionally keep the historical API and do not pass an
|
|
60
|
+
// authorization context. A session id is only trusted when its existing host
|
|
61
|
+
// binding names the exact target library; requests without a session id must
|
|
62
|
+
// go through the host's standalone/transfer callback.
|
|
63
|
+
//
|
|
64
|
+
// The map is the complete audit of library-addressed endpoints (§10 P0): every
|
|
65
|
+
// entry's dispatch consumes `payload.libraryId` — or, for updateMemory and
|
|
66
|
+
// archiveMemory, falls back to the same persisted session binding that
|
|
67
|
+
// `routeLibraryId` resolves — so the target authorized here is exactly the
|
|
68
|
+
// target dispatch works on. Endpoints that are session- or host-scoped
|
|
69
|
+
// (getState, getSidebarState, initSession, setLibrary, setFolderPolicy, engine
|
|
70
|
+
// and settings management, …) are not library-addressed: their credential is
|
|
71
|
+
// the host's own requestRejection plus, for session-scoped reads, the session
|
|
72
|
+
// id the host itself provided.
|
|
73
|
+
const LIBRARY_ROUTE_OPERATIONS = new Map([
|
|
74
|
+
['renameLibrary', 'rename'], ['archiveLibrary', 'archive'], ['deleteLibrary', 'delete'], ['restoreLibrary', 'restore'],
|
|
75
|
+
['browseLibrary', 'read'], ['getMemory', 'read'], ['getStats', 'read'], ['addMemory', 'write'], ['updateMemory', 'write'],
|
|
76
|
+
['importMemories', 'import'], ['exportLibrary', 'export'], ['getAttachment', 'attachment.read'],
|
|
77
|
+
['browseWall', 'read'], ['getGraph', 'read'], ['listEntities', 'read'], ['createEntity', 'write'], ['renameEntity', 'write'],
|
|
78
|
+
['deleteEntity', 'write'], ['mergeEntities', 'write'], ['suggestEntityMerges', 'read'],
|
|
79
|
+
['linkEntries', 'write'], ['unlinkEntry', 'write'], ['getRelationship', 'read'], ['updateRelationship', 'write'],
|
|
80
|
+
['listReviews', 'read'], ['resolveReview', 'write'], ['lexiconList', 'read'], ['lexiconSearch', 'read'], ['lexiconAdd', 'write'],
|
|
81
|
+
['lexiconUpdate', 'write'], ['lexiconDelete', 'write'], ['lexiconArchive', 'write'], ['lexiconRestore', 'write'],
|
|
82
|
+
['archiveMemory', 'archive'], ['deleteMemory', 'delete'],
|
|
83
|
+
])
|
|
84
|
+
|
|
85
|
+
function routeLibraryId(endpoint, payload) {
|
|
86
|
+
const explicit = typeof payload?.libraryId === 'string' ? payload.libraryId.trim() : ''
|
|
87
|
+
if (explicit) return explicit
|
|
88
|
+
// These endpoints deliberately support session-scoped operation without an
|
|
89
|
+
// explicit libraryId. Resolve the target only from the persisted binding.
|
|
90
|
+
if (payload?.sessionId !== undefined) {
|
|
91
|
+
if (typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) return null
|
|
92
|
+
return getSessionBinding(payload.sessionId.trim())?.libraryId || null
|
|
93
|
+
}
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let capabilityAbsentWarned = false
|
|
98
|
+
|
|
99
|
+
// One capability gate for both routes: absent callback falls back to the HTTP
|
|
100
|
+
// boundary (requestRejection) and warns once; a present callback is strict true.
|
|
101
|
+
// Keeping one helper makes the session-first / capability-second order identical
|
|
102
|
+
// in the global queue and the library routes.
|
|
103
|
+
async function authorizeWithCapability(connection, req, { libraryId, operation, label }) {
|
|
104
|
+
if (typeof connection?.authorizeLibrary !== 'function') {
|
|
105
|
+
if (!capabilityAbsentWarned) {
|
|
106
|
+
capabilityAbsentWarned = true
|
|
107
|
+
try { warn(`dsh-memu-memory: host does not implement connection.authorizeLibrary; ${label} falls back to the HTTP boundary (requestRejection)`) } catch {}
|
|
108
|
+
}
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
return (await connection.authorizeLibrary(req, { libraryId, operation })) === true
|
|
113
|
+
} catch {
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Global review queue (listReviews/resolveReview without an explicit libraryId)
|
|
119
|
+
// has no private-library target, so it cannot be authorized as a library route.
|
|
120
|
+
// Embedded requests keep the session-level semantics: the queue is visible to
|
|
121
|
+
// conversations, and a write (resolveReview) additionally demands the session
|
|
122
|
+
// exists and is still bound. In both scopes a session id is only a credential
|
|
123
|
+
// while its persisted binding names a library — an empty or dangling id is
|
|
124
|
+
// never one. Standalone requests are the management plane and fail closed on
|
|
125
|
+
// the host's `review.manage` grant: a missing callback (current host) falls back
|
|
126
|
+
// to the HTTP boundary, while a present callback must return strict true.
|
|
127
|
+
async function authorizeGlobalReviewRoute(connection, req, endpoint, payload) {
|
|
128
|
+
if (payload?.sessionId !== undefined) {
|
|
129
|
+
if (typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) return false
|
|
130
|
+
return Boolean(getSessionBinding(payload.sessionId.trim())?.libraryId)
|
|
131
|
+
}
|
|
132
|
+
return authorizeWithCapability(connection, req, { libraryId: null, operation: 'review.manage', label: 'global review queue' })
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function authorizeLibraryRoute(connection, req, endpoint, payload, libraryId = routeLibraryId(endpoint, payload)) {
|
|
136
|
+
// Review endpoints are dual-scope: without an explicit libraryId they address
|
|
137
|
+
// the global curator queue, which follows its own management model.
|
|
138
|
+
if ((endpoint === 'listReviews' || endpoint === 'resolveReview') && !String(payload?.libraryId || '').trim()) {
|
|
139
|
+
return authorizeGlobalReviewRoute(connection, req, endpoint, payload)
|
|
140
|
+
}
|
|
141
|
+
if (!LIBRARY_ROUTE_OPERATIONS.has(endpoint)) return true
|
|
142
|
+
// Session-bound requests are checked first: a valid binding must name the exact
|
|
143
|
+
// target library, and a present-but-unresolvable session is a bad credential
|
|
144
|
+
// (never a reason to fall back to the host callback). Without a session, the
|
|
145
|
+
// capability decides — including the explicit no-library aggregate read.
|
|
146
|
+
if (payload?.sessionId !== undefined) {
|
|
147
|
+
if (typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) return false
|
|
148
|
+
if (!libraryId) return false
|
|
149
|
+
const binding = getSessionBinding(payload.sessionId.trim())
|
|
150
|
+
return Boolean(binding?.libraryId && binding.libraryId === libraryId)
|
|
151
|
+
}
|
|
152
|
+
return authorizeWithCapability(connection, req, {
|
|
153
|
+
libraryId,
|
|
154
|
+
operation: LIBRARY_ROUTE_OPERATIONS.get(endpoint),
|
|
155
|
+
label: 'library-level authorization',
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function rejectLibraryRoute(res) {
|
|
160
|
+
if (res.headersSent) return
|
|
161
|
+
// JSON 信封而非裸文本:standalone fetch 客户端会 response.json(),裸 "forbidden"
|
|
162
|
+
// 抛 SyntaxError(Unexpected token),用户只看到白屏而不是可读错误。
|
|
163
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
164
|
+
res.end(JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 词典核心(lib/lexicon.js)按需加载:路由注册与既有 86 个
|
|
168
|
+
// case 不能被一个尚未落地的模块卡死,集成落地后这里可以改回静态 import。
|
|
169
|
+
let lexiconModulePromise = null
|
|
170
|
+
function lexiconApi() {
|
|
171
|
+
if (!lexiconModulePromise) {
|
|
172
|
+
lexiconModulePromise = import('./lexicon.js').catch((error) => {
|
|
173
|
+
lexiconModulePromise = null
|
|
174
|
+
throw error
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
return lexiconModulePromise
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 全局图(lib/global-graph.js,F1 包):resolveReview 的 unlink 动作按需加载。
|
|
181
|
+
// 与词典核心同样的按需模式——F1 未落地时路由注册不被卡死,unlink 返回可读错误。
|
|
182
|
+
let globalGraphModulePromise = null
|
|
183
|
+
function globalGraphApi() {
|
|
184
|
+
if (!globalGraphModulePromise) {
|
|
185
|
+
globalGraphModulePromise = import('./global-graph.js').then((mod) => {
|
|
186
|
+
if (typeof mod.removeGlobalLink !== 'function') throw new Error('removeGlobalLink not exported yet')
|
|
187
|
+
return mod
|
|
188
|
+
}).catch((error) => {
|
|
189
|
+
globalGraphModulePromise = null
|
|
190
|
+
throw error
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
return globalGraphModulePromise
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// 词典 RPC 的库映射(§4.1):显式 libraryId 必须是已存在的库——不信任客户端任意
|
|
197
|
+
// id——否则回落到会话绑定,与 case 'listReviews' 的入口模式一致。
|
|
198
|
+
function lexiconLibraryId(payload) {
|
|
199
|
+
const id = String(payload?.libraryId || '').trim()
|
|
200
|
+
if (id) {
|
|
201
|
+
if (!getLibrary(id)) throw new Error('library not found')
|
|
202
|
+
if (payload?.sessionId !== undefined) {
|
|
203
|
+
const sessionId = requireSessionId(payload)
|
|
204
|
+
const binding = getSessionBinding(sessionId)
|
|
205
|
+
if (binding?.libraryId !== id) throw new Error('session is not authorized for this memory library')
|
|
206
|
+
}
|
|
207
|
+
return id
|
|
208
|
+
}
|
|
209
|
+
const binding = getSessionBinding(requireSessionId(payload))
|
|
210
|
+
if (!binding?.libraryId || !getLibrary(binding.libraryId)) throw new Error('session is not bound to a memory library')
|
|
211
|
+
return binding.libraryId
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function lexiconTermView(e) {
|
|
215
|
+
return {
|
|
216
|
+
id: e.id,
|
|
217
|
+
term: e.term,
|
|
218
|
+
kind: e.kind || 'term',
|
|
219
|
+
meaning: String(e.meaning || '').slice(0, 2000),
|
|
220
|
+
usage: String(e.usage || '').slice(0, 800),
|
|
221
|
+
aliases: Array.isArray(e.aliases) ? e.aliases.slice(0, 20) : [],
|
|
222
|
+
examples: Array.isArray(e.examples) ? e.examples.slice(0, 8) : [],
|
|
223
|
+
context: e.context || {},
|
|
224
|
+
knownBy: Array.isArray(e.knownBy) ? e.knownBy : [],
|
|
225
|
+
visibility: e.visibility || 'shared',
|
|
226
|
+
sensitivity: e.sensitivity || 'normal',
|
|
227
|
+
strength: typeof e.strength === 'number' ? e.strength : null,
|
|
228
|
+
confidence: typeof e.confidence === 'number' ? e.confidence : null,
|
|
229
|
+
status: e.status || 'active',
|
|
230
|
+
source: e.source || 'user',
|
|
231
|
+
evidence: Array.isArray(e.evidence) ? e.evidence.slice(0, 6) : [],
|
|
232
|
+
sourceMemoryId: e.sourceMemoryId || null,
|
|
233
|
+
hitCounts: e.hitCounts && typeof e.hitCounts === 'object' ? e.hitCounts : { candidate: 0, injection: 0, query: 0 },
|
|
234
|
+
lastInjectedAt: e.lastInjectedAt || null,
|
|
235
|
+
createdAt: e.createdAt || null,
|
|
236
|
+
updatedAt: e.updatedAt || null,
|
|
237
|
+
reviewedAt: e.reviewedAt || null,
|
|
238
|
+
reviewedBy: e.reviewedBy || null,
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 导入合并(§4.4)。冲突判定用核心层自己的 normalizeLexeme(与存储同源,零漂移):
|
|
243
|
+
// 先在本侧把包内词面对到既有词条,active 且 sensitive 的既有词条永不覆盖——跳过并
|
|
244
|
+
// 在结果里报告 skipped。导入以用户来源写入,所以其余词条直接应用字段(§2.1 起不再
|
|
245
|
+
// 产生 pending revision);真正需要守的是墓碑:rejected 是内部防重放墓碑,导入既不
|
|
246
|
+
// 恢复背包里的 rejected 行,也不复活库里已有的 rejected 词条。legacy pending 按启动
|
|
247
|
+
// 迁移的同一口径收口(新提案 → active、敏感 → archived、revision 草稿 → archived)。
|
|
248
|
+
const LEXICON_KINDS = ['slang', 'meme', 'trigger', 'term']
|
|
249
|
+
// 导入包里可能出现的状态:pending/rejected 是 legacy/墓碑,只用于识别并按下面的口径
|
|
250
|
+
// 收口;公开生命周期只有 active / archived。
|
|
251
|
+
const LEXICON_STATUSES = ['pending', 'active', 'rejected', 'archived']
|
|
252
|
+
const LEXICON_PUBLIC_STATUSES = ['active', 'archived']
|
|
253
|
+
// 字段长度策略与核心 lib/lexicon.js 的直接写入完全统一(§10 P2:同一把尺):
|
|
254
|
+
// meaning/usage/aliases/examples 超长一律按核心的 clip 落地,导入分支不再做自己的
|
|
255
|
+
// 长度拒绝;唯一例外是 term 本身——term 是唯一键,截断会破坏唯一性,所以超长或
|
|
256
|
+
// 规范化后为空的 term 由核心 upsert 抛 typed error(LEXICON_INVALID_TERM),该条
|
|
257
|
+
// 进 failed。
|
|
258
|
+
|
|
259
|
+
async function mergeLexiconImport(libraryId, member) {
|
|
260
|
+
if (!member || typeof member !== 'object' || Array.isArray(member)) throw new Error('lexicon member must be an object')
|
|
261
|
+
if (!Array.isArray(member.terms)) throw new Error('lexicon member has no "terms" array')
|
|
262
|
+
if (member.terms.length > 5000) throw new Error('lexicon member has too many terms')
|
|
263
|
+
const lexicon = await lexiconApi()
|
|
264
|
+
const normalize = typeof lexicon.normalizeLexeme === 'function' ? lexicon.normalizeLexeme : (value) => String(value ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
|
|
265
|
+
const data = lexicon.loadLexicon(libraryId)
|
|
266
|
+
const byKey = new Map()
|
|
267
|
+
for (const [termId, e] of Object.entries(data.terms || {})) {
|
|
268
|
+
for (const key of [...new Set([String(e?.normalizedTerm || ''), ...((Array.isArray(e?.normalizedAliases) ? e.normalizedAliases : []).map((a) => String(a)))])].filter(Boolean)) {
|
|
269
|
+
if (!byKey.has(key)) byKey.set(key, { termId, entry: e })
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const report = { version: 1, applied: 0, added: 0, updated: 0, revisions: 0, skipped: [], failed: [] }
|
|
273
|
+
for (const raw of member.terms) {
|
|
274
|
+
const label = typeof raw?.term === 'string' ? raw.term : ''
|
|
275
|
+
try {
|
|
276
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('term entry must be an object')
|
|
277
|
+
const term = String(raw.term || '').trim()
|
|
278
|
+
const meaning = String(raw.meaning || '').trim()
|
|
279
|
+
if (!term) throw new Error('term is required')
|
|
280
|
+
if (!meaning) throw new Error('meaning is required')
|
|
281
|
+
// 长度不再在本侧拒绝:clip 与 reject 都以核心 upsert 的策略为准(见上方注释)。
|
|
282
|
+
// term 超长/规范化为空由 upsert 抛 LEXICON_INVALID_TERM,整条进 failed。
|
|
283
|
+
const kind = raw.kind == null || raw.kind === '' ? 'term' : String(raw.kind)
|
|
284
|
+
if (!LEXICON_KINDS.includes(kind)) throw new Error(`unknown lexicon kind: ${kind}`)
|
|
285
|
+
const aliases = raw.aliases == null ? undefined : raw.aliases
|
|
286
|
+
const examples = raw.examples == null ? undefined : raw.examples
|
|
287
|
+
const keys = [...new Set([String(raw.normalizedTerm || ''), normalize(term), ...((Array.isArray(raw.aliases) ? raw.aliases : []).map(normalize))])].filter(Boolean)
|
|
288
|
+
const target = keys.map((key) => byKey.get(key)).find(Boolean) || null
|
|
289
|
+
const status = raw.status == null || raw.status === '' ? 'active' : String(raw.status)
|
|
290
|
+
if (!LEXICON_STATUSES.includes(status)) throw new Error(`unknown lexicon status: ${status}`)
|
|
291
|
+
// 墓碑(§2.1):rejected 是内部防重放墓碑,导入是恢复路径也不能把它洗回生命周期;
|
|
292
|
+
// 库里已有同词墓碑时同样跳过——用户来源的 upsert 会复活它并清掉拒绝指纹。
|
|
293
|
+
if (status === 'rejected') {
|
|
294
|
+
report.skipped.push({ term: label || term, reason: 'rejected terms are internal tombstones and are not restored by import' })
|
|
295
|
+
continue
|
|
296
|
+
}
|
|
297
|
+
const targetStatus = target ? (target.entry?.status || 'active') : null
|
|
298
|
+
if (targetStatus === 'rejected') {
|
|
299
|
+
report.skipped.push({ term: label || term, termId: target.termId, reason: 'a rejected tombstone is never resurrected by import' })
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
if (targetStatus === 'active' && target.entry?.sensitivity === 'sensitive') {
|
|
303
|
+
report.skipped.push({ term: label || term, termId: target.termId, reason: 'an active sensitive term is never overwritten by import' })
|
|
304
|
+
continue
|
|
305
|
+
}
|
|
306
|
+
// legacy pending 与 migrateLegacyLexiconStatuses 同一口径(§2.1):新提案 → active
|
|
307
|
+
// (敏感 → archived),revision 草稿 → archived。新写只有公开两态。
|
|
308
|
+
const sensitive = raw.sensitivity === 'sensitive' || (kind === 'trigger' && raw.sensitivity !== 'normal')
|
|
309
|
+
const effectiveStatus = status === 'pending' ? (raw.revisionOf || sensitive ? 'archived' : 'active') : status
|
|
310
|
+
// 收口成 archived 的 legacy 行如果撞上同词的 active 正条,user upsert 会把正条改写
|
|
311
|
+
// 并归档(撞线语义)——迁移会保留正条,这里也跳过草稿,不让它覆盖正条。
|
|
312
|
+
if (status === 'pending' && effectiveStatus === 'archived' && targetStatus === 'active') {
|
|
313
|
+
report.skipped.push({ term: label || term, termId: target.termId, reason: 'legacy pending draft skipped: its active target must not be overwritten by import' })
|
|
314
|
+
continue
|
|
315
|
+
}
|
|
316
|
+
const out = await lexicon.upsertLexiconTerm({
|
|
317
|
+
libraryId,
|
|
318
|
+
term,
|
|
319
|
+
kind,
|
|
320
|
+
meaning,
|
|
321
|
+
usage: raw.usage ?? undefined,
|
|
322
|
+
aliases,
|
|
323
|
+
examples,
|
|
324
|
+
context: raw.context ?? undefined,
|
|
325
|
+
knownBy: raw.knownBy ?? undefined,
|
|
326
|
+
visibility: raw.visibility ?? undefined,
|
|
327
|
+
sensitivity: raw.sensitivity ?? undefined,
|
|
328
|
+
confidence: raw.confidence ?? undefined,
|
|
329
|
+
evidence: raw.evidence ?? undefined,
|
|
330
|
+
source: 'user',
|
|
331
|
+
status: effectiveStatus,
|
|
332
|
+
})
|
|
333
|
+
report.applied += 1
|
|
334
|
+
if (out?.created === false) report.updated += 1
|
|
335
|
+
else report.added += 1
|
|
336
|
+
// revisions 在当前生命周期恒为 0(§2.1 不再生成 pending revision);字段保留只为报告
|
|
337
|
+
// 形状稳定,旧客户端继续拿到一个数字。
|
|
338
|
+
} catch (error) {
|
|
339
|
+
report.failed.push({ term: label, reason: String(error?.message || error).slice(0, 300) })
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return report
|
|
343
|
+
}
|
|
344
|
+
|
|
57
345
|
// List one library's memories. Retrieval needs the MemU engine, but the sidecar
|
|
58
346
|
// index holds the same rows, so an engine that is still installing (or broken)
|
|
59
347
|
// degrades to the index instead of failing the browser.
|
|
@@ -601,6 +889,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
601
889
|
'shortTermTtlHours',
|
|
602
890
|
'sidebarSettings', 'visionCaptionEnabled',
|
|
603
891
|
'inboundToolNames',
|
|
892
|
+
// 全局提炼的审核模式(spec §6.1):恢复默认 = 回到 auto,不保留全审状态。
|
|
893
|
+
'curatorReviewMode',
|
|
894
|
+
// 工单 C/D/E 的调参:没进这张表的 key 会被静默丢弃,设置页就成了死控件。
|
|
895
|
+
'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
|
|
896
|
+
'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
|
|
604
897
|
]) patch[key] = DEFAULT_SETTINGS[key]
|
|
605
898
|
return updateSettings(patch)
|
|
606
899
|
}
|
|
@@ -618,6 +911,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
618
911
|
'memoryMode', 'memoryBackend', 'habitsInjection', 'purgeArchivedAfterDays',
|
|
619
912
|
'shortTermTtlHours',
|
|
620
913
|
'sidebarSettings', 'visionCaptionEnabled', 'inboundToolNames',
|
|
914
|
+
// 全局提炼的审核模式(spec §6.1):不进 allowlist 的 patch 会被静默丢弃。
|
|
915
|
+
'curatorReviewMode',
|
|
916
|
+
// 工单 C/D/E:未了之事复提节奏、时效提示、日期唤醒。缺一个就是设置页写了不生效。
|
|
917
|
+
'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
|
|
918
|
+
'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
|
|
621
919
|
])
|
|
622
920
|
const clean = {}
|
|
623
921
|
for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
|
|
@@ -832,6 +1130,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
832
1130
|
// The payload may be the parsed export (memories array) or the raw file text.
|
|
833
1131
|
let memories = payload?.memories
|
|
834
1132
|
let graphData = payload?.graph || null
|
|
1133
|
+
let lexiconData = payload?.lexicon && typeof payload.lexicon === 'object' && !Array.isArray(payload.lexicon) ? payload.lexicon : null
|
|
835
1134
|
let missingAttachments = 0
|
|
836
1135
|
if (payload?.archiveBase64) {
|
|
837
1136
|
const archive = importMediaBundle(id, Buffer.from(String(payload.archiveBase64), 'base64'))
|
|
@@ -843,7 +1142,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
843
1142
|
let parsed = null
|
|
844
1143
|
try { parsed = JSON.parse(memories) } catch { throw new Error('that file is not valid JSON') }
|
|
845
1144
|
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
846
|
-
if (Array.isArray(parsed.memories)) {
|
|
1145
|
+
if (Array.isArray(parsed.memories)) {
|
|
1146
|
+
memories = parsed.memories
|
|
1147
|
+
graphData = parsed.graph || null
|
|
1148
|
+
lexiconData = lexiconData || (parsed.lexicon && typeof parsed.lexicon === 'object' && !Array.isArray(parsed.lexicon) ? parsed.lexicon : null)
|
|
1149
|
+
}
|
|
847
1150
|
else throw new Error('this JSON has no "memories" array')
|
|
848
1151
|
} else if (Array.isArray(parsed)) memories = parsed
|
|
849
1152
|
else throw new Error('this JSON has no "memories" array')
|
|
@@ -851,19 +1154,35 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
851
1154
|
if (!Array.isArray(memories)) throw new Error('memories must be an array')
|
|
852
1155
|
const result = await importMemories({ libraryId: id, memories })
|
|
853
1156
|
if (graphData && result.idMap) restoreGraphData(id, graphData, result.idMap)
|
|
854
|
-
|
|
1157
|
+
// 词典是版本化 member(§4.4):包里带了才合并恢复;term 冲突(规范化后同词)
|
|
1158
|
+
// 更新既有词条,active+sensitive 一律跳过并上报,超长字段按核心 clip 落地、
|
|
1159
|
+
// term 本身越界/归一化为空才进 failed。
|
|
1160
|
+
const lexiconReport = lexiconData ? await mergeLexiconImport(id, lexiconData) : null
|
|
1161
|
+
const value = { libraryId: id, ...result, missingAttachments }
|
|
1162
|
+
return lexiconReport ? { ...value, lexicon: lexiconReport } : value
|
|
855
1163
|
}
|
|
856
1164
|
case 'exportLibrary': {
|
|
857
1165
|
const id = String(payload?.libraryId || '')
|
|
858
1166
|
const lib = getLibrary(id)
|
|
859
1167
|
if (!lib) throw new Error('library not found')
|
|
860
1168
|
const index = loadPrivateIndex(id)
|
|
1169
|
+
// §4.4:导出包带上版本化词典 member。词典核心暂时不可用(未落地/文件损坏)
|
|
1170
|
+
// 时导出不能整个失败——报 unavailable,让导入端知道这份包没有词典。
|
|
1171
|
+
let lexiconMember = { version: 1, terms: [], unavailable: null }
|
|
1172
|
+
try {
|
|
1173
|
+
const lexicon = await lexiconApi()
|
|
1174
|
+
const data = lexicon.loadLexicon(id)
|
|
1175
|
+
lexiconMember = { version: 1, terms: Object.entries(data.terms || {}).map(([termId, e]) => ({ id: termId, ...e })) }
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
lexiconMember.unavailable = String(error?.message || error).slice(0, 300)
|
|
1178
|
+
}
|
|
861
1179
|
const exported = {
|
|
862
1180
|
format: 'dsh-memu-memory-library@1',
|
|
863
1181
|
exportedAt: new Date().toISOString(),
|
|
864
1182
|
library: { id: lib.id, name: lib.name, scopeKey: lib.scopeKey || null, domain: lib.domain || null },
|
|
865
1183
|
memories: Object.entries(index.entries || {}).map(([memId, e]) => ({ id: memId, ...e })),
|
|
866
1184
|
graph: graphExport(id),
|
|
1185
|
+
lexicon: lexiconMember,
|
|
867
1186
|
}
|
|
868
1187
|
if (payload?.includeAttachments === true) {
|
|
869
1188
|
if (payload?.delivery === 'download') return { filename: `${id}.zip`, downloadUrl: `/dsh-memu-memory/export/${id}.zip` }
|
|
@@ -890,6 +1209,15 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
890
1209
|
expiresAt: entry.expiresAt || null, openLoop: entry.openLoop === true,
|
|
891
1210
|
marginalized: entry.marginalized === true, decay: Math.min(1, decayStrength(entry)),
|
|
892
1211
|
tags: Array.isArray(entry.tags) ? entry.tags : [], attachmentCount: entry.attachments?.length || 0,
|
|
1212
|
+
// Global entries carry F1/F2 metadata; the wall drawer reads it from the
|
|
1213
|
+
// same bounded item payload instead of a second full-body request.
|
|
1214
|
+
...(lib ? {} : {
|
|
1215
|
+
links: Array.isArray(entry.links) ? entry.links : [],
|
|
1216
|
+
absorbedFrom: Array.isArray(entry.absorbedFrom) ? entry.absorbedFrom : [],
|
|
1217
|
+
absorbedAt: entry.absorbedAt || null,
|
|
1218
|
+
representativeId: entry.representativeId || null,
|
|
1219
|
+
absorbOpId: entry.absorbOpId || null,
|
|
1220
|
+
}),
|
|
893
1221
|
// The first usable image becomes the card cover; the drawer requests
|
|
894
1222
|
// the full gallery from getMemory. Secret entries come back hidden
|
|
895
1223
|
// (no url), so the wall never fetches their pixels.
|
|
@@ -900,7 +1228,13 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
900
1228
|
for (const library of libraries) {
|
|
901
1229
|
try { collect(loadPrivateIndex(library.id), library) } catch { errors.push({ libraryId: library.id, error: 'memory index unavailable' }) }
|
|
902
1230
|
}
|
|
903
|
-
|
|
1231
|
+
// Global memory is shared across libraries and the wall always exposes a
|
|
1232
|
+
// global scope. Include it even when a single private library was selected:
|
|
1233
|
+
// the single-library authorization covers that library's private rows, and
|
|
1234
|
+
// global rows are not library-private data. Without this, the standalone
|
|
1235
|
+
// single-library fallback (hosts that deny the all-libraries read) shows an
|
|
1236
|
+
// empty global scope.
|
|
1237
|
+
try { collect(loadGlobalIndex(), null) } catch { errors.push({ libraryId: null, error: 'global index unavailable' }) }
|
|
904
1238
|
items.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')))
|
|
905
1239
|
const limit = Math.max(1, Math.min(1000, Number(payload?.limit) || 300))
|
|
906
1240
|
return { items: items.slice(0, limit), total: items.length, libraries, errors }
|
|
@@ -915,6 +1249,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
915
1249
|
return renameEntity(payload || {})
|
|
916
1250
|
case 'deleteEntity':
|
|
917
1251
|
return deleteEntity(payload || {})
|
|
1252
|
+
case 'mergeEntities':
|
|
1253
|
+
return mergeEntities(payload || {})
|
|
1254
|
+
case 'suggestEntityMerges':
|
|
1255
|
+
return suggestEntityMerges(payload || {})
|
|
918
1256
|
case 'linkEntries':
|
|
919
1257
|
return linkEntries(payload || {})
|
|
920
1258
|
case 'unlinkEntry':
|
|
@@ -945,6 +1283,13 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
945
1283
|
source: f.entry?.source || 'inferred',
|
|
946
1284
|
status: f.entry?.status || 'active',
|
|
947
1285
|
content: String(f.content || '').slice(0, 600),
|
|
1286
|
+
// F1/F2 metadata: the global page renders link/absorb tags and the undo
|
|
1287
|
+
// button from these fields; without them every tag is silently absent.
|
|
1288
|
+
links: Array.isArray(f.entry?.links) ? f.entry.links : [],
|
|
1289
|
+
absorbedFrom: Array.isArray(f.entry?.absorbedFrom) ? f.entry.absorbedFrom : [],
|
|
1290
|
+
absorbedAt: f.entry?.absorbedAt || null,
|
|
1291
|
+
representativeId: f.entry?.representativeId || null,
|
|
1292
|
+
absorbOpId: f.entry?.absorbOpId || null,
|
|
948
1293
|
})),
|
|
949
1294
|
}
|
|
950
1295
|
} catch (error) {
|
|
@@ -957,6 +1302,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
957
1302
|
confidence: e.confidence ?? null, status: e.status || 'active', content: String(e.content || '').slice(0, 600),
|
|
958
1303
|
evidence: e.evidence || [], layer: e.layer || 'long_term', decay: decayStrength(e),
|
|
959
1304
|
createdAt: e.createdAt || null, updatedAt: e.updatedAt || null, source: e.source || 'inferred',
|
|
1305
|
+
links: Array.isArray(e.links) ? e.links : [],
|
|
1306
|
+
absorbedFrom: Array.isArray(e.absorbedFrom) ? e.absorbedFrom : [],
|
|
1307
|
+
absorbedAt: e.absorbedAt || null,
|
|
1308
|
+
representativeId: e.representativeId || null,
|
|
1309
|
+
absorbOpId: e.absorbOpId || null,
|
|
960
1310
|
})),
|
|
961
1311
|
}
|
|
962
1312
|
}
|
|
@@ -985,18 +1335,221 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
985
1335
|
confidence: e.confidence ?? null,
|
|
986
1336
|
reviewReason: e.reviewReason || '',
|
|
987
1337
|
conflictingWith: e.conflictingWith || null,
|
|
1338
|
+
// 包 F2(spec §6.7):风险分与 pendingAbsorb 随队列下发,供 UI 打
|
|
1339
|
+
// 「集合吸收」Tag、列出来源标题并按风险排序;旧条目按缺省读取。
|
|
1340
|
+
reviewRisk: e.reviewRisk ?? null,
|
|
1341
|
+
reviewRiskReasons: Array.isArray(e.reviewRiskReasons) ? e.reviewRiskReasons : [],
|
|
1342
|
+
pendingAbsorb: e.pendingAbsorb || null,
|
|
988
1343
|
evidence: (e.evidence || []).slice(0, 6),
|
|
989
1344
|
updatedAt: e.updatedAt || null,
|
|
990
1345
|
})),
|
|
991
1346
|
}
|
|
992
1347
|
}
|
|
993
1348
|
case 'resolveReview': {
|
|
1349
|
+
// 包 F2(spec §6.7):unlink / undo-absorb 是两个全局元数据动作,不是内容复核
|
|
1350
|
+
// ——都不新增路由,仍走 resolveReview 已在的全局复核授权路径;但它们只作用于
|
|
1351
|
+
// 全局队列,带 libraryId 的调用是私有复核语义错位,直接报错。
|
|
1352
|
+
const reviewAction = String(payload?.action || '')
|
|
1353
|
+
if (reviewAction === 'unlink' || reviewAction === 'undo-absorb') {
|
|
1354
|
+
if (String(payload?.libraryId || '').trim()) {
|
|
1355
|
+
throw new Error(`${reviewAction} is a global review action; pass no libraryId`)
|
|
1356
|
+
}
|
|
1357
|
+
if (reviewAction === 'unlink') {
|
|
1358
|
+
// lib/global-graph.js(F1 包)的 removeGlobalLink,按需加载——与词典核心
|
|
1359
|
+
// 同一模式;模块缺席或未导出时抛固定错误(spec §6.7 RPC 约定)。
|
|
1360
|
+
try {
|
|
1361
|
+
const globalGraph = await globalGraphApi()
|
|
1362
|
+
return globalGraph.removeGlobalLink({
|
|
1363
|
+
linkId: payload?.linkId, fromId: payload?.fromId, toId: payload?.toId, kind: payload?.kind,
|
|
1364
|
+
})
|
|
1365
|
+
} catch (error) {
|
|
1366
|
+
if (globalGraphModulePromise) throw error
|
|
1367
|
+
throw new Error('link removal lands with F1')
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return undoGlobalAbsorb({ id: String(payload?.id || '') })
|
|
1371
|
+
}
|
|
994
1372
|
return resolveMemoryReview({
|
|
995
1373
|
libraryId: payload?.libraryId ? String(payload.libraryId) : null,
|
|
996
|
-
id: String(payload?.id || ''), action:
|
|
1374
|
+
id: String(payload?.id || ''), action: reviewAction,
|
|
997
1375
|
resolution: payload?.resolution || 'replace', reason: payload?.reason || '',
|
|
998
1376
|
content: payload?.content, title: payload?.title,
|
|
1377
|
+
sessionId: payload?.sessionId ? String(payload.sessionId) : null,
|
|
1378
|
+
})
|
|
1379
|
+
}
|
|
1380
|
+
// —— 词典:每本私有库一份;入口先由显式 id(须存在)或会话映射到库 ——
|
|
1381
|
+
case 'lexiconList': {
|
|
1382
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1383
|
+
const lexicon = await lexiconApi()
|
|
1384
|
+
const data = lexicon.loadLexicon(libraryId)
|
|
1385
|
+
// 公开两态(§2.1):pending/rejected 是内部状态与墓碑,列表永不返回。status 只接受
|
|
1386
|
+
// active / archived——未知值明确报错,别静默当成“全都要”把墓碑带出去。
|
|
1387
|
+
const requestedStatus = String(payload?.status || '').trim()
|
|
1388
|
+
if (requestedStatus && !LEXICON_PUBLIC_STATUSES.includes(requestedStatus)) {
|
|
1389
|
+
throw new Error(`unknown lexicon status: ${requestedStatus}; expected active or archived`)
|
|
1390
|
+
}
|
|
1391
|
+
// 默认 active;includeArchived 只把默认视图扩大成 active + archived,显式 status 优先。
|
|
1392
|
+
const includeArchived = payload?.includeArchived === true
|
|
1393
|
+
const status = requestedStatus || (includeArchived ? '' : 'active')
|
|
1394
|
+
const kind = String(payload?.kind || '')
|
|
1395
|
+
const sensitivity = String(payload?.sensitivity || '')
|
|
1396
|
+
const q = String(payload?.q || '').trim().toLowerCase()
|
|
1397
|
+
const rows = Object.entries(data.terms || {})
|
|
1398
|
+
.map(([termId, e]) => ({ ...e, id: termId, status: e?.status || 'active' }))
|
|
1399
|
+
.filter((e) => LEXICON_PUBLIC_STATUSES.includes(e.status))
|
|
1400
|
+
// 页签计数(§2.4)在 kind / 搜索 / 状态筛选之前算好:标签数字不随筛选跳动。
|
|
1401
|
+
const statusCounts = { active: 0, archived: 0 }
|
|
1402
|
+
for (const e of rows) statusCounts[e.status] += 1
|
|
1403
|
+
const selected = rows
|
|
1404
|
+
.filter((e) => !status || e.status === status)
|
|
1405
|
+
.filter((e) => !sensitivity || e.sensitivity === sensitivity)
|
|
1406
|
+
.filter((e) => !q || [e.term, e.meaning, e.usage, ...(Array.isArray(e.aliases) ? e.aliases : [])].join('\n').toLowerCase().includes(q))
|
|
1407
|
+
// 总览计数行只跟随 kind 以外的过滤:kind 标签上的数字才是"点了会变"的实时数。
|
|
1408
|
+
const counts = { slang: 0, meme: 0, trigger: 0, term: 0 }
|
|
1409
|
+
for (const e of selected) if (counts[e.kind] !== undefined) counts[e.kind] += 1
|
|
1410
|
+
// updatedAt 倒序;同一时间戳按 id 兜底——分页与多端渲染的顺序必须可复现。
|
|
1411
|
+
const filtered = selected.filter((e) => !kind || e.kind === kind)
|
|
1412
|
+
.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || ''))
|
|
1413
|
+
|| String(a.id).localeCompare(String(b.id)))
|
|
1414
|
+
const pageSize = Math.max(1, Math.min(200, Number(payload?.pageSize) || 50))
|
|
1415
|
+
const total = filtered.length
|
|
1416
|
+
const pages = Math.max(1, Math.ceil(total / pageSize))
|
|
1417
|
+
const page = Math.min(pages, Math.max(1, Number(payload?.page) || 1))
|
|
1418
|
+
return {
|
|
1419
|
+
libraryId,
|
|
1420
|
+
version: data.version ?? null,
|
|
1421
|
+
items: filtered.slice((page - 1) * pageSize, page * pageSize).map(lexiconTermView),
|
|
1422
|
+
total,
|
|
1423
|
+
page,
|
|
1424
|
+
pages,
|
|
1425
|
+
pageSize,
|
|
1426
|
+
counts,
|
|
1427
|
+
statusCounts,
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
case 'lexiconSearch': {
|
|
1431
|
+
const explicit = String(payload?.libraryId || '').trim()
|
|
1432
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1433
|
+
const query = String(payload?.q ?? payload?.query ?? '').trim()
|
|
1434
|
+
if (!query) throw new Error('q is required')
|
|
1435
|
+
// 会话路径带着该会话的 memoryContext 做可见过滤;设置页显式选库时是管理视角,
|
|
1436
|
+
// 与 browseLibrary 一样不按场景收窄。归档词条只有管理面显式 includeArchived 才查;
|
|
1437
|
+
// pending/rejected 由核心永远排除。
|
|
1438
|
+
const binding = explicit ? null : getSessionBinding(requireSessionId(payload))
|
|
1439
|
+
const lexicon = await lexiconApi()
|
|
1440
|
+
const hits = await lexicon.searchLexicon(
|
|
1441
|
+
{ libraryId, query, memoryContext: binding?.memoryContext || {} },
|
|
1442
|
+
{ includeArchived: payload?.includeArchived === true },
|
|
1443
|
+
)
|
|
1444
|
+
return {
|
|
1445
|
+
libraryId,
|
|
1446
|
+
items: (Array.isArray(hits) ? hits : []).map((hit) => {
|
|
1447
|
+
const e = hit?.entry && typeof hit.entry === 'object' ? hit.entry : hit
|
|
1448
|
+
return {
|
|
1449
|
+
id: hit?.id || hit?.termId || null,
|
|
1450
|
+
term: e?.term,
|
|
1451
|
+
kind: e?.kind || 'term',
|
|
1452
|
+
meaning: String(e?.meaning || '').slice(0, 2000),
|
|
1453
|
+
usage: String(e?.usage || '').slice(0, 800),
|
|
1454
|
+
aliases: Array.isArray(e?.aliases) ? e.aliases.slice(0, 20) : [],
|
|
1455
|
+
sensitivity: e?.sensitivity || 'normal',
|
|
1456
|
+
status: e?.status || 'active',
|
|
1457
|
+
strength: typeof e?.strength === 'number' ? e.strength : null,
|
|
1458
|
+
evidence: Array.isArray(e?.evidence) ? e.evidence.slice(0, 6) : [],
|
|
1459
|
+
sourceMemoryId: e?.sourceMemoryId || null,
|
|
1460
|
+
}
|
|
1461
|
+
}),
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
case 'lexiconAdd': {
|
|
1465
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1466
|
+
const term = String(payload?.term || '').trim()
|
|
1467
|
+
const kind = String(payload?.kind || '').trim()
|
|
1468
|
+
const meaning = String(payload?.meaning || '').trim()
|
|
1469
|
+
if (!term) throw new Error('term is required')
|
|
1470
|
+
if (!kind) throw new Error('kind is required')
|
|
1471
|
+
if (!meaning) throw new Error('meaning is required')
|
|
1472
|
+
const lexicon = await lexiconApi()
|
|
1473
|
+
const result = await lexicon.upsertLexiconTerm({
|
|
1474
|
+
libraryId,
|
|
1475
|
+
term,
|
|
1476
|
+
kind,
|
|
1477
|
+
meaning,
|
|
1478
|
+
usage: payload?.usage,
|
|
1479
|
+
aliases: Array.isArray(payload?.aliases) ? payload.aliases : undefined,
|
|
1480
|
+
examples: Array.isArray(payload?.examples) ? payload.examples : undefined,
|
|
1481
|
+
context: payload?.context,
|
|
1482
|
+
knownBy: payload?.knownBy,
|
|
1483
|
+
visibility: payload?.visibility,
|
|
1484
|
+
sensitivity: payload?.sensitivity,
|
|
1485
|
+
confidence: payload?.confidence,
|
|
1486
|
+
evidence: payload?.evidence,
|
|
1487
|
+
// 面板/管理入口是"用户"来源,直接落 active;敏感字段校验在核心层。
|
|
1488
|
+
source: 'user',
|
|
1489
|
+
status: 'active',
|
|
1490
|
+
})
|
|
1491
|
+
return { libraryId, ...result }
|
|
1492
|
+
}
|
|
1493
|
+
case 'lexiconUpdate': {
|
|
1494
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1495
|
+
const termId = String(payload?.termId || '').trim()
|
|
1496
|
+
if (!termId) throw new Error('termId is required')
|
|
1497
|
+
const patch = payload?.patch && typeof payload.patch === 'object' && !Array.isArray(payload.patch) ? payload.patch : {}
|
|
1498
|
+
// 只开放内容与观感字段;生命周期(归档/恢复)走 lexiconArchive / lexiconRestore,
|
|
1499
|
+
// 来源与类型不在这里改。
|
|
1500
|
+
// 与 updateMemory 同一规矩:名单外的键明确报错,不静默丢弃。
|
|
1501
|
+
const allowed = ['meaning', 'usage', 'aliases', 'examples', 'sensitivity', 'strength', 'visibility', 'context', 'knownBy']
|
|
1502
|
+
const unknown = Object.keys(patch).filter((key) => !allowed.includes(key))
|
|
1503
|
+
if (unknown.length) throw new Error(`unknown lexicon field: ${unknown.join(', ')}; editable: ${allowed.join(', ')}`)
|
|
1504
|
+
const lexicon = await lexiconApi()
|
|
1505
|
+
const data = lexicon.loadLexicon(libraryId)
|
|
1506
|
+
const existing = (data.terms || {})[termId]
|
|
1507
|
+
if (!existing) throw new Error('unknown lexicon term')
|
|
1508
|
+
// 用户来源直接应用字段(含敏感字段);同规范词的撞线语义由核心层管。
|
|
1509
|
+
const result = await lexicon.upsertLexiconTerm({
|
|
1510
|
+
libraryId,
|
|
1511
|
+
term: existing.term,
|
|
1512
|
+
kind: existing.kind,
|
|
1513
|
+
meaning: patch.meaning ?? existing.meaning,
|
|
1514
|
+
usage: patch.usage ?? existing.usage,
|
|
1515
|
+
aliases: patch.aliases ?? existing.aliases,
|
|
1516
|
+
examples: patch.examples ?? existing.examples,
|
|
1517
|
+
context: patch.context ?? existing.context,
|
|
1518
|
+
knownBy: patch.knownBy ?? existing.knownBy,
|
|
1519
|
+
visibility: patch.visibility ?? existing.visibility,
|
|
1520
|
+
sensitivity: patch.sensitivity ?? existing.sensitivity,
|
|
1521
|
+
strength: patch.strength ?? existing.strength,
|
|
1522
|
+
confidence: existing.confidence,
|
|
1523
|
+
evidence: existing.evidence,
|
|
1524
|
+
source: 'user',
|
|
999
1525
|
})
|
|
1526
|
+
return { libraryId, termId, ...result }
|
|
1527
|
+
}
|
|
1528
|
+
case 'lexiconDelete': {
|
|
1529
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1530
|
+
const termId = String(payload?.termId || '').trim()
|
|
1531
|
+
if (!termId) throw new Error('termId is required')
|
|
1532
|
+
const lexicon = await lexiconApi()
|
|
1533
|
+
const result = await lexicon.deleteLexiconTerm({ libraryId, termId })
|
|
1534
|
+
return { libraryId, ...result }
|
|
1535
|
+
}
|
|
1536
|
+
// 归档 / 恢复(§2.3):公开生命周期的两个用户动作,只承认 active↔archived;
|
|
1537
|
+
// legacy pending 由迁移收口,rejected 是墓碑(核心 typed 拒绝)。
|
|
1538
|
+
case 'lexiconArchive': {
|
|
1539
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1540
|
+
const termId = String(payload?.termId || '').trim()
|
|
1541
|
+
if (!termId) throw new Error('termId is required')
|
|
1542
|
+
const lexicon = await lexiconApi()
|
|
1543
|
+
const result = await lexicon.archiveLexiconTerm({ libraryId, termId })
|
|
1544
|
+
return { libraryId, ...result }
|
|
1545
|
+
}
|
|
1546
|
+
case 'lexiconRestore': {
|
|
1547
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1548
|
+
const termId = String(payload?.termId || '').trim()
|
|
1549
|
+
if (!termId) throw new Error('termId is required')
|
|
1550
|
+
const lexicon = await lexiconApi()
|
|
1551
|
+
const result = await lexicon.restoreLexiconTerm({ libraryId, termId })
|
|
1552
|
+
return { libraryId, ...result }
|
|
1000
1553
|
}
|
|
1001
1554
|
case 'generatePrivate': {
|
|
1002
1555
|
const sessionId = requireSessionId(payload)
|
|
@@ -1214,10 +1767,22 @@ export function registerRpc(ctx) {
|
|
|
1214
1767
|
res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
|
|
1215
1768
|
return
|
|
1216
1769
|
}
|
|
1217
|
-
const
|
|
1770
|
+
const requestUrl = new URL(req.url || '/', 'http://dsh.internal')
|
|
1771
|
+
const pathname = requestUrl.pathname
|
|
1218
1772
|
.replace(/^\/dsh-memu(?=\/|$)/, ENDPOINT)
|
|
1773
|
+
// Entry inventory (§10 P0 audit): dispatch is reachable from exactly
|
|
1774
|
+
// three places, each behind authorizeLibraryRoute — the export/import
|
|
1775
|
+
// URL routes below (authorized before any body or media read), the
|
|
1776
|
+
// GET attachment route (same), and the generic POST gate after the
|
|
1777
|
+
// envelope parse. Every other GET here serves static UI bytes or 405s;
|
|
1778
|
+
// no handler code path reaches dispatch without passing one gate.
|
|
1219
1779
|
const exportMatch = /^\/dsh-memu-memory\/export\/([A-Za-z0-9._-]+)\.zip$/.exec(pathname)
|
|
1220
1780
|
if (req.method === 'GET' && exportMatch) {
|
|
1781
|
+
const sessionId = requestUrl.searchParams.has('sessionId') ? requestUrl.searchParams.get('sessionId') : undefined
|
|
1782
|
+
if (!await authorizeLibraryRoute(c.connection, req, 'exportLibrary', { libraryId: exportMatch[1], ...(sessionId !== undefined ? { sessionId } : {}) })) {
|
|
1783
|
+
rejectLibraryRoute(res)
|
|
1784
|
+
return
|
|
1785
|
+
}
|
|
1221
1786
|
try {
|
|
1222
1787
|
const payload = await dispatch(ctx, 'exportLibrary', { libraryId: exportMatch[1] })
|
|
1223
1788
|
await streamMediaExport(exportMatch[1], payload, res)
|
|
@@ -1226,6 +1791,11 @@ export function registerRpc(ctx) {
|
|
|
1226
1791
|
}
|
|
1227
1792
|
const importMatch = /^\/dsh-memu-memory\/import\/([A-Za-z0-9._-]+)\.zip$/.exec(pathname)
|
|
1228
1793
|
if (req.method === 'POST' && importMatch) {
|
|
1794
|
+
const sessionId = requestUrl.searchParams.has('sessionId') ? requestUrl.searchParams.get('sessionId') : undefined
|
|
1795
|
+
if (!await authorizeLibraryRoute(c.connection, req, 'importMemories', { libraryId: importMatch[1], ...(sessionId !== undefined ? { sessionId } : {}) })) {
|
|
1796
|
+
rejectLibraryRoute(res)
|
|
1797
|
+
return
|
|
1798
|
+
}
|
|
1229
1799
|
try {
|
|
1230
1800
|
const bundle = await importMediaStream(importMatch[1], req)
|
|
1231
1801
|
const value = await dispatch(ctx, 'importMemories', { libraryId: importMatch[1], memories: bundle.memories, graph: bundle.graph })
|
|
@@ -1251,9 +1821,13 @@ export function registerRpc(ctx) {
|
|
|
1251
1821
|
}
|
|
1252
1822
|
const attachment = /^\/dsh-memu-memory\/attachment\/([A-Za-z0-9._-]+)\/([a-f0-9]{64})$/.exec(pathname)
|
|
1253
1823
|
if (req.method === 'GET' && attachment) {
|
|
1824
|
+
const sessionId = requestUrl.searchParams.has('sessionId') ? requestUrl.searchParams.get('sessionId') : undefined
|
|
1825
|
+
if (!await authorizeLibraryRoute(c.connection, req, 'getAttachment', { libraryId: attachment[1], ...(sessionId !== undefined ? { sessionId } : {}) })) {
|
|
1826
|
+
rejectLibraryRoute(res)
|
|
1827
|
+
return
|
|
1828
|
+
}
|
|
1254
1829
|
try {
|
|
1255
|
-
const
|
|
1256
|
-
const thumbnail = await attachmentThumbnail({ libraryId: attachment[1], sha256: attachment[2], sessionId: url.searchParams.get('sessionId') })
|
|
1830
|
+
const thumbnail = await attachmentThumbnail({ libraryId: attachment[1], sha256: attachment[2], sessionId: sessionId ?? null })
|
|
1257
1831
|
if (!thumbnail) { res.writeHead(404, { 'Cache-Control': 'no-store' }); res.end('attachment missing'); return }
|
|
1258
1832
|
res.writeHead(200, { 'Content-Type': thumbnail.mime, 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
1259
1833
|
res.end(thumbnail.data)
|
|
@@ -1323,8 +1897,13 @@ export function registerRpc(ctx) {
|
|
|
1323
1897
|
},
|
|
1324
1898
|
}
|
|
1325
1899
|
} else {
|
|
1900
|
+
const payload = envelope.payload || {}
|
|
1901
|
+
if (!await authorizeLibraryRoute(c.connection, req, endpoint, payload)) {
|
|
1902
|
+
rejectLibraryRoute(res)
|
|
1903
|
+
return
|
|
1904
|
+
}
|
|
1326
1905
|
try {
|
|
1327
|
-
result = { ok: true, value: await dispatch(ctx, endpoint,
|
|
1906
|
+
result = { ok: true, value: await dispatch(ctx, endpoint, payload) }
|
|
1328
1907
|
} catch (error) {
|
|
1329
1908
|
result = {
|
|
1330
1909
|
ok: false,
|