dsh-cortex-memory 0.4.162 → 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 +2 -2
- 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/service/cortex.js
CHANGED
|
@@ -10,7 +10,7 @@ import { createSummaryRepository } from '../store/repositories/summaries.js';
|
|
|
10
10
|
import { createJobRepository } from '../store/repositories/jobs.js';
|
|
11
11
|
import { createSkillRepository } from '../store/repositories/skills.js';
|
|
12
12
|
import { createPlaybookRepository } from '../store/repositories/playbook.js';
|
|
13
|
-
import { selectTiers, renderTiers, DEFAULT_TIER_BUDGETS } from '../prompt/tiers.js';
|
|
13
|
+
import { selectTiers, renderTiers, DEFAULT_TIER_BUDGETS, scaleTierBudgets } from '../prompt/tiers.js';
|
|
14
14
|
import { readOverrides, writeOverride, rollbackOverride, effectiveFeatures } from '../core/feature-overrides.js';
|
|
15
15
|
import { effectiveModelConfig, saveModelConfig, redactedModelConfig } from '../core/model-config.js';
|
|
16
16
|
import { estimateTokens, truncate } from '../memory/tokenizer.js';
|
|
@@ -138,6 +138,10 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
138
138
|
dim: config.vectorDim ?? (remoteEmbedding ? modelConfig.embedding.dim : undefined),
|
|
139
139
|
annEnabled: config.features?.vectorAnn === true,
|
|
140
140
|
annMin: config.vectorAnnMin ?? 20000,
|
|
141
|
+
// 2026-12-06 助手:渐进扫描 —— 先扫最近 N 条,命中不够才继续往回扫
|
|
142
|
+
// (纯 JS 约 600 MFLOP/s,全量扫撑不到规模;硬截窗口会把远期记忆的语义召回砍掉)
|
|
143
|
+
scanCap: config.vectorScanCap ?? 200000,
|
|
144
|
+
scanMaxRows: config.vectorScanMax ?? 2000000,
|
|
141
145
|
annEngine: config.vectorAnnEngine === 'nsw' ? 'nsw' : 'hnsw',
|
|
142
146
|
annOptions: { M: 24, efConstruction: 200, efSearch: 800 },
|
|
143
147
|
externalAnnEnabled: config.features?.vectorAnnExternal === true,
|
|
@@ -153,7 +157,18 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
153
157
|
const policyConfig = (kind) => {
|
|
154
158
|
try { return policies.active(kind)?.config ?? null; } catch { return null; }
|
|
155
159
|
};
|
|
156
|
-
|
|
160
|
+
// HTTP reranker is optional. model-config.rerank is the single source of truth;
|
|
161
|
+
// the retrieval engine only uses it for explicit deep searches.
|
|
162
|
+
const reranker = (modelConfig.rerank.enabled || config.rerankEnabled === true || config.features?.rerank === true)
|
|
163
|
+
&& (modelConfig.rerank.baseUrl || config.rerankBaseUrl)
|
|
164
|
+
? createHttpReranker({
|
|
165
|
+
baseUrl: modelConfig.rerank.baseUrl || config.rerankBaseUrl,
|
|
166
|
+
apiKey: modelConfig.rerank.apiKey || config.rerankApiKey || '',
|
|
167
|
+
model: modelConfig.rerank.model || config.rerankModel || 'bge-reranker-base',
|
|
168
|
+
timeoutMs: config.rerankTimeoutMs ?? 60000,
|
|
169
|
+
})
|
|
170
|
+
: null;
|
|
171
|
+
const retrieve = createRetrievalEngine({ traces, facts, graph, vector, policy: policyConfig, config, reranker });
|
|
157
172
|
const compression = createCompressionEngine({ traces, summaries, facts, entities, config, memoryPolicy });
|
|
158
173
|
const extractor = createFactExtractor({ entities, facts });
|
|
159
174
|
const digest = createDigestEngine({ traces, summaries, emotion, goals: goalStore, feedback, scopeId: config.scope });
|
|
@@ -190,15 +205,6 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
190
205
|
}
|
|
191
206
|
return review;
|
|
192
207
|
}
|
|
193
|
-
const reranker = (modelConfig.rerank.enabled || config.rerankEnabled === true || config.features?.rerank === true)
|
|
194
|
-
&& (modelConfig.rerank.baseUrl || config.rerankBaseUrl)
|
|
195
|
-
? createHttpReranker({
|
|
196
|
-
baseUrl: modelConfig.rerank.baseUrl || config.rerankBaseUrl,
|
|
197
|
-
apiKey: modelConfig.rerank.apiKey || config.rerankApiKey || '',
|
|
198
|
-
model: modelConfig.rerank.model || config.rerankModel || 'bge-reranker-base',
|
|
199
|
-
timeoutMs: config.rerankTimeoutMs ?? 15000,
|
|
200
|
-
})
|
|
201
|
-
: null;
|
|
202
208
|
const qa = createQaEngine({ cortex: { search: (query, options) => search(query, options), searchAsync: (query, options) => searchAsync(query, options) }, llm: llmAdapter, reranker, limit: config.qa?.limit ?? 8, budget: config.qa?.budget ?? 3000 });
|
|
203
209
|
const narrative = createNarrativeEngine({ traces, summaries });
|
|
204
210
|
const consolidation = createConsolidationEngine({ db, traces, summaries, audit, llm: llmAdapter });
|
|
@@ -226,14 +232,19 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
226
232
|
}).filter((probe) => probe.query.length >= 4).slice(0, 6);
|
|
227
233
|
if (probes.length < 5) return { ok: true, skipped: 'insufficient-samples', n: probes.length };
|
|
228
234
|
let hits = 0;
|
|
235
|
+
// 2026-12-06 三方复核(寒 P0-2):这条自检本身走同步检索,配真嵌入时**没有向量**,
|
|
236
|
+
// 于是演化守门看不见「语义退化」。这里把语义通道的真实状态一并报出去。
|
|
237
|
+
let semantic = 'unknown';
|
|
229
238
|
for (const probe of probes) {
|
|
230
239
|
try {
|
|
231
240
|
const result = retrieve.search(probe.query, { scopeId, limit: 5 });
|
|
241
|
+
const vec = (result.trace?.sources ?? []).find((s) => s.source === 'vector');
|
|
242
|
+
if (vec) semantic = vec.semantic ?? (vec.ok ? 'async' : 'unavailable');
|
|
232
243
|
if (result.items.some((item) => item.id === probe.id)) hits += 1;
|
|
233
244
|
} catch { /* one probe must not abort the guard */ }
|
|
234
245
|
}
|
|
235
246
|
const recall = hits / probes.length;
|
|
236
|
-
const after = { n: probes.length, hits, recall: Math.round(recall * 1000) / 1000 };
|
|
247
|
+
const after = { n: probes.length, hits, recall: Math.round(recall * 1000) / 1000, semantic };
|
|
237
248
|
if (phase === 'before') return { ok: true, ...after };
|
|
238
249
|
if (baseline?.recall == null) return { ok: true, ...after, skipped: 'no-baseline' };
|
|
239
250
|
return {
|
|
@@ -498,12 +509,19 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
498
509
|
// 让 novelty 有真实基线:说过的话再说不算新,新话题才算新。
|
|
499
510
|
let recentTexts = [];
|
|
500
511
|
try {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
.
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
.
|
|
512
|
+
if (typeof traces.recentTexts === 'function') {
|
|
513
|
+
// 2026-12-05 助手:只取 text,不构造 21 个完整对象(CPU profile 里这条占写入 43%)。
|
|
514
|
+
recentTexts = traces.recentTexts(scopeId, { limit: 20, excludeId: result.trace?.id ?? null })
|
|
515
|
+
.filter(Boolean);
|
|
516
|
+
} else {
|
|
517
|
+
const recent = traces.list?.({ scopeId, limit: 21 }) ?? [];
|
|
518
|
+
recentTexts = recent
|
|
519
|
+
.filter((t) => t && t.id !== result.trace?.id)
|
|
520
|
+
// rowToTrace 的正文列叫 content,不叫 text —— 写 text 会静默得到空串
|
|
521
|
+
.map((t) => String(t.content ?? ''))
|
|
522
|
+
.filter(Boolean)
|
|
523
|
+
.slice(-20);
|
|
524
|
+
}
|
|
507
525
|
} catch {
|
|
508
526
|
recentTexts = [];
|
|
509
527
|
}
|
|
@@ -580,7 +598,10 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
580
598
|
|
|
581
599
|
function write(input = {}) {
|
|
582
600
|
const started = Date.now();
|
|
583
|
-
|
|
601
|
+
// 2026-12-05 助手:单条写以前是裸的(writeMany 有事务、write 没有),
|
|
602
|
+
// 一次 writeInternal 要动 traces/FTS/embeddings/events/audit 五张表,
|
|
603
|
+
// 中途崩就留下"有痕迹没索引"。现在包一层,嵌套由 transaction() 的计数处理。
|
|
604
|
+
const result = transaction(db, () => writeInternal(input));
|
|
584
605
|
metrics.inc(result.skipped ? 'writes.skipped' : 'writes.created');
|
|
585
606
|
metrics.observe('write.ms', Date.now() - started);
|
|
586
607
|
return result;
|
|
@@ -733,16 +754,33 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
733
754
|
identity,
|
|
734
755
|
relationships: relationshipStore.list(scopeId),
|
|
735
756
|
intentions: initiativeStore.pending(scopeId),
|
|
736
|
-
|
|
757
|
+
// 2026-12-04:工作记忆按道各取,否则工程待办(优先级高、更新频繁)会占满 20 条,
|
|
758
|
+
// self/life 道即使有空预算也无米下锅。
|
|
759
|
+
working: [
|
|
760
|
+
...workingStore.list({ scopeId, lane: 'self', limit: 8 }),
|
|
761
|
+
...workingStore.list({ scopeId, lane: 'life', limit: 8 }),
|
|
762
|
+
...workingStore.list({ scopeId, lane: 'work', limit: 8 }),
|
|
763
|
+
],
|
|
737
764
|
goals: goalStore.list({ scopeId, status: 'active', limit: 20 }),
|
|
765
|
+
// Active/trial skills must be visible to the model, otherwise they are
|
|
766
|
+
// created and never used (last_used_at stayed NULL for 19 days).
|
|
767
|
+
skills: [
|
|
768
|
+
...skillsRepo.list({ scopeId, state: 'active', limit: 3 }),
|
|
769
|
+
...skillsRepo.list({ scopeId, state: 'trial', limit: 2 }),
|
|
770
|
+
...skillsRepo.list({ scopeId, state: 'candidate', limit: 4 }),
|
|
771
|
+
].slice(0, 9),
|
|
738
772
|
emotion: emotion.text(),
|
|
739
773
|
calibration: growth.calibration({ scopeId }),
|
|
740
774
|
capacity: {
|
|
741
775
|
identityBudget: config.identityBudget,
|
|
742
776
|
identityTokens: estimateTokens(identityText),
|
|
743
|
-
|
|
777
|
+
// 2026-12-04:工作记忆分道后的真实值(面板不能再说 700/1600 这种旧数)
|
|
778
|
+
workingBudget: (config.workingBudgetSelf ?? 400) + (config.workingBudgetLife ?? 250),
|
|
779
|
+
workingBudgetSelf: config.workingBudgetSelf ?? 400,
|
|
780
|
+
workingBudgetLife: config.workingBudgetLife ?? 250,
|
|
781
|
+
workingBudgetWork: config.workingBudgetWork ?? 800,
|
|
744
782
|
contextBudget: config.contextBudget,
|
|
745
|
-
promptBudget:
|
|
783
|
+
promptBudget: config.promptBudget ?? 2400,
|
|
746
784
|
tiers: DEFAULT_TIER_BUDGETS,
|
|
747
785
|
resultLimit: config.resultLimit,
|
|
748
786
|
ftsLimit: config.ftsLimit,
|
|
@@ -1534,6 +1572,83 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1534
1572
|
} catch (error) {
|
|
1535
1573
|
report.errors.push(`intentions: ${error instanceof Error ? error.message : String(error)}`);
|
|
1536
1574
|
}
|
|
1575
|
+
// 2026-12-05 助手:dream_runs 保留策略。
|
|
1576
|
+
// 没有 LLM 时每次调度都写一行 skipped —— 实测占 66% 的行数(1945/2903)、约 10 MB。
|
|
1577
|
+
// 只留最近 N 条 skipped;真实跑批(applied / rejected / degraded)一条不动。
|
|
1578
|
+
// 阈值可配:config.dreamRunsKeepSkipped(默认 200)。
|
|
1579
|
+
// 2026-12-05 夜:目标数量自动收敛。
|
|
1580
|
+
// 沉思会持续造一次性目标(p=0.45),而 prompt 只取前 20 条 —— 多出来的等于不存在。
|
|
1581
|
+
// 规则:priority 降序、同级取新;超出上限的归档最老的(不删,status=archived 可唤醒)。
|
|
1582
|
+
// 实测这条规则正好保住 3 个 p=1 项目 + p=0.8 的 Cortex + 4 个驱力 + 最新 12 条一次性念头。
|
|
1583
|
+
try {
|
|
1584
|
+
const cap = Math.max(1, Number(config.goalActiveCap ?? 20));
|
|
1585
|
+
const rows = db.prepare(
|
|
1586
|
+
"SELECT id FROM goals WHERE scope_id = ? AND status = 'active' ORDER BY COALESCE(priority, 0) DESC, created_at DESC",
|
|
1587
|
+
).all(scopeId);
|
|
1588
|
+
if (rows.length > cap) {
|
|
1589
|
+
const upd = db.prepare("UPDATE goals SET status = 'archived', updated_at = ? WHERE id = ?");
|
|
1590
|
+
let archived = 0;
|
|
1591
|
+
for (const row of rows.slice(cap)) { upd.run(at, row.id); archived += 1; }
|
|
1592
|
+
report.goalsArchived = archived;
|
|
1593
|
+
}
|
|
1594
|
+
} catch (error) {
|
|
1595
|
+
report.errors.push(`goals.cap: ${error instanceof Error ? error.message : String(error)}`);
|
|
1596
|
+
}
|
|
1597
|
+
// 2026-12-05 夜(允复核指出):dream_runs 的 applied/rejected/degraded 会永续增长。
|
|
1598
|
+
// 不删行 —— 只给**超龄**的行瘦身:把三个大 JSON 列置空,保留 id/at/status/model/error。
|
|
1599
|
+
// 这样"跑过多少次、成没成"的历史还在,吃掉体积的明细没了。
|
|
1600
|
+
// 读者只有 health(只读最新一条 + 当天的 applied)和 consolidate.list(历史详情),
|
|
1601
|
+
// 前者完全不受影响,后者对超龄行会看到空明细 —— 可接受。
|
|
1602
|
+
// 默认 90 天;config.dreamRunsSlimDays 可调。今天库里最老的才 23 天,所以本次零改动。
|
|
1603
|
+
try {
|
|
1604
|
+
const slimDays = Math.max(1, Number(config.dreamRunsSlimDays ?? 90));
|
|
1605
|
+
const slimCutoff = new Date(Date.now() - slimDays * 86_400_000).toISOString();
|
|
1606
|
+
// 2026-12-06 助手:不直接清空成 '[]'(那会丢掉「这次跑批做了什么」的信号)。
|
|
1607
|
+
// 超龄行换成紧凑摘要:{"n":条数,"byAction":{keep:8,merge:4,...},"applied":N}。
|
|
1608
|
+
// 体积约为原 JSON 的 1/30,但"跑过几次、每类动作多少"仍可查。
|
|
1609
|
+
const stale = db.prepare(`
|
|
1610
|
+
SELECT id, decisions_json, applied_json FROM dream_runs
|
|
1611
|
+
WHERE scope_id = ? AND at < ?
|
|
1612
|
+
AND (COALESCE(LENGTH(decisions_json), 0) > 200 OR COALESCE(LENGTH(applied_json), 0) > 200)
|
|
1613
|
+
`).all(scopeId, slimCutoff);
|
|
1614
|
+
let slimmed = 0;
|
|
1615
|
+
if (stale.length) {
|
|
1616
|
+
const upd = db.prepare('UPDATE dream_runs SET input_json = ?, decisions_json = ?, applied_json = ? WHERE id = ?');
|
|
1617
|
+
for (const row of stale) {
|
|
1618
|
+
let decisions = [];
|
|
1619
|
+
try { decisions = JSON.parse(row.decisions_json ?? '[]'); } catch { decisions = []; }
|
|
1620
|
+
const byAction = {};
|
|
1621
|
+
for (const d of Array.isArray(decisions) ? decisions : []) {
|
|
1622
|
+
const a = String(d?.action ?? 'unknown');
|
|
1623
|
+
byAction[a] = (byAction[a] ?? 0) + 1;
|
|
1624
|
+
}
|
|
1625
|
+
let appliedCount = 0;
|
|
1626
|
+
try { const a = JSON.parse(row.applied_json ?? '[]'); appliedCount = Array.isArray(a) ? a.length : 0; } catch { appliedCount = 0; }
|
|
1627
|
+
const summary = JSON.stringify({ n: Array.isArray(decisions) ? decisions.length : 0, byAction, applied: appliedCount, slimmed: true });
|
|
1628
|
+
upd.run('[]', summary, `{"n":${appliedCount},"slimmed":true}`, row.id);
|
|
1629
|
+
slimmed += 1;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
report.dreamRunsSlimmed = slimmed;
|
|
1633
|
+
} catch (error) {
|
|
1634
|
+
report.errors.push(`dream_runs.slim: ${error instanceof Error ? error.message : String(error)}`);
|
|
1635
|
+
}
|
|
1636
|
+
try {
|
|
1637
|
+
const keep = Math.max(0, Number(config.dreamRunsKeepSkipped ?? 200));
|
|
1638
|
+
if (keep === 0) {
|
|
1639
|
+
const result = db.prepare("DELETE FROM dream_runs WHERE scope_id = ? AND status = 'skipped'").run(scopeId);
|
|
1640
|
+
report.dreamRuns = Number(result.changes ?? 0);
|
|
1641
|
+
} else {
|
|
1642
|
+
// OFFSET keep-1 = 第 keep 新的那条;删除「早于它」的,正好留 keep 条(第一版写成 OFFSET keep,多留一条)。
|
|
1643
|
+
const cutoff = db.prepare("SELECT at FROM dream_runs WHERE scope_id = ? AND status = 'skipped' ORDER BY at DESC LIMIT 1 OFFSET ?").get(scopeId, keep - 1);
|
|
1644
|
+
if (cutoff) {
|
|
1645
|
+
const result = db.prepare("DELETE FROM dream_runs WHERE scope_id = ? AND status = 'skipped' AND at < ?").run(scopeId, cutoff.at);
|
|
1646
|
+
report.dreamRuns = Number(result.changes ?? 0);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
} catch (error) {
|
|
1650
|
+
report.errors.push(`dream_runs: ${error instanceof Error ? error.message : String(error)}`);
|
|
1651
|
+
}
|
|
1537
1652
|
try {
|
|
1538
1653
|
const result = db.prepare(`
|
|
1539
1654
|
UPDATE playbook_rules SET status = 'retired', updated_at = ?
|
|
@@ -1549,7 +1664,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1549
1664
|
// them out of active recall; the rows stay for inspection.
|
|
1550
1665
|
const result = db.prepare(`
|
|
1551
1666
|
UPDATE traces SET state = 'archived', updated_at = ?
|
|
1552
|
-
WHERE scope_id = ? AND state = 'active'
|
|
1667
|
+
WHERE scope_id = ? AND state = 'active' AND protected = 0
|
|
1553
1668
|
AND (content LIKE '用户:<goal_round>%' OR content LIKE '<goal_round>%'
|
|
1554
1669
|
OR (content LIKE '%Objective: "%' AND content LIKE '%Round: %'))
|
|
1555
1670
|
`).run(at, scopeId);
|
|
@@ -1565,9 +1680,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1565
1680
|
try {
|
|
1566
1681
|
// Working memory is a small L1 layer. Unpinned items that nobody updated
|
|
1567
1682
|
// for weeks are stale by definition; pinned ones always stay.
|
|
1568
|
-
const ttlDays = Math.max(1, Number(config.workingTtlDays ??
|
|
1683
|
+
const ttlDays = Math.max(1, Number(config.workingTtlDays ?? 7));
|
|
1569
1684
|
const cutoff = new Date(now - ttlDays * 86_400_000).toISOString();
|
|
1570
|
-
const result = db.prepare('DELETE FROM working_items WHERE scope_id = ? AND pinned = 0 AND created_at < ?').run(scopeId, cutoff);
|
|
1685
|
+
const result = db.prepare('DELETE FROM working_items WHERE scope_id = ? AND pinned = 0 AND COALESCE(updated_at, created_at) < ?').run(scopeId, cutoff);
|
|
1571
1686
|
report.working = result.changes;
|
|
1572
1687
|
} catch (error) {
|
|
1573
1688
|
report.errors.push(`working: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -1896,6 +2011,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1896
2011
|
return String(b.createdAt ?? '').localeCompare(String(a.createdAt ?? ''));
|
|
1897
2012
|
});
|
|
1898
2013
|
const lines = [];
|
|
2014
|
+
const renderedIds = [];
|
|
1899
2015
|
let used = 0;
|
|
1900
2016
|
let omitted = 0;
|
|
1901
2017
|
for (const rule of rules) {
|
|
@@ -1911,9 +2027,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1911
2027
|
const line = `- [${rule.id}] ${rule.title}:${body}(helpful=${rule.helpful} harmful=${rule.harmful}${rule.validTo ? ` · 到期 ${rule.validTo}` : ''})`;
|
|
1912
2028
|
const cost = estimateTokens(line);
|
|
1913
2029
|
if (used + cost > budget) { omitted += 1; continue; }
|
|
1914
|
-
lines.push(line); used += cost;
|
|
2030
|
+
lines.push(line); used += cost; renderedIds.push(rule.id);
|
|
1915
2031
|
}
|
|
1916
|
-
return { text: lines.length ? lines.join('\n') : '', count: lines.length, omitted, budget };
|
|
2032
|
+
return { text: lines.length ? lines.join('\n') : '', count: lines.length, omitted, budget, ids: renderedIds };
|
|
1917
2033
|
},
|
|
1918
2034
|
},
|
|
1919
2035
|
asOf: ({ subject, predicate = null, at = null, mode = 'historical', includeDisputed = true, scopeId = config.scope } = {}) => { const entity = entities.findByName(scopeId, subject);
|
|
@@ -2046,15 +2162,31 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
2046
2162
|
return { targetTraceId, extractedTraceId: extractedId, chars: content.length };
|
|
2047
2163
|
},
|
|
2048
2164
|
flushLlmFacts,
|
|
2049
|
-
recallTiered: ({ query, limit = 20, permBudget
|
|
2050
|
-
const
|
|
2051
|
-
const
|
|
2052
|
-
|
|
2165
|
+
recallTiered: ({ query, limit = 20, budget, permBudget, hotBudget, coldBudget, scopeId = config.scope, includeArchived = false } = {}) => {
|
|
2166
|
+
const explicit = permBudget != null || hotBudget != null || coldBudget != null;
|
|
2167
|
+
const tiers = (!explicit && budget != null)
|
|
2168
|
+
? scaleTierBudgets(budget)
|
|
2169
|
+
: {
|
|
2170
|
+
perm: permBudget ?? DEFAULT_TIER_BUDGETS.perm,
|
|
2171
|
+
hot: hotBudget ?? DEFAULT_TIER_BUDGETS.hot,
|
|
2172
|
+
cold: coldBudget ?? DEFAULT_TIER_BUDGETS.cold,
|
|
2173
|
+
};
|
|
2174
|
+
const result = search(query, { limit, budget: tiers.perm + tiers.hot + tiers.cold, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
|
|
2175
|
+
const selection = selectTiers(result.items, { budgets: tiers });
|
|
2176
|
+
return { query, result, selection, budgets: tiers, text: renderTiers(selection) };
|
|
2053
2177
|
},
|
|
2054
|
-
recallTieredAsync: async ({ query, limit = 20, permBudget
|
|
2055
|
-
const
|
|
2056
|
-
const
|
|
2057
|
-
|
|
2178
|
+
recallTieredAsync: async ({ query, limit = 20, budget, permBudget, hotBudget, coldBudget, scopeId = config.scope, includeArchived = false } = {}) => {
|
|
2179
|
+
const explicit = permBudget != null || hotBudget != null || coldBudget != null;
|
|
2180
|
+
const tiers = (!explicit && budget != null)
|
|
2181
|
+
? scaleTierBudgets(budget)
|
|
2182
|
+
: {
|
|
2183
|
+
perm: permBudget ?? DEFAULT_TIER_BUDGETS.perm,
|
|
2184
|
+
hot: hotBudget ?? DEFAULT_TIER_BUDGETS.hot,
|
|
2185
|
+
cold: coldBudget ?? DEFAULT_TIER_BUDGETS.cold,
|
|
2186
|
+
};
|
|
2187
|
+
const result = await searchAsync(query, { limit, budget: tiers.perm + tiers.hot + tiers.cold, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
|
|
2188
|
+
const selection = selectTiers(result.items, { budgets: tiers });
|
|
2189
|
+
return { query, result, selection, budgets: tiers, text: renderTiers(selection) };
|
|
2058
2190
|
},
|
|
2059
2191
|
get,
|
|
2060
2192
|
timeline,
|
package/src/store/database.js
CHANGED
|
@@ -27,6 +27,12 @@ function ensureTraceColumns(db) {
|
|
|
27
27
|
if (!columns.some((column) => column.name === 'author_confidence')) {
|
|
28
28
|
db.exec('ALTER TABLE traces ADD COLUMN author_confidence REAL');
|
|
29
29
|
}
|
|
30
|
+
// 2026-12-05 助手:显式「钉住」。
|
|
31
|
+
// 在此之前保护只靠 importance 数值 —— 等于"重要 = 自动被保护",没有
|
|
32
|
+
// "这条我亲手钉住、谁都不许动"。加一列,老行默认 0(不改变现有语义)。
|
|
33
|
+
if (!columns.some((column) => column.name === 'protected')) {
|
|
34
|
+
db.exec('ALTER TABLE traces ADD COLUMN protected INTEGER NOT NULL DEFAULT 0');
|
|
35
|
+
}
|
|
30
36
|
}
|
|
31
37
|
|
|
32
38
|
function ensureSummonColumns(db) {
|
|
@@ -55,6 +61,30 @@ function ensureFactsColumns(db) {
|
|
|
55
61
|
db.prepare("UPDATE facts SET superseded_at = updated_at WHERE invalidated_by IS NOT NULL AND superseded_at IS NULL").run();
|
|
56
62
|
}
|
|
57
63
|
|
|
64
|
+
/**
|
|
65
|
+
* 2026-12-04:工作记忆分道。self(身份/情感/关系)/ work(工程待办)/ life(生活日常)。
|
|
66
|
+
* 老行默认 'auto',读取时按 kind 推断;写入时显式传 lane 优先。
|
|
67
|
+
* 动机:工程待办占满工作记忆预算,把技能/关系/意图整段挤掉。
|
|
68
|
+
*/
|
|
69
|
+
function ensureWorkingColumns(db) {
|
|
70
|
+
const columns = db.prepare('PRAGMA table_info(working_items)').all();
|
|
71
|
+
if (!columns.some((column) => column.name === 'lane')) {
|
|
72
|
+
db.exec("ALTER TABLE working_items ADD COLUMN lane TEXT NOT NULL DEFAULT 'auto'");
|
|
73
|
+
}
|
|
74
|
+
// 老行 lane='auto':按 kind + 强工程词回填一次,让按道查询能拿到它们。
|
|
75
|
+
// 推断规则与 src/self/working.js 的 deriveLane 保持一致(todo/task→work,identity→self)。
|
|
76
|
+
db.prepare(`UPDATE working_items SET lane = CASE
|
|
77
|
+
WHEN lower(kind) IN ('todo','task','todo_list','backlog') THEN 'work'
|
|
78
|
+
WHEN lower(kind) = 'identity' THEN 'self'
|
|
79
|
+
WHEN lower(kind) = 'focus' AND (
|
|
80
|
+
text LIKE '%DSH%' OR text LIKE '%插件%' OR text LIKE '%备份%' OR text LIKE '%重启%'
|
|
81
|
+
OR text LIKE '%验收%' OR text LIKE '%发布%' OR text LIKE '%commit%' OR text LIKE '%npm%'
|
|
82
|
+
OR text LIKE '%node_modules%' OR text LIKE '%SQLite%' OR text LIKE '%sqlite%'
|
|
83
|
+
) THEN 'work'
|
|
84
|
+
ELSE 'life' END
|
|
85
|
+
WHERE lane = 'auto'`).run();
|
|
86
|
+
}
|
|
87
|
+
|
|
58
88
|
function ensureParent(file) {
|
|
59
89
|
if (file === ':memory:') return;
|
|
60
90
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
@@ -104,6 +134,7 @@ export function migrate(db, { version = SCHEMA_VERSION } = {}) {
|
|
|
104
134
|
ensureFactsColumns(db);
|
|
105
135
|
ensureSummonColumns(db);
|
|
106
136
|
ensurePolicyColumns(db);
|
|
137
|
+
ensureWorkingColumns(db);
|
|
107
138
|
const row = db.prepare('SELECT value FROM meta WHERE key = ?').get('schema_version');
|
|
108
139
|
if (!row) {
|
|
109
140
|
db.prepare('INSERT INTO meta(key, value, updated_at) VALUES (?, ?, ?)').run('schema_version', String(version), nowIso());
|
|
@@ -114,6 +145,27 @@ export function migrate(db, { version = SCHEMA_VERSION } = {}) {
|
|
|
114
145
|
}
|
|
115
146
|
const ftsRebuilt = ensureFtsIndex(db);
|
|
116
147
|
db.exec('COMMIT');
|
|
148
|
+
// 2026-12-06 助手:新建的 traces_scope_hash 索引如果没有统计信息,优化器根本不认它,
|
|
149
|
+
// 仍会为「省排序」去扫 traces_scope_recorded 全库(4379 行时 p50 22.6ms,占写入路径 56%)。
|
|
150
|
+
// 实测:ANALYZE 之后同一查询 22.56ms → 0.05ms。
|
|
151
|
+
// 只在「从没统计过」或「这条索引还没有统计」时跑 —— 大库不会每次启动都全表分析。
|
|
152
|
+
// 2026-12-06 助手 + 寒复核(E1):只分析新索引,不做全库 ANALYZE
|
|
153
|
+
// (百万级库全库分析会扫所有表与 FTS 影子表,可能堵启动数秒到数十秒)。
|
|
154
|
+
// 失败也不再裸吞 —— 把错误带回 migrate() 的结果里,调用方可观测。
|
|
155
|
+
try {
|
|
156
|
+
const stat1 = db.prepare("SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1'").get();
|
|
157
|
+
let needAnalyze = !stat1;
|
|
158
|
+
if (!needAnalyze) {
|
|
159
|
+
const row = db.prepare("SELECT 1 AS x FROM sqlite_stat1 WHERE tbl = 'traces' AND idx = 'traces_scope_hash'").get();
|
|
160
|
+
needAnalyze = !row;
|
|
161
|
+
}
|
|
162
|
+
if (needAnalyze) {
|
|
163
|
+
db.exec('ANALYZE traces_scope_hash');
|
|
164
|
+
return { version, applied: true, ftsRebuilt, analyzed: true };
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
return { version, applied: true, ftsRebuilt, analyzed: false, analyzeError: error instanceof Error ? error.message : String(error) };
|
|
168
|
+
}
|
|
117
169
|
return { version, applied: true, ftsRebuilt };
|
|
118
170
|
} catch (error) {
|
|
119
171
|
try { db.exec('ROLLBACK'); } catch { /* ignore rollback failure */ }
|
|
@@ -121,9 +173,16 @@ export function migrate(db, { version = SCHEMA_VERSION } = {}) {
|
|
|
121
173
|
}
|
|
122
174
|
}
|
|
123
175
|
|
|
176
|
+
// 2026-12-05 助手:嵌套计数。transaction() 以前是盲 BEGIN,
|
|
177
|
+
// write() 包事务之后,批量写(writeMany 外层已有事务)会 "cannot start a transaction within a transaction"。
|
|
178
|
+
// 有了这个计数,内层复用外层事务,语义不变。
|
|
179
|
+
let transactionDepth = 0;
|
|
180
|
+
|
|
124
181
|
export function transaction(db, fn) {
|
|
125
182
|
if (typeof fn !== 'function') throw new CortexError(ERROR_CODES.INVALID_INPUT, 'transaction needs a function');
|
|
183
|
+
if (transactionDepth > 0) return fn();
|
|
126
184
|
db.exec('BEGIN IMMEDIATE');
|
|
185
|
+
transactionDepth += 1;
|
|
127
186
|
try {
|
|
128
187
|
const value = fn();
|
|
129
188
|
db.exec('COMMIT');
|
|
@@ -131,6 +190,8 @@ export function transaction(db, fn) {
|
|
|
131
190
|
} catch (error) {
|
|
132
191
|
try { db.exec('ROLLBACK'); } catch { /* ignore */ }
|
|
133
192
|
throw error;
|
|
193
|
+
} finally {
|
|
194
|
+
transactionDepth -= 1;
|
|
134
195
|
}
|
|
135
196
|
}
|
|
136
197
|
|
|
@@ -60,6 +60,31 @@ export function createEntityRepository(db) {
|
|
|
60
60
|
.all(scopeId, count, skip).map(rowToEntity);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
// 2026-12-05 夜:graph.search 每轮要拿 500 个实体算种子权重,但只用到 name/aliases。
|
|
64
|
+
// 原来为这 500 行都跑 rowToEntity(含 aliases 的 JSON 解析),profile 里占搜索 12%。
|
|
65
|
+
function briefList({ scopeId = 'global', limit = 500 } = {}) {
|
|
66
|
+
const count = Math.max(1, Math.min(10000, Number(limit) || 500));
|
|
67
|
+
return db.prepare('SELECT id, name, aliases_json FROM entities WHERE scope_id = ? ORDER BY name ASC LIMIT ?')
|
|
68
|
+
.all(scopeId, count)
|
|
69
|
+
.map((row) => ({ id: row.id, name: row.name, aliases: asJsonArray(row.aliases_json) }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 排序后只有前几十个实体需要完整行 —— 一次 IN 查询取回,别为 500 条都构造对象。
|
|
73
|
+
function getMany(ids = []) {
|
|
74
|
+
const unique = [...new Set((Array.isArray(ids) ? ids : []).filter(Boolean))];
|
|
75
|
+
const out = new Map();
|
|
76
|
+
for (let i = 0; i < unique.length; i += 400) {
|
|
77
|
+
const chunk = unique.slice(i, i + 400);
|
|
78
|
+
const marks = chunk.map(() => '?').join(',');
|
|
79
|
+
const rows = db.prepare(`SELECT * FROM entities WHERE id IN (${marks})`).all(...chunk);
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
const entity = rowToEntity(row);
|
|
82
|
+
if (entity) out.set(entity.id, entity);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
63
88
|
function search(scopeId, query, { limit = 20 } = {}) {
|
|
64
89
|
const value = `%${String(query ?? '').trim().toLowerCase()}%`;
|
|
65
90
|
if (value === '%%') return [];
|
|
@@ -68,5 +93,5 @@ export function createEntityRepository(db) {
|
|
|
68
93
|
.all(scopeId, value, value, count).map(rowToEntity);
|
|
69
94
|
}
|
|
70
95
|
|
|
71
|
-
return { get, findByName, upsert, list, search };
|
|
96
|
+
return { get, getMany, findByName, upsert, list, briefList, search };
|
|
72
97
|
}
|
|
@@ -278,5 +278,40 @@ export function createFactRepository(db) {
|
|
|
278
278
|
}));
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
-
|
|
281
|
+
// 2026-12-05 助手:检索每轮只需要「已失效事实来自哪些事件」,原来却拉最多 2000 行
|
|
282
|
+
// 完整事实再逐行 rowToFact(JSON 全解析)——CPU profile 里占搜索总时间 10.9%。
|
|
283
|
+
// 这里只取一列,语义完全等价(同一 where、同一 limit),没有缓存陈旧风险。
|
|
284
|
+
function invalidatedEventIds(scopeId = 'global', { limit = 2000 } = {}) {
|
|
285
|
+
const count = Math.max(1, Math.min(10000, Number(limit) || 2000));
|
|
286
|
+
const rows = db.prepare(
|
|
287
|
+
"SELECT DISTINCT source_event_id FROM facts WHERE scope_id = ? AND status = 'invalidated' AND source_event_id IS NOT NULL LIMIT ?",
|
|
288
|
+
).all(scopeId, count);
|
|
289
|
+
return rows.map((row) => row.source_event_id);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// 2026-12-06 助手:graph.loadAdjacency 每次 search 都要 500 条事实来建邻接图,
|
|
293
|
+
// 但只用 subject/object/predicate/confidence/status/有效期这 7 个字段。
|
|
294
|
+
// 原来走 SELECT * + rowToFact(含 JSON 解析),profile 里 facts.list 占搜索 19.8%(23 ms/查询)。
|
|
295
|
+
function briefList({ scopeId = 'global', limit = 500 } = {}) {
|
|
296
|
+
const count = Math.max(1, Math.min(10000, Number(limit) || 500));
|
|
297
|
+
return db.prepare(`
|
|
298
|
+
SELECT id, subject_id, predicate, object_id, confidence, status, valid_from, valid_to, source_event_id
|
|
299
|
+
FROM facts
|
|
300
|
+
WHERE scope_id = ?
|
|
301
|
+
ORDER BY valid_from DESC
|
|
302
|
+
LIMIT ?
|
|
303
|
+
`).all(scopeId, count).map((row) => ({
|
|
304
|
+
id: row.id,
|
|
305
|
+
subjectId: row.subject_id,
|
|
306
|
+
predicate: row.predicate,
|
|
307
|
+
objectId: row.object_id,
|
|
308
|
+
confidence: row.confidence,
|
|
309
|
+
status: row.status,
|
|
310
|
+
validFrom: row.valid_from,
|
|
311
|
+
validTo: row.valid_to,
|
|
312
|
+
sourceEventId: row.source_event_id,
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return { get, resolve, queryAt, queryBeliefAt, list, briefList, invalidate, disputes, overlapping, invalidatedEventIds };
|
|
282
317
|
}
|