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,93 +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 { createJobRepository } from '../../src/store/repositories/jobs.js';
8
- import { createJobRunner } from '../../src/engines/jobs.js';
9
-
10
- function setup() {
11
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-jobs-'));
12
- const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
13
- migrate(db);
14
- return { dir, db, queue: createJobRepository(db) };
15
- }
16
-
17
- test('jobs are idempotent by operationId and can be claimed/completed', () => {
18
- const { dir, db, queue } = setup();
19
- try {
20
- const first = queue.enqueue({ kind: 'extract', payload: { text: '米饭' }, operationId: 'op-1' });
21
- const replay = queue.enqueue({ kind: 'extract', payload: { text: '米饭' }, operationId: 'op-1' });
22
- assert.equal(replay.id, first.id);
23
- assert.equal(queue.counts().pending, 1);
24
- const claimed = queue.claimNext({ now: Date.now() + 1000 });
25
- assert.equal(claimed.id, first.id);
26
- assert.equal(claimed.status, 'running');
27
- assert.equal(claimed.attempts, 1);
28
- const done = queue.complete(claimed.id, { ok: true });
29
- assert.equal(done.status, 'done');
30
- assert.deepEqual(done.result, { ok: true });
31
- assert.equal(queue.counts().done, 1);
32
- } finally {
33
- closeDatabase(db);
34
- rmSync(dir, { recursive: true, force: true });
35
- }
36
- });
37
-
38
- test('a failed job retries and eventually becomes failed', () => {
39
- const { dir, db, queue } = setup();
40
- try {
41
- const now = Date.now();
42
- // Pin runAfter to the test clock; enqueue() otherwise stamps a slightly
43
- // later wall-clock time and the first claim can be skipped as "not yet due".
44
- const job = queue.enqueue({ kind: 'extract', payload: {}, maxAttempts: 2, runAfter: new Date(now).toISOString() });
45
- const first = queue.claimNext({ now });
46
- const retry = queue.fail(first.id, 'boom', { now, retryAfterMs: 60_000 });
47
- assert.equal(retry.status, 'pending');
48
- assert.ok(retry.runAfter > new Date(now).toISOString());
49
- assert.equal(queue.claimNext({ now }), null);
50
- const second = queue.claimNext({ now: now + 61_000 });
51
- assert.equal(second.id, job.id);
52
- const failed = queue.fail(second.id, 'boom again', { now: now + 61_000 });
53
- assert.equal(failed.status, 'failed');
54
- assert.equal(failed.error, 'boom again');
55
- } finally {
56
- closeDatabase(db);
57
- rmSync(dir, { recursive: true, force: true });
58
- }
59
- });
60
-
61
- test('runner executes a handler and records the result', async () => {
62
- const { dir, db, queue } = setup();
63
- try {
64
- queue.enqueue({ kind: 'echo', payload: { text: '米饭' } });
65
- const runner = createJobRunner({ queue, handlers: { echo: async (payload) => ({ echoed: payload.text }) } });
66
- const result = await runner.runUntilIdle();
67
- assert.equal(result.ran, 1);
68
- assert.equal(result.results[0].ok, true);
69
- assert.equal(queue.list({ status: 'done' })[0].result.echoed, '米饭');
70
- } finally {
71
- closeDatabase(db);
72
- rmSync(dir, { recursive: true, force: true });
73
- }
74
- });
75
-
76
- test('runner marks an exception as a retry/failure', async () => {
77
- const { dir, db, queue } = setup();
78
- try {
79
- queue.enqueue({ kind: 'explode', payload: {}, maxAttempts: 1 });
80
- const runner = createJobRunner({ queue, handlers: { explode: async () => { throw new Error('nope'); } } });
81
- const result = await runner.runOne();
82
- assert.equal(result.ok, false);
83
- assert.equal(queue.list({ status: 'failed' })[0].error, 'nope');
84
- const missing = createJobRunner({ queue });
85
- queue.enqueue({ kind: 'missing', payload: {} });
86
- const missingResult = await missing.runOne();
87
- assert.equal(missingResult.ok, false);
88
- assert.match(missingResult.error, /no handler/);
89
- } finally {
90
- closeDatabase(db);
91
- rmSync(dir, { recursive: true, force: true });
92
- }
93
- });
@@ -1,57 +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 { exportSnapshot, validateSnapshot, importSnapshot } from '../../src/adapters/json.js';
8
-
9
- test('snapshot export validates and imports idempotently', () => {
10
- const sourceDir = mkdtempSync(path.join(os.tmpdir(), 'cortex-json-src-'));
11
- const targetDir = mkdtempSync(path.join(os.tmpdir(), 'cortex-json-dst-'));
12
- const source = createCortex({ config: { dataRoot: sourceDir, dbFile: path.join(sourceDir, 'cortex.sqlite') } });
13
- const target = createCortex({ config: { dataRoot: targetDir, dbFile: path.join(targetDir, 'cortex.sqlite') } });
14
- try {
15
- source.write({ text: '用户说会买米饭。', explicit: true, tags: ['米饭'] });
16
- const snapshot = exportSnapshot(source);
17
- assert.equal(validateSnapshot(snapshot).ok, true);
18
- const dry = importSnapshot(target, snapshot, { dryRun: true });
19
- assert.equal(dry.imported, false);
20
- assert.equal(target.repos.traces.count(), 0);
21
- const imported = importSnapshot(target, snapshot);
22
- assert.equal(imported.imported, true);
23
- assert.equal(imported.traces, 1);
24
- assert.equal(target.repos.traces.count(), 1);
25
- const again = importSnapshot(target, snapshot);
26
- assert.equal(again.items[0].skipped, true);
27
- assert.equal(target.repos.traces.count(), 1);
28
- } finally {
29
- source.close();
30
- target.close();
31
- rmSync(sourceDir, { recursive: true, force: true });
32
- rmSync(targetDir, { recursive: true, force: true });
33
- }
34
- });
35
-
36
- test('invalid snapshots are rejected', () => {
37
- assert.equal(validateSnapshot(null).ok, false);
38
- assert.equal(validateSnapshot({ format: 'other', version: 1 }).ok, false);
39
- assert.equal(validateSnapshot({ format: 'dsh-cortex-snapshot', version: 99, traces: [], facts: [], entities: [] }).ok, false);
40
- });
41
-
42
- test('snapshot export is not silently capped at 500 traces', () => {
43
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-json-cap-'));
44
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
45
- try {
46
- const inputs = Array.from({ length: 501 }, (_, i) => ({ text: `第 ${i} 条记忆。`, explicit: true, operationId: `cap:${i}` }));
47
- cortex.writeMany(inputs, { chunkSize: 200 });
48
- assert.equal(cortex.repos.traces.count(), 501);
49
- const snapshot = exportSnapshot(cortex);
50
- assert.equal(snapshot.traces.length, 501);
51
- const plan = cortex.retention.plan({ maxAgeDays: 3650, minImportance: 0.5 });
52
- assert.equal(plan.active, 501);
53
- } finally {
54
- cortex.close();
55
- rmSync(dir, { recursive: true, force: true });
56
- }
57
- });
@@ -1,18 +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('labelEntities 在缺 adapter 时也返回 no-llm-adapter,与巩固标签一致', async () => {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-label-no-adapter-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- try {
12
- const result = await cortex.labelEntities({ scopeId: 'global' });
13
- assert.equal(result.skipped, 'no-llm-adapter');
14
- } finally {
15
- cortex.close();
16
- rmSync(dir, { recursive: true, force: true });
17
- }
18
- });
@@ -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 { createCortex } from '../../src/service/cortex.js';
7
- import { createLifeEngine } from '../../src/engines/life.js';
8
-
9
- test('sleep runs consolidation when LLM is enabled, and records its status', async () => {
10
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-sleep-consolidate-'));
11
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
12
- try {
13
- let called = 0;
14
- const life = createLifeEngine({
15
- db: cortex.db, traces: cortex.repos.traces, scopeId: 'global',
16
- consolidation: { run: async () => { called += 1; return { run: { status: 'applied' }, applied: [{ id: 'a' }, { id: 'b' }] }; } },
17
- features: { llm: true, consolidateOnSleep: true },
18
- });
19
- const report = await life.sleep({ at: Date.parse('2026-11-11T12:00:00+08:00') });
20
- assert.equal(called, 1);
21
- assert.equal(report.consolidation, 'applied');
22
- assert.equal(report.consolidated, 2);
23
- const again = await createLifeEngine({
24
- db: cortex.db, traces: cortex.repos.traces, scopeId: 'global',
25
- consolidation: { run: async () => { called += 1; } },
26
- features: { llm: false },
27
- }).sleep({ at: Date.parse('2026-11-11T12:01:00+08:00') });
28
- assert.equal(again.consolidation, null);
29
- assert.equal(called, 1);
30
- } finally {
31
- cortex.close();
32
- rmSync(dir, { recursive: true, force: true });
33
- }
34
- });
@@ -1,149 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync } from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { createCortex } from '../../src/service/cortex.js';
7
-
8
- function setup() {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-life-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- return { dir, cortex };
12
- }
13
-
14
- test('diary entries can be written, listed and forgotten', () => {
15
- const { dir, cortex } = setup();
16
- try {
17
- const entry = cortex.life.diaryWrite({ text: '今天把守护模块接上了。', mood: '踏实' });
18
- assert.ok(entry.id);
19
- assert.equal(cortex.life.diaryList()[0].id, entry.id);
20
- assert.equal(cortex.life.diaryForget(entry.id), true);
21
- assert.equal(cortex.life.diaryList().length, 0);
22
- } finally {
23
- cortex.close();
24
- rmSync(dir, { recursive: true, force: true });
25
- }
26
- });
27
-
28
- test('web sources are passed into AI diary generation', async () => {
29
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-diary-web-'));
30
- let seenWeb = '';
31
- const cortex = createCortex({
32
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { webSearch: true } },
33
- llm: {
34
- dream: async () => null,
35
- diary: async (args) => { seenWeb = args.web; return '今天助手从一份外部资料里看见了一点新东西。'; },
36
- feeling: async () => null,
37
- },
38
- webSearch: async () => ({
39
- sources: [{ title: 'Source A', url: 'https://example.com/a', snippet: 'A snippet' }],
40
- }),
41
- });
42
- try {
43
- cortex.write({ text: '今天研究联网日记。', explicit: true, importance: 0.8 });
44
- const entry = await cortex.life.diaryGenerate({ at: Date.parse('2026-11-12T13:00:00+08:00') });
45
- assert.match(seenWeb, /example\.com\/a/);
46
- assert.equal(entry.webSources?.[0]?.url, 'https://example.com/a');
47
- assert.doesNotMatch(entry.text, /https:\/\/example\.com\/a/);
48
- } finally {
49
- cortex.close();
50
- rmSync(dir, { recursive: true, force: true });
51
- }
52
- });
53
-
54
- test('diary generation is written by the configured AI, with a labeled fallback', async () => {
55
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-diary-ai-'));
56
- const cortex = createCortex({
57
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') },
58
- llm: {
59
- dream: async () => null,
60
- diary: async () => '今天助手把检索和梦都重新摸了一遍,心里慢慢安静下来。',
61
- },
62
- });
63
- try {
64
- cortex.write({ text: '今天把日记生成接上。', explicit: true, importance: 0.8 });
65
- const entry = await cortex.life.diaryGenerate({ at: Date.parse('2026-11-12T12:00:00+08:00') });
66
- assert.equal(entry.model, 'llm');
67
- assert.equal(entry.source, 'cortex:llm');
68
- assert.match(entry.text, /助手/);
69
- assert.equal(cortex.life.diaryList()[0].source, 'cortex:llm');
70
- } finally {
71
- cortex.close();
72
- rmSync(dir, { recursive: true, force: true });
73
- }
74
- });
75
-
76
- test('feeling generation records AI-chosen emotion labels and affect', async () => {
77
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-feeling-ai-'));
78
- const cortex = createCortex({
79
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') },
80
- llm: {
81
- dream: async () => null,
82
- diary: async () => null,
83
- feeling: async () => ({
84
- text: '助手现在有一点安心,也有一点期待。',
85
- emotions: [{ name: '安', score: 2 }, { name: '盼', score: 1 }],
86
- target: '用户',
87
- }),
88
- },
89
- });
90
- try {
91
- cortex.write({ text: '今天把自动感受接上了。', explicit: true, importance: 0.8 });
92
- const feeling = await cortex.life.feelingGenerate({ at: Date.parse('2026-11-12T13:00:00+08:00') });
93
- assert.equal(feeling.model, 'llm');
94
- assert.deepEqual(feeling.emotions.map((item) => item.name), ['安', '盼']);
95
- assert.ok(cortex.emotion.events({ limit: 5 }).some((event) => event.text.includes('安心')));
96
- assert.match(cortex.emotion.text(), /安/);
97
- } finally {
98
- cortex.close();
99
- rmSync(dir, { recursive: true, force: true });
100
- }
101
- });
102
-
103
- test('dream generation uses recent memories and falls back to template', async () => {
104
- const { dir, cortex } = setup();
105
- try {
106
- cortex.write({ text: '今天修好了图检索。', explicit: true, importance: 0.9, now: Date.parse('2026-11-11T12:00:00+08:00') });
107
- const dream = await cortex.life.dreamGenerate({ at: Date.parse('2026-11-11T20:00:00+08:00') });
108
- assert.ok(dream.text.length > 0);
109
- assert.equal(dream.model, 'template');
110
- assert.ok(cortex.life.dreamList().length >= 1);
111
- } finally {
112
- cortex.close();
113
- rmSync(dir, { recursive: true, force: true });
114
- }
115
- });
116
-
117
- test('dream generation dedupes identical dreams inside five seconds', async () => {
118
- const { dir, cortex } = setup();
119
- try {
120
- const at = Date.parse('2026-11-11T20:00:00+08:00');
121
- const first = await cortex.life.dreamGenerate({ at });
122
- const second = await cortex.life.dreamGenerate({ at: at + 1000 });
123
- assert.equal(second.id, first.id);
124
- assert.equal(cortex.life.dreamList().length, 1);
125
-
126
- const later = await cortex.life.dreamGenerate({ at: at + 6 * 1000 });
127
- assert.notEqual(later.id, first.id);
128
- assert.equal(cortex.life.dreamList().length, 2);
129
- } finally {
130
- cortex.close();
131
- rmSync(dir, { recursive: true, force: true });
132
- }
133
- });
134
-
135
- test('sleep runs consolidation and records a report', async () => {
136
- const { dir, cortex } = setup();
137
- try {
138
- cortex.write({ text: '第一条记忆。', explicit: true });
139
- cortex.write({ text: '第二条记忆。', explicit: true });
140
- cortex.working.add({ text: '会过期的焦点', ttlMs: 1, at: Date.now() - 1000 });
141
- const report = await cortex.life.sleep({ at: Date.now() });
142
- assert.ok(report.id);
143
- assert.ok(report.purgedWorking >= 1);
144
- assert.ok(cortex.life.sleepRuns().length >= 1);
145
- } finally {
146
- cortex.close();
147
- rmSync(dir, { recursive: true, force: true });
148
- }
149
- });
@@ -1,27 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync } from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { createCortex } from '../../src/service/cortex.js';
7
-
8
- test('llmFacts schedules background extraction and writes validated facts', async () => {
9
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-llm-facts-'));
10
- const cortex = createCortex({
11
- config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llmFacts: true } },
12
- llm: {
13
- available: () => true,
14
- complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"米饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.1}]}',
15
- },
16
- });
17
- try {
18
- cortex.write({ text: '助手喜欢米饭。', explicit: true });
19
- await cortex.flushLlmFacts();
20
- const facts = cortex.repos.facts.list({ scopeId: 'global' });
21
- assert.equal(facts.length, 1);
22
- assert.equal(facts[0].predicate, 'likes');
23
- } finally {
24
- cortex.close();
25
- rmSync(dir, { recursive: true, force: true });
26
- }
27
- });
@@ -1,16 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { extractFactsWithLlm } from '../../src/engines/llm-facts.js';
4
-
5
- test('LLM facts parse strict JSON and drop low-confidence/unsupported items', async () => {
6
- const llm = { complete: async () => '```json\n{"facts":[{"subject":"助手","predicate":"likes","object":"米饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.2}]}\n```' };
7
- const result = await extractFactsWithLlm({ llm, text: '助手喜欢米饭。' });
8
- assert.equal(result.candidates.length, 1);
9
- assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '米饭', confidence: 0.9 });
10
- });
11
-
12
- test('LLM facts fail closed on malformed output or missing model', async () => {
13
- const malformed = { complete: async () => 'not json at all' };
14
- assert.equal((await extractFactsWithLlm({ llm: malformed, text: 'x' })).candidates.length, 0);
15
- assert.equal((await extractFactsWithLlm({ llm: null, text: 'x' })).error, 'llm-unavailable');
16
- });
@@ -1,45 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { createLlmAdapter } from '../../src/llm/adapter.js';
4
-
5
- function mockCtx(text = '梦里,助手坐在米饭旁边。') {
6
- return {
7
- get(name) {
8
- if (name === 'llm') {
9
- return {
10
- async *stream() { yield { type: 'text-delta', text }; },
11
- };
12
- }
13
- if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'test', model: 'test-model' }) };
14
- if (name === 'agents') return { currentInitiator: () => ({ session: { id: 's1' } }) };
15
- return null;
16
- },
17
- };
18
- }
19
-
20
- test('llm adapter completes, dreams and summarizes through the host service', async () => {
21
- const adapter = createLlmAdapter({ ctx: mockCtx() });
22
- assert.equal(adapter.available(), true);
23
- const text = await adapter.complete({ system: 's', prompt: 'p' });
24
- assert.match(text, /米饭/);
25
- const dream = await adapter.dream({ pieces: ['米饭'], emotions: '暖' });
26
- assert.match(dream, /米饭/);
27
- const summary = await adapter.summarize({ text: '一段很长的记忆' });
28
- assert.match(summary, /米饭/);
29
- });
30
-
31
- test('llm adapter fails open when the service is missing or errors', async () => {
32
- const missing = createLlmAdapter({ ctx: { get: () => null } });
33
- assert.equal(missing.available(), false);
34
- assert.equal(await missing.complete({ prompt: 'x' }), null);
35
- const broken = createLlmAdapter({
36
- ctx: {
37
- get(name) {
38
- if (name === 'llm') return { async *stream() { throw new Error('boom'); } };
39
- if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'p', model: 'm' }) };
40
- return null;
41
- },
42
- },
43
- });
44
- assert.equal(await broken.complete({ prompt: 'x' }), null);
45
- });
@@ -1,45 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync } from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { createCortex } from '../../src/service/cortex.js';
7
- import { buildLoCoMoIndex, evaluateLoCoMoRetrieval } from '../../bench/locomo.js';
8
-
9
- const sample = {
10
- sample_id: 'conv-1',
11
- conversation: {
12
- speaker_a: 'A',
13
- speaker_b: 'B',
14
- session_1_date_time: '2026-11-01T10:00:00+08:00',
15
- session_1: [
16
- { speaker: 'A', text: '我喜欢米饭。' },
17
- { speaker: 'B', text: '那很好。' },
18
- ],
19
- session_2_date_time: '2026-11-02T10:00:00+08:00',
20
- session_2: [
21
- { speaker: 'A', text: '今天修了插件。' },
22
- ],
23
- },
24
- qa: [
25
- { question: 'A 喜欢什么?', answer: '米饭', evidence: ['D1:1'], category: 1 },
26
- { question: '不存在的事是什么?', answer: '没有', evidence: [], category: 5 },
27
- ],
28
- };
29
-
30
- test('LoCoMo adapter maps evidence turns to trace relevance', async () => {
31
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-locomo-'));
32
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
33
- try {
34
- const built = buildLoCoMoIndex({ cortex, samples: [sample] });
35
- assert.equal(built.traces, 3);
36
- assert.equal(built.queries.length, 2);
37
- assert.equal(built.queries[0].relevant.length, 1);
38
- const result = await evaluateLoCoMoRetrieval({ cortex, samples: [sample], limit: 5 });
39
- assert.equal(result.built.evaluated, 1);
40
- assert.ok(result.recallAtK >= 0 && result.recallAtK <= 1);
41
- } finally {
42
- cortex.close();
43
- rmSync(dir, { recursive: true, force: true });
44
- }
45
- });
@@ -1,56 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtempSync, rmSync } from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { createCortex } from '../../src/service/cortex.js';
7
- import { buildLongMemEvalIndex, evaluateLongMemEvalRetrieval, instanceType } from '../../bench/longmemeval.js';
8
-
9
- const fixture = [
10
- {
11
- question_id: 'q1',
12
- question_type: 'single-session-user',
13
- question: '用户喜欢什么主食?',
14
- answer: '米饭',
15
- question_date: '2026-11-11T12:00:00+08:00',
16
- haystack_session_ids: ['s1', 's2'],
17
- haystack_dates: ['2026-11-01T12:00:00+08:00', '2026-11-02T12:00:00+08:00'],
18
- haystack_sessions: [
19
- [{ role: 'user', content: '用户最喜欢米饭。', has_answer: true }],
20
- [{ role: 'user', content: '今天修插件。' }],
21
- ],
22
- answer_session_ids: ['s1'],
23
- },
24
- {
25
- question_id: 'q2_abs',
26
- question_type: 'temporal-reasoning',
27
- question: '不存在的约定是哪天?',
28
- answer: '没有',
29
- question_date: '2026-11-11T12:00:00+08:00',
30
- haystack_session_ids: ['s3'],
31
- haystack_dates: ['2026-11-03T12:00:00+08:00'],
32
- haystack_sessions: [[{ role: 'user', content: '没有这件事。' }]],
33
- answer_session_ids: [],
34
- },
35
- ];
36
-
37
- test('LongMemEval adapter builds traces and query relevance', () => {
38
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-lme-'));
39
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
40
- try {
41
- const built = buildLongMemEvalIndex({ cortex, instances: fixture });
42
- assert.equal(built.traces, 3);
43
- assert.equal(built.queries.length, 2);
44
- const q1 = built.queries.find((query) => query.id === 'q1');
45
- assert.equal(q1.relevant.length, 1);
46
- assert.equal(q1.abstention, false);
47
- assert.equal(instanceType(fixture[1]), 'abstention');
48
- const result = evaluateLongMemEvalRetrieval({ cortex, instances: fixture, limit: 5 });
49
- assert.equal(result.built.evaluated, 1);
50
- assert.ok(result.recallAtK >= 0);
51
- assert.ok(result.recallAtK <= 1);
52
- } finally {
53
- cortex.close();
54
- rmSync(dir, { recursive: true, force: true });
55
- }
56
- });
@@ -1,62 +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-dispute-'));
10
- const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
- return { dir, cortex };
12
- }
13
-
14
- function seedDispute(cortex, now) {
15
- const subject = cortex.repos.entities.upsert({ scopeId: 'global', name: '小明' });
16
- const early = cortex.repos.entities.upsert({ scopeId: 'global', name: '程序员' });
17
- const later = cortex.repos.entities.upsert({ scopeId: 'global', name: '设计师' });
18
- const at = new Date(now).toISOString();
19
- cortex.repos.facts.resolve({ scopeId: 'global', subjectId: subject.id, predicate: 'is', objectId: early.id, validFrom: at, recordedAt: at });
20
- const second = cortex.repos.facts.resolve({ scopeId: 'global', subjectId: subject.id, predicate: 'is', objectId: later.id, validFrom: at, recordedAt: at });
21
- assert.equal(second.action, 'dispute');
22
- return { subject, disputeId: second.dispute.id };
23
- }
24
-
25
- const statusesOf = (cortex, subjectId) =>
26
- cortex.db.prepare("SELECT status FROM facts WHERE subject_id = ? AND predicate = 'is'").all(subjectId)
27
- .map((row) => row.status).sort();
28
-
29
- test('双方都还是 disputed 的争议不会被误标 resolved', () => {
30
- const { dir, cortex } = setup();
31
- try {
32
- const now = Date.now();
33
- const { subject, disputeId } = seedDispute(cortex, now);
34
- assert.deepEqual(statusesOf(cortex, subject.id), ['disputed', 'disputed']);
35
- cortex.maintain({ now: now + 1000 });
36
- const dispute = cortex.db.prepare('SELECT status FROM disputes WHERE id = ?').get(disputeId);
37
- assert.equal(dispute.status, 'open', 'disputed 不等于失效,争议不能自动结案');
38
- assert.deepEqual(statusesOf(cortex, subject.id), ['disputed', 'disputed'], '两边都还 disputed 时不能动');
39
- } finally {
40
- cortex.close();
41
- rmSync(dir, { recursive: true, force: true });
42
- }
43
- });
44
-
45
- test('争议被关掉后留下的孤儿 disputed 事实会被清成 invalidated', () => {
46
- const { dir, cortex } = setup();
47
- try {
48
- const now = Date.now();
49
- const { subject, disputeId } = seedDispute(cortex, now);
50
- // 模拟旧版本留下的状态:争议已经 resolved,facts 还挂着 disputed。
51
- cortex.db.prepare("UPDATE disputes SET status = 'resolved', resolved_at = ?, resolution = 'auto: both facts invalidated' WHERE id = ?")
52
- .run(new Date(now + 1).toISOString(), disputeId);
53
- const report = cortex.maintain({ now: now + 2000 });
54
- assert.ok(report.orphanDisputes >= 2, '两条孤儿 disputed 都要清');
55
- assert.deepEqual(statusesOf(cortex, subject.id), ['invalidated', 'invalidated']);
56
- const health = cortex.health({ scopeId: 'global' });
57
- assert.equal(health.issues.find((issue) => issue.code === 'DISPUTED_FACTS'), undefined);
58
- } finally {
59
- cortex.close();
60
- rmSync(dir, { recursive: true, force: true });
61
- }
62
- });