dsh-cortex-memory 0.4.148 → 0.4.161

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/README.md CHANGED
@@ -1,133 +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.148
11
- 提取器:dsh-cortex-extractors@0.3.5
12
- DSH:>=0.2.1-rc.2 <0.5.0
13
- Node:>=24
14
- 测试:523/523
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.148
38
- dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
39
- ```
40
-
41
- `dsh-cortex-extractors` 是可选的图片/音频入口;只做文字记忆时可以不装。
42
-
43
- ### Windows 一键包
44
-
45
- GitHub Release 提供:
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 并写理由。
46
18
 
47
- ```text
48
- cortex-memory-oneclick-0.4.148.zip
49
- ```
50
-
51
- 解压后双击 `install.cmd`。安装器会做 profile 检查、备份、SHA256 校验和可选路径迁移。
19
+ ### 工具
52
20
 
53
- ## 该装哪些
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` |
54
30
 
55
- | 需求 | 建议 |
56
- |---|---|
57
- | 只要文字记忆 | 主包 |
58
- | 看截图/图片 | 主包 + extractor,Windows OCR 即可 |
59
- | 扫描件/复杂排版 | 再加 Tesseract + chi_sim 语言包 |
60
- | 手写图片 | PaddleOCR + 本地模型目录 |
61
- | 中文音频 | Whisper.cpp + ggml-small,显式下载 |
62
- | 大模型 | 不安装;走 DSH 自己的模型服务 |
31
+ ## 装之前要知道
63
32
 
64
- 原则:
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`)时,抽取才会调用你配置的模型。
65
40
 
66
- ```text
67
- 核心零外部模型
68
- 提取器不自动下载模型
69
- Whisper 需显式 -Whisper
70
- PaddleOCR 需显式模型目录
71
- 不替用户填 LLM API key
72
- ```
41
+ ## 和谁一起用
73
42
 
74
- ## 开发与测试
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` 留成情景记忆。 |
75
49
 
76
- 必须使用 DSH 自带的 **Node 24** 跑测试/bench。系统 PATH 上如果是 Node 22,会低于 `engines.node >=24`,`node --test` 可能直接失败。
50
+ ## 需要额外装的软件
77
51
 
78
- ```text
79
- DSH 运行时 Node:24.21.0
80
- 系统 Node:仅作兼容性参考,不保证
81
- ```
52
+ 不需要。`node:sqlite` 是 Node 24+ 内置模块;插件没有原生扩展、不下载模型、不要密钥。
82
53
 
83
- CLI 默认读取 `~/.dsh/cortex-memory`;需要指定其他库时显式传 `--data <dir>`。
54
+ ## 安装
84
55
 
85
- ## 性能与边界
56
+ ### 一键包(Windows,推荐给不熟悉命令行的人)
86
57
 
87
- 已做:
58
+ 1. 解压本压缩包;
59
+ 2. 双击 `install.cmd`;
60
+ 3. 想先看它要做什么,就在 PowerShell 里跑 `.\install.ps1 -DryRun`(不会改任何东西)。
88
61
 
89
- ```text
90
- 主包测试:523/523
91
- 受控中文语义探针:recall@3 1.000 / MRR@3 0.917 / nDCG@3 0.938
92
- 受控探针延迟:p50 1.31ms / p95 4.07ms
93
- 真实图片 OCR:已跑通
94
- ```
62
+ 脚本会自动找 `dsh` 命令、校验 SHA256、备份 profile 的 `package.json`,再装进 `desktop` profile。装完**重启 DSH**。
95
63
 
96
- 必须说清楚:
64
+ ### npm
97
65
 
