dsh-cortex-memory 0.4.147 → 0.4.160

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 (46) hide show
  1. package/CHANGELOG.md +2550 -2396
  2. package/README.md +55 -110
  3. package/bench/governance.mjs +265 -0
  4. package/bench/migration-bench.mjs +1 -1
  5. package/bench/semantic-cn.js +4 -4
  6. package/bench/synthetic.js +3 -3
  7. package/bin/copy-db.mjs +1 -1
  8. package/bin/repair.mjs +7 -7
  9. package/docs/install-windows.md +2 -2
  10. package/docs/models.md +1 -1
  11. package/docs/quota-compaction-design.md +3 -3
  12. package/index.js +6 -4
  13. package/package.json +8 -8
  14. package/scripts/backfill-author.mjs +132 -0
  15. package/scripts/backfill-stability.mjs +142 -0
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/core/config.js +47 -2
  18. package/src/engines/autonomy.js +1 -1
  19. package/src/engines/compression.js +8 -3
  20. package/src/engines/consolidate.js +7 -3
  21. package/src/engines/encode.js +70 -7
  22. package/src/engines/extract.js +1 -1
  23. package/src/engines/health.js +1 -1
  24. package/src/engines/life.js +2 -1
  25. package/src/engines/memory-audit.js +168 -0
  26. package/src/engines/narrative.js +4 -8
  27. package/src/engines/reflect.js +25 -1
  28. package/src/engines/retrieve.js +55 -5
  29. package/src/host/scheduler.js +5 -4
  30. package/src/memory/dsr.js +30 -1
  31. package/src/memory/tokenizer.js +8 -2
  32. package/src/prompt/assemble.js +66 -18
  33. package/src/self/alias.js +4 -5
  34. package/src/self/alignment.js +77 -0
  35. package/src/self/appraisal.js +32 -9
  36. package/src/self/evidence.js +102 -0
  37. package/src/self/identity.js +8 -4
  38. package/src/self/initiative.js +12 -0
  39. package/src/self/memory-policy.js +59 -0
  40. package/src/self/state.js +42 -7
  41. package/src/service/cortex.js +212 -12
  42. package/src/store/database.js +10 -0
  43. package/src/store/repositories/facts.js +1 -1
  44. package/src/store/repositories/traces.js +18 -4
  45. package/src/store/schema.sql +3 -0
  46. package/src/tools/definitions.js +348 -4
package/README.md CHANGED
@@ -1,135 +1,80 @@
1
- # Cortex Memory
1
+ # Cortex Memory · dsh-cortex-memory
2
2
 
3
- 本地优先的分层记忆引擎,给 DeepSeek Harness 一个能长期成长的记忆与自我状态。
3
+ 本地优先的分层记忆引擎,给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的模型一套能自己维护的记忆:情景 / 语义 / 程序记忆分层,时序事实、遗忘曲线、混合召回、自我状态、反思与受控进化,全部落在一个 SQLite 文件里。
4
4
 
5
- 不是把聊天记录堆起来,也不是只做关键词检索。Cortex 把记忆拆成工作记忆、情景痕迹、语义事实、程序技能、反思摘要与召唤卡,再配合时序事实、DSR 遗忘、混合召回、身份/情绪/关系和守护审计,让 agent 在新会话里还能把自己拼回来。
5
+ 不联网、不上传,记忆归你。
6
6
 
7
- ## 当前版本
7
+ ## 它能做什么
8
8
 
