dsh-cortex-memory 0.4.162 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +2 -2
  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
package/README.md CHANGED
@@ -1,79 +1,120 @@
1
- # Cortex Memory · dsh-cortex-memory
1
+ # Cortex Memory
2
2
 
3
- 本地优先的分层记忆引擎,给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的模型一套能自己维护的记忆:情景 / 语义 / 程序记忆分层,时序事实、遗忘曲线、混合召回、自我状态、反思与受控进化,全部落在一个 SQLite 文件里。
3
+ 本地优先的分层记忆引擎,给 DeepSeek Harness 一套能长期维护的记忆、自我状态和治理面。
4
4
 
5
- 不联网、不上传,记忆归你。
5
+ 它不是把聊天记录堆起来,也不是只做关键词检索。Cortex 把记忆拆成工作记忆、情景痕迹、语义事实、程序技能、反思摘要与召唤卡,再配合时序事实、DSR 遗忘、混合召回、身份/情绪/关系和守护审计,让 agent 在新会话里还能把自己拼回来。
6
6
 
7
- ## 它能做什么
7
+ ## 当前版本
8
8
 
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 并写理由。
9
+ ```text
10
+ 主包:dsh-cortex-memory 0.5.0
11
+ 可选提取器:dsh-cortex-extractors(单独安装)
12
+ DSH:>=0.2.1-rc.2 <0.5.0
13
+ Node:>=24
14
+ ```
18
15
 
19
- ### 工具
16
+ ## 这个版本能做什么
17
+
18
+ | 能力 | 说明 |
19
+ |---|---|
20
+ | 分层记忆 | 工作记忆、L1 情景痕迹、语义事实、程序技能、反思摘要、召唤卡 |
21
+ | 时序事实 | 事实带有效时间,支持更新、失效、争议和 `cortex_as_of` 回看 |
22
+ | 遗忘曲线 | DSR/FSRS 风格复习、遗忘、归档与唤醒;不静默删除 |
23
+ | 混合召回 | FTS + 向量 + 图/时间/重要性融合;弱相关候选在注入前过滤 |
24
+ | 深排搜索 | `cortex_search(deep:true)` 最多 100 候选本地线性重排;默认关,约 390ms |
25
+ | 分层预算 | `cortex_search(tiered:true)` 按预算缩放 perm/hot/cold 三段 |
26
+ | 自我状态 | 身份、驱力、情绪、关系、主动意图与校准 |
27
+ | 反思与生活 | 摘要、日记、梦、睡眠整理、日摘要 |
28
+ | 程序技能 | 从重复事件聚类候选技能,手动 promote / record 使用结果 |
29
+ | 经验桥 | 单向导入工程经验卡片到 `engineering` scope |
30
+ | 守护与审计 | 健康检查、完整性、FTS 对齐、备份、事件链、只读审计 |
31
+ | 记忆钉住 | `cortex_protect` 钉住/解钉,合并、归档、淘汰都不动它 |
32
+ | 受控进化 | 只提案,不自动应用;要 approve 才生效,可回滚 |
33
+ | 本地优先 | SQLite 单文件;核心引擎无外部模型依赖 |
34
+
35
+ ## 工具
36
+
37
+ 共 31 个 `cortex_*` 工具:
20
38
 
21
39
  | 类别 | 工具 |
22
- | --- | --- |
40
+ |---|---|
23
41
  | 写与读 | `cortex_write`、`cortex_search`、`cortex_get`、`cortex_timeline`、`cortex_as_of` |
24
42
  | 工作记忆 | `cortex_working` |
25
- | 事实与目标 | `cortex_goal`、`cortex_playbook`、`cortex_intention` |
43
+ | 事实/目标/准则/意图 | `cortex_goal`、`cortex_playbook`、`cortex_intention` |
26
44
  | 自我与身份 | `cortex_self`、`cortex_window`、`cortex_identity`、`cortex_emotion` |
27
45
  | 反思与巩固 | `cortex_reflect`、`cortex_consolidate`、`cortex_compress`、`cortex_digest`、`cortex_life` |
28
- | 治理与体检 | `cortex_health`、`cortex_audit`、`cortex_guard`、`cortex_forget`、`cortex_feedback`、`cortex_inhibition` |
46
+ | 治理与审计 | `cortex_health`、`cortex_audit`、`cortex_guard`、`cortex_forget`、`cortex_feedback`、`cortex_inhibition`、`cortex_protect` |
29
47
  | 自主与进化 | `cortex_tick`、`cortex_evolve`、`cortex_design`、`cortex_retag` |
48
+ | 技能与桥 | `cortex_skill`、`cortex_import_powang` |
30
49
 
