dsh-cortex-memory 0.4.146 → 0.4.148

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 (184) hide show
  1. package/CHANGELOG.md +2423 -2369
  2. package/README.md +8 -8
  3. package/bench/governance.mjs +265 -0
  4. package/bench/migration-bench.mjs +1 -1
  5. package/bench/semantic-cn.js +4 -4
  6. package/bench/synthetic.js +3 -3
  7. package/bin/copy-db.mjs +1 -1
  8. package/bin/repair.mjs +7 -7
  9. package/client.js +1 -1
  10. package/docs/install-windows.md +2 -2
  11. package/docs/models.md +1 -1
  12. package/docs/quota-compaction-design.md +3 -3
  13. package/icon.svg +12 -2
  14. package/index.js +5 -6
  15. package/package.json +7 -8
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/engines/compression.js +8 -3
  18. package/src/engines/consolidate.js +1 -1
  19. package/src/engines/encode.js +3 -3
  20. package/src/engines/extract.js +1 -1
  21. package/src/engines/health.js +1 -1
  22. package/src/engines/life.js +2 -2
  23. package/src/engines/narrative.js +4 -8
  24. package/src/engines/retrieve.js +41 -4
  25. package/src/host/scheduler.js +5 -4
  26. package/src/memory/tokenizer.js +1 -1
  27. package/src/self/alias.js +4 -5
  28. package/src/self/memory-policy.js +59 -0
  29. package/src/service/cortex.js +20 -2
  30. package/src/store/repositories/facts.js +1 -1
  31. package/src/store/repositories/traces.js +1 -1
  32. package/test/integration/_helpers.js +0 -128
  33. package/test/integration/acceptance.test.js +0 -803
  34. package/test/integration/ann-load.test.js +0 -61
  35. package/test/integration/api-contract.test.js +0 -1476
  36. package/test/integration/backup-privacy.test.js +0 -214
  37. package/test/integration/consolidate.test.js +0 -79
  38. package/test/integration/edge-cases.test.js +0 -1089
  39. package/test/integration/exchange.test.js +0 -326
  40. package/test/integration/life-loop.test.js +0 -189
  41. package/test/integration/load.test.js +0 -751
  42. package/test/integration/markdown-sync.test.js +0 -35
  43. package/test/integration/policy-query-api.test.js +0 -306
  44. package/test/integration/resilience-writes.test.js +0 -241
  45. package/test/integration/tools-contract.test.js +0 -1324
  46. package/test/unit/alias.test.js +0 -87
  47. package/test/unit/ann-edge.test.js +0 -102
  48. package/test/unit/ann.test.js +0 -77
  49. package/test/unit/api-client.test.js +0 -576
  50. package/test/unit/api-validate.test.js +0 -19
  51. package/test/unit/api.test.js +0 -555
  52. package/test/unit/appraisal.test.js +0 -48
  53. package/test/unit/attachments.test.js +0 -33
  54. package/test/unit/auto-reflect.test.js +0 -141
  55. package/test/unit/autonomy.test.js +0 -53
  56. package/test/unit/batch.test.js +0 -46
  57. package/test/unit/bench.test.js +0 -40
  58. package/test/unit/benchmark-synthetic.test.js +0 -52
  59. package/test/unit/capture-filter.test.js +0 -296
  60. package/test/unit/cli-default-root.test.js +0 -21
  61. package/test/unit/client-contract.test.js +0 -32
  62. package/test/unit/compaction-preview.test.js +0 -91
  63. package/test/unit/compression.test.js +0 -76
  64. package/test/unit/consolidate-dedupe.test.js +0 -174
  65. package/test/unit/consolidate-errors.test.js +0 -63
  66. package/test/unit/consolidate-gate.test.js +0 -26
  67. package/test/unit/consolidate-preview.test.js +0 -168
  68. package/test/unit/consolidate-protection.test.js +0 -156
  69. package/test/unit/consolidate-reason.test.js +0 -206
  70. package/test/unit/consolidate-retry.test.js +0 -91
  71. package/test/unit/consolidate-selection.test.js +0 -103
  72. package/test/unit/core.test.js +0 -77
  73. package/test/unit/coverage-rewrite.test.js +0 -38
  74. package/test/unit/dedupe-episodes.test.js +0 -34
  75. package/test/unit/dedupe-threshold.test.js +0 -14
  76. package/test/unit/develop.test.js +0 -130
  77. package/test/unit/development.test.js +0 -68
  78. package/test/unit/digest.test.js +0 -26
  79. package/test/unit/dsr.test.js +0 -111
  80. package/test/unit/edges-candidates.test.js +0 -113
  81. package/test/unit/emotion.test.js +0 -62
  82. package/test/unit/encode.test.js +0 -98
  83. package/test/unit/evolution.test.js +0 -130
  84. package/test/unit/external-ann-search.test.js +0 -50
  85. package/test/unit/external-ann.test.js +0 -29
  86. package/test/unit/extract-question.test.js +0 -41
  87. package/test/unit/fact-guard.test.js +0 -51
  88. package/test/unit/fact-noise-llm.test.js +0 -44
  89. package/test/unit/facts-belief.test.js +0 -32
  90. package/test/unit/facts-compat.test.js +0 -62
  91. package/test/unit/facts.test.js +0 -107
  92. package/test/unit/feature-overrides.test.js +0 -42
  93. package/test/unit/fts-migration.test.js +0 -42
  94. package/test/unit/graph.test.js +0 -79
  95. package/test/unit/growth-reflect.test.js +0 -124
  96. package/test/unit/guard-runtime.test.js +0 -40
  97. package/test/unit/guardian.test.js +0 -91
  98. package/test/unit/health-consolidation.test.js +0 -52
  99. package/test/unit/health-fts-scope.test.js +0 -33
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/health-summaries.test.js +0 -24
  102. package/test/unit/health-text-maintain.test.js +0 -33
  103. package/test/unit/health-today.test.js +0 -45
  104. package/test/unit/hnsw.test.js +0 -35
  105. package/test/unit/host-runtime.test.js +0 -142
  106. package/test/unit/host.test.js +0 -58
  107. package/test/unit/identity.test.js +0 -98
  108. package/test/unit/induct-evaluate.test.js +0 -41
  109. package/test/unit/ingest-extracted.test.js +0 -35
  110. package/test/unit/inhibition.test.js +0 -90
  111. package/test/unit/initiative.test.js +0 -90
  112. package/test/unit/jobs.test.js +0 -93
  113. package/test/unit/json-snapshot.test.js +0 -57
  114. package/test/unit/label-entities-skip.test.js +0 -18
  115. package/test/unit/life-consolidate.test.js +0 -34
  116. package/test/unit/life.test.js +0 -149
  117. package/test/unit/llm-facts-integration.test.js +0 -27
  118. package/test/unit/llm-facts.test.js +0 -16
  119. package/test/unit/llm.test.js +0 -45
  120. package/test/unit/locomo.test.js +0 -45
  121. package/test/unit/longmemeval.test.js +0 -56
  122. package/test/unit/maintain-dispute.test.js +0 -62
  123. package/test/unit/maintain-duration.test.js +0 -194
  124. package/test/unit/markdown-import.test.js +0 -44
  125. package/test/unit/markdown.test.js +0 -34
  126. package/test/unit/memory-edit.test.js +0 -112
  127. package/test/unit/metrics.test.js +0 -26
  128. package/test/unit/migration.test.js +0 -38
  129. package/test/unit/model-config.test.js +0 -52
  130. package/test/unit/mood-saturation.test.js +0 -33
  131. package/test/unit/narrative-weave.test.js +0 -271
  132. package/test/unit/narrative.test.js +0 -62
  133. package/test/unit/playbook-consolidate.test.js +0 -24
  134. package/test/unit/privacy-scope.test.js +0 -39
  135. package/test/unit/profile-paths.test.js +0 -21
  136. package/test/unit/profile.test.js +0 -26
  137. package/test/unit/prompt.test.js +0 -42
  138. package/test/unit/providers.test.js +0 -42
  139. package/test/unit/qa.test.js +0 -100
  140. package/test/unit/query.test.js +0 -53
  141. package/test/unit/reflect-backfill.test.js +0 -158
  142. package/test/unit/reflect-coverage.test.js +0 -35
  143. package/test/unit/reflect-overview.test.js +0 -22
  144. package/test/unit/reflect-phrasing.test.js +0 -75
  145. package/test/unit/reflect-sampling.test.js +0 -80
  146. package/test/unit/reflect-source-budget.test.js +0 -24
  147. package/test/unit/relationship-dynamics.test.js +0 -29
  148. package/test/unit/retention.test.js +0 -31
  149. package/test/unit/retrieval-ranking.test.js +0 -31
  150. package/test/unit/retrieve.test.js +0 -117
  151. package/test/unit/revive-on-read.test.js +0 -84
  152. package/test/unit/rotation.test.js +0 -25
  153. package/test/unit/scanner.test.js +0 -50
  154. package/test/unit/scenario.test.js +0 -78
  155. package/test/unit/scheduler-autoconsolidate.test.js +0 -95
  156. package/test/unit/scheduler-autodedupe.test.js +0 -52
  157. package/test/unit/scheduler-autosleep.test.js +0 -50
  158. package/test/unit/scheduler-cadence.test.js +0 -33
  159. package/test/unit/scheduler-deep.test.js +0 -62
  160. package/test/unit/scheduler-tick-gate.test.js +0 -38
  161. package/test/unit/scheduler.test.js +0 -137
  162. package/test/unit/self-state.test.js +0 -94
  163. package/test/unit/service.test.js +0 -72
  164. package/test/unit/shiori-import.test.js +0 -77
  165. package/test/unit/skills.test.js +0 -104
  166. package/test/unit/spacing.test.js +0 -14
  167. package/test/unit/store.test.js +0 -111
  168. package/test/unit/summon-left-slot.test.js +0 -51
  169. package/test/unit/summon-rank.test.js +0 -51
  170. package/test/unit/temporal-graph.test.js +0 -44
  171. package/test/unit/tiers-gist.test.js +0 -140
  172. package/test/unit/tiers.test.js +0 -39
  173. package/test/unit/tokenizer-fts.test.js +0 -35
  174. package/test/unit/tools.test.js +0 -122
  175. package/test/unit/upgrade-0412.test.js +0 -104
  176. package/test/unit/upgrade-0413.test.js +0 -84
  177. package/test/unit/upgrade-0414.test.js +0 -101
  178. package/test/unit/vector-ann.test.js +0 -53
  179. package/test/unit/vector-async.test.js +0 -69
  180. package/test/unit/vector-coverage.test.js +0 -34
  181. package/test/unit/vector-override.test.js +0 -37
  182. package/test/unit/vector-typed-array.test.js +0 -47
  183. package/test/unit/vector.test.js +0 -68
  184. package/test/unit/working.test.js +0 -99
