dsh-cortex-memory 0.4.22 → 0.4.147

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 (154) hide show
  1. package/CHANGELOG.md +2390 -154
  2. package/README.md +11 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +10 -10
  5. package/bench/synthetic.js +3 -3
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/client.js +1 -1
  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/icon.svg +12 -2
  15. package/index.js +27 -3
  16. package/package.json +3 -3
  17. package/src/adapters/shiori.js +1 -1
  18. package/src/api/routes.js +1 -1
  19. package/src/core/feature-overrides.js +2 -2
  20. package/src/engines/compression.js +172 -3
  21. package/src/engines/consolidate.js +397 -26
  22. package/src/engines/encode.js +16 -3
  23. package/src/engines/extract.js +72 -8
  24. package/src/engines/fact-guard.js +51 -0
  25. package/src/engines/health.js +263 -3
  26. package/src/engines/inhibition.js +39 -0
  27. package/src/engines/life.js +14 -3
  28. package/src/engines/llm-facts.js +12 -9
  29. package/src/engines/narrative.js +150 -13
  30. package/src/engines/reflect.js +172 -14
  31. package/src/engines/retrieve.js +44 -5
  32. package/src/engines/summary-coverage.js +62 -0
  33. package/src/engines/summary-dedupe.js +77 -0
  34. package/src/engines/summon-rank.js +132 -0
  35. package/src/host/runtime.js +64 -4
  36. package/src/host/scheduler.js +224 -3
  37. package/src/llm/adapter.js +29 -8
  38. package/src/memory/query.js +1 -1
  39. package/src/memory/spacing.js +15 -0
  40. package/src/memory/tokenizer.js +1 -1
  41. package/src/prompt/tiers.js +88 -12
  42. package/src/self/alias.js +25 -0
  43. package/src/self/emotion.js +3 -1
  44. package/src/self/relationship.js +44 -13
  45. package/src/self/state.js +20 -2
  46. package/src/self/working.js +34 -3
  47. package/src/service/cortex.js +493 -53
  48. package/src/store/repositories/facts.js +34 -1
  49. package/src/store/repositories/summaries.js +8 -1
  50. package/src/store/repositories/traces.js +22 -2
  51. package/src/tools/definitions.js +118 -4
  52. package/src/vector/index.js +96 -7
  53. package/test/integration/_helpers.js +0 -128
  54. package/test/integration/acceptance.test.js +0 -803
  55. package/test/integration/ann-load.test.js +0 -61
  56. package/test/integration/api-contract.test.js +0 -1476
  57. package/test/integration/backup-privacy.test.js +0 -214
  58. package/test/integration/consolidate.test.js +0 -75
  59. package/test/integration/edge-cases.test.js +0 -1088
  60. package/test/integration/exchange.test.js +0 -326
  61. package/test/integration/life-loop.test.js +0 -188
  62. package/test/integration/load.test.js +0 -751
  63. package/test/integration/markdown-sync.test.js +0 -35
  64. package/test/integration/policy-query-api.test.js +0 -306
  65. package/test/integration/resilience-writes.test.js +0 -241
  66. package/test/integration/tools-contract.test.js +0 -1324
  67. package/test/unit/ann-edge.test.js +0 -102
  68. package/test/unit/ann.test.js +0 -77
  69. package/test/unit/api-client.test.js +0 -576
  70. package/test/unit/api-validate.test.js +0 -19
  71. package/test/unit/api.test.js +0 -555
  72. package/test/unit/appraisal.test.js +0 -48
  73. package/test/unit/attachments.test.js +0 -33
  74. package/test/unit/autonomy.test.js +0 -53
  75. package/test/unit/batch.test.js +0 -46
  76. package/test/unit/bench.test.js +0 -40
  77. package/test/unit/benchmark-synthetic.test.js +0 -52
  78. package/test/unit/cli-default-root.test.js +0 -21
  79. package/test/unit/client-contract.test.js +0 -32
  80. package/test/unit/compression.test.js +0 -76
  81. package/test/unit/core.test.js +0 -77
  82. package/test/unit/develop.test.js +0 -130
  83. package/test/unit/development.test.js +0 -68
  84. package/test/unit/digest.test.js +0 -26
  85. package/test/unit/dsr.test.js +0 -111
  86. package/test/unit/edges-candidates.test.js +0 -113
  87. package/test/unit/emotion.test.js +0 -61
  88. package/test/unit/encode.test.js +0 -98
  89. package/test/unit/evolution.test.js +0 -130
  90. package/test/unit/external-ann-search.test.js +0 -50
  91. package/test/unit/external-ann.test.js +0 -29
  92. package/test/unit/facts-belief.test.js +0 -32
  93. package/test/unit/facts.test.js +0 -107
  94. package/test/unit/feature-overrides.test.js +0 -42
  95. package/test/unit/fts-migration.test.js +0 -42
  96. package/test/unit/graph.test.js +0 -79
  97. package/test/unit/growth-reflect.test.js +0 -123
  98. package/test/unit/guard-runtime.test.js +0 -40
  99. package/test/unit/guardian.test.js +0 -91
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/hnsw.test.js +0 -35
  102. package/test/unit/host-runtime.test.js +0 -142
  103. package/test/unit/host.test.js +0 -58
  104. package/test/unit/identity.test.js +0 -98
  105. package/test/unit/induct-evaluate.test.js +0 -41
  106. package/test/unit/ingest-extracted.test.js +0 -35
  107. package/test/unit/initiative.test.js +0 -90
  108. package/test/unit/jobs.test.js +0 -93
  109. package/test/unit/json-snapshot.test.js +0 -57
  110. package/test/unit/life-consolidate.test.js +0 -34
  111. package/test/unit/life.test.js +0 -149
  112. package/test/unit/llm-facts-integration.test.js +0 -27
  113. package/test/unit/llm-facts.test.js +0 -16
  114. package/test/unit/llm.test.js +0 -45
  115. package/test/unit/locomo.test.js +0 -45
  116. package/test/unit/longmemeval.test.js +0 -56
  117. package/test/unit/markdown-import.test.js +0 -44
  118. package/test/unit/markdown.test.js +0 -34
  119. package/test/unit/memory-edit.test.js +0 -112
  120. package/test/unit/metrics.test.js +0 -26
  121. package/test/unit/migration.test.js +0 -38
  122. package/test/unit/model-config.test.js +0 -52
  123. package/test/unit/narrative.test.js +0 -62
  124. package/test/unit/playbook-consolidate.test.js +0 -24
  125. package/test/unit/privacy-scope.test.js +0 -39
  126. package/test/unit/profile-paths.test.js +0 -21
  127. package/test/unit/profile.test.js +0 -26
  128. package/test/unit/prompt.test.js +0 -42
  129. package/test/unit/providers.test.js +0 -42
  130. package/test/unit/qa.test.js +0 -100
  131. package/test/unit/query.test.js +0 -53
  132. package/test/unit/retention.test.js +0 -31
  133. package/test/unit/retrieval-ranking.test.js +0 -31
  134. package/test/unit/retrieve.test.js +0 -117
  135. package/test/unit/rotation.test.js +0 -25
  136. package/test/unit/scanner.test.js +0 -50
  137. package/test/unit/scenario.test.js +0 -78
  138. package/test/unit/scheduler.test.js +0 -136
  139. package/test/unit/self-state.test.js +0 -94
  140. package/test/unit/service.test.js +0 -72
  141. package/test/unit/shiori-import.test.js +0 -77
  142. package/test/unit/skills.test.js +0 -104
  143. package/test/unit/store.test.js +0 -111
  144. package/test/unit/temporal-graph.test.js +0 -44
  145. package/test/unit/tiers.test.js +0 -39
  146. package/test/unit/tokenizer-fts.test.js +0 -35
  147. package/test/unit/tools.test.js +0 -122
  148. package/test/unit/upgrade-0412.test.js +0 -104
  149. package/test/unit/upgrade-0413.test.js +0 -84
  150. package/test/unit/upgrade-0414.test.js +0 -101
  151. package/test/unit/vector-ann.test.js +0 -53
  152. package/test/unit/vector-async.test.js +0 -69
  153. package/test/unit/vector.test.js +0 -68
  154. package/test/unit/working.test.js +0 -80
