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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.147",
3
+ "version": "0.4.160",
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",
@@ -28,16 +29,9 @@
28
29
  "README.md",
29
30
  "examples",
30
31
  "LICENSE",
31
- "test",
32
32
  "CHANGELOG.md",
33
33
  "docs"
34
34
  ],
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
35
  "engines": {
42
36
  "node": ">=24",
43
37
  "dsh": ">=0.2.1-rc.2 <0.5.0"
@@ -88,5 +82,11 @@
88
82
  },
89
83
  "bugs": {
90
84
  "url": "https://github.com/Lh1314-China/dsh-cortex-memory/issues"
85
+ },
86
+ "scripts": {
87
+ "test:unit": "node --test test/unit/*.test.js",
88
+ "bench": "node bench/run.js",
89
+ "check": "node --check index.js && node --check client.js",
90
+ "test": "node --test test/unit/*.test.js test/integration/*.test.js"
91
91
  }
92
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();
@@ -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
 
@@ -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) {
@@ -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
  }
@@ -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 } = {}) {
@@ -163,7 +167,7 @@ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allo
163
167
  //
164
168
  // Selection is the opposite of 0.4.116→0.4.130: those versions sorted by
165
169
  // 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
170
+ // prompt protects (99% of the production store is >= 0.7 and the top slice is all
167
171
  // 1.0) and could only answer keep. Rank the other end first instead:
168
172
  // 1. no summary covers the trace yet,
169
173
  // 2. it was not shown to the model in the last 24h,
@@ -470,7 +474,7 @@ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allo
470
474
  let droppedGroups = 0;
471
475
  for (const group of clusters.values()) {
472
476
  if (group.length < 2) continue;
473
- // A production store has 75% of active traces at importance >= 0.95, so "two protected
477
+ // Live store has 75% of active traces at importance >= 0.95, so "two protected
474
478
  // members" is the normal case, not the exception. Dedupe has already proved the
475
479
  // members are near-duplicates (Jaccard >= simThreshold), so keeping N copies buys
476
480
  // nothing; reflections were excluded from the pool above.
@@ -1,6 +1,7 @@
1
1
  import { hashText } from '../core/ids.js';
2
2
  import { clamp, nowIso } from '../core/time.js';
3
3
  import { estimateTokens } from '../memory/tokenizer.js';
4
+ import { initialStability, dsrTypeForKind } from '../memory/dsr.js';
4
5
  import { CortexError, ERROR_CODES } from '../core/errors.js';
5
6
  import { scanText } from '../guardian/scanner.js';
6
7
 
@@ -30,7 +31,7 @@ export function isInjectedNoise(value) {
30
31
 
31
32
  export function scoreTraceText(text, { kind = null, importance = null } = {}) {
32
33
  const value = String(text ?? '').trim();
33
- let importanceScore = Number.isFinite(importance) ? clamp(importance, 0, 1) : 0.42;
34
+ let importanceScore = Number.isFinite(importance) ? clamp(importance, 0, 1) : 0.26;
34
35
  let candidateKind = kind || 'utterance';
35
36
  let valence = 0;
36
37
  if (!kind) {
@@ -47,8 +48,8 @@ export function scoreTraceText(text, { kind = null, importance = null } = {}) {
47
48
  if (pattern.test(value)) valence = v;
48
49
  }
49
50
  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;
51
+ importanceScore += Math.min(0.06, value.length / 1000);
52
+ if (salience > 0.6) importanceScore += 0.05;
52
53
  return {
53
54
  kind: candidateKind,
54
55
  importance: clamp(importanceScore, 0, 1),
@@ -76,6 +77,41 @@ export function createEncodeEngine({
76
77
  if (!events || !traces) throw new CortexError(ERROR_CODES.INVALID_INPUT, 'encode engine needs events and traces');
77
78
  const minChars = config.minContentChars ?? 2;
78
79
  const minCompression = config.minCompressionValue ?? 0.08;
80
+ // 2026-11-26 助手自改:DSR 初值层(initialStability + TYPE_BASE_STABILITY)
81
+ // 从落地起就有实现却从未接线,活库里 3088/3089 条 stability 恒为 1——
82
+ // identity/promise 与闲聊同速衰减。默认接线,可用 dsr.initialStability=false 单点关回旧行为。
83
+ const useInitialStability = config.dsr?.initialStability !== false;
84
+ const maximumStability = Number(config.dsr?.maximumStability) || 3650;
85
+ // 2026-11-26 助手自建:作者归属。只在写入时定,不参与检索打分——
86
+ // 先把「这条是谁写的」记准,再谈要不要按来源排序。
87
+ const markPendingSelfWrites = config.features?.pendingSelfWrites !== false;
88
+
89
+ const SELF_ACTORS = new Set(['self', 'system']);
90
+ const SELF_SOURCES = new Set(['agency:inner', 'policy', 'config']);
91
+
92
+ function classifyAuthor({ input, kind }) {
93
+ if (typeof input.authorKind === 'string' && input.authorKind) {
94
+ return { authorKind: input.authorKind, authorId: input.authorId ?? null, authorConfidence: input.authorConfidence ?? null };
95
+ }
96
+ const actor = String(input.actor ?? 'user');
97
+ const source = String(input.source ?? '');
98
+ const metadata = input.metadata && typeof input.metadata === 'object' ? input.metadata : {};
99
+ const authorId = actor;
100
+ // 2026-11-27:副脑产出走独立归属,和「我写的」「捕获的」分开。
101
+ if (metadata.subbrain === true || source.startsWith('subbrain:') || input.scopeId === 'subbrain') {
102
+ return { authorKind: 'subbrain', authorId: input.authorId ?? authorId, authorConfidence: input.authorConfidence ?? 0.6 };
103
+ }
104
+ if (metadata.imported === true || source.startsWith('shiori:') || source === 'import') {
105
+ return { authorKind: 'imported', authorId, authorConfidence: input.authorConfidence ?? 0.6 };
106
+ }
107
+ if (source === 'extractor' || metadata.derivedFrom) {
108
+ return { authorKind: 'derived', authorId, authorConfidence: input.authorConfidence ?? 0.7 };
109
+ }
110
+ if (SELF_ACTORS.has(actor) || SELF_SOURCES.has(source) || kind === 'reflection') {
111
+ return { authorKind: 'self', authorId, authorConfidence: input.authorConfidence ?? 0.7 };
112
+ }
113
+ return { authorKind: 'captured', authorId, authorConfidence: input.authorConfidence ?? (actor === 'user' ? 0.8 : 0.65) };
114
+ }
79
115
 
80
116
  function applyFacts(rawFacts, { scopeId, recordedAt, sourceEventId }) {
81
117
  const resolved = [];
@@ -161,7 +197,7 @@ export function createEncodeEngine({
161
197
  payload: {
162
198
  textHash: hashText(text),
163
199
  textLength: text.length,
164
- source: input.source || input.actor || 'user',
200
+ source: input.source ?? null,
165
201
  kind: scored.kind,
166
202
  explicit,
167
203
  },
@@ -189,6 +225,29 @@ export function createEncodeEngine({
189
225
  return { skipped: true, reason: 'duplicate', event, trace: duplicate, facts: factsApplied, edgeCandidates };
190
226
  }
191
227
 
228
+ const confidence = input.confidence ?? (input.actor === 'user' ? 0.8 : 0.65);
229
+ const authorship = classifyAuthor({ input, kind: scored.kind });
230
+ const pending = authorship.authorKind === 'self' && markPendingSelfWrites;
231
+ const metadata = input.metadata && typeof input.metadata === 'object' && !Array.isArray(input.metadata)
232
+ ? { ...input.metadata }
233
+ : {};
234
+ if (pending && metadata.pending !== false) {
235
+ metadata.pending = true;
236
+ metadata.pendingSince = recordedAt;
237
+ }
238
+ const stability = Number.isFinite(input.stability)
239
+ ? input.stability
240
+ : (useInitialStability
241
+ ? initialStability({
242
+ type: dsrTypeForKind(scored.kind),
243
+ importance: scored.importance,
244
+ salience: scored.salience,
245
+ confidence,
246
+ valence: scored.valence,
247
+ maximumStability,
248
+ })
249
+ : 1);
250
+
192
251
  const trace = traces.insert({
193
252
  scopeId,
194
253
  kind: scored.kind,
@@ -197,20 +256,24 @@ export function createEncodeEngine({
197
256
  summary: input.summary || null,
198
257
  keywords: input.keywords || [],
199
258
  tags: input.tags || [],
200
- metadata: input.metadata && typeof input.metadata === 'object' ? input.metadata : {},
259
+ metadata,
201
260
  eventId: event.id,
202
261
  sessionId: input.sessionId || null,
203
262
  turnId: input.turnId || null,
204
263
  actor: input.actor || 'user',
205
- source: input.source || input.actor || 'user',
264
+ source: input.source ?? null,
265
+ authorKind: authorship.authorKind,
266
+ authorId: authorship.authorId,
267
+ authorConfidence: authorship.authorConfidence,
206
268
  validAt: input.validAt || recordedAt,
207
269
  recordedAt,
208
270
  importance: scored.importance,
209
- confidence: input.confidence ?? (input.actor === 'user' ? 0.8 : 0.65),
271
+ confidence,
210
272
  salience: scored.salience,
211
273
  valence: scored.valence,
212
274
  arousal: scored.arousal,
213
275
  sensitivity: sensitivity,
276
+ stability,
214
277
  });
215
278
 
216
279
  const resolvedFacts = applyFacts(input.facts, { scopeId, recordedAt, sourceEventId: event.id });
@@ -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;
@@ -275,7 +275,8 @@ export function createLifeEngine({
275
275
  const purged = working?.purgeExpired({ scopeId, at }) ?? 0;
276
276
  let reflection = null;
277
277
  try {
278
- reflection = reflect?.reflect?.({ scopeId, windowDays, now: at }) ?? null;
278
+ // 睡眠是定时巩固,不是「我决定要反思」——走 auto 通道,不受手动反思的证据闸限制。
279
+ reflection = reflect?.reflect?.({ scopeId, windowDays, now: at, trigger: 'auto' }) ?? null;
279
280
  } catch {
280
281
  reflection = null;
281
282
  }