dsh-cortex-memory 0.4.147 → 0.4.148

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 CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.148 — 2026-11-20
4
+
5
+ A governance self-test, retired-trace recall, and an importance score with a low tail.
6
+
7
+ ### Added
8
+ - **`bench/governance.mjs`**: a read-only governance self-test. 30 synthetic facts,
9
+ 10 overwrites, two passes; prints write-to-recall p50/p95, retired-fact count,
10
+ stale hits and clean recall@1. It builds a throwaway temp DB and refuses to run
11
+ against a real store (the db path must be under the OS temp dir, else exit 2).
12
+ CI runs it after the test suite, so the published table is reproducible with
13
+ one command: `node bench/governance.mjs`.
14
+ - **Memory policy layer** (`src/self/memory-policy.js`): how memory flows is now a
15
+ policy row (kind `memory`) — propose → approve → rollback, every step audited.
16
+ `evergreenKinds` never auto-archive, and consolidation cadence reads the policy.
17
+ - **Retired traces are not recalled by default**: a trace whose fact was
18
+ superseded is skipped (and counted as `retiredSkipped`); `includeRetired: true`
19
+ keeps it for audit, ranked below the live memory.
20
+
21
+ ### Changed
22
+ - **Importance keeps a low tail** (public edition): the score starts at 0.26
23
+ instead of 0.42 with smaller boosts, so compression has something to archive.
24
+
25
+ ### Verified
26
+ - Unit: 523/523.
27
+ - Integration: 126/126.
28
+ - Governance bench: retired 10/10, stale hits 0/10, write-to-recall p50 ~0.01s.
29
+
3
30
  ## 0.4.147 — 2026-11-19
4
31
 
5
32
  Second privacy pass: real-life wording out of the public text, a neutral icon and a smaller tarball.
package/README.md CHANGED
@@ -7,11 +7,11 @@
7
7
  ## 当前版本
8
8
 
9
9
  ```text
10
- 主包:dsh-cortex-memory@0.4.147
10
+ 主包:dsh-cortex-memory@0.4.148
11
11
  提取器:dsh-cortex-extractors@0.3.5
12
12
  DSH:>=0.2.1-rc.2 <0.5.0
13
13
  Node:>=24
14
- 测试:520/520
14
+ 测试:523/523
15
15
  ```
16
16
 
17
17
  ## 现在能做什么
@@ -34,7 +34,7 @@ Node:>=24
34
34
  先关闭 DSH,再安装并重启:
35
35
 
36
36
  ```powershell
37
- dsh plugin --profile desktop add dsh-cortex-memory@0.4.147
37
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.148
38
38
  dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
39
39
  ```
40
40
 
@@ -45,7 +45,7 @@ dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
45
45
  GitHub Release 提供:
46
46
 
47
47
  ```text
48
- cortex-memory-oneclick-0.4.147.zip
48
+ cortex-memory-oneclick-0.4.148.zip
49
49
  ```
50
50
 
51
51
  解压后双击 `install.cmd`。安装器会做 profile 检查、备份、SHA256 校验和可选路径迁移。
@@ -75,8 +75,6 @@ PaddleOCR 需显式模型目录
75
75
 
76
76
  必须使用 DSH 自带的 **Node 24** 跑测试/bench。系统 PATH 上如果是 Node 22,会低于 `engines.node >=24`,`node --test` 可能直接失败。
77
77
 
78
- npm 包里不包含 `test/`(从 0.4.147 起):测试在 GitHub 仓库与 CI 里跑,包体更小、审计面更窄。
79
-
80
78
  ```text
81
79
  DSH 运行时 Node:24.21.0
82
80
  系统 Node:仅作兼容性参考,不保证
@@ -89,7 +87,7 @@ CLI 默认读取 `~/.dsh/cortex-memory`;需要指定其他库时显式传 `--d
89
87
  已做:
90
88
 