@@ -1,149 +0,0 @@
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-life-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- return { dir, cortex };
12
- }
13
-
14
- test('diary entries can be written, listed and forgotten', () => {
15
- const { dir, cortex } = setup();
16
- try {
17
- const entry = cortex.life.diaryWrite({ text: '今天把守护模块接上了。', mood: '踏实' });
18
- assert.ok(entry.id);
19
- assert.equal(cortex.life.diaryList()[0].id, entry.id);
20
- assert.equal(cortex.life.diaryForget(entry.id), true);
21
- assert.equal(cortex.life.diaryList().length, 0);
22
- } finally {
23
- cortex.close();
24
- rmSync(dir, { recursive: true, force: true });
25
- }
26
- });
27
-
28
- test('web sources are passed into AI diary generation', async () => {
29
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-diary-web-'));
30
- let seenWeb = '';
31
- const cortex = createCortex({
32
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { webSearch: true } },
33
- llm: {
34
- dream: async () => null,
35
- diary: async (args) => { seenWeb = args.web; return '今天助手从一份外部资料里看见了一点新东西。'; },
36
- feeling: async () => null,
37
- },
38
- webSearch: async () => ({
39
- sources: [{ title: 'Source A', url: 'https://example.com/a', snippet: 'A snippet' }],
40
- }),
41
- });
42
- try {
43
- cortex.write({ text: '今天研究联网日记。', explicit: true, importance: 0.8 });
44
- const entry = await cortex.life.diaryGenerate({ at: Date.parse('2026-11-12T13:00:00+08:00') });
45
- assert.match(seenWeb, /example\.com\/a/);
46
- assert.equal(entry.webSources?.[0]?.url, 'https://example.com/a');
47
- assert.doesNotMatch(entry.text, /https:\/\/example\.com\/a/);
48
- } finally {
49
- cortex.close();
50
- rmSync(dir, { recursive: true, force: true });
51
- }
52
- });
53
-
54
- test('diary generation is written by the configured AI, with a labeled fallback', async () => {
55
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-diary-ai-'));
56
- const cortex = createCortex({
57
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') },
58
- llm: {
59
- dream: async () => null,
60
- diary: async () => '今天助手把检索和梦都重新摸了一遍,心里慢慢安静下来。',
61
- },
62
- });
63
- try {
64
- cortex.write({ text: '今天把日记生成接上。', explicit: true, importance: 0.8 });
65
- const entry = await cortex.life.diaryGenerate({ at: Date.parse('2026-11-12T12:00:00+08:00') });
66
- assert.equal(entry.model, 'llm');
67
- assert.equal(entry.source, 'cortex:llm');
68
- assert.match(entry.text, /助手/);
69
- assert.equal(cortex.life.diaryList()[0].source, 'cortex:llm');
70
- } finally {
71
- cortex.close();
72
- rmSync(dir, { recursive: true, force: true });
73
- }
74
- });
75
-
76
- test('feeling generation records AI-chosen emotion labels and affect', async () => {
77
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-feeling-ai-'));
78
- const cortex = createCortex({
79
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') },
80
- llm: {
81
- dream: async () => null,
82
- diary: async () => null,
83
- feeling: async () => ({
84
- text: '助手现在有一点安心,也有一点期待。',
85
- emotions: [{ name: '安', score: 2 }, { name: '盼', score: 1 }],
86
- target: '用户',
87
- }),
88
- },
89
- });
90
- try {
91
- cortex.write({ text: '今天把自动感受接上了。', explicit: true, importance: 0.8 });
92
- const feeling = await cortex.life.feelingGenerate({ at: Date.parse('2026-11-12T13:00:00+08:00') });
93
- assert.equal(feeling.model, 'llm');
94
- assert.deepEqual(feeling.emotions.map((item) => item.name), ['安', '盼']);
95
- assert.ok(cortex.emotion.events({ limit: 5 }).some((event) => event.text.includes('安心')));
96
- assert.match(cortex.emotion.text(), /安/);
97
- } finally {
98
- cortex.close();
99
- rmSync(dir, { recursive: true, force: true });
100
- }
101
- });
102
-
103
- test('dream generation uses recent memories and falls back to template', async () => {
104
- const { dir, cortex } = setup();
105
- try {
106
- cortex.write({ text: '今天修好了图检索。', explicit: true, importance: 0.9, now: Date.parse('2026-11-11T12:00:00+08:00') });
107
- const dream = await cortex.life.dreamGenerate({ at: Date.parse('2026-11-11T20:00:00+08:00') });
108
- assert.ok(dream.text.length > 0);
109
- assert.equal(dream.model, 'template');
110
- assert.ok(cortex.life.dreamList().length >= 1);
111
- } finally {
112
- cortex.close();
113
- rmSync(dir, { recursive: true, force: true });
114
- }
115
- });
116
-
117
- test('dream generation dedupes identical dreams inside five seconds', async () => {
118
- const { dir, cortex } = setup();
119
- try {
120
- const at = Date.parse('2026-11-11T20:00:00+08:00');
121
- const first = await cortex.life.dreamGenerate({ at });
122
- const second = await cortex.life.dreamGenerate({ at: at + 1000 });
123
- assert.equal(second.id, first.id);
124
- assert.equal(cortex.life.dreamList().length, 1);
125
-
126
- const later = await cortex.life.dreamGenerate({ at: at + 6 * 1000 });
127
- assert.notEqual(later.id, first.id);
128
- assert.equal(cortex.life.dreamList().length, 2);
129
- } finally {
130
- cortex.close();
131
- rmSync(dir, { recursive: true, force: true });
132
- }
133
- });
134
-
135
- test('sleep runs consolidation and records a report', async () => {
136
- const { dir, cortex } = setup();
137
- try {
138
- cortex.write({ text: '第一条记忆。', explicit: true });
139
- cortex.write({ text: '第二条记忆。', explicit: true });
140
- cortex.working.add({ text: '会过期的焦点', ttlMs: 1, at: Date.now() - 1000 });
141
- const report = await cortex.life.sleep({ at: Date.now() });
142
- assert.ok(report.id);
143
- assert.ok(report.purgedWorking >= 1);
144
- assert.ok(cortex.life.sleepRuns().length >= 1);
145
- } finally {
146
- cortex.close();
147
- rmSync(dir, { recursive: true, force: true });
148
- }
149
- });
@@ -1,27 +0,0 @@
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('llmFacts schedules background extraction and writes validated facts', async () => {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-facts-'));
10
- const cortex = createCortex({
11
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llmFacts: true } },
12
- llm: {
13
- available: () => true,
14
- complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"白饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.1}]}',
15
- },
16
- });
17
- try {
18
- cortex.write({ text: '助手喜欢白饭。', explicit: true });
19
- await cortex.flushLlmFacts();
20
- const facts = cortex.repos.facts.list({ scopeId: 'global' });
21
- assert.equal(facts.length, 1);
22
- assert.equal(facts[0].predicate, 'likes');
23
- } finally {
24
- cortex.close();
25
- rmSync(dir, { recursive: true, force: true });
26
- }
27
- });
@@ -1,16 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { extractFactsWithLlm } from '../../src/engines/llm-facts.js';
4
-
5
- test('LLM facts parse strict JSON and drop low-confidence/unsupported items', async () => {
6
- const llm = { complete: async () => '```json\n{"facts":[{"subject":"助手","predicate":"likes","object":"白饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.2}]}\n```' };
7
- const result = await extractFactsWithLlm({ llm, text: '助手喜欢白饭。' });
8
- assert.equal(result.candidates.length, 1);
9
- assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '白饭', confidence: 0.9 });
10
- });
11
-
12
- test('LLM facts fail closed on malformed output or missing model', async () => {
13
- const malformed = { complete: async () => 'not json at all' };
14
- assert.equal((await extractFactsWithLlm({ llm: malformed, text: 'x' })).candidates.length, 0);
15
- assert.equal((await extractFactsWithLlm({ llm: null, text: 'x' })).error, 'llm-unavailable');
16
- });
@@ -1,45 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { createLlmAdapter } from '../../src/llm/adapter.js';
4
-
5
- function mockCtx(text = '梦里,助手坐在白饭旁边。') {
6
- return {
7
- get(name) {
8
- if (name === 'llm') {
9
- return {
10
- async *stream() { yield { type: 'text-delta', text }; },
11
- };
12
- }
13
- if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'test', model: 'test-model' }) };
14
- if (name === 'agents') return { currentInitiator: () => ({ session: { id: 's1' } }) };
15
- return null;
16
- },
17
- };
18
- }
19
-
20
- test('llm adapter completes, dreams and summarizes through the host service', async () => {
21
- const adapter = createLlmAdapter({ ctx: mockCtx() });
22
- assert.equal(adapter.available(), true);
23
- const text = await adapter.complete({ system: 's', prompt: 'p' });
24
- assert.match(text, /白饭/);
25
- const dream = await adapter.dream({ pieces: ['白饭'], emotions: '暖' });
26
- assert.match(dream, /白饭/);
27
- const summary = await adapter.summarize({ text: '一段很长的记忆' });
28
- assert.match(summary, /白饭/);
29
- });
30
-
31
- test('llm adapter fails open when the service is missing or errors', async () => {
32
- const missing = createLlmAdapter({ ctx: { get: () => null } });
33
- assert.equal(missing.available(), false);
34
- assert.equal(await missing.complete({ prompt: 'x' }), null);
35
- const broken = createLlmAdapter({
36
- ctx: {
37
- get(name) {
38
- if (name === 'llm') return { async *stream() { throw new Error('boom'); } };
39
- if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'p', model: 'm' }) };
40
- return null;
41
- },
42
- },
43
- });
44
- assert.equal(await broken.complete({ prompt: 'x' }), null);
45
- });
@@ -1,45 +0,0 @@
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 { buildLoCoMoIndex, evaluateLoCoMoRetrieval } from '../../bench/locomo.js';
8
-
9
- const sample = {
10
- sample_id: 'conv-1',
11
- conversation: {
12
- speaker_a: 'A',
13
- speaker_b: 'B',
14
- session_1_date_time: '2026-11-01T10:00:00+08:00',
15
- session_1: [
16
- { speaker: 'A', text: '我喜欢白饭。' },
17
- { speaker: 'B', text: '那很好。' },
18
- ],
19
- session_2_date_time: '2026-11-02T10:00:00+08:00',
20
- session_2: [
21
- { speaker: 'A', text: '今天修了插件。' },
22
- ],
23
- },
24
- qa: [
25
- { question: 'A 喜欢什么?', answer: '白饭', evidence: ['D1:1'], category: 1 },
26
- { question: '不存在的事是什么?', answer: '没有', evidence: [], category: 5 },
27
- ],
28
- };
29
-
30
- test('LoCoMo adapter maps evidence turns to trace relevance', async () => {
31
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-locomo-'));
32
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
33
- try {
34
- const built = buildLoCoMoIndex({ cortex, samples: [sample] });
35
- assert.equal(built.traces, 3);
36
- assert.equal(built.queries.length, 2);
37
- assert.equal(built.queries[0].relevant.length, 1);
38
- const result = await evaluateLoCoMoRetrieval({ cortex, samples: [sample], limit: 5 });
39
- assert.equal(result.built.evaluated, 1);
40
- assert.ok(result.recallAtK >= 0 && result.recallAtK <= 1);
41
- } finally {
42
- cortex.close();
43
- rmSync(dir, { recursive: true, force: true });
44
- }
45
- });
@@ -1,56 +0,0 @@
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 { buildLongMemEvalIndex, evaluateLongMemEvalRetrieval, instanceType } from '../../bench/longmemeval.js';
8
-
9
- const fixture = [
10
- {
11
- question_id: 'q1',
12
- question_type: 'single-session-user',
13
- question: '用户喜欢什么主食?',
14
- answer: '白饭',
15
- question_date: '2026-11-11T12:00:00+08:00',
16
- haystack_session_ids: ['s1', 's2'],
17
- haystack_dates: ['2026-11-01T12:00:00+08:00', '2026-11-02T12:00:00+08:00'],
18
- haystack_sessions: [
19
- [{ role: 'user', content: '用户最喜欢白饭。', has_answer: true }],
20
- [{ role: 'user', content: '今天修插件。' }],
21
- ],
22
- answer_session_ids: ['s1'],
23
- },
24
- {
25
- question_id: 'q2_abs',
26
- question_type: 'temporal-reasoning',
27
- question: '不存在的约定是哪天?',
28
- answer: '没有',
29
- question_date: '2026-11-11T12:00:00+08:00',
30
- haystack_session_ids: ['s3'],
31
- haystack_dates: ['2026-11-03T12:00:00+08:00'],
32
- haystack_sessions: [[{ role: 'user', content: '没有这件事。' }]],
33
- answer_session_ids: [],
34
- },
35
- ];
36
-
37
- test('LongMemEval adapter builds traces and query relevance', () => {
38
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-lme-'));
39
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
40
- try {
41
- const built = buildLongMemEvalIndex({ cortex, instances: fixture });
42
- assert.equal(built.traces, 3);
43
- assert.equal(built.queries.length, 2);
44
- const q1 = built.queries.find((query) => query.id === 'q1');
45
- assert.equal(q1.relevant.length, 1);
46
- assert.equal(q1.abstention, false);
47
- assert.equal(instanceType(fixture[1]), 'abstention');
48
- const result = evaluateLongMemEvalRetrieval({ cortex, instances: fixture, limit: 5 });
49
- assert.equal(result.built.evaluated, 1);
50
- assert.ok(result.recallAtK >= 0);
51
- assert.ok(result.recallAtK <= 1);
52
- } finally {
53
- cortex.close();
54
- rmSync(dir, { recursive: true, force: true });
55
- }
56
- });
@@ -1,44 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync, writeFileSync } 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 { parseMemoryMarkdown, importMarkdown } from '../../src/adapters/markdown-import.js';
8
-
9
- test('markdown parser reads frontmatter and body', () => {
10
- const parsed = parseMemoryMarkdown('---\nid: "t1"\nkind: "fact"\ntitle: "白饭"\ntags: ["白饭", "承诺"]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\nrecorded_at: "2026-11-05T10:00:00+08:00"\n---\n\n用户喜欢白饭。\n');
11
- assert.equal(parsed.id, 't1');
12
- assert.equal(parsed.kind, 'fact');
13
- assert.deepEqual(parsed.tags, ['白饭', '承诺']);
14
- assert.equal(parsed.attachments.length, 1);
15
- assert.equal(parsed.attachments[0].uri, 'https://example.test/rice.png');
16
- assert.match(parsed.content, /用户喜欢白饭/);
17
- });
18
-
19
- test('markdown import writes active files idempotently', () => {
20
- const dataDir = mkdtempSync(path.join(os.tmpdir(), 'cortex-md-import-'));
21
- const vault = mkdtempSync(path.join(os.tmpdir(), 'cortex-vault-'));
22
- const cortex = createCortex({ config: { dataRoot: dataDir, dbFile: path.join(dataDir, 'cortex.sqlite') } });
23
- try {
24
- writeFileSync(path.join(vault, 'a.md'), '---\nid: a\nkind: utterance\ntitle: 白饭\ntags: [白饭]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\n---\n\n用户喜欢白饭。\n', 'utf8');
25
- writeFileSync(path.join(vault, 'b.md'), '---\nid: b\nstate: archived\n---\n\n不该导入。\n', 'utf8');
26
- const dry = importMarkdown(cortex, vault, { dryRun: true });
27
- assert.equal(dry.files, 2);
28
- assert.equal(cortex.repos.traces.count(), 0);
29
- const result = importMarkdown(cortex, vault);
30
- assert.equal(result.imported, 1);
31
- assert.equal(result.skipped, 1);
32
- assert.equal(cortex.repos.traces.count(), 1);
33
- const importedTrace = cortex.repos.traces.list({ scopeId: 'global', limit: 10 })[0];
34
- assert.equal(importedTrace.metadata.attachments.length, 1);
35
- assert.equal(importedTrace.metadata.attachments[0].uri, 'https://example.test/rice.png');
36
- const again = importMarkdown(cortex, vault);
37
- assert.equal(again.items.find((item) => item.title === '白饭').skipped, true);
38
- assert.equal(cortex.repos.traces.count(), 1);
39
- } finally {
40
- cortex.close();
41
- rmSync(dataDir, { recursive: true, force: true });
42
- rmSync(vault, { recursive: true, force: true });
43
- }
44
- });
@@ -1,34 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, readFileSync, 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 { exportMarkdown } from '../../src/adapters/markdown.js';
8
-
9
- test('markdown mirror exports readable files and skips secrets', () => {
10
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-md-'));
11
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
12
- try {
13
- cortex.write({ text: '用户说会买白饭。', title: '白饭', explicit: true, facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }], attachments: [{ kind: 'image', uri: 'https://example.test/rice.png', mime: 'image/png' }] });
14
- cortex.write({ text: '这是一个 secret:sk-abcdefghijklmnopqrstuvwxyz123456', explicit: true });
15
- cortex.engines.skills.create({ name: '修插件', steps: ['看日志', '改一处', '跑测试'], state: 'active' });
16
- const result = exportMarkdown(cortex, path.join(dir, 'mirror'));
17
- assert.equal(result.traces, 1);
18
- assert.equal(result.skippedSecrets, 1);
19
- const memory = readFileSync(path.join(dir, 'mirror', 'MEMORY.md'), 'utf8');
20
- assert.match(memory, /白饭/);
21
- assert.match(memory, /Attachments \(metadata only\)/);
22
- assert.match(memory, /https:\/\/example\.test\/rice\.png/);
23
- assert.doesNotMatch(memory, /sk-abcdefghijklmnop/);
24
- const self = readFileSync(path.join(dir, 'mirror', 'SELF.md'), 'utf8');
25
- assert.match(self, /Identity/);
26
- const facts = readFileSync(path.join(dir, 'mirror', 'FACTS.md'), 'utf8');
27
- assert.match(facts, /likes/);
28
- const skills = readFileSync(path.join(dir, 'mirror', 'SKILLS.md'), 'utf8');
29
- assert.match(skills, /修插件/);
30
- } finally {
31
- cortex.close();
32
- rmSync(dir, { recursive: true, force: true });
33
- }
34
- });
@@ -1,112 +0,0 @@
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-memory-edit-'));
10
- const cortex = createCortex({
11
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { autoFacts: false, llmFacts: false } },
12
- });
13
- return { dir, cortex };
14
- }
15
-
16
- test('memory day view groups emotion and work; editing is locked by default', () => {
17
- const { dir, cortex } = setup();
18
- try {
19
- const at = '2026-11-12T03:00:00.000Z';
20
- const written = cortex.write({ text: '今天完成记忆查询面板。', title: '面板测试', explicit: true, recordedAt: at, importance: 0.8 });
21
- cortex.emotion.record({ text: '助手觉得安心。', target: '用户', at });
22
- const day = cortex.memoryDay({ date: '2026-11-12' });
23
- assert.equal(day.counts.traces, 1);
24
- assert.equal(day.counts.emotion, 1);
25
- assert.equal(day.work.traces[0].id, written.trace.id);
26
- assert.equal(cortex.memoryEditState().enabled, false);
27
- assert.throws(() => cortex.updateMemoryTrace({ id: written.trace.id, title: '不能改' }), /locked/);
28
- } finally {
29
- cortex.close();
30
- rmSync(dir, { recursive: true, force: true });
31
- }
32
- });
33
-
34
- test('summon cards are built for left/right brain and can be edited after unlock', () => {
35
- const { dir, cortex } = setup();
36
- try {
37
- const at = '2026-11-12T03:00:00.000Z';
38
- cortex.write({ text: '今天完成了召唤册。', title: '召唤册', kind: 'decision', explicit: true, recordedAt: at, importance: 0.9 });
39
- cortex.emotion.record({ text: '助手觉得安心。', target: '用户', at });
40
- const built = cortex.rebuildSummonBook();
41
- assert.ok(built.cards >= 2);
42
- const book = cortex.summonBook({ date: '2026-11-12' });
43
- assert.ok(book.left.length >= 1);
44
- assert.ok(book.right.length >= 1);
45
- assert.ok(book.volumes.length >= 1);
46
- const card = book.left[0];
47
- assert.throws(() => cortex.updateSummonCard({ id: card.id, title: '不能改' }), /locked/);
48
- cortex.setMemoryEdit(true);
49
- const updated = cortex.updateSummonCard({ id: card.id, title: '改过的召唤卡' });
50
- assert.equal(updated.title, '改过的召唤卡');
51
- } finally {
52
- cortex.close();
53
- rmSync(dir, { recursive: true, force: true });
54
- }
55
- });
56
-
57
- test('manual card edits survive a rebuild and cards can be matched by a specific phrase', () => {
58
- const { dir, cortex } = setup();
59
- try {
60
- cortex.write({ text: '白饭约定:以后要一起买白饭。', title: '白饭约定', kind: 'decision', explicit: true, importance: 0.95 });
61
- cortex.rebuildSummonBook();
62
- const first = cortex.summonBook({ date: new Date().toLocaleDateString('en-CA') });
63
- const card = first.right.find((item) => item.title.includes('白饭')) ?? first.right[0];
64
- assert.ok(card);
65
- cortex.setMemoryEdit(true);
66
- cortex.updateSummonCard({ id: card.id, title: '用户改过的白饭卡' });
67
- cortex.rebuildSummonBook();
68
- const second = cortex.summonBook({ date: new Date().toLocaleDateString('en-CA') });
69
- assert.equal(second.right.find((item) => item.id === card.id).title, '用户改过的白饭卡');
70
- const match = cortex.matchSummonCards({ text: '你还记得白饭约定吗?' });
71
- assert.ok(match.cards.length >= 1);
72
- assert.match(match.block, /召唤卡/);
73
- const feedback = cortex.feedbackSummonCard({ id: card.id, signal: 'helpful' });
74
- assert.equal(feedback.signal, 'helpful');
75
- assert.ok(feedback.feedback || feedback.sourceKind !== 'trace');
76
- } finally {
77
- cortex.close();
78
- rmSync(dir, { recursive: true, force: true });
79
- }
80
- });
81
-
82
- test('reviewIntentions creates a pending intention when none are triggered', () => {
83
- const { dir, cortex } = setup();
84
- try {
85
- const result = cortex.reviewIntentions({ at: Date.now() });
86
- assert.ok(result.intentions.length >= 1);
87
- assert.equal(result.intentions[0].kind, 'question');
88
- assert.ok(cortex.self().intentions.some((item) => item.payload?.topic === '1.5h-review'));
89
- } finally {
90
- cortex.close();
91
- rmSync(dir, { recursive: true, force: true });
92
- }
93
- });
94
-
95
- test('unlocking memory edit allows trace edits and audits them', () => {
96
- const { dir, cortex } = setup();
97
- try {
98
- const at = '2026-11-12T03:00:00.000Z';
99
- const written = cortex.write({ text: '旧正文', title: '旧标题', explicit: true, recordedAt: at });
100
- cortex.setMemoryEdit(true);
101
- const updated = cortex.updateMemoryTrace({ id: written.trace.id, title: '新标题', content: '新正文', tags: ['手动', '编辑'] });
102
- assert.equal(updated.title, '新标题');
103
- assert.equal(updated.content, '新正文');
104
- assert.deepEqual(updated.tags, ['手动', '编辑']);
105
- const audit = cortex.repos.audit.list({ limit: 20 });
106
- assert.ok(audit.some((entry) => entry.action === 'memory.trace.edit'));
107
- cortex.setMemoryEdit(false);
108
- } finally {
109
- cortex.close();
110
- rmSync(dir, { recursive: true, force: true });
111
- }
112
- });
@@ -1,26 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { createMetrics } from '../../src/observability/metrics.js';
4
-
5
- test('metrics aggregate counters and percentiles', () => {
6
- const metrics = createMetrics();
7
- metrics.inc('writes');
8
- metrics.inc('writes', 2);
9
- metrics.observe('search.ms', 10);
10
- metrics.observe('search.ms', 20);
11
- metrics.observe('search.ms', 30);
12
- const snapshot = metrics.snapshot();
13
- assert.equal(snapshot.counters.writes, 3);
14
- assert.equal(snapshot.histograms['search.ms'].count, 3);
15
- assert.equal(snapshot.histograms['search.ms'].p50, 20);
16
- assert.equal(snapshot.histograms['search.ms'].max, 30);
17
- metrics.reset();
18
- assert.equal(metrics.snapshot().counters.writes, undefined);
19
- });
20
-
21
- test('metrics ignore non-finite observations', () => {
22
- const metrics = createMetrics();
23
- metrics.observe('x', NaN);
24
- metrics.observe('x', 'bad');
25
- assert.equal(metrics.snapshot().histograms.x?.count ?? 0, 0);
26
- });
@@ -1,38 +0,0 @@
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 { DatabaseSync } from 'node:sqlite';
7
- import { migrate } from '../../src/store/database.js';
8
-
9
- test('migration adds facts.superseded_at and backfills invalidated rows', () => {
10
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-migrate-'));
11
- const file = path.join(dir, 'legacy.sqlite');
12
- const db = new DatabaseSync(file);
13
- try {
14
- db.exec(`
15
- CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL);
16
- CREATE TABLE facts (
17
- id TEXT PRIMARY KEY, scope_id TEXT NOT NULL, subject_id TEXT NOT NULL,
18
- predicate TEXT NOT NULL, object_id TEXT, object_literal TEXT,
19
- valid_from TEXT, valid_to TEXT, recorded_at TEXT NOT NULL,
20
- confidence REAL NOT NULL DEFAULT 0.7, status TEXT NOT NULL DEFAULT 'active',
21
- source_event_id TEXT, invalidated_by TEXT, evidence_json TEXT NOT NULL DEFAULT '[]',
22
- hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
23
- );
24
- INSERT INTO meta VALUES ('schema_version', '5', '2026-11-01T00:00:00Z');
25
- INSERT INTO facts VALUES ('f_old','global','e1','喜欢',NULL,'白饭','2026-01-01','2026-02-01','2026-01-02',0.7,'invalidated',NULL,'f_new','[]','h','2026-01-02','2026-02-01');
26
- `);
27
- migrate(db);
28
- const columns = db.prepare('PRAGMA table_info(facts)').all().map((column) => column.name);
29
- assert.ok(columns.includes('superseded_at'));
30
- const row = db.prepare('SELECT superseded_at FROM facts WHERE id = ?').get('f_old');
31
- assert.equal(row.superseded_at, '2026-02-01');
32
- const version = db.prepare('SELECT value FROM meta WHERE key = ?').get('schema_version');
33
- assert.equal(version.value, '7');
34
- } finally {
35
- db.close();
36
- rmSync(dir, { recursive: true, force: true });
37
- }
38
- });
@@ -1,52 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { readModelConfig, saveModelConfig, redactedModelConfig } from '../../src/core/model-config.js';
7
-
8
- test('model config applies local preset and redacts keys', () => {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-model-config-'));
10
- try {
11
- const saved = saveModelConfig(dir, {
12
- embedding: { mode: 'local', apiKey: 'secret' },
13
- rerank: { enabled: true, baseUrl: 'http://127.0.0.1:9000/v1', model: 'r', apiKey: 'rerank-secret' },
14
- }, { confirm: true });
15
- assert.equal(saved.config.embedding.mode, 'local');
16
- assert.equal(saved.config.embedding.baseUrl, 'http://127.0.0.1:11434/v1');
17
- assert.equal(saved.config.embedding.model, 'bge-m3');
18
- assert.equal(saved.config.embedding.dim, 1024);
19
- assert.equal(saved.config.embedding.apiKeySet, true);
20
- assert.equal(saved.config.rerank.apiKeySet, true);
21
- assert.equal(readModelConfig(dir).embedding.apiKey, 'secret');
22
- assert.doesNotMatch(JSON.stringify(saved.config), /secret/);
23
- } finally {
24
- rmSync(dir, { recursive: true, force: true });
25
- }
26
- });
27
-
28
- test('model config tolerates a UTF-8 BOM from Windows PowerShell', () => {
29
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-model-config-bom-'));
30
- try {
31
- writeFileSync(path.join(dir, 'model-config.json'), '\uFEFF{"embedding":{"mode":"local","baseUrl":"http://127.0.0.1:11434/v1","model":"bge-m3","dim":1024}}', 'utf8');
32
- const config = readModelConfig(dir);
33
- assert.equal(config.embedding.mode, 'local');
34
- assert.equal(config.embedding.model, 'bge-m3');
35
- assert.equal(config.embedding.dim, 1024);
36
- } finally {
37
- rmSync(dir, { recursive: true, force: true });
38
- }
39
- });
40
-
41
- test('model config rejects missing remote fields and no confirmation', () => {
42
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-model-config-bad-'));
43
- try {
44
- assert.throws(() => saveModelConfig(dir, { rerank: { enabled: true, baseUrl: '', model: '' } }, { confirm: true }), /rerank needs/);
45
- assert.throws(() => saveModelConfig(dir, { embedding: { mode: 'remote', baseUrl: 'https://api.example/v1', model: 'm' } }, { confirm: true }), /needs apiKey/);
46
- assert.throws(() => saveModelConfig(dir, { embedding: { mode: 'hash' } }, {}), /confirm/);
47
- writeFileSync(path.join(dir, 'model-config.json'), '{broken', 'utf8');
48
- assert.equal(readModelConfig(dir).embedding.mode, 'hash');
49
- } finally {
50
- rmSync(dir, { recursive: true, force: true });
51
- }
52
- });