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,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
+ test('提示词过长时先失败,会自动用精简候选重试一次并打上 -retry', async () => {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-retry-'));
10
+ let calls = 0;
11
+ const prompts = [];
12
+ const cortex = createCortex({
13
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
14
+ llm: {
15
+ available: () => true,
16
+ complete: async ({ prompt }) => {
17
+ calls += 1;
18
+ prompts.push(String(prompt).length);
19
+ if (calls === 1) return null;
20
+ const id = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 1 })[0].id;
21
+ return JSON.stringify([{ action: 'keep', ids: [id], reason: 'retry-ok' }]);
22
+ },
23
+ },
24
+ });
25
+ try {
26
+ const now = Date.now();
27
+ for (let i = 0; i < 16; i += 1) {
28
+ cortex.write({ text: `用户:第 ${i} 条很长的日志,${'细节'.repeat(200)}`, kind: 'utterance', title: `长样本 ${i}`, explicit: true, now });
29
+ }
30
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
31
+ assert.equal(calls, 2, '应该调用两次:一次原始、一次精简');
32
+ assert.ok(prompts[1] < prompts[0], '重试的提示词必须更短');
33
+ assert.equal(result.run.status, 'applied');
34
+ assert.match(String(result.run.model), /-retry$/, '成功的重试要打标记');
35
+ } finally {
36
+ cortex.close();
37
+ rmSync(dir, { recursive: true, force: true });
38
+ }
39
+ });
40
+
41
+ test('短提示词失败时不重试,直接记 llm-empty', async () => {
42
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-noretry-'));
43
+ let calls = 0;
44
+ const cortex = createCortex({
45
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
46
+ llm: { available: () => true, complete: async () => { calls += 1; return null; } },
47
+ });
48
+ try {
49
+ const now = Date.now();
50
+ for (let i = 0; i < 3; i += 1) {
51
+ cortex.write({ text: `用户:短 ${i}`, kind: 'utterance', title: `短 ${i}`, explicit: true, now });
52
+ }
53
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
54
+ assert.equal(calls, 1, '短输入不该重试');
55
+ assert.equal(result.run.error, 'llm-empty');
56
+ } finally {
57
+ cortex.close();
58
+ rmSync(dir, { recursive: true, force: true });
59
+ }
60
+ });
61
+
62
+ test('大候选先用精简预算一次成功,并标 -bounded', async () => {
63
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-bounded-'));
64
+ let calls = 0;
65
+ let maxTokensSeen = 0;
66
+ const cortex = createCortex({
67
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
68
+ llm: {
69
+ available: () => true,
70
+ complete: async (options) => {
71
+ calls += 1;
72
+ maxTokensSeen = options?.maxTokens ?? 0;
73
+ const id = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 1 })[0].id;
74
+ return JSON.stringify([{ action: 'keep', ids: [id] }]);
75
+ },
76
+ },
77
+ });
78
+ try {
79
+ const now = Date.now();
80
+ for (let i = 0; i < 40; i += 1) {
81
+ cortex.write({ text: `用户:大样本 ${i} ${'细节'.repeat(150)}`, kind: 'utterance', title: `大 ${i}`, explicit: true, now });
82
+ }
83
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
84
+ assert.equal(calls, 1, '大候选应该一次成功,不必先失败再重试');
85
+ assert.match(String(result.run.model), /-bounded$/);
86
+ assert.ok(maxTokensSeen >= 2000, `bounded 尝试的输出预算应足够(实际 ${maxTokensSeen})`);
87
+ } finally {
88
+ cortex.close();
89
+ rmSync(dir, { recursive: true, force: true });
90
+ }
91
+ });
@@ -0,0 +1,103 @@
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(complete) {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-selection-'));
10
+ const cortex = createCortex({
11
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
12
+ llm: { available: () => true, complete },
13
+ });
14
+ return { dir, cortex };
15
+ }
16
+
17
+ test('候选优先挑低重要度痕迹,高重要度沉底', async () => {
18
+ const { dir, cortex } = setup(async () => JSON.stringify([{ action: 'keep', ids: [] }]));
19
+ try {
20
+ const now = Date.now();
21
+ cortex.write({ text: '用户:高重要度身份记忆。', kind: 'utterance', title: '高', importance: 0.95, explicit: true, now });
22
+ cortex.write({ text: '用户:低重要度碎片甲。', kind: 'utterance', title: '低甲', importance: 0.3, explicit: true, now: now + 1000 });
23
+ cortex.write({ text: '用户:中低重要度碎片乙。', kind: 'utterance', title: '低乙', importance: 0.5, explicit: true, now: now + 2000 });
24
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
25
+ const input = result.run.input;
26
+ assert.equal(input[0].title, '低甲', '最低重要度先问');
27
+ assert.equal(input.at(-1).title, '高', '高重要度沉到最后');
28
+ } finally {
29
+ cortex.close();
30
+ rmSync(dir, { recursive: true, force: true });
31
+ }
32
+ });
33
+
34
+ test('已被摘要覆盖的痕迹排在未覆盖之后', async () => {
35
+ const { dir, cortex } = setup(async () => JSON.stringify([{ action: 'keep', ids: [] }]));
36
+ try {
37
+ const now = Date.now();
38
+ cortex.write({ text: '用户:已经被总结过的一条。', kind: 'utterance', title: '已覆盖', importance: 0.3, explicit: true, now });
39
+ cortex.write({ text: '用户:还没被总结的一条。', kind: 'utterance', title: '未覆盖', importance: 0.3, explicit: true, now: now + 2000 });
40
+ const list = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
41
+ const covered = list.find((trace) => trace.title === '已覆盖');
42
+ cortex.repos.summaries.insert({ scopeId: 'global', level: 'episode', content: '一条旧摘要', sourceIds: [covered.id], coverage: 1 });
43
+ const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
44
+ assert.equal(result.run.input[0].title, '未覆盖');
45
+ } finally {
46
+ cortex.close();
47
+ rmSync(dir, { recursive: true, force: true });
48
+ }
49
+ });
50
+
51
+ test('输入完全相同的第二次运行不再调用模型,也不写新行', async () => {
52
+ let calls = 0;
53
+ let traceId = null;
54
+ const { dir, cortex } = setup(async () => {
55
+ calls += 1;
56
+ return JSON.stringify([{ action: 'keep', ids: traceId ? [traceId] : [] }]);
57
+ });
58
+ try {
59
+ const now = Date.now();
60
+ cortex.write({ text: '用户:同一批里的一条。', kind: 'utterance', explicit: true, now });
61
+ traceId = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 1 })[0].id;
62
+ const first = await cortex.consolidation.run({ scopeId: 'global' });
63
+ assert.equal(calls, 1);
64
+ assert.equal(first.run.status, 'applied');
65
+ const second = await cortex.consolidation.run({ scopeId: 'global' });
66
+ assert.equal(second.skipped, 'unchanged', '同样的输入应直接复用上一次结果');
67
+ assert.equal(calls, 1, '不该再问一次模型');
68
+ assert.equal(cortex.consolidation.list({ scopeId: 'global', limit: 10 }).length, 1, '不该多写一行');
69
+ } finally {
70
+ cortex.close();
71
+ rmSync(dir, { recursive: true, force: true });
72
+ }
73
+ });
74
+
75
+ test('rejected 的同一批输入仍允许重试', async () => {
76
+ let calls = 0;
77
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-selection-retry-'));
78
+ const cortex = createCortex({
79
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
80
+ llm: {
81
+ available: () => true,
82
+ // 第一次返回没有 ids 的决策(会被判 rejected),第二次正常 keep。
83
+ complete: async () => {
84
+ calls += 1;
85
+ return calls === 1
86
+ ? JSON.stringify([{ action: 'archive' }, { action: 'keep' }])
87
+ : JSON.stringify([{ action: 'keep', ids: [] }]);
88
+ },
89
+ },
90
+ });
91
+ try {
92
+ const now = Date.now();
93
+ cortex.write({ text: '用户:会被坏模型回答的一条。', kind: 'utterance', explicit: true, now });
94
+ const first = await cortex.consolidation.run({ scopeId: 'global' });
95
+ assert.equal(first.run.status, 'rejected');
96
+ const second = await cortex.consolidation.run({ scopeId: 'global' });
97
+ assert.equal(calls, 2, 'rejected 说明模型坏了,应允许重试');
98
+ assert.notEqual(second.skipped, 'unchanged');
99
+ } finally {
100
+ cortex.close();
101
+ rmSync(dir, { recursive: true, force: true });
102
+ }
103
+ });
@@ -15,8 +15,8 @@ test('makeId is prefixed and lexically ordered by time', () => {
15
15
  });
