dsh-cortex-memory 0.4.22 → 0.4.146

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 (165) hide show
  1. package/CHANGELOG.md +2216 -7
  2. package/README.md +9 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +7 -7
  5. package/bench/synthetic.js +2 -2
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/cordis.patch.yml +1 -1
  10. package/docs/install-windows.md +2 -2
  11. package/docs/models.md +1 -1
  12. package/docs/quota-compaction-design.md +175 -0
  13. package/index.js +27 -3
  14. package/package.json +3 -3
  15. package/src/adapters/shiori.js +1 -1
  16. package/src/api/routes.js +1 -1
  17. package/src/core/feature-overrides.js +2 -2
  18. package/src/engines/compression.js +172 -3
  19. package/src/engines/consolidate.js +397 -26
  20. package/src/engines/encode.js +16 -3
  21. package/src/engines/extract.js +72 -8
  22. package/src/engines/fact-guard.js +51 -0
  23. package/src/engines/health.js +263 -3
  24. package/src/engines/inhibition.js +39 -0
  25. package/src/engines/life.js +12 -1
  26. package/src/engines/llm-facts.js +12 -9
  27. package/src/engines/narrative.js +150 -13
  28. package/src/engines/reflect.js +172 -14
  29. package/src/engines/retrieve.js +44 -5
  30. package/src/engines/summary-coverage.js +62 -0
  31. package/src/engines/summary-dedupe.js +77 -0
  32. package/src/engines/summon-rank.js +132 -0
  33. package/src/host/runtime.js +64 -4
  34. package/src/host/scheduler.js +224 -3
  35. package/src/llm/adapter.js +29 -8
  36. package/src/memory/query.js +1 -1
  37. package/src/memory/spacing.js +15 -0
  38. package/src/memory/tokenizer.js +1 -1
  39. package/src/prompt/tiers.js +88 -12
  40. package/src/self/alias.js +25 -0
  41. package/src/self/emotion.js +3 -1
  42. package/src/self/relationship.js +44 -13
  43. package/src/self/state.js +20 -2
  44. package/src/self/working.js +34 -3
  45. package/src/service/cortex.js +493 -53
  46. package/src/store/repositories/facts.js +34 -1
  47. package/src/store/repositories/summaries.js +8 -1
  48. package/src/store/repositories/traces.js +22 -2
  49. package/src/tools/definitions.js +118 -4
  50. package/src/vector/index.js +96 -7
  51. package/test/integration/acceptance.test.js +47 -47
  52. package/test/integration/api-contract.test.js +17 -17
  53. package/test/integration/backup-privacy.test.js +10 -10
  54. package/test/integration/consolidate.test.js +6 -2
  55. package/test/integration/edge-cases.test.js +16 -15
  56. package/test/integration/exchange.test.js +26 -26
  57. package/test/integration/life-loop.test.js +7 -6
  58. package/test/integration/load.test.js +4 -4
  59. package/test/integration/policy-query-api.test.js +4 -4
  60. package/test/integration/resilience-writes.test.js +7 -7
  61. package/test/integration/tools-contract.test.js +57 -57
  62. package/test/unit/alias.test.js +87 -0
  63. package/test/unit/api-client.test.js +3 -3
  64. package/test/unit/api-validate.test.js +3 -3
  65. package/test/unit/api.test.js +3 -3
  66. package/test/unit/auto-reflect.test.js +141 -0
  67. package/test/unit/capture-filter.test.js +296 -0
  68. package/test/unit/compaction-preview.test.js +91 -0
  69. package/test/unit/compression.test.js +4 -4
  70. package/test/unit/consolidate-dedupe.test.js +174 -0
  71. package/test/unit/consolidate-errors.test.js +63 -0
  72. package/test/unit/consolidate-gate.test.js +26 -0
  73. package/test/unit/consolidate-preview.test.js +168 -0
  74. package/test/unit/consolidate-protection.test.js +156 -0
  75. package/test/unit/consolidate-reason.test.js +206 -0
  76. package/test/unit/consolidate-retry.test.js +91 -0
  77. package/test/unit/consolidate-selection.test.js +103 -0
  78. package/test/unit/core.test.js +11 -11
  79. package/test/unit/coverage-rewrite.test.js +38 -0
  80. package/test/unit/dedupe-episodes.test.js +34 -0
  81. package/test/unit/dedupe-threshold.test.js +14 -0
  82. package/test/unit/develop.test.js +4 -4
  83. package/test/unit/edges-candidates.test.js +2 -2
  84. package/test/unit/emotion.test.js +2 -1
  85. package/test/unit/encode.test.js +6 -6
  86. package/test/unit/evolution.test.js +5 -5
  87. package/test/unit/extract-question.test.js +41 -0
  88. package/test/unit/fact-guard.test.js +51 -0
  89. package/test/unit/fact-noise-llm.test.js +44 -0
  90. package/test/unit/facts-belief.test.js +4 -4
  91. package/test/unit/facts-compat.test.js +62 -0
  92. package/test/unit/facts.test.js +5 -5
  93. package/test/unit/fts-migration.test.js +6 -6
  94. package/test/unit/growth-reflect.test.js +4 -3
  95. package/test/unit/guardian.test.js +1 -1
  96. package/test/unit/health-consolidation.test.js +52 -0
  97. package/test/unit/health-fts-scope.test.js +33 -0
  98. package/test/unit/health-privacy.test.js +6 -6
  99. package/test/unit/health-summaries.test.js +24 -0
  100. package/test/unit/health-text-maintain.test.js +33 -0
  101. package/test/unit/health-today.test.js +45 -0
  102. package/test/unit/host-runtime.test.js +8 -8
  103. package/test/unit/host.test.js +1 -1
  104. package/test/unit/induct-evaluate.test.js +3 -3
  105. package/test/unit/ingest-extracted.test.js +3 -3
  106. package/test/unit/inhibition.test.js +90 -0
  107. package/test/unit/jobs.test.js +4 -4
  108. package/test/unit/json-snapshot.test.js +1 -1
  109. package/test/unit/label-entities-skip.test.js +18 -0
  110. package/test/unit/llm-facts-integration.test.js +2 -2
  111. package/test/unit/llm-facts.test.js +3 -3
  112. package/test/unit/llm.test.js +5 -5
  113. package/test/unit/locomo.test.js +2 -2
  114. package/test/unit/longmemeval.test.js +2 -2
  115. package/test/unit/maintain-dispute.test.js +62 -0
  116. package/test/unit/maintain-duration.test.js +194 -0
  117. package/test/unit/markdown-import.test.js +5 -5
  118. package/test/unit/markdown.test.js +2 -2
  119. package/test/unit/memory-edit.test.js +5 -5
  120. package/test/unit/migration.test.js +1 -1
  121. package/test/unit/mood-saturation.test.js +33 -0
  122. package/test/unit/narrative-weave.test.js +271 -0
  123. package/test/unit/privacy-scope.test.js +1 -1
  124. package/test/unit/prompt.test.js +1 -1
  125. package/test/unit/providers.test.js +2 -2
  126. package/test/unit/qa.test.js +9 -9
  127. package/test/unit/query.test.js +10 -10
  128. package/test/unit/reflect-backfill.test.js +158 -0
  129. package/test/unit/reflect-coverage.test.js +35 -0
  130. package/test/unit/reflect-overview.test.js +22 -0
  131. package/test/unit/reflect-phrasing.test.js +75 -0
  132. package/test/unit/reflect-sampling.test.js +80 -0
  133. package/test/unit/reflect-source-budget.test.js +24 -0
  134. package/test/unit/relationship-dynamics.test.js +29 -0
  135. package/test/unit/retrieve.test.js +9 -9
  136. package/test/unit/revive-on-read.test.js +84 -0
  137. package/test/unit/scanner.test.js +2 -2
  138. package/test/unit/scenario.test.js +2 -2
  139. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  140. package/test/unit/scheduler-autodedupe.test.js +52 -0
  141. package/test/unit/scheduler-autosleep.test.js +50 -0
  142. package/test/unit/scheduler-cadence.test.js +33 -0
  143. package/test/unit/scheduler-deep.test.js +62 -0
  144. package/test/unit/scheduler-tick-gate.test.js +38 -0
  145. package/test/unit/scheduler.test.js +2 -1
  146. package/test/unit/service.test.js +5 -5
  147. package/test/unit/shiori-import.test.js +4 -4
  148. package/test/unit/spacing.test.js +14 -0
  149. package/test/unit/store.test.js +13 -13
  150. package/test/unit/summon-left-slot.test.js +51 -0
  151. package/test/unit/summon-rank.test.js +51 -0
  152. package/test/unit/tiers-gist.test.js +140 -0
  153. package/test/unit/tiers.test.js +1 -1
  154. package/test/unit/tokenizer-fts.test.js +6 -6
  155. package/test/unit/tools.test.js +5 -5
  156. package/test/unit/upgrade-0412.test.js +10 -10
  157. package/test/unit/upgrade-0413.test.js +5 -5
  158. package/test/unit/upgrade-0414.test.js +5 -5
  159. package/test/unit/vector-ann.test.js +3 -3
  160. package/test/unit/vector-async.test.js +7 -7
  161. package/test/unit/vector-coverage.test.js +34 -0
  162. package/test/unit/vector-override.test.js +37 -0
  163. package/test/unit/vector-typed-array.test.js +47 -0
  164. package/test/unit/vector.test.js +8 -8
  165. package/test/unit/working.test.js +19 -0
