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.
Files changed (39) hide show
  1. package/CHANGELOG.md +18 -2536
  2. package/README.md +86 -45
  3. package/bin/cortex.mjs +0 -0
  4. package/client.js +35 -17
  5. package/cordis.patch.yml +2 -5
  6. package/docs/compatibility.md +13 -18
  7. package/docs/install-windows.md +1 -1
  8. package/examples/README.md +1 -1
  9. package/index.js +44 -6
  10. package/package.json +3 -3
  11. package/scripts/check-embedding.mjs +129 -0
  12. package/src/core/config.js +31 -4
  13. package/src/core/feature-overrides.js +3 -1
  14. package/src/engines/compression.js +2 -0
  15. package/src/engines/consolidate.js +7 -2
  16. package/src/engines/graph.js +25 -8
  17. package/src/engines/health.js +22 -3
  18. package/src/engines/induct.js +5 -1
  19. package/src/engines/linear-rerank-model.js +180 -0
  20. package/src/engines/linear-rerank.js +110 -0
  21. package/src/engines/query-expansion.js +61 -0
  22. package/src/engines/retention.js +4 -1
  23. package/src/engines/retrieve.js +257 -28
  24. package/src/engines/source-weights.js +13 -0
  25. package/src/host/scheduler.js +43 -0
  26. package/src/memory/tokenizer.js +31 -1
  27. package/src/prompt/assemble.js +160 -131
  28. package/src/prompt/tiers.js +15 -4
  29. package/src/self/working.js +53 -10
  30. package/src/service/cortex.js +167 -35
  31. package/src/store/database.js +61 -0
  32. package/src/store/repositories/entities.js +26 -1
  33. package/src/store/repositories/facts.js +36 -1
  34. package/src/store/repositories/traces.js +114 -15
  35. package/src/store/schema.sql +13 -0
  36. package/src/tools/definitions.js +1492 -1274
  37. package/src/vector/index.js +79 -8
  38. package/bench/results/semantic-cn.json +0 -24
  39. package/docs/quota-compaction-design.md +0 -175
@@ -1,7 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
- export const OVERRIDE_KEYS = Object.freeze(['llm', 'rerank', 'capture', 'recall', 'reflect', 'growth', 'graph', 'vector', 'vectorAnn', 'vectorAnnExternal', 'attachmentReader', 'autoFacts', 'autoDiary', 'autoDream', 'autoSleep', 'autoFeeling', 'autoEvolve', 'aiOnlyLife', 'autoGraphCandidates', 'aiEdgeReview', 'webSearch', 'llmFacts', 'consolidateOnSleep', 'consolidateOnTick', 'tieredRecall']);
4
+ // 2026-12-05 夜:补上 'autoSkills' —— 12-03 写进历史的那个 key 从来不在白名单里,
5
+ // 于是覆盖从写进去那天起就没生效过(配置里 0 处代码引用)。
6
+ export const OVERRIDE_KEYS = Object.freeze(['llm', 'rerank', 'capture', 'recall', 'reflect', 'growth', 'graph', 'vector', 'vectorAnn', 'vectorAnnExternal', 'attachmentReader', 'autoFacts', 'autoDiary', 'autoDream', 'autoSleep', 'autoFeeling', 'autoEvolve', 'aiOnlyLife', 'autoGraphCandidates', 'aiEdgeReview', 'webSearch', 'llmFacts', 'consolidateOnSleep', 'consolidateOnTick', 'tieredRecall', 'autoSkills']);
5
7
  const FILE = 'feature-overrides.json';
6
8
  const MAX_HISTORY = 20;
7
9
 