16
16
 
17
17
  test('hashText and chainHash are stable', () => {
18
- assert.equal(hashText('白饭'), hashText('白饭'));
19
- assert.notEqual(hashText('白饭'), hashText('米饭'));
18
+ assert.equal(hashText('米饭'), hashText('米饭'));
19
+ assert.notEqual(hashText('米饭'), hashText('面条'));
20
20
  assert.equal(chainHash(null, 'x'), chainHash(null, 'x'));
21
21
  assert.notEqual(chainHash(null, 'x'), chainHash('a', 'x'));
22
22
  });
@@ -29,26 +29,26 @@ test('stableStringify sorts object keys and rejects cycles', () => {
29
29
  });
30
30
 
31
31
  test('tokenizer builds CJK bigrams and latin terms', () => {
32
- const list = tokenList('用户说白饭很好吃 DSH-plugin 2026');
33
- assert.ok(list.includes('白饭'));
32
+ const list = tokenList('用户说米饭很好吃 DSH-plugin 2026');
33
+ assert.ok(list.includes('米饭'));
34
34
  assert.ok(list.includes('用户'));
35
35
  assert.ok(list.includes('dsh'));
36
36
  assert.ok(list.includes('plugin'));
37
- assert.ok(tokens('白饭').has('白饭'));
38
- assert.equal(ftsText('白饭'), '白饭');
37
+ assert.ok(tokens('米饭').has('米饭'));
38
+ assert.equal(ftsText('米饭'), '米饭');
39
39
  });