package/bin/verify.mjs ADDED
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Read-only health snapshot for an installed dsh-cortex store.
4
+ *
5
+ * It exists so a reviewer can answer "is the upgrade actually healthy?" without
6
+ * asking the agent and without writing anything:
7
+ *
8
+ * node bin/verify.mjs
9
+ * node bin/verify.mjs --db <path> --profile <name>
10
+ *
11
+ * Exit code 0 = healthy, 1 = something needs attention.
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import os from 'node:os';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { DatabaseSync } from 'node:sqlite';
18
+
19
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
20
+ const args = process.argv.slice(2);
21
+ const argValue = (name, fallback = null) => {
22
+ const index = args.indexOf(name);
23
+ return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
24
+ };
25
+
26
+ const home = process.env.USERPROFILE || os.homedir();
27
+ const profile = argValue('--profile');
28
+ const expectPath = argValue('--expect');
29
+ const savePath = argValue('--save');
30
+ const dbPath = argValue('--db')
31
+ || (profile
32
+ ? path.join(home, '.dsh', 'cortex-memory', 'profiles', profile, 'cortex.sqlite')
33
+ : path.join(home, '.dsh', 'cortex-memory', 'cortex.sqlite'));
34
+
35
+ // Version must describe what is INSTALLED, not the source tree: on 2026-11-16 the
36
+ // snapshot for 0.4.118 recorded 0.4.119 because the source had already been bumped.
37
+ // --installed makes a missing install a hard failure instead of a wrong label.
38
+ const sourcePkgPath = path.join(HERE, '..', 'package.json');
39
+ const profileDir = process.env.DSH_PROFILE && path.isAbsolute(process.env.DSH_PROFILE)
40
+ ? process.env.DSH_PROFILE
41
+ : path.join(os.homedir(), '.dsh', 'profiles', 'desktop');
42
+ const installedPkgPath = path.join(profileDir, 'node_modules', 'dsh-cortex', 'package.json');
43
+ let sourceVersion = null;
44
+ let installedVersion = null;
45
+ try { sourceVersion = JSON.parse(fs.readFileSync(sourcePkgPath, 'utf8')).version; } catch { /* source tree may be absent */ }
46
+ try { installedVersion = JSON.parse(fs.readFileSync(installedPkgPath, 'utf8')).version; } catch { /* not installed yet */ }
47
+ if (process.argv.includes('--installed') && !installedVersion) {
48
+ console.error('verify: --installed requested but ' + installedPkgPath + ' is missing');
49
+ process.exit(1);
50
+ }
51
+ const version = installedVersion ?? sourceVersion ?? 'unknown';
52
+
53
+ const result = { version, versionSource: installedVersion ? 'installed' : 'source', sourceVersion, db: dbPath, ok: true, problems: [] };
54
+ const problem = (text) => { result.ok = false; result.problems.push(text); };
55
+
56
+ if (!fs.existsSync(dbPath)) {
57
+ console.log(JSON.stringify({ ...result, ok: false, problems: ['database not found'] }, null, 2));
58
+ process.exit(1);
59
+ }
60
+
61
+ let db;
62
+ try {
63
+ db = new DatabaseSync(dbPath, { readOnly: true });
64
+ } catch (error) {
65
+ console.log(JSON.stringify({ ...result, ok: false, problems: [`cannot open database: ${error.message}`] }, null, 2));
66
+ process.exit(1);
67
+ }
68
+
69
+ const q = (sql, ...params) => db.prepare(sql).get(...params);
70
+ const all = (sql, ...params) => db.prepare(sql).all(...params);
71
+
72
+ try {
73
+ const integrity = q('PRAGMA integrity_check').integrity_check;
74
+ result.integrity = integrity;
75
+ if (integrity !== 'ok') problem(`sqlite integrity_check = ${integrity}`);
76
+
77
+ result.schemaVersion = q("SELECT value FROM meta WHERE key = 'schema_version'")?.value ?? null;
78
+
79
+ const active = Number(q("SELECT COUNT(*) AS c FROM traces WHERE state = 'active'")?.c ?? 0);
80
+ const archived = Number(q("SELECT COUNT(*) AS c FROM traces WHERE state = 'archived'")?.c ?? 0);
81
+ result.traces = { active, archived, total: active + archived };
82
+
83
+ const facts = {
84
+ active: Number(q("SELECT COUNT(*) AS c FROM facts WHERE status = 'active'")?.c ?? 0),
85
+ disputed: Number(q("SELECT COUNT(*) AS c FROM facts WHERE status = 'disputed'")?.c ?? 0),
86
+ };
87
+ result.facts = facts;
88
+ if (facts.disputed > 5) problem(`disputed facts: ${facts.disputed}`);
89
+
90
+ const openDisputes = Number(q("SELECT COUNT(*) AS c FROM disputes WHERE status = 'open'")?.c ?? 0);
91
+ result.disputes = { open: openDisputes };
92
+ if (openDisputes > 0) problem(`open disputes: ${openDisputes} (run repair.mjs)`);
93
+
94
+ // Capture hygiene
95
+ const rows = all("SELECT metadata_json, recorded_at FROM traces WHERE source = 'host:turn'");
96
+ const capture = { total: rows.length, stripped: 0, days: {} };
97
+ for (const row of rows) {
98
+ let metadata = {};
99
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
100
+ const stripped = metadata?.stripped === true || metadata?.capture?.stripped === true;
101
+ if (stripped) capture.stripped += 1;
102
+ const day = String(row.recorded_at ?? '').slice(0, 10);
103
+ const bucket = capture.days[day] ?? { total: 0, stripped: 0 };
104
+ bucket.total += 1;
105
+ if (stripped) bucket.stripped += 1;
106
+ capture.days[day] = bucket;
107
+ }
108
+ capture.ratio = capture.total ? Math.round((capture.stripped / capture.total) * 1000) / 1000 : 0;
109
+ result.capture = capture;
110
+
111
+ // Still-visible goal-round traces mean maintain/repair has not run yet.
112
+ const goalRounds = Number(q(`SELECT COUNT(*) AS c FROM traces WHERE state = 'active'
113
+ AND (content LIKE '用户:<goal_round>%' OR content LIKE '<goal_round>%')`)?.c ?? 0);
114
+ result.legacyGoalRounds = goalRounds;
115
+ if (goalRounds > 0) problem(`legacy goal-round traces still active: ${goalRounds} (run repair.mjs)`);
116
+
117
+ // Inhibition marks
118
+ const inhibitionRows = all("SELECT metadata_json FROM traces WHERE metadata_json LIKE '%\"inhibition\"%'");
119
+ let inhibitionCount = 0;
120
+ let inhibitionSum = 0;
121
+ for (const row of inhibitionRows) {
122
+ let metadata = {};
123
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
124
+ const value = Number(metadata?.inhibition ?? 0);
125
+ if (value > 0) { inhibitionCount += 1; inhibitionSum += value; }
126
+ }
127
+ result.inhibition = {
128
+ count: inhibitionCount,
129
+ average: inhibitionCount ? Math.round((inhibitionSum / inhibitionCount) * 1000) / 1000 : 0,
130
+ };
131
+
132
+ // Embedding coverage. Judged after the optional baseline comparison, because
133
+ // "low but climbing" and "low and stuck" need different reactions.
134
+ // Only embeddings that belong to active traces count: otherwise archived
135
+ // traces push coverage above 100% and the number stops meaning anything.
136
+ const embedded = Number(q(`
137
+ SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id
138
+ WHERE t.state = 'active'
139
+ `)?.c ?? 0);
140
+ result.embeddings = { count: embedded, coverage: active ? Math.round((embedded / active) * 1000) / 1000 : 0 };
141
+ result.coverageLow = active >= 100 && result.embeddings.coverage < 0.5;
142
+ } finally {
143
+ db.close();
144
+ }
145
+
146
+ // Optional baseline comparison: "--expect <previous.json>" prints deltas so an
147
+ // upgrade can be judged by movement (coverage up, legacy traces down) instead
148
+ // of a single snapshot.
149
+ if (expectPath && fs.existsSync(expectPath)) {
150
+ try {
151
+ const previous = JSON.parse(fs.readFileSync(expectPath, 'utf8'));
152
+ result.comparison = {
153
+ since: previous.at ?? null,
154
+ previousVersion: previous.version ?? null,
155
+ coverageDelta: Math.round((result.embeddings.coverage - (previous.embeddings?.coverage ?? 0)) * 1000) / 1000,
156
+ activeDelta: result.traces.active - (previous.traces?.active ?? 0),
157
+ legacyGoalRoundsDelta: result.legacyGoalRounds - (previous.legacyGoalRounds ?? 0),
158
+ strippedDelta: result.capture.stripped - (previous.capture?.stripped ?? 0),
159
+ };
160
+ } catch (error) {
161
+ result.comparison = { error: `cannot read baseline: ${error.message}` };
162
+ }
163
+ }
164
+
165
+ if (result.coverageLow) {
166
+ const delta = result.comparison?.coverageDelta;
167
+ const embedded = result.embeddings.count;
168
+ const active = result.traces.active;
169
+ const size = `${result.embeddings.coverage} (${embedded}/${active})`;
170
+ if (typeof delta === 'number' && delta > 0) {
171
+ // Still moving: this is a status line, not a problem.
172
+ result.notes = [...(result.notes ?? []), `embedding coverage ${size} is climbing: +${delta} vs baseline`];
173
+ } else if (typeof delta === 'number') {
174
+ problem(`embedding coverage low: ${size} and not climbing (${delta} vs baseline) — check that the vector feature is enabled and Ollama is reachable.`);
175
+ } else {
176
+ result.notes = [...(result.notes ?? []), `embedding coverage ${size}: no baseline given, so movement is unknown — re-run with --expect <snapshot> after a few minutes`];
177
+ }
178
+ }
179
+
180
+ if (savePath) {
181
+ try {
182
+ fs.writeFileSync(savePath, JSON.stringify({ ...result, at: new Date().toISOString() }, null, 2));
183
+ result.saved = savePath;
184
+ } catch (error) {
185
+ result.saved = null;
186
+ result.problems.push(`cannot save snapshot: ${error.message}`);
187
+ result.ok = false;
188
+ }
189
+ }
190
+
191
+ console.log(JSON.stringify(result, null, 2));
192
+ if (result.comparison && !result.comparison.error) {
193
+ const c = result.comparison;
194
+ console.log(`\n对比基线:覆盖 ${c.coverageDelta >= 0 ? '+' : ''}${c.coverageDelta} · active ${c.activeDelta >= 0 ? '+' : ''}${c.activeDelta} · 旧 goal_round ${c.legacyGoalRoundsDelta >= 0 ? '+' : ''}${c.legacyGoalRoundsDelta}`);
195
+ }
196
+ if (!result.ok) {
197
+ console.log('\nNEEDS ATTENTION:');
198
+ for (const item of result.problems) console.log(`- ${item}`);
199
+ process.exit(1);
200
+ }
201
+ for (const note of result.notes ?? []) console.log(`备注:${note}`);
202
+ console.log('\nHEALTHY');
package/cordis.patch.yml CHANGED
@@ -3,6 +3,6 @@
3
3
  # never shiori's data.
