dsh-memu-memory 1.3.6 → 1.3.8
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 +2 -1
- package/CHANGELOG.md +87 -0
- package/README.md +7 -7
- package/README.zh.md +7 -7
- package/docs/client-conventions.md +4 -0
- package/docs/contributing.md +2 -2
- package/docs/memory-semantics.md +10 -7
- package/docs/troubleshooting.md +132 -7
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +296 -122
- package/lib/consolidation-ledger.js +6 -2
- package/lib/consolidation-worker.js +7 -0
- package/lib/inbound.js +24 -9
- package/lib/inject.js +379 -215
- package/lib/lexicon.js +5 -0
- package/lib/local-embedding-manager.js +4 -0
- package/lib/local-vector-service.js +65 -1
- package/lib/memory.js +711 -175
- package/lib/paths.js +24 -0
- package/lib/private.js +284 -127
- package/lib/rpc.js +144 -45
- package/lib/snippet.js +49 -28
- package/lib/state.js +185 -26
- package/lib/tools.js +150 -31
- package/lib/webui/standalone.css +28 -1
- package/lib/webui.js +25 -1
- package/lib/worker-pool.js +260 -26
- package/package.json +1 -1
- package/scripts/check-i18n.mjs +19 -0
- package/scripts/recall-bench.mjs +4 -4
- package/scripts/simulate-injection.mjs +3 -0
- package/tests/activity-wiring.test.mjs +52 -0
- package/tests/client-render.test.mjs +207 -0
- package/tests/consolidation-feed.test.mjs +26 -0
- package/tests/consolidation-fork.test.mjs +618 -33
- package/tests/consolidation-snapshot.test.mjs +2 -1
- package/tests/cross-library-recall.test.mjs +156 -0
- package/tests/cue.test.mjs +15 -2
- package/tests/hybrid-recall.test.mjs +488 -0
- package/tests/inbound.test.mjs +49 -4
- package/tests/inject-conflict.test.mjs +70 -9
- package/tests/inject-guide.test.mjs +13 -1
- package/tests/inject.test.mjs +10 -0
- package/tests/injection-budget.test.mjs +101 -0
- package/tests/injection-chain.test.mjs +37 -0
- package/tests/injection-rollback.test.mjs +172 -9
- package/tests/issue2-chain.test.mjs +169 -0
- package/tests/lexicon-inject.test.mjs +33 -5
- package/tests/lexicon-ui.test.mjs +99 -2
- package/tests/managed-memory.test.mjs +625 -1
- package/tests/media.test.mjs +1 -1
- package/tests/new-session-gate.test.mjs +280 -25
- package/tests/open-loop-date.test.mjs +11 -1
- package/tests/recall-intent.test.mjs +52 -3
- package/tests/simulate-injection.test.mjs +4 -4
- package/tests/snippet.test.mjs +33 -1
- package/tests/state.test.mjs +8 -3
- package/tests/tool-schema.test.mjs +52 -0
- package/tests/tools.test.mjs +394 -0
- package/tests/webui.test.mjs +16 -2
- package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/rpc.js
CHANGED
|
@@ -19,16 +19,16 @@ import { statsView } from './stats.js'
|
|
|
19
19
|
import { recallCacheStats } from './recall-cache.js'
|
|
20
20
|
import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
|
|
21
21
|
import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
|
|
22
|
-
import { webUiHtml, WEBUI_PATH, standaloneHtml,
|
|
22
|
+
import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAssetResponse, SETTINGS_PATH } from './webui.js'
|
|
23
23
|
import { getGraph, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
|
|
24
24
|
import { generateAnchorCandidates, resetAnchorCandidatesCache } from './auto-link/candidates.js'
|
|
25
25
|
import { refreshPrivateAutoLinks } from './private-links.js'
|
|
26
26
|
import { refreshEntityMentions } from './auto-link/apply.js'
|
|
27
27
|
import { clearSuppression, suppressionSet } from './auto-link/suppression.js'
|
|
28
28
|
import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
|
|
29
|
-
import { listEvents, logStats, clearEvents } from './activity-log.js'
|
|
29
|
+
import { listEvents, logStats, clearEvents, record } from './activity-log.js'
|
|
30
30
|
import { redactSecrets, warn } from './paths.js'
|
|
31
|
-
import { GLOBAL_LEXICON_ID } from './lexicon.js'
|
|
31
|
+
import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
|
|
32
32
|
import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
|
|
33
33
|
|
|
34
34
|
const ENDPOINT = '/dsh-memu-memory'
|
|
@@ -181,6 +181,17 @@ async function authorizeLibraryRoute(connection, req, endpoint, payload, library
|
|
|
181
181
|
// must never be asked to authorize a library that does not exist, and a bound
|
|
182
182
|
// session must not be denied for naming it instead of its own library.
|
|
183
183
|
if (libraryId === GLOBAL_LEXICON_ID) return authorizeGlobalLexiconRoute(connection, req, endpoint, payload)
|
|
184
|
+
// 「全部词典」是跨库聚合管理视图,与 browseWall 的「全部记忆库」同模型:没有单库
|
|
185
|
+
// 目标,会话凭据表达不了多库授权(带 sessionId 一律拒),standalone 走 capability
|
|
186
|
+
// (libraryId=null 的聚合读);宿主拒绝多库枚举时客户端退回单库并禁用该选项。
|
|
187
|
+
if (libraryId === ALL_LEXICON_ID) {
|
|
188
|
+
if (payload?.sessionId !== undefined) return false
|
|
189
|
+
return authorizeWithCapability(connection, req, {
|
|
190
|
+
libraryId: null,
|
|
191
|
+
operation: LIBRARY_ROUTE_OPERATIONS.get(endpoint) || 'read',
|
|
192
|
+
label: 'all-lexicon aggregate read',
|
|
193
|
+
})
|
|
194
|
+
}
|
|
184
195
|
if (!LIBRARY_ROUTE_OPERATIONS.has(endpoint)) return true
|
|
185
196
|
// Session-bound requests are checked first: a valid binding must name the exact
|
|
186
197
|
// target library, and a present-but-unresolvable session is a bad credential
|
|
@@ -287,6 +298,39 @@ function lexiconTermView(e) {
|
|
|
287
298
|
}
|
|
288
299
|
}
|
|
289
300
|
|
|
301
|
+
// 词典列表的筛选 / 计数 / 排序 / 分页:单库与「全部词典」聚合共用同一把尺,避免两套
|
|
302
|
+
// 口径漂移。rows 必须已收窄到公开两态(active/archived);每条带 id/status,聚合路径
|
|
303
|
+
// 另带 libraryId/libraryName。页签计数在 kind/搜索/状态筛选之前算好,标签数字不随筛选跳动。
|
|
304
|
+
function lexiconFilterPage(rows, payload) {
|
|
305
|
+
const requestedStatus = String(payload?.status || '').trim()
|
|
306
|
+
if (requestedStatus && !LEXICON_PUBLIC_STATUSES.includes(requestedStatus)) {
|
|
307
|
+
throw new Error(`unknown lexicon status: ${requestedStatus}; expected active or archived`)
|
|
308
|
+
}
|
|
309
|
+
const includeArchived = payload?.includeArchived === true
|
|
310
|
+
const status = requestedStatus || (includeArchived ? '' : 'active')
|
|
311
|
+
const kind = String(payload?.kind || '')
|
|
312
|
+
const sensitivity = String(payload?.sensitivity || '')
|
|
313
|
+
const q = String(payload?.q || '').trim().toLowerCase()
|
|
314
|
+
const statusCounts = { active: 0, archived: 0 }
|
|
315
|
+
for (const e of rows) statusCounts[e.status] += 1
|
|
316
|
+
const selected = rows
|
|
317
|
+
.filter((e) => !status || e.status === status)
|
|
318
|
+
.filter((e) => !sensitivity || e.sensitivity === sensitivity)
|
|
319
|
+
.filter((e) => !q || [e.term, e.meaning, e.usage, ...(Array.isArray(e.aliases) ? e.aliases : [])].join('\n').toLowerCase().includes(q))
|
|
320
|
+
// 总览计数行只跟随 kind 以外的过滤:kind 标签上的数字才是"点了会变"的实时数。
|
|
321
|
+
const counts = { slang: 0, meme: 0, trigger: 0, term: 0 }
|
|
322
|
+
for (const e of selected) if (counts[e.kind] !== undefined) counts[e.kind] += 1
|
|
323
|
+
// updatedAt 倒序;同一时间戳按 id 兜底——分页与多端渲染的顺序必须可复现。
|
|
324
|
+
const filtered = selected.filter((e) => !kind || e.kind === kind)
|
|
325
|
+
.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || ''))
|
|
326
|
+
|| String(a.id).localeCompare(String(b.id)))
|
|
327
|
+
const pageSize = Math.max(1, Math.min(200, Number(payload?.pageSize) || 50))
|
|
328
|
+
const total = filtered.length
|
|
329
|
+
const pages = Math.max(1, Math.ceil(total / pageSize))
|
|
330
|
+
const page = Math.min(pages, Math.max(1, Number(payload?.page) || 1))
|
|
331
|
+
return { rows: filtered.slice((page - 1) * pageSize, page * pageSize), total, page, pages, pageSize, counts, statusCounts }
|
|
332
|
+
}
|
|
333
|
+
|
|
290
334
|
// 导入合并(§4.4)。冲突判定用核心层自己的 normalizeLexeme(与存储同源,零漂移):
|
|
291
335
|
// 先在本侧把包内词面对到既有词条,active 且 sensitive 的既有词条永不覆盖——跳过并
|
|
292
336
|
// 在结果里报告 skipped。导入以用户来源写入,所以其余词条直接应用字段(§2.1 起不再
|
|
@@ -626,6 +670,27 @@ async function decorateLogRows(ctx, rows) {
|
|
|
626
670
|
|
|
627
671
|
// 侧边栏"整理提醒"的数据源:跨会话(不按当前对话过滤),失败/成功两列分开,
|
|
628
672
|
// 每列只取最新 limit 条。失败的行带会话标题与库名,客户端用它挂跳转按钮。
|
|
673
|
+
function consolidationMeasurementView(measurement) {
|
|
674
|
+
if (measurement?.schemaVersion !== 2) return null
|
|
675
|
+
const number = value => Number.isFinite(value) && value >= 0 ? value : null
|
|
676
|
+
const values = (source, keys) => Object.fromEntries(keys.map(key => [key, number(source?.[key])]))
|
|
677
|
+
const usage = values(measurement.usage, ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens', 'requests'])
|
|
678
|
+
usage.source = measurement.usage?.source === 'assistant/message.data.usage' ? measurement.usage.source : 'unavailable'
|
|
679
|
+
usage.totalInputTokens = ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens'].every(key => usage[key] !== null)
|
|
680
|
+
? usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens : null
|
|
681
|
+
return {
|
|
682
|
+
schemaVersion: 2,
|
|
683
|
+
measurementVersion: number(measurement.measurementVersion),
|
|
684
|
+
packet: measurement.packet ? { ...values(measurement.packet, ['inputChars', 'estimatedTokens']),
|
|
685
|
+
kind: ['fork', 'handoff', 'increment', 'wrapup'].includes(measurement.packet.kind) ? measurement.packet.kind : null } : null,
|
|
686
|
+
dispatched: values(measurement.dispatched, ['inputChars', 'estimatedTokens', 'followups', 'wrapupChars']),
|
|
687
|
+
observed: values(measurement.observed, ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars', 'reasoningChars', 'estimatedTokens']),
|
|
688
|
+
usage,
|
|
689
|
+
serializationErrors: number(measurement.serializationErrors),
|
|
690
|
+
logicalToolCalls: number(measurement.logicalToolCalls),
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
629
694
|
async function consolidationFeed(ctx, payload = {}) {
|
|
630
695
|
const perColumn = Math.max(1, Math.min(20, Number(payload?.limit) || 6))
|
|
631
696
|
const rows = await decorateLogRows(ctx, listEvents({ kind: 'consolidate', limit: 80 }))
|
|
@@ -635,6 +700,8 @@ async function consolidationFeed(ctx, payload = {}) {
|
|
|
635
700
|
timedOut: detail?.timedOut === true,
|
|
636
701
|
count: detail?.count ?? null,
|
|
637
702
|
force: detail?.force === true,
|
|
703
|
+
runner: ['fork', 'worker'].includes(detail?.runner) ? detail.runner : null,
|
|
704
|
+
measurement: consolidationMeasurementView(detail?.measurement),
|
|
638
705
|
})
|
|
639
706
|
return {
|
|
640
707
|
failures: rows.filter(row => row.ok === false).slice(0, perColumn).map(slim),
|
|
@@ -1177,7 +1244,21 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1177
1244
|
if (domain !== null && !allowed.includes(domain) && !String(domain || '').startsWith('project:')) {
|
|
1178
1245
|
throw new Error('invalid domain')
|
|
1179
1246
|
}
|
|
1180
|
-
|
|
1247
|
+
// 显式答案(弹窗确认或侧栏选择器)留下 chosen 凭据:gate 见到它就不再问
|
|
1248
|
+
// (issue #2 缺陷 2 的另一半——隐式绑定与显式绑定从此可区分)。
|
|
1249
|
+
return bindingView(setSessionBinding(sessionId, { domainOverride: domain, domainSource: 'chosen' }))
|
|
1250
|
+
}
|
|
1251
|
+
case 'logClientEvent': {
|
|
1252
|
+
// WebUI 客户端侧的错误上报(issue #2):弹窗未渲染时组件 state 里的错误
|
|
1253
|
+
// 谁也看不见,落进活动日志才可发现。本路由永不抛错——日志失败不能雪上加霜。
|
|
1254
|
+
const message = String(payload?.message || 'client event').slice(0, 400)
|
|
1255
|
+
return { entry: record({
|
|
1256
|
+
kind: payload?.kind === 'error' ? 'error' : 'system',
|
|
1257
|
+
level: 'warn',
|
|
1258
|
+
sessionId: typeof payload?.sessionId === 'string' && payload.sessionId.trim() ? payload.sessionId.trim() : null,
|
|
1259
|
+
message,
|
|
1260
|
+
detail: payload?.detail == null ? null : String(payload.detail).slice(0, 2000),
|
|
1261
|
+
}) }
|
|
1181
1262
|
}
|
|
1182
1263
|
case 'setLibrary': {
|
|
1183
1264
|
const sessionId = requireSessionId(payload)
|
|
@@ -1666,53 +1747,61 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
1666
1747
|
}
|
|
1667
1748
|
// —— 词典:每本私有库一份;入口先由显式 id(须存在)或会话映射到库 ——
|
|
1668
1749
|
case 'lexiconList': {
|
|
1669
|
-
const libraryId = lexiconLibraryId(payload)
|
|
1670
1750
|
const lexicon = await lexiconApi()
|
|
1671
|
-
|
|
1672
|
-
//
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1751
|
+
// 「全部词典」:合并全局词典 + 所有私有库,只读聚合。每条带来源库 id/名,
|
|
1752
|
+
// 客户端据此把编辑/归档/删除路由回词条所属的那一本;写操作不接受 'all'。
|
|
1753
|
+
if (String(payload?.libraryId || '').trim() === ALL_LEXICON_ID) {
|
|
1754
|
+
const rows = []
|
|
1755
|
+
const errors = []
|
|
1756
|
+
const collect = (bookId, bookName) => {
|
|
1757
|
+
let data
|
|
1758
|
+
try { data = lexicon.loadLexicon(bookId) } catch (error) {
|
|
1759
|
+
// 损坏/被隔离的库跳过并留痕(fail-open 必配可观测信号),不让一本坏库
|
|
1760
|
+
// 拖垮整个聚合视图——与 browseWall 的逐库 errors 同一口径。
|
|
1761
|
+
errors.push({ libraryId: bookId, error: String(error?.message || error) })
|
|
1762
|
+
return
|
|
1763
|
+
}
|
|
1764
|
+
for (const [termId, e] of Object.entries(data.terms || {})) {
|
|
1765
|
+
const status = e?.status || 'active'
|
|
1766
|
+
if (!LEXICON_PUBLIC_STATUSES.includes(status)) continue
|
|
1767
|
+
rows.push({ ...e, id: termId, status, libraryId: bookId, libraryName: bookName })
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
collect(GLOBAL_LEXICON_ID, GLOBAL_LEXICON_ID)
|
|
1771
|
+
for (const library of listLibraries()) collect(library.id, library.name || library.id)
|
|
1772
|
+
const view = lexiconFilterPage(rows, payload)
|
|
1773
|
+
return {
|
|
1774
|
+
libraryId: ALL_LEXICON_ID,
|
|
1775
|
+
scope: 'all',
|
|
1776
|
+
version: null,
|
|
1777
|
+
items: view.rows.map((e) => ({ ...lexiconTermView(e), libraryId: e.libraryId, libraryName: e.libraryName })),
|
|
1778
|
+
total: view.total,
|
|
1779
|
+
page: view.page,
|
|
1780
|
+
pages: view.pages,
|
|
1781
|
+
pageSize: view.pageSize,
|
|
1782
|
+
counts: view.counts,
|
|
1783
|
+
statusCounts: view.statusCounts,
|
|
1784
|
+
errors,
|
|
1785
|
+
}
|
|
1677
1786
|
}
|
|
1678
|
-
|
|
1679
|
-
const
|
|
1680
|
-
|
|
1681
|
-
const kind = String(payload?.kind || '')
|
|
1682
|
-
const sensitivity = String(payload?.sensitivity || '')
|
|
1683
|
-
const q = String(payload?.q || '').trim().toLowerCase()
|
|
1787
|
+
const libraryId = lexiconLibraryId(payload)
|
|
1788
|
+
const data = lexicon.loadLexicon(libraryId)
|
|
1789
|
+
// 公开两态(§2.1):pending/rejected 是内部状态与墓碑,列表永不返回。
|
|
1684
1790
|
const rows = Object.entries(data.terms || {})
|
|
1685
1791
|
.map(([termId, e]) => ({ ...e, id: termId, status: e?.status || 'active' }))
|
|
1686
1792
|
.filter((e) => LEXICON_PUBLIC_STATUSES.includes(e.status))
|
|
1687
|
-
|
|
1688
|
-
const statusCounts = { active: 0, archived: 0 }
|
|
1689
|
-
for (const e of rows) statusCounts[e.status] += 1
|
|
1690
|
-
const selected = rows
|
|
1691
|
-
.filter((e) => !status || e.status === status)
|
|
1692
|
-
.filter((e) => !sensitivity || e.sensitivity === sensitivity)
|
|
1693
|
-
.filter((e) => !q || [e.term, e.meaning, e.usage, ...(Array.isArray(e.aliases) ? e.aliases : [])].join('\n').toLowerCase().includes(q))
|
|
1694
|
-
// 总览计数行只跟随 kind 以外的过滤:kind 标签上的数字才是"点了会变"的实时数。
|
|
1695
|
-
const counts = { slang: 0, meme: 0, trigger: 0, term: 0 }
|
|
1696
|
-
for (const e of selected) if (counts[e.kind] !== undefined) counts[e.kind] += 1
|
|
1697
|
-
// updatedAt 倒序;同一时间戳按 id 兜底——分页与多端渲染的顺序必须可复现。
|
|
1698
|
-
const filtered = selected.filter((e) => !kind || e.kind === kind)
|
|
1699
|
-
.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || ''))
|
|
1700
|
-
|| String(a.id).localeCompare(String(b.id)))
|
|
1701
|
-
const pageSize = Math.max(1, Math.min(200, Number(payload?.pageSize) || 50))
|
|
1702
|
-
const total = filtered.length
|
|
1703
|
-
const pages = Math.max(1, Math.ceil(total / pageSize))
|
|
1704
|
-
const page = Math.min(pages, Math.max(1, Number(payload?.page) || 1))
|
|
1793
|
+
const view = lexiconFilterPage(rows, payload)
|
|
1705
1794
|
return {
|
|
1706
1795
|
libraryId,
|
|
1707
1796
|
scope: libraryId === GLOBAL_LEXICON_ID ? 'global' : 'private',
|
|
1708
1797
|
version: data.version ?? null,
|
|
1709
|
-
items:
|
|
1710
|
-
total,
|
|
1711
|
-
page,
|
|
1712
|
-
pages,
|
|
1713
|
-
pageSize,
|
|
1714
|
-
counts,
|
|
1715
|
-
statusCounts,
|
|
1798
|
+
items: view.rows.map(lexiconTermView),
|
|
1799
|
+
total: view.total,
|
|
1800
|
+
page: view.page,
|
|
1801
|
+
pages: view.pages,
|
|
1802
|
+
pageSize: view.pageSize,
|
|
1803
|
+
counts: view.counts,
|
|
1804
|
+
statusCounts: view.statusCounts,
|
|
1716
1805
|
}
|
|
1717
1806
|
}
|
|
1718
1807
|
case 'lexiconSearch': {
|
|
@@ -2153,10 +2242,20 @@ export function registerRpc(ctx) {
|
|
|
2153
2242
|
return
|
|
2154
2243
|
}
|
|
2155
2244
|
if (req.method === 'GET' && pathname.startsWith('/dsh-memu-memory/ui-assets/')) {
|
|
2156
|
-
const asset =
|
|
2245
|
+
const asset = standaloneAssetResponse(pathname, req.headers?.['if-none-match'] || null)
|
|
2157
2246
|
const type = pathname.endsWith('.png') ? 'image/png' : pathname.endsWith('.svg') ? 'image/svg+xml' : 'application/javascript; charset=utf-8'
|
|
2158
|
-
|
|
2159
|
-
|
|
2247
|
+
if (asset === null) {
|
|
2248
|
+
res.writeHead(404, { 'Content-Type': type, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' })
|
|
2249
|
+
res.end('')
|
|
2250
|
+
return
|
|
2251
|
+
}
|
|
2252
|
+
if (asset.notModified) {
|
|
2253
|
+
res.writeHead(304, { 'Cache-Control': 'no-cache', ETag: asset.etag, 'X-Content-Type-Options': 'nosniff' })
|
|
2254
|
+
res.end()
|
|
2255
|
+
return
|
|
2256
|
+
}
|
|
2257
|
+
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache', ETag: asset.etag, 'X-Content-Type-Options': 'nosniff' })
|
|
2258
|
+
res.end(asset.body)
|
|
2160
2259
|
return
|
|
2161
2260
|
}
|
|
2162
2261
|
if (req.method === 'GET' && (pathname === SETTINGS_PATH || pathname === `${SETTINGS_PATH}/`)) {
|
package/lib/snippet.js
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
// hit instead — a little before it for context, more after it, because that is
|
|
8
8
|
// the direction the answer usually continues in.
|
|
9
9
|
|
|
10
|
+
import { redactSecrets } from './paths.js'
|
|
11
|
+
|
|
10
12
|
const ELLIPSIS = '…'
|
|
11
13
|
|
|
12
14
|
function escapeRegExp(value) {
|
|
@@ -48,23 +50,24 @@ export function firstHit(text, terms) {
|
|
|
48
50
|
* the hit (default 40 / 120, per DESIGN). With no hit, or no query, this degrades
|
|
49
51
|
* to a head cut of the same total width so callers never need two code paths.
|
|
50
52
|
*/
|
|
51
|
-
export function
|
|
53
|
+
export function centeredSnippetWindow(text, query, { before = 40, after = 120 } = {}) {
|
|
52
54
|
const body = String(text ?? '')
|
|
55
|
+
const points = Array.from(body)
|
|
53
56
|
const width = Math.max(1, before + after)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
57
|
+
const hit = firstHit(body, queryTerms(query))
|
|
58
|
+
// firstHit returns a UTF-16 index; pagination and slicing use code points.
|
|
59
|
+
const hitPoint = hit < 0 ? -1 : Array.from(body.slice(0, hit)).length
|
|
60
|
+
const start = points.length <= width || hitPoint < 0 ? 0 : Math.max(0, hitPoint - before)
|
|
61
|
+
const end = Math.min(points.length, start + width)
|
|
62
|
+
const truncated = start > 0 || end < points.length
|
|
63
|
+
return {
|
|
64
|
+
body: (start > 0 ? ELLIPSIS : '') + points.slice(start, end).join('') + (end < points.length ? ELLIPSIS : ''),
|
|
65
|
+
start, end, returnedChars: end - start, totalChars: points.length, truncated,
|
|
66
|
+
}
|
|
63
67
|
}
|
|
64
68
|
|
|
65
|
-
function
|
|
66
|
-
|
|
67
|
-
return text.length <= max ? text : text.slice(0, Math.max(0, max - 1)) + ELLIPSIS
|
|
69
|
+
export function centeredSnippet(text, query, options = {}) {
|
|
70
|
+
return centeredSnippetWindow(text, query, options).body
|
|
68
71
|
}
|
|
69
72
|
|
|
70
73
|
/**
|
|
@@ -84,21 +87,39 @@ function observedOf(entry) {
|
|
|
84
87
|
return String(entry?.observed_at || entry?.updatedAt || entry?.createdAt || '')
|
|
85
88
|
}
|
|
86
89
|
|
|
87
|
-
export function conflictCard({ factKey, left, right } = {}) {
|
|
88
|
-
if (!left?.id || !right?.id) return ''
|
|
89
|
-
const
|
|
90
|
+
export function conflictCard({ factKey, left, right, members = null, maxChars = 200, titleChars = 40 } = {}) {
|
|
91
|
+
if (!members && (!left?.id || !right?.id)) return ''
|
|
92
|
+
const ordered = (members || [left, right]).filter(item => item?.id).slice().sort((a, b) => Number(a.available === false) - Number(b.available === false)
|
|
93
|
+
|| authorityOf(b.entry) - authorityOf(a.entry) || observedOf(b.entry).localeCompare(observedOf(a.entry)) || String(a.id).localeCompare(String(b.id)))
|
|
94
|
+
if (!ordered.length) return ''
|
|
95
|
+
const cut = (value, count) => {
|
|
96
|
+
const points = Array.from(redactSecrets(value).replace(/\s+/g, ' ').trim())
|
|
97
|
+
return points.length <= count ? points.join('') : count > 0 ? points.slice(0, count - 1).join('') + ELLIPSIS : ''
|
|
98
|
+
}
|
|
99
|
+
const titles = ordered.map(item => item.available === false ? '' : item.entry?.title || item.entry?.content || '(untitled)')
|
|
100
|
+
const widths = titles.map(title => Math.min(titleChars, Array.from(title).length))
|
|
101
|
+
const flags = ordered.map(item => {
|
|
102
|
+
if (item.available === false) return ''
|
|
90
103
|
const entry = item.entry || {}
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
104
|
+
const source = entry.source || 'inferred'
|
|
105
|
+
return [source !== 'inferred' ? `source=${source}` : '', entry.source_kind && entry.source_kind !== source ? `source_kind=${entry.source_kind}` : '',
|
|
106
|
+
entry.disclosure && entry.disclosure !== 'can_tell' ? `disclosure=${entry.disclosure}` : '',
|
|
107
|
+
entry.speaker_id ? `speaker=${entry.speaker_id}` : ''].filter(Boolean).map(value => redactSecrets(value)).join(' · ')
|
|
108
|
+
})
|
|
109
|
+
const render = header => [`冲突 · ${header}`, ...ordered.map((item, i) => {
|
|
110
|
+
const label = String.fromCharCode(65 + i)
|
|
111
|
+
if (item.available === false) return `- ${label} 另有不可见/不可用版本`
|
|
112
|
+
const date = item.entry?.absolute_date ? `(${redactSecrets(item.entry.absolute_date)})` : ''
|
|
113
|
+
const title = cut(titles[i], widths[i])
|
|
114
|
+
return `- ${label} [${item.id}]${title ? ' ' + title : ''}${date}${flags[i] ? ' · ' + flags[i] : ''}`
|
|
115
|
+
}), '- 未确认哪版为准'].join('\n')
|
|
116
|
+
let header = cut(factKey || '同一事实', 60)
|
|
117
|
+
let text = render(header)
|
|
118
|
+
while (Array.from(text).length > maxChars && widths.some(width => width > 0)) {
|
|
119
|
+
const largest = widths.indexOf(Math.max(...widths))
|
|
120
|
+
widths[largest] -= 1
|
|
121
|
+
text = render(header)
|
|
94
122
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|| String(a.id).localeCompare(String(b.id)))
|
|
98
|
-
return clip([
|
|
99
|
-
`冲突 · ${clip(factKey || '同一事实', 60)}`,
|
|
100
|
-
side(ordered[0], 'A'),
|
|
101
|
-
side(ordered[1], 'B'),
|
|
102
|
-
'- 未确认哪版为准',
|
|
103
|
-
].join('\n'), 200)
|
|
123
|
+
if (Array.from(text).length > maxChars) { header = '同一事实'; text = render(header) }
|
|
124
|
+
return Array.from(text).length <= maxChars ? text : ''
|
|
104
125
|
}
|