98
- ```text
99
- 受控语义探针是合成集,不是 LoCoMo/LongMemEval 官方分数
100
- ASR 还没有真实音频样本验收
101
- 技能沉淀当前为 0,管线存在但没有真实技能闭环
102
- 没有多代理集群验证
66
+ ```powershell
67
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.160
103
68
  ```
104
69
 
105
- Cortex 的定位是“本地可解释、可回滚、能长期长”的记忆系统,不把“功能多”宣传成“公开基准第一”。
106
-
107
- ## 和同类插件的区别
108
-
109
- | 插件 | 主要强项 | 和 Cortex 的差异 |
110
- |---|---|---|
111
- | `dsh-persona-memory` | MEMORY.md / USER.md 文件记忆、用户画像、跨会话注入、简单直接 | 更轻、更透明;没有完整时序事实、DSR、自我状态和召唤卡 |
112
- | `dsh-shiori` | Spark 卡、专题、触发词,卡/专题体验成熟 | 卡片层更专注;没有完整的情绪/关系/遗忘/自进化闭环 |
113
- | `dsh-memory` | SQLite FTS、三工具、轻量 | 简单检索;没有分层、反思和生活模块 |
114
- | `OpenViking` / `dsh-mnemon` | 平台化、多来源、上下文基础设施 | 更偏底座和 provider;Cortex 更偏“长期记忆 + 自我状态”一体 |
70
+ ## 卸载
115
71
 
116
- ## 数据与隐私
117
-
118
- ```text
119
- 默认数据目录:~/.dsh/cortex-memory
120
- 本地 SQLite
121
- 不把密钥写进 npm 包
122
- 不自动上传记忆
123
- 提取器默认不下载模型
72
+ ```powershell
73
+ dsh plugin --profile desktop remove dsh-cortex-memory
124
74
  ```
125
75
 
126
- ## 下载
76
+ 卸载插件不会删除记忆库;想清空请在卸载前先备份 `cortex.sqlite` 再手动删除。
127
77
 
128
- - npm 主包:`dsh-cortex-memory@0.4.148`
129
- - npm 提取器:`dsh-cortex-extractors@0.3.5`
130
- - GitHub Release:`v0.4.148`
131
- - Windows 一键包:`cortex-memory-oneclick-0.4.148.zip`
78
+ ## 许可
132
79
 