9
- ```text
10
- 主包:dsh-cortex-memory@0.4.147
11
- 提取器:dsh-cortex-extractors@0.3.5
12
- DSH:>=0.2.1-rc.2 <0.5.0
13
- Node:>=24
14
- 测试:520/520
15
- ```
16
-
17
- ## 现在能做什么
18
-
19
- | 能力 | 说明 |
20
- |---|---|
21
- | 分层记忆 | 工作记忆、L1 情景痕迹、语义事实、程序技能、反思摘要 |
22
- | 时序事实 | 事实带有效时间,支持更新、失效和争议,不把旧结论当永久真相 |
23
- | 遗忘曲线 | DSR/FSRS 风格复习、遗忘、归档与唤醒 |
24
- | 混合召回 | FTS + 向量 + 时间/重要性;弱相关候选在注入前过滤 |
25
- | 自我状态 | 身份、驱力、情绪、关系、主动意图与校准 |
26
- | 召唤卡 | L2 卡片 + L3 专题,按触发词浮回,可人工修订 |
27
- | 反思与生活 | 摘要、日记、梦、睡眠整理 |
28
- | 守护与审计 | 健康检查、完整性、FTS 对齐、备份、事件链 |
29
- | 眼耳 | Windows OCR / Tesseract / Whisper / PaddleOCR,可选安装 |
30
- | 本地优先 | SQLite 本地库;核心引擎无外部模型依赖 |
31
-
32
- ## 安装
33
-
34
- 先关闭 DSH,再安装并重启:
35
-
36
- ```powershell
37
- dsh plugin --profile desktop add dsh-cortex-memory@0.4.147
38
- dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
39
- ```
40
-
41
- `dsh-cortex-extractors` 是可选的图片/音频入口;只做文字记忆时可以不装。
9
+ - **分层记忆**:L1 工作记忆(每轮注入的焦点与置顶)、L2 情景痕迹、L3 语义事实与反思摘要,按预算裁剪后再拼进提示词。
10
+ - **写入与召回**:`cortex_write` 写一条痕迹(可带事实三元组),`cortex_search` 混合召回(FTS + 共现 + 可选向量),`cortex_get` / `cortex_timeline` 看原始现场与时序邻居。
11
+ - **时序事实**:同一主体同一谓词的多次取值按时间版本化,`cortex_as_of` 能回答「当时是什么」「当时我以为是什么」。
12
+ - **遗忘与稳定**:DSR 模型(难度 / 稳定度 / 可提取性),长期不用的痕迹会降权、可归档,但不会静默删除。
13
+ - **自我状态**:驱力、情绪、阶段、关系、待处理意图;`cortex_self` 一眼看全,`cortex_window` 看「这轮实际注入了什么、被裁掉了什么」。
14
+ - **反思与巩固**:`cortex_reflect` 把一段窗口压成一条可追溯的反思;`cortex_consolidate` 合并重复;`cortex_compress` 归档已被摘要覆盖的旧痕迹。
15
+ - **治理与体检**:事件链、SQLite 完整性、FTS 对齐、重复、矛盾事实、僵尸痕迹——`cortex_health` 一次报全,`cortex_audit` 只读审计。
16
+ - **受控进化**:`cortex_evolve` 只提案,不自动应用;要 `approve` 才生效,可回滚。
17
+ - **身份版本**:`cortex_identity` 把「我是谁」做成版本化叙事,改内容必须走 propose 并写理由。
42
18
 
43
- ### Windows 一键包
19
+ ### 工具
44
20
 
45
- GitHub Release 提供:
21
+ | 类别 | 工具 |
22
+ | --- | --- |
23
+ | 写与读 | `cortex_write`、`cortex_search`、`cortex_get`、`cortex_timeline`、`cortex_as_of` |
24
+ | 工作记忆 | `cortex_working` |
25
+ | 事实与目标 | `cortex_goal`、`cortex_playbook`、`cortex_intention` |
26
+ | 自我与身份 | `cortex_self`、`cortex_window`、`cortex_identity`、`cortex_emotion` |
27
+ | 反思与巩固 | `cortex_reflect`、`cortex_consolidate`、`cortex_compress`、`cortex_digest`、`cortex_life` |
28
+ | 治理与体检 | `cortex_health`、`cortex_audit`、`cortex_guard`、`cortex_forget`、`cortex_feedback`、`cortex_inhibition` |
29
+ | 自主与进化 | `cortex_tick`、`cortex_evolve`、`cortex_design`、`cortex_retag` |
46
30
 
47
- ```text
48
- cortex-memory-oneclick-0.4.147.zip
49
- ```
50
-
51
- 解压后双击 `install.cmd`。安装器会做 profile 检查、备份、SHA256 校验和可选路径迁移。
31
+ ## 装之前要知道
52
32
 