4
4
  - insert:
5
5
  - id: dsh-cortex-memory
6
- name: 'dsh-cortex-memory'
6
+ name: 'dsh-cortex'
7
7
  config: {}
8
8
 
@@ -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 上原生二进制/驱动差异;
@@ -0,0 +1,175 @@
1
+ # 配额压缩(Quota Compaction)设计草案 · v3
2
+
3
+ > v1 → v2 → v3:v3 采纳豆包第二轮批注(①–⑨),核心是**修复 r 的数学**(重归一)与**可核验、可承载的覆盖**。
4
+ > 状态:可以开工 0.4.116(只读)。未写执行代码。
5
+
6
+ ## 0. v3 相对 v2 的关键修正
7
+
8
+ | 批注 | 修正 |
9
+ |---|---|
10
+ | ① 加权后 r 永远 <0.8 | `r` 改为**在场信号重归一** `Σ(w·s)/Σ(w)`;缺席项不进分母;阈值由 116 实测分位定 |
11
+ | ② extract.js 没有实体词表 | 改用 `src/memory/tokenizer.js` 的 `tokens()` + 数字/日期正则 |
12
+ | ③ pin 是死引用 | traces 无 pinned;保护位写 `kind==='reflection' \|\| kind==='promise'` |
13
+ | ④ access_count 是累计 | 改 `last_access_at >= now-30d`(有索引) |
14
+ | ⑤ 灰区没有入口 | evaluate 三档:auto / gray / keep |
15
+ | ⑥ 熔断阈值=额度 | 熔断改 2;REVIVE_PER_DAY 提到 6 |
16
+ | ⑦ 「2 轮/天」实为 0 | 现状 consolidateOnTick=false、traceDelta 为空 → 自动 0 轮;117 显式工具触发 |
17
+ | ⑧ 覆盖≠承载 | 加承载下限:摘要 tokens ≥ trace tokens 的 30%,否则只允许「有更优副本」时归档 |
18
+ | ⑨ 小项 | 样本 ≥30 再判精度;revive 口径统一;coverage2 预编译 grams;观测期等有轮次 |
19
+
20
+ ## 1. 代码级根因(已核实)
21
+
22
+ ```js
23
+ // compression.js L12:sourceIds 命中即覆盖=1(许可证)
24
+ if (sourceHit) return { coverage: 1, by: 'summary-source' };
25
+ // evaluate 四道门,importance<0.35 永不成立(p25=0.95)→ 管道从不触发
26
+ ```
27
+
28
+ `REVIVE_PER_DAY = 3`,`get({revive:true})` 会自动复活并写 audit(读路径副作用)。
29
+
30
+ ## 2. 可核验覆盖(coverage2)
31
+
32
+ ```js
33
+ import { tokens } from '../memory/tokenizer.js';
34
+
35
+ coverage2(trace, summaries, facts):
36
+ best = 0
37
+ traceTokens = new Set(tokens(trace.title + trace.content))
38
+ if (fact-source): best = 0.6
39
+ for s in summaries (只取 period 与 trace 时间重叠的):
40
+ sTokens = new Set(tokens(s.content))
41
+ hit = |traceTokens ∩ sTokens|
42
+ if hit >= 2:
43
+ rate = hit / traceTokens.size
44
+ score = min(0.9, 0.45 + 0.45 * rate) // rate 0.5 → 0.675,rate 1.0 → 0.9
45
+ // 承载下限:摘要必须装得下这条
46
+ if (sTokens.size < 0.3 * traceTokens.size) score = min(score, 0.35)
47
+ best = max(best, score)
48
+ return best
49
+ ```
50
+
51
+ - 数字/日期另加正则命中(`\d{1,4}`、日期格式),命中也算「实体」;
52
+ - 预编译:每轮把候选与摘要的 token 集算一次(`Map<id,Set>`),避免 N×M 重算;
53
+ - `sourceIds` 命中**仅用于选候选摘要**,不加分。
54
+
55
+ ## 3. 信号与 r(重归一)
56
+
57
+ ```
58
+ s1 = coverage2(t) 权重 0.5
59
+ s2 = similarity_to_better_survivor(t) 权重 0.3 (无簇时缺席)
60
+ s3 = duplicate_support(t) 权重 0.2 (无簇时缺席)
61
+
62
+ r = Σ(w_i * s_i,仅在场项) / Σ(仅在场项的 w_i)
63
+ ```
64
+
65
+ - 只有 coverage 在场时 `r = s1`,可以到 0.9 → 与 0/0.35 的低覆盖条有区分度;
66
+ - 「在场」判定:`s2` 需存在更优同簇成员;`s3` 需 dedupe 簇;
67
+ - **门槛双条件**:`r >= T` **且**在场证据类别 ≥1(coverage 或 similarity,其一是主证据);
68
+ - `T` 由 116 实测分位定:初值 `T_hi = p90`、`T_lo = p75`,并给绝对下限 `T_hi >= 0.75`;若分布无区分度(p90−p75 < 0.05),116 就报告「信号不可用」,不开 117。
69
+
70
+ ## 4. 三档判决(evaluate 入口)
71
+
72
+ | 档 | 条件 | 动作 |
73
+ |---|---|---|
74
+ | **auto** | `r >= T_hi` 且有第二证据 | 代码直接归档(无需 LLM) |
75
+ | **gray** | `T_lo <= r < T_hi` | 交 LLM 双问;一致才归档 |
76
+ | **keep** | 其余 | 不动 |
77
+
78
+ 候选池前置过滤(都在打门前):
79
+
80
+ - `isProtected`:`importance >= max(0.9, p75)`、`kind in (reflection, promise)`、`age < 7d`;
81
+ - `recentlyAccessed`:`last_access_at >= now - 30d`(不看累计 access_count);
82
+ - 承载不足:`coverage2` 命中但摘要 tokens < 30% trace tokens → 只能走 gray,且必须有更优副本。
83
+
84
+ ## 5. 配额(与真实轮次对齐)
85
+
86
+ 现状:`consolidateOnTick=false`、`consolidateTraceDelta` 未配 → **自动巩固 0 轮/天**。117 执行必须显式触发(`cortex_consolidate action=run`,caller=tool)。
87
+
88
+ ```
89
+ runs_day = 2 // 人为安排:午/晚各一次
90
+ k_round = clamp( ceil((|A| - S*) / runs_day), 0, ceil(0.025 * |A|) )
91
+ k_day = min(2 * k_round, ceil(0.05 * |A|))
92
+ ```
93
+
94
+ - `S*` 初值 **永不触发**(116/117 纯观测);
95
+ - **bottom-k 只在 `r >= T_hi` 池内取**,不足就 0;k 是上限不是 KPI;
96
+ - LLM 全 keep 时,bottom-k 仍在该池内执行——唯一的「不会永不压缩」保证。
97
+
98
+ ## 6. 安全与回滚
99
+
100
+ | 项 | 规定 |
101
+ |---|---|
102
+ | 软删 | `state='archived'`、`compression='quota'`、`metadata.archiveReason/basis` |
103
+ | 快照 | `VACUUM INTO backups/quota-<ISO>.sqlite`;时间戳命名;保留 7 天/2GB;**失败即跳过本轮** |
104
+ | 事务 | LLM 判定在事务外;archive+ledger 短事务(持锁 <1s) |
105
+ | 账本 | 新表 `compaction_ledger`:`op_id, trace_id, bucket(auto/gray), r, r_components, basis, before_hash, after_hash, created_at, revived_at, revived_by, revive_trigger(read/tool)` |
106
+ | 熔断 | 单轮被复活 ≥2 条,或连续两轮 ≥2% → 停用并写 health warn;`REVIVE_PER_DAY` 提到 6,避免熔断与额度耗尽重合 |
107
+ | 复活口径 | `compression.revive()` → `trigger='tool'`;`get({revive:true})` → `trigger='read'`;两条路径都写 ledger 并保留归档原因 |
108
+
109
+ ## 7. 观测点(口径先定义)
110
+
111
+ - `archive_precision` = 1 − (归档后 7 天内**任一触发** revive 的比例);
112
+ - `resurrection_rate_tool` = tool revive / 归档数;`resurrection_rate_read` = read revive / 归档数;
113
+ - `coverage_delta`:可核验覆盖占比变化;
114
+ - `quota_skipped_rounds`:快照失败/池不足跳过的轮次;
115
+ - health 一行:`压缩:候选 N · 归档 k · 复活 主动 T/读 D · 预算 S*/|A|`。
116
+
117
+ ## 8. 分批落地
118
+
119
+ | 版本 | 内容 | 验收门槛 |
120
+ |---|---|---|
121
+ | 0.4.116 | 只读:coverage2、r 分布、三档划分、若开 118 会削哪 5 条 | 池 ≥20;`r≥T_hi` ≥5;列出 5 条含 basis;**不改库** |
122
+ | 0.4.117 | gray 双问 + auto 执行;每轮 ≤1%,绝对值 ≥5 条 | 累计归档 ≥30 条后再判:`archive_precision` ≥95% 或「0 主动复活」 |
123
+ | 0.4.118 | bottom-k、每日 5%、熔断接 health | 连续 3 天 tool 复活率 ≤2% |
124
+
125
+ ## 9. 四问答案(采纳豆包)
126
+
127
+ 1. **S\***:先永不触发,纯观测;条数不是理由,冗余才是。
128
+ 2. **摘要覆盖**:先修可核验 + 承载下限,再谈数量。
129
+ 3. **utterance**:不加类别门槛;用证据门槛(可核验覆盖 + 承载)或 `r × 0.85`。
130
+ 4. **ledger**:新表;`migrate()` 的 `CREATE TABLE IF NOT EXISTS` 对老库可行(已核)。
131
+
132
+ ## 10. 仍未决
133
+
134
+ - `tokenizer.tokens()` 对中文的切分粒度(字/词)要实测;若是按字,命中率阈值要重标。
135
+ - `T_lo/T_hi` 先看 116 实测;若 p75/p90 差距 <0.05,直接宣布「信号不可用」,不开 117。
136
+ - 熔断恢复:自动熔断、人工恢复(待确认)。
137
+
138
+ ## 11. 2026-11-16 晚的实测补充(重要)
139
+
140
+ 在活库副本上跑 0.4.117 预演,并单独统计了「摘要自己声明覆盖的痕迹」:
141
+
142
+ - 5 条 episode 摘要的 `sourceIds` 并集 = **32 条**,而 active 有 **941 条** → 摘要声明覆盖率仅 **3.4%**;
143
+ - 这 32 条里,可核验覆盖 `r ≥ 0.25` 的只有 2 条,最高 0.33;
144
+ - 其余 909 条痕迹**从未被任何摘要选中**。
145
+
146
+ 结论:**配额压缩的瓶颈不在评分器,也不在阈值,而在摘要的覆盖面本身。** 在覆盖率从 3.4% 提上来之前,任何「按覆盖归档」的方案都只能动极少数条目,或者被迫误伤。
147
+
148
+ 因此 117/118 的顺序调整为:
149
+
150
+ 1. 先让 episode 摘要更**广**(覆盖更多痕迹,哪怕每条更短);
151
+ 2. 再让摘要更**实**(可核验 token 覆盖);
152
+ 3. 最后才开灰区与配额。
153
+
154
+ `coverage2` 的统计口径也应改为**在 `sourceIds` 队列内评估**(「声明覆盖的是否真被装下」),而不是对全库 active 求覆盖——后者天然接近 0,会反复误报 `flat`。
155
+
156
+ ## 12. 窗口补齐:操作口径(2026-11-16 晚定)
157
+
158
+ 实现:`reflect.backfillEpisodes({ windowSize, maxWindows, dryRun, force })`,
159
+ 工具入口 `cortex_consolidate action="backfill"`,**dryRun 默认 true**。
160
+
161
+ **口令:每段 40 条、跑 24 段。**
162
+
163
+ - 6 段是「走过 240 条」;每段真正写进 `sourceIds` 的是 `min(24, windowSize)` 条
164
+ (24/40 = 60%),所以 6 段只声明 144 条 ≈15%,不是 60%;
165
+ - 要覆盖可压缩子集的 ~60%(约 576/949 条),需要 **24 段**;
166
+ - 窗口下限 32 条(32×25% 正好压在 `sourceBudgetFor` 的 min 8 上,更小会被静默过采样),
167
+ 上限 60 条;
168
+ - **幂等**:每个窗口先 `summaries.findPeriod()`,命中报 `already-reflected` 跳过;
169
+ `force: true` 只用于「窗口真的变了要重算」;
170
+ - **同毫秒边界**:窗口会并入同一 `recordedAt` 的全部痕迹,`until` 取下一条不同的时间戳,
171
+ 避免批量写入时切在毫秒中间漏条目;
172
+ - episode 摘要是**抽取式**(不调 LLM),不存在摘要模型的 maxTokens 预算问题。
173
+
174
+ 下一步(0.4.123):真跑 24 段后,重新量 `declaredCoverage`(目标 ≥40%)与
175
+ `fidelity`(目标 ≥60%),再决定灰区是否开启。
package/index.js CHANGED
@@ -26,6 +26,8 @@ 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
31
  }).description('人格称呼配置'),
