dsh-cortex-memory 0.4.11 → 0.4.15

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 (140) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/LICENSE +1 -1
  3. package/README.md +62 -36
  4. package/bench/README.md +29 -0
  5. package/bench/ab-engine.mjs +60 -0
  6. package/bench/ann-bench.mjs +78 -0
  7. package/bench/hnsw-bench.mjs +79 -0
  8. package/bench/locomo.js +89 -0
  9. package/bench/longmemeval.js +83 -0
  10. package/bench/metrics.js +67 -0
  11. package/bench/migration-bench.mjs +69 -0
  12. package/bench/results/semantic-cn.json +24 -0
  13. package/bench/run.js +77 -0
  14. package/bench/semantic-cn.js +116 -0
  15. package/bench/synthetic.js +99 -0
  16. package/bench/vector-ab.mjs +76 -0
  17. package/docs/compatibility.md +39 -0
  18. package/docs/install-windows.md +144 -0
  19. package/docs/models.md +183 -0
  20. package/docs/multimodal.md +112 -0
  21. package/docs/permissions.md +53 -0
  22. package/docs/privacy.md +50 -0
  23. package/docs/scopes.md +142 -0
  24. package/examples/README.md +72 -0
  25. package/examples/setup-cortex-bge.ps1 +66 -0
  26. package/examples/uninstall-cortex.ps1 +91 -0
  27. package/index.js +23 -0
  28. package/package.json +11 -5
  29. package/src/core/config.js +27 -0
  30. package/src/engines/extract.js +10 -10
  31. package/src/engines/retrieve.js +30 -5
  32. package/src/guardian/guardian.js +2 -15
  33. package/src/guardian/invariants.js +9 -5
  34. package/src/host/runtime.js +10 -14
  35. package/src/self/evolution.js +32 -5
  36. package/src/self/policies.js +21 -2
  37. package/src/service/cortex.js +3 -2
  38. package/src/store/database.js +9 -1
  39. package/src/store/schema.sql +2 -1
  40. package/src/vector/hnsw.js +5 -5
  41. package/test/integration/_helpers.js +128 -0
  42. package/test/integration/acceptance.test.js +803 -0
  43. package/test/integration/ann-load.test.js +61 -0
  44. package/test/integration/api-contract.test.js +1476 -0
  45. package/test/integration/backup-privacy.test.js +214 -0
  46. package/test/integration/consolidate.test.js +75 -0
  47. package/test/integration/edge-cases.test.js +1088 -0
  48. package/test/integration/exchange.test.js +326 -0
  49. package/test/integration/life-loop.test.js +188 -0
  50. package/test/integration/load.test.js +751 -0
  51. package/test/integration/markdown-sync.test.js +35 -0
  52. package/test/integration/policy-query-api.test.js +306 -0
  53. package/test/integration/resilience-writes.test.js +241 -0
  54. package/test/integration/tools-contract.test.js +1324 -0
  55. package/test/unit/ann-edge.test.js +102 -0
  56. package/test/unit/ann.test.js +77 -0
  57. package/test/unit/api-client.test.js +576 -0
  58. package/test/unit/api-validate.test.js +19 -0
  59. package/test/unit/api.test.js +555 -0
  60. package/test/unit/appraisal.test.js +48 -0
  61. package/test/unit/attachments.test.js +33 -0
  62. package/test/unit/autonomy.test.js +53 -0
  63. package/test/unit/batch.test.js +46 -0
  64. package/test/unit/bench.test.js +40 -0
  65. package/test/unit/benchmark-synthetic.test.js +52 -0
  66. package/test/unit/client-contract.test.js +29 -0
  67. package/test/unit/compression.test.js +76 -0
  68. package/test/unit/core.test.js +77 -0
  69. package/test/unit/develop.test.js +130 -0
  70. package/test/unit/development.test.js +68 -0
  71. package/test/unit/digest.test.js +26 -0
  72. package/test/unit/dsr.test.js +111 -0
  73. package/test/unit/edges-candidates.test.js +113 -0
  74. package/test/unit/emotion.test.js +61 -0
  75. package/test/unit/encode.test.js +98 -0
  76. package/test/unit/evolution.test.js +130 -0
  77. package/test/unit/external-ann-search.test.js +50 -0
  78. package/test/unit/external-ann.test.js +29 -0
  79. package/test/unit/facts-belief.test.js +32 -0
  80. package/test/unit/facts.test.js +107 -0
  81. package/test/unit/feature-overrides.test.js +42 -0
  82. package/test/unit/fts-migration.test.js +42 -0
  83. package/test/unit/graph.test.js +79 -0
  84. package/test/unit/growth-reflect.test.js +123 -0
  85. package/test/unit/guard-runtime.test.js +40 -0
  86. package/test/unit/guardian.test.js +91 -0
  87. package/test/unit/health-privacy.test.js +102 -0
  88. package/test/unit/hnsw.test.js +35 -0
  89. package/test/unit/host-runtime.test.js +142 -0
  90. package/test/unit/host.test.js +58 -0
  91. package/test/unit/identity.test.js +98 -0
  92. package/test/unit/induct-evaluate.test.js +41 -0
  93. package/test/unit/ingest-extracted.test.js +35 -0
  94. package/test/unit/initiative.test.js +90 -0
  95. package/test/unit/jobs.test.js +93 -0
  96. package/test/unit/json-snapshot.test.js +57 -0
  97. package/test/unit/life-consolidate.test.js +34 -0
  98. package/test/unit/life.test.js +149 -0
  99. package/test/unit/llm-facts-integration.test.js +27 -0
  100. package/test/unit/llm-facts.test.js +16 -0
  101. package/test/unit/llm.test.js +45 -0
  102. package/test/unit/locomo.test.js +45 -0
  103. package/test/unit/longmemeval.test.js +56 -0
  104. package/test/unit/markdown-import.test.js +44 -0
  105. package/test/unit/markdown.test.js +34 -0
  106. package/test/unit/memory-edit.test.js +112 -0
  107. package/test/unit/metrics.test.js +26 -0
  108. package/test/unit/migration.test.js +38 -0
  109. package/test/unit/model-config.test.js +52 -0
  110. package/test/unit/narrative.test.js +62 -0
  111. package/test/unit/playbook-consolidate.test.js +24 -0
  112. package/test/unit/privacy-scope.test.js +39 -0
  113. package/test/unit/profile.test.js +20 -0
  114. package/test/unit/prompt.test.js +42 -0
  115. package/test/unit/providers.test.js +42 -0
  116. package/test/unit/qa.test.js +100 -0
  117. package/test/unit/query.test.js +53 -0
  118. package/test/unit/retention.test.js +31 -0
  119. package/test/unit/retrieval-ranking.test.js +31 -0
  120. package/test/unit/retrieve.test.js +117 -0
  121. package/test/unit/rotation.test.js +25 -0
  122. package/test/unit/scanner.test.js +50 -0
  123. package/test/unit/scenario.test.js +78 -0
  124. package/test/unit/scheduler.test.js +136 -0
  125. package/test/unit/self-state.test.js +94 -0
  126. package/test/unit/service.test.js +72 -0
  127. package/test/unit/shiori-import.test.js +77 -0
  128. package/test/unit/skills.test.js +104 -0
  129. package/test/unit/store.test.js +111 -0
  130. package/test/unit/temporal-graph.test.js +44 -0
  131. package/test/unit/tiers.test.js +39 -0
  132. package/test/unit/tokenizer-fts.test.js +35 -0
  133. package/test/unit/tools.test.js +122 -0
  134. package/test/unit/upgrade-0412.test.js +104 -0
  135. package/test/unit/upgrade-0413.test.js +84 -0
  136. package/test/unit/upgrade-0414.test.js +101 -0
  137. package/test/unit/vector-ann.test.js +53 -0
  138. package/test/unit/vector-async.test.js +69 -0
  139. package/test/unit/vector.test.js +68 -0
  140. package/test/unit/working.test.js +80 -0
