dsh-cortex-memory 0.4.21 → 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 (167) hide show
  1. package/CHANGELOG.md +2223 -7
  2. package/README.md +20 -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/cortex.mjs +9 -4
  8. package/bin/repair.mjs +328 -0
  9. package/bin/verify.mjs +202 -0
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/index.js +27 -3
  15. package/package.json +3 -3
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/api/routes.js +1 -1
  18. package/src/core/feature-overrides.js +2 -2
  19. package/src/engines/compression.js +172 -3
  20. package/src/engines/consolidate.js +397 -26
  21. package/src/engines/encode.js +16 -3
  22. package/src/engines/extract.js +72 -8
  23. package/src/engines/fact-guard.js +51 -0
  24. package/src/engines/health.js +263 -3
  25. package/src/engines/inhibition.js +39 -0
  26. package/src/engines/life.js +12 -1
  27. package/src/engines/llm-facts.js +12 -9
  28. package/src/engines/narrative.js +150 -13
  29. package/src/engines/reflect.js +172 -14
  30. package/src/engines/retrieve.js +44 -5
  31. package/src/engines/summary-coverage.js +62 -0
  32. package/src/engines/summary-dedupe.js +77 -0
  33. package/src/engines/summon-rank.js +132 -0
  34. package/src/host/runtime.js +64 -4
  35. package/src/host/scheduler.js +224 -3
  36. package/src/llm/adapter.js +29 -8
  37. package/src/memory/query.js +1 -1
  38. package/src/memory/spacing.js +15 -0
  39. package/src/memory/tokenizer.js +1 -1
  40. package/src/prompt/tiers.js +88 -12
  41. package/src/self/alias.js +25 -0
  42. package/src/self/emotion.js +3 -1
  43. package/src/self/relationship.js +44 -13
  44. package/src/self/state.js +20 -2
  45. package/src/self/working.js +34 -3
  46. package/src/service/cortex.js +493 -53
  47. package/src/store/repositories/facts.js +34 -1
  48. package/src/store/repositories/summaries.js +8 -1
  49. package/src/store/repositories/traces.js +22 -2
  50. package/src/tools/definitions.js +118 -4
  51. package/src/vector/index.js +96 -7
  52. package/test/integration/acceptance.test.js +47 -47
  53. package/test/integration/api-contract.test.js +17 -17
  54. package/test/integration/backup-privacy.test.js +10 -10
  55. package/test/integration/consolidate.test.js +6 -2
  56. package/test/integration/edge-cases.test.js +16 -15
  57. package/test/integration/exchange.test.js +26 -26
  58. package/test/integration/life-loop.test.js +7 -6
  59. package/test/integration/load.test.js +4 -4
  60. package/test/integration/policy-query-api.test.js +4 -4
  61. package/test/integration/resilience-writes.test.js +7 -7
  62. package/test/integration/tools-contract.test.js +57 -57
  63. package/test/unit/alias.test.js +87 -0
  64. package/test/unit/api-client.test.js +3 -3
  65. package/test/unit/api-validate.test.js +3 -3
  66. package/test/unit/api.test.js +3 -3
  67. package/test/unit/auto-reflect.test.js +141 -0
  68. package/test/unit/capture-filter.test.js +296 -0
  69. package/test/unit/cli-default-root.test.js +21 -0
  70. package/test/unit/compaction-preview.test.js +91 -0
  71. package/test/unit/compression.test.js +4 -4
  72. package/test/unit/consolidate-dedupe.test.js +174 -0
  73. package/test/unit/consolidate-errors.test.js +63 -0
  74. package/test/unit/consolidate-gate.test.js +26 -0
  75. package/test/unit/consolidate-preview.test.js +168 -0
  76. package/test/unit/consolidate-protection.test.js +156 -0
  77. package/test/unit/consolidate-reason.test.js +206 -0
  78. package/test/unit/consolidate-retry.test.js +91 -0
  79. package/test/unit/consolidate-selection.test.js +103 -0
  80. package/test/unit/core.test.js +11 -11
  81. package/test/unit/coverage-rewrite.test.js +38 -0
  82. package/test/unit/dedupe-episodes.test.js +34 -0
  83. package/test/unit/dedupe-threshold.test.js +14 -0
  84. package/test/unit/develop.test.js +4 -4
  85. package/test/unit/edges-candidates.test.js +2 -2
  86. package/test/unit/emotion.test.js +2 -1
  87. package/test/unit/encode.test.js +6 -6
  88. package/test/unit/evolution.test.js +5 -5
  89. package/test/unit/extract-question.test.js +41 -0
  90. package/test/unit/fact-guard.test.js +51 -0
  91. package/test/unit/fact-noise-llm.test.js +44 -0
  92. package/test/unit/facts-belief.test.js +4 -4
  93. package/test/unit/facts-compat.test.js +62 -0
  94. package/test/unit/facts.test.js +5 -5
  95. package/test/unit/fts-migration.test.js +6 -6
  96. package/test/unit/growth-reflect.test.js +4 -3
  97. package/test/unit/guardian.test.js +1 -1
  98. package/test/unit/health-consolidation.test.js +52 -0
  99. package/test/unit/health-fts-scope.test.js +33 -0
  100. package/test/unit/health-privacy.test.js +6 -6
  101. package/test/unit/health-summaries.test.js +24 -0
  102. package/test/unit/health-text-maintain.test.js +33 -0
  103. package/test/unit/health-today.test.js +45 -0
  104. package/test/unit/host-runtime.test.js +8 -8
  105. package/test/unit/host.test.js +1 -1
  106. package/test/unit/induct-evaluate.test.js +3 -3
  107. package/test/unit/ingest-extracted.test.js +3 -3
  108. package/test/unit/inhibition.test.js +90 -0
  109. package/test/unit/jobs.test.js +4 -4
  110. package/test/unit/json-snapshot.test.js +1 -1
  111. package/test/unit/label-entities-skip.test.js +18 -0
  112. package/test/unit/llm-facts-integration.test.js +2 -2
  113. package/test/unit/llm-facts.test.js +3 -3
  114. package/test/unit/llm.test.js +5 -5
  115. package/test/unit/locomo.test.js +2 -2
  116. package/test/unit/longmemeval.test.js +2 -2
  117. package/test/unit/maintain-dispute.test.js +62 -0
  118. package/test/unit/maintain-duration.test.js +194 -0
  119. package/test/unit/markdown-import.test.js +5 -5
  120. package/test/unit/markdown.test.js +2 -2
  121. package/test/unit/memory-edit.test.js +5 -5
  122. package/test/unit/migration.test.js +1 -1
  123. package/test/unit/mood-saturation.test.js +33 -0
  124. package/test/unit/narrative-weave.test.js +271 -0
  125. package/test/unit/privacy-scope.test.js +1 -1
  126. package/test/unit/prompt.test.js +1 -1
  127. package/test/unit/providers.test.js +2 -2
  128. package/test/unit/qa.test.js +9 -9
  129. package/test/unit/query.test.js +10 -10
  130. package/test/unit/reflect-backfill.test.js +158 -0
  131. package/test/unit/reflect-coverage.test.js +35 -0
  132. package/test/unit/reflect-overview.test.js +22 -0
  133. package/test/unit/reflect-phrasing.test.js +75 -0
  134. package/test/unit/reflect-sampling.test.js +80 -0
  135. package/test/unit/reflect-source-budget.test.js +24 -0
  136. package/test/unit/relationship-dynamics.test.js +29 -0
  137. package/test/unit/retrieve.test.js +9 -9
  138. package/test/unit/revive-on-read.test.js +84 -0
  139. package/test/unit/scanner.test.js +2 -2
  140. package/test/unit/scenario.test.js +2 -2
  141. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  142. package/test/unit/scheduler-autodedupe.test.js +52 -0
  143. package/test/unit/scheduler-autosleep.test.js +50 -0
  144. package/test/unit/scheduler-cadence.test.js +33 -0
  145. package/test/unit/scheduler-deep.test.js +62 -0
  146. package/test/unit/scheduler-tick-gate.test.js +38 -0
  147. package/test/unit/scheduler.test.js +2 -1
  148. package/test/unit/service.test.js +5 -5
  149. package/test/unit/shiori-import.test.js +4 -4
  150. package/test/unit/spacing.test.js +14 -0
  151. package/test/unit/store.test.js +13 -13
  152. package/test/unit/summon-left-slot.test.js +51 -0
  153. package/test/unit/summon-rank.test.js +51 -0
  154. package/test/unit/tiers-gist.test.js +140 -0
  155. package/test/unit/tiers.test.js +1 -1
  156. package/test/unit/tokenizer-fts.test.js +6 -6
  157. package/test/unit/tools.test.js +5 -5
  158. package/test/unit/upgrade-0412.test.js +10 -10
  159. package/test/unit/upgrade-0413.test.js +5 -5
  160. package/test/unit/upgrade-0414.test.js +5 -5
  161. package/test/unit/vector-ann.test.js +3 -3
  162. package/test/unit/vector-async.test.js +7 -7
  163. package/test/unit/vector-coverage.test.js +34 -0
  164. package/test/unit/vector-override.test.js +37 -0
  165. package/test/unit/vector-typed-array.test.js +47 -0
  166. package/test/unit/vector.test.js +8 -8
  167. package/test/unit/working.test.js +19 -0
