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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { hashText, traceId } from '../../core/ids.js';
|
|
1
|
+
import { hashText, traceId } from '../../core/ids.js';
|
|
2
2
|
import { asJsonArray, asJsonObject, stableStringify } from '../../core/json.js';
|
|
3
3
|
import { nowIso } from '../../core/time.js';
|
|
4
4
|
import { ftsText, buildMatchQuery } from '../../memory/tokenizer.js';
|
|
@@ -31,6 +31,8 @@ const FIELD_MAP = Object.freeze({
|
|
|
31
31
|
authorKind: 'author_kind',
|
|
32
32
|
authorId: 'author_id',
|
|
33
33
|
authorConfidence: 'author_confidence',
|
|
34
|
+
// 2026-12-05 助手:显式钉住。不进 FIELD_MAP 的话 update() 会静默忽略这个字段。
|
|
35
|
+
protected: 'protected',
|
|
34
36
|
validAt: 'valid_at',
|
|
35
37
|
recordedAt: 'recorded_at',
|
|
36
38
|
lastAccessAt: 'last_access_at',
|
|
@@ -72,6 +74,8 @@ function rowToTrace(row) {
|
|
|
72
74
|
authorKind: row.author_kind ?? 'captured',
|
|
73
75
|
authorId: row.author_id ?? null,
|
|
74
76
|
authorConfidence: row.author_confidence == null ? null : Number(row.author_confidence),
|
|
77
|
+
// 2026-12-05 助手:显式钉住标记(0/1)。老行默认 0。
|
|
78
|
+
protected: Number(row.protected ?? 0),
|
|
75
79
|
validAt: row.valid_at,
|
|
76
80
|
recordedAt: row.recorded_at,
|
|
77
81
|
lastAccessAt: row.last_access_at,
|
|
@@ -97,6 +101,27 @@ function rowToTrace(row) {
|
|
|
97
101
|
}
|
|
98
102
|
|
|
99
103
|
export function createTraceRepository(db) {
|
|
104
|
+
// 2026-12-06 助手:跨 scope 行数计数(带 60 秒缓存)。
|
|
105
|
+
// searchFts 用它判断「全局候选池会不会把目标 scope 的行挤出去」(寒复核 A1)。
|
|
106
|
+
let scopeCountCache = { at: 0, total: 0, byScope: new Map() };
|
|
107
|
+
function countOtherScopes(scopeId) {
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
if (now - scopeCountCache.at > 60_000) {
|
|
110
|
+
try {
|
|
111
|
+
const total = Number(db.prepare('SELECT COUNT(*) AS c FROM traces').get().c);
|
|
112
|
+
const byScope = new Map();
|
|
113
|
+
for (const row of db.prepare('SELECT scope_id, COUNT(*) AS c FROM traces GROUP BY scope_id').all()) {
|
|
114
|
+
byScope.set(row.scope_id, Number(row.c));
|
|
115
|
+
}
|
|
116
|
+
scopeCountCache = { at: now, total, byScope };
|
|
117
|
+
} catch {
|
|
118
|
+
scopeCountCache = { at: now, total: 0, byScope: new Map() };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!scopeCountCache.total) return null; // 计数失败 → 走精确版
|
|
122
|
+
return Math.max(0, scopeCountCache.total - (scopeCountCache.byScope.get(scopeId) ?? 0));
|
|
123
|
+
}
|
|
124
|
+
|
|
100
125
|
function syncFts(trace, { replace = true } = {}) {
|
|
101
126
|
// trace_id is UNINDEXED in FTS5. Deleting by it on a brand-new insert scans
|
|
102
127
|
// the whole index and makes bulk writes quadratic; only updates need delete.
|
|
@@ -195,12 +220,27 @@ export function createTraceRepository(db) {
|
|
|
195
220
|
function list({ scopeId = 'global', state = null, limit = 50, offset = 0 } = {}) {
|
|
196
221
|
const count = Math.max(1, Math.min(10000, Number(limit) || 50));
|
|
197
222
|
const skip = Math.max(0, Number(offset) || 0);
|
|
223
|
+
// 2026-12-05 助手:recorded_at 并列时的顺序,原来是「表扫描顺序」这个副作用
|
|
224
|
+
// (加不加索引结果不同)。补 rowid DESC 把语义定死:同刻写入,后写的排前面。
|
|
198
225
|
const rows = state
|
|
199
|
-
? db.prepare('SELECT * FROM traces WHERE scope_id = ? AND state = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?').all(scopeId, state, count, skip)
|
|
200
|
-
: db.prepare('SELECT * FROM traces WHERE scope_id = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?').all(scopeId, count, skip);
|
|
226
|
+
? db.prepare('SELECT * FROM traces WHERE scope_id = ? AND state = ? ORDER BY recorded_at DESC, rowid DESC LIMIT ? OFFSET ?').all(scopeId, state, count, skip)
|
|
227
|
+
: db.prepare('SELECT * FROM traces WHERE scope_id = ? ORDER BY recorded_at DESC, rowid DESC LIMIT ? OFFSET ?').all(scopeId, count, skip);
|
|
201
228
|
return rows.map(rowToTrace);
|
|
202
229
|
}
|
|
203
230
|
|
|
231
|
+
// 2026-12-05 助手:writeInternal 每条写都要为「新鲜度」取最近 N 条文本,
|
|
232
|
+
// 原来走 list() → SELECT * + rowToTrace(JSON.parse metadata、构造 21 个对象)。
|
|
233
|
+
// 这里只取正文列(traces 表的列名是 content,不是 text —— 写错会直接抛
|
|
234
|
+
// "no such column: text",然后被 writeInternal 的 catch 吞成空数组,
|
|
235
|
+
// 表现为「新鲜度永远算不出来」,不报错、只是悄悄退化)。
|
|
236
|
+
function recentTexts(scopeId = 'global', { limit = 20, excludeId = null } = {}) {
|
|
237
|
+
const count = Math.max(1, Math.min(200, Number(limit) || 20));
|
|
238
|
+
const rows = excludeId
|
|
239
|
+
? db.prepare('SELECT content FROM traces WHERE scope_id = ? AND id <> ? ORDER BY recorded_at DESC, rowid DESC LIMIT ?').all(scopeId, excludeId, count)
|
|
240
|
+
: db.prepare('SELECT content FROM traces WHERE scope_id = ? ORDER BY recorded_at DESC, rowid DESC LIMIT ?').all(scopeId, count);
|
|
241
|
+
return rows.map((row) => String(row.content ?? ''));
|
|
242
|
+
}
|
|
243
|
+
|
|
204
244
|
function listSince(scopeId, sinceIso, { limit = 200, state = 'active' } = {}) {
|
|
205
245
|
const count = Math.max(1, Math.min(1000, Number(limit) || 200));
|
|
206
246
|
const rows = state
|
|
@@ -255,22 +295,64 @@ export function createTraceRepository(db) {
|
|
|
255
295
|
return result.changes > 0;
|
|
256
296
|
}
|
|
257
297
|
|
|
258
|
-
function searchFts(query, { scopeId = 'global', limit = 30, includeArchived = false, soft = false } = {}) {
|
|
259
|
-
const match = buildMatchQuery(query, { soft });
|
|
298
|
+
function searchFts(query, { scopeId = 'global', limit = 30, includeArchived = false, soft = false, mode = 'or' } = {}) {
|
|
299
|
+
const match = buildMatchQuery(query, { soft, mode });
|
|
260
300
|
if (!match) return [];
|
|
261
301
|
const count = Math.max(1, Math.min(200, Number(limit) || 30));
|
|
262
302
|
const stateClause = includeArchived ? "t.state IN ('active','archived')" : "t.state = 'active'";
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
303
|
+
// 子查询里没有 t 别名,单独给一份无别名的写法
|
|
304
|
+
const stateBare = includeArchived ? "state IN ('active','archived')" : "state = 'active'";
|
|
305
|
+
// 2026-12-06 助手:原写法「FTS JOIN traces → ORDER BY bm25 → LIMIT」会把全部命中行
|
|
306
|
+
// (实测 122~1515 行)JOIN 出来再排序,33.7 ms/查询,约 90% 花在永远用不到的行上。
|
|
307
|
+
// 改成两段:FTS 内部先按 bm25 排序并截断候选池(1.8 ms),只 JOIN 这几十行(3.4 ms)。
|
|
308
|
+
//
|
|
309
|
+
// ⚠️ 2026-12-06 寒复核(A1)指出:池是按**全库** bm25 截的,之后才按 scope 过滤。
|
|
310
|
+
// 查少数派 scope(agency/engineering/minecraft)时,global 的大量命中会把池占满,
|
|
311
|
+
// 目标 scope 的行被挤出 → 返回条数骤降(实测 agency「cortex」14 → 2)。
|
|
312
|
+
// 所以池满且目标 scope 命中不足时,必须退回旧写法(慢一点,但不能漏)。
|
|
313
|
+
const pool = Math.max(200, count * 10);
|
|
314
|
+
const runPaged = () => db.prepare(`
|
|
315
|
+
SELECT t.*, f.r AS fts_rank
|
|
316
|
+
FROM (
|
|
317
|
+
SELECT rowid AS fr, bm25(traces_fts_index) AS r
|
|
318
|
+
FROM traces_fts_index
|
|
319
|
+
WHERE traces_fts_index MATCH ?
|
|
320
|
+
ORDER BY r ASC
|
|
321
|
+
LIMIT ?
|
|
322
|
+
) f
|
|
323
|
+
JOIN traces_fts_index x ON x.rowid = f.fr
|
|
324
|
+
JOIN traces t ON t.id = x.trace_id
|
|
325
|
+
WHERE t.scope_id = ?
|
|
269
326
|
AND ${stateClause}
|
|
270
|
-
ORDER BY
|
|
327
|
+
ORDER BY f.r ASC
|
|
271
328
|
LIMIT ?
|
|
272
|
-
`).all(match, scopeId, count);
|
|
273
|
-
|
|
329
|
+
`).all(match, pool, scopeId, count).map((row) => ({ ...rowToTrace(row), ftsRank: Number(row.fts_rank ?? 0) }));
|
|
330
|
+
// 精确版:把 scope 过滤用 IN 下推进 FTS 子查询(先过滤再取前 pool 条),
|
|
331
|
+
// 少数派 scope 不会因为别的 scope 占满池而漏结果。实测与旧写法 Jaccard = 1.00。
|
|
332
|
+
const runExact = () => db.prepare(`
|
|
333
|
+
SELECT t.*, f.r AS fts_rank
|
|
334
|
+
FROM (
|
|
335
|
+
SELECT ft.rowid AS fr, bm25(traces_fts_index) AS r
|
|
336
|
+
FROM traces_fts_index ft
|
|
337
|
+
WHERE traces_fts_index MATCH ?
|
|
338
|
+
AND ft.trace_id IN (SELECT id FROM traces WHERE scope_id = ? AND ${stateBare})
|
|
339
|
+
ORDER BY r ASC
|
|
340
|
+
LIMIT ?
|
|
341
|
+
) f
|
|
342
|
+
JOIN traces_fts_index x ON x.rowid = f.fr
|
|
343
|
+
JOIN traces t ON t.id = x.trace_id
|
|
344
|
+
ORDER BY f.r ASC
|
|
345
|
+
LIMIT ?
|
|
346
|
+
`).all(match, scopeId, pool, count).map((row) => ({ ...rowToTrace(row), ftsRank: Number(row.fts_rank ?? 0) }));
|
|
347
|
+
|
|
348
|
+
// 2026-12-06 寒复核(A1):池是按全库 bm25 截的,之后才按 scope 过滤。
|
|
349
|
+
// 可证明安全的判据:目标 scope 的 top-count 若可能被挤出池,必须有 > pool-count+1 行
|
|
350
|
+
// 「别的 scope 且排名更靠前」的行;那些行全在其它 scope 里,所以
|
|
351
|
+
// 其它 scope 总行数 < pool - count + 1 ⇒ 不可能挤出 ⇒ 池版与旧写法等价。
|
|
352
|
+
// 否则走精确版(慢一点,但不错)。计数带 60 秒缓存,避免大库每次 COUNT 全表。
|
|
353
|
+
const others = countOtherScopes(scopeId);
|
|
354
|
+
if (others !== null && others < pool - count + 1) return runPaged();
|
|
355
|
+
return runExact();
|
|
274
356
|
}
|
|
275
357
|
|
|
276
358
|
function count({ scopeId = null, state = null } = {}) {
|
|
@@ -308,5 +390,22 @@ export function createTraceRepository(db) {
|
|
|
308
390
|
`).all(scopeId, Math.max(1, Math.min(100, limit))).map((row) => ({ hash: row.hash, count: Number(row.c) }));
|
|
309
391
|
}
|
|
310
392
|
|
|
311
|
-
|
|
393
|
+
// 2026-12-05 助手:检索里「每个候选按 id 取一次」是搜索第一大热点(CPU profile 22%)。
|
|
394
|
+
// 批量取 + Map,语义不变(同一条 SQL 换成 WHERE id IN (...))。分块 400 保守避开变量上限。
|
|
395
|
+
function getMany(ids = []) {
|
|
396
|
+
const unique = [...new Set((Array.isArray(ids) ? ids : []).filter(Boolean))];
|
|
397
|
+
const out = new Map();
|
|
398
|
+
for (let i = 0; i < unique.length; i += 400) {
|
|
399
|
+
const chunk = unique.slice(i, i + 400);
|
|
400
|
+
const marks = chunk.map(() => '?').join(',');
|
|
401
|
+
const rows = db.prepare(`SELECT * FROM traces WHERE id IN (${marks})`).all(...chunk);
|
|
402
|
+
for (const row of rows) {
|
|
403
|
+
const trace = rowToTrace(row);
|
|
404
|
+
if (trace) out.set(trace.id, trace);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return out;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return { insert, get, getMany, findByEvent, findByHash, list, listSince, range, update, touch, remove, searchFts, count, ftsCount, reindexFts, duplicateHashes, recentTexts };
|
|
312
411
|
}
|
package/src/store/schema.sql
CHANGED
|
@@ -49,6 +49,8 @@ CREATE TABLE IF NOT EXISTS traces (
|
|
|
49
49
|
author_kind TEXT NOT NULL DEFAULT 'captured',
|
|
50
50
|
author_id TEXT,
|
|
51
51
|
author_confidence REAL,
|
|
52
|
+
-- 2026-12-05 助手:显式「钉住」。1 = 这条是我亲手钉的,合并/归档/留存都不许动它。
|
|
53
|
+
protected INTEGER NOT NULL DEFAULT 0,
|
|
52
54
|
valid_at TEXT,
|
|
53
55
|
recorded_at TEXT NOT NULL,
|
|
54
56
|
last_access_at TEXT,
|
|
@@ -77,6 +79,16 @@ CREATE INDEX IF NOT EXISTS traces_scope_valid ON traces(scope_id, valid_at);
|
|
|
77
79
|
CREATE INDEX IF NOT EXISTS traces_last_access ON traces(last_access_at);
|
|
78
80
|
CREATE INDEX IF NOT EXISTS traces_hash ON traces(hash);
|
|
79
81
|
CREATE INDEX IF NOT EXISTS traces_event ON traces(event_id);
|
|
82
|
+
-- 2026-12-05 助手:traces.list() 的排序键是 recorded_at,但索引只建了 valid_at,
|
|
83
|
+
-- 于是每次 list 都 "USE TEMP B-TREE FOR ORDER BY"(全量排序)。而 writeInternal 每写一条
|
|
84
|
+
-- 都要为「新鲜度」调一次 traces.list(limit 21) —— 实测 6k 条时 8.9ms/写,加这条索引后 3.98ms。
|
|
85
|
+
CREATE INDEX IF NOT EXISTS traces_scope_recorded ON traces(scope_id, recorded_at);
|
|
86
|
+
-- 2026-12-06 助手:writeInternal 每条写之前都要 findByHash(scope_id, hash) 做内容去重。
|
|
87
|
+
-- 这条查询是 WHERE scope_id=? AND hash=? ORDER BY recorded_at ASC LIMIT 1,
|
|
88
|
+
-- 表上已有 traces_hash,但 SQLite 为了「省掉排序」选了 traces_scope_recorded(scope_id=?)
|
|
89
|
+
-- —— 于是每写一条都扫一遍全库该 scope 的行(4379 行时 p50 22.6ms,占写入路径 56%)。
|
|
90
|
+
-- 补一条 (scope_id, hash) 复合索引:等值命中后只剩极少数行,ORDER BY 代价可忽略。
|
|
91
|
+
CREATE INDEX IF NOT EXISTS traces_scope_hash ON traces(scope_id, hash);
|
|
80
92
|
|
|
81
93
|
CREATE VIRTUAL TABLE IF NOT EXISTS traces_fts_index USING fts5(
|
|
82
94
|
trace_id UNINDEXED,
|
|
@@ -366,6 +378,7 @@ CREATE TABLE IF NOT EXISTS working_items (
|
|
|
366
378
|
text TEXT NOT NULL,
|
|
367
379
|
priority REAL NOT NULL DEFAULT 0.5,
|
|
368
380
|
pinned INTEGER NOT NULL DEFAULT 0,
|
|
381
|
+
lane TEXT NOT NULL DEFAULT 'auto',
|
|
369
382
|
source_trace_id TEXT,
|
|
370
383
|
created_at TEXT NOT NULL,
|
|
371
384
|
updated_at TEXT NOT NULL,
|