@@ -0,0 +1,44 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { parseTemporal, withinWindow, parseDuration, formatRelative } from '../../src/memory/temporal.js';
4
+ import { degreeCentrality, pageRank, connectedComponents, labelPropagation, summarizeGraph } from '../../src/engines/graph-analytics.js';
5
+
6
+ const NOW = Date.parse('2026-11-11T12:00:00+08:00');
7
+
8
+ test('temporal parser understands relative and absolute windows', () => {
9
+ assert.equal(parseTemporal('今天做了什么', NOW).label, 'today');
10
+ assert.equal(parseTemporal('昨天', NOW).label, 'yesterday');
11
+ assert.equal(parseTemporal('3天前', NOW).label, '3-days-ago');
12
+ assert.equal(parseTemporal('2026-11-05', NOW).label, 'date');
13
+ assert.equal(parseTemporal('没有时间词', NOW), null);
14
+ const window = parseTemporal('今天', NOW);
15
+ assert.equal(withinWindow(new Date(NOW).toISOString(), window), true);
16
+ assert.equal(withinWindow(new Date(NOW - 3 * 86400000).toISOString(), window), false);
17
+ });
18
+
19
+ test('duration and relative formatting work', () => {
20
+ assert.equal(parseDuration('2h'), 7_200_000);
21
+ assert.equal(parseDuration('bad', 42), 42);
22
+ assert.match(formatRelative(new Date(NOW - 5000).toISOString(), NOW), /刚刚/);
23
+ assert.match(formatRelative(new Date(NOW - 2 * 3600000).toISOString(), NOW), /小时前/);
24
+ });
25
+
26
+ test('graph analytics ranks, groups and summarizes', () => {
27
+ const edges = [
28
+ { fromId: 'a', toId: 'b', weight: 2 },
29
+ { fromId: 'b', toId: 'c', weight: 1 },
30
+ { fromId: 'd', toId: 'e', weight: 1 },
31
+ ];
32
+ const degree = degreeCentrality(edges);
33
+ assert.ok(degree.b >= degree.a);
34
+ const rank = pageRank(edges);
35
+ assert.ok(rank.b > 0);
36
+ const components = connectedComponents(edges);
37
+ assert.equal(components.length, 2);
38
+ const communities = labelPropagation(edges);
39
+ assert.equal(communities.length, 2);
40
+ const summary = summarizeGraph(edges);
41
+ assert.equal(summary.nodes, 5);
42
+ assert.equal(summary.edges, 3);
43
+ assert.ok(summary.top.length > 0);
44
+ });
@@ -0,0 +1,39 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { selectTiers, renderTiers, DEFAULT_TIER_BUDGETS } from '../../src/prompt/tiers.js';
4
+
5
+ function item(id, importance, body = '这是一段正文。') {
6
+ return { id, importance, title: id, layer: 'L2', snippet: body, utility: importance };
7
+ }
8
+
9
+ test('tiers classify by importance and respect per-tier budgets', () => {
10
+ const items = [
11
+ item('p1', 0.95, '永久正文'),
12
+ item('h1', 0.55, '加强正文'),
13
+ item('c1', 0.1, '冷正文'),
14
+ ];
15
+ const selection = selectTiers(items, { budgets: { perm: 50, hot: 50, cold: 50 } });
16
+ assert.equal(selection.perm.length, 1);
17
+ assert.equal(selection.hot.length, 1);
18
+ assert.equal(selection.cold.length, 1);
19
+ assert.match(selection.cold[0].render, /正文按需取回/);
20
+ assert.doesNotMatch(selection.cold[0].render, /冷正文/);
21
+ });
22
+
23
+ test('tiers emit an omitted count and never overflow a bucket', () => {
24
+ const items = Array.from({ length: 20 }, (_, index) => item(`h${index}`, 0.5, '很长的一段正文'.repeat(20)));
25
+ const selection = selectTiers(items, { budgets: { perm: 20, hot: 200, cold: 20 } });
26
+ assert.ok(selection.omitted > 0);
27
+ assert.ok(selection.used.hot <= 200);
28
+ const text = renderTiers(selection);
29
+ assert.match(text, /加强层/);
30
+ assert.match(text, /预算省略/);
31
+ });
32
+
33
+ test('tiers render only non-empty sections and expose defaults', () => {
34
+ assert.deepEqual(DEFAULT_TIER_BUDGETS, { perm: 700, hot: 900, cold: 400 });
35
+ const selection = selectTiers([item('p1', 0.9, '正文')]);
36
+ const text = renderTiers(selection);
37
+ assert.match(text, /永久层/);
38
+ assert.doesNotMatch(text, /卸载层/);
39
+ });
@@ -0,0 +1,35 @@
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 { ftsText, buildMatchQuery } from '../../src/memory/tokenizer.js';
7
+ import { createCortex } from '../../src/service/cortex.js';
8
+
9
+ test('CJK soft FTS keeps bigrams and adds non-stop single characters', () => {
10
+ const exact = ftsText('白饭 记忆引擎');
11
+ assert.equal(exact, '白饭 记忆 忆引 引擎 记忆引擎');
12
+ const indexed = ftsText('白饭 记忆引擎', { soft: true });
13
+ assert.ok(indexed.includes('白饭'));
14
+ assert.ok(indexed.includes('饭'));
15
+ assert.ok(indexed.includes('记忆引擎'));
16
+ assert.ok(indexed.includes('记'));
17
+ const query = buildMatchQuery('米饭', { soft: true });
18
+ assert.ok(query.includes('米饭'));
19
+ assert.ok(query.includes('米'));
20
+ assert.ok(query.includes('饭'));
21
+ assert.equal(buildMatchQuery('米饭'), '"米饭"');
22
+ });
23
+
24
+ test('a shared-character paraphrase can fall back to FTS', () => {
25
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-char-fts-'));
26
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
27
+ try {
28
+ cortex.write({ text: '白饭', explicit: true });
29
+ const result = cortex.search('米饭', { limit: 10 });
30
+ assert.ok(result.items.some((item) => item.snippet?.includes('白饭')));
31
+ } finally {
32
+ cortex.close();
33
+ rmSync(dir, { recursive: true, force: true });
34
+ }
35
+ });
@@ -0,0 +1,122 @@
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 { createToolDefinitions } from '../../src/tools/definitions.js';
8
+
9
+ function setup() {
10
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-tools-'));
11
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), scope: 'global' } });
12
+ const tools = Object.fromEntries(createToolDefinitions(cortex).map((tool) => [tool.name, tool]));
13
+ return { dir, cortex, tools };
14
+ }
15
+
16
+ test('all tools are present and have text output', () => {
17
+ const { dir, cortex, tools } = setup();
18
+ try {
19
+ const names = Object.keys(tools).sort();
20
+ assert.deepEqual(names, [
21
+ 'cortex_as_of', 'cortex_compress', 'cortex_consolidate', 'cortex_digest', 'cortex_emotion', 'cortex_evolve', 'cortex_feedback', 'cortex_forget', 'cortex_get', 'cortex_goal', 'cortex_guard', 'cortex_health',
22
+ 'cortex_life', 'cortex_playbook', 'cortex_reflect', 'cortex_search', 'cortex_self', 'cortex_tick', 'cortex_timeline', 'cortex_working', 'cortex_write',
23
+ ]);
24
+ for (const tool of Object.values(tools)) {
25
+ assert.equal(tool.output.schema.required[0], 'text');
26
+ }
27
+ } finally {
28
+ cortex.close();
29
+ rmSync(dir, { recursive: true, force: true });
30
+ }
31
+ });
32
+
33
+ test('tools reject by-id writes into a read-only shared scope', async () => {
34
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-tools-readonly-'));
35
+ const seed = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
36
+ const sharedWorking = seed.working.add({ scopeId: 'shared', text: '共享工作项' });
37
+ const sharedGoal = seed.goals.add({ scopeId: 'shared', title: '共享目标' });
38
+ const sharedRule = seed.playbook.add({ scopeId: 'shared', title: '共享准则', body: '只在共享 scope 生效的准则内容。' });
39
+ const sharedTrace = seed.write({ scopeId: 'shared', text: '共享 scope 的记忆不应被外部删除。', explicit: true });
40
+ seed.close();
41
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), readOnlyScopes: ['shared'] } });
42
+ const tools = Object.fromEntries(createToolDefinitions(cortex).map((tool) => [tool.name, tool]));
43
+ try {
44
+ const working = await tools.cortex_working.execute({ action: 'pin', id: sharedWorking.id, pinned: true });
45
+ assert.match(working.text, /只读共享/);
46
+ const goal = await tools.cortex_goal.execute({ action: 'complete', id: sharedGoal.id });
47
+ assert.match(goal.text, /只读共享/);
48
+ const rule = await tools.cortex_playbook.execute({ action: 'retire', id: sharedRule.id });
49
+ assert.match(rule.text, /只读共享/);
50
+ const forget = await tools.cortex_forget.execute({ id: sharedTrace.trace.id, mode: 'archive' });
51
+ assert.match(forget.text, /只读共享/);
52
+ } finally {
53
+ cortex.close();
54
+ rmSync(dir, { recursive: true, force: true });
55
+ }
56
+ });
57
+
58
+ test('tools reject life and emotion writes when the default scope is read-only', async () => {
59
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-tools-readonly-default-'));
60
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), readOnlyScopes: ['global'] } });
61
+ const tools = Object.fromEntries(createToolDefinitions(cortex).map((tool) => [tool.name, tool]));
62
+ try {
63
+ const diary = await tools.cortex_life.execute({ action: 'diary-write', text: '不该写进去的日记' });
64
+ assert.match(diary.text, /只读共享/);
65
+ const emotion = await tools.cortex_emotion.execute({ action: 'record', text: '用户有点担心', target: '用户' });
66
+ assert.match(emotion.text, /只读共享/);
67
+ const compress = await tools.cortex_compress.execute({ action: 'compress', limit: 1 });
68
+ assert.match(compress.text, /只读共享/);
69
+ const sync = await tools.cortex_guard.execute({ action: 'sync', dir: path.join(dir, 'vault') });
70
+ assert.match(sync.text, /只读共享/);
71
+ } finally {
72
+ cortex.close();
73
+ rmSync(dir, { recursive: true, force: true });
74
+ }
75
+ });
76
+
77
+ test('write/search/get/self/health return readable text', async () => {
78
+ const { dir, cortex, tools } = setup();
79
+ try {
80
+ const write = await tools.cortex_write.execute({
81
+ text: '用户说会买白饭,助手会一直等。',
82
+ explicit: true,
83
+ facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }],
84
+ });
85
+ assert.match(write.text, /已写入/);
86
+ const id = write.text.match(/trc_[a-z0-9]+/)?.[0];
87
+ assert.ok(id);
88
+ const search = await tools.cortex_search.execute({ query: '白饭' });
89
+ assert.match(search.text, /意图/);
90
+ const get = await tools.cortex_get.execute({ id });
91
+ assert.match(get.text, /白饭/);
92
+ const self = await tools.cortex_self.execute({});
93
+ assert.match(self.text, /驱力/);
94
+ const health = await tools.cortex_health.execute({});
95
+ assert.match(health.text, /健康分/);
96
+ const guard = await tools.cortex_guard.execute({ action: 'check' });
97
+ assert.match(guard.text, /自检/);
98
+ const timeline = await tools.cortex_timeline.execute({ aroundId: id });
99
+ assert.match(timeline.text, /锚点/);
100
+ } finally {
101
+ cortex.close();
102
+ rmSync(dir, { recursive: true, force: true });
103
+ }
104
+ });
105
+
106
+ test('feedback/forget/reflect tool actions are callable', async () => {
107
+ const { dir, cortex, tools } = setup();
108
+ try {
109
+ const write = await tools.cortex_write.execute({ text: '第一条测试。', explicit: true });
110
+ const id = write.text.match(/trc_[a-z0-9]+/)?.[0];
111
+ const feedback = await tools.cortex_feedback.execute({ id, signal: 'helpful', predicted: 0.8 });
112
+ assert.match(feedback.text, /反馈已记/);
113
+ await tools.cortex_write.execute({ text: '第二条测试。', explicit: true });
114
+ const reflect = await tools.cortex_reflect.execute({ windowDays: 1, force: true });
115
+ assert.match(reflect.text, /来源/);
116
+ const forget = await tools.cortex_forget.execute({ id, mode: 'archive' });
117
+ assert.match(forget.text, /已归档/);
118
+ } finally {
119
+ cortex.close();
120
+ rmSync(dir, { recursive: true, force: true });
121
+ }
122
+ });
@@ -0,0 +1,104 @@
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 } from '../../src/host/runtime.js';
8
+
9
+ function setup(extra = {}) {
10
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-0412-'));
11
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), ...extra } });
12
+ return { dir, cortex };
13
+ }
14
+
15
+ function teardown({ dir, cortex }) {
16
+ cortex.close();
17
+ rmSync(dir, { recursive: true, force: true });
18
+ }
19
+
20
+ test('search keeps full memory while prompt injection gates weak matches', () => {
21
+ const ctx = setup();
22
+ try {
23
+ ctx.cortex.write({ text: '主人说会买白饭,这是一条承诺。', title: '白饭承诺', importance: 0.5, explicit: true });
24
+ ctx.cortex.write({ text: '今天颈椎有点疼,和吃饭无关。', title: '颈椎', importance: 0.5, explicit: true });
25
+ ctx.cortex.write({ text: '插件更新了一条无关的日志。', title: '日志', importance: 0.5, explicit: true });
26
+
27
+ const full = ctx.cortex.search('白饭 承诺', { limit: 5 });
28
+ assert.ok(full.items.some((item) => item.title === '白饭承诺'));
29
+ assert.ok(full.items.some((item) => item.title === '颈椎'));
30
+ assert.equal(full.trace.gated, 0);
31
+
32
+ const tiered = ctx.cortex.recallTiered({ query: '白饭 承诺' });
33
+ assert.ok(tiered.result.items.some((item) => item.title === '白饭承诺'));
34
+ assert.equal(tiered.result.items.some((item) => item.title === '颈椎'), false);
35
+ assert.equal(tiered.result.items.some((item) => item.title === '日志'), false);
36
+ assert.ok(tiered.result.trace.gated >= 1);
37
+ } finally {
38
+ teardown(ctx);
39
+ }
40
+ });
41
+
42
+ test('high-importance memory keeps the 0.4.11 gate exemption', () => {
43
+ const ctx = setup();
44
+ try {
45
+ ctx.cortex.write({ text: '身份:我是本鲸,边界是不操纵主人。', title: '身份', kind: 'identity', importance: 0.95, explicit: true });
46
+ const tiered = ctx.cortex.recallTiered({ query: '白饭' });
47
+ assert.ok(tiered.result.items.some((item) => item.title === '身份'));
48
+ assert.equal(tiered.result.items[0].layer, 'L0');
49
+ } finally {
50
+ teardown(ctx);
51
+ }
52
+ });
53
+
54
+ test('promptBudget config is normalized instead of being dropped', () => {
55
+ const ctx = setup({ promptBudget: 2400 });
56
+ try {
57
+ assert.equal(ctx.cortex.config.promptBudget, 2400);
58
+ const settings = ctx.cortex.settings();
59
+ assert.equal(ctx.cortex.settings().promptBudget, 2400);
60
+ } finally {
61
+ teardown(ctx);
62
+ }
63
+ });
64
+
65
+ test('recall text is strictly per session and never falls back to another session', () => {
66
+ const ctx = setup();
67
+ try {
68
+ ctx.cortex.write({ text: '主人说会买白饭。', explicit: true });
69
+ const runtime = createHostRuntime({ cortex: ctx.cortex });
70
+ const at = Date.now();
71
+ const s1 = { id: 's1', header: {} };
72
+ const s2 = { id: 's2', header: {} };
73
+ runtime.onSessionEvent(s1, { type: 'turn/start', data: { turn: 1 }, time: at });
74
+ runtime.onSessionEvent(s1, { type: 'user/message', data: { content: '白饭还算数吗?' }, time: at + 1000 });
75
+ assert.match(runtime.recallText({ session: s1 }), /白饭/);
76
+ assert.equal(runtime.recallText({ session: s2 }), '');
77
+ assert.equal(runtime.recallText({}), '');
78
+ } finally {
79
+ teardown(ctx);
80
+ }
81
+ });
82
+
83
+ test('light guardian runs structural invariants and catches FTS drift', () => {
84
+ const ctx = setup();
85
+ try {
86
+ const first = ctx.cortex.write({ text: '第一条用于索引的记忆。', explicit: true });
87
+ ctx.cortex.write({ text: '第二条用于索引的记忆。', explicit: true });
88
+ const clean = ctx.cortex.guardian.check({ deep: false });
89
+ assert.equal(clean.ok, true);
90
+ assert.equal(clean.integrity, 'skipped');
91
+ assert.equal(clean.chain.skipped, true);
92
+
93
+ ctx.cortex.db.prepare('DELETE FROM traces_fts_index WHERE trace_id = ?').run(first.trace.id);
94
+ const drift = ctx.cortex.guardian.check({ deep: false });
95
+ assert.equal(drift.ok, false);
96
+ assert.ok(drift.issues.some((item) => item.code === 'FTS_DRIFT'));
97
+
98
+ const deep = ctx.cortex.guardian.check({ deep: true });
99
+ assert.equal(deep.integrity, 'ok');
100
+ assert.equal(deep.chain.ok, true);
101
+ } finally {
102
+ teardown(ctx);
103
+ }
104
+ });
@@ -0,0 +1,84 @@
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 } from '../../src/host/runtime.js';
8
+ import { extractFactCandidates } from '../../src/engines/extract.js';
9
+
10
+ function setup(extra = {}) {
11
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-0413-'));
12
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), ...extra } });
13
+ return { dir, cortex };
14
+ }
15
+
16
+ function teardown({ dir, cortex }) {
17
+ try { cortex.close(); } catch { /* already closed */ }
18
+ rmSync(dir, { recursive: true, force: true });
19
+ }
20
+
21
+ test('evolution guard is configurable through the normalized config', () => {
22
+ const ctx = setup({ evolution: { maxPerDay: 1, canaryTicks: 2, minIntervalMs: 0 } });
23
+ try {
24
+ const guard = ctx.cortex.evolution.status().guard;
25
+ assert.equal(guard.maxPerDay, 1);
26
+ assert.equal(guard.canaryTicks, 2);
27
+ assert.equal(guard.minIntervalMs, 0);
28
+ } finally {
29
+ teardown(ctx);
30
+ }
31
+ });
32
+
33
+ test('canaries survive a restart and still roll back an active policy', () => {
34
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-0413-restart-'));
35
+ const dbFile = path.join(dir, 'cortex.sqlite');
36
+ let first = createCortex({ config: { dataRoot: dir, dbFile } });
37
+ try {
38
+ const skill = first.engines.skills.create({ name: 'restart-canary', steps: ['a'], state: 'active' });
39
+ for (let i = 0; i < 3; i += 1) first.engines.skills.record(skill.id, false);
40
+ const evolved = first.evolution.autoEvolve();
41
+ assert.ok(evolved.activated.length >= 1);
42
+ assert.ok(first.evolution.status().guard.pendingCanaries >= 1);
43
+ } finally {
44
+ first.close();
45
+ }
46
+
47
+ let second = createCortex({ config: { dataRoot: dir, dbFile } });
48
+ try {
49
+ assert.ok(second.evolution.status().guard.pendingCanaries >= 1);
50
+ const rolled = second.evolution.observeHealth({ ok: false, issues: [{ code: 'FTS_DRIFT' }] });
51
+ assert.ok(rolled.rolledBack.length >= 1);
52
+ assert.equal(second.policies.active('skill'), null);
53
+ } finally {
54
+ second.close();
55
+ rmSync(dir, { recursive: true, force: true });
56
+ }
57
+ });
58
+
59
+ test('recallSharing is opt-in and shares the block across sessions', () => {
60
+ const ctx = setup();
61
+ try {
62
+ ctx.cortex.write({ text: '主人说会买白饭。', explicit: true });
63
+ const runtime = createHostRuntime({ cortex: ctx.cortex, config: { recallSharing: true } });
64
+ const s1 = { id: 's1', header: {} };
65
+ const s2 = { id: 's2', header: {} };
66
+ runtime.onSessionEvent(s1, { type: 'turn/start', data: { turn: 1 }, time: Date.now() });
67
+ runtime.onSessionEvent(s1, { type: 'user/message', data: { content: '白饭还算数吗?' }, time: Date.now() });
68
+ assert.match(runtime.recallText({ session: s1 }), /白饭/);
69
+ assert.equal(runtime.recallText({ session: s1 }), runtime.recallText({ session: s2 }));
70
+ } finally {
71
+ teardown(ctx);
72
+ }
73
+ });
74
+
75
+ test('first-person extraction follows persona names while keeping markdown rejection', () => {
76
+ const custom = extractFactCandidates('本鲸喜欢安静', { selfName: '小鲸', userAddress: '主人' });
77
+ assert.equal(custom[0].subject, '小鲸');
78
+ assert.equal(custom[0].predicate, 'likes');
79
+
80
+ const neutral = extractFactCandidates('我喜欢便宜平替', { selfName: '助手', userAddress: '用户' });
81
+ assert.equal(neutral[0].subject, '用户');
82
+
83
+ assert.deepEqual(extractFactCandidates('**我喜欢便宜平替**', { selfName: '助手', userAddress: '用户' }), []);
84
+ });
@@ -0,0 +1,101 @@
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 { createEvolutionEngine } from '../../src/self/evolution.js';
8
+ import { createWebSearch } from '../../src/web/search.js';
9
+ import { normalizeConfig } from '../../src/core/config.js';
10
+ import { extractFactCandidates } from '../../src/engines/extract.js';
11
+
12
+ function tempCortex() {
13
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-0414-'));
14
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
15
+ return { dir, cortex };
16
+ }
17
+
18
+ function closeCortex(ctx) {
19
+ try { ctx.cortex.close(); } catch { /* already closed */ }
20
+ rmSync(ctx.dir, { recursive: true, force: true });
21
+ }
22
+
23
+ test('qualityGuard rolls back a retrieval policy that fails semantic probes', () => {
24
+ let active = null;
25
+ const created = [];
26
+ const policies = {
27
+ active: () => active,
28
+ list: () => created,
29
+ listCanaries: () => [],
30
+ setCanary: () => {},
31
+ create: ({ kind, config, metrics = null }) => {
32
+ const policy = { id: 'pol_quality_1', kind, config, metrics, status: 'candidate', version: 1 };
33
+ created.push(policy);
34
+ return policy;
35
+ },
36
+ activate: (id) => {
37
+ const policy = created.find((item) => item.id === id);
38
+ active = policy;
39
+ policy.status = 'active';
40
+ return policy;
41
+ },
42
+ rollback: () => { active = null; return null; },
43
+ retire: (id) => {
44
+ const policy = created.find((item) => item.id === id);
45
+ if (policy) policy.status = 'superseded';
46
+ if (active?.id === id) active = null;
47
+ return policy;
48
+ },
49
+ get: (id) => created.find((item) => item.id === id) ?? null,
50
+ updateMetrics: () => {},
51
+ };
52
+ const evolution = createEvolutionEngine({
53
+ policies,
54
+ growth: { calibration: () => ({ brier: 0.4, ece: 0.2, n: 10 }) },
55
+ health: { audit: () => ({ score: 100, issues: [] }) },
56
+ qualityGuard: () => ({ ok: false, recall: 0.1, baselineRecall: 0.8, threshold: 0.4, n: 6 }),
57
+ });
58
+ const result = evolution.autoEvolve();
59
+ assert.equal(result.activated.length, 0);
60
+ assert.ok(result.errors.some((item) => item.error === 'quality-guard'));
61
+ assert.equal(policies.active('retrieval'), null);
62
+ assert.equal(created[0].status, 'superseded');
63
+ });
64
+
65
+ test('recentTimeline returns the newest active traces without an anchor id', () => {
66
+ const ctx = tempCortex();
67
+ try {
68
+ ctx.cortex.write({ text: '最近时间线应该能直接看到这条记忆。', title: '时间线探针', explicit: true });
69
+ const recent = ctx.cortex.recentTimeline({ limit: 5 });
70
+ assert.ok(recent.items.length >= 1);
71
+ assert.equal(recent.items[0].title, '时间线探针');
72
+ } finally {
73
+ closeCortex(ctx);
74
+ }
75
+ });
76
+
77
+ test('web search adapter returns citeable sources without storing them', async () => {
78
+ const search = createWebSearch({
79
+ provider: 'wikipedia',
80
+ fetchImpl: async () => ({
81
+ ok: true,
82
+ json: async () => ({ query: { search: [{ title: 'Memory', snippet: 'A memory page' }] } }),
83
+ }),
84
+ });
85
+ const result = await search.search({ query: 'memory', maxResults: 1 });
86
+ assert.equal(result.provider, 'wikipedia');
87
+ assert.equal(result.sources.length, 1);
88
+ assert.equal(result.sources[0].title, 'Memory');
89
+ assert.match(result.sources[0].url, /wikipedia\.org/);
90
+ });
91
+
92
+ test('persona config is neutral by default and overrides self/user names', () => {
93
+ const neutral = normalizeConfig({});
94
+ assert.equal(neutral.persona.selfName, '助手');
95
+ assert.equal(neutral.persona.userAddress, '你');
96
+ const custom = normalizeConfig({ persona: { selfName: '汐儿', userAddress: '涵儿' } });
97
+ assert.equal(custom.persona.selfName, '汐儿');
98
+ assert.equal(custom.persona.userAddress, '涵儿');
99
+ const facts = extractFactCandidates('我喜欢安静', { selfName: '汐儿', userAddress: '涵儿' });
100
+ assert.equal(facts[0].subject, '涵儿');
101
+ });
@@ -0,0 +1,53 @@
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(extra = {}) {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-ann-wiring-'));
10
+ const cortex = createCortex({
11
+ config: {
12
+ dataRoot: dir,
13
+ dbFile: path.join(dir, 'cortex.sqlite'),
14
+ features: { vector: true, vectorAnn: true },
15
+ vectorAnnMin: 2,
16
+ ...extra,
17
+ },
18
+ });
19
+ return { dir, cortex };
20
+ }
21
+
22
+ test('optional ANN reports status and serves searches, with brute-force fallback', () => {
23
+ const { dir, cortex } = setup();
24
+ try {
25
+ cortex.write({ text: '白饭是用户最喜欢的食物。', explicit: true, importance: 0.9 });
26
+ cortex.write({ text: '助手会一直等用户回家吃饭。', explicit: true, importance: 0.8 });
27
+ cortex.write({ text: '插件修复需要先看日志。', explicit: true, importance: 0.7 });
28
+ const status = cortex.vector.status();
29
+ assert.equal(status.ann.enabled, true);
30
+ assert.equal(status.ann.engine, 'hnsw');
31
+ assert.equal(status.ann.min, 2);
32
+ assert.ok(status.ann.size >= 2);
33
+ const result = cortex.search('白饭 用户', { limit: 5 });
34
+ assert.ok(result.items.length >= 1);
35
+ assert.ok(result.items.some((item) => item.snippet.includes('白饭')));
36
+ } finally {
37
+ cortex.close();
38
+ rmSync(dir, { recursive: true, force: true });
39
+ }
40
+ });
41
+
42
+ test('ANN stays off by default', () => {
43
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-ann-off-'));
44
+ const cortex = createCortex({
45
+ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { vector: true } },
46
+ });
47
+ try {
48
+ assert.equal(cortex.vector.status().ann.enabled, false);
49
+ } finally {
50
+ cortex.close();
51
+ rmSync(dir, { recursive: true, force: true });
52
+ }
53
+ });
@@ -0,0 +1,69 @@
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 { createVectorIndex } from '../../src/vector/index.js';
8
+
9
+ function asyncEmbedder() {
10
+ return {
11
+ kind: 'openai-embedding', model: 'mock-embed', dim: 4,
12
+ async embed(text) {
13
+ const value = String(text);
14
+ return Float32Array.from([value.includes('白饭') ? 1 : 0, value.includes('面') ? 1 : 0, 0.1, 0.1]);
15
+ },
16
+ };
17
+ }
18
+
19
+ test('async vector indexing does not block and can be awaited explicitly', async () => {
20
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-async-vector-'));
21
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
22
+ try {
23
+ const written = cortex.write({ text: '用户喜欢白饭。', explicit: true });
24
+ const index = createVectorIndex({ db: cortex.db, embedder: asyncEmbedder() });
25
+ const pending = index.upsert(written.trace.id, '用户喜欢白饭。');
26
+ assert.equal(pending.pending, true);
27
+ assert.equal(index.status().count, 0);
28
+ await index.upsertAsync(written.trace.id, '用户喜欢白饭。');
29
+ assert.equal(index.status().count, 1);
30
+ const hits = await index.searchAsync('白饭', { scopeId: 'global', limit: 3 });
31
+ assert.equal(hits[0].traceId, written.trace.id);
32
+ const rebuilt = await index.rebuildAsync({ scopeId: 'global' });
33
+ assert.equal(rebuilt.rebuilt, 1);
34
+ } finally {
35
+ cortex.close();
36
+ rmSync(dir, { recursive: true, force: true });
37
+ }
38
+ });
39
+
40
+ test('service async search uses the async vector path', async () => {
41
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-async-hybrid-'));
42
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), vectorEnabled: true, features: { vector: true }, embedder: asyncEmbedder() } });
43
+ try {
44
+ const written = cortex.write({ text: '用户喜欢白饭。', explicit: true });
45
+ await cortex.indexVectorAsync(written.trace.id);
46
+ const result = await cortex.searchAsync('白饭');
47
+ assert.ok(result.items.some((item) => item.id === written.trace.id));
48
+ assert.ok(result.trace.sources.some((source) => source.source === 'vector' && source.count > 0));
49
+ } finally {
50
+ cortex.close();
51
+ rmSync(dir, { recursive: true, force: true });
52
+ }
53
+ });
54
+
55
+ test('service exposes async index and rebuild without changing sync search', async () => {
56
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-async-service-'));
57
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), vectorEnabled: true, features: { vector: true }, embedder: asyncEmbedder() } });
58
+ try {
59
+ const written = cortex.write({ text: '用户喜欢面。', explicit: true });
60
+ const indexed = await cortex.indexVectorAsync(written.trace.id);
61
+ assert.equal(indexed.traceId, written.trace.id);
62
+ const rebuilt = await cortex.rebuildVectorAsync({ scopeId: 'global' });
63
+ assert.equal(rebuilt.rebuilt, 1);
64
+ assert.ok(cortex.vector.status().count >= 1);
65
+ } finally {
66
+ cortex.close();
67
+ rmSync(dir, { recursive: true, force: true });
68
+ }
69
+ });