@@ -1,84 +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 { 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
- });
@@ -1,101 +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 { 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
- });
@@ -1,53 +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(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
- });
@@ -1,69 +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 { 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
- });
@@ -1,34 +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 { openDatabase, migrate } from '../../src/store/database.js';
7
- import { createCortex } from '../../src/service/cortex.js';
8
-
9
- test('覆盖率只数活跃痕迹的向量,不会超过 100%', () => {
10
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-vector-coverage-'));
11
- const dbFile = path.join(dir, 'cortex.sqlite');
12
- const { db } = openDatabase({ dataRoot: dir, dbFile });
13
- migrate(db);
14
- const now = new Date().toISOString();
15
- db.prepare(`INSERT INTO events(id, seq, at, kind, scope_id, payload_json, hash) VALUES ('evt_1', 1, ?, 'observation', 'global', '{}', 'eh1')`).run(now);
16
- const insertTrace = db.prepare(`INSERT INTO traces(id, scope_id, kind, state, title, content, event_id, hash, recorded_at, updated_at, created_at) VALUES (?, 'global', 'observation', ?, ?, ?, 'evt_1', ?, ?, ?, ?)`);
17
- insertTrace.run('t_active_1', 'active', '活跃一', '正文一', 'h1', now, now, now);
18
- insertTrace.run('t_active_2', 'active', '活跃二', '正文二', 'h2', now, now, now);
19
- insertTrace.run('t_archived', 'archived', '旧的一', '正文三', 'h3', now, now, now); const blob = Buffer.from(new Float32Array(4).fill(0.1).buffer);
20
- const insertEmbedding = db.prepare(`INSERT INTO embeddings(trace_id, model, dim, vector, hash, updated_at) VALUES (?, 'fake', 4, ?, ?, ?)`);
21
- insertEmbedding.run('t_active_1', blob, 'h1', now);
22
- insertEmbedding.run('t_archived', blob, 'h3', now);
23
- db.close();
24
-
25
- const cortex = createCortex({ config: { dataRoot: dir, dbFile } });
26
- try {
27
- const health = cortex.health({ scopeId: 'global' });
28
- assert.equal(health.vectors.embedded, 1, '只应数活跃痕迹的向量');
29
- assert.ok(health.vectors.coverage <= 1, `覆盖率不应超过 1:${health.vectors.coverage}`);
30
- } finally {
31
- cortex.close();
32
- rmSync(dir, { recursive: true, force: true });
33
- }
34
- });
@@ -1,37 +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
-
8
- function setup(overrides) {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-vector-override-'));
10
- if (overrides) {
11
- writeFileSync(path.join(dir, 'feature-overrides.json'), JSON.stringify({ version: 1, current: overrides, history: [] }));
12
- }
13
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
14
- return { dir, cortex };
15
- }
16
-
17
- test('the settings-panel vector override actually enables the vector engine', () => {
18
- const { dir, cortex } = setup({ vector: true });
19
- try {
20
- assert.ok(cortex.vector, 'vector engine should exist when overrides say vector: true');
21
- assert.equal(typeof cortex.vector.backfillMissing, 'function');
22
- assert.equal(typeof cortex.vectorMaintain, 'function');
23
- } finally {
24
- cortex.close();
25
- rmSync(dir, { recursive: true, force: true });
26
- }
27
- });
28
-
29
- test('without the override and without config, vector stays off', () => {
30
- const { dir, cortex } = setup(null);
31
- try {
32
- assert.equal(cortex.vector, null);
33
- } finally {
34
- cortex.close();
35
- rmSync(dir, { recursive: true, force: true });
36
- }
37
- });
@@ -1,47 +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 { createVectorIndex } from '../../src/vector/index.js';
8
-
9
- function memoryDb() {
10
- const db = new DatabaseSync(':memory:');
11
- db.exec(`
12
- CREATE TABLE traces (id TEXT PRIMARY KEY, scope_id TEXT, state TEXT, title TEXT, content TEXT, summary TEXT, recorded_at TEXT);
13
- CREATE TABLE embeddings (trace_id TEXT PRIMARY KEY, model TEXT NOT NULL, dim INTEGER NOT NULL, vector BLOB NOT NULL, hash TEXT NOT NULL, updated_at TEXT NOT NULL);
14
- `);
15
- db.prepare("INSERT INTO traces(id, scope_id, state, title, content, summary, recorded_at) VALUES ('t1','global','active','标题','正文',NULL,'2026-11-15T00:00:00Z')").run();
16
- return db;
17
- }
18
-
19
- test('drainQueue accepts a Float32Array embedding and stores it', async () => {
20
- const db = memoryDb();
21
- try {
22
- const embedder = { kind: 'openai-embedding', async embed() { return new Float32Array(4).fill(0.5); } };
23
- const vector = createVectorIndex({ db, embedder, model: 'fake', dim: 4 });
24
- vector.backfillMissing({ limit: 1 });
25
- const result = await vector.drainQueue({ max: 1, budgetMs: 5000 });
26
- assert.equal(result.ok, 1);
27
- assert.equal(result.failed, 0);
28
- assert.equal(db.prepare('SELECT COUNT(*) AS c FROM embeddings').get().c, 1);
29
- } finally {
30
- db.close();
31
- }
32
- });
33
-
34
- test('a wrong dimension is still rejected and retried later', async () => {
35
- const db = memoryDb();
36
- try {
37
- const embedder = { kind: 'openai-embedding', async embed() { return new Float32Array(3); } };
38
- const vector = createVectorIndex({ db, embedder, model: 'fake', dim: 4 });
39
- vector.backfillMissing({ limit: 1 });
40
- const result = await vector.drainQueue({ max: 1, budgetMs: 5000 });
41
- assert.equal(result.ok, 0);
42
- assert.equal(db.prepare('SELECT COUNT(*) AS c FROM embeddings').get().c, 0);
43
- assert.ok(result.pending >= 1);
44
- } finally {
45
- db.close();
46
- }
47
- });
@@ -1,68 +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 { openDatabase, migrate, closeDatabase } from '../../src/store/database.js';
7
- import { createEventRepository } from '../../src/store/repositories/events.js';
8
- import { createTraceRepository } from '../../src/store/repositories/traces.js';
9
- import { createHashEmbedder, cosine } from '../../src/vector/embedder.js';
10
- import { createVectorIndex } from '../../src/vector/index.js';
11
- import { createCortex } from '../../src/service/cortex.js';
12
-
13
- function setup() {
14
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-vector-'));
15
- const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
16
- migrate(db);
17
- const events = createEventRepository(db);
18
- const traces = createTraceRepository(db);
19
- const embedder = createHashEmbedder();
20
- const vector = createVectorIndex({ db, embedder });
21
- return { dir, db, events, traces, embedder, vector };
22
- }
23
-
24
- test('hash embedder is deterministic and normalized', () => {
25
- const embedder = createHashEmbedder({ dim: 64 });
26
- const a = embedder.embed('米饭 用户');
27
- const b = embedder.embed('米饭 用户');
28
- assert.equal(a.length, 64);
29
- assert.ok(cosine(a, b) > 0.999);
30
- const c = embedder.embed('插件 安装');
31
- assert.ok(cosine(a, c) < 0.99);
32
- });
33
-
34
- test('vector index upserts, searches and removes', () => {
35
- const { dir, db, events, traces, vector } = setup();
36
- try {
37
- const event = events.append({ kind: 'utterance', payload: { text: '米饭' } });
38
- const trace = traces.insert({ eventId: event.id, content: '用户说会买米饭,助手等得起。' });
39
- vector.upsert(trace.id, trace.content);
40
- const hits = vector.search('米饭');
41
- assert.equal(hits[0].traceId, trace.id);
42
- assert.ok(hits[0].score > 0);
43
- assert.equal(vector.status().count, 1);
44
- vector.remove(trace.id);
45
- assert.equal(vector.search('米饭').length, 0);
46
- } finally {
47
- closeDatabase(db);
48
- rmSync(dir, { recursive: true, force: true });
49
- }
50
- });
51
-
52
- test('service enables vector retrieval and degrades when disabled', () => {
53
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-vector-service-'));
54
- const embedder = createHashEmbedder();
55
- const cortex = createCortex({
56
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), vectorEnabled: true, embedder },
57
- });
58
- try {
59
- cortex.write({ text: '用户说会买米饭,助手等得起。', explicit: true });
60
- const result = cortex.search('米饭');
61
- assert.ok(result.items.length >= 1);
62
- assert.ok(result.trace.sources.some((source) => source.source === 'vector' && source.ok));
63
- assert.equal(cortex.rebuildVector().rebuilt, 1);
64
- } finally {
65
- cortex.close();
66
- rmSync(dir, { recursive: true, force: true });
67
- }
68
- });
@@ -1,99 +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 { openDatabase, migrate, closeDatabase } from '../../src/store/database.js';
7
- import { createWorkingStore, createGoalStore, renderWorkingMemory } from '../../src/self/working.js';
8
- import { createCortex } from '../../src/service/cortex.js';
9
-
10
- function setup() {
11
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-working-'));
12
- const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
13
- migrate(db);
14
- return { dir, db, working: createWorkingStore(db), goals: createGoalStore(db) };
15
- }
16
-
17
- test('working memory orders pinned/high-priority and purges expired', () => {
18
- const { dir, db, working } = setup();
19
- try {
20
- const now = Date.parse('2026-11-11T12:00:00+08:00');
21
- const a = working.add({ text: '普通焦点', priority: 0.3, at: now });
22
- const b = working.add({ text: '重要焦点', priority: 0.9, at: now });
23
- const c = working.add({ text: '置顶焦点', priority: 0.1, pinned: true, at: now });
24
- const expired = working.add({ text: '会过期的焦点', priority: 1, ttlMs: 1000, at: now });
25
- const list = working.list({ at: now + 500 });
26
- assert.equal(list[0].id, c.id);
27
- assert.ok(list.some((item) => item.id === b.id));
28
- assert.equal(working.list({ at: now + 2000 }).some((item) => item.id === expired.id), false);
29
- assert.equal(working.purgeExpired({ at: now + 2000 }), 1);
30
- assert.equal(working.remove(a.id), true);
31
- } finally {
32
- closeDatabase(db);
33
- rmSync(dir, { recursive: true, force: true });
34
- }
35
- });
36
-
37
- test('a near-duplicate working item refreshes instead of piling up', () => {
38
- const { dir, db, working } = setup();
39
- try {
40
- const now = Date.parse('2026-11-15T12:00:00+08:00');
41
- const first = working.add({ text: '创造模式待办:①鱼塘 caps 放开;②shiori 残留清理', priority: 0.6, at: now });
42
- const second = working.add({ text: '创造模式待办:①鱼塘 caps 放开;②shiori 残留清理。', priority: 0.9, at: now + 1000 });
43
- assert.equal(second.id, first.id, 'the same todo must not be stored twice');
44
- assert.equal(working.list({ at: now + 2000 }).length, 1);
45
- assert.equal(working.get(first.id).priority, 0.9, 'priority is refreshed to the higher value');
46
- const distinct = working.add({ text: '完全不同的另一件事:给 agency 加抑制实验。', priority: 0.5, at: now + 2000 });
47
- assert.notEqual(distinct.id, first.id);
48
- const forced = working.add({ text: '创造模式待办:①鱼塘 caps 放开;②shiori 残留清理', priority: 0.4, at: now + 3000, dedupe: false });
49
- assert.notEqual(forced.id, first.id, 'dedupe:false still allows an explicit duplicate');
50
- } finally {
51
- closeDatabase(db);
52
- rmSync(dir, { recursive: true, force: true });
53
- }
54
- });
55
-
56
- test('working memory render respects the token budget', () => {
57
- const { dir, db, working } = setup();
58
- try {
59
- for (let i = 0; i < 10; i += 1) working.add({ text: `第 ${i} 条比较长的焦点内容,用来测试预算裁剪。`, priority: 0.5 });
60
- const rendered = renderWorkingMemory(working.list(), { budgetTokens: 40 });
61
- assert.ok(rendered.used <= 40);
62
- assert.ok(rendered.count >= 1);
63
- } finally {
64
- closeDatabase(db);
65
- rmSync(dir, { recursive: true, force: true });
66
- }
67
- });
68
-
69
- test('goals can be added, progressed and completed', () => {
70
- const { dir, db, goals } = setup();
71
- try {
72
- const goal = goals.add({ title: '把 cortex 写到 30k 行', priority: 0.8 });
73
- assert.equal(goal.status, 'active');
74
- const updated = goals.update(goal.id, { progress: 0.4, description: '继续写模块' });
75
- assert.equal(updated.progress, 0.4);
76
- const done = goals.complete(goal.id);
77
- assert.equal(done.status, 'completed');
78
- assert.equal(done.progress, 1);
79
- assert.equal(goals.list({ status: 'active' }).length, 0);
80
- } finally {
81
- closeDatabase(db);
82
- rmSync(dir, { recursive: true, force: true });
83
- }
84
- });
85
-
86
- test('service self shows working memory and active goals', () => {
87
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-working-service-'));
88
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
89
- try {
90
- cortex.working.add({ text: '当前焦点:写模块' });
91
- cortex.goals.add({ title: '完成 30k 行' });
92
- const snapshot = cortex.self();
93
- assert.ok(snapshot.working.some((item) => item.text.includes('写模块')));
94
- assert.ok(snapshot.goals.some((item) => item.title.includes('30k')));
95
- } finally {
96
- cortex.close();
97
- rmSync(dir, { recursive: true, force: true });
98
- }
99
- });