30
32
  readOnlyScopes: Schema.array(Schema.string()).default([]).description('只读共享 scope 列表'),
31
33
  scopeWriteGrants: Schema.array(Schema.any()).default([]).description('显式写授权:scope:agent 或 {grant, until}'),
@@ -34,6 +36,15 @@ export const Config = Schema ? Schema.object({
34
36
  recallTimeoutMs: Schema.natural().default(1200).description('前台召回硬截止'),
35
37
  asyncJobs: Schema.boolean().default(true).description('允许后台任务'),
36
38
  captureSubagents: Schema.boolean().default(false).description('是否把子代理会话也写入记忆'),
39
+ captureMaxChars: Schema.natural().default(4000).description('单轮捕获正文上限;超出截断'),
40
+ maxContentChars: Schema.natural().default(8000).description('单条记忆正文硬上限;超出截断'),
41
+ touchOnRecall: Schema.boolean().default(true).description('召回时回写 access_count / last_access_at(DSR 复习信号)'),
42
+ touchMinIntervalMs: Schema.natural().default(300000).description('同一条记忆两次 access 回写的最小间隔;防每步召回灌水'),
43
+ touchMaxIntervalMs: Schema.natural().default(21600000).description('间隔随访问次数翻倍后的上限(默认 6 小时)'),
44
+ workingTtlDays: Schema.natural().default(14).description('工作记忆里未置顶且多久没更新就清掉(天)'),
45
+ vectorBackfillBatch: Schema.natural().default(200).description('每次心跳最多排队的缺失向量条数'),
46
+ vectorDrainBatch: Schema.natural().default(50).description('每次心跳最多真正嵌入的条数'),
47
+ vectorDrainBudgetMs: Schema.natural().default(45000).description('一次向量回填最多占用的毫秒数;到点就停,下一轮继续'),
37
48
  vectorEnabled: Schema.boolean().default(false).description('启用向量检索(默认用离线 hash embedder 兜底)'),
38
49
  vectorAnnMin: Schema.natural().default(20000).description('向量 ANN 生效的最小条数'),
39
50
  vectorAnnEngine: Schema.string().default('hnsw').description('ANN 引擎:hnsw(默认)或 nsw(旧实现)'),
@@ -41,8 +52,7 @@ export const Config = Schema ? Schema.object({
41
52
  vectorAnnTimeoutMs: Schema.natural().default(800).description('外置 ANN 超时毫秒'),
42
53
  scheduler: Schema.boolean().default(true).description('启用宿主心跳(安全自主 tick/作业/保留计划)'),
43
54
  schedulerIntervalMs: Schema.natural().default(60000).description('心跳间隔毫秒'),
44
- injectionGate: Schema.boolean().default(true).description('只过滤注入 prompt 的弱相关候选;cortex_search 仍返回全量'),
45
- recentMinMatch: Schema.number().default(0.12).description('注入层近期候选最低匹配度'),
55
+ injectionGate: Schema.boolean().default(true).description('只过滤注入 prompt 的弱相关候选;cortex_search 仍返回全量'), recentMinMatch: Schema.number().default(0.12).description('注入层近期候选最低匹配度'),
46
56
  recentImportanceFloor: Schema.number().default(0.8).description('注入层允许重要度豁免的最低重要度;默认保持 0.4.11 行为'),
47
57
  recallSharing: Schema.boolean().default(false).description('允许所有会话共享同一份召回块;默认按 session 隔离'),
48
58
  evolution: Schema.object({
@@ -84,6 +94,7 @@ export const Config = Schema ? Schema.object({
84
94
  autoFacts: Schema.boolean().default(false),
85
95
  autoDiary: Schema.boolean().default(false),
86
96
  autoDream: Schema.boolean().default(false),
97
+ autoSleep: Schema.boolean().default(false),
87
98
  autoFeeling: Schema.boolean().default(false),
88
99
  autoEvolve: Schema.boolean().default(false),
89
100
  aiOnlyLife: Schema.boolean().default(false),
@@ -94,7 +105,15 @@ export const Config = Schema ? Schema.object({
94
105
  tieredRecall: Schema.boolean().default(true),
95
106
  consolidateOnSleep: Schema.boolean().default(true),
96
107
  consolidateOnTick: Schema.boolean().default(false),
108
+ consolidateOnTraceDelta: Schema.boolean().default(false),
109
+ consolidateTraceDelta: Schema.number().default(20).description('新增活跃痕迹达到多少条才自动巩固'),
110
+ consolidateTraceGapMinutes: Schema.number().default(30).description('两次自动巩固的最小间隔(分钟)'),
111
+ inhibition: Schema.boolean().default(false),
97
112
  }).description('功能开关'),
113
+ inhibitionStrength: Schema.number().default(0.35).description('抑制对排序的最大削弱比例'),
114
+ inhibitionHalfLifeDays: Schema.number().default(14).description('抑制的半衰期(天)'),
115
+ inhibitionStep: Schema.number().default(0.15).description('每次被相似竞争者挤掉时抑制的增量'),
116
+ inhibitionCompetitorSim: Schema.number().default(0.5).description('判定「竞争者」的相似度下限'),
98
117
  }) : undefined;
99
118
 
100
119
  function selfText(cortex) {
@@ -186,6 +205,11 @@ export async function apply(ctx, config = {}) {
186
205
  ingestExtractedText: cortex.ingestExtractedText,
187
206
  self: cortex.self,
188
207
  health: cortex.health,
208
+ // Companion plugins (dsh-cortex-agency) ride the host heartbeat and
209
+ // write through the public write() path; they never reach into the DB.
210
+ onTick: cortex.onTick,
211
+ llm: cortex.llm,
212
+ config: cortex.config,
189
213
  });
190
214
  if (typeof disposeService === 'function') disposers.push(disposeService);
191
215
  }
@@ -206,4 +230,4 @@ export async function apply(ctx, config = {}) {
206
230
 
207
231
  ctx.logger?.info?.(`cortex: ready(db=${cortex.config.dbFile},scope=${cortex.config.scope})`);
208
232
  }
209
-
233
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.22",
3
+ "version": "0.4.146",
4
4
  "description": "本地优先的分层记忆引擎:情景/语义/程序记忆、时序事实、DSR 遗忘、混合召回、自我状态、反思、守护与受控进化。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -40,7 +40,7 @@
40
40
  },
41
41
  "engines": {
42
42
  "node": ">=24",
43
- "dsh": ">=0.2.1-rc.2 <0.4.0"
43
+ "dsh": ">=0.2.1-rc.2 <0.5.0"
44
44
  },
45
45
  "dsh": {
46
46
  "manifestVersion": 1,
@@ -53,7 +53,7 @@
53
53
  "inject": []
54
54
  },
55
55
  "compatibility": {
56
- "dsh": ">=0.2.1-rc.2 <0.4.0",
56
+ "dsh": ">=0.2.1-rc.2 <0.5.0",
57
57
  "node": ">=24",
58
58
  "profiles": [
59
59
  "desktop",
@@ -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
 
package/src/api/routes.js CHANGED
@@ -477,7 +477,7 @@ export function createApiHandler({ cortex, logger = null, getExtractor = null }
477
477
  return sendJson(response, 200, { ok: true, data: await cortex.indexVectorAsync(requireString(body.id, 'id', { max: 200 })) });
478
478
  }
479
479
  if (route === '/consolidate') {
480
- return sendJson(response, 200, { ok: true, data: await cortex.consolidation.run({ scopeId: scopeOf(request, url, body), limit: body.limit, dryRun: body.dryRun === true }) });
480
+ return sendJson(response, 200, { ok: true, data: await cortex.consolidation.run({ scopeId: scopeOf(request, url, body), limit: body.limit, dryRun: body.dryRun === true, caller: 'api' }) });
481
481
  }
482
482
  if (route === '/retention/apply') {
483
483
  const plan = cortex.retention.plan({ scopeId: scopeOf(request, url, body) });
@@ -1,7 +1,7 @@
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', 'autoFeeling', 'autoEvolve', 'aiOnlyLife', 'autoGraphCandidates', 'aiEdgeReview', 'webSearch', 'llmFacts', 'consolidateOnSleep', 'consolidateOnTick', 'tieredRecall']);
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']);
5
5
  const FILE = 'feature-overrides.json';
6
6
  const MAX_HISTORY = 20;
7
7
 
@@ -32,7 +32,7 @@ export function loadFeatureOverrides(config = {}) {
32
32
  export function effectiveFeatures(config = {}) {
33
33
  const overrides = loadFeatureOverrides(config);
34
34
  const features = { ...(config.features ?? {}) };
35
- for (const key of ['llm', 'capture', 'recall', 'reflect', 'growth', 'graph', 'vector', 'vectorAnn', 'vectorAnnExternal', 'attachmentReader', 'autoFacts', 'autoDiary', 'autoDream', 'autoFeeling', 'autoEvolve', 'aiOnlyLife', 'autoGraphCandidates', 'aiEdgeReview', 'webSearch', 'llmFacts', 'consolidateOnSleep', 'consolidateOnTick', 'tieredRecall']) {
35
+ for (const key of ['llm', 'capture', 'recall', 'reflect', 'growth', 'graph', 'vector', 'vectorAnn', 'vectorAnnExternal', 'attachmentReader', 'autoFacts', 'autoDiary', 'autoDream', 'autoSleep', 'autoFeeling', 'autoEvolve', 'aiOnlyLife', 'autoGraphCandidates', 'aiEdgeReview', 'webSearch', 'llmFacts', 'consolidateOnSleep', 'consolidateOnTick', 'tieredRecall']) {
36
36
  if (typeof overrides[key] === 'boolean') features[key] = overrides[key];
37
37
  }
38
38
  if (typeof overrides.rerank === 'boolean') features.rerank = overrides.rerank;