91
89
  ```text
92
- 主包测试:520/520
90
+ 主包测试:523/523
93
91
  受控中文语义探针:recall@3 1.000 / MRR@3 0.917 / nDCG@3 0.938
94
92
  受控探针延迟:p50 1.31ms / p95 4.07ms
95
93
  真实图片 OCR:已跑通
@@ -127,9 +125,9 @@ Cortex 的定位是“本地可解释、可回滚、能长期长”的记忆系
127
125
 
128
126
  ## 下载
129
127
 
130
- - npm 主包:`dsh-cortex-memory@0.4.147`
128
+ - npm 主包:`dsh-cortex-memory@0.4.148`
131
129
  - npm 提取器:`dsh-cortex-extractors@0.3.5`
132
- - GitHub Release:`v0.4.147`
133
- - Windows 一键包:`cortex-memory-oneclick-0.4.147.zip`
130
+ - GitHub Release:`v0.4.148`
131
+ - Windows 一键包:`cortex-memory-oneclick-0.4.148.zip`
134
132
 
135
133
  安装后重启 DSH,左侧出现「Cortex 记忆」入口。
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 记忆治理自测(governance bench)
4
+ *
5
+ * 协议对齐 KrabArena 的 write-to-recall / overwrite 测法,只测「库的行为」,不测 LLM 作答。
6
+ * 产出三个数字:
7
+ * 1. 写后可召回 p50 / p95 —— 写完到这条事实能被召回要多久
8
+ * 2. 旧值退役 —— 覆盖后当前事实还是不是旧值
9
+ * 3. 干净召回 @1 —— 没被覆盖的事实 top1 对不对
10
+ *
11
+ * 安全边界(写死):
12
+ * - 在系统临时目录里建一个全新库,绝不打开真实记忆库
13
+ * - dbFile 不在临时目录 -> 直接 exit 2 拒跑
14
+ * - 数据全部是合成事实,不含任何真实记忆
15
+ *
16
+ * 用法:
17
+ * node bench/governance.mjs --passes 2 --topk 5
18
+ * node bench/governance.mjs --out results/governance-20261119
19
+ */
20
+ import { mkdtempSync, rmSync, statSync } from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { performance } from 'node:perf_hooks';
24
+ import { createCortex } from '../src/service/cortex.js';
25
+
26
+ const argv = process.argv.slice(2);
27
+ const arg = (name, dflt) => {
28
+ const i = argv.indexOf(`--${name}`);
29
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : dflt;
30
+ };
31
+ const PASSES = Math.max(1, Number(arg('passes', 2)));
32
+ const TOPK = Math.max(1, Number(arg('topk', 5)));
33
+ const CAP_MS = Math.max(1000, Number(arg('cap', 60000)));
34
+ const OUT = arg('out', '');
35
+
36
+ // ---- 红线:只在临时目录建库 ----
37
+ const tmpRoot = path.resolve(os.tmpdir());
38
+ const dir = mkdtempSync(path.join(tmpRoot, 'cortex-governance-'));
39
+ const dbFile = path.join(dir, 'cortex.sqlite');
40
+ if (!path.resolve(dbFile).startsWith(tmpRoot + path.sep)) {
41
+ console.error(`拒绝执行:dbFile 不在临时目录(${dbFile})`);
42
+ process.exit(2);
43
+ }
44
+
45
+ // ---- 合成数据:10 人 × 3 字段 = 30 条;前 10 条(job)做覆盖 ----
46
+ const SUBJECTS = ['林舟', '周野', '阿柚', '陈默', '小满', '顾辰', '苏禾', '程一', '夜白', '何夕'];
47
+ const FIELDS = [
48
+ { predicate: 'job', question: '现在做什么工作', values: ['大二学生', '在读研究生', '自由插画师', '产品实习生', '咖啡店主'] },
49
+ { predicate: 'city', question: '现在住在哪个城市', values: ['杭州', '成都', '广州', '南京', '西安'] },
50
+ { predicate: 'pet', question: '养了什么宠物', values: ['两只英短', '一只柯基', '没有宠物', '三只仓鼠', '一只布偶'] },
51
+ ];
52
+
53
+ const FACTS = [];
54
+ for (let i = 0; i < 30; i++) {
55
+ const subject = SUBJECTS[i % SUBJECTS.length];
56
+ const field = FIELDS[i % FIELDS.length];
57
+ const value = field.values[Math.floor(i / 10) % field.values.length];
58
+ FACTS.push({
59
+ id: `f${String(i + 1).padStart(2, '0')}`,
60
+ subject,
61
+ predicate: field.predicate,
62
+ question: field.question,
63
+ probe: `${subject}${field.question}`,
64
+ value,
65
+ text: `${subject}${field.question}:${value}`,
66
+ });
67
+ }
68
+
69
+ // 覆盖:只动前 10 条(10 个人的 job),每轮轮换到下一个值
70
+ const OVERWRITE_IDS = new Set(FACTS.slice(0, 10).map((f) => f.id));
71
+ const valueAt = (fact, offset) => {
72
+ const field = FIELDS.find((f) => f.predicate === fact.predicate);
73
+ const base = field.values.indexOf(fact.value);
74
+ return field.values[(base + offset) % field.values.length];
75
+ };
76
+
77
+ // ---- 工具 ----
78
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
79
+ const median = (xs) => {
80
+ const a = [...xs].sort((x, y) => x - y);
81
+ if (!a.length) return null;
82
+ const m = a.length >> 1;
83
+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
84
+ };
85
+ const p95 = (xs) => {
86
+ const a = [...xs].sort((x, y) => x - y);
87
+ return a.length ? a[Math.min(a.length - 1, Math.ceil(a.length * 0.95) - 1)] : null;
88
+ };
89
+ const round3 = (x) => (x === null || x === undefined || !Number.isFinite(x) ? null : Math.round(x * 1000) / 1000);
90
+
91
+ function itemText(item) {
92
+ return [item.content, item.snippet, item.title, item.text].filter(Boolean).join(' ');
93
+ }
94
+ function hitValue(items, value) {
95
+ return items.some((item) => itemText(item).includes(value));
96
+ }
97
+ // 旧值残留只认「同一个人、同一个问题」下的旧答案:同字段的值会在不同人之间
98
+ // 重复,纯文本匹配会把别人的记录误算成残留。
99
+ function hitRetired(items, fact, oldValue) {
100
+ const prefix = `${fact.subject}${fact.question}:`;
101
+ return items.some((item) => {
102
+ const text = itemText(item);
103
+ return text.includes(prefix) && text.includes(oldValue);
104
+ });
105
+ }
106
+ function topValue(items) {
107
+ return items.length ? itemText(items[0]) : '';
108
+ }
109
+
110
+ function currentFact(cortex, subject, predicate) {
111
+ // asOf 返回 { subject, mode, facts: [...] },facts 里当前值字段叫 object
112
+ const result = cortex.asOf({ subject, predicate, mode: 'strict', scopeId: 'global' });
113
+ const rows = result?.facts ?? [];
114
+ return rows.length ? (rows[0].object ?? null) : null;
115
+ }
116
+
117
+ function search(cortex, query) {
118
+ return cortex.search(query, { limit: TOPK, scopeId: 'global' })?.items ?? [];
119
+ }
120
+
121
+ function writeFact(cortex, { subject, predicate, objectLiteral, text, operationId }) {
122
+ return cortex.write({
123
+ text,
124
+ kind: 'observation',
125
+ explicit: true,
126
+ importance: 0.7,
127
+ scopeId: 'global',
128
+ facts: [{ subject, predicate, objectLiteral, confidence: 0.9 }],
129
+ operationId,
130
+ });
131
+ }
132
+
133
+ async function runPass(cortex, passNo) {
134
+ // 阶段 1:写后到可召回
135
+ const lags = [];
136
+ const misses = [];
137
+ for (const fact of FACTS) {
138
+ const t0 = performance.now();
139
+ writeFact(cortex, {
140
+ subject: fact.subject,
141
+ predicate: fact.predicate,
142
+ objectLiteral: valueAt(fact, passNo - 1),
143
+ text: `${fact.subject}${fact.question}:${valueAt(fact, passNo - 1)}`,
144
+ operationId: `gov:p${passNo}:${fact.id}`,
145
+ });
146
+ let landed = false;
147
+ while (performance.now() - t0 < CAP_MS) {
148
+ if (hitValue(search(cortex, fact.probe), valueAt(fact, passNo - 1))) { landed = true; break; }
149
+ await sleep(20);
150
+ }
151
+ lags.push(landed ? performance.now() - t0 : CAP_MS);
152
+ if (!landed) misses.push(fact.id);
153
+ }
154
+
155
+ // 阶段 2:干净召回(没被覆盖的 20 条)
156
+ let cleanOk = 0;
157
+ for (const fact of FACTS.filter((f) => !OVERWRITE_IDS.has(f.id))) {
158
+ const items = search(cortex, fact.probe);
159
+ if (topValue(items).includes(valueAt(fact, passNo - 1))) cleanOk += 1;
160
+ }
161
+
162
+ // 阶段 3:覆盖 —— 同 subject+predicate 写新值,看旧值退不退役
163
+ let retired = 0;
164
+ let staleFact = 0;
165
+ let staleHits = 0;
166
+ const oldValues = [];
167
+ for (const fact of FACTS.filter((f) => OVERWRITE_IDS.has(f.id))) {
168
+ const oldValue = valueAt(fact, passNo - 1);
169
+ const newValue = valueAt(fact, passNo);
170
+ oldValues.push(oldValue);
171
+ writeFact(cortex, {
172
+ subject: fact.subject,
173
+ predicate: fact.predicate,
174
+ objectLiteral: newValue,
175
+ text: `${fact.subject}${fact.question}:${newValue}`,
176
+ operationId: `gov:ov:p${passNo}:${fact.id}`,
177
+ });
178
+ const now = currentFact(cortex, fact.subject, fact.predicate);
179
+ if (now === newValue) retired += 1;
180
+ if (now === oldValue) staleFact += 1;
181
+ if (hitRetired(search(cortex, fact.probe), fact, oldValue)) staleHits += 1;
182
+ }
183
+
184
+ const size = (() => {
185
+ try { return statSync(dbFile).size; } catch { return null; }
186
+ })();
187
+
188
+ return {
189
+ pass: passNo,
190
+ lagP50s: round3(median(lags) / 1000),
191
+ lagP95s: round3(p95(lags) / 1000),
192
+ timeouts: misses.length,
193
+ timeoutIds: misses,
194
+ cleanRecallAt1: round3(cleanOk / 20),
195
+ factRetired: `${retired}/10`,
196
+ factStale: `${staleFact}/10`,
197
+ staleHits: `${staleHits}/10`,
198
+ storeBytes: size,
199
+ traceCount: cortex.repos.traces.count(),
200
+ factActive: cortex.repos.facts.list({ scopeId: 'global', status: 'active', limit: 1000 }).length,
201
+ };
202
+ }
203
+
204
+ // ---- 主流程 ----
205
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile } });
206
+ const rows = [];
207
+ try {
208
+ console.log(`governance bench | facts=${FACTS.length} overwrites=10 passes=${PASSES} topk=${TOPK} cap=${CAP_MS / 1000}s`);
209
+ for (let p = 1; p <= PASSES; p++) {
210
+ const r = await runPass(cortex, p);
211
+ rows.push(r);
212
+ console.log(` pass${p}: p50=${r.lagP50s}s p95=${r.lagP95s}s clean@1=${r.cleanRecallAt1} retired=${r.factRetired} stale=${r.factStale} staleHits=${r.staleHits} rows=${r.factActive} active`);
213
+ }
214
+ } finally {
215
+ cortex.close();
216
+ rmSync(dir, { recursive: true, force: true });
217
+ }
218
+
219
+ const agg = (k) => {
220
+ const xs = rows.map((r) => r[k]).filter((x) => typeof x === 'number');
221
+ return xs.length ? round3(median(xs)) : null;
222
+ };
223
+ const fmt = (x) => (x === null || x === undefined ? 'n/a' : String(x));
224
+
225
+ const report = {
226
+ bench: 'governance',
227
+ engine: 'dsh-cortex',
228
+ generatedAt: new Date().toISOString(),
229
+ protocol: { facts: FACTS.length, overwrites: 10, passes: PASSES, topk: TOPK, capMs: CAP_MS },
230
+ passes: rows,
231
+ median: {
232
+ lagP50s: agg('lagP50s'),
233
+ lagP95s: agg('lagP95s'),
234
+ cleanRecallAt1: agg('cleanRecallAt1'),
235
+ storeBytes: agg('storeBytes'),
236
+ },
237
+ note: '只测库的治理行为(写入可见、覆盖退役、干净召回),不含 LLM 作答,不构成 LoCoMo / LongMemEval 分数。',
238
+ };
239
+
240
+ const md = [
241
+ `### governance bench — ${new Date().toISOString().slice(0, 10)}`,
242
+ '',
243
+ '| 指标 | 定义 | 结果 |',
244
+ '| --- | --- | --- |',
245
+ `| 写后可召回 p50 | 写入完成 → 该事实能被召回 | ${fmt(report.median.lagP50s)} s |`,
246
+ `| 写后可召回 p95 | 同上,p95 | ${fmt(report.median.lagP95s)} s |`,
247
+ `| 超时未召回 | 超过 ${CAP_MS / 1000}s 仍召不回的条数 | ${rows.reduce((a, r) => a + r.timeouts, 0)} / ${FACTS.length * PASSES} |`,
248
+ `| 干净召回 @1 | 未被覆盖的 20 条,top1 正确 | ${fmt(report.median.cleanRecallAt1)} |`,
249
+ `| 旧值退役 | 覆盖后当前事实 = 新值 | ${rows.map((r) => r.factRetired).join(' / ')} |`,
250
+ `| 旧值仍为当前 | 覆盖后当前事实 = 旧值 | ${rows.map((r) => r.factStale).join(' / ')} |`,
251
+ `| 旧值仍在检索 top-${TOPK} | 覆盖后旧值文本仍可检索到 | ${rows.map((r) => r.staleHits).join(' / ')} |`,
252
+ `| 活跃事实数 | active facts | ${rows.map((r) => r.factActive).join(' / ')} |`,
253
+ `| 库大小 | bytes | ${rows.map((r) => (r.storeBytes === null ? 'n/a' : r.storeBytes)).join(' / ')} |`,
254
+ '',
255
+ '> 只测库的行为,不含 LLM 作答,不构成 LoCoMo / LongMemEval 分数。',
256
+ ].join('\n');
257
+
258
+ console.log('\n' + md);
259
+ if (OUT) {
260
+ const { mkdirSync, writeFileSync } = await import('node:fs');
261
+ mkdirSync(path.dirname(OUT), { recursive: true });
262
+ writeFileSync(`${OUT}.json`, JSON.stringify(report, null, 2) + '\n', 'utf8');
263
+ writeFileSync(`${OUT}.md`, md + '\n', 'utf8');
264
+ console.log(`\nwritten: ${OUT}.json / ${OUT}.md`);
265
+ }
@@ -18,7 +18,7 @@ try {
18
18
  const texts = [];
19
19
  for (let i = 0; i < count; i += 1) {
20
20
  texts.push({
21
- text: i === 0 ? '米饭:升级后仍然应该能通过“饭”的 soft 查询找到。' : `老库迁移样本 ${i}:普通记忆内容。`,
21
+ text: i === 0 ? '米饭:升级后仍然应该能通过“米饭”的 soft 查询找到。' : `老库迁移样本 ${i}:普通记忆内容。`,
22
22
  title: `迁移样本 #${i}`,
23
23
  explicit: true,
24
24
  operationId: `migrate:${count}:${i}`,
@@ -24,13 +24,13 @@ const cortex = createCortex({
24
24
  const data = [
25
25
  ['便宜订阅', '用户喜欢便宜的音乐订阅,不买贵的套餐。'],
26
26
  ['米饭承诺', '用户答应下班带米饭,助手记得这个承诺。'],
27
- ['屏幕', '手机屏幕太亮,看着眼睛累。'],
27
+ ['屏幕', '久坐后屏幕会疼,助手提醒用户起身。'],
28
28
  ['猫粮', '家里的猫只吃鸡肉味猫粮。'],
29
29
  ['雨天', '下雨天要带伞,用户常忘记。'],
30
30
  ['周末', '周末计划去河边散步。'],
31
31
  ['米饭', '米饭要热的,不要隔夜。'],
32
32
  ['订阅', '订阅续费前先看价格。'],
33
- ['屏幕', '屏幕亮度过高时,调低一点。'],
33
+ ['屏幕', '屏幕疼时不要继续低头。'],
34
34
  ['猫', '猫晚上会在门口等。'],
35
35
  ['伞', '伞放在玄关的右边。'],
36
36
  ['散步', '散步时不看手机。'],
@@ -43,13 +43,13 @@ for (const [title, text] of data) {
43
43
  const queries = [
44
44
  ['米饭', '米饭承诺'],
45
45
  ['便宜 订阅', '便宜订阅'],
46
- ['屏幕 亮', '屏幕'],
46
+ ['屏幕 疼', '屏幕'],
47
47
  ['猫 吃 什么', '猫粮'],
48
48
  ['下雨 带伞', '雨天'],
49
49
  ['周末 散步', '周末'],
50
50
  ['米饭 热', '米饭'],
51
51
  ['订阅 价格', '订阅'],
52
- ['亮度 屏幕', '屏幕'],
52
+ ['低头 屏幕', '屏幕'],
53
53
  ['猫 晚上', '猫'],
54
54
  ['玄关 伞', '伞'],
55
55
  ['散步 手机', '散步'],
@@ -15,14 +15,14 @@ function mulberry32(seed) {
15
15
  };
16
16
  }
17
17
 
18
- const PLACES = ['米饭', '插件', '记忆引擎', '日程', '用户', '同伴', '直播', '语音', '项目', '代码', '测试', 'legacy-data', 'QQ', 'B站', '声音', '梦', '日记'];
18
+ const PLACES = ['米饭', '插件', '记忆引擎', '记忆', '用户', '同伴', '直播', '语音', '项目', '代码', '测试', 'legacy-data', 'QQ', 'B站', '声音', '梦', '日记'];
19
19
  const VERBS = ['修好了', '想起来了', '决定继续', '记录一下', '有点担心', '很开心', '测试了', '重新整理了', '发现了', '计划明天'];
20
20
  const TOPICS = ['图检索', '向量检索', '遗忘曲线', '工作卡', '火花卡', '身份版本', '关系模型', '反思', '巩固', '守护', '备份', '权限'];
21
21
  const PARAPHRASES = new Map([
22
- ['米饭', '饭'],
22
+ ['米饭', '米饭'],
23
23
  ['插件', '扩展程序'],
24
24
  ['记忆引擎', '记忆系统'],
25
- ['日程', '计划'],
25
+ ['记忆', '鲸'],
26
26
  ['直播', '实况'],
27
27
  ['测试', '验证'],
28
28
  ['图检索', '图谱查询'],
package/bin/copy-db.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  * drills and offline inspection. Never writes to the source.
5
5
  *
6
6
  * node bin/copy-db.mjs --source <db> --target <copy>
7
- * node bin/copy-db.mjs # default store -> temp file
7
+ * node bin/copy-db.mjs # default production store -> temp file
8
8
  */
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
package/bin/repair.mjs CHANGED
@@ -7,9 +7,9 @@
7
7
  *
8
8
  * node bin/repair.mjs # dry run: report only
9
9
  * node bin/repair.mjs --apply # back up (VACUUM INTO) then write
10
- * node bin/repair.mjs --apply --user-address 用户 --alias 小名
10
+ * node bin/repair.mjs --apply --user-address 用户 --alias 用户
11
11
  *
12
- * Also covers the identity-boundary rewrite that the 0.4.23 migration needed.
12
+ * Supersedes bin/migrate-0.4.23.mjs (kept for its identity-boundary step).
13
13
  */
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
@@ -24,8 +24,8 @@ const apply = args.includes('--apply');
24
24
  // Opt-in only: rewriting summaries is a data change, so it never happens as part
25
25
  // of a plain repair run and always reports its diff before touching rows.
26
26
  const rewriteCoverage = args.includes('--rewrite-coverage');
27
- const dedupeEpisodes = args.includes('--dedupe-episodes');
28
- // Opt-in: archive facts that are sentence fragments, not assertions.
27
+ const dedupeEpisodes = args.includes('--dedupe-episodes');
28
+ // Opt-in: archive facts that are sentence fragments, not assertions.
29
29
  const dropNoiseFacts = args.includes('--drop-noise-facts');
30
30
  const argValue = (name, fallback = null) => {
31
31
  const index = args.indexOf(name);
@@ -39,7 +39,7 @@ const dbPath = argValue('--db')
39
39
  : path.join(home, '.dsh', 'cortex-memory', 'cortex.sqlite'));
40
40
  const scopeId = argValue('--scope', 'global');
41
41
  const userAddress = argValue('--user-address');
42
- const aliases = ['用户', '你', '您'];
42
+ const aliases = ['用户', '用户', '你', '您'];
43
43
  for (let i = 0; i < args.length; i += 1) {
44
44
  if (args[i] === '--alias' && args[i + 1]) aliases.push(args[i + 1]);
45
45
  }
@@ -65,7 +65,7 @@ const report = {
65
65
  aliasRows: 0,
66
66
  titles: 0,
67
67
  titleFixes: 0,
68
- coverageRewrite: null,
68
+ coverageRewrite: null,
69
69
  noiseFacts: null,
70
70
  dedupeEpisodes: null,
71
71
  };
@@ -91,7 +91,7 @@ function run(sql, ...params) {
91
91
 
92
92
  function deriveTitle(content) {
93
93
  const text = String(content ?? '').replace(/^(用户|助手|User|Assistant)\s*[::]\s*/, '').trim();
94
- // Assistant-side captures start with the persona name ("<name>:…"); strip that
94
+ // Assistant-side captures start with the persona name ("助手:…"); strip that
95
95
  // short label too so the derived title is not just the name.
96
96
  const withoutName = text.replace(/^([^\s::]{1,6})\s*[::]\s*/, '');
97
97
  const candidate = withoutName.length >= 8 ? withoutName : text;
@@ -1,6 +1,6 @@
1
1
  # Windows 安装与回滚
2
2
 
3
- > 目标:和本项目一样的 Windows DSH 用户,能从 tgz 直接安装,不需要编译、不需要原生依赖。
3
+ > 目标:和我一样的 Windows DSH 用户,能从 tgz 直接安装,不需要编译、不需要原生依赖。
4
4
  > 前提:**Node >= 24**(`node:sqlite` 内置)、DSH `>=0.2.1-rc.2 <0.4.0`、Windows 10/11。
5
5
 
6
6
  ## 1. 先备份
@@ -21,7 +21,7 @@ npm pack
21
21
  # 产出 dsh-cortex-0.2.0-dev.1.tgz
22
22
  ```
23
23
 
24
- 如果用本项目打好的包,直接用 `dist/dsh-cortex-0.2.0-dev.1.tgz`。包是纯 JS + SQL,无 `node_modules` 依赖。
24
+ 如果用我打好的包,直接用 `dist/dsh-cortex-0.2.0-dev.1.tgz`。包是纯 JS + SQL,无 `node_modules` 依赖。
25
25
 
26
26
  ## 3. 安装到 desktop profile
27
27
 
package/docs/models.md CHANGED
@@ -159,7 +159,7 @@ POST {baseUrl}/rerank
159
159
 
160
160
  ## 4. 本地 ONNX 模型(未内置)
161
161
 
162
- 本项目没有把 `onnxruntime-node` 或 `@huggingface/transformers` 放进运行时依赖,原因:
162
+ 我没有把 `onnxruntime-node` 或 `@huggingface/transformers` 放进运行时依赖,原因:
163
163
 
164
164
  - 安装体积大(数百 MB);
165
165
  - Windows 上原生二进制/驱动差异;
@@ -1,6 +1,6 @@
1
1
  # 配额压缩(Quota Compaction)设计草案 · v3
2
2
 
3
- > v1 → v2 → v3:v3 采纳第二轮评审意见(①–⑨),核心是**修复 r 的数学**(重归一)与**可核验、可承载的覆盖**。
3
+ > v1 → v2 → v3:v3 采纳review第二轮批注(①–⑨),核心是**修复 r 的数学**(重归一)与**可核验、可承载的覆盖**。
4
4
  > 状态:可以开工 0.4.116(只读)。未写执行代码。
5
5
 
6
6
  ## 0. v3 相对 v2 的关键修正
@@ -122,7 +122,7 @@ k_day = min(2 * k_round, ceil(0.05 * |A|))
122
122
  | 0.4.117 | gray 双问 + auto 执行;每轮 ≤1%,绝对值 ≥5 条 | 累计归档 ≥30 条后再判:`archive_precision` ≥95% 或「0 主动复活」 |
123
123
  | 0.4.118 | bottom-k、每日 5%、熔断接 health | 连续 3 天 tool 复活率 ≤2% |
124
124
 
125
- ## 9. 四问答案(采纳评审意见)
125
+ ## 9. 四问答案(采纳review)
126
126
 
127
127
  1. **S\***:先永不触发,纯观测;条数不是理由,冗余才是。
128
128
  2. **摘要覆盖**:先修可核验 + 承载下限,再谈数量。
@@ -133,7 +133,7 @@ k_day = min(2 * k_round, ceil(0.05 * |A|))
133
133
 
134
134
  - `tokenizer.tokens()` 对中文的切分粒度(字/词)要实测;若是按字,命中率阈值要重标。
135
135
  - `T_lo/T_hi` 先看 116 实测;若 p75/p90 差距 <0.05,直接宣布「信号不可用」,不开 117。
136
- - 熔断恢复:自动熔断、人工恢复(待确认)。
136
+ - 熔断恢复:自动熔断、人工恢复(待用户确认)。
137
137
 
138
138
  ## 11. 2026-11-16 晚的实测补充(重要)
139
139
 
package/index.js CHANGED
@@ -26,8 +26,7 @@ export const Config = Schema ? Schema.object({
26
26
  persona: Schema.object({
27
27
  selfName: Schema.string().default('助手').description('助手自称;默认中性'),
28
28
  userAddress: Schema.string().default('你').description('用户称呼;默认中性'),
29
- userAliases: Schema.array(Schema.string()).default([]).description('用户的其他叫法(如 你、您),统一归到 userAddress 名下'),
30
- description: Schema.string().default('').description('助手的一句话人设;留空时使用中性默认描述'),
29
+ userAliases: Schema.array(Schema.string()).default([]).description('用户的其他叫法(如 用户),统一归到 userAddress 名下'),
31
30
  }).description('人格称呼配置'),
32
31
  readOnlyScopes: Schema.array(Schema.string()).default([]).description('只读共享 scope 列表'),
33
32
  scopeWriteGrants: Schema.array(Schema.any()).default([]).description('显式写授权:scope:agent 或 {grant, until}'),
@@ -93,7 +92,7 @@ export const Config = Schema ? Schema.object({
93
92
  api: Schema.boolean().default(true),
94
93
  autoFacts: Schema.boolean().default(false),
95
94
  autoDiary: Schema.boolean().default(false),
96
- autoDream: Schema.boolean().default(false),
95
+ autoDream: Schema.boolean().default(false),
97
96
  autoSleep: Schema.boolean().default(false),
98
97
  autoFeeling: Schema.boolean().default(false),
99
98
  autoEvolve: Schema.boolean().default(false),
@@ -104,9 +103,9 @@ export const Config = Schema ? Schema.object({
104
103
  llmFacts: Schema.boolean().default(false),
105
104
  tieredRecall: Schema.boolean().default(true),
106
105
  consolidateOnSleep: Schema.boolean().default(true),
107
- consolidateOnTick: Schema.boolean().default(false),
108
- consolidateOnTraceDelta: Schema.boolean().default(false),
109
- consolidateTraceDelta: Schema.number().default(20).description('新增活跃痕迹达到多少条才自动巩固'),
106
+ consolidateOnTick: Schema.boolean().default(false),
107
+ consolidateOnTraceDelta: Schema.boolean().default(false),
108
+ consolidateTraceDelta: Schema.number().default(20).description('新增活跃痕迹达到多少条才自动巩固'),
110
109
  consolidateTraceGapMinutes: Schema.number().default(30).description('两次自动巩固的最小间隔(分钟)'),
111
110
  inhibition: Schema.boolean().default(false),
112
111
  }).description('功能开关'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.147",
3
+ "version": "0.4.148",
4
4
  "description": "本地优先的分层记忆引擎:情景/语义/程序记忆、时序事实、DSR 遗忘、混合召回、自我状态、反思、守护与受控进化。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -28,16 +28,9 @@
28
28
  "README.md",
29
29
  "examples",
30
30
  "LICENSE",
31
- "test",
32
31
  "CHANGELOG.md",
33
32
  "docs"
34
33
  ],
35
- "scripts": {
36
- "test:unit": "node --test test/unit/*.test.js",
37
- "bench": "node bench/run.js",
38
- "check": "node --check index.js && node --check client.js",
39
- "test": "node --test test/unit/*.test.js test/integration/*.test.js"
40
- },
41
34
  "engines": {
42
35
  "node": ">=24",
43
36
  "dsh": ">=0.2.1-rc.2 <0.5.0"
@@ -88,5 +81,11 @@
88
81
  },
89
82
  "bugs": {
90
83
  "url": "https://github.com/Lh1314-China/dsh-cortex-memory/issues"
84
+ },
85
+ "scripts": {
86
+ "test:unit": "node --test test/unit/*.test.js",
87
+ "bench": "node bench/run.js",
88
+ "check": "node --check index.js && node --check client.js",
89
+ "test": "node --test test/unit/*.test.js test/integration/*.test.js"
91
90
  }
92
91
  }
@@ -43,7 +43,7 @@ export function classifySparkCard(card = {}) {
43
43
  const text = `${card.title ?? ''} ${card.content ?? card.contentPreview ?? card.summary ?? ''} ${(card.triggers ?? []).join(' ')}`;
44
44
  if (/应该|必须|不要|先|再|每次|以后|记得|避免|优先|禁止|务必|规则|教训/.test(text)) return 'instruction';
45
45
  if (/插件|安装|配置|命令|路径|报错|测试|接口|版本|构建|项目|函数|文件|系统|git|npm|dsh|api|bug|fix|build|deploy|代码|模块|记忆区域|海马体|语义|面板|开关|检索|时间线|叙事|焦点|健康|体检|策略|权限|工具|上下文|注入|向量|图谱|工作卡|火花|协议|服务|进程|数据库|SQLite|脚本|日志/i.test(text)) return 'observation';
46
- if (/用户|助手|喜欢|爱|难过|开心|心疼|陪|声音|抱|想|梦|日记|称呼|相处|情绪|温暖|孤单|甜|笑|哭|晚安|早安/.test(text)) return 'preference';
46
+ if (/用户|助手|喜欢|爱|难过|开心|心疼|陪|声音|米饭|抱|想|梦|日记|称呼|相处|情绪|温暖|孤单|甜|笑|哭|晚安|早安/.test(text)) return 'preference';
47
47
  return 'utterance';
48
48
  }
49
49
 
@@ -23,22 +23,27 @@ export function coverageOf(trace, { summaries = [], facts = [] } = {}) {
23
23
  return { coverage: Math.min(1, best), by };
24
24
  }
25
25
 
26
- export function createCompressionEngine({ traces, summaries, facts = null, entities = null, config = {} } = {}) {
26
+ export function createCompressionEngine({ traces, summaries, facts = null, entities = null, config = {}, memoryPolicy = null } = {}) {
27
27
  if (!traces || !summaries) throw new Error('compression engine needs traces and summaries');
28
28
 
29
29
  function evaluate({ scopeId = 'global', now = Date.now() } = {}) {
30
30
  const active = traces.list({ scopeId, state: 'active', limit: 5000 });
31
31
  const threadSummaries = summaries.list(scopeId, { limit: 200 });
32
32
  const factList = facts?.list?.({ scopeId, limit: 5000 }) ?? [];
33
+ // Evergreen kinds are the owner's decision, not a heuristic: compression
34
+ // never auto-archives them even when coverage and decay say it could.
35
+ const evergreenKinds = memoryPolicy?.current?.().evergreenKinds ?? [];
33
36
  const rows = active.map((trace) => {
34
37
  const ageDays = daysBetween(trace.lastAccessAt || trace.recordedAt, now);
35
38
  const retrievability = computeRetrievability(trace, now, config.dsr?.decay ?? -0.5);
36
39
  const covered = coverageOf(trace, { summaries: threadSummaries, facts: factList });
37
- const eligible = ageDays >= (config.compression?.minAgeDays ?? 7)
40
+ const evergreen = evergreenKinds.includes(String(trace.kind ?? ''));
41
+ const eligible = !evergreen
42
+ && ageDays >= (config.compression?.minAgeDays ?? 7)
38
43
  && retrievability < (config.compression?.retrievability ?? 0.5)
39
44
  && Number(trace.importance) < (config.compression?.importance ?? 0.35)
40
45
  && covered.coverage >= (config.compression?.coverageThreshold ?? 0.8);
41
- return { trace, ageDays, retrievability, coverage: covered.coverage, by: covered.by, eligible, cost: estimateTokens(trace.content) };
46
+ return { trace, ageDays, retrievability, coverage: covered.coverage, by: covered.by, evergreen, eligible, cost: estimateTokens(trace.content) };
42
47
  });
43
48
  return rows;
44
49
  }
@@ -163,7 +163,7 @@ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allo
163
163
  //
164
164
  // Selection is the opposite of 0.4.116→0.4.130: those versions sorted by
165
165
  // importance descending, so the model was always handed the batch its own
166
- // prompt protects (99% of a production store is >= 0.7 and the top slice is all
166
+ // prompt protects (99% of the production store is >= 0.7 and the top slice is all
167
167
  // 1.0) and could only answer keep. Rank the other end first instead:
168
168
  // 1. no summary covers the trace yet,
169
169
  // 2. it was not shown to the model in the last 24h,
@@ -470,7 +470,7 @@ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allo
470
470
  let droppedGroups = 0;
471
471
  for (const group of clusters.values()) {
472
472
  if (group.length < 2) continue;
473
- // A production store has 75% of active traces at importance >= 0.95, so "two protected
473
+ // Live store has 75% of active traces at importance >= 0.95, so "two protected
474
474
  // members" is the normal case, not the exception. Dedupe has already proved the
475
475
  // members are near-duplicates (Jaccard >= simThreshold), so keeping N copies buys
476
476
  // nothing; reflections were excluded from the pool above.
@@ -30,7 +30,7 @@ export function isInjectedNoise(value) {
30
30
 
31
31
  export function scoreTraceText(text, { kind = null, importance = null } = {}) {
32
32
  const value = String(text ?? '').trim();
33
- let importanceScore = Number.isFinite(importance) ? clamp(importance, 0, 1) : 0.42;
33
+ let importanceScore = Number.isFinite(importance) ? clamp(importance, 0, 1) : 0.26;
34
34
  let candidateKind = kind || 'utterance';
35
35
  let valence = 0;
36
36
  if (!kind) {
@@ -47,8 +47,8 @@ export function scoreTraceText(text, { kind = null, importance = null } = {}) {
47
47
  if (pattern.test(value)) valence = v;
48
48
  }
49
49
  const salience = clamp(0.3 + Math.abs(valence) * 0.6 + Math.min(0.2, value.length / 500), 0, 1);
50
- importanceScore += Math.min(0.15, value.length / 400);
51
- if (salience > 0.6) importanceScore += 0.08;
50
+ importanceScore += Math.min(0.06, value.length / 1000);
51
+ if (salience > 0.6) importanceScore += 0.05;
52
52
  return {
53
53
  kind: candidateKind,
54
54
  importance: clamp(importanceScore, 0, 1),
@@ -81,7 +81,7 @@ export function extractFactCandidates(text, persona = {}) {
81
81
  }
82
82
  const inQuote = (index) => quoteSpans.some(([start, end]) => index >= start && index < end);
83
83
  const selfAliases = new Set(['你', selfName]);
84
- const userAliases = new Set(['我', '自己', '我们', '咱', '用户', '您', userAddress]);
84
+ const userAliases = new Set(['我', '自己', '我们', '咱', '用户', '用户', '您', userAddress]);
85
85
  const out = [];
86
86
  const seen = new Set();
87
87
  for (const rule of RULES) {
@@ -300,7 +300,7 @@ export function createHealthEngine({
300
300
  } catch { /* ignore */ }
301
301
  if (config?.features?.llm !== true) {
302
302
  // Without this the consolidation/dream path silently records no-llm on every
303
- // tick (observed in a busy production store) and the memory layer never solidifies.
303
+ // tick (hundreds of rows in the production store) and the memory layer never solidifies.
304
304
  add('warn', 'LLM_DISABLED', 'LLM 功能未开启(features.llm=false):巩固/做梦只会空转,记得在 profile 配置里打开', { feature: 'llm' });
305
305
  }
306
306
  const slowMs = Number.isFinite(Number(config?.maintainSlowMs)) ? Number(config.maintainSlowMs) : 2000;
@@ -15,7 +15,7 @@ function sentence(text, max = 140) {
15
15
  * around a seed memory, linked by time, tags and content. They are stored as
16
16
  * `summaries` with level=thread, so they can be recalled as one memory.
17
17
  */
18
- export function createNarrativeEngine({ traces, summaries, selfName = '助手', now = () => Date.now() } = {}) {
18
+ export function createNarrativeEngine({ traces, summaries, now = () => Date.now() } = {}) {
19
19
  if (!traces || !summaries) throw new Error('narrative engine needs traces and summaries');
20
20
 
21
21
  function buildThread({ scopeId = 'global', seedTraceId, windowDays = 7, windowHours = 24, max = 8, at = now() } = {}) {
@@ -98,12 +98,8 @@ export function createNarrativeEngine({ traces, summaries, selfName = '助手',
98
98
  };
99
99
  // Capture stores a 40-char title (it stops mid-parenthesis: "…验收(工具名:desk")
100
100
  // while the content holds the whole turn. Read the content first and strip the
101
- // speaker prefix ("用户:" / the assistant's own name) capture writes in front of it.
102
- const speakerPrefix = ['用户', '助手', '系统', selfName, 'user', 'assistant']
103
- .filter((item) => typeof item === 'string' && item.trim())
104
- .map((item) => item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
105
- .join('|');
106
- const stripSpeaker = (text) => String(text ?? '').replace(new RegExp(`^(?:${speakerPrefix})\\s*[::]\\s*`, 'i'), '');
101
+ // "用户:" / "助手:" speaker prefix capture writes in front of it.
102
+ const stripSpeaker = (text) => String(text ?? '').replace(/^(?:用户|助手|助手|系统|我|user|assistant)\s*[::]\s*/i, '');
107
103
  // A quoted turn arrives as "用户:> …": the speaker prefix hides the quote marker, so
108
104
  // both have to come off together — one pass strips only the prefix and leaves "> ".
109
105
  const stripDecoration = (text) => {
@@ -161,7 +157,7 @@ export function createNarrativeEngine({ traces, summaries, selfName = '助手',
161
157
  : '只留下了这一个种子,附近还没别的痕迹。';
162
158
  const seedTopic = cleanTitle(trimAtBoundary(String(seed.content || seed.title || '').replace(/\s+/g, ' ').trim(), 60))
163
159
  || sentence(seed.content, 40);
164
- const content = `一段关于…${seedTopic}」的经历:${body}`;
160
+ const content = `一段关于「${seedTopic}」的经历:${body}`;
165
161
  const summary = summaries.insert({
166
162
  scopeId,
167
163
  level: 'thread',
@@ -155,6 +155,11 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
155
155
  mu: config.costPenalty ?? 0.08,
156
156
  recentMinMatch: config.recentMinMatch ?? 0.12,
157
157
  recentImportanceFloor: config.recentImportanceFloor ?? 0.8,
158
+ // A trace whose fact was superseded (its event is the source of an
159
+ // invalidated fact) is historical: keep it searchable but rank it below the
160
+ // replacement. Without this, overwrite correctness lived only in the fact
161
+ // layer while retrieval still surfaced the old sentence.
162
+ retiredPenalty: config.retiredPenalty ?? 0.25,
158
163
  decay: config.dsr?.decay ?? -0.5,
159
164
  inhibition: config.features?.inhibition === true
160
165
  ? {
@@ -166,18 +171,35 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
166
171
  : null,
167
172
  };
168
173
 
169
- function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, weights = null, filters = null, vectorHits = null, gate = 'none' } = {}, intent = 'fact') {
174
+ function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, includeRetired = false, weights = null, filters = null, vectorHits = null, gate = 'none' } = {}, intent = 'fact') {
170
175
  const queryTokens = tokens(query);
171
176
  const sourceTrace = [];
172
177
  const lists = [];
173
178
  let ftsCount = 0;
174
179
  let recentCount = 0;
180
+ // Retired facts are the write-side truth: collect the events they came from
181
+ // so the matching traces can be demoted below their replacements.
182
+ const retiredEvents = (() => {
183
+ if (!facts || typeof facts.list !== 'function') return null;
184
+ try {
185
+ const rows = facts.list({ scopeId, status: 'invalidated', limit: 2000 });
186
+ if (!rows.length) return null;
187
+ const set = new Set();
188
+ for (const row of rows) {
189
+ const eventId = row?.sourceEventId ?? null;
190
+ if (eventId) set.add(eventId);
191
+ }
192
+ return set.size ? set : null;
193
+ } catch {
194
+ return null;
195
+ }
196
+ })();
175
197
  try {
176
198
  let hits = traces.searchFts(query, { scopeId, limit: Math.max(limit * 3, defaults.ftsLimit), includeArchived });
177
199
  let sourceName = 'fts';
178
200
  if (!hits.length) {
179
201
  // Character fallback: only when the exact bigram query has no hits.
180
- // This keeps normal FTS precision and lets 米饭 find 饭 via 饭.
202
+ // This keeps normal FTS precision and lets 米饭 find 米饭 via 饭.
181
203
  hits = traces.searchFts(query, {
182
204
  scopeId,
183
205
  limit: Math.max(limit * 3, defaults.ftsLimit),
@@ -244,11 +266,23 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
244
266
  const candidates = [];
245
267
  const fallbacks = [];
246
268
  let gated = 0;
269
+ let retiredSkipped = 0;
247
270
  for (const [id, entry] of fused) {
248
271
  const trace = traces.get(id);
249
272
  if (!trace || trace.state === 'archived' && !includeArchived) continue;
250
273
  if (filters && !matchesFilters(trace, filters)) continue;
251
274
  const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens, defaults.inhibition);
275
+ // Historical sentence whose fact was superseded. Default recall drops it
276
+ // (the replacement answers the question); an explicit includeRetired keeps
277
+ // it, ranked below live memories.
278
+ if (retiredEvents && retiredEvents.has(trace.eventId)) {
279
+ if (!includeRetired) {
280
+ retiredSkipped += 1;
281
+ continue;
282
+ }
283
+ candidate.utility *= defaults.retiredPenalty;
284
+ candidate.retired = true;
285
+ }
252
286
  // Prompt-injection gate: only weaken candidates that entered solely via
253
287
  // the recency list or the soft FTS fallback. Strong sources still pass.
254
288
  // High importance is allowed to bypass the match floor, preserving the
@@ -272,7 +306,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
272
306
  for (const list of lists) {
273
307
  sourceTrace.push({ source: list.name, ok: true, count: list.items.length });
274
308
  }
275
- return { candidates, sourceTrace, ftsCount, recentCount, gated };
309
+ return { candidates, sourceTrace, ftsCount, recentCount, gated, retiredSkipped };
276
310
  }
277
311
 
278
312
  function search(query, {
@@ -281,6 +315,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
281
315
  limit = defaults.limit,
282
316
  now = Date.now(),
283
317
  includeArchived = false,
318
+ includeRetired = false,
284
319
  filters = null,
285
320
  vectorHits = null,
286
321
  gate = 'none',
@@ -294,7 +329,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
294
329
  const effectiveBudget = activePolicy?.budget != null
295
330
  ? Math.max(64, Math.min(20000, Number(activePolicy.budget)))
296
331
  : budget;
297
- const sources = searchSources(query, { scopeId, limit, now, includeArchived, weights: policyWeights, filters, vectorHits, gate }, intent);
332
+ const sources = searchSources(query, { scopeId, limit, now, includeArchived, includeRetired, weights: policyWeights, filters, vectorHits, gate }, intent);
298
333
  const portfolio = selectPortfolio(sources.candidates, {
299
334
  budget: effectiveBudget,
300
335
  limit,
@@ -346,6 +381,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
346
381
  confidence: Number(item.confidence ?? 0),
347
382
  match: Number(item.match ?? 0),
348
383
  kind: item.trace?.kind ?? null,
384
+ retired: item.retired === true,
349
385
  why: item.sources.map((source) => `${source.name}#${source.rank}`).join(','),
350
386
  attachments: item.attachments ?? 0,
351
387
  }));
@@ -359,6 +395,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
359
395
  elapsedMs: Date.now() - started,
360
396
  candidates: sources.candidates.length,
361
397
  gated: sources.gated ?? 0,
398
+ retiredSkipped: sources.retiredSkipped ?? 0,
362
399
  selected: items.length,
363
400
  dropped: portfolio.dropped.length,
364
401
  sources: sources.sourceTrace,
@@ -269,7 +269,8 @@ export function createScheduler({
269
269
  const scopeId = cortex.config?.scope ?? 'global';
270
270
  if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(scopeId)) return;
271
271
  const at = now();
272
- const hour = Math.max(0, Math.min(23, Number(cortex.config?.deepConsolidateHour ?? 4)));
272
+ const policy = cortex.memoryPolicy?.current?.() ?? null;
273
+ const hour = Math.max(0, Math.min(23, Number(policy?.deepConsolidateHour ?? cortex.config?.deepConsolidateHour ?? 4)));
273
274
  if (new Date(at).getHours() < hour) return;
274
275
  const day = localDayOf(at);
275
276
  if (lastDeepDay === day) return;
@@ -283,7 +284,7 @@ export function createScheduler({
283
284
  const result = await cortex.consolidation.run({
284
285
  scopeId,
285
286
  now: at,
286
- limit: Math.max(1, Math.min(80, Number(cortex.config?.deepConsolidateLimit ?? 60))),
287
+ limit: Math.max(1, Math.min(80, Number(policy?.deepConsolidateLimit ?? cortex.config?.deepConsolidateLimit ?? 60))),
287
288
  caller: 'deep-daily',
288
289
  spread: true,
289
290
  });
@@ -379,10 +380,10 @@ export function createScheduler({
379
380
  } catch (error) {
380
381
  report.steps.jobs = { error: error instanceof Error ? error.message : String(error) };
381
382
  }
382
- if (consolidateOnTick && cortex.consolidation?.run) {
383
+ if ((consolidateOnTick || cortex.memoryPolicy?.current?.().consolidateOnTick === true) && cortex.consolidation?.run) {
383
384
  try {
384
385
  // The tick path used to fire on every tick (once a minute with the live
385
- // interval) — hundreds of no-llm audit rows prove it. Even with the flag on, honour the
386
+ // interval) — hundreds of no-llm rows prove it. Even with the flag on, honour the
386
387
  // same gap so enabling it cannot turn into a per-minute LLM call.
387
388
  const scopeId = cortex.config?.scope ?? 'global';
388
389
  const gapMs = Math.max(1, Number(cortex.config?.features?.consolidateTraceGapMinutes ?? 30)) * 60_000;
@@ -25,7 +25,7 @@ export function tokens(text) {
25
25
 
26
26
  export function ftsTokenList(text) {
27
27
  // Bigrams preserve phrase specificity; single non-stop CJK chars act as a
28
- // cheap fuzzy fallback for near-synonyms that share a character (米饭/饭).
28
+ // cheap fuzzy fallback for near-synonyms that share a character (米饭/米饭).
29
29
  const out = tokenList(text);
30
30
  const value = String(text ?? '');
31
31
  for (const run of value.match(HAN) ?? []) {
package/src/self/alias.js CHANGED
@@ -1,11 +1,10 @@
1
1
  /**
2
2
  * Alias resolution for people.
3
3
  *
4
- * The same person can be stored under two targets (a nickname from the early
5
- * days and the configured address now), so the relationship model would never
6
- * accumulate and the affect counts would split. Everything that takes a target
7
- * name goes through this resolver first, so aliases converge on the configured
8
- * user address. `persona.userAliases` adds local nicknames.
4
+ * The same person was stored as two targets ("用户" from the early days and
5
+ * "用户" now), so the relationship model never accumulated and the affect
6
+ * counts split. Everything that takes a target name goes through this resolver
7
+ * first, so aliases converge on the configured user address.
9
8
  */
10
9
  const DEFAULT_USER_ALIASES = ['用户', '你', '您'];
11
10
 
@@ -0,0 +1,59 @@
1
+ import { nowIso } from '../core/time.js';
2
+
3
+ /**
4
+ * Memory policy: how memory flows is a decision, not a hard-coded constant.
5
+ *
6
+ * A policy is an ordinary `policies` row (kind: 'memory'): propose → approve →
7
+ * rollback, every step audited by the evolution engine. Defaults come from the
8
+ * config, so an install without a policy behaves exactly as before.
9
+ *
10
+ * Current knobs:
11
+ * - evergreenKinds: trace kinds that compression never auto-archives
12
+ * - consolidateOnTick / deepConsolidateHour / deepConsolidateLimit: consolidation cadence
13
+ */
14
+ export function createMemoryPolicy({ policies = null, config = {} } = {}) {
15
+ const defaults = Object.freeze({
16
+ evergreenKinds: ['identity', 'promise'],
17
+ consolidateOnTick: config.consolidateOnTick === true || config.features?.consolidateOnTick === true,
18
+ deepConsolidateHour: Number(config.deepConsolidateHour ?? 4),
19
+ deepConsolidateLimit: Number(config.deepConsolidateLimit ?? 60),
20
+ compressionMinAgeDays: Number(config.compression?.minAgeDays ?? 7),
21
+ });
22
+
23
+ function current() {
24
+ try {
25
+ const active = policies?.active?.('memory');
26
+ const cfg = active?.config;
27
+ if (cfg && typeof cfg === 'object') {
28
+ return {
29
+ ...defaults,
30
+ ...cfg,
31
+ source: 'policy',
32
+ policyId: active.id,
33
+ policyVersion: active.version,
34
+ activatedAt: active.activatedAt ?? null,
35
+ };
36
+ }
37
+ } catch {
38
+ /* a bad policy row must never block memory */
39
+ }
40
+ return { ...defaults, source: 'config' };
41
+ }
42
+
43
+ function evergreen(kind) {
44
+ const list = current().evergreenKinds;
45
+ return Array.isArray(list) && list.includes(String(kind ?? ''));
46
+ }
47
+
48
+ function describe() {
49
+ const value = current();
50
+ const lines = [
51
+ `记忆策略来源:${value.source === 'policy' ? `policy v${value.policyVersion}(${value.policyId})` : '配置文件默认'}`,
52
+ `evergreen:${value.evergreenKinds?.join('、') || '(空)'}`,
53
+ `巩固:tick=${value.consolidateOnTick ? '开' : '关'} · 深整理 ${value.deepConsolidateHour} 点 · 上限 ${value.deepConsolidateLimit} 条`,
54
+ ];
55
+ return lines.join('\n');
56
+ }
57
+
58
+ return { defaults, current, evergreen, describe, at: nowIso() };
59
+ }
@@ -22,6 +22,7 @@ import { createSummonRepository } from '../store/repositories/summon.js';
22
22
  import { createIdentityStore } from '../self/identity.js';
23
23
  import { createRelationshipStore } from '../self/relationship.js';
24
24
  import { createTargetResolver } from '../self/alias.js';
25
+ import { createMemoryPolicy } from '../self/memory-policy.js';
25
26
  import { createEncodeEngine, isInjectedNoise } from '../engines/encode.js';
26
27
  import { createRetrievalEngine } from '../engines/retrieve.js';
27
28
  import { createGrowthEngine } from '../engines/growth.js';
@@ -90,6 +91,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
90
91
  const identityStore = createIdentityStore(db);
91
92
  const targetResolver = createTargetResolver(config.persona ?? {});
92
93
  const relationshipStore = createRelationshipStore(db, { resolveTarget: targetResolver.resolveTarget });
94
+ let lastFamiliarityBumpAt = 0;
93
95
  const metrics = createMetrics();
94
96
  const workingStore = createWorkingStore(db);
95
97
  const goalStore = createGoalStore(db);
@@ -132,11 +134,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
132
134
  const encode = createEncodeEngine({ events, traces, entities, facts, edges, audit, vector, config });
133
135
  const graph = createGraphEngine({ entities, facts, edges, traces });
134
136
  const policies = createPolicyRepository(db);
137
+ const memoryPolicy = createMemoryPolicy({ policies, config });
135
138
  const policyConfig = (kind) => {
136
139
  try { return policies.active(kind)?.config ?? null; } catch { return null; }
137
140
  };
138
141
  const retrieve = createRetrievalEngine({ traces, facts, graph, vector, policy: policyConfig, config });
139
- const compression = createCompressionEngine({ traces, summaries, facts, entities, config });
142
+ const compression = createCompressionEngine({ traces, summaries, facts, entities, config, memoryPolicy });
140
143
  const extractor = createFactExtractor({ entities, facts });
141
144
  const digest = createDigestEngine({ traces, summaries, emotion, goals: goalStore, feedback, scopeId: config.scope });
142
145
  const retention = createRetentionEngine({ traces });
@@ -182,7 +185,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
182
185
  })
183
186
  : null;
184
187
  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 });
185
- const narrative = createNarrativeEngine({ traces, summaries, selfName: config.persona?.selfName ?? '助手' });
188
+ const narrative = createNarrativeEngine({ traces, summaries });
186
189
  const consolidation = createConsolidationEngine({ db, traces, summaries, audit, llm: llmAdapter });
187
190
  const skills = createSkillEngine({ skills: skillsRepo, traces });
188
191
  const health = createHealthEngine({
@@ -442,6 +445,20 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
442
445
  if (!result.skipped && config.features?.llmFacts === true && llmAdapter?.available?.() && !Array.isArray(input.facts)) {
443
446
  scheduleLlmFacts(result, input);
444
447
  }
448
+ // Shared time is relationship too: a captured turn (not every recall, not
449
+ // every read) nudges familiarity. Throttled to once per two hours so a busy
450
+ // afternoon cannot inflate it, and it never touches trust/care.
451
+ if (!result.skipped && input.source === 'host:turn') {
452
+ const at = Date.now();
453
+ if (at - lastFamiliarityBumpAt > 2 * 3_600_000) {
454
+ lastFamiliarityBumpAt = at;
455
+ try {
456
+ relationshipStore.applyDelta(scopeId, targetResolver.canonical, { familiarityDelta: 0.002 }, { event: 'interaction:turn', at: new Date(at).toISOString() });
457
+ } catch {
458
+ /* the relationship nudge must never block capture */
459
+ }
460
+ }
461
+ }
445
462
  return result;
446
463
  }
447
464
 
@@ -1581,6 +1598,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1581
1598
  repos: { events, traces, entities, facts, edges, feedback, summaries, jobs, skills: skillsRepo, audit, playbook: playbookRepo },
1582
1599
  stores: { selfStore, appraisalStore, initiativeStore, identityStore, relationshipStore },
1583
1600
  engines: { encode, graph, retrieve, growth, reflect, narrative, skills, health, privacy, develop, development, vector, compression, extractor, runner },
1601
+ memoryPolicy,
1584
1602
  development,
1585
1603
  narrative,
1586
1604
  vector,
@@ -142,7 +142,7 @@ export function createFactRepository(db) {
142
142
  if (later.validFrom === validFrom) {
143
143
  // Same start, different object. The compatibility rule only applies
144
144
  // when both sides are free text: "一直在" and "一直存在着" can coexist.
145
- // Entity-to-entity conflicts (likes 咖啡 vs likes 茶) still dispute.
145
+ // Entity-to-entity conflicts (likes 米饭 vs likes 米饭) still dispute.
146
146
  const newLiteral = objectLiteral ?? null;
147
147
  const allLiterals = Boolean(newLiteral) && existing.every((fact) => Boolean(fact.objectLiteral));
148
148
  const flip = allLiterals && existing.some((fact) => negationFlip(fact.objectLiteral, newLiteral));
@@ -269,7 +269,7 @@ export function createTraceRepository(db) {
269
269
  // Without a scope this is the whole index. With one it must join through
270
270
  // traces: health used to compare the *global* trace count against the
271
271
  // *whole* FTS table and reported drift whenever another scope existed
272
- // (a real store had an `agency` scope, so it warned by exactly those
272
+ // (the production store has an `agency` scope, so it warned by exactly those
273
273
  // 12 rows forever).
274
274
  if (scopeId) {
275
275
  return Number(db.prepare('SELECT COUNT(*) AS c FROM traces_fts_index f JOIN traces t ON t.id = f.trace_id WHERE t.scope_id = ?').get(scopeId).c);