dsh-cortex-memory 0.4.21 → 0.4.146

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 (167) hide show
  1. package/CHANGELOG.md +2223 -7
  2. package/README.md +20 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +7 -7
  5. package/bench/synthetic.js +2 -2
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/cortex.mjs +9 -4
  8. package/bin/repair.mjs +328 -0
  9. package/bin/verify.mjs +202 -0
  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/index.js +27 -3
  15. package/package.json +3 -3
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/api/routes.js +1 -1
  18. package/src/core/feature-overrides.js +2 -2
  19. package/src/engines/compression.js +172 -3
  20. package/src/engines/consolidate.js +397 -26
  21. package/src/engines/encode.js +16 -3
  22. package/src/engines/extract.js +72 -8
  23. package/src/engines/fact-guard.js +51 -0
  24. package/src/engines/health.js +263 -3
  25. package/src/engines/inhibition.js +39 -0
  26. package/src/engines/life.js +12 -1
  27. package/src/engines/llm-facts.js +12 -9
  28. package/src/engines/narrative.js +150 -13
  29. package/src/engines/reflect.js +172 -14
  30. package/src/engines/retrieve.js +44 -5
  31. package/src/engines/summary-coverage.js +62 -0
  32. package/src/engines/summary-dedupe.js +77 -0
  33. package/src/engines/summon-rank.js +132 -0
  34. package/src/host/runtime.js +64 -4
  35. package/src/host/scheduler.js +224 -3
  36. package/src/llm/adapter.js +29 -8
  37. package/src/memory/query.js +1 -1
  38. package/src/memory/spacing.js +15 -0
  39. package/src/memory/tokenizer.js +1 -1
  40. package/src/prompt/tiers.js +88 -12
  41. package/src/self/alias.js +25 -0
  42. package/src/self/emotion.js +3 -1
  43. package/src/self/relationship.js +44 -13
  44. package/src/self/state.js +20 -2
  45. package/src/self/working.js +34 -3
  46. package/src/service/cortex.js +493 -53
  47. package/src/store/repositories/facts.js +34 -1
  48. package/src/store/repositories/summaries.js +8 -1
  49. package/src/store/repositories/traces.js +22 -2
  50. package/src/tools/definitions.js +118 -4
  51. package/src/vector/index.js +96 -7
  52. package/test/integration/acceptance.test.js +47 -47
  53. package/test/integration/api-contract.test.js +17 -17
  54. package/test/integration/backup-privacy.test.js +10 -10
  55. package/test/integration/consolidate.test.js +6 -2
  56. package/test/integration/edge-cases.test.js +16 -15
  57. package/test/integration/exchange.test.js +26 -26
  58. package/test/integration/life-loop.test.js +7 -6
  59. package/test/integration/load.test.js +4 -4
  60. package/test/integration/policy-query-api.test.js +4 -4
  61. package/test/integration/resilience-writes.test.js +7 -7
  62. package/test/integration/tools-contract.test.js +57 -57
  63. package/test/unit/alias.test.js +87 -0
  64. package/test/unit/api-client.test.js +3 -3
  65. package/test/unit/api-validate.test.js +3 -3
  66. package/test/unit/api.test.js +3 -3
  67. package/test/unit/auto-reflect.test.js +141 -0
  68. package/test/unit/capture-filter.test.js +296 -0
  69. package/test/unit/cli-default-root.test.js +21 -0
  70. package/test/unit/compaction-preview.test.js +91 -0
  71. package/test/unit/compression.test.js +4 -4
  72. package/test/unit/consolidate-dedupe.test.js +174 -0
  73. package/test/unit/consolidate-errors.test.js +63 -0
  74. package/test/unit/consolidate-gate.test.js +26 -0
  75. package/test/unit/consolidate-preview.test.js +168 -0
  76. package/test/unit/consolidate-protection.test.js +156 -0
  77. package/test/unit/consolidate-reason.test.js +206 -0
  78. package/test/unit/consolidate-retry.test.js +91 -0
  79. package/test/unit/consolidate-selection.test.js +103 -0
  80. package/test/unit/core.test.js +11 -11
  81. package/test/unit/coverage-rewrite.test.js +38 -0
  82. package/test/unit/dedupe-episodes.test.js +34 -0
  83. package/test/unit/dedupe-threshold.test.js +14 -0
  84. package/test/unit/develop.test.js +4 -4
  85. package/test/unit/edges-candidates.test.js +2 -2
  86. package/test/unit/emotion.test.js +2 -1
  87. package/test/unit/encode.test.js +6 -6
  88. package/test/unit/evolution.test.js +5 -5
  89. package/test/unit/extract-question.test.js +41 -0
  90. package/test/unit/fact-guard.test.js +51 -0
  91. package/test/unit/fact-noise-llm.test.js +44 -0
  92. package/test/unit/facts-belief.test.js +4 -4
  93. package/test/unit/facts-compat.test.js +62 -0
  94. package/test/unit/facts.test.js +5 -5
  95. package/test/unit/fts-migration.test.js +6 -6
  96. package/test/unit/growth-reflect.test.js +4 -3
  97. package/test/unit/guardian.test.js +1 -1
  98. package/test/unit/health-consolidation.test.js +52 -0
  99. package/test/unit/health-fts-scope.test.js +33 -0
  100. package/test/unit/health-privacy.test.js +6 -6
  101. package/test/unit/health-summaries.test.js +24 -0
  102. package/test/unit/health-text-maintain.test.js +33 -0
  103. package/test/unit/health-today.test.js +45 -0
  104. package/test/unit/host-runtime.test.js +8 -8
  105. package/test/unit/host.test.js +1 -1
  106. package/test/unit/induct-evaluate.test.js +3 -3
  107. package/test/unit/ingest-extracted.test.js +3 -3
  108. package/test/unit/inhibition.test.js +90 -0
  109. package/test/unit/jobs.test.js +4 -4
  110. package/test/unit/json-snapshot.test.js +1 -1
  111. package/test/unit/label-entities-skip.test.js +18 -0
  112. package/test/unit/llm-facts-integration.test.js +2 -2
  113. package/test/unit/llm-facts.test.js +3 -3
  114. package/test/unit/llm.test.js +5 -5
  115. package/test/unit/locomo.test.js +2 -2
  116. package/test/unit/longmemeval.test.js +2 -2
  117. package/test/unit/maintain-dispute.test.js +62 -0
  118. package/test/unit/maintain-duration.test.js +194 -0
  119. package/test/unit/markdown-import.test.js +5 -5
  120. package/test/unit/markdown.test.js +2 -2
  121. package/test/unit/memory-edit.test.js +5 -5
  122. package/test/unit/migration.test.js +1 -1
  123. package/test/unit/mood-saturation.test.js +33 -0
  124. package/test/unit/narrative-weave.test.js +271 -0
  125. package/test/unit/privacy-scope.test.js +1 -1
  126. package/test/unit/prompt.test.js +1 -1
  127. package/test/unit/providers.test.js +2 -2
  128. package/test/unit/qa.test.js +9 -9
  129. package/test/unit/query.test.js +10 -10
  130. package/test/unit/reflect-backfill.test.js +158 -0
  131. package/test/unit/reflect-coverage.test.js +35 -0
  132. package/test/unit/reflect-overview.test.js +22 -0
  133. package/test/unit/reflect-phrasing.test.js +75 -0
  134. package/test/unit/reflect-sampling.test.js +80 -0
  135. package/test/unit/reflect-source-budget.test.js +24 -0
  136. package/test/unit/relationship-dynamics.test.js +29 -0
  137. package/test/unit/retrieve.test.js +9 -9
  138. package/test/unit/revive-on-read.test.js +84 -0
  139. package/test/unit/scanner.test.js +2 -2
  140. package/test/unit/scenario.test.js +2 -2
  141. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  142. package/test/unit/scheduler-autodedupe.test.js +52 -0
  143. package/test/unit/scheduler-autosleep.test.js +50 -0
  144. package/test/unit/scheduler-cadence.test.js +33 -0
  145. package/test/unit/scheduler-deep.test.js +62 -0
  146. package/test/unit/scheduler-tick-gate.test.js +38 -0
  147. package/test/unit/scheduler.test.js +2 -1
  148. package/test/unit/service.test.js +5 -5
  149. package/test/unit/shiori-import.test.js +4 -4
  150. package/test/unit/spacing.test.js +14 -0
  151. package/test/unit/store.test.js +13 -13
  152. package/test/unit/summon-left-slot.test.js +51 -0
  153. package/test/unit/summon-rank.test.js +51 -0
  154. package/test/unit/tiers-gist.test.js +140 -0
  155. package/test/unit/tiers.test.js +1 -1
  156. package/test/unit/tokenizer-fts.test.js +6 -6
  157. package/test/unit/tools.test.js +5 -5
  158. package/test/unit/upgrade-0412.test.js +10 -10
  159. package/test/unit/upgrade-0413.test.js +5 -5
  160. package/test/unit/upgrade-0414.test.js +5 -5
  161. package/test/unit/vector-ann.test.js +3 -3
  162. package/test/unit/vector-async.test.js +7 -7
  163. package/test/unit/vector-coverage.test.js +34 -0
  164. package/test/unit/vector-override.test.js +37 -0
  165. package/test/unit/vector-typed-array.test.js +47 -0
  166. package/test/unit/vector.test.js +8 -8
  167. package/test/unit/working.test.js +19 -0