133
- 安装后重启 DSH,左侧出现「Cortex 记忆」入口。
80
+ MIT © 2026 Lh1314-China。问题请走 [Issues](https://github.com/Lh1314-China/dsh-cortex-memory/issues)。
package/bin/cortex.mjs CHANGED
File without changes
package/cordis.patch.yml CHANGED
@@ -1,8 +1,11 @@
1
- # dsh-cortex bundle patch.
1
+ # dsh-cortex-memory 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'.
4
7
  - insert:
5
8
  - id: dsh-cortex-memory
6
- name: 'dsh-cortex'
9
+ name: 'dsh-cortex-memory'
7
10
  config: {}
8
-
11
+
package/index.js CHANGED
@@ -31,7 +31,10 @@ export const Config = Schema ? Schema.object({
31
31
  readOnlyScopes: Schema.array(Schema.string()).default([]).description('只读共享 scope 列表'),
32
32
  scopeWriteGrants: Schema.array(Schema.any()).default([]).description('显式写授权:scope:agent 或 {grant, until}'),
33
33
  contextBudget: Schema.natural().default(2200).description('检索注入的 token 预算'),
34
- 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 字截断并给全文指针'),
35
38
  recallTimeoutMs: Schema.natural().default(1200).description('前台召回硬截止'),
36
39
  asyncJobs: Schema.boolean().default(true).description('允许后台任务'),
37
40
  captureSubagents: Schema.boolean().default(false).description('是否把子代理会话也写入记忆'),
@@ -92,7 +95,7 @@ export const Config = Schema ? Schema.object({
92
95
  api: Schema.boolean().default(true),
93
96
  autoFacts: Schema.boolean().default(false),
94
97
  autoDiary: Schema.boolean().default(false),
95
- autoDream: Schema.boolean().default(false),
98
+ autoDream: Schema.boolean().default(false),
96
99
  autoSleep: Schema.boolean().default(false),
97
100
  autoFeeling: Schema.boolean().default(false),
98
101
  autoEvolve: Schema.boolean().default(false),
@@ -103,9 +106,9 @@ export const Config = Schema ? Schema.object({
103
106
  llmFacts: Schema.boolean().default(false),
104
107
  tieredRecall: Schema.boolean().default(true),
105
108
  consolidateOnSleep: Schema.boolean().default(true),
106
- consolidateOnTick: Schema.boolean().default(false),
107
- consolidateOnTraceDelta: Schema.boolean().default(false),
108
- consolidateTraceDelta: Schema.number().default(20).description('新增活跃痕迹达到多少条才自动巩固'),
109
+ consolidateOnTick: Schema.boolean().default(false),
110
+ consolidateOnTraceDelta: Schema.boolean().default(false),
111
+ consolidateTraceDelta: Schema.number().default(20).description('新增活跃痕迹达到多少条才自动巩固'),
109
112
  consolidateTraceGapMinutes: Schema.number().default(30).description('两次自动巩固的最小间隔(分钟)'),
110
113
  inhibition: Schema.boolean().default(false),
111
114
  }).description('功能开关'),
@@ -191,7 +194,7 @@ export async function apply(ctx, config = {}) {
191
194
  name: 'cortex-self',
192
195
  order: 1.05,
193
196
  text: (context) => assembleSystemPrompt(cortex, {
194
- budgetTokens: config.promptBudget ?? 1600,
197
+ budgetTokens: config.promptBudget ?? 1800,
195
198
  recall: runtime?.recallText(context) ?? '',
196
199
  }).text,
197
200
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.148",
3
+ "version": "0.4.161",
4
4
  "description": "本地优先的分层记忆引擎:情景/语义/程序记忆、时序事实、DSR 遗忘、混合召回、自我状态、反思、守护与受控进化。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -20,6 +20,7 @@
20
20
  "index.js",
21
21
  "client.js",
22
22
  "src",
23
+ "scripts",
23
24
  "bench",
24
25
  "bin",
25
26
  "cordis.patch.yml",
@@ -88,4 +89,4 @@
88
89
  "check": "node --check index.js && node --check client.js",
89
90
  "test": "node --test test/unit/*.test.js test/integration/*.test.js"
90
91
  }
91
- }
92
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * 作者归属回填(2026-11-26 助手自建,一次性)。
3
+ *
4
+ * 写入侧已在 src/engines/encode.js 接线:author_kind / author_id / author_confidence。
5
+ * 本脚本补历史行,并把分类规则落成 SQL,规则与 classifyAuthor() 保持一致:
6
+ * imported ← source 以 shiori: 开头 / source='import' / metadata.imported
7
+ * derived ← source='extractor' / metadata.derivedFrom
8
+ * self ← actor ∈ {self, system} / source ∈ {agency:inner, policy, config} / kind='reflection'
9
+ * captured ← 其余
10
+ *
11
+ * 安全:默认 dry-run;--apply 才写;单事务;只填 author_* 三列,不改 content / events;
12
+ * 已经显式写过 author_kind(不等于默认 captured 或 author_id 非空)的行跳过。
13
+ */
14
+ import { DatabaseSync } from 'node:sqlite';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ function parseArgs(argv) {
19
+ const out = { apply: false, db: null };
20
+ for (let i = 0; i < argv.length; i += 1) {
21
+ const arg = argv[i];
22
+ if (arg === '--apply') out.apply = true;
23
+ else if (arg === '--dry-run') out.apply = false;
24
+ else if (arg === '--db') out.db = argv[++i];
25
+ }
26
+ return out;
27
+ }
28
+
29
+ const CLASSIFY = `
30
+ CASE
31
+ WHEN source LIKE 'shiori:%' OR source = 'import' OR metadata_json LIKE '%"imported":true%' THEN 'imported'
32
+ WHEN source = 'extractor' OR metadata_json LIKE '%"derivedFrom"%' THEN 'derived'
33
+ WHEN actor IN ('self', 'system') OR source IN ('agency:inner', 'policy', 'config') OR kind = 'reflection' THEN 'self'
34
+ ELSE 'captured'
35
+ END
36
+ `;
37
+
38
+ const CONFIDENCE = `
39
+ CASE
40
+ WHEN ${CLASSIFY} = 'imported' THEN 0.6
41
+ WHEN ${CLASSIFY} = 'self' THEN 0.7
42
+ WHEN ${CLASSIFY} = 'derived' THEN 0.7
43
+ WHEN actor = 'user' THEN 0.8
44
+ ELSE 0.65
45
+ END
46
+ `;
47
+
48
+ function main() {
49
+ const args = parseArgs(process.argv.slice(2));
50
+ if (!args.db) {
51
+ console.error('缺少 --db <path>');
52
+ process.exit(2);
53
+ }
54
+ const dbPath = path.resolve(args.db);
55
+ if (!fs.existsSync(dbPath)) {
56
+ console.error(`库不存在:${dbPath}`);
57
+ process.exit(2);
58
+ }
59
+ console.log(`库:${dbPath}`);
60
+ console.log(`模式:${args.apply ? 'APPLY(会写)' : 'DRY-RUN(只演不写)'}`);
61
+
62
+ const db = new DatabaseSync(dbPath);
63
+
64
+ const columns = db.prepare('PRAGMA table_info(traces)').all().map((column) => column.name);
65
+ const missing = ['author_kind', 'author_id', 'author_confidence'].filter((name) => !columns.includes(name));
66
+ console.log(missing.length ? `缺列,需要先加:${missing.join(', ')}` : '三列都在。');
67
+ if (missing.length && !args.apply) {
68
+ console.log('\nDRY-RUN:会先 ALTER TABLE 加列,再按规则回填。');
69
+ } else if (missing.length) {
70
+ if (!columns.includes('author_kind')) db.exec("ALTER TABLE traces ADD COLUMN author_kind TEXT NOT NULL DEFAULT 'captured'");
71
+ if (!columns.includes('author_id')) db.exec('ALTER TABLE traces ADD COLUMN author_id TEXT');
72
+ if (!columns.includes('author_confidence')) db.exec('ALTER TABLE traces ADD COLUMN author_confidence REAL');
73
+ console.log('已加三列。');
74
+ }
75
+
76
+ const preview = db.prepare(`
77
+ SELECT ${CLASSIFY} AS calc_kind, COUNT(*) AS n FROM traces GROUP BY calc_kind ORDER BY n DESC
78
+ `).all();
79
+ console.log('\n-- 分类预览(全表)--');
80
+ for (const row of preview) console.log(`${row.calc_kind}\t${row.n}`);
81
+
82
+ const target = missing.length
83
+ ? db.prepare('SELECT COUNT(*) AS n FROM traces').get()
84
+ : db.prepare(`
85
+ SELECT COUNT(*) AS n FROM traces
86
+ WHERE (author_kind IS NULL OR author_kind = 'captured') AND author_id IS NULL
87
+ `).get();
88
+ console.log(`\n会回填:${target.n} 条(已有 author_id 的显式行跳过)`);
89
+
90
+ if (!args.apply) {
91
+ console.log('DRY-RUN 结束,没有写入。加 --apply 才写。');
92
+ db.close();
93
+ return;
94
+ }
95
+
96
+ const nowIso = new Date().toISOString();
97
+ db.exec('BEGIN');
98
+ let changed = 0;
99
+ try {
100
+ changed = db.prepare(`
101
+ UPDATE traces
102
+ SET author_kind = ${CLASSIFY},
103
+ author_id = actor,
104
+ author_confidence = ${CONFIDENCE}
105
+ WHERE (author_kind IS NULL OR author_kind = 'captured') AND author_id IS NULL
106
+ `).run().changes;
107
+ try {
108
+ db.prepare(`
109
+ INSERT INTO audit (id, at, actor, action, target_type, target_id, detail_json)
110
+ VALUES (?, ?, 'self', 'trace.author.backfill', 'db', NULL, ?)
111
+ `).run(`aud_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`, nowIso,
112
+ JSON.stringify({ changed, script: 'backfill-author.mjs' }));
113
+ } catch (error) {
114
+ console.warn(`审计写入失败(不影响回填):${error.message}`);
115
+ }
116
+ db.exec('COMMIT');
117
+ } catch (error) {
118
+ db.exec('ROLLBACK');
119
+ console.error(`回填失败已回滚:${error.message}`);
120
+ db.close();
121
+ process.exit(1);
122
+ }
123
+
124
+ const after = db.prepare(`
125
+ SELECT COALESCE(author_kind, 'null') AS kind_value, COUNT(*) AS n FROM traces GROUP BY kind_value ORDER BY n DESC
126
+ `).all();
127
+ console.log(`\n已改 ${changed} 条。-- 改后分布 --`);
128
+ for (const row of after) console.log(`${row.kind_value}\t${row.n}`);
129
+ db.close();
130
+ }
131
+
132
+ main();
@@ -0,0 +1,142 @@
1
+ /**
2
+ * DSR 初值回填(2026-11-26 助手自建,一次性)。
3
+ *
4
+ * 背景:initialStability() 从 0.4.x 起就存在却从未被调用,活库里 3088/3089 条
5
+ * traces 的 stability 恒为 1——identity/promise 与闲聊同速衰减。写入侧已在
6
+ * src/engines/encode.js 接线;本脚本只补历史行。
7
+ *
8
+ * 安全约束:
9
+ * - 默认 dry-run,必须显式 --apply 才写;
10
+ * - 只改 stability = 1 的行(已经复习过、被 DSR 更新过的行一律不碰);
11
+ * - 不改 content / 不删行 / 不动 events 哈希链;
12
+ * - 写前打印每条 kind 的改前改后对照,写后校验分布;
13
+ * - --db 指定库文件,--dry-run 显式表示只演不写。
14
+ *
15
+ * 用法:
16
+ * node scripts/backfill-stability.mjs --db <path> # 演练
17
+ * node scripts/backfill-stability.mjs --db <path> --apply # 真写
18
+ */
19
+ import { DatabaseSync } from 'node:sqlite';
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { initialStability, dsrTypeForKind, TYPE_BASE_STABILITY } from '../src/memory/dsr.js';
23
+
24
+ function parseArgs(argv) {
25
+ const out = { apply: false, db: null, maximumStability: 3650 };
26
+ for (let i = 0; i < argv.length; i += 1) {
27
+ const arg = argv[i];
28
+ if (arg === '--apply') out.apply = true;
29
+ else if (arg === '--dry-run') out.apply = false;
30
+ else if (arg === '--db') out.db = argv[++i];
31
+ else if (arg === '--max') out.maximumStability = Number(argv[++i]) || 3650;
32
+ }
33
+ return out;
34
+ }
35
+
36
+ function main() {
37
+ const args = parseArgs(process.argv.slice(2));
38
+ if (!args.db) {
39
+ console.error('缺少 --db <path>');
40
+ process.exit(2);
41
+ }
42
+ const dbPath = path.resolve(args.db);
43
+ if (!fs.existsSync(dbPath)) {
44
+ console.error(`库不存在:${dbPath}`);
45
+ process.exit(2);
46
+ }
47
+
48
+ console.log(`库:${dbPath}`);
49
+ console.log(`模式:${args.apply ? 'APPLY(会写)' : 'DRY-RUN(只演不写)'}`);
50
+
51
+ const db = new DatabaseSync(dbPath);
52
+
53
+ const before = db.prepare(`
54
+ SELECT kind, COUNT(*) n, SUM(CASE WHEN stability = 1 THEN 1 ELSE 0 END) eq1
55
+ FROM traces GROUP BY kind ORDER BY n DESC
56
+ `).all();
57
+ console.log('\n-- 改前 --');
58
+ for (const row of before) console.log(`${row.kind}\t总 ${row.n}\tstability=1 ${row.eq1}`);
59
+
60
+ const rows = db.prepare(`
61
+ SELECT id, kind, importance, salience, confidence, valence, stability, recorded_at
62
+ FROM traces WHERE stability = 1
63
+ `).all();
64
+
65
+ const plan = [];
66
+ const perKind = new Map();
67
+ for (const row of rows) {
68
+ const next = initialStability({
69
+ type: dsrTypeForKind(row.kind),
70
+ importance: row.importance,
71
+ salience: row.salience,
72
+ confidence: row.confidence,
73
+ valence: row.valence,
74
+ maximumStability: args.maximumStability,
75
+ });
76
+ if (!Number.isFinite(next) || Math.abs(next - row.stability) < 1e-9) continue;
77
+ plan.push({ id: row.id, from: row.stability, to: next });
78
+ const bucket = perKind.get(row.kind) ?? { kind: row.kind, n: 0, min: next, max: next, sum: 0 };
79
+ bucket.n += 1;
80
+ bucket.min = Math.min(bucket.min, next);
81
+ bucket.max = Math.max(bucket.max, next);
82
+ bucket.sum += next;
83
+ perKind.set(row.kind, bucket);
84
+ }
85
+
86
+ console.log('\n-- 将改(按 kind)--');
87
+ for (const bucket of [...perKind.values()].sort((a, b) => b.n - a.n)) {
88
+ const dsrType = dsrTypeForKind(bucket.kind);
89
+ const base = TYPE_BASE_STABILITY[dsrType] ?? TYPE_BASE_STABILITY.episodic;
90
+ console.log(`${bucket.kind} → ${dsrType}\t${bucket.n} 条\t类型基座 ${base} 天\t新初值 ${bucket.min.toFixed(2)}–${bucket.max.toFixed(2)}\t均值 ${(bucket.sum / bucket.n).toFixed(2)}`);
91
+ }
92
+ console.log(`合计:${plan.length} 条会改(不动 stability≠1 的行)`);
93
+
94
+ if (!args.apply) {
95
+ console.log('\nDRY-RUN 结束,没有写入。加 --apply 才写。');
96
+ db.close();
97
+ return;
98
+ }
99
+ if (plan.length === 0) {
100
+ console.log('\n没有需要改的行。');
101
+ db.close();
102
+ return;
103
+ }
104
+
105
+ const tx = db.prepare('UPDATE traces SET stability = ?, updated_at = ? WHERE id = ? AND stability = 1');
106
+ const nowIso = new Date().toISOString();
107
+ let changed = 0;
108
+ db.exec('BEGIN');
109
+ try {
110
+ for (const item of plan) {
111
+ changed += tx.run(item.to, nowIso, item.id).changes;
112
+ }
113
+ // 审计:不改 events 哈希链结构,只追加一行 audit 记录。
114
+ try {
115
+ db.prepare(`
116
+ INSERT INTO audit (id, at, actor, action, target_type, target_id, detail_json)
117
+ VALUES (?, ?, 'self', 'trace.stability.backfill', 'db', NULL, ?)
118
+ `).run(`aud_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`, nowIso,
119
+ JSON.stringify({ changed, scanned: rows.length, maximumStability: args.maximumStability, script: 'backfill-stability.mjs' }));
120
+ } catch (error) {
121
+ console.warn(`审计写入失败(不影响回填):${error.message}`);
122
+ }
123
+ db.exec('COMMIT');
124
+ } catch (error) {
125
+ db.exec('ROLLBACK');
126
+ console.error(`回填失败已回滚:${error.message}`);
127
+ db.close();
128
+ process.exit(1);
129
+ }
130
+
131
+ console.log(`\n已改 ${changed} 条。`);
132
+
133
+ const after = db.prepare(`
134
+ SELECT CASE WHEN stability <= 1 THEN '=1' WHEN stability < 7 THEN '<7' WHEN stability < 30 THEN '<30' ELSE '>=30' END AS bucket,
135
+ COUNT(*) n FROM traces GROUP BY bucket ORDER BY n DESC
136
+ `).all();
137
+ console.log('-- 改后稳定性分布 --');
138
+ for (const row of after) console.log(`${row.bucket}\t${row.n}`);
139
+ db.close();
140
+ }
141
+
142
+ main();
@@ -12,11 +12,19 @@ export const DEFAULT_CONFIG = Object.freeze({
12
12
  scope: 'global',
13
13
  persona: Object.freeze({ selfName: '助手', userAddress: '你' }),
14
14
  contextBudget: 2200,
15
- promptBudget: 1600,
15
+ promptBudget: 1800,
16
16
  readOnlyScopes: Object.freeze([]),
17
17
  scopeWriteGrants: Object.freeze([]),
18
18
  identityBudget: 360,
19
- workingBudget: 800,
19
+ // 2026-11-29:fit 修好单位后 800 是「真 800 token」,工作记忆会独吞并挤掉尾注/意图。
20
+ // 收到 700,留出后段的份额(实测总注入 ~1530/1600)。
21
+ workingBudget: 700,
22
+ // 2026-11-29:playbook 段预算(原来硬编码 260,只放得下 2 条长规则)。420 能放 3-4 条。
23
+ playbookBudget: 420,
24
+ // 2026-11-29:护栏白名单。投票只表达「有用」,表达不了「重要」;
25
+ // 实测:投完票后「中文/JSON 别用 PowerShell」靠 created_at 把「用户划的线」顶掉。
26
+ // 白名单里的规则在 playbook.render 永远排最前。
27
+ playbookPinned: Object.freeze([]),
20
28
  recallTimeoutMs: 1200,
21
29
  recentMinMatch: 0.12,
22
30
  recentImportanceFloor: 0.8,
@@ -46,12 +54,27 @@ export const DEFAULT_CONFIG = Object.freeze({
46
54
  archiveImportance: 0.35,
47
55
  minAgeDays: 14,
48
56
  reviewCap: 60,
57
+ // 2026-11-26:写入时按 kind/importance/salience/valence 计算初值稳定性。
58
+ // 关掉即回到 0.4.x 的旧行为(一律 stability=1)。
59
+ initialStability: true,
49
60
  }),
50
61
  compression: Object.freeze({
51
62
  coverageThreshold: 0.8,
52
63
  minAgeDays: 7,
53
64
  keepEvidencePointers: true,
54
65
  }),
66
+ // 2026-11-26:自我写入的闸。手动反思必须有外部硬证据(被纠正/失败/反对);
67
+ // 定时巩固(auto/backfill)不受此限。
68
+ selfWrite: Object.freeze({
69
+ reflectionRequiresEvidence: true,
70
+ }),
71
+ // 2026-11-27 助手自建:工程模式。大工程期间 coherence/safety 只升不降、energy 不扣,
72
+ // 避免长篇技术讨论被当成威胁,把仪表打穿。
73
+ selfDesign: Object.freeze({
74
+ mode: false,
75
+ floorCoherence: 0.3,
76
+ floorSafety: 0.2,
77
+ }),
55
78
  features: Object.freeze({
56
79
  recall: true,
57
80
  capture: true,
@@ -95,6 +118,7 @@ export function normalizeConfig(raw = {}) {
95
118
  const featuresInput = input.features && typeof input.features === 'object' ? input.features : {};
96
119
  const personaInput = input.persona && typeof input.persona === 'object' ? input.persona : {};
97
120
  const evolutionInput = input.evolution && typeof input.evolution === 'object' ? input.evolution : {};
121
+ const selfWriteInput = input.selfWrite && typeof input.selfWrite === 'object' ? input.selfWrite : {};
98
122
  const scope = typeof input.scope === 'string' && input.scope.trim() ? input.scope.trim() : DEFAULT_CONFIG.scope;
99
123
 
100
124
  return Object.freeze({
@@ -136,6 +160,23 @@ export function normalizeConfig(raw = {}) {
136
160
  promptBudget: numeric(input.promptBudget, DEFAULT_CONFIG.promptBudget, 256, 8000),
137
161
  identityBudget: numeric(input.identityBudget, DEFAULT_CONFIG.identityBudget, 64, 4000),
138
162
  workingBudget: numeric(input.workingBudget, DEFAULT_CONFIG.workingBudget, 128, 8000),
163
+ playbookBudget: numeric(input.playbookBudget, DEFAULT_CONFIG.playbookBudget, 100, 2000),
164
+ // 2026-11-29:护栏白名单(规则 id 数组,最多 20 条)
165
+ playbookPinned: Object.freeze((() => {
166
+ const raw = input.playbookPinned;
167
+ const out = [];
168
+ const seen = new Set();
169
+ if (Array.isArray(raw)) {
170
+ for (const item of raw) {
171
+ const id = String(item ?? '').trim();
172
+ if (!id || seen.has(id)) continue;
173
+ seen.add(id);
174
+ out.push(id);
175
+ if (out.length >= 3) break;
176
+ }
177
+ }
178
+ return out;
179
+ })()),
139
180
  recallTimeoutMs: numeric(input.recallTimeoutMs, DEFAULT_CONFIG.recallTimeoutMs, 100, 5000),
140
181
  recentMinMatch: numeric(input.recentMinMatch, DEFAULT_CONFIG.recentMinMatch, 0, 1),
141
182
  recentImportanceFloor: numeric(input.recentImportanceFloor, DEFAULT_CONFIG.recentImportanceFloor, 0, 1),
@@ -161,12 +202,16 @@ export function normalizeConfig(raw = {}) {
161
202
  archiveImportance: numeric(dsrInput.archiveImportance, DEFAULT_CONFIG.dsr.archiveImportance, 0, 1),
162
203
  minAgeDays: numeric(dsrInput.minAgeDays, DEFAULT_CONFIG.dsr.minAgeDays, 0, 3650),
163
204
  reviewCap: numeric(dsrInput.reviewCap, DEFAULT_CONFIG.dsr.reviewCap, 1, 3650),
205
+ initialStability: dsrInput.initialStability !== false,
164
206
  }),
165
207
  compression: Object.freeze({
166
208
  coverageThreshold: numeric(compressionInput.coverageThreshold, DEFAULT_CONFIG.compression.coverageThreshold, 0.1, 1),
167
209
  minAgeDays: numeric(compressionInput.minAgeDays, DEFAULT_CONFIG.compression.minAgeDays, 0, 3650),
168
210
  keepEvidencePointers: compressionInput.keepEvidencePointers !== false,
169
211
  }),
212
+ selfWrite: Object.freeze({
213
+ reflectionRequiresEvidence: selfWriteInput.reflectionRequiresEvidence !== false,
214
+ }),
170
215
  features: Object.freeze({
171
216
  ...DEFAULT_CONFIG.features,
172
217
  ...featuresInput,
@@ -21,7 +21,7 @@ export function createAutonomyEngine({
21
21
  if (executed.length >= max) break;
22
22
  if (intention.kind === 'consolidate' && reflect) {
23
23
  try {
24
- const result = reflect.reflect({ scopeId, windowDays: 1, now: at });
24
+ const result = reflect.reflect({ scopeId, windowDays: 1, now: at, trigger: 'auto' });
25
25
  executed.push({ id: intention.id, kind: intention.kind, result });
26
26
  initiativeStore.mark(intention.id, 'acted', { kind: 'reflect', summaryId: result?.summary?.id ?? null, skipped: result?.skipped ?? false });
27
27
  } catch (error) {
@@ -88,7 +88,11 @@ export function createConsolidationEngine({ db, traces, summaries = null, audit
88
88
  // used to spell this out separately, and the merge branch forgot reflections: a
89
89
  // low-importance reflection could be merged away as a source.
90
90
  function isProtected(trace, protect = PROTECTED_IMPORTANCE) {
91
- return Number(trace?.importance ?? 0) >= protect || trace?.kind === 'reflection';
91
+ // 2026-11-28:自己写下的记忆默认受保护——不被合并、不被归档。
92
+ // 这是「让那 3% 变厚」的一半:光加权不够,还得不被吃掉。
93
+ return Number(trace?.importance ?? 0) >= protect
94
+ || trace?.kind === 'reflection'
95
+ || String(trace?.authorKind ?? '') === 'self';
92
96
  }
93
97
 
94
98
  function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allowProtectedMerge = false } = {}) {