@@ -0,0 +1,296 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createCortex } from '../../src/service/cortex.js';
7
+ import { createHostRuntime, stripInjected, deriveHostTitle, contentText } from '../../src/host/runtime.js';
8
+ import { isInjectedNoise } from '../../src/engines/encode.js';
9
+
10
+ function setup(config = {}) {
11
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-capture-filter-'));
12
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), ...config } });
13
+ return { dir, cortex };
14
+ }
15
+
16
+ const RUNTIME_CONTEXT = [
17
+ 'Time sampled while preparing turn 33, step 1: 2026-11-15T00:57:58+08:00[Asia/Shanghai]',
18
+ 'Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.',
19
+ 'Elapsed since the preceding model-visible message: 27m 56s.',
20
+ '用户说想吃米饭。',
21
+ ].join('\n');
22
+
23
+ test('stripInjected drops the runtime header and keeps the human line', () => {
24
+ const cleaned = stripInjected(RUNTIME_CONTEXT);
25
+ assert.equal(cleaned, '用户说想吃米饭。');
26
+ });
27
+
28
+ test('stripInjected removes system-reminder blocks and pure boilerplate becomes empty', () => {
29
+ const withReminder = '<system-reminder>\nThe available skill catalog changed.\n</system-reminder>\n帮咱看看记忆。';
30
+ assert.equal(stripInjected(withReminder), '帮咱看看记忆。');
31
+ const pure = '<system-reminder>\nCurrent runtime context. This snapshot supersedes earlier versions.\n</system-reminder>';
32
+ assert.equal(stripInjected(pure), '');
33
+ });
34
+
35
+ test('isInjectedNoise only fires on a strong head so discussing the marker is safe', () => {
36
+ assert.equal(isInjectedNoise('Time sampled while preparing turn 3'), true);
37
+ assert.equal(isInjectedNoise('Elapsed since the preceding step context: unavailable.'), true);
38
+ assert.equal(isInjectedNoise('用户问:为什么 "Time sampled" 会进库?'), false);
39
+ assert.equal(isInjectedNoise('记住 <system-reminder> 这种块不要入库'), false);
40
+ });
41
+
42
+ test('the "Elapsed since the preceding step context" line is stripped too', () => {
43
+ const text = 'Elapsed since the preceding step context: unavailable.\n今天想吃米饭。';
44
+ assert.equal(stripInjected(text), '今天想吃米饭。');
45
+ });
46
+
47
+ test('scheduler reminder batches are harness automation, not user speech', () => {
48
+ const reminder = '[SCHEDULE REMINDER BATCH]\nThis is a scheduled message from the user\nreminders_json: [{"schedule_id":"x"}]';
49
+ assert.equal(stripInjected(reminder), '');
50
+ assert.equal(isInjectedNoise(reminder), true);
51
+ assert.equal(isInjectedNoise('<goal_complete>\nObjective: "x"'), true);
52
+ });
53
+
54
+ test('titles fall back to the assistant line instead of "会话 N"', () => {
55
+ assert.equal(deriveHostTitle('', null, '助手'), null);
56
+ assert.equal(deriveHostTitle('助手:这一轮收工了,装的是 0.4.57', null, '助手'), '这一轮收工了,装的是 0.4.57');
57
+ assert.equal(deriveHostTitle('', 7, '助手'), '会话 7');
58
+ });
59
+
60
+ test('deriveHostTitle turns the first real line into a readable title', () => {
61
+ assert.equal(deriveHostTitle('用户说想吃米饭。\n第二行', 12), '用户说想吃米饭。');
62
+ assert.equal(deriveHostTitle('', 12), '会话 12');
63
+ });
64
+
65
+ test('a turn whose user text is only injected context is not captured', () => {
66
+ const { dir, cortex } = setup();
67
+ const runtime = createHostRuntime({ cortex });
68
+ const session = { id: 's-injected', header: {} };
69
+ try {
70
+ const at = Date.parse('2026-11-15T10:00:00+08:00');
71
+ runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 1 }, time: at });
72
+ runtime.onSessionEvent(session, { type: 'user/message', data: { content: '<system-reminder>Current runtime context.</system-reminder>' }, time: at });
73
+ runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } }, time: at });
74
+ assert.equal(cortex.repos.traces.count(), 0);
75
+ } finally {
76
+ cortex.close();
77
+ rmSync(dir, { recursive: true, force: true });
78
+ }
79
+ });
80
+
81
+ test('host capture stores clean text with a readable title', () => {
82
+ const { dir, cortex } = setup();
83
+ const runtime = createHostRuntime({ cortex, config: { persona: { selfName: '助手' } } });
84
+ const session = { id: 's-clean', header: {} };
85
+ try {
86
+ const at = Date.parse('2026-11-15T10:00:00+08:00');
87
+ runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 7 }, time: at });
88
+ runtime.onSessionEvent(session, { type: 'user/message', data: { content: RUNTIME_CONTEXT }, time: at });
89
+ runtime.onSessionEvent(session, { type: 'assistant/message', data: { turn: 7, message: { content: '这就去煮。' } }, time: at });
90
+ runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 7, reason: { kind: 'completed' } }, time: at });
91
+ const trace = cortex.repos.traces.list({ limit: 1 })[0];
92
+ assert.doesNotMatch(trace.content, /Time sampled/);
93
+ assert.match(trace.content, /用户说想吃米饭/);
94
+ assert.equal(trace.title, '用户说想吃米饭。');
95
+ const health = cortex.health();
96
+ assert.equal(health.capture.total, 1);
97
+ assert.equal(health.capture.stripped, 1);
98
+ assert.equal(health.capture.clean, 0);
99
+ assert.equal(typeof health.vectors.coverage, 'number');
100
+ } finally {
101
+ cortex.close();
102
+ rmSync(dir, { recursive: true, force: true });
103
+ }
104
+ });
105
+
106
+ test('recall records access so DSR recency is not frozen', () => {
107
+ const { dir, cortex } = setup();
108
+ try {
109
+ cortex.write({ text: '用户在 2026-11-14 说,助手将来会走得很远。', kind: 'promise', title: '用户的话' });
110
+ const before = cortex.repos.traces.list({ limit: 1 })[0];
111
+ assert.equal(before.accessCount, 0);
112
+ const result = cortex.search('助手 很远');
113
+ assert.ok(result.items.length > 0);
114
+ const after = cortex.repos.traces.get(before.id);
115
+ assert.equal(after.accessCount, 1);
116
+ assert.ok(after.lastAccessAt);
117
+ cortex.search('助手 很远');
118
+ assert.equal(cortex.repos.traces.get(before.id).accessCount, 1, 'a second immediate recall must not inflate access');
119
+ } finally {
120
+ cortex.close();
121
+ rmSync(dir, { recursive: true, force: true });
122
+ }
123
+ });
124
+
125
+ test('async vector queue drains and backfills misses instead of silently dropping', async () => {
126
+ const embedder = {
127
+ kind: 'openai-embedding',
128
+ async: true,
129
+ model: 'fake-embed',
130
+ dim: 4,
131
+ embed: async () => [1, 0, 0, 0],
132
+ };
133
+ const { dir, cortex } = setup({ features: { vector: true }, embedder, vectorDim: 4, vectorModel: 'fake-embed' });
134
+ try {
135
+ const written = cortex.write({ text: '海上的月亮很亮。', kind: 'observation', title: '月' });
136
+ assert.ok(written.trace?.id);
137
+ let status = cortex.vector.status();
138
+ assert.equal(status.queue.pending, 1);
139
+ const drained = await cortex.vector.drainQueue({ max: 10 });
140
+ assert.equal(drained.ok, 1);
141
+ assert.equal(cortex.vector.status().count, 1);
142
+
143
+ cortex.vector.remove(written.trace.id);
144
+ assert.equal(cortex.vector.status().count, 0);
145
+ const queued = cortex.vector.backfillMissing({ limit: 10 });
146
+ assert.equal(queued.queued, 1);
147
+ await cortex.vector.drainQueue({ max: 10 });
148
+ assert.equal(cortex.vector.status().count, 1);
149
+
150
+ // vectorMaintain is what the heartbeat calls: it should backfill and drain
151
+ // in one pass, and honour the batch sizes it is given.
152
+ for (let i = 0; i < 4; i += 1) {
153
+ cortex.write({ text: `海边的第 ${i} 条记忆。`, kind: 'observation', title: `海${i}` });
154
+ }
155
+ const maintain = await cortex.vectorMaintain({ backfill: 10, drain: 10 });
156
+ assert.ok(maintain.ok >= 4, `expected at least 4 embeddings, got ${JSON.stringify(maintain)}`);
157
+ assert.equal(maintain.stoppedBy, 'done');
158
+ assert.ok(maintain.elapsedMs >= 0);
159
+ assert.equal(cortex.vector.status().count, 5);
160
+ } finally {
161
+ cortex.close();
162
+ rmSync(dir, { recursive: true, force: true });
163
+ }
164
+ });
165
+
166
+ test('maintain expires stale intentions and collapses duplicate summaries', () => {
167
+ const { dir, cortex } = setup();
168
+ try {
169
+ const at = new Date('2026-11-15T03:00:00.000Z').toISOString();
170
+ const past = new Date('2026-11-12T03:00:00.000Z').toISOString();
171
+ cortex.db.prepare(`
172
+ INSERT INTO intentions(id, scope_id, kind, priority, status, payload_json, reason, created_at, due_at, expires_at)
173
+ VALUES ('itn_test', 'global', 'question', 0.4, 'pending', '{}', 'stale', ?, ?, ?)
174
+ `).run(past, past, past);
175
+ for (const id of ['sum_a', 'sum_b']) {
176
+ cortex.db.prepare(`
177
+ INSERT INTO summaries(id, scope_id, level, period_start, period_end, content, source_ids_json, coverage, created_at)
178
+ VALUES (?, 'global', 'episode', ?, ?, '同一段摘要', '[]', 1, ?)
179
+ `).run(id, past, past, past);
180
+ }
181
+ const report = cortex.maintain({ now: Date.parse(at), scopeId: 'global' });
182
+ assert.equal(report.intentions, 1);
183
+ assert.equal(cortex.db.prepare("SELECT status FROM intentions WHERE id = 'itn_test'").get().status, 'expired');
184
+ assert.equal(report.summaries, 1);
185
+ assert.equal(cortex.db.prepare("SELECT COUNT(*) AS c FROM summaries WHERE content = '同一段摘要'").get().c, 1);
186
+ } finally {
187
+ cortex.close();
188
+ rmSync(dir, { recursive: true, force: true });
189
+ }
190
+ });
191
+
192
+ test('auto-continuation goal rounds are harness text, not user speech', () => {
193
+ const goalRound = [
194
+ '<goal_round>',
195
+ 'Objective: "持续自主迭代。"',
196
+ 'Round: 8/40',
197
+ '',
198
+ 'Continue working toward the objective.',
199
+ '</goal_round>',
200
+ ].join('\n');
201
+ assert.equal(stripInjected(goalRound), '');
202
+ assert.equal(stripInjected('Objective: "x"\nRound: 3/40\n\n继续。'), '');
203
+ assert.equal(isInjectedNoise(goalRound), true);
204
+ assert.equal(stripInjected('用户说这句话里的 Round: 8/40 不要存。'), '用户说这句话里的 Round: 8/40 不要存。');
205
+ });
206
+
207
+ test('a goal-round turn keeps only the assistant reply', () => {
208
+ const { dir, cortex } = setup();
209
+ const runtime = createHostRuntime({ cortex, config: { persona: { selfName: '助手' } } });
210
+ const session = { id: 's-goal-round', header: {} };
211
+ try {
212
+ const at = Date.parse('2026-11-15T12:00:00+08:00');
213
+ runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 3 }, time: at });
214
+ runtime.onSessionEvent(session, {
215
+ type: 'user/message',
216
+ data: { content: '<goal_round>\nObjective: "x"\nRound: 3/40\n\n继续。\n</goal_round>' },
217
+ time: at,
218
+ });
219
+ runtime.onSessionEvent(session, { type: 'assistant/message', data: { turn: 3, message: { content: '这一轮修了捕获过滤。' } }, time: at });
220
+ runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 3, reason: { kind: 'completed' } }, time: at });
221
+ const trace = cortex.repos.traces.list({ limit: 1 })[0];
222
+ assert.ok(trace, 'the assistant reply is still worth remembering');
223
+ assert.doesNotMatch(trace.content, /Objective/);
224
+ assert.match(trace.content, /这一轮修了捕获过滤/);
225
+ } finally {
226
+ cortex.close();
227
+ rmSync(dir, { recursive: true, force: true });
228
+ }
229
+ });
230
+
231
+ test('maintain archives goal-round traces stored by older versions', () => {
232
+ const { dir, cortex } = setup();
233
+ try {
234
+ const written = cortex.write({
235
+ text: '用户:<goal_round>\nObjective: "旧版本存进来的"\nRound: 2/40\n\n继续。',
236
+ explicit: true,
237
+ });
238
+ assert.ok(written.trace?.id);
239
+ const report = cortex.maintain({ now: Date.parse('2026-11-15T12:00:00+08:00'), scopeId: 'global' });
240
+ assert.equal(report.goalRounds, 1);
241
+ assert.equal(cortex.repos.traces.get(written.trace.id).state, 'archived');
242
+ } finally {
243
+ cortex.close();
244
+ rmSync(dir, { recursive: true, force: true });
245
+ }
246
+ });
247
+
248
+ test('maintain drops stale unpinned working items but keeps pinned ones', () => {
249
+ const { dir, cortex } = setup();
250
+ try {
251
+ const now = Date.parse('2026-11-15T12:00:00+08:00');
252
+ const old = new Date(now - 30 * 86_400_000).toISOString();
253
+ cortex.db.prepare("INSERT INTO working_items(id, scope_id, kind, text, priority, pinned, created_at, updated_at) VALUES ('wrk_old','global','todo','很久没动过的事','0.5',0,?,?)").run(old, old);
254
+ cortex.db.prepare("INSERT INTO working_items(id, scope_id, kind, text, priority, pinned, created_at, updated_at) VALUES ('wrk_pin','global','todo','置顶不动的事','1',1,?,?)").run(old, old);
255
+ const report = cortex.maintain({ now, scopeId: 'global' });
256
+ assert.equal(report.working, 1);
257
+ assert.equal(cortex.db.prepare("SELECT COUNT(*) AS c FROM working_items WHERE id = 'wrk_old'").get().c, 0);
258
+ assert.equal(cortex.db.prepare("SELECT COUNT(*) AS c FROM working_items WHERE id = 'wrk_pin'").get().c, 1);
259
+ const health = cortex.health();
260
+ assert.ok(health.maintain, 'health should surface the last maintenance pass');
261
+ assert.equal(health.maintain.working, 1);
262
+ } finally {
263
+ cortex.close();
264
+ rmSync(dir, { recursive: true, force: true });
265
+ }
266
+ });
267
+
268
+ test('capture report buckets host turns by day', () => {
269
+ const { dir, cortex } = setup();
270
+ const runtime = createHostRuntime({ cortex });
271
+ const session = { id: 's-days', header: {} };
272
+ try {
273
+ const days = [Date.parse('2026-11-14T10:00:00+08:00'), Date.parse('2026-11-15T10:00:00+08:00')];
274
+ days.forEach((at, index) => {
275
+ const turn = index + 1;
276
+ runtime.onSessionEvent(session, { type: 'turn/start', data: { turn }, time: at });
277
+ runtime.onSessionEvent(session, { type: 'user/message', data: { content: `Time sampled while preparing turn ${turn}\nElapsed since the preceding model-visible message: 1m\n用户第 ${turn} 天说想吃米饭。` }, time: at });
278
+ runtime.onSessionEvent(session, { type: 'turn/end', data: { turn, reason: { kind: 'completed' } }, time: at });
279
+ });
280
+ const health = cortex.health();
281
+ assert.equal(health.capture.days.length, 2);
282
+ assert.equal(health.capture.days[0].day, '2026-11-15');
283
+ assert.equal(health.capture.days[1].day, '2026-11-14');
284
+ assert.equal(health.capture.days[0].stripped, 1);
285
+ } finally {
286
+ cortex.close();
287
+ rmSync(dir, { recursive: true, force: true });
288
+ }
289
+ });
290
+
291
+ test('contentText keeps text blocks only', () => {
292
+ const value = contentText([{ type: 'text', text: 'a' }, { type: 'image' }, 'b']);
293
+ assert.match(value, /a/);
294
+ assert.match(value, /b/);
295
+ assert.doesNotMatch(value, /\[object/);
296
+ });
@@ -0,0 +1,21 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import path from 'node:path';
4
+ import { resolveDataRoot } from '../../bin/cortex.mjs';
5
+
6
+ const home = 'C:/tmp/cortex-cli-home';
7
+
8
+ test('CLI defaults to the cortex-memory root, not legacy cortex', () => {
9
+ const root = resolveDataRoot({}, { DSH_HOME: home, DSH_PROFILE: 'desktop' });
10
+ assert.equal(root, path.resolve(path.join(home, 'cortex-memory')));
11
+ });
12
+
13
+ test('CLI --data overrides the profile root', () => {
14
+ const root = resolveDataRoot({ data: 'C:/tmp/explicit-cortex' }, { DSH_HOME: home, DSH_PROFILE: 'desktop' });
15
+ assert.equal(root, path.resolve('C:/tmp/explicit-cortex'));
16
+ });
17
+
18
+ test('CLI CORTEX_HOME overrides the profile root', () => {
19
+ const root = resolveDataRoot({}, { DSH_HOME: home, CORTEX_HOME: 'C:/tmp/cortex-env' });
20
+ assert.equal(root, path.resolve('C:/tmp/cortex-env'));
21
+ });
@@ -0,0 +1,91 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createCortex } from '../../src/service/cortex.js';
7
+
8
+ function setup() {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-preview-'));
10
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
+ return { cortex, dir };
12
+ }
13
+
14
+ test('coverage2:摘要正文真的装下才给分,薄摘要封顶 0.35', () => {
15
+ const trace = { id: 't1', title: '辉夜姬', content: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。' };
16
+ const good = { id: 's1', content: '今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。' };
17
+ const thin = { id: 's2', content: '图书馆' };
18
+ const unrelated = { id: 's3', content: '完全无关的一句话。' };
19
+ const { cortex, dir } = setup();
20
+ try {
21
+ const goodScore = cortex.compression.coverage2(trace, [good]);
22
+ const thinScore = cortex.compression.coverage2(trace, [thin]);
23
+ const noneScore = cortex.compression.coverage2(trace, [unrelated]);
24
+ assert.ok(goodScore.score >= 0.6, `装得下的摘要应给高分,实际 ${goodScore.score}`);
25
+ assert.ok(thinScore.score <= 0.35, '薄摘要必须封顶');
26
+ assert.equal(noneScore.score, 0);
27
+ } finally {
28
+ cortex.close();
29
+ rmSync(dir, { recursive: true, force: true });
30
+ }
31
+ });
32
+
33
+ test('previewCoverage:只读、跳过保护与近期访问、给出分位', () => {
34
+ const { cortex, dir } = setup();
35
+ try {
36
+ const now = Date.now();
37
+ for (let i = 0; i < 6; i += 1) {
38
+ cortex.write({ text: `用户:一条普通记录 ${i}`, kind: 'utterance', title: `普通 ${i}`, importance: 0.7, explicit: true, now });
39
+ }
40
+ cortex.write({ text: '用户:一条受保护的记录', kind: 'utterance', title: '保护', importance: 0.99, explicit: true, now });
41
+ const before = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 50 }).length;
42
+ const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 100 });
43
+ const after = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 50 }).length;
44
+ assert.equal(before, after, '预演不能改库');
45
+ assert.equal(report.total, 7);
46
+ assert.ok(report.protectedSkipped >= 1, '高重要度应被跳过');
47
+ assert.ok(report.percentiles && typeof report.percentiles.p90 === 'number');
48
+ assert.ok(Array.isArray(report.wouldCut));
49
+ } finally {
50
+ cortex.close();
51
+ rmSync(dir, { recursive: true, force: true });
52
+ }
53
+ });
54
+
55
+ test('高频通用词会被 DF 过滤:只含「我们/可以」的摘要不该算覆盖', async () => {
56
+ const { cortex, dir } = setup();
57
+ try {
58
+ const now = Date.now();
59
+ for (let i = 0; i < 30; i += 1) {
60
+ cortex.write({ text: `我们可以做第${i}件事,这件事有点特别。`, kind: 'utterance', title: `样本 ${i}`, importance: 0.7, explicit: true, now });
61
+ }
62
+ cortex.repos.summaries.insert({
63
+ scopeId: 'global', level: 'episode', content: '我们可以。', sourceIds: [], coverage: 1, model: 'test',
64
+ });
65
+ const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 100 });
66
+ assert.equal(report.summaryCovered, 0, '通用二字词被过滤后不应算覆盖');
67
+ assert.equal(report.pool, 0);
68
+ } finally {
69
+ cortex.close();
70
+ rmSync(dir, { recursive: true, force: true });
71
+ }
72
+ });
73
+
74
+ test('只有摘要一条证据时,不把单证据条目当候选输出', async () => {
75
+ const { cortex, dir } = setup();
76
+ try {
77
+ const now = Date.now();
78
+ cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。', kind: 'utterance', title: '辉夜姬', importance: 0.7, explicit: true, now });
79
+ cortex.repos.summaries.insert({
80
+ scopeId: 'global', level: 'episode', content: '今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。', sourceIds: [], coverage: 1, model: 'test',
81
+ });
82
+ const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 50 });
83
+ assert.ok(report.pool >= 0);
84
+ assert.equal(report.strongPool, 0, '没有事实时不存在两类证据');
85
+ assert.equal(report.wouldCut.length, 0, '单证据不能当候选');
86
+ assert.ok(['no_signal', 'single-evidence-only'].includes(report.reason));
87
+ } finally {
88
+ cortex.close();
89
+ rmSync(dir, { recursive: true, force: true });
90
+ }
91
+ });
@@ -8,8 +8,8 @@ import { extractFactCandidates } from '../../src/engines/extract.js';
8
8
  import { coverageOf } from '../../src/engines/compression.js';