31
- ## 装之前要知道
50
+ ## 安装
32
51
 
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`)时,抽取才会调用你配置的模型。
52
+ ### npm
40
53
 
41
- ## 和谁一起用
54
+ 先关闭 DSH,再安装并重启:
42
55
 
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` 留成情景记忆。 |
56
+ ```powershell
57
+ dsh plugin --profile desktop add dsh-cortex-memory@latest
58
+ ```
49
59
 
50
- ## 需要额外装的软件
60
+ 可选提取器:
51
61
 
52
- 不需要。`node:sqlite` 是 Node 24+ 内置模块;插件没有原生扩展、不下载模型、不要密钥。
62
+ ```powershell
63
+ dsh plugin --profile desktop add dsh-cortex-extractors@latest
64
+ ```
53
65
 
54
- ## 安装
66
+ ### Windows 一键包
55
67
 
56
- ### 一键包(Windows,推荐给不熟悉命令行的人)
68
+ 从 GitHub Releases 下载 `cortex-memory-oneclick-*`,解压后:
57
69
 
58
- 1. 解压本压缩包;
70
+ 1. 关闭 DSH;
59
71
  2. 双击 `install.cmd`;
60
- 3. 想先看它要做什么,就在 PowerShell 里跑 `.\install.ps1 -DryRun`(不会改任何东西)。
61
-
62
- 脚本会自动找 `dsh` 命令、校验 SHA256、备份 profile 的 `package.json`,再装进 `desktop` profile。装完**重启 DSH**。
72
+ 3. 按提示选择 profile;装完重启 DSH。
63
73
 
64
- ### npm
74
+ 安装器会自己找 DSH CLI、校验 SHA256、备份 profile,再装公开包。
65
75
 
66
76
  ```powershell
67
- dsh plugin --profile desktop add dsh-cortex-memory@0.4.160
77
+ .\install.ps1 -DryRun # 只看将做什么
78
+ .\install.ps1 -Profile desktop # 干净安装
79
+ .\install.ps1 -Upgrade # 已装公开包时备份升级
80
+ .\install.ps1 -SkipExtractor # 不装提取器
68
81
  ```
69
82
 
70
- ## 卸载
83
+ ## 外部依赖(可选)
84
+
85
+ **默认不需要任何外部软件。** Cortex 用内置哈希向量 + FTS + 图召回就能工作。
86
+
87
+ 想要更好的本地语义召回,可以接 Ollama + `bge-m3`:
88
+
89
+ - 一键包会**检测** Ollama / bge-m3;缺失时询问一次是否安装/拉取,默认选否。
90
+ - 不选或非交互运行:**一个字节都不下载**。
91
+ - 显式选择:
71
92
 
72
93
  ```powershell
73
- dsh plugin --profile desktop remove dsh-cortex-memory
94
+ .\install.ps1 -InstallOllama -PullBgeM3
95
+ .\install.ps1 -PullBgeM3
96
+ .\check-env.ps1 # 只读检测
97
+ .\install-engines.ps1 -DryRun # 只看计划
74
98
  ```
75
99
 
76
- 卸载插件不会删除记忆库;想清空请在卸载前先备份 `cortex.sqlite` 再手动删除。
100
+ 没有 winget 时不会静默下载安装包;只提示官方下载页。
101
+
102
+ OCR/ASR 是可选提取器的能力:Windows OCR 用系统;Tesseract/Whisper 需要本地引擎,安装器只做显式开关下载,不静默提权。
103
+
104
+ ## 兼容性
105
+
106
+ - Node.js **>=24**:存储使用 `node:sqlite`,无原生扩展、无需编译。
107
+ - DSH **>=0.2.1-rc.2 <0.5.0**;桌面与 Web profile 均支持。
108
+ - 安装后重启 DSH,`cortex_*` 工具才会出现。
109
+ - 数据默认落在 `<DSH_HOME>/cortex-memory/`,一个 SQLite 文件;可用配置改 `dataRoot` / `dbFile`。
110
+
111
+ ## 隐私与边界
112
+
113
+ - 不联网;只有显式接 LLM 适配器时,抽取才调用你配置的模型。
114
+ - 记忆库不上传;卸载插件不会删除记忆库。
115
+ - 作废来源的痕迹默认**降权保留**并标记 `retired`,不是静默删除;要归档用 `cortex_forget`。
116
+ - 反思有一道硬闸:手动反思需要外部证据(被纠正/任务失败/明确反对),没有证据会返回 `no-external-evidence`;定时巩固不受此限。
117
+ - `cortex_evolve` 不会自己改配置;必须 approve,改完可 rollback。
77
118
 
78
119
  ## 许可
79
120
 
package/bin/cortex.mjs CHANGED
File without changes
package/client.js CHANGED
@@ -925,7 +925,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
925
925
  h('h4', {}, '容量上限'),
