dsh-cortex-memory 0.4.146 → 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 (168) hide show
  1. package/CHANGELOG.md +2396 -2369
  2. package/README.md +8 -6
  3. package/bench/semantic-cn.js +4 -4
  4. package/bench/synthetic.js +2 -2
  5. package/bin/copy-db.mjs +1 -1
  6. package/client.js +1 -1
  7. package/docs/quota-compaction-design.md +2 -2
  8. package/icon.svg +12 -2
  9. package/package.json +1 -1
  10. package/src/engines/consolidate.js +2 -2
  11. package/src/engines/health.js +1 -1
  12. package/src/engines/life.js +2 -2
  13. package/src/engines/narrative.js +2 -2
  14. package/src/host/scheduler.js +1 -1
  15. package/src/store/repositories/traces.js +1 -1
  16. package/test/integration/_helpers.js +0 -128
  17. package/test/integration/acceptance.test.js +0 -803
  18. package/test/integration/ann-load.test.js +0 -61
  19. package/test/integration/api-contract.test.js +0 -1476
  20. package/test/integration/backup-privacy.test.js +0 -214
  21. package/test/integration/consolidate.test.js +0 -79
  22. package/test/integration/edge-cases.test.js +0 -1089
  23. package/test/integration/exchange.test.js +0 -326
  24. package/test/integration/life-loop.test.js +0 -189
  25. package/test/integration/load.test.js +0 -751
  26. package/test/integration/markdown-sync.test.js +0 -35
  27. package/test/integration/policy-query-api.test.js +0 -306
  28. package/test/integration/resilience-writes.test.js +0 -241
  29. package/test/integration/tools-contract.test.js +0 -1324
  30. package/test/unit/alias.test.js +0 -87
  31. package/test/unit/ann-edge.test.js +0 -102
  32. package/test/unit/ann.test.js +0 -77
  33. package/test/unit/api-client.test.js +0 -576
  34. package/test/unit/api-validate.test.js +0 -19
  35. package/test/unit/api.test.js +0 -555
  36. package/test/unit/appraisal.test.js +0 -48
  37. package/test/unit/attachments.test.js +0 -33
  38. package/test/unit/auto-reflect.test.js +0 -141
  39. package/test/unit/autonomy.test.js +0 -53
  40. package/test/unit/batch.test.js +0 -46
  41. package/test/unit/bench.test.js +0 -40
  42. package/test/unit/benchmark-synthetic.test.js +0 -52
  43. package/test/unit/capture-filter.test.js +0 -296
  44. package/test/unit/cli-default-root.test.js +0 -21
  45. package/test/unit/client-contract.test.js +0 -32
  46. package/test/unit/compaction-preview.test.js +0 -91
  47. package/test/unit/compression.test.js +0 -76
  48. package/test/unit/consolidate-dedupe.test.js +0 -174
  49. package/test/unit/consolidate-errors.test.js +0 -63
  50. package/test/unit/consolidate-gate.test.js +0 -26
  51. package/test/unit/consolidate-preview.test.js +0 -168
  52. package/test/unit/consolidate-protection.test.js +0 -156
  53. package/test/unit/consolidate-reason.test.js +0 -206
  54. package/test/unit/consolidate-retry.test.js +0 -91
  55. package/test/unit/consolidate-selection.test.js +0 -103
  56. package/test/unit/core.test.js +0 -77
  57. package/test/unit/coverage-rewrite.test.js +0 -38
  58. package/test/unit/dedupe-episodes.test.js +0 -34
  59. package/test/unit/dedupe-threshold.test.js +0 -14
  60. package/test/unit/develop.test.js +0 -130
  61. package/test/unit/development.test.js +0 -68
  62. package/test/unit/digest.test.js +0 -26
  63. package/test/unit/dsr.test.js +0 -111
  64. package/test/unit/edges-candidates.test.js +0 -113
  65. package/test/unit/emotion.test.js +0 -62
  66. package/test/unit/encode.test.js +0 -98
  67. package/test/unit/evolution.test.js +0 -130
  68. package/test/unit/external-ann-search.test.js +0 -50
  69. package/test/unit/external-ann.test.js +0 -29
  70. package/test/unit/extract-question.test.js +0 -41
  71. package/test/unit/fact-guard.test.js +0 -51
  72. package/test/unit/fact-noise-llm.test.js +0 -44
  73. package/test/unit/facts-belief.test.js +0 -32
  74. package/test/unit/facts-compat.test.js +0 -62
  75. package/test/unit/facts.test.js +0 -107
  76. package/test/unit/feature-overrides.test.js +0 -42
  77. package/test/unit/fts-migration.test.js +0 -42
  78. package/test/unit/graph.test.js +0 -79
  79. package/test/unit/growth-reflect.test.js +0 -124
  80. package/test/unit/guard-runtime.test.js +0 -40
  81. package/test/unit/guardian.test.js +0 -91
  82. package/test/unit/health-consolidation.test.js +0 -52
  83. package/test/unit/health-fts-scope.test.js +0 -33
  84. package/test/unit/health-privacy.test.js +0 -102
  85. package/test/unit/health-summaries.test.js +0 -24
  86. package/test/unit/health-text-maintain.test.js +0 -33
  87. package/test/unit/health-today.test.js +0 -45
  88. package/test/unit/hnsw.test.js +0 -35
  89. package/test/unit/host-runtime.test.js +0 -142
  90. package/test/unit/host.test.js +0 -58
  91. package/test/unit/identity.test.js +0 -98
  92. package/test/unit/induct-evaluate.test.js +0 -41
  93. package/test/unit/ingest-extracted.test.js +0 -35
  94. package/test/unit/inhibition.test.js +0 -90
  95. package/test/unit/initiative.test.js +0 -90
  96. package/test/unit/jobs.test.js +0 -93
  97. package/test/unit/json-snapshot.test.js +0 -57
  98. package/test/unit/label-entities-skip.test.js +0 -18
  99. package/test/unit/life-consolidate.test.js +0 -34
  100. package/test/unit/life.test.js +0 -149
  101. package/test/unit/llm-facts-integration.test.js +0 -27
  102. package/test/unit/llm-facts.test.js +0 -16
  103. package/test/unit/llm.test.js +0 -45
  104. package/test/unit/locomo.test.js +0 -45
  105. package/test/unit/longmemeval.test.js +0 -56
  106. package/test/unit/maintain-dispute.test.js +0 -62
  107. package/test/unit/maintain-duration.test.js +0 -194
  108. package/test/unit/markdown-import.test.js +0 -44
  109. package/test/unit/markdown.test.js +0 -34
  110. package/test/unit/memory-edit.test.js +0 -112
  111. package/test/unit/metrics.test.js +0 -26
  112. package/test/unit/migration.test.js +0 -38
  113. package/test/unit/model-config.test.js +0 -52
  114. package/test/unit/mood-saturation.test.js +0 -33
  115. package/test/unit/narrative-weave.test.js +0 -271
  116. package/test/unit/narrative.test.js +0 -62
  117. package/test/unit/playbook-consolidate.test.js +0 -24
  118. package/test/unit/privacy-scope.test.js +0 -39
  119. package/test/unit/profile-paths.test.js +0 -21
  120. package/test/unit/profile.test.js +0 -26
  121. package/test/unit/prompt.test.js +0 -42
  122. package/test/unit/providers.test.js +0 -42
  123. package/test/unit/qa.test.js +0 -100
  124. package/test/unit/query.test.js +0 -53
  125. package/test/unit/reflect-backfill.test.js +0 -158
  126. package/test/unit/reflect-coverage.test.js +0 -35
  127. package/test/unit/reflect-overview.test.js +0 -22
  128. package/test/unit/reflect-phrasing.test.js +0 -75
  129. package/test/unit/reflect-sampling.test.js +0 -80
  130. package/test/unit/reflect-source-budget.test.js +0 -24
  131. package/test/unit/relationship-dynamics.test.js +0 -29
  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/revive-on-read.test.js +0 -84
  136. package/test/unit/rotation.test.js +0 -25
  137. package/test/unit/scanner.test.js +0 -50
  138. package/test/unit/scenario.test.js +0 -78
  139. package/test/unit/scheduler-autoconsolidate.test.js +0 -95
  140. package/test/unit/scheduler-autodedupe.test.js +0 -52
  141. package/test/unit/scheduler-autosleep.test.js +0 -50
  142. package/test/unit/scheduler-cadence.test.js +0 -33
  143. package/test/unit/scheduler-deep.test.js +0 -62
  144. package/test/unit/scheduler-tick-gate.test.js +0 -38
  145. package/test/unit/scheduler.test.js +0 -137
  146. package/test/unit/self-state.test.js +0 -94
  147. package/test/unit/service.test.js +0 -72
  148. package/test/unit/shiori-import.test.js +0 -77
  149. package/test/unit/skills.test.js +0 -104
  150. package/test/unit/spacing.test.js +0 -14
  151. package/test/unit/store.test.js +0 -111
  152. package/test/unit/summon-left-slot.test.js +0 -51
  153. package/test/unit/summon-rank.test.js +0 -51
  154. package/test/unit/temporal-graph.test.js +0 -44
  155. package/test/unit/tiers-gist.test.js +0 -140
  156. package/test/unit/tiers.test.js +0 -39
  157. package/test/unit/tokenizer-fts.test.js +0 -35
  158. package/test/unit/tools.test.js +0 -122
  159. package/test/unit/upgrade-0412.test.js +0 -104
  160. package/test/unit/upgrade-0413.test.js +0 -84
  161. package/test/unit/upgrade-0414.test.js +0 -101
  162. package/test/unit/vector-ann.test.js +0 -53
  163. package/test/unit/vector-async.test.js +0 -69
  164. package/test/unit/vector-coverage.test.js +0 -34
  165. package/test/unit/vector-override.test.js +0 -37
  166. package/test/unit/vector-typed-array.test.js +0 -47
  167. package/test/unit/vector.test.js +0 -68
  168. package/test/unit/working.test.js +0 -99