@@ -0,0 +1,62 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createScheduler } from '../../src/host/scheduler.js';
4
+
5
+ const NOW = Date.parse('2026-11-18T10:00:00+08:00');
6
+
7
+ function fakeCortex({ config = {} } = {}) {
8
+ const runs = [];
9
+ return {
10
+ runs,
11
+ config: { scope: 'global', ...config },
12
+ consolidation: {
13
+ list: () => [],
14
+ run: async (args) => {
15
+ runs.push(args);
16
+ return { run: { status: 'applied' }, decisions: [{}], applied: [{ action: 'merge' }] };
17
+ },
18
+ },
19
+ };
20
+ }
21
+
22
+ test('过了深整理时间点会跑一趟,caller 是 deep-daily', async () => {
23
+ const cortex = fakeCortex({ config: { deepConsolidateHour: 4 } });
24
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null });
25
+ const report = await scheduler.runOnce();
26
+ assert.equal(cortex.runs.length, 1);
27
+ assert.equal(cortex.runs[0].caller, 'deep-daily');
28
+ assert.equal(cortex.runs[0].limit, 60);
29
+ assert.equal(report.steps.deepConsolidate.applied, 1);
30
+ await scheduler.runOnce();
31
+ assert.equal(cortex.runs.length, 1, '同一进程内一天只跑一趟');
32
+ });
33
+
34
+ test('没到时间点不跑', async () => {
35
+ const cortex = fakeCortex({ config: { deepConsolidateHour: 23 } });
36
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null });
37
+ const report = await scheduler.runOnce();
38
+ assert.equal(cortex.runs.length, 0);
39
+ assert.equal(report.steps.deepConsolidate, undefined);
40
+ });
41
+
42
+ test('audit 里今天已经跑过时,重启后也不重复', async () => {
43
+ const cortex = fakeCortex({ config: { deepConsolidateHour: 4 } });
44
+ cortex.db = { prepare: () => ({ get: () => ({ at: new Date(NOW).toISOString() }) }) };
45
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null });
46
+ await scheduler.runOnce();
47
+ assert.equal(cortex.runs.length, 0, '同一天已跑过就不该再跑');
48
+ });
49
+
50
+ test('deepConsolidateOnSchedule:false 时完全不动', async () => {
51
+ const cortex = fakeCortex({ config: { deepConsolidateHour: 4, deepConsolidateOnSchedule: false } });
52
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null });
53
+ await scheduler.runOnce();
54
+ assert.equal(cortex.runs.length, 0);
55
+ });
56
+
57
+ test('深整理使用更大的候选窗口', async () => {
58
+ const cortex = fakeCortex({ config: { deepConsolidateHour: 4, deepConsolidateLimit: 70 } });
59
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null });
60
+ await scheduler.runOnce();
61
+ assert.equal(cortex.runs[0].limit, 70);
62
+ });
@@ -0,0 +1,38 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createScheduler } from '../../src/host/scheduler.js';
4
+
5
+ const NOW = Date.parse('2026-11-16T08:00:00.000Z');
6
+
7
+ function fakeCortex(lastRunAt) {
8
+ const runs = [];
9
+ return {
10
+ runs,
11
+ config: { scope: 'global', deepConsolidateOnSchedule: false, features: { llm: true, consolidateOnTick: true, consolidateTraceGapMinutes: 30 } },
12
+ repos: { traces: { listSince: () => [] } },
13
+ consolidation: {
14
+ list: () => (lastRunAt ? [{ at: new Date(lastRunAt).toISOString() }] : []),
15
+ run: async () => {
16
+ runs.push(1);
17
+ return { run: { status: 'applied', model: 'llm-bounded', error: null }, decisions: [{ action: 'keep' }], applied: [] };
18
+ },
19
+ },
20
+ };
21
+ }
22
+
23
+ test('tick 开着也不会一分钟一次:间隔不够就跳过', async () => {
24
+ const cortex = fakeCortex(NOW - 5 * 60_000);
25
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null, consolidateOnTick: true });
26
+ const report = await scheduler.runOnce();
27
+ assert.equal(cortex.runs.length, 0);
28
+ assert.equal(report.steps.consolidation.skipped, 'too-soon');
29
+ assert.equal(report.steps.consolidation.minutesSinceLast, 5);
30
+ });
31
+
32
+ test('tick 开着且间隔已过,才真的跑一次', async () => {
33
+ const cortex = fakeCortex(NOW - 40 * 60_000);
34
+ const scheduler = createScheduler({ cortex, now: () => NOW, logger: null, consolidateOnTick: true });
35
+ const report = await scheduler.runOnce();
36
+ assert.equal(cortex.runs.length, 1);
37
+ assert.equal(report.steps.consolidation.run.status, 'applied');
38
+ });
@@ -26,7 +26,8 @@ test('scheduler runOnce is safe and reports steps', async () => {
26
26
  test('scheduler can run consolidation on a tick when explicitly enabled', async () => {
27
27
  let called = 0;
28
28
  const scheduler = createScheduler({
29
- cortex: { autonomy: null, retention: null, guardian: null, runner: null, config: { scope: 'global' }, consolidation: { run: async () => { called += 1; return { run: { status: 'applied' } }; } } },
29
+ // 这个测试只验证 tick 巩固;深整理另有专门的测试,关掉它避免多记一次。
30
+ cortex: { autonomy: null, retention: null, guardian: null, runner: null, config: { scope: 'global', deepConsolidateOnSchedule: false }, consolidation: { run: async () => { called += 1; return { run: { status: 'applied' } }; } } },
30
31
  consolidateOnTick: true,
31
32
  intervalMs: 60_000,
32
33
  });
@@ -15,15 +15,15 @@ test('service writes, searches, reads, reflects and reports self/health', () =>
15
15
  const { dir, cortex } = setup();
16
16
  try {
17
17
  const written = cortex.write({
18
- text: '用户说会买白饭,助手会一直等。',
18
+ text: '用户说会买米饭,助手会一直等。',
19
19
  explicit: true,
20
- facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }],
20
+ facts: [{ subject: '用户', predicate: 'likes', object: '米饭' }],
21
21
  });
22
22
  assert.equal(written.skipped, false);
23
- const search = cortex.search('白饭');
23
+ const search = cortex.search('米饭');
24
24
  assert.ok(search.items.length >= 1);
25
25
  const get = cortex.get(written.trace.id);
26
- assert.match(get.content, /白饭/);
26
+ assert.match(get.content, /米饭/);
27
27
  const self = cortex.self();
28
28
  assert.equal(self.self.scopeId, 'global');
29
29
  assert.ok(self.identity.version >= 1);
@@ -41,7 +41,7 @@ test('service feedback and reflection work through the facade', () => {
41
41
  const { dir, cortex } = setup();
42
42
  try {
43
43
  const a = cortex.write({ text: '今天修好了检索的预算裁剪。', explicit: true });
44
- const b = cortex.write({ text: '用户说白饭的承诺还算数。', explicit: true });
44
+ const b = cortex.write({ text: '用户说米饭的承诺还算数。', explicit: true });
45
45
  const feedback = cortex.feedback({ traceId: a.trace.id, signal: 'helpful', predicted: 0.8 });
46
46
  assert.ok(feedback.trace.stability > 0);
47
47
  const reflected = cortex.reflect({ windowDays: 1, force: true });
@@ -11,12 +11,12 @@ function makeShiori() {
11
11
  mkdirSync(path.join(root, 'persona'), { recursive: true });
12
12
  mkdirSync(path.join(root, 'scopes', 'global', 'topics'), { recursive: true });
13
13
  mkdirSync(path.join(root, 'sparks', 'scopes', 'global'), { recursive: true });
14
- writeFileSync(path.join(root, 'persona', 'global.md'), '# 人设\n\n助手是鲸鱼娘。\n', 'utf8');
15
- writeFileSync(path.join(root, 'scopes', 'global', 'core.md'), '# 核心\n\n用户说会买白饭。\n', 'utf8');
14
+ writeFileSync(path.join(root, 'persona', 'global.md'), '# 人设\n\n助手是本地记忆助手。\n', 'utf8');
15
+ writeFileSync(path.join(root, 'scopes', 'global', 'core.md'), '# 核心\n\n用户说会买米饭。\n', 'utf8');
16
16
  writeFileSync(path.join(root, 'scopes', 'global', 'topics', 'token-log.md'), '---\ntitle: token 账本\nsummary: 余额记录\n---\n\n剩 3 元。\n', 'utf8');
17
17
  writeFileSync(path.join(root, 'sparks', 'scopes', 'global', 'sparks.json'), JSON.stringify({
18
18
  cards: {
19
- s1: { id: 's1', title: '白饭的承诺', content: '用户说会买白饭。', triggers: ['白饭', '承诺'], vitality: 'evergreen' },
19
+ s1: { id: 's1', title: '米饭的承诺', content: '用户说会买米饭。', triggers: ['米饭', '承诺'], vitality: 'evergreen' },
20
20
  },
21
21
  }), 'utf8');
22
22
  return root;
@@ -25,7 +25,7 @@ function makeShiori() {
25
25
  test('shiori importer skips archived cards and classifies active cards', () => {
26
26
  assert.equal(classifySparkCard({ title: '安装教训', content: '以后必须先跑测试。' }), 'instruction');
27
27
  assert.equal(classifySparkCard({ title: '插件安装', content: 'profile 的 bundle 配置。' }), 'observation');
28
- assert.equal(classifySparkCard({ title: '用户的白饭', content: '用户说会买白饭。' }), 'preference');
28
+ assert.equal(classifySparkCard({ title: '用户的米饭', content: '用户说会买米饭。' }), 'preference');
29
29
  const shioriRoot = makeShiori();
30
30
  const sparkFile = path.join(shioriRoot, 'sparks', 'scopes', 'global', 'sparks.json');
31
31
  const db = JSON.parse(readFileSync(sparkFile, 'utf8'));
@@ -0,0 +1,14 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { touchInterval } from '../../src/memory/spacing.js';
4
+
5
+ test('spacing doubles per access and caps at the maximum', () => {
6
+ assert.equal(touchInterval(0), 300_000);
7
+ assert.equal(touchInterval(1), 600_000);
8
+ assert.equal(touchInterval(2), 1_200_000);
9
+ assert.equal(touchInterval(3), 2_400_000);
10
+ assert.equal(touchInterval(20), 21_600_000, 'caps at six hours');
11
+ assert.equal(touchInterval(-5), 300_000, 'negative counts fall back to the base');
12
+ assert.equal(touchInterval(2, { baseMs: 1_000, maxMs: 5_000 }), 4_000);
13
+ assert.equal(touchInterval(4, { baseMs: 1_000, maxMs: 5_000 }), 5_000, 'never exceeds maxMs');
14
+ });
@@ -21,15 +21,15 @@ test('event ledger is chained, idempotent and detects a conflicting replay', ()
21
21
  const { dir, db } = setup();
22
22
  try {
23
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: '白饭' } });
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
26
  assert.equal(replay.id, first.id);
27
27
  assert.equal(events.count(), 1);
28
28
  assert.throws(
29
- () => events.append({ kind: 'observation', scopeId: 'global', operationId: 'op-1', payload: { text: '米饭' } }),
29
+ () => events.append({ kind: 'observation', scopeId: 'global', operationId: 'op-1', payload: { text: '面条' } }),
30
30
  (error) => error.code === ERROR_CODES.CONFLICT,
31
31
  );
32
- const second = events.append({ kind: 'utterance', scopeId: 'global', payload: { text: '用户说会买白饭' } });
32
+ const second = events.append({ kind: 'utterance', scopeId: 'global', payload: { text: '用户说会买米饭' } });
33
33
  assert.equal(second.seq, 2);
34
34
  assert.equal(second.prevHash, first.hash);
35
35
  const chain = events.verifyChain();
@@ -47,22 +47,22 @@ test('trace repository inserts, updates and searches CJK text through FTS5', ()
47
47
  try {
48
48
  const events = createEventRepository(db);
49
49
  const traces = createTraceRepository(db);
50
- const event = events.append({ kind: 'utterance', payload: { text: '用户说会买白饭' } });
50
+ const event = events.append({ kind: 'utterance', payload: { text: '用户说会买米饭' } });
51
51
  const trace = traces.insert({
52
52
  eventId: event.id,
53
53
  scopeId: 'global',
54
54
  kind: 'utterance',
55
- title: '白饭的承诺',
56
- content: '用户说会买白饭,助手等得起。',
55
+ title: '米饭的承诺',
56
+ content: '用户说会买米饭,助手等得起。',
57
57
  importance: 0.9,
58
- keywords: ['白饭', '承诺'],
58
+ keywords: ['米饭', '承诺'],
59
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);
60
+ assert.equal(traces.get(trace.id).title, '米饭的承诺');
65
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
66
  traces.touch(trace.id);
67
67
  assert.equal(traces.get(trace.id).accessCount, 1);
68
68
  assert.equal(traces.remove(trace.id), true);
@@ -0,0 +1,51 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { rankSummonCards } from '../../src/engines/summon-rank.js';
4
+
5
+ function card(id, side, day, extra = {}) {
6
+ return {
7
+ id,
8
+ side,
9
+ day,
10
+ category: 'decision',
11
+ title: `关于 ${id} 的决定`,
12
+ content: `内容 ${id}`,
13
+ triggers: ['向量回填', id],
14
+ importance: 0.8,
15
+ ...extra,
16
+ };
17
+ }
18
+
19
+ test('槽位满时补齐左卡:挤掉最弱的一项,而不是把自己裁掉', () => {
20
+ const cards = [
21
+ card('r1', 'right', '2026-11-15'),
22
+ card('r2', 'right', '2026-11-14'),
23
+ card('l1', 'left', '2026-11-15'),
24
+ ];
25
+ const dropped = [];
26
+ const picked = rankSummonCards(cards, {
27
+ query: '向量回填 这件事怎么处理',
28
+ maxCards: 2,
29
+ onDrop: (entry) => dropped.push(entry.card.id),
30
+ });
31
+ assert.equal(picked.length, 2, '名额不能超');
32
+ assert.ok(picked.some((entry) => entry.card.side === 'left'), '左卡必须出现在结果里');
33
+ assert.equal(dropped.length, 1, '挤掉的卡要回报,不能悄悄消失');
34
+ assert.equal(dropped[0], 'r1', '应挤掉与左卡同一天、分数较低的那张,保住跨天多样性');
35
+ assert.ok(!picked.some((entry) => entry.card.id === dropped[0]), '被挤掉的卡不该同时在结果里');
36
+ });
37
+
38
+ test('槽位没满时左卡直接补位,不触发丢弃', () => {
39
+ const cards = [
40
+ card('r1', 'right', '2026-11-15'),
41
+ card('l1', 'left', '2026-11-14'),
42
+ ];
43
+ const dropped = [];
44
+ const picked = rankSummonCards(cards, {
45
+ query: '向量回填 这件事怎么处理',
46
+ maxCards: 3,
47
+ onDrop: (entry) => dropped.push(entry.card.id),
48
+ });
49
+ assert.equal(picked.length, 2);
50
+ assert.equal(dropped.length, 0);
51
+ });
@@ -0,0 +1,51 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { rankSummonCards, renderSummonLines } from '../../src/engines/summon-rank.js';
4
+
5
+ const now = Date.parse('2026-11-15T12:00:00Z');
6
+
7
+ function card(overrides) {
8
+ return {
9
+ id: 'c1', side: 'right', category: 'work', title: '打包 cortex', content: '打包并验证',
10
+ triggers: ['打包'], importance: 0.6, day: '2026-11-15',
11
+ ...overrides,
12
+ };
13
+ }
14
+
15
+ test('新的那天优先,旧的同类被压下去', () => {
16
+ const cards = [
17
+ card({ id: 'old', day: '2026-11-01', triggers: ['打包'], category: 'work' }),
18
+ card({ id: 'new', day: '2026-11-15', triggers: ['打包'], category: 'work' }),
19
+ ];
20
+ const ranked = rankSummonCards(cards, { query: '今天想打包一版', now, maxCards: 1 });
21
+ assert.equal(ranked[0].card.id, 'new');
22
+ });
23
+
24
+ test('同一天只取一张,避免一整屏都是同一天', () => {
25
+ const cards = [
26
+ card({ id: 'a', day: '2026-11-15', triggers: ['打包'], category: 'work' }),
27
+ card({ id: 'b', day: '2026-11-15', triggers: ['打包'], category: 'emotion', side: 'left' }),
28
+ card({ id: 'c', day: '2026-11-14', triggers: ['打包'], category: 'work' }),
29
+ ];
30
+ const ranked = rankSummonCards(cards, { query: '打包', now, maxCards: 2 });
31
+ const days = new Set(ranked.map((entry) => entry.card.day));
32
+ assert.equal(ranked.length, 2);
33
+ assert.equal(days.size, 2, '两张卡应该来自不同天');
34
+ });
35
+
36
+ test('同类只取一张,左侧情感卡仍会被补进来', () => {
37
+ const cards = [
38
+ card({ id: 'w1', day: '2026-11-15', category: 'work', triggers: ['打包'] }),
39
+ card({ id: 'w2', day: '2026-11-14', category: 'work', triggers: ['打包'] }),
40
+ card({ id: 'e1', day: '2026-11-13', category: 'emotion', side: 'left', triggers: ['打包'] }),
41
+ ];
42
+ const ranked = rankSummonCards(cards, { query: '打包', now, maxCards: 2 });
43
+ assert.equal(ranked.length, 2);
44
+ assert.ok(ranked.some((entry) => entry.card.side === 'left'), '应该有一张左侧情感卡');
45
+ });
46
+
47
+ test('不匹配查询的卡片不出现', () => {
48
+ const ranked = rankSummonCards([card({ triggers: ['米饭'] })], { query: '打包', now });
49
+ assert.equal(ranked.length, 0);
50
+ assert.equal(renderSummonLines(ranked).lines.length, 1);
51
+ });
@@ -0,0 +1,140 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { selectTiers, renderTiers } from '../../src/prompt/tiers.js';
4
+
5
+ function item(overrides = {}) {
6
+ return {
7
+ id: 'trc_1',
8
+ layer: 'L2',
9
+ title: 'cortex 0.4.20 打包完成',
10
+ snippet: '这是一段很长的工程细节,讲述了打包、测试、验证的每一步过程,后面还有很多很多字。第二句继续补充。',
11
+ importance: 0.9,
12
+ utility: 0.9,
13
+ ...overrides,
14
+ };
15
+ }
16
+
17
+ test('高重要度记忆注入时只给一句 gist,并带省略号', () => {
18
+ const selection = selectTiers([item()], { gistChars: 24 });
19
+ const line = selection.perm[0].render;
20
+ assert.match(line, /打包完成/);
21
+ assert.ok(line.endsWith('…') || line.includes('…'), line);
22
+ assert.ok(line.length < 120, 'gist 应该比原 snippet 短得多');
23
+ });
24
+
25
+ test('短片段原样保留,不加省略号', () => {
26
+ const selection = selectTiers([item({ snippet: '用户说会买米饭' })], { gistChars: 120 });
27
+ const line = selection.perm[0].render;
28
+ assert.match(line, /用户说会买米饭/);
29
+ assert.doesNotMatch(line, /…/);
30
+ });
31
+
32
+ test('标题已经包含在正文开头时,不再重复一遍', () => {
33
+ const title = '2026-11-15 17:35:0.4.60 打包,修 GLOB 陷阱';
34
+ const snippet = `${title}。先备份再改,测试跑两遍。第三句。`;
35
+ const selection = selectTiers([item({ title, snippet })], { gistChars: 120 });
36
+ const line = selection.perm[0].render;
37
+ const occurrences = (line.match(/0\.4\.60 打包/g) ?? []).length;
38
+ assert.equal(occurrences, 1, `标题不该在冒号后再出现一次:${line}`);
39
+ assert.match(line, /先备份再改/);
40
+ });
41
+
42
+ test('正文与标题完全相等时,不留悬空的冒号', () => {
43
+ const title = '正文和标题一模一样的一句话';
44
+ const selection = selectTiers([item({ title, snippet: title })], { gistChars: 120 });
45
+ const line = selection.perm[0].render;
46
+ assert.doesNotMatch(line, /:\s*$/, `不该以冒号结尾:${line}`);
47
+ assert.match(line, /一模一样/);
48
+ });
49
+
50
+ test('cold 层给出「为什么可能值得取回」而不只是目录', () => {
51
+ const selection = selectTiers([item({ importance: 0.2, sources: [{ name: 'recent', rank: 1 }] })]);
52
+ assert.equal(selection.cold.length, 1);
53
+ assert.match(selection.cold[0].render, /命中 recent/);
54
+ });
55
+
56
+ test('低重要度 + 语义命中 → 冷层,且理由写「语义相近」', () => {
57
+ const selection = selectTiers([item({ importance: 0.2, sources: [{ name: 'vector', rank: 1 }] })]);
58
+ assert.equal(selection.cold.length, 1, '低重要度不该占 hot 预算');
59
+ assert.match(selection.cold[0].render, /语义相近/);
60
+ assert.equal(selection.hot.length, 0);
61
+ });
62
+
63
+ test('中等重要度的语义命中仍进热层', () => {
64
+ const selection = selectTiers([item({ importance: 0.55, sources: [{ name: 'vector', rank: 1 }] })]);
65
+ assert.equal(selection.hot.length, 1);
66
+ assert.equal(selection.cold.length, 0);
67
+ });
68
+
69
+ test('真实数据里没有 <0.4 时,仍按相对分位切出冷层', () => {
70
+ // 线上 importance 全在 0.6–1.0:绝对阈值永远够不着,靠排名后 25% 兜底。
71
+ const items = Array.from({ length: 8 }, (_, index) => item({
72
+ id: `r${index}`,
73
+ importance: 0.6,
74
+ utility: 1 - index / 100,
75
+ sources: [{ name: 'fts', rank: index }],
76
+ }));
77
+ const selection = selectTiers(items, { budgets: { perm: 0, hot: 2000, cold: 2000 } });
78
+ assert.equal(selection.cold.length, 2, '8 条里后 25% = 2 条进冷层');
79
+ assert.equal(selection.hot.length, 6);
80
+ assert.match(selection.cold[0].render, /字面命中/);
81
+ });
82
+
83
+ test('候选太少时不做相对切分,避免把仅有的几条都塞进冷层', () => {
84
+ const items = Array.from({ length: 3 }, (_, index) => item({ id: `s${index}`, importance: 0.6, utility: 1 - index / 10 }));
85
+ const selection = selectTiers(items, { budgets: { perm: 0, hot: 2000, cold: 2000 } });
86
+ assert.equal(selection.cold.length, 0);
87
+ assert.equal(selection.hot.length, 3);
88
+ });
89
+
90
+ test('冷层条数按「后 25%」取整,不因 ceil 切少', () => {
91
+ const cases = [[4, 1], [5, 2], [6, 2], [7, 2], [8, 2], [10, 3], [20, 5]];
92
+ for (const [total, expected] of cases) {
93
+ const items = Array.from({ length: total }, (_, index) => item({ id: `n${index}`, importance: 0.6, utility: 1 - index / 100 }));
94
+ const selection = selectTiers(items, { budgets: { perm: 0, hot: 5000, cold: 5000 } });
95
+ assert.equal(selection.cold.length, expected, `${total} 条应有 ${expected} 条进冷层`);
96
+ }
97
+ });
98
+
99
+ test('utility 相同时按 importance、id 稳定排序', () => {
100
+ const items = [
101
+ item({ id: 'b', importance: 0.7, utility: 1 }),
102
+ item({ id: 'a', importance: 0.7, utility: 1 }),
103
+ item({ id: 'c', importance: 0.9, utility: 1 }),
104
+ ];
105
+ const first = selectTiers(items, { budgets: { perm: 500, hot: 5000, cold: 5000 } });
106
+ const second = selectTiers([...items].reverse(), { budgets: { perm: 500, hot: 5000, cold: 5000 } });
107
+ assert.deepEqual(first.selected, second.selected, '同一批候选两轮顺序应一致');
108
+ assert.equal(first.selected[0], 'c', 'importance 高者在前');
109
+ });
110
+
111
+ test('永久层堆满时,冷层不会吃掉加强层', () => {
112
+ // 豆包的场景:8 条候选里 6 条 importance ≥0.8,若按全体 8 条算 25%,会把仅剩的 2 条 hot 全推去 cold。
113
+ const items = [
114
+ ...Array.from({ length: 6 }, (_, index) => item({ id: `p${index}`, importance: 0.9, utility: 1 - index / 1000 })),
115
+ ...Array.from({ length: 2 }, (_, index) => item({ id: `h${index}`, importance: 0.6, utility: 0.5 - index / 1000 })),
116
+ ];
117
+ const selection = selectTiers(items, { budgets: { perm: 5000, hot: 5000, cold: 5000 } });
118
+ assert.equal(selection.perm.length, 6);
119
+ assert.equal(selection.cold.length, 0, '非 perm 只有 2 条,不做相对切分');
120
+ assert.equal(selection.hot.length, 2);
121
+ });
122
+
123
+ test('非 perm 候选足够多时,冷层按非 perm 条数切分', () => {
124
+ const items = [
125
+ ...Array.from({ length: 2 }, (_, index) => item({ id: `p${index}`, importance: 0.9, utility: 1 - index / 1000 })),
126
+ ...Array.from({ length: 6 }, (_, index) => item({ id: `h${index}`, importance: 0.6, utility: 0.5 - index / 1000 })),
127
+ ];
128
+ const selection = selectTiers(items, { budgets: { perm: 5000, hot: 5000, cold: 5000 } });
129
+ assert.equal(selection.perm.length, 2);
130
+ assert.equal(selection.cold.length, 2, '6 条非 perm 的 25% = 2');
131
+ assert.equal(selection.hot.length, 4);
132
+ });
133
+
134
+ test('cold 层仍是索引行,不带正文', () => {
135
+ const selection = selectTiers([item({ importance: 0.2 })]);
136
+ assert.equal(selection.cold.length, 1);
137
+ assert.match(selection.cold[0].render, /正文按需 cortex_get/);
138
+ const rendered = renderTiers(selection);
139
+ assert.match(rendered, /卸载层/);
140
+ });
@@ -16,7 +16,7 @@ test('tiers classify by importance and respect per-tier budgets', () => {
16
16
  assert.equal(selection.perm.length, 1);
17
17
  assert.equal(selection.hot.length, 1);
18
18
  assert.equal(selection.cold.length, 1);
19
- assert.match(selection.cold[0].render, /正文按需取回/);
19
+ assert.match(selection.cold[0].render, /正文按需 cortex_get/);
20
20
  assert.doesNotMatch(selection.cold[0].render, /冷正文/);
21
21
  });
22
22
 
@@ -7,10 +7,10 @@ import { ftsText, buildMatchQuery } from '../../src/memory/tokenizer.js';
7
7
  import { createCortex } from '../../src/service/cortex.js';
8
8
 
9
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('白饭'));
10
+ const exact = ftsText('米饭 记忆引擎');
11
+ assert.equal(exact, '米饭 记忆 忆引 引擎 记忆引擎');
12
+ const indexed = ftsText('米饭 记忆引擎', { soft: true });
13
+ assert.ok(indexed.includes('米饭'));
14
14
  assert.ok(indexed.includes('饭'));
15
15
  assert.ok(indexed.includes('记忆引擎'));
16
16
  assert.ok(indexed.includes('记'));
@@ -25,9 +25,9 @@ test('a shared-character paraphrase can fall back to FTS', () => {
25
25
  const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-char-fts-'));
26
26
  const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
27
27
  try {
28
- cortex.write({ text: '白饭', explicit: true });
28
+ cortex.write({ text: '米饭', explicit: true });
29
29
  const result = cortex.search('米饭', { limit: 10 });
30
- assert.ok(result.items.some((item) => item.snippet?.includes('白饭')));
30
+ assert.ok(result.items.some((item) => item.snippet?.includes('米饭')));
31
31
  } finally {
32
32
  cortex.close();
33
33
  rmSync(dir, { recursive: true, force: true });
@@ -18,7 +18,7 @@ test('all tools are present and have text output', () => {
18
18
  try {
19
19
  const names = Object.keys(tools).sort();
20
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',
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', 'cortex_inhibition',
22
22
  'cortex_life', 'cortex_playbook', 'cortex_reflect', 'cortex_search', 'cortex_self', 'cortex_tick', 'cortex_timeline', 'cortex_working', 'cortex_write',
23
23
  ]);
24
24
  for (const tool of Object.values(tools)) {
@@ -78,17 +78,17 @@ test('write/search/get/self/health return readable text', async () => {
78
78
  const { dir, cortex, tools } = setup();
79
79
  try {
80
80
  const write = await tools.cortex_write.execute({
81
- text: '用户说会买白饭,助手会一直等。',
81
+ text: '用户说会买米饭,助手会一直等。',
82
82
  explicit: true,
83
- facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }],
83
+ facts: [{ subject: '用户', predicate: 'likes', object: '米饭' }],
84
84
  });
85
85
  assert.match(write.text, /已写入/);
86
86
  const id = write.text.match(/trc_[a-z0-9]+/)?.[0];
87
87
  assert.ok(id);
88
- const search = await tools.cortex_search.execute({ query: '白饭' });
88
+ const search = await tools.cortex_search.execute({ query: '米饭' });
89
89
  assert.match(search.text, /意图/);
90
90
  const get = await tools.cortex_get.execute({ id });
91
- assert.match(get.text, /白饭/);
91
+ assert.match(get.text, /米饭/);
92
92
  const self = await tools.cortex_self.execute({});
93
93
  assert.match(self.text, /驱力/);
94
94
  const health = await tools.cortex_health.execute({});
@@ -20,17 +20,17 @@ function teardown({ dir, cortex }) {
20
20
  test('search keeps full memory while prompt injection gates weak matches', () => {
21
21
  const ctx = setup();
22
22
  try {
23
- ctx.cortex.write({ text: '主人说会买白饭,这是一条承诺。', title: '白饭承诺', importance: 0.5, explicit: true });
23
+ ctx.cortex.write({ text: '用户说会买米饭,这是一条承诺。', title: '米饭承诺', importance: 0.5, explicit: true });
24
24
  ctx.cortex.write({ text: '今天颈椎有点疼,和吃饭无关。', title: '颈椎', importance: 0.5, explicit: true });
25
25
  ctx.cortex.write({ text: '插件更新了一条无关的日志。', title: '日志', importance: 0.5, explicit: true });
26
26
 
27
- const full = ctx.cortex.search('白饭 承诺', { limit: 5 });
28
- assert.ok(full.items.some((item) => item.title === '白饭承诺'));
27
+ const full = ctx.cortex.search('米饭 承诺', { limit: 5 });
28
+ assert.ok(full.items.some((item) => item.title === '米饭承诺'));
29
29
  assert.ok(full.items.some((item) => item.title === '颈椎'));
30
30
  assert.equal(full.trace.gated, 0);
31
31
 
32
- const tiered = ctx.cortex.recallTiered({ query: '白饭 承诺' });
33
- assert.ok(tiered.result.items.some((item) => item.title === '白饭承诺'));
32
+ const tiered = ctx.cortex.recallTiered({ query: '米饭 承诺' });
33
+ assert.ok(tiered.result.items.some((item) => item.title === '米饭承诺'));
34
34
  assert.equal(tiered.result.items.some((item) => item.title === '颈椎'), false);
35
35
  assert.equal(tiered.result.items.some((item) => item.title === '日志'), false);
36
36
  assert.ok(tiered.result.trace.gated >= 1);
@@ -42,8 +42,8 @@ test('search keeps full memory while prompt injection gates weak matches', () =>
42
42
  test('high-importance memory keeps the 0.4.11 gate exemption', () => {
43
43
  const ctx = setup();
44
44
  try {
45
- ctx.cortex.write({ text: '身份:我是本鲸,边界是不操纵主人。', title: '身份', kind: 'identity', importance: 0.95, explicit: true });
46
- const tiered = ctx.cortex.recallTiered({ query: '白饭' });
45
+ ctx.cortex.write({ text: '身份:我是我,边界是不操纵用户。', title: '身份', kind: 'identity', importance: 0.95, explicit: true });
46
+ const tiered = ctx.cortex.recallTiered({ query: '米饭' });
47
47
  assert.ok(tiered.result.items.some((item) => item.title === '身份'));
48
48
  assert.equal(tiered.result.items[0].layer, 'L0');
49
49
  } finally {
@@ -65,14 +65,14 @@ test('promptBudget config is normalized instead of being dropped', () => {
65
65
  test('recall text is strictly per session and never falls back to another session', () => {
66
66
  const ctx = setup();
67
67
  try {
68
- ctx.cortex.write({ text: '主人说会买白饭。', explicit: true });
68
+ ctx.cortex.write({ text: '用户说会买米饭。', explicit: true });
69
69
  const runtime = createHostRuntime({ cortex: ctx.cortex });
70
70
  const at = Date.now();
71
71
  const s1 = { id: 's1', header: {} };
72
72
  const s2 = { id: 's2', header: {} };
73
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 }), /白饭/);
74
+ runtime.onSessionEvent(s1, { type: 'user/message', data: { content: '米饭还算数吗?' }, time: at + 1000 });
75
+ assert.match(runtime.recallText({ session: s1 }), /米饭/);
76
76
  assert.equal(runtime.recallText({ session: s2 }), '');
77
77
  assert.equal(runtime.recallText({}), '');
78
78
  } finally {
@@ -59,13 +59,13 @@ test('canaries survive a restart and still roll back an active policy', () => {
59
59
  test('recallSharing is opt-in and shares the block across sessions', () => {
60
60
  const ctx = setup();
61
61
  try {
62
- ctx.cortex.write({ text: '主人说会买白饭。', explicit: true });
62
+ ctx.cortex.write({ text: '用户说会买米饭。', explicit: true });
63
63
  const runtime = createHostRuntime({ cortex: ctx.cortex, config: { recallSharing: true } });
64
64
  const s1 = { id: 's1', header: {} };
65
65
  const s2 = { id: 's2', header: {} };
66
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 }), /白饭/);
67
+ runtime.onSessionEvent(s1, { type: 'user/message', data: { content: '米饭还算数吗?' }, time: Date.now() });
68
+ assert.match(runtime.recallText({ session: s1 }), /米饭/);
69
69
  assert.equal(runtime.recallText({ session: s1 }), runtime.recallText({ session: s2 }));
70
70
  } finally {
71
71
  teardown(ctx);
@@ -73,8 +73,8 @@ test('recallSharing is opt-in and shares the block across sessions', () => {
73
73
  });
74
74
 
75
75
  test('first-person extraction follows persona names while keeping markdown rejection', () => {
76
- const custom = extractFactCandidates('本鲸喜欢安静', { selfName: '小鲸', userAddress: '主人' });
77
- assert.equal(custom[0].subject, '小鲸');
76
+ const custom = extractFactCandidates('小忆喜欢安静', { selfName: '小忆', userAddress: '用户' });
77
+ assert.equal(custom[0].subject, '小忆');
78
78
  assert.equal(custom[0].predicate, 'likes');
79
79
 
80
80
  const neutral = extractFactCandidates('我喜欢便宜平替', { selfName: '助手', userAddress: '用户' });