926
926
  data.capacity ? h('div', {}, [
927
927
  h('div', { key: 'l0', className: 'cortex-row' }, `人设 L0:${data.capacity.identityTokens} / ${data.capacity.identityBudget} tokens${data.capacity.identityTokens > data.capacity.identityBudget ? '(超出预算,注入会截断)' : ''}`),
928
- h('div', { key: 'l1', className: 'cortex-row' }, `工作记忆 L1:${data.capacity.workingBudget} tokens`),
928
+ h('div', { key: 'l1', className: 'cortex-row' }, `工作记忆 L1:self ${data.capacity.workingBudgetSelf ?? '?'} / life ${data.capacity.workingBudgetLife ?? '?'} / work ${data.capacity.workingBudgetWork ?? '?'}(仅工程模式)tokens`),
929
929
  h('div', { key: 'prompt', className: 'cortex-row' }, `系统提示总预算:${data.capacity.promptBudget} tokens`),
930
930
  h('div', { key: 'ctx', className: 'cortex-row' }, `检索上下文:${data.capacity.contextBudget} tokens`),
931
931
  h('div', { key: 'tiers', className: 'cortex-row' }, `分层召回:perm ${data.capacity.tiers?.perm} / hot ${data.capacity.tiers?.hot} / cold ${data.capacity.tiers?.cold} tokens`),
@@ -2734,6 +2734,8 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2734
2734
  const [error, setError] = useState('');
2735
2735
  const [detailId, setDetailId] = useState(null);
2736
2736
  const [timelineId, setTimelineId] = useState('');
2737
+ // 2026-12-05 助手(硬约束④ 面板简单化):诊断/运维页默认收起。
2738
+ const [showAllTabs, setShowAllTabs] = useState(false);
2737
2739
 
2738
2740
  const loadSelf = useCallback(async () => {
2739
2741
  setSelfBusy(true);
@@ -2780,15 +2782,20 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2780
2782
  ['settings', t('tabSettings')],
2781
2783
  ];
2782
2784
 
2785
+ // 2026-12-05 助手:第一眼只给「常看的五个」,其余收进「更多」。
2786
+ // 一个标签都没删 —— 只是默认不铺满一屏(原来 14 个并排,9 个是排障用的)。
2787
+ const PRIMARY_TABS = new Set(['self', 'search', 'timeline', 'life', 'emotion']);
2788
+ const visibleTabs = showAllTabs ? tabs : tabs.filter(([id]) => PRIMARY_TABS.has(id));
2789
+
2783
2790
  const moveTab = (event, index) => {
2784
2791
  if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft' && event.key !== 'Home' && event.key !== 'End') return;
2785
2792
  event.preventDefault();
2786
2793
  let next = index;
2787
- if (event.key === 'ArrowRight') next = (index + 1) % tabs.length;
2788
- else if (event.key === 'ArrowLeft') next = (index - 1 + tabs.length) % tabs.length;
2794
+ if (event.key === 'ArrowRight') next = (index + 1) % visibleTabs.length;
2795
+ else if (event.key === 'ArrowLeft') next = (index - 1 + visibleTabs.length) % visibleTabs.length;
2789
2796
  else if (event.key === 'Home') next = 0;
2790
- else if (event.key === 'End') next = tabs.length - 1;
2791
- const [nextId] = tabs[next];
2797
+ else if (event.key === 'End') next = visibleTabs.length - 1;
2798
+ const [nextId] = visibleTabs[next] ?? [];
2792
2799
  setTab(nextId);
2793
2800
  document.getElementById(`cortex-tab-${nextId}`)?.focus();
2794
2801
  };
@@ -2835,18 +2842,29 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2835
2842
  h('button', { key: 'r', type: 'button', className: 'cortex-btn', onClick: loadSelf, disabled: selfBusy }, t('refresh')),
2836
2843
  ]),
2837
2844
  tab === 'self' && error ? h(ErrorBlock, { key: 'err', message: error, prefix: t('errorPrefix'), onRetry: loadSelf, retryLabel: t('retry') }) : null,
2838
- h('div', { key: 'tabs', className: 'cortex-tabs', role: 'tablist', 'aria-label': t('navLabel') }, tabs.map(([id, label], index) => h('button', {
2839
- key: id,
2840
- id: `cortex-tab-${id}`,
2841
- type: 'button',
2842
- role: 'tab',
2843
- 'aria-selected': tab === id,
2844
- 'aria-controls': `cortex-panel-${id}`,
2845
- tabIndex: tab === id ? 0 : -1,
2846
- className: `cortex-tab${tab === id ? ' on' : ''}`,
2847
- onClick: () => setTab(id),
2848
- onKeyDown: (event) => moveTab(event, index),
2849
- }, label))),
2845
+ h('div', { key: 'tabs', className: 'cortex-tabs', role: 'tablist', 'aria-label': t('navLabel') }, [
2846
+ ...visibleTabs.map(([id, label], index) => h('button', {
2847
+ key: id,
2848
+ id: `cortex-tab-${id}`,
2849
+ type: 'button',
2850
+ role: 'tab',
2851
+ 'aria-selected': tab === id,
2852
+ 'aria-controls': `cortex-panel-${id}`,
2853
+ tabIndex: tab === id ? 0 : -1,
2854
+ className: `cortex-tab${tab === id ? ' on' : ''}`,
2855
+ onClick: () => setTab(id),
2856
+ onKeyDown: (event) => moveTab(event, index),
2857
+ }, label)),
2858
+ // 「更多」不开 role=tab:它不是面板,是个开关。
2859
+ h('button', {
2860
+ key: 'more',
2861
+ type: 'button',
2862
+ className: 'cortex-tab cortex-tab-more',
2863
+ 'aria-expanded': showAllTabs,
2864
+ title: showAllTabs ? '收起诊断页' : '展开诊断/运维页',
2865
+ onClick: () => setShowAllTabs((value) => !value),
2866
+ }, showAllTabs ? '‹ 收起' : `更多 ${tabs.length - visibleTabs.length} ›`),
2867
+ ]),
2850
2868
  h('div', {
2851
2869
  key: tab,
2852
2870
  id: `cortex-panel-${tab}`,
package/cordis.patch.yml CHANGED
@@ -1,11 +1,8 @@
1
- # dsh-cortex-memory bundle patch.
1
+ # dsh-cortex bundle patch.
2
2
  # Host row + client panel. The engine owns its own data root (~/.dsh/cortex-memory),
3
3
  # never shiori's data.
4
- # 2026-12-03: entry name must match the published package name. It used to say
5
- # 'dsh-cortex' (the private package), so a standalone `npm i dsh-cortex-memory`
6
- # failed with ERR_MODULE_NOT_FOUND: Cannot find package 'dsh-cortex'.
7
4
  - insert:
8
5
  - id: dsh-cortex-memory
9
6
  name: 'dsh-cortex-memory'
10
7
  config: {}
11
-
8
+
@@ -5,35 +5,30 @@
5
5
  | Item | Value |
6
6
  |---|---|
7
7
  | OS | Windows 11 |
8
- | DSH | 0.2.2-rc.1 |
8
+ | DSH | 0.2.2-rc.3 |
9
9
  | Node | 26.13.0 |
10
- | Public package | `dsh-cortex-memory` 0.1.0 |
11
- | Data root | fresh `~/.dsh/cortex` |
10
+ | Public package | `dsh-cortex-memory` 0.5.0 |
11
+ | Data root | `<DSH_HOME>/cortex-memory` |
12
12
  | Native dependencies | none required |
13
- | Tests | 373 passing |
14
- | Package smoke | packed tgz extracted and started |
13
+ | Tests | unit 553 / integration 126 |
14
+ | Package smoke | temp profile install + composed profile dump |
15
15
 
16
16
  ## What was actually checked
17
17
 
18
- 1. `npm pack` produced a 99-file tgz with `dsh.bundle.patch`.
19
- 2. The tgz was extracted; `createCortex` wrote, searched and health-checked.
20
- 3. The public source tests passed: 373 / 0.
21
- 4. The client bundle is a DSH web client plugin; the host row is a bundle patch.
18
+ 1. `npm pack` produced the 0.5.0 tgz with `dsh.bundle.patch`.
19
+ 2. The tgz installed into a temporary DSH profile together with `dsh-cortex-extractors` 0.3.7.
20
+ 3. `dsh --profile <temp> --dump-config` composed the profile and resolved `dsh-cortex-memory`.
21
+ 4. Unit 553/553 and integration 126/126 pass in the stripped public tree.
22
22
  5. No absolute personal paths or credentials are required.
23
23
 
24
24
  ## Hard requirements
25
25
 
26
26
  - **Node.js >= 24** — the engine uses `node:sqlite`.
27
- - **DSH >=0.2.1-rc.2 <0.4.0**.
27
+ - **DSH >=0.2.1-rc.2 <0.5.0**.
28
28
  - A profile may run only one plugin whose host id is `cortex`.
29
29
 
30
30
  ## Not yet verified
31
31
 
32
- - Installation into a brand-new DSH profile from the exact release tgz.
33
- - A click-through browser E2E of every panel control.
34
- - Node 20/22 users.
35
- - Very old DSH releases.
36
- - Running alongside the private development build that uses the same `cortex` id.
37
-
38
- Do not claim “works for every Windows/DSH user” until a clean-profile
39
- installation is done on a machine without the development build.
32
+ - Full desktop click-through of every panel control on a clean machine.
33
+ - Node 20/22 users (not supported; Node 24+ is required).
34
+ - Very old DSH releases outside the declared range.
@@ -1,7 +1,7 @@
1
1
  # Windows 安装与回滚
2
2
 
3
3
  > 目标:和我一样的 Windows DSH 用户,能从 tgz 直接安装,不需要编译、不需要原生依赖。
4
- > 前提:**Node >= 24**(`node:sqlite` 内置)、DSH `>=0.2.1-rc.2 <0.4.0`、Windows 10/11。
4
+ > 前提:**Node >= 24**(`node:sqlite` 内置)、DSH `>=0.2.1-rc.2 <0.5.0`、Windows 10/11。
5
5
 
6
6
  ## 1. 先备份
7
7
 
@@ -13,7 +13,7 @@
13
13
  powershell -ExecutionPolicy Bypass -File .\examples\setup-cortex-bge.ps1 `
14
14
  -Dsh "D:\path\to\dsh.cmd" `
15
15
  -Profile cortex-bge `
16
- -Package "C:\path\to\dsh-cortex-memory-0.1.0.tgz"
16
+ -Package "C:\path\to\dsh-cortex-memory-0.5.0.tgz"
17
17
  ```
18
18
 
19
19
  首次先用 Ollama 启动模型服务:
package/index.js CHANGED
@@ -30,11 +30,20 @@ export const Config = Schema ? Schema.object({
30
30
  }).description('人格称呼配置'),
31
31
  readOnlyScopes: Schema.array(Schema.string()).default([]).description('只读共享 scope 列表'),
32
32
  scopeWriteGrants: Schema.array(Schema.any()).default([]).description('显式写授权:scope:agent 或 {grant, until}'),
33
- contextBudget: Schema.natural().default(2200).description('检索注入的 token 预算'),
34
- promptBudget: Schema.natural().default(1800).description('常驻自我/工作记忆提示词预算'),
33
+ contextBudget: Schema.natural().default(2600).description('检索注入的 token 预算'),
34
+ promptBudget: Schema.natural().default(2400).description('常驻自我/工作记忆提示词预算'),
35
+ // 2026-12-04:工作记忆分道预算(与 src/core/config.js 的 DEFAULT_CONFIG 同源)。
36
+ // Schema 默认值会被 profile cordis.patch.yml 的同名键覆盖,改这里只是兜底。
37
+ workingBudgetSelf: Schema.natural().default(400).description('工作记忆 self 道预算(身份/情感/关系)'),
38
+ workingBudgetLife: Schema.natural().default(250).description('工作记忆 life 道预算(生活日常)'),
39
+ workingBudgetWork: Schema.natural().default(800).description('工作记忆 work 道预算(仅工程模式生效)'),
40
+ goalsBudget: Schema.natural().default(300).description('当前目标段预算'),
41
+ skillsBudget: Schema.natural().default(200).description('技能段预算'),
42
+ relationsBudget: Schema.natural().default(150).description('关系模型段预算'),
43
+ intentionsBudget: Schema.natural().default(100).description('待处理意图段预算'),
35
44
  // 2026-11-29:护栏白名单(准则 id)——排在最前,不被同票的手艺条按创建时间顶掉
36
45
  playbookPinned: Schema.array(Schema.string()).default([]).description('永远排最前的准则 id(护栏);投票表达「有用」,表达不了「重要」'),
37
- playbookBudget: Schema.natural().default(420).description('工作准则段的 token 预算;白名单护栏全文,其余超 80 字截断并给全文指针'),
46
+ playbookBudget: Schema.natural().default(400).description('工作准则段的 token 预算;白名单护栏全文,其余超 80 字截断并给全文指针'),
38
47
  recallTimeoutMs: Schema.natural().default(1200).description('前台召回硬截止'),
39
48
  asyncJobs: Schema.boolean().default(true).description('允许后台任务'),
40
49
  captureSubagents: Schema.boolean().default(false).description('是否把子代理会话也写入记忆'),
@@ -43,7 +52,7 @@ export const Config = Schema ? Schema.object({
43
52
  touchOnRecall: Schema.boolean().default(true).description('召回时回写 access_count / last_access_at(DSR 复习信号)'),
44
53
  touchMinIntervalMs: Schema.natural().default(300000).description('同一条记忆两次 access 回写的最小间隔;防每步召回灌水'),
45
54
  touchMaxIntervalMs: Schema.natural().default(21600000).description('间隔随访问次数翻倍后的上限(默认 6 小时)'),
46
- workingTtlDays: Schema.natural().default(14).description('工作记忆里未置顶且多久没更新就清掉(天)'),
55
+ workingTtlDays: Schema.natural().default(7).description('工作记忆里未置顶且多久没更新就清掉(天)'),
47
56
  vectorBackfillBatch: Schema.natural().default(200).description('每次心跳最多排队的缺失向量条数'),
48
57
  vectorDrainBatch: Schema.natural().default(50).description('每次心跳最多真正嵌入的条数'),
49
58
  vectorDrainBudgetMs: Schema.natural().default(45000).description('一次向量回填最多占用的毫秒数;到点就停,下一轮继续'),
@@ -194,7 +203,7 @@ export async function apply(ctx, config = {}) {
194
203
  name: 'cortex-self',
195
204
  order: 1.05,
196
205
  text: (context) => assembleSystemPrompt(cortex, {
197
- budgetTokens: config.promptBudget ?? 1800,
206
+ budgetTokens: config.promptBudget ?? 2400,
198
207
  recall: runtime?.recallText(context) ?? '',
199
208
  }).text,
200
209
  }));
@@ -208,10 +217,39 @@ export async function apply(ctx, config = {}) {
208
217
  self: cortex.self,
209
218
  health: cortex.health,
210
219
  // Companion plugins (dsh-cortex-agency) ride the host heartbeat and
211
- // write through the public write() path; they never reach into the DB.
220
+ // write through the public write() path.
221
+ // 2026-12-05 夜(允复核指出):这里原来写「they never reach into the DB」,是假的 ——
222
+ // 下面把完整 repos 递了出去(repos: cortex.repos),拿到它的伴生插件可以直接
223
+ // traces.update / traces.remove,绕过工具层、也不进 audit。目前只有 agency 用它
224
+ // 做只读(engine.js:103 只调 list/listSince,且有 ?? null 兜底)。
225
+ // 收窄留到安全体系那一轮再做,现在只把注释改成实话。
212
226
  onTick: cortex.onTick,
213
227
  llm: cortex.llm,
214
228
  config: cortex.config,
229
+ // 2026-12-05 助手:伴生插件的结构化通道。
230
+ // 之前这里只有 9 个字段,导致 dsh-cortex-agency 的 submitGoal / listActiveGoals
231
+ // 全是 undefined —— 12-03 那轮手工补丁写进去的目标一条都没落到库里,
232
+ // 159 条沉思也永远进不了 prompt。以下 shim 只转发到已有的 store / alignment,
233
+ // 不新增写路径,不绕过 scope 约束。
234
+ working: cortex.working,
235
+ goals: cortex.goals,
236
+ repos: cortex.repos,
237
+ submitGoal: (input = {}) => cortex.goals.add({
238
+ ...input,
239
+ scopeId: input.scopeId ?? cortex.config?.scope ?? 'global',
240
+ }),
241
+ listActiveGoals: (options = {}) => cortex.goals.list({
242
+ status: 'active',
243
+ limit: 100,
244
+ ...options,
245
+ scopeId: options.scopeId ?? cortex.config?.scope ?? 'global',
246
+ }),
247
+ updateGoal: (id, patch = {}) => cortex.goals.update(id, patch),
248
+ claimIntent: (options = {}) => cortex.alignment.claim({
249
+ ...options,
250
+ scopeId: options.scopeId ?? cortex.config?.scope ?? 'global',
251
+ }),
252
+ observeIntent: (options = {}) => cortex.alignment.observe(options),
215
253
  });
216
254
  if (typeof disposeService === 'function') disposers.push(disposeService);
217
255
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.162",
3
+ "version": "0.5.0",
4
4
  "description": "本地优先的分层记忆引擎:情景/语义/程序记忆、时序事实、DSR 遗忘、混合召回、自我状态、反思、守护与受控进化。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -89,4 +89,4 @@
89
89
  "check": "node --check index.js && node --check client.js",
90
90
  "test": "node --test test/unit/*.test.js test/integration/*.test.js"
91
91
  }
92
- }
92
+ }
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 嵌入环境自检(一键包安装时可选调用,不接进主流程)
4
+ *
5
+ * 为什么单独一个脚本:
6
+ * 插件本体**零 npm 依赖**,语义召回只靠「可选」的本地嵌入服务(Ollama + bge-m3)。
7
+ * 所以安装器不该强制装它,而应该:检测 → 告诉用户有/没有 → 让他自己选。
8
+ *
9
+ * 用法:
10
+ * node scripts/check-embedding.mjs # 人读的输出
11
+ * node scripts/check-embedding.mjs --json # 机器读(给安装器用)
12
+ *
13
+ * 退出码:
14
+ * 0 = 可以用(远程服务在、模型在)
15
+ * 1 = 需要用户做点什么(没装/没拉模型)
16
+ * 2 = 配置读不出来
17
+ */
18
+ import { readFileSync, existsSync } from 'node:fs';
19
+ import path from 'node:path';
20
+ import os from 'node:os';
21
+
22
+ const DSH_HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
23
+ const DATA_ROOT = process.env.CORTEX_DATA_ROOT || path.join(DSH_HOME, 'cortex-memory');
24
+ const CONFIG = path.join(DATA_ROOT, 'model-config.json');
25
+ const json = process.argv.includes('--json');
26
+
27
+ function out(payload, exitCode) {
28
+ if (json) console.log(JSON.stringify(payload, null, 2));
29
+ else {
30
+ console.log(payload.title);
31
+ for (const line of payload.lines) console.log(' ' + line);
32
+ if (payload.hint) console.log('\n' + payload.hint);
33
+ }
34
+ process.exit(exitCode);
35
+ }
36
+
37
+ let cfg = null;
38
+ try {
39
+ cfg = JSON.parse(readFileSync(CONFIG, 'utf8'));
40
+ } catch (error) {
41
+ out({
42
+ ok: false,
43
+ state: 'no-config',
44
+ title: '嵌入配置读不出来:' + CONFIG,
45
+ lines: [
46
+ '这不是错误 —— 插件会用默认的 hash 嵌入(纯词法),功能正常但语义召回弱。',
47
+ '文件不存在或不是合法 JSON 时都会落到这个分支。',
48
+ ],
49
+ hint: '想启用语义召回:安装 Ollama,然后运行 `ollama pull bge-m3`,再把 ' +
50
+ 'model-config.json 的 embedding.mode 改成 "local"。',
51
+ }, 2);
52
+ }
53
+
54
+ const emb = cfg?.embedding ?? {};
55
+ const mode = String(emb.mode ?? 'hash');
56
+ const baseUrl = String(emb.baseUrl ?? '').replace(/\/+$/, '');
57
+ const model = String(emb.model ?? '');
58
+
59
+ if (mode === 'hash' || !baseUrl) {
60
+ out({
61
+ ok: true,
62
+ state: 'hash',
63
+ title: '当前用的是 hash 嵌入(纯词法,零依赖)',
64
+ lines: [
65
+ '插件可以正常跑,不需要任何外部服务。',
66
+ '区别:换个说法提问时,召回会弱一些(词对不上就找不到)。',
67
+ ],
68
+ hint: '想要语义召回:装 Ollama → `ollama pull bge-m3` → 把 embedding.mode 改成 "local"。',
69
+ }, 0);
70
+ }
71
+
72
+ // 探测本地/远程嵌入服务。
73
+ // 注意:baseUrl 一般是 OpenAI 兼容路径(以 /v1 结尾),而 Ollama 的模型列表在
74
+ // 原生接口 /api/tags 上。所以要先用去掉 /v1 的 origin 试原生接口,再退回 /models。
75
+ const probe = async () => {
76
+ const origin = baseUrl.replace(/\/v\d+$/, '');
77
+ const attempts = [
78
+ { url: origin + '/api/tags', parse: (b) => (b?.models ?? []).map((m) => String(m.name ?? '')) },
79
+ { url: baseUrl + '/models', parse: (b) => (b?.data ?? []).map((m) => String(m.id ?? '')) },
80
+ { url: origin + '/models', parse: (b) => (b?.data ?? []).map((m) => String(m.id ?? '')) },
81
+ ];
82
+ let lastError = null;
83
+ for (const attempt of attempts) {
84
+ const controller = new AbortController();
85
+ const timer = setTimeout(() => controller.abort(), 4000);
86
+ try {
87
+ const res = await fetch(attempt.url, { signal: controller.signal });
88
+ if (!res.ok) { lastError = 'HTTP ' + res.status + ' @ ' + attempt.url; continue; }
89
+ const body = await res.json();
90
+ return { reachable: true, names: attempt.parse(body), via: attempt.url };
91
+ } catch (error) {
92
+ lastError = (error?.name === 'AbortError' ? 'timeout' : String(error?.message ?? error)) + ' @ ' + attempt.url;
93
+ } finally {
94
+ clearTimeout(timer);
95
+ }
96
+ }
97
+ return { reachable: false, error: lastError };
98
+ };
99
+
100
+ const r = await probe();
101
+ if (!r.reachable) {
102
+ out({
103
+ ok: false,
104
+ state: 'service-down',
105
+ title: '配置要求语义嵌入,但服务连不上:' + baseUrl,
106
+ lines: [
107
+ '插件会退化成"查不到语义"(每次查询都会标记 semantic: unavailable,不会静默假装成功)。',
108
+ ],
109
+ hint: '先启动 Ollama(`ollama serve` 或桌面版),确认 ' + baseUrl + ' 能访问,再重跑本脚本。',
110
+ }, 1);
111
+ }
112
+
113
+ const hasModel = r.names.some((n) => n === model || n.startsWith(model + ':'));
114
+ if (!hasModel) {
115
+ out({
116
+ ok: false,
117
+ state: 'model-missing',
118
+ title: '服务在,但没有模型:' + model,
119
+ lines: ['已装模型:' + (r.names.length ? r.names.join(', ') : '(无)')],
120
+ hint: '运行 `ollama pull ' + model + '`(约 446 MB)。',
121
+ }, 1);
122
+ }
123
+
124
+ out({
125
+ ok: true,
126
+ state: 'ready',
127
+ title: '语义嵌入可用',
128
+ lines: ['服务:' + baseUrl, '模型:' + model],
129
+ }, 0);
@@ -11,16 +11,26 @@ export const DEFAULT_CONFIG = Object.freeze({
11
11
  dbFile: path.join(DEFAULT_ROOT, 'cortex.sqlite'),
12
12
  scope: 'global',
13
13
  persona: Object.freeze({ selfName: '助手', userAddress: '你' }),
14
- contextBudget: 2200,
15
- promptBudget: 1800,
14
+ contextBudget: 2600,
15
+ promptBudget: 2400,
16
16
  readOnlyScopes: Object.freeze([]),
17
17
  scopeWriteGrants: Object.freeze([]),
18
- identityBudget: 360,
18
+ identityBudget: 400,
19
19
  // 2026-11-29:fit 修好单位后 800 是「真 800 token」,工作记忆会独吞并挤掉尾注/意图。
20
20
  // 收到 700,留出后段的份额(实测总注入 ~1530/1600)。
21
21
  workingBudget: 700,
22
+ // 2026-12-04:工作记忆按道分预算。work 道默认 0(工程模式才给 800),
23
+ // 让技能/关系/意图在普通模式下能进来;self 道守身份情感,life 道守生活日常。
24
+ workingBudgetSelf: 400,
25
+ workingBudgetLife: 250,
26
+ workingBudgetWork: 800,
27
+ workingTtlDays: 7,
28
+ goalsBudget: 300,
29
+ skillsBudget: 200,
30
+ relationsBudget: 150,
31
+ intentionsBudget: 100,
22
32
  // 2026-11-29:playbook 段预算(原来硬编码 260,只放得下 2 条长规则)。420 能放 3-4 条。
23
- playbookBudget: 420,
33
+ playbookBudget: 400,
24
34
  // 2026-11-29:护栏白名单。投票只表达「有用」,表达不了「重要」;
25
35
  // 实测:投完票后「中文/JSON 别用 PowerShell」靠 created_at 把「用户划的线」顶掉。
26
36
  // 白名单里的规则在 playbook.render 永远排最前。
@@ -74,6 +84,9 @@ export const DEFAULT_CONFIG = Object.freeze({
74
84
  mode: false,
75
85
  floorCoherence: 0.3,
76
86
  floorSafety: 0.2,
87
+ // 2026-12-04:工程模式与破妄(powang)软绑定。开工程模式时尝试唤醒破妄,
88
+ // 失败只记 warning,不阻断。任何同时装了 dsh-cortex 和 dsh-powang 的 profile 都适用。
89
+ powangBind: true,
77
90
  }),
78
91
  features: Object.freeze({
79
92
  recall: true,
@@ -160,6 +173,20 @@ export function normalizeConfig(raw = {}) {
160
173
  promptBudget: numeric(input.promptBudget, DEFAULT_CONFIG.promptBudget, 256, 8000),
161
174
  identityBudget: numeric(input.identityBudget, DEFAULT_CONFIG.identityBudget, 64, 4000),
162
175
  workingBudget: numeric(input.workingBudget, DEFAULT_CONFIG.workingBudget, 128, 8000),
176
+ workingBudgetSelf: numeric(input.workingBudgetSelf, DEFAULT_CONFIG.workingBudgetSelf, 0, 4000),
177
+ workingBudgetLife: numeric(input.workingBudgetLife, DEFAULT_CONFIG.workingBudgetLife, 0, 4000),
178
+ workingBudgetWork: numeric(input.workingBudgetWork, DEFAULT_CONFIG.workingBudgetWork, 0, 8000),
179
+ workingTtlDays: numeric(input.workingTtlDays, DEFAULT_CONFIG.workingTtlDays, 1, 365),
180
+ goalsBudget: numeric(input.goalsBudget, DEFAULT_CONFIG.goalsBudget, 0, 4000),
181
+ skillsBudget: numeric(input.skillsBudget, DEFAULT_CONFIG.skillsBudget, 0, 4000),
182
+ relationsBudget: numeric(input.relationsBudget, DEFAULT_CONFIG.relationsBudget, 0, 4000),
183
+ intentionsBudget: numeric(input.intentionsBudget, DEFAULT_CONFIG.intentionsBudget, 0, 4000),
184
+ selfDesign: Object.freeze({
185
+ mode: input.selfDesign?.mode === true,
186
+ floorCoherence: numeric(input.selfDesign?.floorCoherence, DEFAULT_CONFIG.selfDesign.floorCoherence, 0, 1),
187
+ floorSafety: numeric(input.selfDesign?.floorSafety, DEFAULT_CONFIG.selfDesign.floorSafety, 0, 1),
188
+ powangBind: input.selfDesign?.powangBind !== false,
189
+ }),
163
190
  playbookBudget: numeric(input.playbookBudget, DEFAULT_CONFIG.playbookBudget, 100, 2000),
164
191
  // 2026-11-29:护栏白名单(规则 id 数组,最多 20 条)
165
192
  playbookPinned: Object.freeze((() => {
@@ -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