53
- ## 该装哪些
33
+ - **Node.js >= 24**:存储用 `node:sqlite`(内置 SQLite,22 上要带实验标志,DSH 拉起时不会带),没有原生依赖,也不需要编译。
34
+ - 装完**重启 DSH**,28 个 `cortex_*` 工具才会出现。
35
+ - 数据默认落在 `<DSH_HOME>/cortex-memory/`,一个 SQLite 文件;想换位置用配置里的 `dataRoot` / `dbFile`。
36
+ - 写入有配额与压缩策略:默认不会无限增长,但长期使用建议定期 `cortex_health` 看一眼。
37
+ - 反思有一道硬闸:**手动反思需要外部证据**(被纠正 / 任务失败 / 明确反对),没有证据会返回 `no-external-evidence`;定时巩固(auto/backfill)不受此限。这是故意的,不是 bug。
38
+ - `cortex_evolve` 不会自己改配置,必须 `approve`;改完可 `rollback`。
39
+ - 不联网。只有你显式接 LLM 适配器(`dsh-cortex-extractors`)时,抽取才会调用你配置的模型。
54
40
 
55
- | 需求 | 建议 |
56
- |---|---|
57
- | 只要文字记忆 | 主包 |
58
- | 看截图/图片 | 主包 + extractor,Windows OCR 即可 |
59
- | 扫描件/复杂排版 | 再加 Tesseract + chi_sim 语言包 |
60
- | 手写图片 | PaddleOCR + 本地模型目录 |
61
- | 中文音频 | Whisper.cpp + ggml-small,显式下载 |
62
- | 大模型 | 不安装;走 DSH 自己的模型服务 |
41
+ ## 和谁一起用
63
42
 
64
- 原则:
43
+ | 插件 | 为什么 |
44
+ | --- | --- |
45
+ | `dsh-cortex-extractors` | 可选,需单独安装(不在本包内)。装了它,写入的痕迹会被自动抽取成事实三元组,`cortex_as_of` 才有东西可查。不装也能用,只是事实要手动写。 |
46
+ | `dsh-shiori-bridge` | 桥负责跨会话调度,Cortex 负责记住「上次那个会话聊到哪」;两者不重叠。 |
47
+ | `dsh-powang`(破妄) | 左脑管工程经验卡片,Cortex 管长期记忆;可以并存,互不依赖。 |
48
+ | `dsh-whale-eyes` / `dsh-whale-sight` | 感知插件读到的现场(在哪个应用、看到了什么)可以经 `cortex_write` 留成情景记忆。 |
65
49
 
66
- ```text
67
- 核心零外部模型
68
- 提取器不自动下载模型
69
- Whisper 需显式 -Whisper
70
- PaddleOCR 需显式模型目录
71
- 不替用户填 LLM API key
72
- ```
50
+ ## 需要额外装的软件
73
51
 
74
- ## 开发与测试
52
+ 不需要。`node:sqlite` 是 Node 24+ 内置模块;插件没有原生扩展、不下载模型、不要密钥。
75
53
 
76
- 必须使用 DSH 自带的 **Node 24** 跑测试/bench。系统 PATH 上如果是 Node 22,会低于 `engines.node >=24`,`node --test` 可能直接失败。
77
-
78
- npm 包里不包含 `test/`(从 0.4.147 起):测试在 GitHub 仓库与 CI 里跑,包体更小、审计面更窄。
79
-
80
- ```text
81
- DSH 运行时 Node:24.21.0
82
- 系统 Node:仅作兼容性参考,不保证
83
- ```
84
-
85
- CLI 默认读取 `~/.dsh/cortex-memory`;需要指定其他库时显式传 `--data <dir>`。
54
+ ## 安装
86
55
 
87
- ## 性能与边界
56
+ ### 一键包(Windows,推荐给不熟悉命令行的人)
88
57
 
89
- 已做:
58
+ 1. 解压本压缩包;
59
+ 2. 双击 `install.cmd`;
60
+ 3. 想先看它要做什么,就在 PowerShell 里跑 `.\install.ps1 -DryRun`(不会改任何东西)。
90
61
 
91
- ```text
92
- 主包测试:520/520
93
- 受控中文语义探针:recall@3 1.000 / MRR@3 0.917 / nDCG@3 0.938
94
- 受控探针延迟:p50 1.31ms / p95 4.07ms
95
- 真实图片 OCR:已跑通
96
- ```
62
+ 脚本会自动找 `dsh` 命令、校验 SHA256、备份 profile 的 `package.json`,再装进 `desktop` profile。装完**重启 DSH**。
97
63
 
