dsh-cortex-memory 0.4.161 → 0.5.0
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/CHANGELOG.md +18 -2536
- package/README.md +86 -45
- package/bin/cortex.mjs +0 -0
- package/client.js +35 -17
- package/cordis.patch.yml +2 -5
- package/docs/compatibility.md +13 -18
- package/docs/install-windows.md +1 -1
- package/examples/README.md +1 -1
- package/index.js +44 -6
- package/package.json +3 -3
- package/scripts/check-embedding.mjs +129 -0
- package/src/core/config.js +31 -4
- package/src/core/feature-overrides.js +3 -1
- package/src/engines/compression.js +2 -0
- package/src/engines/consolidate.js +7 -2
- package/src/engines/graph.js +25 -8
- package/src/engines/health.js +22 -3
- package/src/engines/induct.js +5 -1
- package/src/engines/linear-rerank-model.js +180 -0
- package/src/engines/linear-rerank.js +110 -0
- package/src/engines/query-expansion.js +61 -0
- package/src/engines/retention.js +4 -1
- package/src/engines/retrieve.js +257 -28
- package/src/engines/source-weights.js +13 -0
- package/src/host/scheduler.js +43 -0
- package/src/memory/tokenizer.js +31 -1
- package/src/prompt/assemble.js +160 -131
- package/src/prompt/tiers.js +15 -4
- package/src/self/working.js +53 -10
- package/src/service/cortex.js +167 -35
- package/src/store/database.js +61 -0
- package/src/store/repositories/entities.js +26 -1
- package/src/store/repositories/facts.js +36 -1
- package/src/store/repositories/traces.js +114 -15
- package/src/store/schema.sql +13 -0
- package/src/tools/definitions.js +1492 -1274
- package/src/vector/index.js +79 -8
- package/bench/results/semantic-cn.json +0 -24
- package/docs/quota-compaction-design.md +0 -175
package/src/engines/retrieve.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { retrievability } from '../memory/dsr.js';
|
|
2
|
-
import { estimateTokens, jaccard, overlapScore, tokens } from '../memory/tokenizer.js';
|
|
2
|
+
import { estimateTokens, jaccard, overlapScore, tokens, tokensCached } from '../memory/tokenizer.js';
|
|
3
3
|
import { daysBetween, nowIso } from '../core/time.js';
|
|
4
4
|
import { matchesFilters } from '../memory/query.js';
|
|
5
5
|
import { competingFactor, withSuppression } from './inhibition.js';
|
|
6
|
+
import { expansionVariants } from './query-expansion.js';
|
|
7
|
+
import { linearRerank } from './linear-rerank.js';
|
|
6
8
|
|
|
7
9
|
const INTENT_RULES = [
|
|
8
10
|
[/昨天|今天|明天|上周|上个月|去年|什么时候|多久|时间|日期|几点|temporal/i, 'temporal'],
|
|
@@ -78,38 +80,46 @@ const AUTHOR_WEIGHT = Object.freeze({
|
|
|
78
80
|
derived: 0.85,
|
|
79
81
|
});
|
|
80
82
|
|
|
81
|
-
function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, queryTokens = null, inhibition = null) {
|
|
83
|
+
function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, queryTokens = null, inhibition = null, expandTokens = null, expandMatchFactor = 0.5) {
|
|
82
84
|
const recency = retrievability(trace.stability, daysBetween(trace.lastAccessAt || trace.recordedAt, now), decay);
|
|
83
85
|
const access = Math.log1p(Number(trace.accessCount) || 0) / Math.log1p(50);
|
|
84
86
|
const w = { ...(INTENT_WEIGHTS[intent] || INTENT_WEIGHTS.fact), ...(weights ?? {}) };
|
|
85
87
|
const fusionScore = typeof fusion === 'number' ? fusion : Number(fusion?.score) || 0;
|
|
86
88
|
const text = `${trace.title ?? ''} ${trace.content ?? ''} ${trace.summary ?? ''}`;
|
|
87
|
-
|
|
89
|
+
// 2026-12-05 助手:同一条痕迹会反复出现在多次搜索里,走带缓存的取词(结果与 tokens() 完全一致)
|
|
90
|
+
const textTokens = tokensCached(`${trace.id}|${text.length}`, text);
|
|
88
91
|
const match = queryCoverage(queryTokens, textTokens);
|
|
92
|
+
// 2026-12-06 助手(路线 A):如果这条痕迹含查询的某个同义说法,
|
|
93
|
+
// 它对该查询的「匹配度」不应被原查询词覆盖不足一票否决。
|
|
94
|
+
// 只给到五折(0.5),且 exact 仍然只认原查询全覆盖 —— 不给同义词发「精确命中」的名分。
|
|
95
|
+
const expandMatch = expandTokens && expandTokens.size > 0 ? queryCoverage(expandTokens, textTokens) : 0;
|
|
96
|
+
const effectiveMatch = Math.max(match, expandMatch * expandMatchFactor);
|
|
89
97
|
const authorBoost = AUTHOR_WEIGHT[String(trace.authorKind ?? 'captured')] ?? 1;
|
|
90
98
|
const utility = (w.fusion * fusionScore
|
|
91
99
|
+ w.importance * Number(trace.importance || 0)
|
|
92
100
|
+ w.recency * recency
|
|
93
101
|
+ w.confidence * Number(trace.confidence || 0)
|
|
94
102
|
+ w.access * access
|
|
95
|
-
+ w.match *
|
|
103
|
+
+ w.match * effectiveMatch
|
|
96
104
|
+ w.exact * (match >= 0.999 ? 1 : 0)) * (inhibition ? competingFactor(trace.metadata, now, inhibition) : 1) * authorBoost;
|
|
105
|
+
// 2026-12-05 助手:原来 snippet(trace) 在同一个返回对象里算两次(snippet 和 cost)
|
|
106
|
+
const snip = snippet(trace);
|
|
97
107
|
return {
|
|
98
108
|
id: trace.id,
|
|
99
109
|
type: 'trace',
|
|
100
110
|
layer: trace.kind === 'identity' ? 'L0' : trace.kind === 'reflection' ? 'L5' : 'L2',
|
|
101
111
|
title: trace.title || trace.kind,
|
|
102
|
-
snippet:
|
|
112
|
+
snippet: snip,
|
|
103
113
|
text,
|
|
104
114
|
tokenSet: textTokens,
|
|
105
115
|
utility,
|
|
106
116
|
recency,
|
|
107
|
-
match,
|
|
117
|
+
match: effectiveMatch,
|
|
108
118
|
importance: Number(trace.importance || 0),
|
|
109
119
|
confidence: Number(trace.confidence || 0),
|
|
110
120
|
validAt: trace.validAt,
|
|
111
121
|
recordedAt: trace.recordedAt,
|
|
112
|
-
cost: Math.max(16, estimateTokens(
|
|
122
|
+
cost: Math.max(16, estimateTokens(snip)),
|
|
113
123
|
sources: fusion.sources,
|
|
114
124
|
attachments: Array.isArray(trace.metadata?.attachments) ? trace.metadata.attachments.length : 0,
|
|
115
125
|
trace,
|
|
@@ -158,12 +168,12 @@ export function selectPortfolio(candidates, {
|
|
|
158
168
|
return { selected, dropped, used, budget };
|
|
159
169
|
}
|
|
160
170
|
|
|
161
|
-
export function createRetrievalEngine({ traces, facts = null, graph = null, vector = null, policy = null, config = {} } = {}) {
|
|
171
|
+
export function createRetrievalEngine({ traces, facts = null, graph = null, vector = null, policy = null, config = {}, reranker = null } = {}) {
|
|
162
172
|
const defaults = {
|
|
163
173
|
budget: config.contextBudget ?? 2200,
|
|
164
|
-
limit: config.resultLimit ??
|
|
174
|
+
limit: config.resultLimit ?? 20,
|
|
165
175
|
ftsLimit: config.ftsLimit ?? 40,
|
|
166
|
-
k:
|
|
176
|
+
k: 20,
|
|
167
177
|
lambda: config.mmrLambda ?? 0.35,
|
|
168
178
|
mu: config.costPenalty ?? 0.08,
|
|
169
179
|
recentMinMatch: config.recentMinMatch ?? 0.12,
|
|
@@ -172,7 +182,24 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
172
182
|
// invalidated fact) is historical: keep it searchable but rank it below the
|
|
173
183
|
// replacement. Without this, overwrite correctness lived only in the fact
|
|
174
184
|
// layer while retrieval still surfaced the old sentence.
|
|
175
|
-
retiredPenalty: config.retiredPenalty ?? 0.
|
|
185
|
+
retiredPenalty: config.retiredPenalty ?? 0.7,
|
|
186
|
+
// 2026-12-06 助手(路线 A):查询扩展出来的每个说法单独做一路 FTS。
|
|
187
|
+
// 权重接近 fts(1.0),因为它提供的也是一条**精确措辞**证据,不是模糊提示。
|
|
188
|
+
expandWeight: config.expandWeight ?? 0.9,
|
|
189
|
+
// 同义说法命中后 match 的折算系数:只补「原查询词覆盖不足」的场,不重排已经匹配得很好的结果。
|
|
190
|
+
expandMatchFactor: config.expandMatchFactor ?? 0.5,
|
|
191
|
+
// 2026-12-06 助手:可选 deep-rerank。默认关;开启后先取深候选,再用 HTTP reranker 重排。
|
|
192
|
+
// 5.8~14.5 秒/查询(CPU int8),只适合显式“慢速深检索”,不放进默认路径。
|
|
193
|
+
rerankInSearch: config.rerankInSearch === true,
|
|
194
|
+
rerankLimit: config.rerankLimit ?? 50,
|
|
195
|
+
rerankBudget: config.rerankBudget ?? 8000,
|
|
196
|
+
// 2026-12-06 助手:线性重排。默认关;候选级 40 维特征,打分近零延迟。
|
|
197
|
+
// 候选池预算 16000 是为了真能选出 100 条(8000 时实测只选到 58~64 条,
|
|
198
|
+
// 与模型训练/冻结时的 100 候选口径不一致)。最终返回仍守用户 budget。
|
|
199
|
+
linearRerank: config.linearRerank === true,
|
|
200
|
+
linearRerankPool: config.linearRerankPool ?? 100,
|
|
201
|
+
linearRerankMin: config.linearRerankMin ?? 12,
|
|
202
|
+
linearRerankBudget: config.linearRerankBudget ?? 16000,
|
|
176
203
|
decay: config.dsr?.decay ?? -0.5,
|
|
177
204
|
inhibition: config.features?.inhibition === true
|
|
178
205
|
? {
|
|
@@ -184,6 +211,28 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
184
211
|
: null,
|
|
185
212
|
};
|
|
186
213
|
|
|
214
|
+
// 深排是否真的会跑:把「请求了但被静默跳过」的情况变成可观测的 reason。
|
|
215
|
+
function linearDecision(query, limit, option) {
|
|
216
|
+
const requested = option === true || (option === undefined && defaults.linearRerank);
|
|
217
|
+
if (!requested || option === false) return { requested: false, ok: false, reason: 'off' };
|
|
218
|
+
if (limit < defaults.linearRerankMin) return { requested: true, ok: false, reason: 'limit-below-min' };
|
|
219
|
+
if (!/[\u4e00-\u9fff]/.test(String(query ?? ''))) return { requested: true, ok: false, reason: 'non-chinese' };
|
|
220
|
+
return { requested: true, ok: true, reason: null };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function capByBudget(items, budget, limit = Number.POSITIVE_INFINITY) {
|
|
224
|
+
const capped = [];
|
|
225
|
+
let spent = 0;
|
|
226
|
+
for (const item of items) {
|
|
227
|
+
if (capped.length >= limit) break;
|
|
228
|
+
const cost = Number(item.cost) || 0;
|
|
229
|
+
if (spent + cost > budget) break;
|
|
230
|
+
capped.push(item);
|
|
231
|
+
spent += cost;
|
|
232
|
+
}
|
|
233
|
+
return capped;
|
|
234
|
+
}
|
|
235
|
+
|
|
187
236
|
function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, includeRetired = false, weights = null, filters = null, vectorHits = null, gate = 'none' } = {}, intent = 'fact') {
|
|
188
237
|
const queryTokens = tokens(query);
|
|
189
238
|
const sourceTrace = [];
|
|
@@ -195,6 +244,12 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
195
244
|
const retiredEvents = (() => {
|
|
196
245
|
if (!facts || typeof facts.list !== 'function') return null;
|
|
197
246
|
try {
|
|
247
|
+
// 2026-12-05 助手:优先走「只取 source_event_id 一列」的窄查询;
|
|
248
|
+
// 老仓库没有该方法时退回原来的全行路径(向后兼容)。
|
|
249
|
+
if (typeof facts.invalidatedEventIds === 'function') {
|
|
250
|
+
const ids = facts.invalidatedEventIds(scopeId, { limit: 2000 });
|
|
251
|
+
return ids.length ? new Set(ids) : null;
|
|
252
|
+
}
|
|
198
253
|
const rows = facts.list({ scopeId, status: 'invalidated', limit: 2000 });
|
|
199
254
|
if (!rows.length) return null;
|
|
200
255
|
const set = new Set();
|
|
@@ -226,6 +281,42 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
226
281
|
} catch (error) {
|
|
227
282
|
sourceTrace.push({ source: 'fts', ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
228
283
|
}
|
|
284
|
+
// 查询扩展(2026-12-06 · 路线 A):把查询里的人话扩成库里真出现过的说法,
|
|
285
|
+
// 每个说法**单独**做一路 FTS,再与主检索在 RRF 里合并。
|
|
286
|
+
// 为什么不拼成一个长查询:buildMatchQuery 只取前 24 个 token 且全 OR,
|
|
287
|
+
// 实测 key-vault 单独检索 gold 第 5,拼进长查询后掉到第 18。
|
|
288
|
+
// 特异性闸门:中文变体若把候选池填满(模板 127 行、上线 80 行),说明它在库里是大词,
|
|
289
|
+
// 整路丢弃;含拉丁词的变体(key-vault / oneclick)天然是多 token AND,池满也保留。
|
|
290
|
+
let expandLists = 0;
|
|
291
|
+
const expandTokenMap = new Map();
|
|
292
|
+
const variants = expansionVariants(query);
|
|
293
|
+
if (variants.length && typeof traces.searchFts === 'function') {
|
|
294
|
+
const variantLimit = Math.max(limit * 3, defaults.ftsLimit);
|
|
295
|
+
for (const variant of variants) {
|
|
296
|
+
try {
|
|
297
|
+
// 变体是「一个说法」,必须整词命中:key-vault 若按 OR 会变成 key OR vault,
|
|
298
|
+
// 55 行的精确短语膨胀成几百行,gold 直接被挤出候选池。
|
|
299
|
+
const hits = traces.searchFts(variant, { scopeId, limit: variantLimit, includeArchived, mode: 'and' });
|
|
300
|
+
const variantTokens = tokens(variant);
|
|
301
|
+
// 特异性闸门:中文变体若把候选池填满(模板/人设/归档候选/上线),说明它在库里是大词,
|
|
302
|
+
// 前几名也多是同话题噪声;整路丢弃。含拉丁词的变体(key-vault / oneclick)天然是
|
|
303
|
+
// 多 token AND,仍保留 —— 它们池满时前几名依然是强证据。
|
|
304
|
+
const latin = /[a-z0-9]/i.test(variant);
|
|
305
|
+
if (hits.length === 0 || (hits.length >= variantLimit && !latin)) continue;
|
|
306
|
+
lists.push({ name: 'expand', weight: defaults.expandWeight, items: hits });
|
|
307
|
+
expandLists += 1;
|
|
308
|
+
// 记下「这条痕迹是凭哪个说法的词命中的」,给它的 match 计分用。
|
|
309
|
+
for (const hit of hits) {
|
|
310
|
+
let set = expandTokenMap.get(hit.id);
|
|
311
|
+
if (!set) { set = new Set(); expandTokenMap.set(hit.id, set); }
|
|
312
|
+
for (const token of variantTokens) set.add(token);
|
|
313
|
+
}
|
|
314
|
+
} catch (error) {
|
|
315
|
+
sourceTrace.push({ source: 'expand', ok: false, variant, error: error instanceof Error ? error.message : String(error) });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (expandLists > 0) sourceTrace.push({ source: 'expand', ok: true, count: expandLists, variants });
|
|
319
|
+
}
|
|
229
320
|
try {
|
|
230
321
|
const recent = traces.list({ scopeId, state: 'active', limit: Math.max(limit * 4, 50) });
|
|
231
322
|
recentCount = recent.length;
|
|
@@ -255,6 +346,10 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
255
346
|
}
|
|
256
347
|
}
|
|
257
348
|
if (vector && (vectorHits !== null || typeof vector.search === 'function')) {
|
|
349
|
+
// 2026-12-06 三方复核一致点:同步 search() 在 async embedder 下会跳过语义通道。
|
|
350
|
+
// 原来这里照样报 ok:true/count:0 —— 调用方会以为是「记忆里没有」。现在如实报 ok:false。
|
|
351
|
+
const usedAsync = vectorHits !== null;
|
|
352
|
+
const skipBefore = (() => { try { return vector?.status?.()?.syncSkip?.at ?? 0; } catch { return 0; } })();
|
|
258
353
|
try {
|
|
259
354
|
const hits = vectorHits !== null
|
|
260
355
|
? vectorHits
|
|
@@ -268,8 +363,21 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
268
363
|
seen.add(hit.traceId);
|
|
269
364
|
items.push(trace);
|
|
270
365
|
}
|
|
271
|
-
if (items.length) lists.push({ name: 'vector', weight: 0
|
|
272
|
-
|
|
366
|
+
if (items.length) lists.push({ name: 'vector', weight: 3.0, items });
|
|
367
|
+
// 2026-12-06 寒复核:把「这次扫了多少、有没有被截断」带到结果里,
|
|
368
|
+
// 只放 status() 里的话调用方看不见(静默截断)。scan 为 null 表示不适用/未跑。
|
|
369
|
+
const scan = (() => {
|
|
370
|
+
try { return vector?.status?.()?.scan ?? null; } catch { return null; }
|
|
371
|
+
})();
|
|
372
|
+
const skip = (() => { try { return vector?.status?.()?.syncSkip ?? null; } catch { return null; } })();
|
|
373
|
+
const skippedSync = !usedAsync && Boolean(skip) && (skip.at ?? 0) > skipBefore;
|
|
374
|
+
sourceTrace.push({
|
|
375
|
+
source: 'vector',
|
|
376
|
+
ok: !skippedSync,
|
|
377
|
+
count: items.length,
|
|
378
|
+
...(skippedSync ? { reason: skip.reason, semantic: 'unavailable' } : { semantic: usedAsync ? 'async' : 'sync' }),
|
|
379
|
+
scan,
|
|
380
|
+
});
|
|
273
381
|
} catch (error) {
|
|
274
382
|
sourceTrace.push({ source: 'vector', ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
275
383
|
}
|
|
@@ -280,19 +388,22 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
280
388
|
const fallbacks = [];
|
|
281
389
|
let gated = 0;
|
|
282
390
|
let retiredSkipped = 0;
|
|
391
|
+
// 2026-12-05 助手:一次批量取回所有融合候选,替代循环内逐个 traces.get(profile 里 22%)。
|
|
392
|
+
// 老仓库没有 getMany 时退回原路径。
|
|
393
|
+
const preloaded = typeof traces.getMany === 'function' ? traces.getMany([...fused.keys()]) : null;
|
|
283
394
|
for (const [id, entry] of fused) {
|
|
284
|
-
const trace = traces.get(id);
|
|
395
|
+
const trace = preloaded ? preloaded.get(id) : traces.get(id);
|
|
285
396
|
if (!trace || trace.state === 'archived' && !includeArchived) continue;
|
|
286
397
|
if (filters && !matchesFilters(trace, filters)) continue;
|
|
287
|
-
const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens, defaults.inhibition);
|
|
398
|
+
const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens, defaults.inhibition, expandTokenMap.get(trace.id) ?? null, defaults.expandMatchFactor);
|
|
288
399
|
// Historical sentence whose fact was superseded. Default recall drops it
|
|
289
400
|
// (the replacement answers the question); an explicit includeRetired keeps
|
|
290
401
|
// it, ranked below live memories.
|
|
291
402
|
if (retiredEvents && retiredEvents.has(trace.eventId)) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
403
|
+
// 2026-12-06 助手:「来源事实被作废」不等于「这条痕迹对当前查询没用」。
|
|
404
|
+
// 实测有一条 FTS 排第 1 的记录因为这里 continue 而整个消失。
|
|
405
|
+
// 改成降权保留(× retiredPenalty)并标记 retired,让调用方自己判断。
|
|
406
|
+
if (!includeRetired) retiredSkipped += 1;
|
|
296
407
|
candidate.utility *= defaults.retiredPenalty;
|
|
297
408
|
candidate.retired = true;
|
|
298
409
|
}
|
|
@@ -300,7 +411,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
300
411
|
// the recency list or the soft FTS fallback. Strong sources still pass.
|
|
301
412
|
// High importance is allowed to bypass the match floor, preserving the
|
|
302
413
|
// 0.4.11 behaviour for identity-grade memories.
|
|
303
|
-
const strongSource = (entry.sources ?? []).some((source) => ['fts', 'graph', 'vector', 'vector-ann', 'facts'].includes(source.name));
|
|
414
|
+
const strongSource = (entry.sources ?? []).some((source) => ['fts', 'graph', 'vector', 'vector-ann', 'facts', 'expand'].includes(source.name));
|
|
304
415
|
if (gate === 'inject' && !strongSource
|
|
305
416
|
&& candidate.match < defaults.recentMinMatch
|
|
306
417
|
&& candidate.importance < defaults.recentImportanceFloor) {
|
|
@@ -316,10 +427,15 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
316
427
|
fallbacks.sort((a, b) => b.importance - a.importance || b.recency - a.recency);
|
|
317
428
|
candidates.push(fallbacks[0]);
|
|
318
429
|
}
|
|
430
|
+
// 2026-12-06 助手:fts/vector/graph 在上面已经各自 push 过一次(带上 ok/error 信息),
|
|
431
|
+
// 这里只补那些还没上报过的来源 —— 否则 sources 里同一条会出现两遍,
|
|
432
|
+
// 排查时看起来像「向量被算了两遍」。
|
|
433
|
+
const reported = new Set(sourceTrace.map((s) => s.source));
|
|
319
434
|
for (const list of lists) {
|
|
435
|
+
if (reported.has(list.name)) continue;
|
|
320
436
|
sourceTrace.push({ source: list.name, ok: true, count: list.items.length });
|
|
321
437
|
}
|
|
322
|
-
return { candidates, sourceTrace, ftsCount, recentCount, gated, retiredSkipped };
|
|
438
|
+
return { candidates, sourceTrace, ftsCount, recentCount, gated, retiredSkipped, expandLists };
|
|
323
439
|
}
|
|
324
440
|
|
|
325
441
|
function search(query, {
|
|
@@ -332,6 +448,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
332
448
|
filters = null,
|
|
333
449
|
vectorHits = null,
|
|
334
450
|
gate = 'none',
|
|
451
|
+
linearRerank: linearRerankOption = undefined,
|
|
335
452
|
} = {}) {
|
|
336
453
|
const started = Date.now();
|
|
337
454
|
const intent = classifyIntent(query);
|
|
@@ -342,10 +459,16 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
342
459
|
const effectiveBudget = activePolicy?.budget != null
|
|
343
460
|
? Math.max(64, Math.min(20000, Number(activePolicy.budget)))
|
|
344
461
|
: budget;
|
|
345
|
-
const
|
|
462
|
+
const queryTokens = tokens(query);
|
|
463
|
+
const linear = linearDecision(query, limit, linearRerankOption);
|
|
464
|
+
const wantLinear = linear.ok;
|
|
465
|
+
let linearInfo = linear.requested && !linear.ok ? { ok: false, reason: linear.reason } : null;
|
|
466
|
+
const poolLimit = wantLinear ? Math.max(limit, defaults.linearRerankPool) : limit;
|
|
467
|
+
const searchBudget = wantLinear ? Math.max(effectiveBudget, defaults.linearRerankBudget) : effectiveBudget;
|
|
468
|
+
const sources = searchSources(query, { scopeId, limit: poolLimit, now, includeArchived, includeRetired, weights: policyWeights, filters, vectorHits, gate }, intent);
|
|
346
469
|
const portfolio = selectPortfolio(sources.candidates, {
|
|
347
|
-
budget:
|
|
348
|
-
limit,
|
|
470
|
+
budget: searchBudget,
|
|
471
|
+
limit: poolLimit,
|
|
349
472
|
lambda: defaults.lambda,
|
|
350
473
|
mu: defaults.mu,
|
|
351
474
|
});
|
|
@@ -379,7 +502,47 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
379
502
|
}
|
|
380
503
|
}
|
|
381
504
|
}
|
|
382
|
-
|
|
505
|
+
let selected = portfolio.selected;
|
|
506
|
+
if (wantLinear) {
|
|
507
|
+
try {
|
|
508
|
+
if (selected.length > limit) {
|
|
509
|
+
selected = linearRerank(selected, queryTokens, { now }).slice(0, limit);
|
|
510
|
+
linearInfo = {
|
|
511
|
+
ok: true,
|
|
512
|
+
candidates: portfolio.selected.length,
|
|
513
|
+
poolTarget: defaults.linearRerankPool,
|
|
514
|
+
selected: selected.length,
|
|
515
|
+
};
|
|
516
|
+
} else {
|
|
517
|
+
linearInfo = {
|
|
518
|
+
ok: false,
|
|
519
|
+
reason: 'few-candidates',
|
|
520
|
+
candidates: selected.length,
|
|
521
|
+
poolTarget: defaults.linearRerankPool,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
} catch (error) {
|
|
525
|
+
selected = selected.slice(0, limit);
|
|
526
|
+
linearInfo = { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
527
|
+
}
|
|
528
|
+
// 候选池预算只用于「选出 100 条」;最终返回仍必须守住用户给的预算。
|
|
529
|
+
const capped = capByBudget(selected, effectiveBudget, limit);
|
|
530
|
+
selected = capped;
|
|
531
|
+
if (linearInfo?.ok) {
|
|
532
|
+
linearInfo.selected = selected.length;
|
|
533
|
+
if (selected.length === 0) {
|
|
534
|
+
linearInfo = {
|
|
535
|
+
ok: false,
|
|
536
|
+
reason: 'budget',
|
|
537
|
+
candidates: portfolio.selected.length,
|
|
538
|
+
poolTarget: defaults.linearRerankPool,
|
|
539
|
+
selected: 0,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
const used = selected.reduce((sum, item) => sum + (item.cost || 0), 0);
|
|
545
|
+
const items = selected.map((item) => ({
|
|
383
546
|
id: item.id,
|
|
384
547
|
type: item.type,
|
|
385
548
|
layer: item.layer,
|
|
@@ -403,12 +566,14 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
403
566
|
intent,
|
|
404
567
|
scopeId,
|
|
405
568
|
items,
|
|
406
|
-
budget: { used
|
|
569
|
+
budget: { used, total: effectiveBudget },
|
|
407
570
|
trace: {
|
|
408
571
|
elapsedMs: Date.now() - started,
|
|
409
572
|
candidates: sources.candidates.length,
|
|
410
573
|
gated: sources.gated ?? 0,
|
|
411
574
|
retiredSkipped: sources.retiredSkipped ?? 0,
|
|
575
|
+
expandLists: sources.expandLists ?? 0,
|
|
576
|
+
linearRerank: linearInfo,
|
|
412
577
|
selected: items.length,
|
|
413
578
|
dropped: portfolio.dropped.length,
|
|
414
579
|
sources: sources.sourceTrace,
|
|
@@ -419,18 +584,82 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
419
584
|
|
|
420
585
|
async function searchAsync(query, options = {}) {
|
|
421
586
|
if (!vector || typeof vector.searchAsync !== 'function') return search(query, options);
|
|
587
|
+
const started = Date.now();
|
|
422
588
|
const limit = options.limit ?? defaults.limit;
|
|
589
|
+
const userBudget = options.budget ?? defaults.budget;
|
|
590
|
+
const useRerank = Boolean(reranker) && (options.rerank === true || defaults.rerankInSearch);
|
|
591
|
+
const deepLimit = useRerank ? Math.max(limit, defaults.rerankLimit) : limit;
|
|
592
|
+
const linear = linearDecision(query, limit, options.linearRerank);
|
|
593
|
+
const wantLinear = linear.ok;
|
|
594
|
+
const linearPool = wantLinear ? Math.max(limit, defaults.linearRerankPool) : limit;
|
|
595
|
+
const fetchLimit = Math.max(deepLimit, linearPool);
|
|
423
596
|
let vectorHits = [];
|
|
424
597
|
try {
|
|
425
598
|
vectorHits = await vector.searchAsync(query, {
|
|
426
599
|
scopeId: options.scopeId ?? 'global',
|
|
427
|
-
limit: Math.max(
|
|
600
|
+
limit: Math.max(fetchLimit * 3, 20),
|
|
428
601
|
includeArchived: options.includeArchived === true,
|
|
429
602
|
});
|
|
430
603
|
} catch {
|
|
431
604
|
vectorHits = [];
|
|
432
605
|
}
|
|
433
|
-
|
|
606
|
+
const base = search(query, {
|
|
607
|
+
...options,
|
|
608
|
+
budget: useRerank ? Math.max(userBudget, defaults.rerankBudget) : userBudget,
|
|
609
|
+
...(useRerank ? { limit: deepLimit } : {}),
|
|
610
|
+
vectorHits,
|
|
611
|
+
});
|
|
612
|
+
if (!useRerank) return base;
|
|
613
|
+
try {
|
|
614
|
+
// 只把 snippet 交给重排器,避免把完整正文(可能含敏感内容)发到外部服务。
|
|
615
|
+
const docs = base.items.map((item) => item.snippet || item.title || '');
|
|
616
|
+
const ranked = await reranker.rerank(query, docs, { topN: docs.length });
|
|
617
|
+
const seen = new Set();
|
|
618
|
+
const ordered = [];
|
|
619
|
+
for (const row of ranked) {
|
|
620
|
+
const item = base.items[row.index];
|
|
621
|
+
if (!item || seen.has(item.id)) continue;
|
|
622
|
+
seen.add(item.id);
|
|
623
|
+
ordered.push(item);
|
|
624
|
+
}
|
|
625
|
+
for (const item of base.items) {
|
|
626
|
+
if (!seen.has(item.id)) { seen.add(item.id); ordered.push(item); }
|
|
627
|
+
}
|
|
628
|
+
const items = capByBudget(ordered, userBudget, limit);
|
|
629
|
+
const used = items.reduce((sum, item) => sum + (item.cost || 0), 0);
|
|
630
|
+
const baseElapsed = Number(base.trace?.elapsedMs) || 0;
|
|
631
|
+
return {
|
|
632
|
+
...base,
|
|
633
|
+
items,
|
|
634
|
+
budget: { ...base.budget, total: userBudget, used },
|
|
635
|
+
trace: {
|
|
636
|
+
...base.trace,
|
|
637
|
+
elapsedMs: Date.now() - started,
|
|
638
|
+
rerank: {
|
|
639
|
+
ok: items.length > 0,
|
|
640
|
+
...(items.length === 0 ? { reason: 'budget' } : {}),
|
|
641
|
+
model: reranker.model ?? null,
|
|
642
|
+
candidates: base.items.length,
|
|
643
|
+
selected: items.length,
|
|
644
|
+
elapsedMs: Math.max(0, Date.now() - started - baseElapsed),
|
|
645
|
+
},
|
|
646
|
+
},
|
|
647
|
+
};
|
|
648
|
+
} catch (error) {
|
|
649
|
+
// Fail open:重排服务挂了就按深检索的基线顺序返回,不假装成功。
|
|
650
|
+
const items = capByBudget(base.items, userBudget, limit);
|
|
651
|
+
const used = items.reduce((sum, item) => sum + (item.cost || 0), 0);
|
|
652
|
+
return {
|
|
653
|
+
...base,
|
|
654
|
+
items,
|
|
655
|
+
budget: { ...base.budget, total: userBudget, used },
|
|
656
|
+
trace: {
|
|
657
|
+
...base.trace,
|
|
658
|
+
elapsedMs: Date.now() - started,
|
|
659
|
+
rerank: { ok: false, error: error instanceof Error ? error.message : String(error) },
|
|
660
|
+
},
|
|
661
|
+
};
|
|
662
|
+
}
|
|
434
663
|
}
|
|
435
664
|
|
|
436
665
|
function timeline({ scopeId = 'global', aroundId, before = 5, after = 5, now = Date.now() } = {}) {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Fusion weights: single source of truth.
|
|
2
|
+
// Online feature extraction (src/engines/linear-rerank.js) and offline dataset
|
|
3
|
+
// generation (审计/lab/rerank-dataset.mjs) must use the same table; a hand-copied
|
|
4
|
+
// second table drifts silently when a source is added or reweighted.
|
|
5
|
+
export const SOURCE_WEIGHT = Object.freeze({
|
|
6
|
+
fts: 1.0,
|
|
7
|
+
'fts-soft': 0.7,
|
|
8
|
+
graph: 0.9,
|
|
9
|
+
vector: 3.0,
|
|
10
|
+
recent: 0.35,
|
|
11
|
+
expand: 0.9,
|
|
12
|
+
facts: 1.0,
|
|
13
|
+
});
|
package/src/host/scheduler.js
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
* safe autonomy tick, drains jobs, plans retention and checks invariants.
|
|
4
4
|
* The interval is unref'ed so it never keeps a process alive by itself.
|
|
5
5
|
*/
|
|
6
|
+
|
|
7
|
+
import { induceSkills } from '../engines/induct.js';
|
|
8
|
+
|
|
6
9
|
export function createScheduler({
|
|
7
10
|
cortex,
|
|
8
11
|
intervalMs = 60_000,
|
|
@@ -32,6 +35,8 @@ export function createScheduler({
|
|
|
32
35
|
// One wider consolidation pass a day, so the 30-minute delta trigger is not the
|
|
33
36
|
// only thing that ever looks at the store.
|
|
34
37
|
let lastDeepDay = '';
|
|
38
|
+
// 2026-12-05 夜:autoSkills 的「一天一次」闸门(与 lastDeepDay 同款)
|
|
39
|
+
let lastSkillsDay = '';
|
|
35
40
|
const autoDreamDays = new Set();
|
|
36
41
|
const edgeReviewSeen = new Set();
|
|
37
42
|
|
|
@@ -300,6 +305,38 @@ export function createScheduler({
|
|
|
300
305
|
}
|
|
301
306
|
}
|
|
302
307
|
|
|
308
|
+
/**
|
|
309
|
+
* 2026-12-05 夜:把 autoSkills 接上。
|
|
310
|
+
* 12-03 写好了配置(feature-overrides: autoSkills=true,why 写着
|
|
311
|
+
* 「scheduler 日频调 suggestSkills,候选进 skills 表」),也写好了引擎
|
|
312
|
+
* (engines/induct.js 的 induceSkills),但两头从没接上 ——
|
|
313
|
+
* 配置在代码里 0 处引用、引擎 0 个调用方。
|
|
314
|
+
* 这里接成「一天一次」,**只建 candidate,不自动升 active**(升迁仍要显式)。
|
|
315
|
+
*/
|
|
316
|
+
function runAutoSkills(report) {
|
|
317
|
+
if (cortex.config?.features?.autoSkills === false) return;
|
|
318
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
319
|
+
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(scopeId)) return;
|
|
320
|
+
const day = localDayOf(now());
|
|
321
|
+
if (lastSkillsDay === day) return;
|
|
322
|
+
const traces = cortex.repos?.traces ?? null;
|
|
323
|
+
const skills = cortex.repos?.skills ?? null;
|
|
324
|
+
if (!traces || !skills) {
|
|
325
|
+
report.steps.autoSkills = { skipped: 'no-repo' };
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
const result = induceSkills({ traces, skills, scopeId, minSupport: 4, limit: 3 });
|
|
330
|
+
lastSkillsDay = day;
|
|
331
|
+
report.steps.autoSkills = {
|
|
332
|
+
created: result.count,
|
|
333
|
+
suggestions: result.suggestions?.length ?? 0,
|
|
334
|
+
};
|
|
335
|
+
} catch (error) {
|
|
336
|
+
report.steps.autoSkills = { error: error instanceof Error ? error.message : String(error) };
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
303
340
|
async function runAutoDedupe(report) {
|
|
304
341
|
if (!cortex.consolidation?.dedupe) return;
|
|
305
342
|
if (cortex.config?.dedupeOnSchedule === false) return;
|
|
@@ -418,6 +455,12 @@ export function createScheduler({
|
|
|
418
455
|
} catch (error) {
|
|
419
456
|
report.steps.autoDedupe = { error: error instanceof Error ? error.message : String(error) };
|
|
420
457
|
}
|
|
458
|
+
try {
|
|
459
|
+
// 2026-12-05 夜:autoSkills 接线(配置与引擎此前两头悬空)
|
|
460
|
+
runAutoSkills(report);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
report.steps.autoSkills = { error: error instanceof Error ? error.message : String(error) };
|
|
463
|
+
}
|
|
421
464
|
try {
|
|
422
465
|
await runGraphAuto(report);
|
|
423
466
|
} catch (error) {
|
package/src/memory/tokenizer.js
CHANGED
|
@@ -23,6 +23,36 @@ export function tokens(text) {
|
|
|
23
23
|
return new Set(tokenList(text));
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// 2026-12-05 助手:candidateFromTrace 对「每个候选、每次搜索」都重新分词
|
|
27
|
+
// (title+content+summary 常常一两千字),CPU profile 里 tokens() 占搜索时间 21%。
|
|
28
|
+
// 这里按「身份串」记忆化:同样的输入必然得到同样的 token 集,所以缓存不会改变结果。
|
|
29
|
+
// 有界:到上限就整体清空(粗粒度但绝不无界增长)。
|
|
30
|
+
// 身份串由调用方给(trace.id + 文本长度)—— 正文被改过时长度几乎必变,缓存自然失效;
|
|
31
|
+
// 真的是「等长改写」的极端情况,影响的只是打分里的匹配度微调,不影响召回对象。
|
|
32
|
+
const TOKEN_CACHE_LIMIT = 600;
|
|
33
|
+
const tokenCache = new Map();
|
|
34
|
+
|
|
35
|
+
export function tokensCached(identity, text) {
|
|
36
|
+
const key = identity == null ? null : String(identity);
|
|
37
|
+
// 2026-12-05 夜(寒复核指出):只按 id|长度 做键时,「同 id 同长度改正文」会返回旧 token ——
|
|
38
|
+
// 那不是性能问题,是正确性问题。这里把原文一起存着,命中时比对内容:
|
|
39
|
+
// 比对是 O(n),但远便宜于重新分词(正则 + 造数组),而且保证绝不返回错的 token 集。
|
|
40
|
+
if (key) {
|
|
41
|
+
const hit = tokenCache.get(key);
|
|
42
|
+
if (hit && hit.text === text) return hit.tokens;
|
|
43
|
+
}
|
|
44
|
+
const value = tokens(text);
|
|
45
|
+
if (key) {
|
|
46
|
+
if (tokenCache.size >= TOKEN_CACHE_LIMIT) tokenCache.clear();
|
|
47
|
+
tokenCache.set(key, { text, tokens: value });
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function tokensCacheStats() {
|
|
53
|
+
return { size: tokenCache.size, limit: TOKEN_CACHE_LIMIT };
|
|
54
|
+
}
|
|
55
|
+
|
|
26
56
|
export function ftsTokenList(text) {
|
|
27
57
|
// Bigrams preserve phrase specificity; single non-stop CJK chars act as a
|
|
28
58
|
// cheap fuzzy fallback for near-synonyms that share a character (米饭/米饭).
|
|
@@ -81,7 +111,7 @@ export function jaccard(a, b) {
|
|
|
81
111
|
export function truncate(text, max) {
|
|
82
112
|
const value = String(text ?? '');
|
|
83
113
|
if (value.length <= max) return value;
|
|
84
|
-
// 2026-11-29
|
|
114
|
+
// 2026-11-29 二修(review复核):仍按 UTF-16 码元切,和 estimateTokens(value.length) 同一把尺子。
|
|
85
115
|
// 只处理边界:末尾若是孤立高位代理项(\ud83d 之类),丢掉它,别和后面的省略号拼成乱码。
|
|
86
116
|
// 上一版改按码点切,结果 emoji 段预算翻倍(1 emoji = 2 码元 = 1 码点),比乱码更糟。
|
|
87
117
|
let cut = value.slice(0, Math.max(0, max - 1));
|