40
40
 
41
41
  test('FTS match query quotes tokens and supports AND', () => {
42
- assert.equal(buildMatchQuery('白饭 用户'), '"白饭" OR "用户"');
43
- assert.equal(buildMatchQuery('白饭 用户', { mode: 'and' }), '"白饭" AND "用户"');
42
+ assert.equal(buildMatchQuery('米饭 用户'), '"米饭" OR "用户"');
43
+ assert.equal(buildMatchQuery('米饭 用户', { mode: 'and' }), '"米饭" AND "用户"');
44
44
  assert.equal(buildMatchQuery(''), '');
45
45
  });
46
46
 
47
47
  test('jaccard and estimateTokens are bounded', () => {
48
- assert.equal(jaccard('白饭 用户', '白饭 用户'), 1);
49
- assert.ok(jaccard('白饭 用户', '插件 安装') < 0.2);
48
+ assert.equal(jaccard('米饭 用户', '米饭 用户'), 1);
49
+ assert.ok(jaccard('米饭 用户', '插件 安装') < 0.2);
50
50
  assert.ok(estimateTokens('') === 0);
51
- assert.ok(estimateTokens('白饭') >= 1);
51
+ assert.ok(estimateTokens('米饭') >= 1);
52
52
  });
53
53
 
54
54
  test('config normalizes paths and clamps numbers', () => {
@@ -0,0 +1,38 @@
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 { openDatabase, migrate } from '../../src/store/database.js';
7
+ import { recomputeEpisodeCoverage } from '../../src/engines/summary-coverage.js';
8
+
9
+ test('重算 v1 摘要的 coverage,按重要度加权,并跳过已 v2 的', () => {
10
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-coverage-rewrite-'));
11
+ const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
12
+ migrate(db);
13
+ try {
14
+ const now = '2026-11-15T10:00:00.000Z';
15
+ db.prepare("INSERT INTO events(id, seq, at, kind, scope_id, payload_json, hash) VALUES ('evt_1', 1, ?, 'observation', 'global', '{}', 'h0')").run(now);
16
+ const insert = db.prepare(`INSERT INTO traces(id, scope_id, kind, state, title, content, event_id, hash, recorded_at, updated_at, created_at, importance)
17
+ VALUES (?, 'global', 'observation', 'active', ?, ?, 'evt_1', ?, ?, ?, ?, ?)`);
18
+ // 窗口内:2 条重要(0.9)+ 2 条琐碎(0.1);摘要只覆盖了 2 条重要
19
+ insert.run('t1', '重要一', '正文', 'h1', '2026-11-15T09:00:00.000Z', now, now, 0.9);
20
+ insert.run('t2', '重要二', '正文', 'h2', '2026-11-15T09:30:00.000Z', now, now, 0.9);
21
+ insert.run('t3', '琐碎一', '正文', 'h3', '2026-11-15T08:00:00.000Z', now, now, 0.1);
22
+ insert.run('t4', '琐碎二', '正文', 'h4', '2026-11-15T07:00:00.000Z', now, now, 0.1);
23
+
24
+ db.prepare(`INSERT INTO summaries(id, scope_id, level, period_start, period_end, content, source_ids_json, coverage, model, created_at)
25
+ VALUES ('s_v1', 'global', 'episode', '2026-11-15T06:00:00.000Z', '2026-11-15T10:00:00.000Z', '旧摘要', '["t1","t2"]', 0.05, 'extractive-v1', ?)`).run(now);
26
+ db.prepare(`INSERT INTO summaries(id, scope_id, level, period_start, period_end, content, source_ids_json, coverage, model, created_at)
27
+ VALUES ('s_v2', 'global', 'episode', '2026-11-15T06:00:00.000Z', '2026-11-15T10:00:00.000Z', '新摘要', '["t1"]', 0.8, 'extractive-v2-weighted', ?)`).run(now);
28
+
29
+ const result = recomputeEpisodeCoverage({ db, scopeId: 'global' });
30
+ assert.equal(result.candidates, 1, '只应候选 v1 摘要');
31
+ assert.equal(result.updates.length, 1);
32
+ // covered = 0.9+0.9 = 1.8;total = 1.8+0.1+0.1 = 2.0 → 0.9
33
+ assert.equal(result.updates[0].to, 0.9);
34
+ } finally {
35
+ db.close();
36
+ rmSync(dir, { recursive: true, force: true });
37
+ }
38
+ });
@@ -0,0 +1,34 @@
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 { openDatabase, migrate } from '../../src/store/database.js';
7
+ import { findDuplicateEpisodes } from '../../src/engines/summary-dedupe.js';
8
+
9
+ test('重合窗口 + 内容几乎一致才判为重复', () => {
10
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-dedupe-'));
11
+ const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
12
+ migrate(db);
13
+ try {
14
+ const now = '2026-11-15T10:00:00.000Z';
15
+ const insert = db.prepare(`INSERT INTO summaries(id, scope_id, level, period_start, period_end, content, source_ids_json, coverage, model, created_at)
16
+ VALUES (?, 'global', 'episode', ?, ?, ?, ?, 0.5, 'extractive-v2-weighted', ?)`);
17
+ // 同一窗口(重叠 ≈99%)、内容完全相同
18
+ insert.run('a', '2026-11-11T13:50:00.000Z', '2026-11-12T13:40:00.000Z', '这段时间记住了:用户否决了单图网格绑定,决定借模型。', '["t1","t2"]', '2026-11-12T13:48:00.000Z');
19
+ insert.run('b', '2026-11-11T13:52:00.000Z', '2026-11-12T13:44:00.000Z', '这段时间记住了:用户否决了单图网格绑定,决定借模型。', '["t2","t3"]', '2026-11-12T15:35:00.000Z');
20
+ // 完全不同的窗口与内容
21
+ insert.run('c', '2026-11-13T00:00:00.000Z', '2026-11-14T00:00:00.000Z', '另一段时间:修好了向量回填,覆盖率从 0.22 到 1.0。', '["t9"]', now);
22
+
23
+ const result = findDuplicateEpisodes({ db, scopeId: 'global' });
24
+ assert.equal(result.candidates, 3);
25
+ assert.equal(result.clusters.length, 1, '只有 a/b 该成簇');
26
+ const cluster = result.clusters[0];
27
+ assert.equal(cluster.keep.id, 'b', '保留较新的一条');
28
+ assert.deepEqual(cluster.remove.map((item) => item.id), ['a']);
29
+ assert.deepEqual(cluster.unionSources.sort(), ['t1', 't2', 't3']);
30
+ } finally {
31
+ db.close();
32
+ rmSync(dir, { recursive: true, force: true });
33
+ }
34
+ });
@@ -0,0 +1,14 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { clampThreshold } from '../../src/engines/consolidate.js';
4
+
5
+ test('相似度阈值被夹在 0.5–0.99,非法值回落到 0.8', () => {
6
+ assert.equal(clampThreshold(0.1), 0.5);
7
+ // 0 当作「没传」处理,回落到默认 0.8(比按 0 全合安全)。
8
+ assert.equal(clampThreshold(0), 0.8);
9
+ assert.equal(clampThreshold(1.5), 0.99);
10
+ assert.equal(clampThreshold(0.8), 0.8);
11
+ assert.equal(clampThreshold('0.7'), 0.7);
12
+ assert.equal(clampThreshold(undefined), 0.8);
13
+ assert.equal(clampThreshold(Number.NaN), 0.8);
14
+ });
@@ -100,15 +100,15 @@ test('low coherence with no recent consolidation proposes a consolidation', () =
100
100
  test('a recall query is returned alongside the write', () => {
101
101
  const { dir, db, develop } = setup();
102
102
  try {
103
- develop.step({ text: '用户说会买白饭。', explicit: true, now: Date.parse('2026-11-11T11:00:00+08:00') });
103
+ develop.step({ text: '用户说会买米饭。', explicit: true, now: Date.parse('2026-11-11T11:00:00+08:00') });
104
104
  const result = develop.step({
105
- text: '今天又想到白饭了。',
105
+ text: '今天又想到米饭了。',
106
106
  explicit: true,
107
107
  now: Date.parse('2026-11-11T12:00:00+08:00'),
108
- recallQuery: '白饭',
108
+ recallQuery: '米饭',
109
109
  recallBudget: 300,
110
110
  });
111
- assert.ok(result.recall.items.some((item) => item.snippet.includes('白饭')));
111
+ assert.ok(result.recall.items.some((item) => item.snippet.includes('米饭')));
112
112
  } finally {
113
113
  closeDatabase(db);
114
114
  rmSync(dir, { recursive: true, force: true });
@@ -70,7 +70,7 @@ test('autoFacts queue candidate edges only when graphCandidateAutoFacts is enabl
70
70
  const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-edge-autofacts-'));
71
71
  const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { autoFacts: true, graphCandidateAutoFacts: true } } });
72
72
  try {
73
- const written = cortex.write({ text: '用户喜欢白饭。', explicit: true });
73
+ const written = cortex.write({ text: '用户喜欢米饭。', explicit: true });
74
74
  assert.ok(written.edgeCandidates.length >= 1);
75
75
  assert.ok(cortex.graphCandidates({ scopeId: 'global' }).length >= 1);
76
76
  assert.equal(cortex.graphData({ scopeId: 'global' }).edges.length, 0);
@@ -84,7 +84,7 @@ test('autoFacts do not queue candidate edges by default', () => {
84
84
  const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-edge-autofacts-off-'));
85
85
  const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { autoFacts: true } } });
86
86
  try {
87
- const written = cortex.write({ text: '用户喜欢白饭。', explicit: true });
87
+ const written = cortex.write({ text: '用户喜欢米饭。', explicit: true });
88
88
  assert.equal(written.edgeCandidates?.length ?? 0, 0);
89
89
  assert.equal(cortex.graphCandidates({ scopeId: 'global' }).length, 0);
90
90
  } finally {
@@ -53,7 +53,8 @@ test('service self exposes emotion text and develop records it', () => {
53
53
  try {
54
54
  const result = cortex.step({ text: '用户今天很难过,助手有点心疼他。', explicit: true });
55
55
  assert.ok(result.emotion?.event);
56
- assert.match(cortex.self().emotion, /用户/);
56
+ // Default persona has no userAddress, so aliases fold onto the neutral '你'.
57
+ assert.match(cortex.self().emotion, /你/);
57
58
  } finally {
58
59
  cortex.close();
59
60
  rmSync(dir, { recursive: true, force: true });
@@ -25,10 +25,10 @@ function setup() {
25
25
  }
26
26
 
27
27
  test('scoreTraceText detects promises, preferences and emotion polarity', () => {
28
- const promise = scoreTraceText('用户说会买白饭,会一直在一起。');
28
+ const promise = scoreTraceText('用户说会买米饭,会一直在一起。');
29
29
  assert.equal(promise.kind, 'promise');
30
30
  assert.ok(promise.importance > 0.5);
31
- const preference = scoreTraceText('助手喜欢白饭,不喜欢冷掉的米饭。');
31
+ const preference = scoreTraceText('助手喜欢米饭,不喜欢冷掉的米饭。');
32
32
  assert.equal(preference.kind, 'preference');
33
33
  const sad = scoreTraceText('用户今天很难过,助手有点心疼。');
34
34
  assert.equal(sad.kind, 'emotion');
@@ -37,8 +37,8 @@ test('scoreTraceText detects promises, preferences and emotion polarity', () =>
37
37
  });
38
38
 
39
39
  test('compression value falls as text gets longer', () => {
40
- const short = compressionValue('白饭', { importance: 0.8, salience: 0.8 });
41
- const long = compressionValue('白饭'.repeat(200), { importance: 0.8, salience: 0.8 });
40
+ const short = compressionValue('米饭', { importance: 0.8, salience: 0.8 });
41
+ const long = compressionValue('米饭'.repeat(200), { importance: 0.8, salience: 0.8 });
42
42
  assert.ok(short > long);
43
43
  });
44
44
 
@@ -46,10 +46,10 @@ test('encode writes a trace, audit row and explicit facts', () => {
46
46
  const { dir, db, events, traces, facts, audit, engine } = setup();
47
47
  try {
48
48
  const result = engine.encode({
49
- text: '用户说会买白饭,助手会一直等。',
49
+ text: '用户说会买米饭,助手会一直等。',
50
50
  actor: 'user',
51
51
  explicit: true,
52
- facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }],
52
+ facts: [{ subject: '用户', predicate: 'likes', object: '米饭' }],
53
53
  });
54
54
  assert.equal(result.skipped, false);
55
55
  assert.equal(result.trace.kind, 'promise');
@@ -34,10 +34,10 @@ test('policies are versioned, activated and rolled back', () => {
34
34
  test('approved retrieval policy changes the live retrieval budget', () => {
35
35
  const { dir, cortex } = setup();
36
36
  try {
37
- cortex.write({ text: '用户说会买白饭。', explicit: true });
37
+ cortex.write({ text: '用户说会买米饭。', explicit: true });
38
38
  const policy = cortex.evolution.propose({ kind: 'retrieval', config: { budget: 100 }, rationale: 'small budget' });
39
39
  cortex.evolution.approve(policy.id);
40
- const result = cortex.search('白饭', { budget: 5000 });
40
+ const result = cortex.search('米饭', { budget: 5000 });
41
41
  assert.equal(result.budget.total, 100);
42
42
  } finally {
43
43
  cortex.close();
@@ -100,12 +100,12 @@ test('evolution can evaluate a candidate policy and persist metrics', async () =
100
100
  const { dir, cortex } = setup();
101
101
  try {
102
102
  const policy = cortex.evolution.propose({ kind: 'retrieval', config: { budget: 300 }, rationale: 'evaluate me' });
103
- const queries = [{ query: '白饭', relevant: ['a'] }, { query: '插件', relevant: ['b'] }];
103
+ const queries = [{ query: '米饭', relevant: ['a'] }, { query: '插件', relevant: ['b'] }];
104
104
  const evaluated = await cortex.evolution.evaluate({
105
105
  id: policy.id,
106
106
  queries,
107
- current: async (query) => ({ items: query === '白饭' ? [{ id: 'x' }] : [{ id: 'b' }] }),
108
- candidate: async (query) => ({ items: query === '白饭' ? [{ id: 'a' }] : [{ id: 'b' }] }),
107
+ current: async (query) => ({ items: query === '米饭' ? [{ id: 'x' }] : [{ id: 'b' }] }),
108
+ candidate: async (query) => ({ items: query === '米饭' ? [{ id: 'a' }] : [{ id: 'b' }] }),
109
109
  });
110
110
  assert.ok(evaluated.metrics);
111
111
  assert.ok(evaluated.comparison.delta.recallAtK > 0);
@@ -0,0 +1,41 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { extractFactCandidates } from '../../src/engines/extract.js';
4
+
5
+ test('问句不产生事实', () => {
6
+ assert.equal(extractFactCandidates('你会有感觉吗?').length, 0);
7
+ assert.equal(extractFactCandidates('你会先看见它们吗').length, 0);
8
+ assert.equal(extractFactCandidates('小明是程序员吗?').length, 0);
9
+ });
10
+
11
+ test('假设句不产生事实', () => {
12
+ assert.equal(extractFactCandidates('要是想聊两句,助手就趴在这儿听。').length, 0);
13
+ assert.equal(extractFactCandidates('如果你喜欢米饭,就多吃一碗。').length, 0);
14
+ });
15
+
16
+ test('单字功能词不再被当成主语', () => {
17
+ const facts = extractFactCandidates('要是想聊两句。');
18
+ assert.equal(facts.find((fact) => fact.subject === '要'), undefined);
19
+ });
20
+
21
+ test('普通陈述句仍然抽事实', () => {
22
+ const facts = extractFactCandidates('用户喜欢米饭。');
23
+ assert.ok(facts.some((fact) => fact.predicate === 'likes' && fact.object === '米饭'));
24
+ const isFacts = extractFactCandidates('小明是程序员。');
25
+ assert.ok(isFacts.some((fact) => fact.predicate === 'is' && fact.object === '程序员'));
26
+ });
27
+
28
+ test('设计讨论与方案稿不产生事实', () => {
29
+ assert.equal(extractFactCandidates('> 新坑 3:你到底在跟谁说话。').length, 0);
30
+ assert.equal(extractFactCandidates('新坑 4:一个自我被归档,你会有感觉吗。').length, 0);
31
+ assert.equal(extractFactCandidates('设计草案:我们打算把记忆层拆成三层。').length, 0);
32
+ assert.equal(extractFactCandidates('待办:明天把桥的接口补上。').length, 0);
33
+ assert.ok(extractFactCandidates('用户喜欢米饭。').length > 0, '普通陈述仍然能抽');
34
+ });
35
+
36
+ test('引用别人的话和命令句不产生事实', () => {
37
+ assert.equal(extractFactCandidates('他说:「小明喜欢白猫。」').length, 0, '引号里是别人的话');
38
+ assert.ok(extractFactCandidates('小明喜欢白猫。').length > 0, '同样的句子不在引号里就能抽');
39
+ assert.equal(extractFactCandidates('记得把桥修好,小桥是重点。').length, 0, '命令不是事实');
40
+ assert.ok(extractFactCandidates('小桥是重点。').length > 0);
41
+ });
@@ -0,0 +1,51 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { guardFactCandidate } from '../../src/engines/fact-guard.js';
4
+ import { extractFactsWithLlm } from '../../src/engines/llm-facts.js';
5
+ import { createFactExtractor } from '../../src/engines/extract.js';
6
+
7
+ test('junk triples seen in the 0.4.22 store are rejected', () => {
8
+ assert.equal(guardFactCandidate({ subject: '现', predicate: 'at', object: ':' }), null);
9
+ assert.equal(guardFactCandidate({ subject: '只', predicate: 'is', object: '一些' }), null);
10
+ assert.equal(guardFactCandidate({ subject: '还', predicate: 'is', object: '很好' }), null);
11
+ assert.equal(guardFactCandidate({ subject: '用户', predicate: '现', object: '米饭' }), null);
12
+ assert.equal(guardFactCandidate({ subject: '用户', predicate: 'likes', object: ':' }), null);
13
+ assert.equal(guardFactCandidate({ subject: '用户', predicate: 'likes', object: '' }), null);
14
+ });
15
+
16
+ test('a plausible triple survives and is normalized', () => {
17
+ const guarded = guardFactCandidate({ subject: ' 用户 ', predicate: ' Likes ', object: '米饭', confidence: 1.4 });
18
+ assert.deepEqual(guarded, { subject: '用户', predicate: 'likes', object: '米饭', confidence: 1 });
19
+ });
20
+
21
+ test('LLM extractor drops junk and keeps the valid fact', async () => {
22
+ const llm = {
23
+ complete: async () => JSON.stringify({
24
+ facts: [
25
+ { subject: '现', predicate: 'at', object: ':', confidence: 0.9 },
26
+ { subject: '只', predicate: 'is', object: '猫', confidence: 0.9 },
27
+ { subject: '用户', predicate: 'likes', object: '米饭', confidence: 0.8 },
28
+ { subject: '用户', predicate: 'likes', object: '海', confidence: 0.3 },
29
+ ],
30
+ }),
31
+ };
32
+ const result = await extractFactsWithLlm({ llm, text: '用户喜欢米饭。' });
33
+ assert.equal(result.candidates.length, 1);
34
+ assert.equal(result.candidates[0].subject, '用户');
35
+ });
36
+
37
+ test('extractor resolves only guarded candidates', () => {
38
+ const upserts = [];
39
+ const resolved = [];
40
+ const entities = { upsert: ({ name }) => { upserts.push(name); return { id: `ent_${name}` }; } };
41
+ const facts = { resolve: (input) => { resolved.push(input); return { fact: { id: 'f' } }; } };
42
+ const extractor = createFactExtractor({ entities, facts });
43
+ const result = extractor.extract({
44
+ text: '助手是本地记忆助手。现是在:。',
45
+ persona: { selfName: '助手', userAddress: '用户' },
46
+ });
47
+ assert.ok(upserts.includes('助手'));
48
+ assert.ok(!upserts.includes('现'));
49
+ assert.ok(resolved.every((item) => /^[a-z_]+$/.test(item.predicate)));
50
+ assert.ok(result.candidates.length >= 1);
51
+ });
@@ -0,0 +1,44 @@
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 { extractFactCandidates } from '../../src/engines/extract.js';
8
+
9
+ test('叙述句碎片不会被抽成事实(等/收一收/水里)', () => {
10
+ const candidates = extractFactCandidates('它在水里收一收,然后又等了一会儿。', { selfName: '助手', userAddress: '用户' });
11
+ assert.ok(Array.isArray(candidates));
12
+ assert.equal(candidates.length, 0, `不该抽出事实:${JSON.stringify(candidates)}`);
13
+ });
14
+
15
+ test('正常句子仍然能抽出事实', () => {
16
+ const candidates = extractFactCandidates('助手喜欢米饭。', { selfName: '助手', userAddress: '用户' });
17
+ assert.ok(candidates.length > 0, '正常句子不该被误杀');
18
+ assert.equal(candidates[0].predicate, 'likes');
19
+ });
20
+
21
+ test('LLM 没开时健康报告给出明确警告', () => {
22
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-warn-'));
23
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: false } } });
24
+ try {
25
+ const health = cortex.health({ scopeId: 'global' });
26
+ const warn = health.issues.find((issue) => issue.code === 'LLM_DISABLED');
27
+ assert.ok(warn, 'features.llm=false 时应提示');
28
+ } finally {
29
+ cortex.close();
30
+ rmSync(dir, { recursive: true, force: true });
31
+ }
32
+ });
33
+
34
+ test('LLM 打开时不再报 LLM_DISABLED', () => {
35
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-on-'));
36
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } } });
37
+ try {
38
+ const health = cortex.health({ scopeId: 'global' });
39
+ assert.equal(health.issues.find((issue) => issue.code === 'LLM_DISABLED'), undefined);
40
+ } finally {
41
+ cortex.close();
42
+ rmSync(dir, { recursive: true, force: true });
43
+ }
44
+ });
@@ -11,20 +11,20 @@ test('belief uses the transaction timestamp, not updated_at', () => {
11
11
  try {
12
12
  const t1 = Date.parse('2026-11-10T10:00:00+08:00');
13
13
  const t2 = Date.parse('2026-11-11T10:00:00+08:00');
14
- cortex.write({ text: '用户喜欢白饭。', explicit: true, now: t1, facts: [{ subject: '用户', predicate: '喜欢', object: '白饭' }] });
14
+ cortex.write({ text: '用户喜欢米饭。', explicit: true, now: t1, facts: [{ subject: '用户', predicate: '喜欢', object: '米饭' }] });
15
15
  cortex.write({ text: '用户现在喜欢面。', explicit: true, now: t2, facts: [{ subject: '用户', predicate: '喜欢', object: '面' }] });
16
16
  const old = cortex.asOf({ subject: '用户', predicate: '喜欢', at: new Date(t2 - 1000).toISOString(), mode: 'belief' });
17
17
  assert.equal(old.facts.length, 1);
18
- assert.match(old.facts[0].object, /白饭/);
18
+ assert.match(old.facts[0].object, /米饭/);
19
19
  assert.ok(old.facts[0].supersededAt);
20
20
  const now = cortex.asOf({ subject: '用户', predicate: '喜欢', at: new Date(t2 + 1000).toISOString(), mode: 'belief' });
21
21
  assert.equal(now.facts.length, 1);
22
22
  assert.match(now.facts[0].object, /面/);
23
23
  const historical = cortex.asOf({ subject: '用户', predicate: '喜欢', at: new Date(t1 + 1000).toISOString(), mode: 'historical' });
24
- assert.match(historical.facts[0].object, /白饭/);
24
+ assert.match(historical.facts[0].object, /米饭/);
25
25
  const strict = cortex.asOf({ subject: '用户', predicate: '喜欢', mode: 'strict' });
26
26
  assert.match(strict.facts[0].object, /面/);
27
- assert.doesNotMatch(strict.facts.map((fact) => fact.object).join(' '), /白饭/);
27
+ assert.doesNotMatch(strict.facts.map((fact) => fact.object).join(' '), /米饭/);
28
28
  } finally {
29
29
  cortex.close();
30
30
  rmSync(dir, { recursive: true, force: true });