98
- 必须说清楚:
64
+ ### npm
99
65
 
100
- ```text
101
- 受控语义探针是合成集,不是 LoCoMo/LongMemEval 官方分数
102
- ASR 还没有真实音频样本验收
103
- 技能沉淀当前为 0,管线存在但没有真实技能闭环
104
- 没有多代理集群验证
66
+ ```powershell
67
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.160
105
68
  ```
106
69
 
107
- Cortex 的定位是“本地可解释、可回滚、能长期长”的记忆系统,不把“功能多”宣传成“公开基准第一”。
108
-
109
- ## 和同类插件的区别
110
-
111
- | 插件 | 主要强项 | 和 Cortex 的差异 |
112
- |---|---|---|
113
- | `dsh-persona-memory` | MEMORY.md / USER.md 文件记忆、用户画像、跨会话注入、简单直接 | 更轻、更透明;没有完整时序事实、DSR、自我状态和召唤卡 |
114
- | `dsh-shiori` | Spark 卡、专题、触发词,卡/专题体验成熟 | 卡片层更专注;没有完整的情绪/关系/遗忘/自进化闭环 |
115
- | `dsh-memory` | SQLite FTS、三工具、轻量 | 简单检索;没有分层、反思和生活模块 |
116
- | `OpenViking` / `dsh-mnemon` | 平台化、多来源、上下文基础设施 | 更偏底座和 provider;Cortex 更偏“长期记忆 + 自我状态”一体 |
70
+ ## 卸载
117
71
 
118
- ## 数据与隐私
119
-
120
- ```text
121
- 默认数据目录:~/.dsh/cortex-memory
122
- 本地 SQLite
123
- 不把密钥写进 npm 包
124
- 不自动上传记忆
125
- 提取器默认不下载模型
72
+ ```powershell
73
+ dsh plugin --profile desktop remove dsh-cortex-memory
126
74
  ```
127
75
 
128
- ## 下载
76
+ 卸载插件不会删除记忆库;想清空请在卸载前先备份 `cortex.sqlite` 再手动删除。
129
77
 
130
- - npm 主包:`dsh-cortex-memory@0.4.147`
131
- - npm 提取器:`dsh-cortex-extractors@0.3.5`
132
- - GitHub Release:`v0.4.147`
133
- - Windows 一键包:`cortex-memory-oneclick-0.4.147.zip`
78
+ ## 许可
134
79
 
135
- 安装后重启 DSH,左侧出现「Cortex 记忆」入口。
80
+ MIT © 2026 Lh1314-China。问题请走 [Issues](https://github.com/Lh1314-China/dsh-cortex-memory/issues)。
@@ -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,13 +26,15 @@ 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}'),
34
33
  contextBudget: Schema.natural().default(2200).description('检索注入的 token 预算'),
35
- promptBudget: Schema.natural().default(1600).description('常驻自我/工作记忆提示词预算'),
34
+ promptBudget: Schema.natural().default(1800).description('常驻自我/工作记忆提示词预算'),
35
+ // 2026-11-29:护栏白名单(准则 id)——排在最前,不被同票的手艺条按创建时间顶掉
36
+ playbookPinned: Schema.array(Schema.string()).default([]).description('永远排最前的准则 id(护栏);投票表达「有用」,表达不了「重要」'),
37
+ playbookBudget: Schema.natural().default(420).description('工作准则段的 token 预算;白名单护栏全文,其余超 80 字截断并给全文指针'),
36
38
  recallTimeoutMs: Schema.natural().default(1200).description('前台召回硬截止'),
37
39
  asyncJobs: Schema.boolean().default(true).description('允许后台任务'),
38
40
  captureSubagents: Schema.boolean().default(false).description('是否把子代理会话也写入记忆'),
@@ -192,7 +194,7 @@ export async function apply(ctx, config = {}) {
192
194
  name: 'cortex-self',
193
195
  order: 1.05,
194
196
  text: (context) => assembleSystemPrompt(cortex, {
195
- budgetTokens: config.promptBudget ?? 1600,
197
+ budgetTokens: config.promptBudget ?? 1800,
196
198
  recall: runtime?.recallText(context) ?? '',
197
199
  }).text,
198
200
  }));