@@ -1,32 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { readFileSync } from 'node:fs';
4
- import path from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
-
7
- const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'client.js');
8
- const source = readFileSync(file, 'utf8');
9
-
10
- test('client registers the expected panel tabs and playbook actions', () => {
11
- assert.match(source, /__ModuleLoader__\.load/);
12
- assert.match(source, /id: 'dsh-cortex'/);
13
- assert.doesNotMatch(source, /id: 'dsh-cortex-memory'/);
14
- for (const tab of ['self', 'search', 'timeline', 'working', 'emotion', 'life', 'graph', 'playbook', 'audit', 'retention', 'health', 'evolution', 'settings']) {
15
- assert.match(source, new RegExp(`\\['${tab}', t\\('`), `tab ${tab}`);
16
- }
17
- assert.match(source, /api\('\/playbook\?status=candidate'\)/);
18
- assert.match(source, /act\('approve'/);
19
- assert.match(source, /api\('\/permissions'/);
20
- assert.match(source, /window\.confirm/);
21
- assert.match(source, /vectorDisabled/);
22
- assert.match(source, /autoFacts/);
23
- });
24
-
25
- test('client keeps keyboard and aria wiring for the panel', () => {
26
- assert.match(source, /role: 'tablist'/);
27
- assert.match(source, /aria-selected/);
28
- assert.match(source, /ArrowRight/);
29
- assert.match(source, /role: 'tabpanel'/);
30
- });
31
-
32
-
@@ -1,91 +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-preview-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- return { cortex, dir };
12
- }
13
-
14
- test('coverage2:摘要正文真的装下才给分,薄摘要封顶 0.35', () => {
15
- const trace = { id: 't1', title: '辉夜姬', content: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。' };
16
- const good = { id: 's1', content: '今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。' };
17
- const thin = { id: 's2', content: '图书馆' };
18
- const unrelated = { id: 's3', content: '完全无关的一句话。' };
19
- const { cortex, dir } = setup();
20
- try {
21
- const goodScore = cortex.compression.coverage2(trace, [good]);
22
- const thinScore = cortex.compression.coverage2(trace, [thin]);
23
- const noneScore = cortex.compression.coverage2(trace, [unrelated]);
24
- assert.ok(goodScore.score >= 0.6, `装得下的摘要应给高分,实际 ${goodScore.score}`);
25
- assert.ok(thinScore.score <= 0.35, '薄摘要必须封顶');
26
- assert.equal(noneScore.score, 0);
27
- } finally {
28
- cortex.close();
29
- rmSync(dir, { recursive: true, force: true });
30
- }
31
- });
32
-
33
- test('previewCoverage:只读、跳过保护与近期访问、给出分位', () => {
34
- const { cortex, dir } = setup();
35
- try {
36
- const now = Date.now();
37
- for (let i = 0; i < 6; i += 1) {
38
- cortex.write({ text: `用户:一条普通记录 ${i}`, kind: 'utterance', title: `普通 ${i}`, importance: 0.7, explicit: true, now });
39
- }
40
- cortex.write({ text: '用户:一条受保护的记录', kind: 'utterance', title: '保护', importance: 0.99, explicit: true, now });
41
- const before = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 50 }).length;
42
- const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 100 });
43
- const after = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 50 }).length;
44
- assert.equal(before, after, '预演不能改库');
45
- assert.equal(report.total, 7);
46
- assert.ok(report.protectedSkipped >= 1, '高重要度应被跳过');
47
- assert.ok(report.percentiles && typeof report.percentiles.p90 === 'number');
48
- assert.ok(Array.isArray(report.wouldCut));
49
- } finally {
50
- cortex.close();
51
- rmSync(dir, { recursive: true, force: true });
52
- }
53
- });
54
-
55
- test('高频通用词会被 DF 过滤:只含「我们/可以」的摘要不该算覆盖', async () => {
56
- const { cortex, dir } = setup();
57
- try {
58
- const now = Date.now();
59
- for (let i = 0; i < 30; i += 1) {
60
- cortex.write({ text: `我们可以做第${i}件事,这件事有点特别。`, kind: 'utterance', title: `样本 ${i}`, importance: 0.7, explicit: true, now });
61
- }
62
- cortex.repos.summaries.insert({
63
- scopeId: 'global', level: 'episode', content: '我们可以。', sourceIds: [], coverage: 1, model: 'test',
64
- });
65
- const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 100 });
66
- assert.equal(report.summaryCovered, 0, '通用二字词被过滤后不应算覆盖');
67
- assert.equal(report.pool, 0);
68
- } finally {
69
- cortex.close();
70
- rmSync(dir, { recursive: true, force: true });
71
- }
72
- });
73
-
74
- test('只有摘要一条证据时,不把单证据条目当候选输出', async () => {
75
- const { cortex, dir } = setup();
76
- try {
77
- const now = Date.now();
78
- cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。', kind: 'utterance', title: '辉夜姬', importance: 0.7, explicit: true, now });
79
- cortex.repos.summaries.insert({
80
- scopeId: 'global', level: 'episode', content: '今天在图书馆看了超时空辉夜姬第三集,很好笑,还吃了米饭。', sourceIds: [], coverage: 1, model: 'test',
81
- });
82
- const report = cortex.compression.previewCoverage({ scopeId: 'global', limit: 50 });
83
- assert.ok(report.pool >= 0);
84
- assert.equal(report.strongPool, 0, '没有事实时不存在两类证据');
85
- assert.equal(report.wouldCut.length, 0, '单证据不能当候选');
86
- assert.ok(['no_signal', 'single-evidence-only'].includes(report.reason));
87
- } finally {
88
- cortex.close();
89
- rmSync(dir, { recursive: true, force: true });
90
- }
91
- });
@@ -1,76 +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 { extractFactCandidates } from '../../src/engines/extract.js';
8
- import { coverageOf } from '../../src/engines/compression.js';
9
-
10
- test('fact extraction finds preferences, states and plans', () => {
11
- const candidates = extractFactCandidates('用户喜欢米饭,助手会在明天继续修插件,米饭是主食。');
12
- assert.ok(candidates.some((item) => item.predicate === 'likes' && item.object.includes('米饭')));
13
- assert.ok(candidates.some((item) => item.predicate === 'will'));
14
- assert.ok(candidates.some((item) => item.predicate === 'is'));
15
- });
16
-
17
- test('negated predicates are not also extracted as their positive form', () => {
18
- const negative = extractFactCandidates('用户不喜欢猫。');
19
- assert.ok(negative.some((item) => item.predicate === 'dislikes' && item.object.includes('猫')));
20
- assert.ok(!negative.some((item) => item.predicate === 'likes'));
21
-
22
- const positive = extractFactCandidates('用户喜欢猫。');
23
- assert.ok(positive.some((item) => item.predicate === 'likes' && item.confidence === 0.55));
24
- assert.ok(!positive.some((item) => item.predicate === 'dislikes'));
25
- });
26
-
27
- test('coverage prefers source pointers over token overlap', () => {
28
- const trace = { id: 't1', eventId: 'e1', content: '米饭 承诺 用户' };
29
- const bySource = coverageOf(trace, { summaries: [{ id: 's1', sourceIds: ['t1'], content: '完全不同的摘要' }], facts: [] });
30
- assert.equal(bySource.coverage, 1);
31
- assert.equal(bySource.by, 'summary-source');
32
- const byFact = coverageOf(trace, { summaries: [], facts: [{ sourceEventId: 'e1' }] });
33
- assert.equal(byFact.coverage, 0.6);
34
- });
35
-
36
- test('compression archives covered old traces and revive brings them back', () => {
37
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-compress-'));
38
- const cortex = createCortex({
39
- config: {
40
- dataRoot: dir,
41
- dbFile: path.join(dir, 'cortex.sqlite'),
42
- compression: { minAgeDays: 0, retrievability: 1, importance: 1, coverageThreshold: 0 },
43
- },
44
- });
45
- try {
46
- const written = cortex.write({ text: '一条会被压缩的旧记忆。', explicit: true, importance: 0.1, now: Date.now() - 30 * 86400000 });
47
- cortex.repos.summaries.insert({ content: '摘要', sourceIds: [written.trace.id], coverage: 1 });
48
- const evaluated = cortex.compression.evaluate();
49
- assert.ok(evaluated.some((row) => row.trace.id === written.trace.id && row.eligible));
50
- const compressed = cortex.compression.compress();
51
- assert.ok(compressed.archived >= 1);
52
- assert.equal(cortex.get(written.trace.id).state, 'archived');
53
- const revived = cortex.compression.revive(written.trace.id);
54
- assert.equal(revived.revived, true);
55
- assert.equal(cortex.get(written.trace.id).state, 'active');
56
- } finally {
57
- cortex.close();
58
- rmSync(dir, { recursive: true, force: true });
59
- }
60
- });
61
-
62
- test('autoFacts writes semantic facts when enabled', () => {
63
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-autofacts-'));
64
- const cortex = createCortex({
65
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { autoFacts: true } },
66
- });
67
- try {
68
- const result = cortex.write({ text: '用户喜欢米饭。', explicit: true });
69
- assert.ok(result.autoFacts);
70
- assert.ok(result.autoFacts.resolved.length >= 1);
71
- assert.ok(cortex.repos.facts.list({ limit: 10 }).length >= 1);
72
- } finally {
73
- cortex.close();
74
- rmSync(dir, { recursive: true, force: true });
75
- }
76
- });
@@ -1,174 +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
- const PAIR = [
9
- '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。',
10
- '用户:今天在图书馆看了超时空辉夜姬第三集,特别好笑。',
11
- ];
12
-
13
- function setup(importances = [0.6, 0.55]) {
14
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-dedupe-'));
15
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
16
- return { cortex, dir };
17
- }
18
-
19
- test('确定性去重:预演只报可合并组,不动库', async () => {
20
- const { cortex, dir } = setup();
21
- try {
22
- const now = Date.now();
23
- PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.6, explicit: true, now }));
24
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: true, threshold: 0.7 });
25
- assert.equal(result.decisions.length, 1, '应识别出一组');
26
- assert.equal(result.applied.length, 0);
27
- assert.equal(result.run.model, 'dedupe');
28
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
29
- assert.equal(active.length, 2, '预演不能改库');
30
- } finally {
31
- cortex.close();
32
- rmSync(dir, { recursive: true, force: true });
33
- }
34
- });
35
-
36
- test('确定性去重:真跑会把低重要度那条归档,并留合并摘要', async () => {
37
- const { cortex, dir } = setup();
38
- try {
39
- const now = Date.now();
40
- PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.6, explicit: true, now }));
41
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.7 });
42
- assert.equal(result.applied.length, 1);
43
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
44
- assert.equal(active.length, 1, '重复的两条应合成一条');
45
- const archived = cortex.repos.traces.list({ scopeId: 'global', state: 'archived', limit: 10 });
46
- assert.equal(archived.length, 1);
47
- assert.equal(archived[0].compression, 'merged');
48
- } finally {
49
- cortex.close();
50
- rmSync(dir, { recursive: true, force: true });
51
- }
52
- });
53
-
54
- test('保护线上的近重复仍可合并(活库里 75% 都在线上)', async () => {
55
- const { cortex, dir } = setup();
56
- try {
57
- const now = Date.now();
58
- PAIR.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `辉夜姬 ${i}`, importance: 0.95, explicit: true, now }));
59
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.7 });
60
- assert.equal(result.applied.length, 1, '近乎相同的两条不该因为都在保护线上就永久并存');
61
- assert.equal(result.decisions.length, 1);
62
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
63
- assert.equal(active.length, 1);
64
- } finally {
65
- cortex.close();
66
- rmSync(dir, { recursive: true, force: true });
67
- }
68
- });
69
-
70
- test('reflection 不参与去重(既不当来源也不被合并)', async () => {
71
- const { cortex, dir } = setup();
72
- try {
73
- const now = Date.now();
74
- cortex.write({ text: '今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'reflection', title: '反思', importance: 0.5, explicit: true, now });
75
- cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'utterance', title: '辉夜姬', importance: 0.5, explicit: true, now });
76
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold: 0.6 });
77
- assert.equal(result.applied.length, 0, '单独一条 utterance 没有同伙,不该合并');
78
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
79
- assert.equal(active.length, 2, 'reflection 与普通痕迹都还在');
80
- } finally {
81
- cortex.close();
82
- rmSync(dir, { recursive: true, force: true });
83
- }
84
- });
85
-
86
- test('LLM 想把 reflection 当来源 merge 时会被拒', async () => {
87
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-dedupe-v-'));
88
- let reflexId = null;
89
- const cortex = createCortex({
90
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
91
- llm: {
92
- available: () => true,
93
- complete: async () => {
94
- const ids = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 }).sort((a, b) => Number(b.importance) - Number(a.importance));
95
- return JSON.stringify([{ action: 'merge', ids: ids.map((t) => t.id), targetId: ids[0].id }]);
96
- },
97
- },
98
- });
99
- try {
100
- const now = Date.now();
101
- reflexId = cortex.write({ text: '我想:一条低重要度的反思。', kind: 'reflection', title: '反思', importance: 0.5, explicit: true, now });
102
- cortex.write({ text: '用户:另一条普通痕迹。', kind: 'utterance', title: '普通', importance: 0.6, explicit: true, now });
103
- const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
104
- assert.equal(result.applied.length, 0, '不应真的合并');
105
- assert.match(String(result.run.error), /rejected 1|rejected 2/);
106
- const still = cortex.repos.traces.get(String(reflexId?.trace?.id ?? reflexId));
107
- assert.notEqual(still?.state, 'archived');
108
- } finally {
109
- cortex.close();
110
- rmSync(dir, { recursive: true, force: true });
111
- }
112
- });
113
-
114
- test('LLM 路线仍不允许把受保护的痕迹当 merge 来源', async () => {
115
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-protect-'));
116
- const cortex = createCortex({
117
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
118
- llm: {
119
- available: () => true,
120
- complete: async () => {
121
- const list = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
122
- return JSON.stringify([{ action: 'merge', ids: list.map((t) => t.id), targetId: list[0].id }]);
123
- },
124
- },
125
- });
126
- try {
127
- const now = Date.now();
128
- for (let i = 0; i < 2; i += 1) cortex.write({ text: `用户:受保护样本 ${i}`, kind: 'utterance', title: `保护 ${i}`, importance: 0.97, explicit: true, now });
129
- const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
130
- assert.equal(result.applied.length, 0, 'LLM 不能合受保护的痕迹');
131
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 });
132
- assert.equal(active.length, 2);
133
- } finally {
134
- cortex.close();
135
- rmSync(dir, { recursive: true, force: true });
136
- }
137
- });
138
-
139
- test('被归档的条目,与 target 的相似度必须仍然达标(防链式误合)', async () => {
140
- const shingles = (value) => {
141
- const flat = String(value ?? '').replace(/\s+/g, '');
142
- const set = new Set();
143
- for (let i = 0; i + 2 <= flat.length; i += 1) set.add(flat.slice(i, i + 2));
144
- return set;
145
- };
146
- const jaccard = (a, b) => {
147
- if (!a.size || !b.size) return 0;
148
- let shared = 0;
149
- for (const g of a) if (b.has(g)) shared += 1;
150
- return shared / (a.size + b.size - shared);
151
- };
152
- const { cortex, dir } = setup();
153
- try {
154
- const now = Date.now();
155
- const texts = [
156
- '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。',
157
- '用户:今天在图书馆看了超时空辉夜姬第三集,特别好笑。',
158
- '用户:今天在图书馆看了超时空辉夜姬第三集,非常好笑。',
159
- '用户:今天下雨了,路上很挤,回家吃了米饭。',
160
- ];
161
- texts.forEach((text, i) => cortex.write({ text, kind: 'utterance', title: `样本 ${i}`, importance: 1.0 - i * 0.01, explicit: true, now }));
162
- const threshold = 0.7;
163
- await cortex.consolidation.dedupe({ scopeId: 'global', dryRun: false, threshold });
164
- const active = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 20 });
165
- const archived = cortex.repos.traces.list({ scopeId: 'global', state: 'archived', limit: 20 });
166
- for (const loser of archived) {
167
- const target = active.find((trace) => jaccard(shingles(loser.content), shingles(trace.content)) >= threshold);
168
- assert.ok(target, `归档的 ${loser.title} 必须仍与某条 active 达标相似`);
169
- }
170
- } finally {
171
- cortex.close();
172
- rmSync(dir, { recursive: true, force: true });
173
- }
174
- });
@@ -1,63 +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 seed(cortex, count = 6) {
9
- const now = Date.now();
10
- for (let i = 0; i < count; i += 1) {
11
- cortex.write({ text: `用户:第 ${i} 条待巩固的痕迹,内容各不相同 ${i}。`, kind: 'utterance', title: `巩固样本 ${i}`, explicit: true, now });
12
- }
13
- }
14
-
15
- test('没有 adapter 时记 no-llm-adapter,而不是笼统的 no-llm', async () => {
16
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-no-adapter-'));
17
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
18
- try {
19
- seed(cortex);
20
- const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
21
- assert.equal(result.run.error, 'no-llm-adapter');
22
- } finally {
23
- cortex.close();
24
- rmSync(dir, { recursive: true, force: true });
25
- }
26
- });
27
-
28
- test('adapter 返回空时记 llm-empty,与缺 adapter 区分开', async () => {
29
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-empty-'));
30
- const cortex = createCortex({
31
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') },
32
- llm: { complete: async () => null, available: () => true },
33
- });
34
- try {
35
- seed(cortex);
36
- const result = await cortex.consolidation.run({ scopeId: 'global', force: true });
37
- assert.equal(result.run.error, 'llm-empty');
38
- } finally {
39
- cortex.close();
40
- rmSync(dir, { recursive: true, force: true });
41
- }
42
- });
43
-
44
- test('6 小时内多次 llm-empty 会在健康报告里报 LLM_EMPTY', async () => {
45
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-warn-'));
46
- const cortex = createCortex({
47
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
48
- llm: { complete: async () => null, available: () => true },
49
- });
50
- try {
51
- seed(cortex);
52
- for (let i = 0; i < 6; i += 1) {
53
- await cortex.consolidation.run({ scopeId: 'global', force: true });
54
- }
55
- const health = cortex.health({ scopeId: 'global' });
56
- const warn = health.issues.find((issue) => issue.code === 'LLM_EMPTY');
57
- assert.ok(warn, '多次空返回应被报出来');
58
- assert.equal(warn.detail?.count, 6);
59
- } finally {
60
- cortex.close();
61
- rmSync(dir, { recursive: true, force: true });
62
- }
63
- });
@@ -1,26 +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('without an LLM, consolidation does not record identical skipped runs twice', async () => {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-consolidate-gate-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- try {
12
- cortex.write({ text: '用户:今天想去看海。', kind: 'utterance', title: '今天想去看海', explicit: true });
13
- const first = await cortex.consolidation.run({ scopeId: 'global' });
14
- assert.equal(first.run.status, 'skipped');
15
- assert.equal(first.run.error, 'no-llm-adapter');
16
- const second = await cortex.consolidation.run({ scopeId: 'global' });
17
- assert.equal(second.skipped, 'unchanged', '第二次应识别为未变化并跳过记录');
18
- assert.equal(cortex.consolidation.list({ scopeId: 'global', limit: 10 }).length, 1, '不应多写一行');
19
- const forced = await cortex.consolidation.run({ scopeId: 'global', force: true });
20
- assert.equal(forced.run.status, 'skipped');
21
- assert.equal(cortex.consolidation.list({ scopeId: 'global', limit: 10 }).length, 2, 'force 时仍会记录');
22
- } finally {
23
- cortex.close();
24
- rmSync(dir, { recursive: true, force: true });
25
- }
26
- });
@@ -1,168 +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(complete) {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-preview-'));
10
- const cortex = createCortex({
11
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
12
- llm: { available: () => true, complete },
13
- });
14
- return { dir, cortex };
15
- }
16
-
17
- test('预演不占候选位,同一批真跑时不会被幂等门挡掉', async () => {
18
- let calls = 0;
19
- const { dir, cortex } = setup(async () => {
20
- calls += 1;
21
- return '[]';
22
- });
23
- try {
24
- const now = Date.now();
25
- cortex.write({ text: '用户:低甲碎片。', kind: 'utterance', title: '低甲', importance: 0.3, explicit: true, now });
26
- cortex.write({ text: '用户:低乙碎片。', kind: 'utterance', title: '低乙', importance: 0.35, explicit: true, now: now + 1000 });
27
- cortex.write({ text: '用户:中丙碎片。', kind: 'utterance', title: '中丙', importance: 0.4, explicit: true, now: now + 2000 });
28
- cortex.write({ text: '用户:中丁碎片。', kind: 'utterance', title: '中丁', importance: 0.45, explicit: true, now: now + 3000 });
29
- const preview = await cortex.consolidation.run({ scopeId: 'global', limit: 2, dryRun: true });
30
- assert.equal(calls, 1);
31
- assert.deepEqual(preview.run.input.map((item) => item.title), ['低甲', '低乙']);
32
- const real = await cortex.consolidation.run({ scopeId: 'global', limit: 2 });
33
- assert.equal(calls, 2, '预演过的同一批,真跑时仍应问模型');
34
- assert.notEqual(real.skipped, 'unchanged', '预演行不该让真跑变成 unchanged');
35
- assert.deepEqual(real.run.input.map((item) => item.title), ['低甲', '低乙'], '预演不该把候选挤走');
36
- } finally {
37
- cortex.close();
38
- rmSync(dir, { recursive: true, force: true });
39
- }
40
- });
41
-
42
- test('提示词要求 merge 的 ids 至少两条', async () => {
43
- let seen = '';
44
- const { dir, cortex } = setup(async (options) => {
45
- seen = `${options?.system ?? ''}\n${options?.prompt ?? ''}`;
46
- return '[]';
47
- });
48
- try {
49
- const now = Date.now();
50
- cortex.write({ text: '用户:重复样本甲,今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'utterance', title: '重复甲', importance: 0.6, explicit: true, now });
51
- cortex.write({ text: '用户:重复样本乙,今天在图书馆看了超时空辉夜姬第三集,特别好笑。', kind: 'utterance', title: '重复乙', importance: 0.6, explicit: true, now: now + 1000 });
52
- await cortex.consolidation.run({ scopeId: 'global', force: true });
53
- assert.match(seen, /merge 的 ids 至少两条/);
54
- assert.match(seen, /targetId 必须是 ids 里的一条/);
55
- assert.match(seen, /只带一条 id 的 merge 会被拒绝/);
56
- assert.match(seen, /merge 必须一次给出所有参与合并的 ids/);
57
- } finally {
58
- cortex.close();
59
- rmSync(dir, { recursive: true, force: true });
60
- }
61
- });
62
-
63
- test('dedupe 候选优先低重要度(重复更可能藏在那里)', async () => {
64
- const { dir, cortex } = setup(async () => '[]');
65
- try {
66
- const now = Date.now();
67
- cortex.write({ text: '用户:低一碎片。', kind: 'utterance', title: '低一', importance: 0.3, explicit: true, now });
68
- cortex.write({ text: '用户:低二碎片。', kind: 'utterance', title: '低二', importance: 0.35, explicit: true, now: now + 1000 });
69
- cortex.write({ text: '用户:高三重要。', kind: 'utterance', title: '高三', importance: 0.9, explicit: true, now: now + 2000 });
70
- cortex.write({ text: '用户:高四重要。', kind: 'utterance', title: '高四', importance: 0.95, explicit: true, now: now + 3000 });
71
- cortex.write({ text: '用户:高五重要。', kind: 'utterance', title: '高五', importance: 1.0, explicit: true, now: now + 4000 });
72
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', limit: 2, dryRun: true });
73
- assert.deepEqual(result.run.input.map((item) => item.title), ['低一', '低二']);
74
- } finally {
75
- cortex.close();
76
- rmSync(dir, { recursive: true, force: true });
77
- }
78
- });
79
-
80
- test('没有 LLM 时的 skipped 行不会挡住 LLM 接上后的真跑', async () => {
81
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-preview-nollm-'));
82
- const dbFile = path.join(dir, 'cortex.sqlite');
83
- const now = Date.now();
84
- const first = createCortex({ config: { dataRoot: dir, dbFile } });
85
- try {
86
- first.write({ text: '用户:样本甲。', kind: 'utterance', title: '样本甲', explicit: true, now });
87
- first.write({ text: '用户:样本乙。', kind: 'utterance', title: '样本乙', explicit: true, now: now + 1000 });
88
- first.write({ text: '用户:样本丙。', kind: 'utterance', title: '样本丙', explicit: true, now: now + 2000 });
89
- const skipped = await first.consolidation.run({ scopeId: 'global' });
90
- assert.equal(skipped.run.status, 'skipped');
91
- assert.equal(skipped.run.error, 'no-llm-adapter');
92
- } finally {
93
- first.close();
94
- }
95
- let calls = 0;
96
- const second = createCortex({
97
- config: { dataRoot: dir, dbFile, features: { llm: true } },
98
- llm: { available: () => true, complete: async () => { calls += 1; return '[]'; } },
99
- });
100
- try {
101
- const real = await second.consolidation.run({ scopeId: 'global' });
102
- assert.equal(calls, 1, 'LLM 接上后应真跑,而不是被 skipped 行挡成 unchanged');
103
- assert.notEqual(real.skipped, 'unchanged');
104
- } finally {
105
- second.close();
106
- rmSync(dir, { recursive: true, force: true });
107
- }
108
- });
109
-
110
- test('dedupe 的预演不挡真去重', async () => {
111
- const { dir, cortex } = setup(async () => '[]');
112
- try {
113
- const now = Date.now();
114
- cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,很好笑。', kind: 'utterance', title: '重复甲', importance: 0.6, explicit: true, now });
115
- cortex.write({ text: '用户:今天在图书馆看了超时空辉夜姬第三集,特别好笑。', kind: 'utterance', title: '重复乙', importance: 0.6, explicit: true, now: now + 1000 });
116
- const dry = await cortex.consolidation.dedupe({ scopeId: 'global', threshold: 0.6, dryRun: true });
117
- assert.equal(dry.run.status, 'preview');
118
- const real = await cortex.consolidation.dedupe({ scopeId: 'global', threshold: 0.6, dryRun: false });
119
- assert.notEqual(real.skipped, 'unchanged', '预演不该挡真去重');
120
- assert.ok(real.applied.length >= 1, '真去重应归档一条');
121
- const archived = cortex.db.prepare("SELECT COUNT(*) AS c FROM traces WHERE scope_id = 'global' AND state = 'archived'").get().c;
122
- assert.ok(archived >= 1);
123
- } finally {
124
- cortex.close();
125
- rmSync(dir, { recursive: true, force: true });
126
- }
127
- });
128
-
129
- test('dedupe 的采样能覆盖到高重要度那半', async () => {
130
- const { dir, cortex } = setup(async () => '[]');
131
- try {
132
- const now = Date.now();
133
- for (let i = 0; i < 6; i += 1) {
134
- cortex.write({ text: `用户:低样本 ${i}。`, kind: 'utterance', title: `低${i}`, importance: 0.2 + i * 0.01, explicit: true, now: now + i * 100 });
135
- }
136
- for (let i = 0; i < 6; i += 1) {
137
- cortex.write({ text: `用户:高样本 ${i}。`, kind: 'utterance', title: `高${i}`, importance: 0.9 + i * 0.01, explicit: true, now: now + 1000 + i * 100 });
138
- }
139
- const result = await cortex.consolidation.dedupe({ scopeId: 'global', limit: 4, dryRun: true });
140
- const titles = result.run.input.map((item) => item.title);
141
- assert.equal(titles.length, 4);
142
- assert.ok(titles.some((title) => title.startsWith('高')), '高重要度一半也要被采样到');
143
- assert.ok(titles.some((title) => title.startsWith('低')), '低重要度一半仍优先');
144
- } finally {
145
- cortex.close();
146
- rmSync(dir, { recursive: true, force: true });
147
- }
148
- });
149
-
150
- test('深整理用跨重要度采样,不会整批落在同一档', async () => {
151
- const { dir, cortex } = setup(async () => '[]');
152
- try {
153
- const now = Date.now();
154
- for (let i = 0; i < 8; i += 1) {
155
- cortex.write({ text: `用户:低档痕迹 ${i}。`, kind: 'utterance', title: `低${i}`, importance: 0.2 + i * 0.01, explicit: true, now: now + i * 100 });
156
- }
157
- for (let i = 0; i < 8; i += 1) {
158
- cortex.write({ text: `用户:高档痕迹 ${i}。`, kind: 'utterance', title: `高${i}`, importance: 0.9 + i * 0.01, explicit: true, now: now + 1000 + i * 100 });
159
- }
160
- const result = await cortex.consolidation.run({ scopeId: 'global', spread: true, limit: 8, force: true });
161
- const levels = result.run.input.map((item) => Number(item.importance));
162
- assert.ok(levels.some((value) => value < 0.5), '低档应有一半');
163
- assert.ok(levels.some((value) => value >= 0.9), '高档也应被采样到');
164
- } finally {
165
- cortex.close();
166
- rmSync(dir, { recursive: true, force: true });
167
- }
168
- });