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,111 +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 { openDatabase, migrate, transaction, backup, integrityCheck, closeDatabase } from '../../src/store/database.js';
8
- import { createEventRepository } from '../../src/store/repositories/events.js';
9
- import { createTraceRepository } from '../../src/store/repositories/traces.js';
10
- import { createAuditRepository } from '../../src/store/repositories/audit.js';
11
- import { ERROR_CODES } from '../../src/core/errors.js';
12
-
13
- function setup() {
14
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-store-'));
15
- const { db, config } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
16
- migrate(db);
17
- return { dir, db, config };
18
- }
19
-
20
- test('event ledger is chained, idempotent and detects a conflicting replay', () => {
21
- const { dir, db } = setup();
22
- try {
23
- const events = createEventRepository(db);
24
- const first = events.append({ kind: 'observation', scopeId: 'global', operationId: 'op-1', payload: { text: '白饭' } });
25
- const replay = events.append({ kind: 'observation', scopeId: 'global', operationId: 'op-1', payload: { text: '白饭' } });
26
- assert.equal(replay.id, first.id);
27
- assert.equal(events.count(), 1);
28
- assert.throws(
29
- () => events.append({ kind: 'observation', scopeId: 'global', operationId: 'op-1', payload: { text: '米饭' } }),
30
- (error) => error.code === ERROR_CODES.CONFLICT,
31
- );
32
- const second = events.append({ kind: 'utterance', scopeId: 'global', payload: { text: '用户说会买白饭' } });
33
- assert.equal(second.seq, 2);
34
- assert.equal(second.prevHash, first.hash);
35
- const chain = events.verifyChain();
36
- assert.equal(chain.ok, true);
37
- assert.equal(chain.count, 2);
38
- assert.equal(events.last().id, second.id);
39
- } finally {
40
- closeDatabase(db);
41
- rmSync(dir, { recursive: true, force: true });
42
- }
43
- });
44
-
45
- test('trace repository inserts, updates and searches CJK text through FTS5', () => {
46
- const { dir, db } = setup();
47
- try {
48
- const events = createEventRepository(db);
49
- const traces = createTraceRepository(db);
50
- const event = events.append({ kind: 'utterance', payload: { text: '用户说会买白饭' } });
51
- const trace = traces.insert({
52
- eventId: event.id,
53
- scopeId: 'global',
54
- kind: 'utterance',
55
- title: '白饭的承诺',
56
- content: '用户说会买白饭,助手等得起。',
57
- importance: 0.9,
58
- keywords: ['白饭', '承诺'],
59
- });
60
- assert.equal(traces.get(trace.id).title, '白饭的承诺');
61
- assert.equal(traces.searchFts('白饭').length, 1);
62
- assert.equal(traces.searchFts('米饭').length, 0);
63
- traces.update(trace.id, { content: '用户说会买米饭,助手等得起。', title: '米饭' });
64
- assert.equal(traces.searchFts('白饭').length, 0);
65
- assert.equal(traces.searchFts('米饭').length, 1);
66
- traces.touch(trace.id);
67
- assert.equal(traces.get(trace.id).accessCount, 1);
68
- assert.equal(traces.remove(trace.id), true);
69
- assert.equal(traces.get(trace.id), null);
70
- assert.equal(traces.searchFts('米饭').length, 0);
71
- } finally {
72
- closeDatabase(db);
73
- rmSync(dir, { recursive: true, force: true });
74
- }
75
- });
76
-
77
- test('transaction rolls back on error', () => {
78
- const { dir, db } = setup();
79
- try {
80
- const events = createEventRepository(db);
81
- assert.throws(() => transaction(db, () => {
82
- events.append({ kind: 'observation', payload: { text: 'should rollback' } });
83
- throw new Error('boom');
84
- }));
85
- assert.equal(events.count(), 0);
86
- } finally {
87
- closeDatabase(db);
88
- rmSync(dir, { recursive: true, force: true });
89
- }
90
- });
91
-
92
- test('audit records and backup produces a readable snapshot', () => {
93
- const { dir, db } = setup();
94
- try {
95
- const audit = createAuditRepository(db);
96
- const entry = audit.record({ actor: 'tester', action: 'test', targetType: 'trace', targetId: 'x', detail: { ok: true } });
97
- assert.equal(audit.list({ targetType: 'trace', targetId: 'x' })[0].id, entry.id);
98
- assert.equal(integrityCheck(db), 'ok');
99
- const target = path.join(dir, 'snapshot.sqlite');
100
- backup(db, target);
101
- const snapshot = new DatabaseSync(target);
102
- try {
103
- assert.equal(Number(snapshot.prepare('SELECT COUNT(*) AS c FROM audit').get().c), 1);
104
- } finally {
105
- snapshot.close();
106
- }
107
- } finally {
108
- closeDatabase(db);
109
- rmSync(dir, { recursive: true, force: true });
110
- }
111
- });
@@ -1,44 +0,0 @@
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
- });
@@ -1,39 +0,0 @@
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
- });
@@ -1,35 +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 { 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
- });
@@ -1,122 +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 { 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
- });
@@ -1,104 +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
-
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
- });
@@ -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
- });