dsh-memu-memory 1.3.7 → 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 +1 -1
- package/CHANGELOG.md +58 -0
- package/README.md +7 -7
- package/README.zh.md +7 -7
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +2 -2
- package/docs/memory-semantics.md +7 -6
- package/docs/troubleshooting.md +74 -7
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +150 -81
- package/lib/consolidation-ledger.js +6 -2
- package/lib/inbound.js +24 -9
- package/lib/inject.js +379 -215
- package/lib/memory.js +704 -181
- package/lib/paths.js +24 -0
- package/lib/private.js +242 -132
- package/lib/rpc.js +53 -6
- package/lib/snippet.js +49 -28
- package/lib/state.js +185 -26
- package/lib/tools.js +137 -28
- 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 +587 -26
- 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/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/memory.js
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
getLibrary, setSessionBinding, setRecallError, effectiveScope, listLibrariesAll,
|
|
12
12
|
listLibraries, listSessionBindings, getWorkspacePolicy, memoryRevision,
|
|
13
13
|
} from './state.js'
|
|
14
|
-
import { stamp, redactSecrets, retryStoreWrite, warn, indexDir, readJson, writeJson } from './paths.js'
|
|
14
|
+
import { stamp, redactSecrets, retryStoreWrite, warn, indexDir, readJson, readFailure, writeJson, memoryRef, memoryRefKey } from './paths.js'
|
|
15
15
|
import { scopeGenerationOf } from './consolidation-ledger.js'
|
|
16
16
|
import { record } from './activity-log.js'
|
|
17
17
|
import { BASE_AROUSAL, derivedValence, dominanceBias, emotionActive, maxShare, moodCongruence, moodDecay, normalizeEmotion, overlap, readMood } from './mood.js'
|
|
@@ -63,6 +63,72 @@ const RETRIEVAL_FLOOR = 0
|
|
|
63
63
|
// existing mood/strength/MMR pipeline sees it. The candidate cap keeps a long
|
|
64
64
|
// library from turning every turn into two full scans.
|
|
65
65
|
const HYBRID_RRF_K = 60
|
|
66
|
+
|
|
67
|
+
const LEXICAL_DOMINANT_MIN = 24
|
|
68
|
+
const LEXICAL_DOMINANCE_RATIO = 4
|
|
69
|
+
|
|
70
|
+
function lexicalEvidence(file) {
|
|
71
|
+
return Math.max(0, Number(file?.lexicalEvidence ?? file?.lexical) || 0)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function dominanceQuery(query) {
|
|
75
|
+
const original = String(query || '')
|
|
76
|
+
const body = original
|
|
77
|
+
.replace(/^\[(?:私聊|群)[::][^\]]+\][^\n]*?#-?\d+(?:\s*\[[^\]]*\])*\s*[::]\s*/gm, '')
|
|
78
|
+
.replace(/\n(?:\[管理员的长期偏好[^\]]*\]|【本会话是QQ)[\s\S]*$/, '')
|
|
79
|
+
const englishStyle = new Set('please answer respond reply clearly concisely accurately naturally briefly politely with accurate context and natural language avoid repetition unnecessary details use a an the in tone keep responses short concise clear do not repeat yourself'.split(' '))
|
|
80
|
+
let removed = false
|
|
81
|
+
const topic = body.replace(/[^。.!!??\n]+[。.!!??]?/g, sentence => {
|
|
82
|
+
const text = sentence.trim()
|
|
83
|
+
if (/[??]$/.test(text)) return sentence
|
|
84
|
+
let styleOnly = false
|
|
85
|
+
if (/^(?:请|务必|不要|避免)/.test(text) && /自然|简洁|语气|重复|条理/.test(text)) {
|
|
86
|
+
const rest = text.replace(/请|你|务必|用|以|根据|结合|上下文|准确|理解|我的|问题|不要|避免|机械|重复|给出|自然|简洁|且|有|条理|的|语气|回答|回复|细节|多余|冗长|[\s,,。.!!]/g, '')
|
|
87
|
+
styleOnly = !rest
|
|
88
|
+
}
|
|
89
|
+
if (/^(?:please\s+)?(?:answer|respond|reply|avoid|use|keep|do not)\b/i.test(text)) {
|
|
90
|
+
const words = text.toLowerCase().match(/[a-z]+/g) || []
|
|
91
|
+
styleOnly = words.length > 0 && words.every(word => englishStyle.has(word)) && !/[^a-z\s,.!'-]/i.test(text)
|
|
92
|
+
}
|
|
93
|
+
if (!styleOnly) return sentence
|
|
94
|
+
removed = true
|
|
95
|
+
return ''
|
|
96
|
+
})
|
|
97
|
+
return removed && /[\p{L}\p{N}]/u.test(topic) ? topic.trim() : body
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function inheritLexicalEvidence(file, source) {
|
|
101
|
+
if (file.lexical === undefined && source.lexical === undefined && file.lexicalEvidence === undefined && source.lexicalEvidence === undefined) return file
|
|
102
|
+
return {
|
|
103
|
+
...file,
|
|
104
|
+
lexical: Math.max(Number(file.lexical) || 0, Number(source.lexical) || 0),
|
|
105
|
+
lexicalEvidence: Math.max(lexicalEvidence(file), lexicalEvidence(source)),
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function applyLexicalDominance(files, stage) {
|
|
110
|
+
const ranked = files.slice().sort((a, b) => lexicalEvidence(b) - lexicalEvidence(a))
|
|
111
|
+
const topLex = lexicalEvidence(ranked[0])
|
|
112
|
+
const second = lexicalEvidence(ranked[1])
|
|
113
|
+
const dominant = topLex >= LEXICAL_DOMINANT_MIN && topLex >= second * LEXICAL_DOMINANCE_RATIO
|
|
114
|
+
const floor = 1 / (1 + topLex / 50)
|
|
115
|
+
const scored = files.map(file => {
|
|
116
|
+
const { lexicalDominant, lexicalDiscount, lexicalDominantId, dominanceStage, ...fusion } = file.fusion || {}
|
|
117
|
+
const raw = fusion.rawRetrievalScore ?? file.retrievalScore
|
|
118
|
+
// 微弱词法证据不能比零词法证据更差;每次筛选后从未折减分值重新计算。
|
|
119
|
+
const discount = dominant ? Math.max(floor, Math.sqrt(Math.min(1, lexicalEvidence(file) / topLex))) : 1
|
|
120
|
+
return {
|
|
121
|
+
...file,
|
|
122
|
+
retrievalScore: Math.min(1, raw * discount),
|
|
123
|
+
fusion: { ...fusion, rawRetrievalScore: raw,
|
|
124
|
+
...(dominant ? { lexicalDominant: topLex, lexicalDiscount: discount, lexicalDominantId: ranked[0].name, dominanceStage: stage } : {}) },
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
return {
|
|
128
|
+
files: scored,
|
|
129
|
+
dominance: dominant ? { topLex, second, id: ranked[0].name, stage, discounted: scored.filter(file => file.fusion.lexicalDiscount < 1).length } : null,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
66
132
|
const HYBRID_CANDIDATE_MIN = 12
|
|
67
133
|
const HYBRID_CANDIDATE_MAX = 40
|
|
68
134
|
const HYBRID_SEMANTIC_TIMEOUT_MS = 15_000
|
|
@@ -239,7 +305,7 @@ async function withManagedGlobalWrite(action) {
|
|
|
239
305
|
return withVectorWrite(() => { assertVectorWriteAllowed(); return action() })
|
|
240
306
|
}
|
|
241
307
|
|
|
242
|
-
async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
|
|
308
|
+
async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
|
|
243
309
|
const local = localRecall(index, query, undefined, { cacheKey: libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`, topK })
|
|
244
310
|
try {
|
|
245
311
|
if (intent.error) throw intent.error
|
|
@@ -251,13 +317,20 @@ async function managedRecall({ exec, index, query, topK, libraryId, automatic =
|
|
|
251
317
|
// 这是持久状态,每轮召回都在同一个点上失败,把 "1 个错误" 常驻挂进召回结果
|
|
252
318
|
// 只会教模型反复无谓重试。降级为 local-only + 诊断记录(vector 域可观测),
|
|
253
319
|
// 不再进 errors;该库下次向量生成入册后语义腿自动恢复。
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
//
|
|
257
|
-
//
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
320
|
+
// 空库连降级都算不上(2026-11-18):索引一条都没有时 local-only 与语义召回的
|
|
321
|
+
// 结果都是空——跨库召回扫到一个旧工作区遗留的空库,每轮给它刷一条 warn 纯属
|
|
322
|
+
// 噪音(group_893418498 空库实测常驻活动日志)。有内容而缺向量库才值得诊断
|
|
323
|
+
// 与追平探测。
|
|
324
|
+
// 调用方复用已加载的整库索引判空,不能用领域过滤后的 index,也不再重复加载/克隆。
|
|
325
|
+
if (!sourceEmpty) {
|
|
326
|
+
warn('managed vector generation has no database for library ' + (libraryId ?? 'global') + ' — recall degraded to local-only')
|
|
327
|
+
record({ kind: 'vector', level: 'warn', scope: libraryId ? 'library' : 'global', message: '向量库未生成,召回降级 local-only', detail: { libraryId, route: intent.route } })
|
|
328
|
+
// 自动追平:向量已启用时 force 重建一次代际,把缺库索引补进向量库(幂等护栏在服务内)。
|
|
329
|
+
// 动态 import:local-vector-service → memu → memory 存在模块环,静态引会扩大环面。
|
|
330
|
+
void import('./local-vector-service.js')
|
|
331
|
+
.then((svc) => svc.maybeAutoRebuildVectorGeneration())
|
|
332
|
+
.catch(() => {})
|
|
333
|
+
}
|
|
261
334
|
return { ...local, recallRoute: 'local-fallback' }
|
|
262
335
|
}
|
|
263
336
|
// P1-1 召回缓存:只缓存成功的语义召回——byId 与 local-fallback 都在上面短路或走
|
|
@@ -282,8 +355,9 @@ async function managedRecall({ exec, index, query, topK, libraryId, automatic =
|
|
|
282
355
|
if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
|
|
283
356
|
if (captured) assertGeneration(captured)
|
|
284
357
|
const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
|
|
285
|
-
limit: hybridCandidateLimit(topK), automatic,
|
|
286
|
-
|
|
358
|
+
limit: hybridCandidateLimit(topK), automatic, disclosureAsked: detectQueryIntent(query) === 'boundary',
|
|
359
|
+
speakerFilter: detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
|
|
360
|
+
return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug, vectorGeneration: captured?.token ?? null }
|
|
287
361
|
})
|
|
288
362
|
clearRecallError(exec)
|
|
289
363
|
return result
|
|
@@ -1139,12 +1213,16 @@ function localRecall(index, query, filter = () => true, { cacheKey = null, topK
|
|
|
1139
1213
|
return { files: files.filter(file => file.name === id).map(file => ({ ...file, lexical: 5 })), segments: [], resources: [], raw: null, parseWarning: null }
|
|
1140
1214
|
}
|
|
1141
1215
|
const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
|
|
1216
|
+
const topic = dominanceQuery(query)
|
|
1217
|
+
const evidenceChanged = topic !== String(query || '')
|
|
1142
1218
|
if (recallLexicalMode() === 'includes') {
|
|
1143
1219
|
const tokens = queryTokens(query)
|
|
1220
|
+
const evidenceTokens = evidenceChanged ? queryTokens(topic) : null
|
|
1144
1221
|
const ordered = tokens.length === 0
|
|
1145
1222
|
? files.sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK))
|
|
1146
1223
|
: files
|
|
1147
|
-
.map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates)
|
|
1224
|
+
.map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates),
|
|
1225
|
+
lexicalEvidence: lexicalScore(file.entry, evidenceTokens || tokens, []) }))
|
|
1148
1226
|
.filter((file) => file.lexical > 0)
|
|
1149
1227
|
.sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
|
|
1150
1228
|
return { files: ordered, segments: [], resources: [], raw: null, parseWarning: null }
|
|
@@ -1154,6 +1232,7 @@ function localRecall(index, query, filter = () => true, { cacheKey = null, topK
|
|
|
1154
1232
|
return { files: files.sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), segments: [], resources: [], raw: null, parseWarning: null }
|
|
1155
1233
|
}
|
|
1156
1234
|
const corpus = lexicalCorpusFor(files, cacheKey)
|
|
1235
|
+
const evidenceTokens = evidenceChanged ? tokenize(topic) : null
|
|
1157
1236
|
// The date boost came over from the includes scorer unchanged (+4), where it shared
|
|
1158
1237
|
// a ruler with "title matches = 4". BM25 has no upper bound and its IDF depends on
|
|
1159
1238
|
// the library (about 2.7 at N=21/df=1, a typical hit scoring 2-5), so an additive +4
|
|
@@ -1162,9 +1241,11 @@ function localRecall(index, query, filter = () => true, { cacheKey = null, topK
|
|
|
1162
1241
|
// hit at all past the `lexical > 0` filter below, spending candidate slots on them.
|
|
1163
1242
|
const scored = files.map((file) => {
|
|
1164
1243
|
const doc = corpus.docs.get(file.name)
|
|
1244
|
+
const lexical = doc ? bm25(tokens, doc, corpus) : 0
|
|
1165
1245
|
return {
|
|
1166
1246
|
file,
|
|
1167
|
-
lexical
|
|
1247
|
+
lexical,
|
|
1248
|
+
lexicalEvidence: evidenceTokens && doc ? bm25(evidenceTokens, doc, corpus) : lexical,
|
|
1168
1249
|
dateMatch: Boolean(file.entry?.absolute_date && queryDates.includes(file.entry.absolute_date)),
|
|
1169
1250
|
}
|
|
1170
1251
|
})
|
|
@@ -1173,8 +1254,9 @@ function localRecall(index, query, filter = () => true, { cacheKey = null, topK
|
|
|
1173
1254
|
// seat at all; otherwise it lands a thousandth of the best hit — present, last.
|
|
1174
1255
|
const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
|
|
1175
1256
|
const ordered = scored
|
|
1176
|
-
.map(({ file, lexical, dateMatch }) => ({
|
|
1257
|
+
.map(({ file, lexical, lexicalEvidence: evidence, dateMatch }) => ({
|
|
1177
1258
|
...file,
|
|
1259
|
+
...(evidence === undefined ? {} : { lexicalEvidence: evidence }),
|
|
1178
1260
|
lexical: lexical > 0
|
|
1179
1261
|
? lexical * (dateMatch ? DATE_MATCH_FACTOR : 1)
|
|
1180
1262
|
: (dateMatch ? dateOnly : 0),
|
|
@@ -1190,6 +1272,87 @@ export function hybridCandidateLimit(topK) {
|
|
|
1190
1272
|
return Math.max(HYBRID_CANDIDATE_MIN, Math.min(HYBRID_CANDIDATE_MAX, wanted * 4))
|
|
1191
1273
|
}
|
|
1192
1274
|
|
|
1275
|
+
export function groupConflictCandidates(files, indexesByLibrary, { scope = 'private', canRead = entry => isMemoryEligible(entry, { automatic: true }), maxMembers = 8 } = {}) {
|
|
1276
|
+
const indexes = indexesByLibrary instanceof Map ? indexesByLibrary : new Map(Object.entries(indexesByLibrary || {}))
|
|
1277
|
+
const libraryGraphs = new Map()
|
|
1278
|
+
const graphFor = libraryId => {
|
|
1279
|
+
if (libraryGraphs.has(libraryId)) return libraryGraphs.get(libraryId)
|
|
1280
|
+
const index = indexes.get(libraryId) || (indexes.size === 1 ? indexes.values().next().value : null)
|
|
1281
|
+
const entries = new Map(Object.entries(index?.entries || {}).filter(([, entry]) => canRead(entry, libraryId)))
|
|
1282
|
+
const parents = new Map([...entries.keys()].map(id => [id, id]))
|
|
1283
|
+
const find = id => {
|
|
1284
|
+
let root = id
|
|
1285
|
+
while (parents.get(root) !== root) root = parents.get(root)
|
|
1286
|
+
while (id !== root) { const next = parents.get(id); parents.set(id, root); id = next }
|
|
1287
|
+
return root
|
|
1288
|
+
}
|
|
1289
|
+
for (const [id, entry] of entries) {
|
|
1290
|
+
const other = entry.conflicts_with
|
|
1291
|
+
if (other && entries.has(other)) parents.set(find(id), find(other))
|
|
1292
|
+
}
|
|
1293
|
+
const components = new Map()
|
|
1294
|
+
for (const id of entries.keys()) {
|
|
1295
|
+
const root = find(id)
|
|
1296
|
+
if (!components.has(root)) components.set(root, [])
|
|
1297
|
+
components.get(root).push(id)
|
|
1298
|
+
}
|
|
1299
|
+
const graph = { entries, components, find }
|
|
1300
|
+
libraryGraphs.set(libraryId, graph)
|
|
1301
|
+
return graph
|
|
1302
|
+
}
|
|
1303
|
+
const roots = new Map()
|
|
1304
|
+
for (const file of files || []) {
|
|
1305
|
+
const libraryId = scope === 'global' ? null : file.libraryId ?? indexes.keys().next().value ?? null
|
|
1306
|
+
const graph = graphFor(libraryId)
|
|
1307
|
+
if (!graph.entries.has(file.name)) continue
|
|
1308
|
+
const root = graph.find(file.name)
|
|
1309
|
+
const key = JSON.stringify([libraryId, root])
|
|
1310
|
+
if (!roots.has(key)) roots.set(key, { libraryId, graph, root, candidates: [] })
|
|
1311
|
+
roots.get(key).candidates.push(file)
|
|
1312
|
+
}
|
|
1313
|
+
return [...roots.values()].map(({ libraryId, graph, root, candidates }) => {
|
|
1314
|
+
const ids = graph.components.get(root).slice().sort()
|
|
1315
|
+
const unavailableIds = [...new Set(ids.map(id => graph.entries.get(id).conflicts_with).filter(id => id && !graph.entries.has(id)))].sort()
|
|
1316
|
+
const key = JSON.stringify([scope, libraryId, [...new Set([...ids, ...unavailableIds])].sort()])
|
|
1317
|
+
const ranked = candidates.slice().sort((a, b) => (Number(b.score) || 0) - (Number(a.score) || 0))
|
|
1318
|
+
const byId = new Map(ranked.map(file => [file.name, file]))
|
|
1319
|
+
const groupFiles = ids.slice(0, maxMembers).map(id => {
|
|
1320
|
+
const entry = graph.entries.get(id)
|
|
1321
|
+
const file = byId.get(id)
|
|
1322
|
+
return { ...(file || {}), name: id, libraryId, entry, description: entry.title || '', content: String(entry.content || ''),
|
|
1323
|
+
strength: file?.strength ?? decayStrength(entry), createdAtIdentity: entry.createdAt || null }
|
|
1324
|
+
})
|
|
1325
|
+
const refs = groupFiles.map(file => memoryRef({ scope, libraryId, id: file.name, entry: file.entry }))
|
|
1326
|
+
const revision = crypto.createHash('sha256').update(JSON.stringify([refs.map(ref => [ref.id, ref.revision]), unavailableIds, ids.length])).digest('hex')
|
|
1327
|
+
for (let i = 0; i < groupFiles.length; i++) {
|
|
1328
|
+
const ref = { ...refs[i], groupKey: key, groupRevision: revision }
|
|
1329
|
+
refs[i] = ref
|
|
1330
|
+
groupFiles[i].ref = ref
|
|
1331
|
+
groupFiles[i].groupKey = key
|
|
1332
|
+
groupFiles[i].groupRevision = revision
|
|
1333
|
+
}
|
|
1334
|
+
const conflict = ids.length > 1 || unavailableIds.length > 0 || ids.some(id => graph.entries.get(id).conflicts_with)
|
|
1335
|
+
return { key, name: key, revision, scope, libraryId, files: groupFiles, refs, conflict,
|
|
1336
|
+
complete: unavailableIds.length === 0 && ids.length <= maxMembers && (!conflict || ids.length > 1), truncated: ids.length > maxMembers,
|
|
1337
|
+
unavailableIds, memberCount: ids.length, candidateRows: candidates.length,
|
|
1338
|
+
score: Number(ranked[0]?.score) || 0, retrieval: Number(ranked[0]?.retrieval) || 0,
|
|
1339
|
+
entry: ranked[0]?.entry || null, content: groupFiles.map(file => `${file.entry.title || ''} ${file.content}`).join('\n') }
|
|
1340
|
+
})
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
function recentRefMap(refs, scope) {
|
|
1344
|
+
return new Map((refs || []).filter(ref => ref?.scope === scope && ref.id && ref.revision).map(ref => [memoryRefKey(ref), ref]))
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
function groupWasSeen(group, recent) {
|
|
1348
|
+
return group.refs.length > 0 && group.refs.every(ref => {
|
|
1349
|
+
const previous = recent.get(memoryRefKey(ref))
|
|
1350
|
+
if (!previous || previous.revision !== ref.revision) return false
|
|
1351
|
+
if (!previous.groupKey) return !group.conflict
|
|
1352
|
+
return previous.groupKey === group.key && previous.groupRevision === group.revision
|
|
1353
|
+
})
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1193
1356
|
/** How much of a recency-only result set is worth passing on. */
|
|
1194
1357
|
function emptyQueryLimit(topK) {
|
|
1195
1358
|
const wanted = Number(topK)
|
|
@@ -1215,11 +1378,10 @@ function mmrPool(items, max) {
|
|
|
1215
1378
|
* and then be dropped later. Ids are canonicalised against the live index so the
|
|
1216
1379
|
* two routes cannot return the same memory twice under a prefix or a .md suffix.
|
|
1217
1380
|
*
|
|
1218
|
-
* The returned retrievalScore is the normalised RRF share
|
|
1219
|
-
*
|
|
1220
|
-
* fusion order is not silently overwritten by the old rank decay.
|
|
1381
|
+
* The returned retrievalScore is the normalised RRF share with lexical dominance applied.
|
|
1382
|
+
* fusion.rawRetrievalScore retains its unadjusted value for later eligibility filtering.
|
|
1221
1383
|
*/
|
|
1222
|
-
export function fuseRecallCandidates({ local = [], semantic = [], index, limit = HYBRID_CANDIDATE_MIN, automatic = false, sessionId = null, now = Date.now(), route = 'vector-rrf' } = {}) {
|
|
1384
|
+
export function fuseRecallCandidates({ local = [], semantic = [], index, limit = HYBRID_CANDIDATE_MIN, automatic = false, disclosureAsked = false, speakerFilter = null, sessionId = null, now = Date.now(), route = 'vector-rrf' } = {}) {
|
|
1223
1385
|
const entries = index?.entries || {}
|
|
1224
1386
|
const canonical = (ref) => {
|
|
1225
1387
|
const raw = String(ref || '').trim()
|
|
@@ -1237,6 +1399,8 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1237
1399
|
if (!isMemoryEligible(entry, { automatic, now })) return null
|
|
1238
1400
|
if (!visibleToSession(entry, sessionId)) return null
|
|
1239
1401
|
if (automatic && entry.visibility === 'secret') return null
|
|
1402
|
+
if (!isDisclosureEligible(entry, { automatic, asked: disclosureAsked })) return null
|
|
1403
|
+
if (!speakerMatchesFilter(entry, speakerFilter)) return null
|
|
1240
1404
|
return { id, entry, file, route, rank }
|
|
1241
1405
|
}
|
|
1242
1406
|
const take = (files, route, collapsed) => {
|
|
@@ -1245,7 +1409,7 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1245
1409
|
// pass both `mem-x` and `mem-x.md`, and an engine can repeat a hit. Dedupe by
|
|
1246
1410
|
// canonical id before scoring and truncating, keeping the first (best) rank.
|
|
1247
1411
|
// Otherwise every duplicate adds another 1/(k+rank) and consumes a slot.
|
|
1248
|
-
const seen = new
|
|
1412
|
+
const seen = new Map()
|
|
1249
1413
|
// Fact-level folding : id dedupe cannot see "same fact,
|
|
1250
1414
|
// different id", so a paraphrase cluster would spend one candidate slot per
|
|
1251
1415
|
// member and crowd real memories out before any ranking runs. A candidate that
|
|
@@ -1262,13 +1426,20 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1262
1426
|
}
|
|
1263
1427
|
for (const file of Array.isArray(files) ? files : []) {
|
|
1264
1428
|
const item = eligible(file, route, picked.length + 1)
|
|
1265
|
-
if (!item
|
|
1266
|
-
seen.
|
|
1429
|
+
if (!item) continue
|
|
1430
|
+
const duplicate = seen.get(item.id)
|
|
1431
|
+
if (duplicate) {
|
|
1432
|
+
duplicate.file = inheritLexicalEvidence(duplicate.file, item.file)
|
|
1433
|
+
continue
|
|
1434
|
+
}
|
|
1267
1435
|
const twin = picked.find((accepted) => similarTexts(textOf(item), textOf(accepted)) >= DUP_DICE)
|
|
1268
1436
|
if (twin) {
|
|
1437
|
+
seen.set(item.id, twin)
|
|
1438
|
+
twin.file = inheritLexicalEvidence(twin.file, item.file)
|
|
1269
1439
|
collapsed.push({ kept: twin.id, dropped: item.id })
|
|
1270
1440
|
continue
|
|
1271
1441
|
}
|
|
1442
|
+
seen.set(item.id, item)
|
|
1272
1443
|
picked.push(item)
|
|
1273
1444
|
if (picked.length >= limit) break
|
|
1274
1445
|
}
|
|
@@ -1279,15 +1450,23 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1279
1450
|
const semanticPicked = take(semantic, 'semantic', routeCollapsed)
|
|
1280
1451
|
const merged = new Map()
|
|
1281
1452
|
const add = (item) => {
|
|
1282
|
-
const current = merged.get(item.id) || { id: item.id, entry: item.entry, file: item.file, rrf: 0, bestRank: Infinity, localRank: null, semanticRank: null, routes: [], mergedTogether: [] }
|
|
1453
|
+
const current = merged.get(item.id) || { id: item.id, entry: item.entry, file: item.file, rrf: 0, bestRank: Infinity, localRank: null, semanticRank: null, semanticScore: null, routes: [], mergedTogether: [] }
|
|
1283
1454
|
current.rrf += 1 / (HYBRID_RRF_K + item.rank)
|
|
1284
1455
|
current.bestRank = Math.min(current.bestRank, item.rank)
|
|
1285
1456
|
if (item.route === 'local') current.localRank = item.rank
|
|
1286
|
-
else
|
|
1457
|
+
else {
|
|
1458
|
+
current.semanticRank = item.rank
|
|
1459
|
+
// R4:引擎命中自带原始相似度时透传,跨库融合才有可比分数;缺失保持 null,
|
|
1460
|
+
// 上层据此退回显式标记的 rank-only,不伪造可比性。
|
|
1461
|
+
const score = item.file?.score == null ? NaN : Number(item.file.score)
|
|
1462
|
+
if (Number.isFinite(score)) current.semanticScore = Math.max(current.semanticScore ?? -Infinity, score)
|
|
1463
|
+
}
|
|
1287
1464
|
if (!current.routes.includes(item.route)) current.routes.push(item.route)
|
|
1288
1465
|
// Prefer the local object when both routes carry the entry: it already has the
|
|
1289
1466
|
// lexical score and the index-backed content used below by enrichFiles.
|
|
1290
|
-
|
|
1467
|
+
current.file = item.route === 'local'
|
|
1468
|
+
? inheritLexicalEvidence(item.file, current.file)
|
|
1469
|
+
: inheritLexicalEvidence(current.file, item.file)
|
|
1291
1470
|
merged.set(item.id, current)
|
|
1292
1471
|
}
|
|
1293
1472
|
for (const item of localPicked) add(item)
|
|
@@ -1313,6 +1492,16 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1313
1492
|
for (const row of rows.slice().sort((a, b) => b.rrf - a.rrf || a.id.localeCompare(b.id))) {
|
|
1314
1493
|
const host = hosts.find((kept) => similarTexts(textOfRow(row), textOfRow(kept)) >= DUP_DICE)
|
|
1315
1494
|
if (host) {
|
|
1495
|
+
host.file = inheritLexicalEvidence(host.file, row.file)
|
|
1496
|
+
host.localRank = Math.min(host.localRank ?? Infinity, row.localRank ?? Infinity)
|
|
1497
|
+
host.semanticRank = Math.min(host.semanticRank ?? Infinity, row.semanticRank ?? Infinity)
|
|
1498
|
+
if (!Number.isFinite(host.localRank)) host.localRank = null
|
|
1499
|
+
if (!Number.isFinite(host.semanticRank)) host.semanticRank = null
|
|
1500
|
+
if (row.semanticScore !== null) host.semanticScore = Math.max(host.semanticScore ?? -Infinity, row.semanticScore)
|
|
1501
|
+
host.routes = [...new Set([...host.routes, ...row.routes])]
|
|
1502
|
+
host.bestRank = Math.min(host.bestRank, row.bestRank)
|
|
1503
|
+
host.rrf = (host.localRank === null ? 0 : 1 / (HYBRID_RRF_K + host.localRank))
|
|
1504
|
+
+ (host.semanticRank === null ? 0 : 1 / (HYBRID_RRF_K + host.semanticRank))
|
|
1316
1505
|
host.mergedTogether.push(row.id)
|
|
1317
1506
|
absorbed.add(row.id)
|
|
1318
1507
|
fusionCollapsed.push({ kept: host.id, dropped: row.id })
|
|
@@ -1328,17 +1517,18 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1328
1517
|
if (!group.dropped.includes(dropped)) group.dropped.push(dropped)
|
|
1329
1518
|
}
|
|
1330
1519
|
const collapsed = [...collapsedGroups.values()]
|
|
1331
|
-
const
|
|
1332
|
-
const
|
|
1333
|
-
|
|
1334
|
-
.
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1520
|
+
const survivors = rows.filter(row => !absorbed.has(row.id))
|
|
1521
|
+
const maxRrf = survivors.reduce((max, row) => Math.max(max, row.rrf), 0) || 1
|
|
1522
|
+
const adjusted = applyLexicalDominance(survivors.map(row => ({
|
|
1523
|
+
...row.file,
|
|
1524
|
+
name: row.id,
|
|
1525
|
+
entry: row.entry,
|
|
1526
|
+
retrievalScore: row.rrf / maxRrf,
|
|
1527
|
+
fusion: { rrf: row.rrf, bestRank: row.bestRank, localRank: row.localRank, semanticRank: row.semanticRank, routes: row.routes.slice(),
|
|
1528
|
+
...(row.semanticScore !== null ? { semanticScore: row.semanticScore } : {}) },
|
|
1529
|
+
...(row.mergedTogether.length ? { mergedTogether: row.mergedTogether.slice() } : {}),
|
|
1530
|
+
})), 'library')
|
|
1531
|
+
const files = adjusted.files
|
|
1342
1532
|
.sort((a, b) => b.retrievalScore - a.retrievalScore
|
|
1343
1533
|
|| a.fusion.bestRank - b.fusion.bestRank
|
|
1344
1534
|
|| a.name.localeCompare(b.name))
|
|
@@ -1358,6 +1548,7 @@ export function fuseRecallCandidates({ local = [], semantic = [], index, limit =
|
|
|
1358
1548
|
shared: [...localIds].filter((id) => semanticIds.has(id)).length,
|
|
1359
1549
|
collapsed,
|
|
1360
1550
|
clusterCount: collapsed.length,
|
|
1551
|
+
lexicalDominance: adjusted.dominance,
|
|
1361
1552
|
},
|
|
1362
1553
|
}
|
|
1363
1554
|
}
|
|
@@ -1509,6 +1700,7 @@ function recallPercentile() {
|
|
|
1509
1700
|
}
|
|
1510
1701
|
|
|
1511
1702
|
function privateWeighted(result, max, context = {}) {
|
|
1703
|
+
const started = performance.now()
|
|
1512
1704
|
const ctx = {
|
|
1513
1705
|
moodEnabled: false,
|
|
1514
1706
|
moodValence: 0,
|
|
@@ -1526,7 +1718,7 @@ function privateWeighted(result, max, context = {}) {
|
|
|
1526
1718
|
retrievalFloor: RETRIEVAL_FLOOR,
|
|
1527
1719
|
...context,
|
|
1528
1720
|
}
|
|
1529
|
-
const
|
|
1721
|
+
const eligible = (result.files || [])
|
|
1530
1722
|
.filter((f) => isMemoryEligible(f.entry, { automatic: ctx.automatic, now: ctx.now }))
|
|
1531
1723
|
// Context is the only scope left: a memory written inside a channel / character /
|
|
1532
1724
|
// world / branch is recalled only inside that same scope, and a blank scope (`{}`)
|
|
@@ -1539,16 +1731,59 @@ function privateWeighted(result, max, context = {}) {
|
|
|
1539
1731
|
// S3.2:明确问“我说过/你说过/他说的”时,只留下说话人对得上的条目;
|
|
1540
1732
|
// 没有 speaker 字段的旧条目保留,避免一次查询把历史记忆全清空。
|
|
1541
1733
|
.filter((f) => speakerMatchesFilter(f.entry, ctx.speakerFilter))
|
|
1734
|
+
const adjusted = result.files?.[0]?.fusion?.rawRetrievalScore === undefined ? null : applyLexicalDominance(eligible, 'eligible')
|
|
1735
|
+
const items = (adjusted?.files || eligible)
|
|
1542
1736
|
.map((f, i) => ({ ...f, score: recallScore(f, i, ctx), retrieval: retrievalShare(f, i) }))
|
|
1543
1737
|
.sort((a, b) => b.score - a.score)
|
|
1544
|
-
const
|
|
1738
|
+
const strong = cutWeakScores(items, ctx.relevanceThreshold, ctx.retrievalFloor, recallPercentile())
|
|
1739
|
+
if (ctx.automatic) {
|
|
1740
|
+
const recent = recentRefMap(ctx.excludedRefs, 'private')
|
|
1741
|
+
const groups = groupConflictCandidates(strong, ctx.indexesByLibrary, { scope: 'private', canRead: ctx.canRead })
|
|
1742
|
+
for (const group of groups) {
|
|
1743
|
+
const previous = group.refs.map(ref => recent.get(memoryRefKey(ref)))
|
|
1744
|
+
group.reintroducedForConflict = group.conflict && previous.some(Boolean) && !groupWasSeen(group, recent)
|
|
1745
|
+
group.reintroducedForRevision = group.refs.some((ref, i) => previous[i] && previous[i].revision !== ref.revision)
|
|
1746
|
+
}
|
|
1747
|
+
const oversized = groups.filter(group => group.truncated)
|
|
1748
|
+
const recentGroups = groups.filter(group => !group.truncated && groupWasSeen(group, recent))
|
|
1749
|
+
const fresh = groups.filter(group => !group.truncated && !groupWasSeen(group, recent))
|
|
1750
|
+
const pool = mmrPool(fresh, max)
|
|
1751
|
+
const ranked = mmrSelect(pool, max)
|
|
1752
|
+
const files = ranked.chosen.flatMap(group => group.files)
|
|
1753
|
+
const allGroups = new Map(groups.map(group => [group.key, group]))
|
|
1754
|
+
const skipped = ranked.skipped.map(group => ({
|
|
1755
|
+
...group, kept: allGroups.get(group.kept)?.files[0]?.name || group.kept,
|
|
1756
|
+
dropped: group.dropped.flatMap(key => allGroups.get(key)?.files.map(file => file.name) || []),
|
|
1757
|
+
}))
|
|
1758
|
+
const fusionCollapsed = Array.isArray(result.fusion?.collapsed) ? result.fusion.collapsed : []
|
|
1759
|
+
const collapsed = [...fusionCollapsed, ...skipped]
|
|
1760
|
+
return { ...result, files, groups: ranked.chosen,
|
|
1761
|
+
...(adjusted ? { fusion: { ...result.fusion, lexicalDominance: adjusted.dominance } } : {}),
|
|
1762
|
+
dedup: { collapsed, clusterCount: collapsed.length },
|
|
1763
|
+
omittedGroups: oversized.map(group => ({ key: group.key, reason: 'conflict-group-too-large', members: group.memberCount })),
|
|
1764
|
+
trace: { counts: { retrievedRows: result.files?.length || 0, ineligibleRows: (result.files?.length || 0) - eligible.length,
|
|
1765
|
+
qualifiedRows: strong.length, weakRows: items.length - strong.length,
|
|
1766
|
+
recentRows: recentGroups.reduce((sum, group) => sum + group.candidateRows, 0),
|
|
1767
|
+
candidateGroups: groups.length, recentGroups: recentGroups.length, oversizedGroups: oversized.length,
|
|
1768
|
+
poolOmittedRows: fresh.slice(pool.length).reduce((sum, group) => sum + group.candidateRows, 0), poolOmittedGroups: fresh.length - pool.length,
|
|
1769
|
+
duplicateRows: skipped.reduce((sum, group) => sum + group.dropped.length, 0),
|
|
1770
|
+
selectedRows: files.length, selectedGroups: ranked.chosen.length }, selectionMs: performance.now() - started } }
|
|
1771
|
+
}
|
|
1772
|
+
const pool = mmrPool(strong, max)
|
|
1773
|
+
const { chosen, skipped } = mmrSelect(pool, max)
|
|
1545
1774
|
// Observation for the dedup thresholds : candidate folding
|
|
1546
1775
|
// (①②) reports through result.fusion, the ranking-level hard skips (③) come back
|
|
1547
1776
|
// from mmrSelect. One merged list — without it, a mistuned threshold eats real
|
|
1548
1777
|
// memories invisibly. Fail-open: metadata only, never a recall failure.
|
|
1549
1778
|
const fusionCollapsed = Array.isArray(result.fusion?.collapsed) ? result.fusion.collapsed : []
|
|
1550
1779
|
const collapsed = [...fusionCollapsed, ...skipped]
|
|
1551
|
-
return { ...result, files: chosen,
|
|
1780
|
+
return { ...result, files: chosen,
|
|
1781
|
+
...(adjusted ? { fusion: { ...result.fusion, lexicalDominance: adjusted.dominance } } : {}),
|
|
1782
|
+
dedup: { collapsed, clusterCount: collapsed.length },
|
|
1783
|
+
trace: { counts: { retrievedRows: result.files?.length || 0, ineligibleRows: (result.files?.length || 0) - eligible.length,
|
|
1784
|
+
weakRows: items.length - strong.length, poolOmittedRows: strong.length - pool.length,
|
|
1785
|
+
duplicateRows: new Set(skipped.flatMap(group => group.dropped || [])).size, selectedRows: chosen.length },
|
|
1786
|
+
selectionMs: performance.now() - started } }
|
|
1552
1787
|
}
|
|
1553
1788
|
|
|
1554
1789
|
/**
|
|
@@ -1573,9 +1808,13 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1573
1808
|
if (items.length <= 1) return { chosen: items.slice(0, limit), skipped: [] }
|
|
1574
1809
|
const chosen = []
|
|
1575
1810
|
const pool = items.slice()
|
|
1811
|
+
// R4:跨库候选里同一个裸 id 可以是两条不同事实,文本/相似度缓存必须按
|
|
1812
|
+
// [libraryId,id] 区分,否则第二条会读到第一条的正文。组对象的 .key 本身
|
|
1813
|
+
// 已是复合身份,直接沿用,skipped 报告形状不变。
|
|
1814
|
+
const itemKey = (item) => item.key ?? JSON.stringify([item.libraryId ?? null, item.name])
|
|
1576
1815
|
const textCache = new Map()
|
|
1577
1816
|
const textOf = (file) => {
|
|
1578
|
-
const key = file
|
|
1817
|
+
const key = itemKey(file)
|
|
1579
1818
|
if (textCache.has(key)) return textCache.get(key)
|
|
1580
1819
|
const text = `${file.entry?.title || ''} ${file.entry?.content || ''}`
|
|
1581
1820
|
textCache.set(key, text)
|
|
@@ -1583,7 +1822,9 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1583
1822
|
}
|
|
1584
1823
|
const pairCache = new Map()
|
|
1585
1824
|
const similarityOf = (a, b) => {
|
|
1586
|
-
const
|
|
1825
|
+
const ka = itemKey(a)
|
|
1826
|
+
const kb = itemKey(b)
|
|
1827
|
+
const key = ka < kb ? `${ka}\u0000${kb}` : `${kb}\u0000${ka}`
|
|
1587
1828
|
if (pairCache.has(key)) return pairCache.get(key)
|
|
1588
1829
|
const value = similarTexts(textOf(a), textOf(b))
|
|
1589
1830
|
pairCache.set(key, value)
|
|
@@ -1592,8 +1833,9 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1592
1833
|
// Anchor the penalty to the best raw score so the diversity term is on the same
|
|
1593
1834
|
// scale as relevance instead of being dominated by it.
|
|
1594
1835
|
const ceiling = Number(items[0]?.score || 0) || 1
|
|
1595
|
-
// dropped
|
|
1596
|
-
// stays blocked (chosen only grows), and the map keeps
|
|
1836
|
+
// dropped identity -> kept/dropped names. Recorded across rounds; an item
|
|
1837
|
+
// hard-blocked in one round stays blocked (chosen only grows), and the map keeps
|
|
1838
|
+
// it reported exactly once.
|
|
1597
1839
|
const blocked = new Map()
|
|
1598
1840
|
while (pool.length > 0 && chosen.length < limit) {
|
|
1599
1841
|
let bestIdx = -1
|
|
@@ -1603,10 +1845,10 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1603
1845
|
let twin = null
|
|
1604
1846
|
for (const picked of chosen) {
|
|
1605
1847
|
const similarity = similarityOf(pool[i], picked)
|
|
1606
|
-
if (similarity >= DUP_DICE) { twin = picked
|
|
1848
|
+
if (similarity >= DUP_DICE) { twin = picked; break }
|
|
1607
1849
|
if (similarity >= TOPIC_DICE) overlap = Math.max(overlap, similarity)
|
|
1608
1850
|
}
|
|
1609
|
-
if (twin) { blocked.set(pool[i].name,
|
|
1851
|
+
if (twin) { blocked.set(itemKey(pool[i]), { kept: twin.name, dropped: pool[i].name }); continue }
|
|
1610
1852
|
const adjusted = Number(pool[i].score || 0) - lambda * overlap * ceiling
|
|
1611
1853
|
if (adjusted > bestScore) { bestScore = adjusted; bestIdx = i }
|
|
1612
1854
|
}
|
|
@@ -1614,7 +1856,7 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1614
1856
|
chosen.push(pool.splice(bestIdx, 1)[0])
|
|
1615
1857
|
}
|
|
1616
1858
|
const skipped = []
|
|
1617
|
-
for (const
|
|
1859
|
+
for (const { kept, dropped } of blocked.values()) {
|
|
1618
1860
|
let group = skipped.find((g) => g.kept === kept)
|
|
1619
1861
|
if (!group) { group = { kept, dropped: [] }; skipped.push(group) }
|
|
1620
1862
|
group.dropped.push(dropped)
|
|
@@ -2341,57 +2583,95 @@ function domainScopedIndex(index, domain) {
|
|
|
2341
2583
|
}
|
|
2342
2584
|
}
|
|
2343
2585
|
|
|
2344
|
-
//
|
|
2345
|
-
//
|
|
2346
|
-
//
|
|
2347
|
-
|
|
2586
|
+
// R4:进入统一语料前的资格门,与 privateWeighted 的过滤链同一套谓词。不可见
|
|
2587
|
+
// 条目不能先占候选位再被丢弃,更不能进 BM25 语料改变 IDF 后影响可见条目的排序
|
|
2588
|
+
// (侧信道)。secret 的自动排除已含在 isMemoryEligible({automatic}) 内。
|
|
2589
|
+
function crossLibraryEligible(entry, { automatic, sessionId, disclosureAsked, speakerFilter }) {
|
|
2590
|
+
return isMemoryEligible(entry, { automatic })
|
|
2591
|
+
&& visibleToSession(entry, sessionId)
|
|
2592
|
+
&& isDisclosureEligible(entry, { automatic, asked: disclosureAsked })
|
|
2593
|
+
&& speakerMatchesFilter(entry, speakerFilter)
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
// R4:跨库统一词法评分。文档身份是复合 [libraryId,id] key,两库同 id 是两份
|
|
2597
|
+
// 文档而不是同一份;语料指纹含复合 id,任一成员库内容变化都会失效共享语料。
|
|
2598
|
+
// 评分规则与 localRecall 的 BM25 分支一致(日期加成、证据分离、date-only 末位),
|
|
2599
|
+
// 只是 IDF/avgdl 来自授权集合的统一语料,分数跨库可比。
|
|
2600
|
+
function crossLibraryLexical(files, query, { cacheKey = null, topK = null } = {}) {
|
|
2601
|
+
const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
|
|
2602
|
+
const topic = dominanceQuery(query)
|
|
2603
|
+
const evidenceChanged = topic !== String(query || '')
|
|
2604
|
+
if (recallLexicalMode() === 'includes') {
|
|
2605
|
+
const tokens = queryTokens(query)
|
|
2606
|
+
if (tokens.length === 0) return { files: files.slice().sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), mode: 'recency' }
|
|
2607
|
+
const evidenceTokens = evidenceChanged ? queryTokens(topic) : null
|
|
2608
|
+
const ordered = files
|
|
2609
|
+
.map((file) => ({ ...file, lexical: lexicalScore(file.entry, tokens, queryDates),
|
|
2610
|
+
lexicalEvidence: lexicalScore(file.entry, evidenceTokens || tokens, []) }))
|
|
2611
|
+
.filter((file) => file.lexical > 0)
|
|
2612
|
+
.sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
|
|
2613
|
+
return { files: ordered, mode: 'includes' }
|
|
2614
|
+
}
|
|
2615
|
+
const tokens = tokenize(query)
|
|
2616
|
+
if (tokens.length === 0) return { files: files.slice().sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), mode: 'recency' }
|
|
2617
|
+
const docId = (file) => JSON.stringify([file.libraryId ?? null, file.name])
|
|
2618
|
+
const corpus = lexicalCorpusFor(files.map((file) => ({ name: docId(file), entry: file.entry })), cacheKey)
|
|
2619
|
+
const evidenceTokens = evidenceChanged ? tokenize(topic) : null
|
|
2620
|
+
const scored = files.map((file) => {
|
|
2621
|
+
const doc = corpus.docs.get(docId(file))
|
|
2622
|
+
const lexical = doc ? bm25(tokens, doc, corpus) : 0
|
|
2623
|
+
return {
|
|
2624
|
+
file,
|
|
2625
|
+
lexical,
|
|
2626
|
+
lexicalEvidence: evidenceTokens && doc ? bm25(evidenceTokens, doc, corpus) : lexical,
|
|
2627
|
+
dateMatch: Boolean(file.entry?.absolute_date && queryDates.includes(file.entry.absolute_date)),
|
|
2628
|
+
}
|
|
2629
|
+
})
|
|
2630
|
+
const best = scored.reduce((max, item) => Math.max(max, item.lexical), 0)
|
|
2631
|
+
const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
|
|
2632
|
+
const ordered = scored
|
|
2633
|
+
.map(({ file, lexical, lexicalEvidence: evidence, dateMatch }) => ({
|
|
2634
|
+
...file,
|
|
2635
|
+
...(evidence === undefined ? {} : { lexicalEvidence: evidence }),
|
|
2636
|
+
lexical: lexical > 0
|
|
2637
|
+
? lexical * (dateMatch ? DATE_MATCH_FACTOR : 1)
|
|
2638
|
+
: (dateMatch ? dateOnly : 0),
|
|
2639
|
+
}))
|
|
2640
|
+
.filter((file) => file.lexical > 0)
|
|
2641
|
+
.sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
|
|
2642
|
+
return { files: ordered, mode: 'unified-bm25' }
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
// R4:跨库融合不再把各库榜单当同等投票(各库第一名同分会让弱外库首名挤掉强
|
|
2646
|
+
// 本库命中),也不按裸 id 折叠(两库同 id 是两条事实)。词法腿用统一授权语料的
|
|
2647
|
+
// 可比分数;向量腿在原始相似度齐全且同代际时按分数全局排序,否则保留显式标记
|
|
2648
|
+
// 的 rank-only 限制。RRF 只用于“词法与向量两种方法对同一候选集合”的融合。
|
|
2649
|
+
async function recallCrossLibrary({ exec, sources, query, topK, route, byId, automatic, intent, retrieveImpl, domain, disclosureAsked = false, speakerFilter = null }) {
|
|
2650
|
+
const sessionId = memorySessionId(exec)
|
|
2651
|
+
const gate = { automatic, sessionId, disclosureAsked, speakerFilter }
|
|
2652
|
+
const rowKey = (libraryId, name) => JSON.stringify([libraryId ?? null, name])
|
|
2348
2653
|
const lists = []
|
|
2349
2654
|
for (const source of sources) {
|
|
2350
2655
|
const scoped = source.primary ? source.index : domainScopedIndex(source.index, domain)
|
|
2351
2656
|
if (route === 'lexical' || byId) {
|
|
2352
|
-
|
|
2657
|
+
const files = byId
|
|
2658
|
+
? localRecall(scoped, query, undefined, { cacheKey: `lib:${source.libraryId}:${domain || 'all'}`, topK }).files
|
|
2659
|
+
: localIndexFiles(scoped).filter((file) => crossLibraryEligible(file.entry, gate))
|
|
2660
|
+
lists.push({ libraryId: source.libraryId, files: files.map((file) => ({ ...file, libraryId: source.libraryId })) })
|
|
2353
2661
|
continue
|
|
2354
2662
|
}
|
|
2355
2663
|
const managed = await managedRecall({
|
|
2356
|
-
exec, index: scoped,
|
|
2357
|
-
automatic, intent, retrieveImpl, byId, domain,
|
|
2664
|
+
exec, index: scoped, sourceEmpty: Object.keys(source.index.entries || {}).length === 0,
|
|
2665
|
+
query, topK, libraryId: source.libraryId, automatic, intent, retrieveImpl, byId, domain,
|
|
2358
2666
|
})
|
|
2359
|
-
lists.push({
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
list.files.forEach((file, position) => {
|
|
2365
|
-
const key = list.libraryId + '\u0000' + file.name
|
|
2366
|
-
const row = rows.get(key) || { file: { ...file, libraryId: list.libraryId }, rrf: 0, bestRank: Infinity }
|
|
2367
|
-
row.rrf += 1 / (RRF_K + position + 1)
|
|
2368
|
-
row.bestRank = Math.min(row.bestRank, position + 1)
|
|
2369
|
-
rows.set(key, row)
|
|
2667
|
+
lists.push({
|
|
2668
|
+
libraryId: source.libraryId,
|
|
2669
|
+
vectorGeneration: managed.vectorGeneration ?? null,
|
|
2670
|
+
files: (managed.files || []).filter((file) => crossLibraryEligible(file.entry, gate)).map((file) => ({ ...file, libraryId: source.libraryId })),
|
|
2671
|
+
errors: managed.errors || [],
|
|
2370
2672
|
})
|
|
2371
2673
|
}
|
|
2372
|
-
const
|
|
2373
|
-
const primaryId = sources.find((source) => source.primary)?.libraryId || null
|
|
2374
|
-
const ordered = [...rows.values()]
|
|
2375
|
-
.map((row) => ({
|
|
2376
|
-
...row.file,
|
|
2377
|
-
entry: row.file.entry || null,
|
|
2378
|
-
content: String(row.file.content ?? row.file.entry?.content ?? ''),
|
|
2379
|
-
strength: Number.isFinite(Number(row.file.strength)) ? Number(row.file.strength) : decayStrength(row.file.entry),
|
|
2380
|
-
createdAtIdentity: row.file.createdAtIdentity ?? row.file.entry?.createdAt ?? null,
|
|
2381
|
-
retrievalScore: row.rrf / maxRrf,
|
|
2382
|
-
fusion: { ...(row.file.fusion || {}), crossLibraryRrf: row.rrf, bestRank: row.bestRank },
|
|
2383
|
-
}))
|
|
2384
|
-
.sort((a, b) => b.retrievalScore - a.retrievalScore
|
|
2385
|
-
|| String(b.entry?.updatedAt || b.entry?.createdAt || '').localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || '')))
|
|
2386
|
-
// The same id can exist in two libraries (ids are generated per library). Keep
|
|
2387
|
-
// the bound library's copy so an id shown by recall resolves there first.
|
|
2388
|
-
const chosen = new Map()
|
|
2389
|
-
for (const file of ordered) {
|
|
2390
|
-
const current = chosen.get(file.name)
|
|
2391
|
-
if (!current || (file.libraryId === primaryId && current.libraryId !== primaryId)) chosen.set(file.name, file)
|
|
2392
|
-
}
|
|
2393
|
-
return {
|
|
2394
|
-
files: [...chosen.values()],
|
|
2674
|
+
const base = {
|
|
2395
2675
|
segments: [],
|
|
2396
2676
|
resources: [],
|
|
2397
2677
|
raw: null,
|
|
@@ -2400,9 +2680,177 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
|
|
|
2400
2680
|
libraries: sources.map((source) => source.libraryId),
|
|
2401
2681
|
errors: lists.flatMap((list) => (list.errors || []).map((error) => `${list.libraryId}: ${error}`)),
|
|
2402
2682
|
}
|
|
2683
|
+
const primaryId = sources.find((source) => source.primary)?.libraryId || null
|
|
2684
|
+
if (byId) {
|
|
2685
|
+
// 精确 id 保留每个库自己的文档;本库优先只决定顺序,不丢外库同 id 事实。
|
|
2686
|
+
const files = lists.flatMap((list) => list.files)
|
|
2687
|
+
.map((file) => ({ ...file, retrievalScore: 1, fusion: { rawRetrievalScore: 1, crossLibraryLexical: 'exact-id' } }))
|
|
2688
|
+
.sort((a, b) => (a.libraryId === primaryId ? 0 : 1) - (b.libraryId === primaryId ? 0 : 1))
|
|
2689
|
+
return { ...base, files, fusion: { crossLibraryLexical: 'exact-id' } }
|
|
2690
|
+
}
|
|
2691
|
+
if (route === 'lexical') {
|
|
2692
|
+
const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${automatic ? 'auto' : 'explicit'}:${disclosureAsked ? 'asked' : 'plain'}`
|
|
2693
|
+
const unified = crossLibraryLexical(lists.flatMap((list) => list.files), query, { cacheKey, topK })
|
|
2694
|
+
if (unified.mode === 'recency') {
|
|
2695
|
+
return { ...base, files: unified.files, fusion: { crossLibraryLexical: 'recency' } }
|
|
2696
|
+
}
|
|
2697
|
+
const maxLexical = unified.files.reduce((max, file) => Math.max(max, Number(file.lexical) || 0), 0) || 1
|
|
2698
|
+
const adjusted = applyLexicalDominance(unified.files.map((file) => ({
|
|
2699
|
+
...file,
|
|
2700
|
+
entry: file.entry || null,
|
|
2701
|
+
content: String(file.content ?? file.entry?.content ?? ''),
|
|
2702
|
+
strength: Number.isFinite(Number(file.strength)) ? Number(file.strength) : decayStrength(file.entry),
|
|
2703
|
+
createdAtIdentity: file.createdAtIdentity ?? file.entry?.createdAt ?? null,
|
|
2704
|
+
retrievalScore: Math.min(1, (Number(file.lexical) || 0) / maxLexical),
|
|
2705
|
+
fusion: { rawRetrievalScore: Math.min(1, (Number(file.lexical) || 0) / maxLexical), crossLibraryLexical: unified.mode },
|
|
2706
|
+
})), 'cross-library')
|
|
2707
|
+
return {
|
|
2708
|
+
...base,
|
|
2709
|
+
files: adjusted.files.sort((a, b) => b.retrievalScore - a.retrievalScore
|
|
2710
|
+
|| String(b.entry?.updatedAt || b.entry?.createdAt || '').localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || ''))),
|
|
2711
|
+
fusion: { lexicalDominance: adjusted.dominance, crossLibraryLexical: unified.mode },
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
// hybrid:各库 managedRecall 保留自己的缓存与降级;合并后对候选并集做统一
|
|
2715
|
+
// 词法评分与方法间 RRF。并集随 query 变化,不做语料缓存(有界小集合)。
|
|
2716
|
+
const rows = new Map()
|
|
2717
|
+
for (const list of lists) {
|
|
2718
|
+
for (const file of list.files) {
|
|
2719
|
+
const key = rowKey(list.libraryId, file.name)
|
|
2720
|
+
// Number(null) 是 0:词法-only 行的 fusion.semanticRank 显式为 null,
|
|
2721
|
+
// 不先挡掉会被当成合法的 rank 0 混进向量腿。
|
|
2722
|
+
const rawScore = file.fusion?.semanticScore
|
|
2723
|
+
const rawRank = file.fusion?.semanticRank
|
|
2724
|
+
const score = rawScore == null ? NaN : Number(rawScore)
|
|
2725
|
+
const rank = rawRank == null ? NaN : Number(rawRank)
|
|
2726
|
+
const current = rows.get(key)
|
|
2727
|
+
if (current) {
|
|
2728
|
+
current.file = inheritLexicalEvidence(current.file, file)
|
|
2729
|
+
if (Number.isFinite(score)) current.semanticScore = Math.max(current.semanticScore ?? -Infinity, score)
|
|
2730
|
+
if (Number.isFinite(rank)) current.semanticRank = Math.min(current.semanticRank ?? Infinity, rank)
|
|
2731
|
+
continue
|
|
2732
|
+
}
|
|
2733
|
+
rows.set(key, {
|
|
2734
|
+
key,
|
|
2735
|
+
file: { ...file, libraryId: list.libraryId },
|
|
2736
|
+
semanticScore: Number.isFinite(score) ? score : null,
|
|
2737
|
+
semanticRank: Number.isFinite(rank) ? rank : null,
|
|
2738
|
+
vectorGeneration: list.vectorGeneration ?? null,
|
|
2739
|
+
})
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
const semanticRows = [...rows.values()].filter((row) => row.semanticRank !== null)
|
|
2743
|
+
const generations = new Set(semanticRows.map((row) => row.vectorGeneration))
|
|
2744
|
+
const semanticComparable = semanticRows.length > 0
|
|
2745
|
+
&& semanticRows.every((row) => row.semanticScore !== null)
|
|
2746
|
+
&& generations.size <= 1
|
|
2747
|
+
const semanticMode = semanticRows.length === 0 ? 'none' : semanticComparable ? 'score' : 'rank-only'
|
|
2748
|
+
const unified = crossLibraryLexical([...rows.values()].map((row) => row.file), query, { topK })
|
|
2749
|
+
const lexicalRank = new Map(unified.files.map((file, position) => [rowKey(file.libraryId, file.name), position + 1]))
|
|
2750
|
+
const lexicalByKey = new Map(unified.files.map((file) => [rowKey(file.libraryId, file.name), file]))
|
|
2751
|
+
const semanticRank = semanticComparable
|
|
2752
|
+
? new Map(semanticRows.slice()
|
|
2753
|
+
.sort((a, b) => b.semanticScore - a.semanticScore || a.key.localeCompare(b.key))
|
|
2754
|
+
.map((row, position) => [row.key, position + 1]))
|
|
2755
|
+
: new Map(semanticRows.map((row) => [row.key, row.semanticRank]))
|
|
2756
|
+
const fusedRows = [...rows.values()].map((row) => {
|
|
2757
|
+
const lex = lexicalRank.get(row.key)
|
|
2758
|
+
const sem = semanticRank.get(row.key)
|
|
2759
|
+
const rrf = (lex ? 1 / (HYBRID_RRF_K + lex) : 0) + (sem ? 1 / (HYBRID_RRF_K + sem) : 0)
|
|
2760
|
+
const bestRank = Math.min(lex ?? Infinity, sem ?? Infinity)
|
|
2761
|
+
return { ...row, rrf, bestRank: Number.isFinite(bestRank) ? bestRank : null, lexicalFile: lexicalByKey.get(row.key) || null }
|
|
2762
|
+
})
|
|
2763
|
+
const maxRrf = fusedRows.reduce((max, row) => Math.max(max, row.rrf), 0) || 1
|
|
2764
|
+
const adjusted = applyLexicalDominance(fusedRows.map((row) => ({
|
|
2765
|
+
...row.file,
|
|
2766
|
+
...(row.lexicalFile ? { lexical: row.lexicalFile.lexical, lexicalEvidence: row.lexicalFile.lexicalEvidence ?? row.lexicalFile.lexical } : {}),
|
|
2767
|
+
entry: row.file.entry || null,
|
|
2768
|
+
content: String(row.file.content ?? row.file.entry?.content ?? ''),
|
|
2769
|
+
strength: Number.isFinite(Number(row.file.strength)) ? Number(row.file.strength) : decayStrength(row.file.entry),
|
|
2770
|
+
createdAtIdentity: row.file.createdAtIdentity ?? row.file.entry?.createdAt ?? null,
|
|
2771
|
+
retrievalScore: row.rrf / maxRrf,
|
|
2772
|
+
fusion: { ...(row.file.fusion || {}), rawRetrievalScore: row.rrf / maxRrf, crossLibraryRrf: row.rrf, bestRank: row.bestRank,
|
|
2773
|
+
crossLibraryLexical: unified.mode, crossLibrarySemantic: semanticMode },
|
|
2774
|
+
})), 'cross-library')
|
|
2775
|
+
return {
|
|
2776
|
+
...base,
|
|
2777
|
+
files: adjusted.files.sort((a, b) => b.retrievalScore - a.retrievalScore
|
|
2778
|
+
|| String(b.entry?.updatedAt || b.entry?.createdAt || '').localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || ''))),
|
|
2779
|
+
fusion: { lexicalDominance: adjusted.dominance, crossLibraryLexical: unified.mode, crossLibrarySemantic: semanticMode },
|
|
2780
|
+
}
|
|
2403
2781
|
}
|
|
2404
2782
|
|
|
2405
|
-
|
|
2783
|
+
function memoryReadError(code, message) {
|
|
2784
|
+
return Object.assign(new Error(message), { code })
|
|
2785
|
+
}
|
|
2786
|
+
|
|
2787
|
+
export function readMemoryByRef({ exec, scope = 'private', id, libraryId = null, offset = 0, limitChars = 2000, revision = null }) {
|
|
2788
|
+
if (!['private', 'global'].includes(scope)) throw memoryReadError('MEMORY_SCOPE_INVALID', 'scope must be private or global')
|
|
2789
|
+
if (!/^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(id || '').trim())) throw memoryReadError('EXACT_ID_REQUIRED', 'full-body reads require a memory id')
|
|
2790
|
+
if (!Number.isInteger(offset) || offset < 0) throw memoryReadError('MEMORY_OFFSET_INVALID', 'offset must be a non-negative code point integer')
|
|
2791
|
+
if (!Number.isInteger(limitChars) || limitChars < 1 || limitChars > 8000) throw memoryReadError('MEMORY_LIMIT_INVALID', 'limitChars must be an integer from 1 to 8000')
|
|
2792
|
+
if (revision !== null && typeof revision !== 'string') throw memoryReadError('MEMORY_REVISION_INVALID', 'revision must be the token from the previous page')
|
|
2793
|
+
if (offset > 0 && !revision) throw memoryReadError('REVISION_REQUIRED', 'continuation pages require the previous body revision')
|
|
2794
|
+
if (libraryId !== null && (scope !== 'private' || typeof libraryId !== 'string')) throw memoryReadError('MEMORY_LIBRARY_FORBIDDEN', 'libraryId is only supported for private memory ids')
|
|
2795
|
+
const binding = peekBinding(exec)
|
|
2796
|
+
if (scope === 'private' && !binding?.libraryId) throw memoryReadError('MEMORY_UNBOUND', 'this conversation has no bound memory library')
|
|
2797
|
+
assertScopeEnabled(binding, { layer: scope === 'private' ? 'library' : 'global' })
|
|
2798
|
+
const generation = binding ? scopeGenerationOf(binding) : null
|
|
2799
|
+
const domain = domainOf(binding || { domain: 'general' })
|
|
2800
|
+
const sources = scope === 'global' ? [{ libraryId: null, primary: true }]
|
|
2801
|
+
: getSettings().crossLibraryRecall === true ? crossLibrarySources(binding, domain) : [{ libraryId: binding.libraryId, primary: true }]
|
|
2802
|
+
if (libraryId !== null && !sources.some(source => source.libraryId === libraryId)) throw memoryReadError('MEMORY_LIBRARY_FORBIDDEN', 'that library is outside this conversation memory scope')
|
|
2803
|
+
const matches = []
|
|
2804
|
+
for (const source of sources.filter(source => libraryId === null || source.libraryId === libraryId)) {
|
|
2805
|
+
const index = scope === 'global' ? loadGlobalIndex() : loadPrivateIndex(source.libraryId)
|
|
2806
|
+
if (readFailure(path.join(indexDir(), scope === 'global' ? 'global.json' : source.libraryId + '.json'))) throw memoryReadError('MEMORY_STORAGE_UNAVAILABLE', 'the memory index could not be read safely')
|
|
2807
|
+
let canonical
|
|
2808
|
+
try { canonical = resolveEntryId(index, String(id).trim()) } catch (error) {
|
|
2809
|
+
if (/ambiguous/i.test(error.message)) throw memoryReadError('MEMORY_ID_AMBIGUOUS', error.message)
|
|
2810
|
+
continue
|
|
2811
|
+
}
|
|
2812
|
+
matches.push({ source, index, canonical, entry: index.entries[canonical] })
|
|
2813
|
+
if (source.primary) break
|
|
2814
|
+
}
|
|
2815
|
+
if (!matches.length) throw memoryReadError('MEMORY_NOT_FOUND', 'the memory id was not found in the allowed libraries')
|
|
2816
|
+
if (matches.length > 1) throw memoryReadError('MEMORY_ID_AMBIGUOUS', 'the id exists in several libraries; specify its libraryId')
|
|
2817
|
+
const { source, index, canonical, entry } = matches[0]
|
|
2818
|
+
const automatic = scope === 'global'
|
|
2819
|
+
const canRead = candidate => isMemoryEligible(candidate, { automatic }) && visibleToSession(candidate, memorySessionId(exec))
|
|
2820
|
+
&& isDisclosureEligible(candidate, { automatic, asked: false })
|
|
2821
|
+
&& (scope === 'global' ? appliesToDomain(candidate, binding || { domain: 'general' }) : source.primary || !candidate.domain || candidate.domain === domain)
|
|
2822
|
+
if (!canRead(entry)) throw memoryReadError('MEMORY_NOT_READABLE', 'that memory is not eligible in this conversation')
|
|
2823
|
+
const body = redactSecrets(String(entry.content ?? ''))
|
|
2824
|
+
const bodyRevision = crypto.createHash('sha256').update(body).digest('hex')
|
|
2825
|
+
if (revision !== null && revision !== bodyRevision) throw memoryReadError('MEMORY_CHANGED', 'memory changed between pages; read again from offset 0')
|
|
2826
|
+
const points = Array.from(body)
|
|
2827
|
+
if (offset > points.length) throw memoryReadError('MEMORY_OFFSET_OUT_OF_RANGE', 'offset exceeds the redacted body length')
|
|
2828
|
+
const page = points.slice(offset, offset + limitChars)
|
|
2829
|
+
const nextOffset = offset + page.length < points.length ? offset + page.length : null
|
|
2830
|
+
const current = peekBinding(exec)
|
|
2831
|
+
if ((current ? scopeGenerationOf(current) : null) !== generation) throw memoryReadError('MEMORY_SCOPE_CHANGED', 'conversation memory scope changed; read again')
|
|
2832
|
+
assertScopeEnabled(current, { layer: scope === 'private' ? 'library' : 'global' })
|
|
2833
|
+
if (scope === 'private' && source.libraryId !== current.libraryId) {
|
|
2834
|
+
const allowed = getSettings().crossLibraryRecall === true ? crossLibrarySources(current, domainOf(current)) : []
|
|
2835
|
+
if (!allowed.some(item => item.libraryId === source.libraryId)) throw memoryReadError('MEMORY_SCOPE_CHANGED', 'the source library is no longer allowed')
|
|
2836
|
+
}
|
|
2837
|
+
const otherId = entry.conflicts_with || null
|
|
2838
|
+
const other = otherId ? index.entries[otherId] : null
|
|
2839
|
+
return {
|
|
2840
|
+
ref: { scope, libraryId: source.libraryId, id: canonical },
|
|
2841
|
+
title: redactSecrets(String(entry.title || '(untitled)')),
|
|
2842
|
+
body: page.join(''),
|
|
2843
|
+
revision: bodyRevision,
|
|
2844
|
+
pagination: { offset, returnedChars: page.length, totalChars: points.length, truncated: nextOffset !== null, nextOffset },
|
|
2845
|
+
provenance: { source: entry.source || 'inferred', sourceKind: entry.source_kind || null, speakerId: entry.speaker_id || null },
|
|
2846
|
+
restrictions: { visibility: entry.visibility || 'shared', disclosure: entry.disclosure || 'can_tell', status: entry.status || 'active', layer: entry.layer || 'long_term' },
|
|
2847
|
+
related: otherId ? [{ id: otherId, libraryId: source.libraryId, kind: 'conflict', available: Boolean(other && canRead(other)) }] : [],
|
|
2848
|
+
domain,
|
|
2849
|
+
unbound: !binding,
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
export async function privateRecall({ exec, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
|
|
2406
2854
|
const binding = peekBinding(exec)
|
|
2407
2855
|
if (!binding) throw new Error('no bound session')
|
|
2408
2856
|
if (!binding.libraryId) throw new Error('this conversation has no memory library')
|
|
@@ -2418,24 +2866,36 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
2418
2866
|
const queryDates = decomposed.dates
|
|
2419
2867
|
const searchQuery = decomposed.expanded
|
|
2420
2868
|
const route = effectiveVectorRoute(settings)
|
|
2421
|
-
const
|
|
2869
|
+
const requested = Math.max(1, Math.min(20, Math.floor(Number(topK ?? settings.privateTopK) || 5)))
|
|
2870
|
+
let candidateK = intentTopK(recallIntent, requested)
|
|
2871
|
+
const wanted = requested
|
|
2422
2872
|
const domain = domainOf(binding)
|
|
2423
2873
|
const sources = (settings.crossLibraryRecall === true
|
|
2424
2874
|
? crossLibrarySources(binding, domain)
|
|
2425
2875
|
: [{ libraryId: binding.libraryId, primary: true }])
|
|
2426
2876
|
.map((source) => ({ ...source, index: loadPrivateIndex(source.libraryId) }))
|
|
2877
|
+
if (purpose === 'automatic') {
|
|
2878
|
+
const allowed = new Set(sources.map(source => source.libraryId))
|
|
2879
|
+
const excludedCount = excludedRefs.filter(ref => ref?.scope === 'private' && allowed.has(ref.libraryId)).length
|
|
2880
|
+
if (excludedCount) candidateK = Math.min(HYBRID_CANDIDATE_MAX, candidateK + excludedCount)
|
|
2881
|
+
}
|
|
2882
|
+
const generationAtStart = scopeGenerationOf(binding)
|
|
2427
2883
|
// Single source keeps the old path byte-for-byte; the cross-library merge only
|
|
2428
2884
|
// exists when another qualifying library is actually present.
|
|
2885
|
+
const retrievalStarted = performance.now()
|
|
2429
2886
|
const result = sources.length === 1
|
|
2430
2887
|
? (route === 'lexical' || byId
|
|
2431
|
-
? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK:
|
|
2432
|
-
: await managedRecall({ exec, index: sources[0].index,
|
|
2433
|
-
|
|
2888
|
+
? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK: candidateK }), recallRoute: 'local' }
|
|
2889
|
+
: await managedRecall({ exec, index: sources[0].index, sourceEmpty: Object.keys(sources[0].index.entries || {}).length === 0,
|
|
2890
|
+
query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
|
|
2891
|
+
: await recallCrossLibrary({ exec, sources, query: searchQuery, topK: candidateK, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain,
|
|
2892
|
+
disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) })
|
|
2893
|
+
const retrievalMs = performance.now() - retrievalStarted
|
|
2434
2894
|
const current = peekBinding(exec)
|
|
2435
|
-
if (!current || current.libraryId !== binding.libraryId) throw new Error('memory scope changed during recall; retry')
|
|
2895
|
+
if (!current || current.libraryId !== binding.libraryId || scopeGenerationOf(current) !== generationAtStart) throw new Error('memory scope changed during recall; retry')
|
|
2436
2896
|
assertScopeEnabled(current)
|
|
2437
2897
|
const index = loadPrivateIndex(binding.libraryId)
|
|
2438
|
-
const indexByLibrary = new Map(sources.map((source) => [source.libraryId, source.libraryId === binding.libraryId ? index : source.index]))
|
|
2898
|
+
const indexByLibrary = new Map(sources.map((source) => [source.libraryId, source.libraryId === binding.libraryId ? index : domainScopedIndex(source.index, domain)]))
|
|
2439
2899
|
// enrichFiles fills body/strength from one index; doing that against the bound
|
|
2440
2900
|
// library would blank every foreign hit. Cross-library files already carry
|
|
2441
2901
|
// their entry from the library that produced them.
|
|
@@ -2458,6 +2918,8 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
2458
2918
|
(source.libraryId === binding.libraryId ? index : source.index).entries || {},
|
|
2459
2919
|
).map((entry) => ({ entry }))))
|
|
2460
2920
|
const mood = moodDecay(binding.mood)
|
|
2921
|
+
const canRead = entry => isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, memorySessionId(exec))
|
|
2922
|
+
&& isDisclosureEligible(entry, { automatic: true, asked: recallIntent === 'boundary' })
|
|
2461
2923
|
const scored = privateWeighted(enriched, wanted, {
|
|
2462
2924
|
// Three independent legs: a clear composition, an arousal away from rest, or a
|
|
2463
2925
|
// clear sense of control. A null composition only closes the first one — a tense
|
|
@@ -2477,64 +2939,26 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
2477
2939
|
// The asking conversation's context is what memories are filtered against; the id is
|
|
2478
2940
|
// only how that context is looked up.
|
|
2479
2941
|
sessionId: memorySessionId(exec),
|
|
2480
|
-
automatic: purpose === 'automatic',
|
|
2942
|
+
automatic: purpose === 'automatic', excludedRefs, indexesByLibrary: indexByLibrary, canRead,
|
|
2481
2943
|
})
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
//
|
|
2485
|
-
// 座位是共享的,不是白送的:一半的矛盾读起来像一条已定论的事实,比不召回更糟,
|
|
2486
|
-
// 所以配对优先于「最后一条边缘记忆」。追加完之后按需从尾部挤掉**没有配对**的
|
|
2487
|
-
// 条目,让 files.length 回到 wanted。只剩配对时挤不动——那时配对更重要,并且
|
|
2488
|
-
// 会留下一条可观测记录,而不是让「不变量」在无人知晓的地方破掉。
|
|
2489
|
-
const paired = new Set((scored.files || []).map((file) => file.name))
|
|
2944
|
+
const paired = new Set(scored.files.map(file => JSON.stringify([file.libraryId || binding.libraryId, file.name])))
|
|
2945
|
+
const groupsByKey = new Map((scored.groups || []).map(group => [group.key, group]))
|
|
2490
2946
|
const conflictPairs = []
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
const
|
|
2495
|
-
if (!
|
|
2496
|
-
|
|
2947
|
+
const pairKeys = new Set()
|
|
2948
|
+
for (const file of scored.files) {
|
|
2949
|
+
const group = groupsByKey.get(file.groupKey)
|
|
2950
|
+
const otherId = file.entry?.conflicts_with || (group?.conflict ? group.files.find(other => other.name !== file.name)?.name : null)
|
|
2951
|
+
if (!otherId) continue
|
|
2952
|
+
const owner = file.libraryId || binding.libraryId
|
|
2497
2953
|
file.conflictPair = otherId
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
})
|
|
2507
|
-
paired.add(otherId)
|
|
2508
|
-
conflictPairs.push({ a: file.name, b: otherId })
|
|
2509
|
-
}
|
|
2510
|
-
if (conflictPairs.length) {
|
|
2511
|
-
scored.conflictPairs = conflictPairs
|
|
2512
|
-
const seatBudget = Math.max(1, Number(wanted) || scored.files.length)
|
|
2513
|
-
while (scored.files.length > seatBudget) {
|
|
2514
|
-
let victim = -1
|
|
2515
|
-
for (let i = scored.files.length - 1; i >= 0; i -= 1) {
|
|
2516
|
-
if (scored.files[i]?.conflictPair) continue
|
|
2517
|
-
victim = i
|
|
2518
|
-
break
|
|
2519
|
-
}
|
|
2520
|
-
if (victim === -1) break
|
|
2521
|
-
scored.files.splice(victim, 1)
|
|
2522
|
-
}
|
|
2523
|
-
// Everything left is a half of a pair: the block is bigger than topK and the user
|
|
2524
|
-
// is about to pay for it. Say so once, with numbers, instead of letting it look
|
|
2525
|
-
// like a rounding error in the token budget.
|
|
2526
|
-
if (scored.files.length > seatBudget) {
|
|
2527
|
-
record({
|
|
2528
|
-
kind: 'recall',
|
|
2529
|
-
scope: 'private',
|
|
2530
|
-
sessionId: memorySessionId(exec),
|
|
2531
|
-
libraryId: binding.libraryId,
|
|
2532
|
-
message: `冲突对超出座位预算:${scored.files.length} 条 > topK ${seatBudget}`,
|
|
2533
|
-
detail: { wanted: seatBudget, delivered: scored.files.length, pairs: conflictPairs.length },
|
|
2534
|
-
refs: conflictPairs.map((pair) => pair.a).slice(0, 20),
|
|
2535
|
-
})
|
|
2536
|
-
}
|
|
2537
|
-
}
|
|
2954
|
+
file.conflictComplete = group ? group.complete : otherId !== file.name && paired.has(JSON.stringify([owner, otherId]))
|
|
2955
|
+
if (!file.conflictComplete) continue
|
|
2956
|
+
const key = JSON.stringify([owner, [file.name, otherId].sort()])
|
|
2957
|
+
if (pairKeys.has(key)) continue
|
|
2958
|
+
pairKeys.add(key)
|
|
2959
|
+
conflictPairs.push({ a: file.name, b: otherId, libraryId: owner })
|
|
2960
|
+
}
|
|
2961
|
+
if (conflictPairs.length) scored.conflictPairs = conflictPairs
|
|
2538
2962
|
// Being recalled is being used, and a memory that keeps being used should not fade
|
|
2539
2963
|
// like one nobody ever touches. Group by the library each hit came from so a
|
|
2540
2964
|
// cross-library recall touches the owning index, not the bound one.
|
|
@@ -2566,54 +2990,107 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
2566
2990
|
for (const file of scored.files || []) {
|
|
2567
2991
|
const fileLibraryId = file.libraryId || binding.libraryId
|
|
2568
2992
|
const fileIndex = indexByLibrary.get(fileLibraryId) || index
|
|
2993
|
+
file.ref ??= memoryRef({ scope: 'private', libraryId: fileLibraryId, id: file.name, entry: file.entry })
|
|
2569
2994
|
if (file.entry?.attachments?.length) {
|
|
2570
2995
|
file.entry = { ...file.entry, attachments: file.entry.attachments.map(item => {
|
|
2571
2996
|
try { return { ...item, ...attachmentRefs(fileLibraryId, [{ sha256: item.sha256 }])[0] } } catch { return { ...item, missing: true } }
|
|
2572
2997
|
}) }
|
|
2573
2998
|
}
|
|
2574
2999
|
try { file.related = recallRelations(fileLibraryId, fileIndex, file.name, memorySessionId(exec)) } catch { file.related = [] }
|
|
3000
|
+
if (file.conflictPair) {
|
|
3001
|
+
const other = fileIndex.entries[file.conflictPair]
|
|
3002
|
+
const available = Boolean(other && isMemoryEligible(other, { automatic: purpose === 'automatic' })
|
|
3003
|
+
&& visibleToSession(other, memorySessionId(exec)) && isDisclosureEligible(other, { automatic: purpose === 'automatic', asked: recallIntent === 'boundary' }))
|
|
3004
|
+
file.related = [...file.related.filter(item => item.id !== file.conflictPair), {
|
|
3005
|
+
id: file.conflictPair, libraryId: fileLibraryId, kind: 'conflict', available,
|
|
3006
|
+
complete: file.conflictComplete, title: available ? other.title || '(untitled)' : '不可见或不可用版本',
|
|
3007
|
+
}]
|
|
3008
|
+
}
|
|
2575
3009
|
}
|
|
2576
3010
|
// S5 多跳:沿显式 links 扩展一跳(人物/事件/时间线索),但只补 topK 的空位。
|
|
2577
3011
|
// 已经选满时不再追加:图扩展不额外占用注入预算。冲突对(S2)在更早一步成对
|
|
2578
3012
|
// 带回,它们属于既有语义,不计入这里的扩展额度。
|
|
2579
|
-
const
|
|
3013
|
+
const rankingSelectedRows = scored.groups ? scored.groups.reduce((sum, group) => sum + group.candidateRows, 0) : scored.files.length
|
|
3014
|
+
const conflictAddedRows = Math.max(0, scored.files.length - rankingSelectedRows)
|
|
3015
|
+
const expansionRoom = Math.max(0, Number(wanted) - (scored.groups?.length ?? scored.files.length))
|
|
2580
3016
|
const expansionLimit = Math.min(recallIntent === 'entity' ? 3 : 2, expansionRoom)
|
|
2581
|
-
const knownIds = new Set(scored.files.map(
|
|
3017
|
+
const knownIds = new Set(scored.files.map(file => JSON.stringify([file.libraryId || binding.libraryId, file.name])))
|
|
2582
3018
|
const expanded = []
|
|
3019
|
+
let expandedGroups = 0
|
|
2583
3020
|
// One hop is a guess: "the query hit this, and this is linked to it". A relation
|
|
2584
3021
|
// whose retention has decayed below the floor is a guess about something the user
|
|
2585
3022
|
// stopped caring about, and spending one of the two expansion seats on it costs a
|
|
2586
3023
|
// memory that actually matched. The floor is deliberately low — this filters dead
|
|
2587
3024
|
// edges, it does not rank friendships.
|
|
2588
3025
|
const EXPANSION_RETENTION_FLOOR = 0.2
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
3026
|
+
if (purpose === 'automatic' && expansionLimit > 0) {
|
|
3027
|
+
const candidates = []
|
|
3028
|
+
const collected = new Set()
|
|
3029
|
+
for (const file of scored.files) {
|
|
3030
|
+
for (const link of file.related || []) {
|
|
3031
|
+
const libraryId = file.libraryId || binding.libraryId
|
|
3032
|
+
const key = JSON.stringify([libraryId, link?.id])
|
|
3033
|
+
if (!link?.id || link.missing || link.kind === 'conflict' || knownIds.has(key) || collected.has(key)) continue
|
|
3034
|
+
if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
|
|
3035
|
+
const entry = indexByLibrary.get(libraryId)?.entries[link.id]
|
|
3036
|
+
if (!entry || !canRead(entry)) continue
|
|
3037
|
+
collected.add(key)
|
|
3038
|
+
candidates.push({ name: link.id, libraryId, entry, score: file.score || groupsByKey.get(file.groupKey)?.score || 0,
|
|
3039
|
+
relatedTo: file.name, relationKind: link.kind || 'related' })
|
|
3040
|
+
if (candidates.length >= HYBRID_CANDIDATE_MAX) break
|
|
3041
|
+
}
|
|
3042
|
+
if (candidates.length >= HYBRID_CANDIDATE_MAX) break
|
|
3043
|
+
}
|
|
3044
|
+
const recent = recentRefMap(excludedRefs, 'private')
|
|
3045
|
+
for (const group of groupConflictCandidates(candidates, indexByLibrary, { scope: 'private', canRead })) {
|
|
3046
|
+
if (expandedGroups >= expansionLimit) break
|
|
3047
|
+
if (group.truncated || groupWasSeen(group, recent) || group.refs.some(ref => knownIds.has(JSON.stringify([ref.libraryId, ref.id])))) continue
|
|
3048
|
+
const root = group.files.find(file => file.relatedTo)
|
|
3049
|
+
for (const file of group.files) {
|
|
3050
|
+
file.relatedTo = root?.relatedTo || null
|
|
3051
|
+
file.relationKind = root?.relationKind || 'related'
|
|
3052
|
+
file.conflictComplete = group.complete
|
|
3053
|
+
knownIds.add(JSON.stringify([file.libraryId, file.name]))
|
|
3054
|
+
expanded.push({ from: file.relatedTo, to: file.name, libraryId: file.libraryId, kind: file.relationKind })
|
|
3055
|
+
}
|
|
3056
|
+
scored.groups.push(group)
|
|
3057
|
+
scored.files.push(...group.files)
|
|
3058
|
+
expandedGroups += 1
|
|
3059
|
+
}
|
|
3060
|
+
} else if (purpose !== 'automatic') {
|
|
3061
|
+
for (const file of scored.files.slice()) {
|
|
2612
3062
|
if (expanded.length >= expansionLimit) break
|
|
3063
|
+
for (const link of file.related || []) {
|
|
3064
|
+
const fileLibraryId = file.libraryId || binding.libraryId
|
|
3065
|
+
const ref = JSON.stringify([fileLibraryId, link?.id])
|
|
3066
|
+
if (!link?.id || link.missing || link.kind === 'conflict' || knownIds.has(ref)) continue
|
|
3067
|
+
if (Number.isFinite(link.retention) && link.retention < EXPANSION_RETENTION_FLOOR) continue
|
|
3068
|
+
const fileIndex = indexByLibrary.get(fileLibraryId) || index
|
|
3069
|
+
const target = fileIndex.entries[link.id]
|
|
3070
|
+
if (!target) continue
|
|
3071
|
+
if (!isMemoryEligible(target, { automatic: false })) continue
|
|
3072
|
+
if (!visibleToSession(target, memorySessionId(exec)) || !isDisclosureEligible(target, { automatic: false, asked: recallIntent === 'boundary' })) continue
|
|
3073
|
+
knownIds.add(ref)
|
|
3074
|
+
scored.files.push({ name: link.id, libraryId: fileLibraryId, description: target.title || '', content: String(target.content || ''),
|
|
3075
|
+
entry: target, strength: decayStrength(target), createdAtIdentity: target.createdAt || null,
|
|
3076
|
+
relatedTo: file.name, relationKind: link.kind || 'related' })
|
|
3077
|
+
expanded.push({ from: file.name, to: link.id, kind: link.kind || 'related' })
|
|
3078
|
+
if (expanded.length >= expansionLimit) break
|
|
3079
|
+
}
|
|
2613
3080
|
}
|
|
2614
3081
|
}
|
|
2615
3082
|
if (expanded.length) scored.expanded = expanded
|
|
2616
3083
|
if (sources.length > 1) scored.libraries = sources.map((source) => source.libraryId)
|
|
3084
|
+
scored.trace.retrievalMs = retrievalMs
|
|
3085
|
+
scored.trace.request = { purpose, intent: recallIntent, requestedTopK: requested, candidateTopK: candidateK, maxGroups: purpose === 'automatic' ? wanted : null }
|
|
3086
|
+
scored.trace.counts.rankingSelectedRows = rankingSelectedRows
|
|
3087
|
+
scored.trace.counts.conflictAddedRows = conflictAddedRows
|
|
3088
|
+
scored.trace.counts.expandedRows = expanded.length
|
|
3089
|
+
scored.trace.counts.expandedGroups = expandedGroups
|
|
3090
|
+
scored.trace.counts.selectedRows = scored.files.length
|
|
3091
|
+
if (scored.groups) scored.trace.counts.selectedGroups = scored.groups.length
|
|
3092
|
+
for (const file of scored.files) file.ref ??= memoryRef({ scope: 'private', libraryId: file.libraryId || binding.libraryId, id: file.name, entry: file.entry })
|
|
3093
|
+
scored.refs = scored.files.map(file => file.ref)
|
|
2617
3094
|
return scored
|
|
2618
3095
|
}
|
|
2619
3096
|
|
|
@@ -3816,7 +4293,7 @@ export function appliesToDomain(entry, binding) {
|
|
|
3816
4293
|
return false
|
|
3817
4294
|
}
|
|
3818
4295
|
|
|
3819
|
-
export async function globalRecall({ exec, query, topK, relevanceThreshold, retrieveImpl = retrieve }) {
|
|
4296
|
+
export async function globalRecall({ exec, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
|
|
3820
4297
|
// peek, not ensure: injection has already bound any live session before a tool
|
|
3821
4298
|
// can run, so a missing binding here means a read from an unbound conversation.
|
|
3822
4299
|
// That fallback quietly narrows results to the `general` domain, so it is
|
|
@@ -3831,18 +4308,27 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
|
|
|
3831
4308
|
const sceneAt = Number.isFinite(Date.parse(binding.sceneTime || '')) ? new Date(binding.sceneTime) : new Date()
|
|
3832
4309
|
const queryDates = resolveQueryDates(query, { now: sceneAt, timeZone: DEFAULT_TIME_ZONE })
|
|
3833
4310
|
const searchQuery = queryDates.length ? `${query} ${queryDates.join(' ')}` : query
|
|
3834
|
-
const wanted = Number(topK
|
|
4311
|
+
const wanted = Math.max(1, Math.min(20, Math.floor(Number(topK ?? settings.globalTopK) || 5)))
|
|
4312
|
+
const queryIntent = detectQueryIntent(query)
|
|
4313
|
+
let candidateK = intentTopK(queryIntent, wanted)
|
|
4314
|
+
if (purpose === 'automatic') {
|
|
4315
|
+
const excludedCount = excludedRefs.filter(ref => ref?.scope === 'global').length
|
|
4316
|
+
if (excludedCount) candidateK = Math.min(HYBRID_CANDIDATE_MAX, candidateK + excludedCount)
|
|
4317
|
+
}
|
|
4318
|
+
const generationAtStart = scopeGenerationOf(peeked)
|
|
3835
4319
|
let index = loadGlobalIndex()
|
|
3836
4320
|
const intent = managedVectorIntent()
|
|
3837
4321
|
const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
|
|
3838
4322
|
.filter(([, entry]) => appliesToDomain(entry, binding))) }
|
|
4323
|
+
const retrievalStarted = performance.now()
|
|
3839
4324
|
const result = effectiveVectorRoute() !== 'lexical'
|
|
3840
|
-
? await managedRecall({ exec, index: domainIndex,
|
|
3841
|
-
libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
|
|
3842
|
-
: localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding), { cacheKey: `global:${domainOf(binding)}`, topK:
|
|
4325
|
+
? await managedRecall({ exec, index: domainIndex, sourceEmpty: Object.keys(index.entries || {}).length === 0,
|
|
4326
|
+
query: searchQuery, topK: candidateK, libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
|
|
4327
|
+
: localRecall(index, searchQuery, (file) => appliesToDomain(file.entry, binding), { cacheKey: `global:${domainOf(binding)}`, topK: candidateK })
|
|
4328
|
+
const retrievalMs = performance.now() - retrievalStarted
|
|
3843
4329
|
if (peeked) {
|
|
3844
4330
|
const current = peekBinding(exec)
|
|
3845
|
-
if (!current) throw new Error('memory binding changed during recall; retry')
|
|
4331
|
+
if (!current || scopeGenerationOf(current) !== generationAtStart) throw new Error('memory binding changed during recall; retry')
|
|
3846
4332
|
assertScopeEnabled(current, { layer: 'global' })
|
|
3847
4333
|
}
|
|
3848
4334
|
index = loadGlobalIndex()
|
|
@@ -3855,10 +4341,12 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
|
|
|
3855
4341
|
// a private runner-up at 0.75 survived while a global best of 5.4 and runner-up of
|
|
3856
4342
|
// 0.9 had the runner-up cut outright — the same setting meant two different things
|
|
3857
4343
|
// depending on which layer asked. Normalise against the best hit of this query.
|
|
4344
|
+
const selectionStarted = performance.now()
|
|
3858
4345
|
const bestLexical = enriched.files.reduce((max, f) => Math.max(max, Number(f.lexical) || 0), 0)
|
|
3859
4346
|
const filtered = enriched.files
|
|
3860
4347
|
.filter((f) => isMemoryEligible(f.entry, { automatic: true }))
|
|
3861
4348
|
.filter((f) => appliesToDomain(f.entry, binding))
|
|
4349
|
+
.filter((f) => visibleToSession(f.entry, memorySessionId(exec)) && isDisclosureEligible(f.entry, { automatic: true, asked: queryIntent === 'boundary' }))
|
|
3862
4350
|
.map((f, i) => {
|
|
3863
4351
|
const fused = Number(f.retrievalScore)
|
|
3864
4352
|
const lexical = Number(f.lexical) || 0
|
|
@@ -3881,10 +4369,45 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
|
|
|
3881
4369
|
}
|
|
3882
4370
|
})
|
|
3883
4371
|
.sort((a, b) => b.score - a.score)
|
|
3884
|
-
const
|
|
4372
|
+
const strong = cutWeakScores(filtered, threshold, RETRIEVAL_FLOOR, recallPercentile())
|
|
4373
|
+
if (purpose === 'automatic') {
|
|
4374
|
+
const recent = recentRefMap(excludedRefs, 'global')
|
|
4375
|
+
const groups = groupConflictCandidates(strong, new Map([[null, index]]), {
|
|
4376
|
+
scope: 'global', canRead: entry => isMemoryEligible(entry, { automatic: true }) && appliesToDomain(entry, binding)
|
|
4377
|
+
&& visibleToSession(entry, memorySessionId(exec)) && isDisclosureEligible(entry, { automatic: true, asked: queryIntent === 'boundary' }),
|
|
4378
|
+
})
|
|
4379
|
+
for (const group of groups) {
|
|
4380
|
+
group.reintroducedForConflict = group.conflict && group.refs.some(ref => recent.has(memoryRefKey(ref))) && !groupWasSeen(group, recent)
|
|
4381
|
+
group.reintroducedForRevision = group.refs.some(ref => recent.get(memoryRefKey(ref)) && recent.get(memoryRefKey(ref)).revision !== ref.revision)
|
|
4382
|
+
}
|
|
4383
|
+
const fresh = groups.filter(group => !group.truncated && !groupWasSeen(group, recent))
|
|
4384
|
+
const pool = mmrPool(fresh, wanted)
|
|
4385
|
+
const ranked = mmrSelect(pool, wanted)
|
|
4386
|
+
const files = ranked.chosen.flatMap(group => group.files)
|
|
4387
|
+
const recentGroups = groups.filter(group => !group.truncated && groupWasSeen(group, recent))
|
|
4388
|
+
return { ...enriched, files, refs: files.map(file => file.ref), groups: ranked.chosen,
|
|
4389
|
+
trace: { request: { purpose, intent: queryIntent, requestedTopK: wanted, candidateTopK: candidateK, maxGroups: wanted },
|
|
4390
|
+
retrievalMs, selectionMs: performance.now() - selectionStarted,
|
|
4391
|
+
counts: { retrievedRows: enriched.files.length, ineligibleRows: enriched.files.length - filtered.length,
|
|
4392
|
+
qualifiedRows: strong.length, weakRows: filtered.length - strong.length,
|
|
4393
|
+
recentRows: recentGroups.reduce((sum, group) => sum + group.candidateRows, 0), recentGroups: recentGroups.length,
|
|
4394
|
+
candidateGroups: groups.length, oversizedGroups: groups.filter(group => group.truncated).length,
|
|
4395
|
+
poolOmittedRows: fresh.slice(pool.length).reduce((sum, group) => sum + group.candidateRows, 0), poolOmittedGroups: fresh.length - pool.length,
|
|
4396
|
+
duplicateRows: ranked.skipped.reduce((sum, collapsed) => sum + collapsed.dropped.reduce((count, key) => count + (groups.find(group => group.key === key)?.files.length || 0), 0), 0),
|
|
4397
|
+
selectedRows: files.length, selectedGroups: ranked.chosen.length } },
|
|
4398
|
+
dedup: { collapsed: ranked.skipped, clusterCount: ranked.skipped.length }, domain: domainOf(binding), unbound: !peeked }
|
|
4399
|
+
}
|
|
4400
|
+
const pool = mmrPool(strong, wanted)
|
|
4401
|
+
const ranked = mmrSelect(pool, wanted)
|
|
4402
|
+
for (const file of ranked.chosen) file.ref = memoryRef({ scope: 'global', id: file.name, entry: file.entry })
|
|
3885
4403
|
return {
|
|
3886
4404
|
...enriched,
|
|
3887
|
-
files: ranked.chosen,
|
|
4405
|
+
files: ranked.chosen, refs: ranked.chosen.map(file => file.ref),
|
|
4406
|
+
trace: { request: { purpose, intent: queryIntent, requestedTopK: wanted, candidateTopK: candidateK },
|
|
4407
|
+
retrievalMs, selectionMs: performance.now() - selectionStarted,
|
|
4408
|
+
counts: { retrievedRows: enriched.files.length, ineligibleRows: enriched.files.length - filtered.length,
|
|
4409
|
+
weakRows: filtered.length - strong.length, poolOmittedRows: strong.length - pool.length,
|
|
4410
|
+
duplicateRows: new Set(ranked.skipped.flatMap(group => group.dropped || [])).size, selectedRows: ranked.chosen.length } },
|
|
3888
4411
|
dedup: { collapsed: ranked.skipped, clusterCount: ranked.skipped.length },
|
|
3889
4412
|
domain: domainOf(binding),
|
|
3890
4413
|
unbound: !peeked,
|