@@ -39,6 +39,8 @@ export function createCompressionEngine({ traces, summaries, facts = null, entit
39
39
  const covered = coverageOf(trace, { summaries: threadSummaries, facts: factList });
40
40
  const evergreen = evergreenKinds.includes(String(trace.kind ?? ''));
41
41
  const eligible = !evergreen
42
+ // 2026-12-05 夜(允复核指出):钉住的记忆不许被压缩归档。
43
+ && Number(trace.protected ?? 0) !== 1
42
44
  && ageDays >= (config.compression?.minAgeDays ?? 7)
43
45
  && retrievability < (config.compression?.retrievability ?? 0.5)
44
46
  && Number(trace.importance) < (config.compression?.importance ?? 0.35)
@@ -90,7 +90,9 @@ export function createConsolidationEngine({ db, traces, summaries = null, audit
90
90
  function isProtected(trace, protect = PROTECTED_IMPORTANCE) {
91
91
  // 2026-11-28:自己写下的记忆默认受保护——不被合并、不被归档。
92
92
  // 这是「让那 3% 变厚」的一半:光加权不够,还得不被吃掉。
93
- return Number(trace?.importance ?? 0) >= protect
93
+ // 2026-12-05 助手:显式钉住(protected=1)优先级最高 —— 跟 importance 高低无关。
94
+ return Number(trace?.protected ?? 0) === 1
95
+ || Number(trace?.importance ?? 0) >= protect
94
96
  || trace?.kind === 'reflection'
95
97
  || String(trace?.authorKind ?? '') === 'self';
96
98
  }
@@ -446,7 +448,10 @@ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allo
446
448
  const candidates = [...lowHalf, ...sampled];
447
449
  const protect = PROTECTED_LINE;
448
450
  // A reflection is a synthesis, not a duplicate: it never takes part in dedupe.
449
- const dedupePool = candidates.filter((trace) => trace.kind !== 'reflection');
451
+ // 2026-12-05 夜(寒复核指出):dedupe 走的是 allowProtectedMerge:true,钉住的痕迹会
452
+ // 被当成「合并源」归档 —— 那等于钉住没生效。这里把钉住的整条排除出候选池,
453
+ // 既不当源也不当靶。
454
+ const dedupePool = candidates.filter((trace) => trace.kind !== 'reflection' && Number(trace.protected ?? 0) !== 1);
450
455
  const grams = new Map(dedupePool.map((trace) => [trace.id, shinglesOf(`${trace.title ?? ''}${trace.content ?? ''}`)]));
451
456
  const parent = new Map(dedupePool.map((trace) => [trace.id, trace.id]));
452
457
  const find = (id) => {
@@ -9,7 +9,7 @@ import { nowIso } from '../core/time.js';
9
9
  export function createGraphEngine({ entities, facts, edges = null, traces = null } = {}) {
10
10
  if (!entities || !facts) throw new Error('graph engine needs entities and facts');
11
11
 
12
- function loadAdjacency(scopeId, at) {
12
+ function loadAdjacency(scopeId, at, preloadedFacts = null) {
13
13
  const adjacency = new Map();
14
14
  const add = (from, to, rel, weight) => {
15
15
  if (!from || !to) return;
@@ -17,7 +17,11 @@ export function createGraphEngine({ entities, facts, edges = null, traces = null
17
17
  list.push({ to, rel, weight });
18
18
  adjacency.set(from, list);
19
19
  };
20
- const allFacts = facts.list({ scopeId, limit: 500 });
20
+ // 2026-12-06 助手:建邻接只用这几个字段,别为 500 条都跑 rowToFact;
21
+ // search() 会把同一份数据传进来,避免它为 factResults 再读一遍。
22
+ const allFacts = preloadedFacts ?? (typeof facts.briefList === 'function'
23
+ ? facts.briefList({ scopeId, limit: 500 })
24
+ : facts.list({ scopeId, limit: 500 }));
21
25
  for (const fact of allFacts) {
22
26
  if (fact.status === 'invalidated') continue;
23
27
  if (fact.validFrom && fact.validFrom > at) continue;
@@ -34,8 +38,10 @@ export function createGraphEngine({ entities, facts, edges = null, traces = null
34
38
  return adjacency;
35
39
  }
36
40
 
37
- function seedWeights(query, scopeId) {
38
- const candidates = entities.list({ scopeId, limit: 500 });
41
+ // 2026-12-05 助手:可选传入已取好的实体表 —— search() 里原来为了 seed 和 entityMap
42
+ // 各扫一次 500 条(CPU profile 里 entities.list 占 11.4%),实际同一份数据用两次。
43
+ function seedWeights(query, scopeId, preloaded = null) {
44
+ const candidates = preloaded ?? entities.list({ scopeId, limit: 500 });
39
45
  const weights = new Map();
40
46
  const text = String(query ?? '');
41
47
  const lower = text.toLowerCase().trim();
@@ -91,14 +97,25 @@ export function createGraphEngine({ entities, facts, edges = null, traces = null
91
97
  }
92
98
 
93
99
  function search(query, { scopeId = 'global', limit = 10, at = nowIso() } = {}) {
94
- const seeds = seedWeights(query, scopeId);
100
+ // 2026-12-05 夜:算种子权重只需要 name/aliases(briefList),完整行只给排在前面的那些(getMany)。
101
+ // 老仓库没有这两个方法时退回原来的全量 list。
102
+ const briefEntities = typeof entities.briefList === 'function'
103
+ ? entities.briefList({ scopeId, limit: 500 })
104
+ : entities.list({ scopeId, limit: 500 });
105
+ const seeds = seedWeights(query, scopeId, briefEntities);
95
106
  if (seeds.size === 0) return { query, seeds: [], entities: [], facts: [], traces: [], at };
96
- const adjacency = loadAdjacency(scopeId, at);
107
+ // 2026-12-06 助手:同一份 500 条事实,建邻接和 factResults 各读一次 → 改成一读两用。
108
+ const allFacts = typeof facts.briefList === 'function'
109
+ ? facts.briefList({ scopeId, limit: 500 })
110
+ : facts.list({ scopeId, limit: 500 });
111
+ const adjacency = loadAdjacency(scopeId, at, allFacts);
97
112
  const ranked = ppr(adjacency, seeds).slice(0, Math.max(1, Math.min(50, limit)));
98
- const entityMap = new Map(entities.list({ scopeId, limit: 500 }).map((item) => [item.id, item]));
113
+ const entityMap = typeof entities.getMany === 'function'
114
+ ? entities.getMany(ranked.map((item) => item.id))
115
+ : new Map(briefEntities.map((item) => [item.id, item]));
99
116
  const entityResults = ranked.map((item) => ({ ...item, entity: entityMap.get(item.id) ?? null })).filter((item) => item.entity);
100
117
  const top = new Set([...seeds.keys(), ...entityResults.map((item) => item.id)]);
101
- const factResults = facts.list({ scopeId, limit: 500 })
118
+ const factResults = allFacts
102
119
  .filter((fact) => fact.status !== 'invalidated')
103
120
  .filter((fact) => top.has(fact.subjectId) || top.has(fact.objectId))
104
121
  .map((fact) => {
@@ -122,11 +122,30 @@ export function createHealthEngine({
122
122
  at: dream.at,
123
123
  status: dream.status,
124
124
  error: dream.error ?? null,
125
- decisions: (() => { try { return JSON.parse(dream.decisions_json ?? '[]').length; } catch { return 0; } })(),
125
+ // 2026-12-06 助手(寒复核 D1):dream_runs 超龄后会被压成摘要对象
126
+ // {"n":N,"byAction":{...},"applied":M},不再是数组。这里两种形状都要认,
127
+ // 否则摘要行会让 length 变成 undefined、filter 抛错被 catch 吞掉(静默错数据)。
128
+ decisions: (() => {
129
+ try {
130
+ const x = JSON.parse(dream.decisions_json ?? '[]');
131
+ return Array.isArray(x) ? x.length : Number(x?.n ?? 0);
132
+ } catch { return 0; }
133
+ })(),
126
134
  // `status: applied` with every decision `keep` and `applied: 0` is a
127
135
  // no-op, not a consolidation. Keep the count so a reader can tell.
128
- keep: (() => { try { return JSON.parse(dream.decisions_json ?? '[]').filter((item) => item?.action === 'keep').length; } catch { return 0; } })(),
129
- applied: (() => { try { return JSON.parse(dream.applied_json ?? '[]').length; } catch { return 0; } })(),
136
+ keep: (() => {
137
+ try {
138
+ const x = JSON.parse(dream.decisions_json ?? '[]');
139
+ if (Array.isArray(x)) return x.filter((item) => item?.action === 'keep').length;
140
+ return Number(x?.byAction?.keep ?? 0);
141
+ } catch { return 0; }
142
+ })(),
143
+ applied: (() => {
144
+ try {
145
+ const x = JSON.parse(dream.applied_json ?? '[]');
146
+ return Array.isArray(x) ? x.length : Number(x?.n ?? 0);
147
+ } catch { return 0; }
148
+ })(),
130
149
  } : null,
131
150
  sleep: sleep ? {
132
151
  at: sleep.at,
@@ -7,9 +7,13 @@ import { suggestSkillsFromTraces } from './skills.js';
7
7
  export function induceSkills({ traces, skills, scopeId = 'global', minSupport = 3, limit = 3 } = {}) {
8
8
  if (!traces || !skills) throw new Error('skill induction needs traces and skills');
9
9
  const recent = traces.list({ scopeId, state: 'active', limit: 300 });
10
- const suggestions = suggestSkillsFromTraces(recent, { minSupport, max: limit });
10
+ // 2026-12-05 夜:原来是「先截断(limit)再去重」—— 排在前面的往往是**已存在**的技能,
11
+ // 于是新技能永远轮不到(实测:5 条建议里前 3 条都已存在,新建 0 条)。
12
+ // 改成多取候选,去重后再数满 limit 个才停。
13
+ const suggestions = suggestSkillsFromTraces(recent, { minSupport, max: Math.max(limit * 4, limit) });
11
14
  const created = [];
12
15
  for (const suggestion of suggestions) {
16
+ if (created.length >= limit) break;
13
17
  const existing = skills.findByName(scopeId, suggestion.name);
14
18
  if (existing) continue;
15
19
  const skill = skills.create({
@@ -0,0 +1,180 @@
1
+ // 冻结的线性重排模型(100→20,hard+holdout 训练,pairwise L2=0.03)
2
+ // 由 审计/lab/rerank-model-100.json 生成;不要手改。
3
+ export const LINEAR_RERANK_MODEL = {
4
+ "features": [
5
+ "fusionNorm",
6
+ "match",
7
+ "importance",
8
+ "confidence",
9
+ "sourceCount",
10
+ "ftsInv",
11
+ "softFtsInv",
12
+ "vectorInv",
13
+ "graphInv",
14
+ "recentInv",
15
+ "expandInv",
16
+ "hasFts",
17
+ "hasVector",
18
+ "hasGraph",
19
+ "hasRecent",
20
+ "hasExpand",
21
+ "queryCoverage",
22
+ "sharedTokens",
23
+ "logTitle",
24
+ "logText",
25
+ "logDays",
26
+ "retired",
27
+ "attachments",
28
+ "kind_utterance",
29
+ "kind_decision",
30
+ "kind_reflection",
31
+ "kind_observation",
32
+ "kind_promise",
33
+ "kind_preference",
34
+ "kind_identity",
35
+ "kind_other",
36
+ "author_self",
37
+ "author_captured",
38
+ "author_imported",
39
+ "author_derived",
40
+ "author_subbrain",
41
+ "author_other",
42
+ "layer_L0",
43
+ "layer_L2",
44
+ "layer_L5"
45
+ ],
46
+ "weights": [
47
+ 0.6546952973088342,
48
+ 0.09744623511663755,
49
+ -0.052319233104124105,
50
+ -0.09619344562549201,
51
+ 0.3167612113982056,
52
+ 0.21193857784055783,
53
+ 0,
54
+ 0.3619321765688432,
55
+ -0.06811654194958869,
56
+ -0.12467699307216994,
57
+ 0.04845362753243863,
58
+ 0.07944137395158012,
59
+ 0.11713697387945145,
60
+ -0.08502657408191701,
61
+ 0.042117905529216584,
62
+ 0.16454456217431238,
63
+ 0.09212223917440632,
64
+ 0.09212223917440622,
65
+ -0.16109605664845847,
66
+ -0.4499884592640321,
67
+ -0.2614481813968271,
68
+ 0.032181478215699076,
69
+ 0,
70
+ -0.0382781605697604,
71
+ 0.047082917757471233,
72
+ 0.04124693191513831,
73
+ 0.042226588951023054,
74
+ -0.09437723025138521,
75
+ -0.08035249884058347,
76
+ -0.00011910811490735017,
77
+ 0,
78
+ 0.14629014117225228,
79
+ -0.13547950192521221,
80
+ -0.05048158128129357,
81
+ -0.019194467005957092,
82
+ 0,
83
+ 0,
84
+ -0.00011910811490735017,
85
+ -0.04130432040282256,
86
+ 0.04124693191513831
87
+ ],
88
+ "mean": [
89
+ 1.3250858743596438e-16,
90
+ 4.923561558456413e-16,
91
+ -5.176525874617255e-15,
92
+ 2.519262576328174e-15,
93
+ -2.5424107263916086e-17,
94
+ 2.0920765120280294e-17,
95
+ 0,
96
+ 1.4136261605735e-16,
97
+ -1.63202784619898e-17,
98
+ 7.702172233337024e-18,
99
+ 8.049116928532384e-18,
100
+ 2.2593038551121934e-17,
101
+ -3.314015728506092e-17,
102
+ -2.0886070650760756e-17,
103
+ -6.6474603599431245e-18,
104
+ 4.107825191113079e-18,
105
+ 5.363209876207975e-16,
106
+ 1.509903313490213e-17,
107
+ -5.113409695667314e-16,
108
+ 1.0877965195277284e-15,
109
+ -2.0429491431883662e-16,
110
+ 1.9675233664528947e-17,
111
+ 0,
112
+ 4.718447854656916e-18,
113
+ -4.340972026284362e-17,
114
+ -2.4549806632023773e-17,
115
+ -1.511984981661385e-17,
116
+ -6.203371150093062e-18,
117
+ 2.0559942637277118e-17,
118
+ 3.2439329000766295e-18,
119
+ 0,
120
+ -1.5237811012980275e-17,
121
+ 7.216449660063518e-18,
122
+ 1.4654943925052067e-17,
123
+ 5.759281940243e-19,
124
+ 0,
125
+ 0,
126
+ 3.2439329000766295e-18,
127
+ 1.5404344466674048e-17,
128
+ -2.4549806632023773e-17
129
+ ],
130
+ "std": [
131
+ 1.0000000000000009,
132
+ 1.0000000000000053,
133
+ 0.9999999999999998,
134
+ 0.9999999999999893,
135
+ 0.9999999999999952,
136
+ 0.9999999999999928,
137
+ 1,
138
+ 1.0000000000000009,
139
+ 0.9082951062292459,
140
+ 0.9999999999999984,
141
+ 0.4183300132670381,
142
+ 1.000000000000014,
143
+ 1.000000000000002,
144
+ 0.9082951062292648,
145
+ 1.0000000000000007,
146
+ 0.41833001326703806,
147
+ 1.0000000000000044,
148
+ 1.0000000000000047,
149
+ 1.0000000000000027,
150
+ 1.0000000000000002,
151
+ 1.0000000000000018,
152
+ 0.6614378277661578,
153
+ 1,
154
+ 1.0000000000000102,
155
+ 1.0000000000000016,
156
+ 1.0000000000000004,
157
+ 0.993730345717596,
158
+ 0.9999999999999913,
159
+ 0.9874208829065653,
160
+ 0.24999999999999833,
161
+ 1,
162
+ 1.000000000000008,
163
+ 1.0000000000000062,
164
+ 0.5809475019311141,
165
+ 0.1936491673103706,
166
+ 1,
167
+ 1,
168
+ 0.24999999999999833,
169
+ 1.0000000000000027,
170
+ 1.0000000000000004
171
+ ],
172
+ "version": 1,
173
+ "train_suites": [
174
+ "hard",
175
+ "holdout"
176
+ ],
177
+ "candidate_limit": 100,
178
+ "l2": 0.03,
179
+ "normalization": "per-query z-score across 100 candidates, then train mean/std"
180
+ };
@@ -0,0 +1,110 @@
1
+ // 线性重排:候选级特征 + 冻结模型。
2
+ // 训练数据生成:审计/lab/rerank-dataset-100.mjs;融合权重复用 source-weights.js。
3
+ // 训练口径:审计/lab/rerank-dataset-100.mjs(每查询内 z-score,再按训练 mean/std 标准化)。
4
+ import { LINEAR_RERANK_MODEL as MODEL } from './linear-rerank-model.js';
5
+ import { SOURCE_WEIGHT } from './source-weights.js';
6
+
7
+ const K = 20;
8
+ const KINDS = ['utterance', 'decision', 'reflection', 'observation', 'promise', 'preference', 'identity', 'other'];
9
+ // 模型只建模这 8 类;milestone/lesson/instruction/task 与训练时一样落到全 0 one-hot。
10
+ // 这不是数据丢类,而是模型 features 本来只有 8 个 kind 槽位。
11
+ const AUTHORS = ['self', 'captured', 'imported', 'derived', 'subbrain', 'other'];
12
+ const LAYERS = ['L0', 'L2', 'L5'];
13
+
14
+ function inv(rank) {
15
+ const r = Number(rank) || 0;
16
+ return r > 0 ? 1 / (1 + r) : 0;
17
+ }
18
+ function finite(value, fallback = 0) {
19
+ const n = Number(value);
20
+ return Number.isFinite(n) ? n : fallback;
21
+ }
22
+ function log1p(value) {
23
+ return Math.log1p(Math.max(0, finite(value)));
24
+ }
25
+ function rawFusion(candidate) {
26
+ let sum = 0;
27
+ for (const source of candidate.sources ?? []) {
28
+ const weight = finite(source.weight ?? SOURCE_WEIGHT[source.name] ?? 1, 1);
29
+ const rank = finite(source.rank);
30
+ if (rank > 0) sum += weight / (K + rank);
31
+ }
32
+ return sum;
33
+ }
34
+
35
+ function features(candidate, queryTokens, maxFusion, now) {
36
+ const sources = candidate.sources ?? [];
37
+ const byName = {};
38
+ for (const source of sources) byName[source.name] = finite(source.rank);
39
+ const trace = candidate.trace ?? {};
40
+ const text = String(candidate.text ?? '');
41
+ const title = String(trace.title ?? candidate.title ?? '');
42
+ const textTokens = candidate.tokenSet ?? new Set();
43
+ let shared = 0;
44
+ for (const token of queryTokens ?? []) if (textTokens.has(token)) shared += 1;
45
+ const recordedAt = trace.recordedAt ?? candidate.recordedAt;
46
+ const recorded = recordedAt ? Date.parse(recordedAt) : NaN;
47
+ const daysOld = Number.isFinite(recorded) ? Math.max(0, (now - recorded) / 86_400_000) : 999;
48
+ const kind = String(trace.kind ?? candidate.kind ?? 'unknown');
49
+ const author = String(trace.authorKind ?? 'other');
50
+ const layer = String(candidate.layer ?? 'L2');
51
+ const out = {
52
+ fusionNorm: maxFusion > 0 ? rawFusion(candidate) / maxFusion : 0,
53
+ match: finite(candidate.match),
54
+ importance: finite(candidate.importance),
55
+ confidence: finite(candidate.confidence),
56
+ sourceCount: sources.length,
57
+ ftsInv: inv(byName.fts),
58
+ softFtsInv: inv(byName['fts-soft']),
59
+ vectorInv: inv(byName.vector),
60
+ graphInv: inv(byName.graph),
61
+ recentInv: inv(byName.recent),
62
+ expandInv: inv(byName.expand),
63
+ hasFts: byName.fts ? 1 : 0,
64
+ hasVector: byName.vector ? 1 : 0,
65
+ hasGraph: byName.graph ? 1 : 0,
66
+ hasRecent: byName.recent ? 1 : 0,
67
+ hasExpand: byName.expand ? 1 : 0,
68
+ queryCoverage: queryTokens && queryTokens.size ? shared / queryTokens.size : 0,
69
+ sharedTokens: shared,
70
+ logTitle: log1p(title.length),
71
+ logText: log1p(text.length),
72
+ logDays: log1p(daysOld),
73
+ retired: candidate.retired ? 1 : 0,
74
+ attachments: finite(candidate.attachments),
75
+ };
76
+ for (const k of KINDS) out[`kind_${k}`] = kind === k ? 1 : 0;
77
+ for (const a of AUTHORS) out[`author_${a}`] = author === a ? 1 : 0;
78
+ for (const l of LAYERS) out[`layer_${l}`] = layer === l ? 1 : 0;
79
+ return out;
80
+ }
81
+
82
+ export function linearRerank(candidates, queryTokens, { maxFusion = null, now = Date.now() } = {}) {
83
+ if (!Array.isArray(candidates) || candidates.length < 2) return candidates;
84
+ const max = maxFusion ?? Math.max(1e-9, ...candidates.map(rawFusion));
85
+ const names = MODEL.features;
86
+ const rows = candidates.map((candidate) => features(candidate, queryTokens, max, now));
87
+ // 每查询内 z-score(与训练脚本一致)
88
+ const rawMean = new Array(names.length).fill(0);
89
+ const rawStd = new Array(names.length).fill(0);
90
+ for (let j = 0; j < names.length; j += 1) {
91
+ const values = rows.map((row) => Number(row[names[j]]) || 0);
92
+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
93
+ const variance = values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length;
94
+ rawMean[j] = mean;
95
+ rawStd[j] = Math.sqrt(variance);
96
+ }
97
+ const scored = candidates.map((candidate, index) => {
98
+ let score = 0;
99
+ for (let j = 0; j < names.length; j += 1) {
100
+ const raw = finite(rows[index][names[j]]);
101
+ const z = rawStd[j] > 1e-9 ? (raw - rawMean[j]) / rawStd[j] : 0;
102
+ const std = finite(MODEL.std[j], 1) || 1;
103
+ const weight = finite(MODEL.weights[j]);
104
+ score += ((z - finite(MODEL.mean[j])) / (std > 1e-9 ? std : 1)) * weight;
105
+ }
106
+ return { candidate, score: Number.isFinite(score) ? score : 0, index };
107
+ });
108
+ scored.sort((a, b) => b.score - a.score || a.index - b.index);
109
+ return scored.map((row) => row.candidate);
110
+ }
@@ -0,0 +1,61 @@
1
+ // 查询扩展词表(2026-12-06 · 路线 A 手写版)
2
+ //
3
+ // 只写「人话 → 库里真出现过的说法」,每条规则都必须能指回一条真实记忆,
4
+ // 不是通用同义词库。命中规则后,每个 variant 单独做一次 FTS(不是拼成长查询):
5
+ // 拼长查询会被 24 个 bigram 的 OR 稀释,实测 key-vault 从第 5 掉到第 18。
6
+ //
7
+ // 维护约定:
8
+ // - 新增一条,先看审计\lab 里那次实验的漏召回原文(触发词必须真的在原文里出现过)
9
+ // - variant 越具体越好;通用词(模板/人设/上线)会被检索层的特异性闸门挡掉
10
+ // - 规则按序匹配,同一查询命中多条规则时合并去重,最多取前 MAX_VARIANTS 个
11
+
12
+ const MAX_VARIANTS = 8;
13
+
14
+ export const QUERY_EXPANSIONS = Object.freeze([
15
+ {
16
+ re: /密钥|凭据|key.?vault/i,
17
+ variants: ['key-vault', 'keyvault', '密钥库', '凭据', 'credential', 'isTrusted'],
18
+ note: '「密钥保管」那条实际记在 key-vault 名下(trace_ref)',
19
+ },
20
+ {
21
+ re: /内部状态|驱力|驱动力|激素|多巴胺|皮质醇|状态描述/,
22
+ variants: ['驱动力', '激素', '多巴胺', '皮质醇', '状态描述', '喂给模型', '提示词'],
23
+ note: '「内部状态有没有影响输出」原文写成 驱动力/激素/多巴胺/喂给模型(trace_ref)',
24
+ },
25
+ {
26
+ re: /渠道|发包|发布|npm|github|一键包/i,
27
+ variants: ['npm', 'GitHub', '一键包', 'oneclick', 'release', 'zip', '三渠道'],
28
+ note: '发版三渠道 = npm / GitHub release / 一键包 zip(trace_ref)',
29
+ },
30
+ {
31
+ re: /体检|审计|僵尸|过期/,
32
+ variants: ['cortex_audit', 'healthcheck'],
33
+ note: '「全面体检」在工具名里是 cortex_audit / healthcheck;僵尸/过期 这类词查询里通常自带,不再作为变体(trace_ref)',
34
+ },
35
+ {
36
+ re: /经验库|破妄|powang|经验桥|工程经验/,
37
+ variants: ['powang', '破妄', '经验桥', 'cortex_import_powang', '导入'],
38
+ note: '「两边的经验库」= powang 破妄 ↔ cortex,桥工具叫 cortex_import_powang(trace_ref)',
39
+ },
40
+ {
41
+ re: /人格模板|人设|货架|给外人/,
42
+ variants: ['货架', '外人', '产品', '人设', '模板', '商品'],
43
+ note: '「人格模板是商品」原文写 产品/货架/给外人看(trace_ref;该痕迹已归档,本规则未被探针验证)',
44
+ },
45
+ {
46
+ re: /重启|装完/,
47
+ variants: ['重启', '验证', '上线', '生效', 'cortex_audit', 'cortex_intention'],
48
+ note: '「重启后两个工具能用了」原文写 上线/生效/cortex_audit/cortex_intention(trace_ref)',
49
+ },
50
+ ]);
51
+
52
+ export function expansionVariants(query) {
53
+ const value = String(query ?? '');
54
+ if (!value) return [];
55
+ const out = [];
56
+ for (const rule of QUERY_EXPANSIONS) {
57
+ if (!rule.re.test(value)) continue;
58
+ for (const variant of rule.variants) out.push(variant);
59
+ }
60
+ return [...new Set(out)].filter(Boolean).slice(0, MAX_VARIANTS);
61
+ }
@@ -16,7 +16,10 @@ export function createRetentionEngine({ traces } = {}) {
16
16
  const overCount = index >= Math.max(0, maxTraces);
17
17
  const overAge = ageDays > maxAgeDays;
18
18
  const lowValue = Number(trace.importance) < minImportance && Number(trace.confidence) < 0.75;
19
- if ((overCount || overAge) && lowValue && trace.kind !== 'reflection') {
19
+ // 2026-12-05 夜(砚/允复核指出):钉住的记忆不许被留存淘汰。
20
+ // 这里原来完全不看 protected,导致 cortex_protect 的承诺「留存淘汰也不会动它」是假的。
21
+ const pinned = Number(trace.protected ?? 0) === 1;
22
+ if ((overCount || overAge) && lowValue && trace.kind !== 'reflection' && !pinned) {
20
23
  candidates.push({ id: trace.id, ageDays, importance: trace.importance, confidence: trace.confidence, reason: overCount ? 'over-count' : 'over-age' });
21
24
  if (candidates.length >= Math.max(1, Math.min(2000, limit))) break;
22
25
  }