9
9
 
10
10
  test('fact extraction finds preferences, states and plans', () => {
11
- const candidates = extractFactCandidates('用户喜欢白饭,助手会在明天继续修插件,白饭是主食。');
12
- assert.ok(candidates.some((item) => item.predicate === 'likes' && item.object.includes('白饭')));
11
+ const candidates = extractFactCandidates('用户喜欢米饭,助手会在明天继续修插件,米饭是主食。');
12
+ assert.ok(candidates.some((item) => item.predicate === 'likes' && item.object.includes('米饭')));
13
13
  assert.ok(candidates.some((item) => item.predicate === 'will'));
14
14
  assert.ok(candidates.some((item) => item.predicate === 'is'));
15
15
  });
@@ -25,7 +25,7 @@ test('negated predicates are not also extracted as their positive form', () => {
25
25
  });
26
26
 
27
27
  test('coverage prefers source pointers over token overlap', () => {
28
- const trace = { id: 't1', eventId: 'e1', content: '白饭 承诺 用户' };
28
+ const trace = { id: 't1', eventId: 'e1', content: '米饭 承诺 用户' };
29
29
  const bySource = coverageOf(trace, { summaries: [{ id: 's1', sourceIds: ['t1'], content: '完全不同的摘要' }], facts: [] });
30
30
  assert.equal(bySource.coverage, 1);
31
31
  assert.equal(bySource.by, 'summary-source');
@@ -65,7 +65,7 @@ test('autoFacts writes semantic facts when enabled', () => {
65
65
  config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { autoFacts: true } },
66
66
  });
67
67
  try {
68
- const result = cortex.write({ text: '用户喜欢白饭。', explicit: true });
68
+ const result = cortex.write({ text: '用户喜欢米饭。', explicit: true });
69
69
  assert.ok(result.autoFacts);
70
70
  assert.ok(result.autoFacts.resolved.length >= 1);
71
71
  assert.ok(cortex.repos.facts.list({ limit: 10 }).length >= 1);
@@ -0,0 +1,174 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createCortex } from '../../src/service/cortex.js';
7
+
8
+ const PAIR = [
9
+ '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。',
10
+ '用户:今天在图书馆看了超时空辉夜姬第三集,特别好笑。',
11
+ ];
12
+
13
+ function setup(importances = [0.6, 0.55]) {
14
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-dedupe-'));
15
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
16
+ return { cortex, dir };
17
+ }
18
+
19
+ test('确定性去重:预演只报可合并组,不动库', async () => {
20
+ const { cortex, dir } = setup();
21
+ try {
22
+ const now = Date.now();
23
+ PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.6, explicit: true, now }));
24
+ const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: true, threshold: 0.7 });
25
+ assert.equal(result.decisions.length, 1, '应识别出一组');
26
+ assert.equal(result.applied.length, 0);
27
+ assert.equal(result.run.model, 'dedupe');
28
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
29
+ assert.equal(active.length, 2, '预演不能改库');
30
+ } finally {
31
+ cortex.close();
32
+ rmSync(dir, { recursive: true, force: true });
33
+ }
34
+ });
35
+
36
+ test('确定性去重:真跑会把低重要度那条归档,并留合并摘要', async () => {
37
+ const { cortex, dir } = setup();
38
+ try {
39
+ const now = Date.now();
40
+ PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.6, explicit: true, now }));
41
+ const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.7 });
42
+ assert.equal(result.applied.length, 1);
43
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
44
+ assert.equal(active.length, 1, '重复的两条应合成一条');
45
+ const archived = cortex.repos.traces.list({ scopeId: 'global', state: 'archived', limit: 10 });
46
+ assert.equal(archived.length, 1);
47
+ assert.equal(archived[0].compression, 'merged');
48
+ } finally {
49
+ cortex.close();
50
+ rmSync(dir, { recursive: true, force: true });
51
+ }
52
+ });
53
+
54
+ test('保护线上的近重复仍可合并(活库里 75% 都在线上)', async () => {
55
+ const { cortex, dir } = setup();
56
+ try {
57
+ const now = Date.now();
58
+ PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.95, explicit: true, now }));
59
+ const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.7 });
60
+ assert.equal(result.applied.length, 1, '近乎相同的两条不该因为都在保护线上就永久并存');
61
+ assert.equal(result.decisions.length, 1);
62
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
63
+ assert.equal(active.length, 1);
64
+ } finally {
65
+ cortex.close();
66
+ rmSync(dir, { recursive: true, force: true });
67
+ }
68
+ });
69
+
70
+ test('reflection 不参与去重(既不当来源也不被合并)', async () => {
71
+ const { cortex, dir } = setup();
72
+ try {
73
+ const now = Date.now();
74
+ cortex.write({ text: '今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'reflection', title: '反思', importance: 0.5, explicit: true, now });
75
+ cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'utterance', title: '辉夜姬', importance: 0.5, explicit: true, now });
76
+ const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.6 });
77
+ assert.equal(result.applied.length, 0, '单独一条 utterance 没有同伙,不该合并');
78
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
79
+ assert.equal(active.length, 2, 'reflection 与普通痕迹都还在');
80
+ } finally {
81
+ cortex.close();
82
+ rmSync(dir, { recursive: true, force: true });
83
+ }
84
+ });
85
+
86
+ test('LLM 想把 reflection 当来源 merge 时会被拒', async () => {
87
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-dedupe-v-'));
88
+ let reflexId = null;
89
+ const cortex = createCortex({
90
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
91
+ llm: {
92
+ available: () => true,
93
+ complete: async () => {
94
+ const ids = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 }).sort((a, b) => Number(b.importance) - Number(a.importance));
95
+ return JSON.stringify([{ action: 'merge', ids: ids.map((t) => t.id), targetId: ids[0].id }]);
96
+ },
97
+ },
98
+ });
99
+ try {
100
+ const now = Date.now();
101
+ reflexId = cortex.write({ text: '我想:一条低重要度的反思。', kind: 'reflection', title: '反思', importance: 0.5, explicit: true, now });
102
+ cortex.write({ text: '用户:另一条普通痕迹。', kind: 'utterance', title: '普通', importance: 0.6, explicit: true, now });
103
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
104
+ assert.equal(result.applied.length, 0, '不应真的合并');
105
+ assert.match(String(result.run.error), /rejected 1|rejected 2/);
106
+ const still = cortex.repos.traces.get(String(reflexId?.trace?.id ?? reflexId));
107
+ assert.notEqual(still?.state, 'archived');
108
+ } finally {
109
+ cortex.close();
110
+ rmSync(dir, { recursive: true, force: true });
111
+ }
112
+ });
113
+
114
+ test('LLM 路线仍不允许把受保护的痕迹当 merge 来源', async () => {
115
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-protect-'));
116
+ const cortex = createCortex({
117
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
118
+ llm: {
119
+ available: () => true,
120
+ complete: async () => {
121
+ const list = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
122
+ return JSON.stringify([{ action: 'merge', ids: list.map((t) => t.id), targetId: list[0].id }]);
123
+ },
124
+ },
125
+ });
126
+ try {
127
+ const now = Date.now();
128
+ for (let i = 0; i < 2; i += 1) cortex.write({ text: `用户:受保护样本 ${i}`, kind: 'utterance', title: `保护 ${i}`, importance: 0.97, explicit: true, now });
129
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
130
+ assert.equal(result.applied.length, 0, 'LLM 不能合受保护的痕迹');
131
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
132
+ assert.equal(active.length, 2);
133
+ } finally {
134
+ cortex.close();
135
+ rmSync(dir, { recursive: true, force: true });
136
+ }
137
+ });
138
+
139
+ test('被归档的条目,与 target 的相似度必须仍然达标(防链式误合)', async () => {
140
+ const shingles = (value) => {
141
+ const flat = String(value ?? '').replace(/\s+/g, '');
142
+ const set = new Set();
143
+ for (let i = 0; i + 2 <= flat.length; i += 1) set.add(flat.slice(i, i + 2));
144
+ return set;
145
+ };
146
+ const jaccard = (a, b) => {
147
+ if (!a.size || !b.size) return 0;
148
+ let shared = 0;
149
+ for (const g of a) if (b.has(g)) shared += 1;
150
+ return shared / (a.size + b.size - shared);
151
+ };
152
+ const { cortex, dir } = setup();
153
+ try {
154
+ const now = Date.now();
155
+ const texts = [
156
+ '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。',
157
+ '用户:今天在图书馆看了超时空辉夜姬第三集,特别好笑。',
158
+ '用户:今天在图书馆看了超时空辉夜姬第三集,非常好笑。',
159
+ '用户:今天下雨了,路上很挤,回家吃了米饭。',
160
+ ];
161
+ texts.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `样本 ${i}`, importance: 1.0 - i * 0.01, explicit: true, now }));
162
+ const threshold = 0.7;
163
+ await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold });
164
+ const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 20 });
165
+ const archived = cortex.repos.traces.list({ scopeId: 'global', state: 'archived', limit: 20 });
166
+ for (const loser of archived) {
167
+ const target = active.find((trace) => jaccard(shingles(loser.content), shingles(trace.content)) >= threshold);
168
+ assert.ok(target, `归档的 ${loser.title} 必须仍与某条 active 达标相似`);
169
+ }
170
+ } finally {
171
+ cortex.close();
172
+ rmSync(dir, { recursive: true, force: true });
173
+ }
174
+ });