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
@@ -11,11 +11,11 @@ test('llmFacts schedules background extraction and writes validated facts', asyn
11
11
  config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llmFacts: true } },
12
12
  llm: {
13
13
  available: () => true,
14
- complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"白饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.1}]}',
14
+ complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"米饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.1}]}',
15
15
  },
16
16
  });
17
17
  try {
18
- cortex.write({ text: '助手喜欢白饭。', explicit: true });
18
+ cortex.write({ text: '助手喜欢米饭。', explicit: true });
19
19
  await cortex.flushLlmFacts();
20
20
  const facts = cortex.repos.facts.list({ scopeId: 'global' });
21
21
  assert.equal(facts.length, 1);
@@ -3,10 +3,10 @@ import assert from 'node:assert/strict';
3
3
  import { extractFactsWithLlm } from '../../src/engines/llm-facts.js';
4
4
 
5
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: '助手喜欢白饭。' });
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
8
  assert.equal(result.candidates.length, 1);
9
- assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '白饭', confidence: 0.9 });
9
+ assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '米饭', confidence: 0.9 });
10
10
  });
11
11
 
12
12
  test('LLM facts fail closed on malformed output or missing model', async () => {
@@ -2,7 +2,7 @@ import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import { createLlmAdapter } from '../../src/llm/adapter.js';
4
4
 
5
- function mockCtx(text = '梦里,助手坐在白饭旁边。') {
5
+ function mockCtx(text = '梦里,助手坐在米饭旁边。') {
6
6
  return {
7
7
  get(name) {
8
8
  if (name === 'llm') {
@@ -21,11 +21,11 @@ test('llm adapter completes, dreams and summarizes through the host service', as
21
21
  const adapter = createLlmAdapter({ ctx: mockCtx() });
22
22
  assert.equal(adapter.available(), true);
23
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, /白饭/);
24
+ assert.match(text, /米饭/);
25
+ const dream = await adapter.dream({ pieces: ['米饭'], emotions: '暖' });
26
+ assert.match(dream, /米饭/);
27
27
  const summary = await adapter.summarize({ text: '一段很长的记忆' });
28
- assert.match(summary, /白饭/);
28
+ assert.match(summary, /米饭/);
29
29
  });
30
30
 
31
31
  test('llm adapter fails open when the service is missing or errors', async () => {
@@ -13,7 +13,7 @@ const sample = {
13
13
  speaker_b: 'B',
14
14
  session_1_date_time: '2026-11-01T10:00:00+08:00',
15
15
  session_1: [
16
- { speaker: 'A', text: '我喜欢白饭。' },
16
+ { speaker: 'A', text: '我喜欢米饭。' },
17
17
  { speaker: 'B', text: '那很好。' },
18
18
  ],
19
19
  session_2_date_time: '2026-11-02T10:00:00+08:00',
@@ -22,7 +22,7 @@ const sample = {
22
22
  ],
23
23
  },
24
24
  qa: [
25
- { question: 'A 喜欢什么?', answer: '白饭', evidence: ['D1:1'], category: 1 },
25
+ { question: 'A 喜欢什么?', answer: '米饭', evidence: ['D1:1'], category: 1 },
26
26
  { question: '不存在的事是什么?', answer: '没有', evidence: [], category: 5 },
27
27
  ],
28
28
  };
@@ -11,12 +11,12 @@ const fixture = [
11
11
  question_id: 'q1',
12
12
  question_type: 'single-session-user',
13
13
  question: '用户喜欢什么主食?',
14
- answer: '白饭',
14
+ answer: '米饭',
15
15
  question_date: '2026-11-11T12:00:00+08:00',
16
16
  haystack_session_ids: ['s1', 's2'],
17
17
  haystack_dates: ['2026-11-01T12:00:00+08:00', '2026-11-02T12:00:00+08:00'],
18
18
  haystack_sessions: [
19
- [{ role: 'user', content: '用户最喜欢白饭。', has_answer: true }],
19
+ [{ role: 'user', content: '用户最喜欢米饭。', has_answer: true }],
20
20
  [{ role: 'user', content: '今天修插件。' }],
21
21
  ],
22
22
  answer_session_ids: ['s1'],
@@ -0,0 +1,62 @@
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
+ });
@@ -0,0 +1,194 @@
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('maintain 会记录耗时,健康报告能读到(空转走内存回退)', () => {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-ms-'));
10
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
+ try {
12
+ const now = Date.now();
13
+ const report = cortex.maintain({ now });
14
+ assert.ok(Number.isFinite(report.ms) && report.ms >= 0, `maintain 应回报耗时(实际 ${report.ms})`);
15
+ const health = cortex.health({ scopeId: 'global', now });
16
+ assert.ok(health.maintain, '健康报告应带上一次维护');
17
+ assert.equal(health.maintain.ms, report.ms, '耗时应通过内存回退传到健康报告');
18
+ } finally {
19
+ cortex.close();
20
+ rmSync(dir, { recursive: true, force: true });
21
+ }
22
+ });
23
+
24
+ test('真产生变更(写审计行)时,审计行里也有 ms', () => {
25
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-audit-ms-'));
26
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
27
+ try {
28
+ const now = Date.now();
29
+ // 两条完全相同的摘要会被维护清掉一条 → 一定会写 maintain.run 审计行
30
+ cortex.repos.summaries.insert({ level: 'thread', content: '重复的摘要内容', sourceIds: ['t1'], coverage: 0.2 });
31
+ cortex.repos.summaries.insert({ level: 'thread', content: '重复的摘要内容', sourceIds: ['t1'], coverage: 0.2 });
32
+ const report = cortex.maintain({ now });
33
+ assert.ok(report.summaries >= 1, '应清掉一条重复摘要');
34
+
35
+ const row = cortex.repos.audit.list({ targetType: 'scope', targetId: 'global', limit: 1 })[0];
36
+ assert.ok(row, '应写入 maintain.run 审计行');
37
+ const detail = row.detail ?? {};
38
+ assert.ok(Number.isFinite(detail.ms), `审计 detail 里应该有 ms(实际 ${JSON.stringify(Object.keys(detail))})`);
39
+
40
+ const health = cortex.health({ scopeId: 'global', now });
41
+ assert.ok(Number.isFinite(health.maintain?.ms), '有审计行时健康报告也要拿到 ms');
42
+ } finally {
43
+ cortex.close();
44
+ rmSync(dir, { recursive: true, force: true });
45
+ }
46
+ });
47
+
48
+ test('维护超过阈值的耗时会被报成 SLOW_MAINTAIN,阈值可配', () => {
49
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-slow-'));
50
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), maintainSlowMs: 5 } });
51
+ try {
52
+ const now = Date.now();
53
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(now).toISOString(), ms: 50 } });
54
+ const health = cortex.health({ scopeId: 'global', now });
55
+ const slow = health.issues.find((issue) => issue.code === 'SLOW_MAINTAIN');
56
+ assert.ok(slow, '超过 maintainSlowMs 应提示慢维护');
57
+ assert.equal(slow.detail?.ms, 50);
58
+ } finally {
59
+ cortex.close();
60
+ rmSync(dir, { recursive: true, force: true });
61
+ }
62
+ });
63
+
64
+ test('旧审计行缺 ms 时整条回退到内存快照,不混合两次维护的数字', () => {
65
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-mixed-'));
66
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
67
+ try {
68
+ const now = Date.now();
69
+ // 升级前留下的 9 键旧行:没有 ms,但 working=7
70
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(now - 60000).toISOString(), working: 7, intentions: 3 } });
71
+ const report = cortex.maintain({ now });
72
+ const health = cortex.health({ scopeId: 'global', now });
73
+ assert.ok(Number.isFinite(health.maintain?.ms), '应回退到内存快照拿到 ms');
74
+ assert.equal(health.maintain.working, report.working, '条数与耗时必须来自同一次维护');
75
+ assert.notEqual(health.maintain.working, 7, '不应把旧行的 7 与新的耗时混在一起');
76
+ } finally {
77
+ cortex.close();
78
+ rmSync(dir, { recursive: true, force: true });
79
+ }
80
+ });
81
+
82
+ test('安静的一趟不写审计行时,健康报告同时说清「最近一趟」与「最近一次有变更」', () => {
83
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-twolines-'));
84
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
85
+ try {
86
+ const now = Date.now();
87
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(now - 6 * 3600000).toISOString(), working: 7, intentions: 3 } });
88
+ cortex.maintain({ now });
89
+ const health = cortex.health({ scopeId: 'global', now });
90
+ const lines = health.ok.join('\n');
91
+ assert.match(lines, /最近一趟维护/, '应报告最近一趟');
92
+ assert.match(lines, /最近一次有变更的维护/, '旧审计行较旧时应另说一句');
93
+ assert.equal(health.maintainLastChanged?.working, 7, 'maintainLastChanged 应保留旧行数据');
94
+ } finally {
95
+ cortex.close();
96
+ rmSync(dir, { recursive: true, force: true });
97
+ }
98
+ });
99
+
100
+ test('先变更一趟、再安静一趟:第一行是最近的安静趟,第二行才是那次变更', () => {
101
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-order-'));
102
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
103
+ try {
104
+ const t1 = Date.now();
105
+ cortex.repos.summaries.insert({ level: 'thread', content: '重复摘要 A', sourceIds: ['t1'], coverage: 0.2 });
106
+ cortex.repos.summaries.insert({ level: 'thread', content: '重复摘要 A', sourceIds: ['t1'], coverage: 0.2 });
107
+ const change = cortex.maintain({ now: t1 });
108
+ assert.ok(change.summaries >= 1, '第一趟应真的产生变更');
109
+
110
+ const t2 = t1 + 60_000;
111
+ const quiet = cortex.maintain({ now: t2 });
112
+ assert.equal(quiet.summaries, 0, '第二趟应无变更');
113
+
114
+ const health = cortex.health({ scopeId: 'global', now: t2 });
115
+ assert.equal(health.maintain.at, quiet.at, '第一行必须是最近那一趟(安静趟)');
116
+ assert.equal(health.maintainLastChanged?.passAt ?? health.maintainLastChanged?.at, change.at, '第二行才是那次有变更的维护');
117
+ assert.notEqual(health.maintain.at, health.maintainLastChanged?.passAt, '两行不能同源');
118
+ } finally {
119
+ cortex.close();
120
+ rmSync(dir, { recursive: true, force: true });
121
+ }
122
+ });
123
+
124
+ test('慢维护被后续安静趟盖住时,仍要报 SLOW_MAINTAIN', () => {
125
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-masked-'));
126
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
127
+ try {
128
+ const t1 = Date.now() - 60_000;
129
+ // 伪造一次 8.5 秒的慢维护审计行
130
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(t1).toISOString(), ms: 8500, working: 2 } });
131
+ // 一分钟后跑一次很快的安静维护,把「最近一趟」顶掉
132
+ const quiet = cortex.maintain({ now: Date.now() });
133
+ assert.ok(quiet.ms < 2000, '安静趟本身不该慢');
134
+
135
+ const health = cortex.health({ scopeId: 'global' });
136
+ const slow = health.issues.find((issue) => issue.code === 'SLOW_MAINTAIN');
137
+ assert.ok(slow, '慢趟不该被后续安静趟遮住');
138
+ assert.equal(slow.detail.ms, 8500);
139
+ assert.match(String(slow.detail.at), /T/, '告警要带上那一趟的时间');
140
+ } finally {
141
+ cortex.close();
142
+ rmSync(dir, { recursive: true, force: true });
143
+ }
144
+ });
145
+
146
+ test('慢维护即使没有变更也要落审计行(否则护栏永远没样本)', () => {
147
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-slowrow-'));
148
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), maintainSlowMs: 0 } });
149
+ try {
150
+ const now = Date.now();
151
+ const report = cortex.maintain({ now });
152
+ assert.ok(report.ms > 0, '阈值设 0 时每趟都算慢');
153
+ const row = cortex.repos.audit.list({ targetType: 'scope', targetId: 'global', limit: 1 })[0];
154
+ assert.ok(row, '慢趟应写审计行');
155
+ assert.ok(Number.isFinite(row.detail?.ms), '审计 detail 应带 ms');
156
+ } finally {
157
+ cortex.close();
158
+ rmSync(dir, { recursive: true, force: true });
159
+ }
160
+ });
161
+
162
+ test('超过窗口的慢维护不再常驻告警', () => {
163
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-olderv-'));
164
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
165
+ try {
166
+ const now = Date.now();
167
+ const old = now - 8 * 3600_000;
168
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(old).toISOString(), ms: 9000, working: 1 } });
169
+ const health = cortex.health({ scopeId: 'global', now });
170
+ const slow = health.issues.find((issue) => issue.code === 'SLOW_MAINTAIN');
171
+ assert.equal(slow, undefined, '8 小时前的慢趟属于历史,不该常驻');
172
+ } finally {
173
+ cortex.close();
174
+ rmSync(dir, { recursive: true, force: true });
175
+ }
176
+ });
177
+
178
+ test('时间戳带空格也能正确比较,不被字典序骗到', () => {
179
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-maintain-spacefmt-'));
180
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
181
+ try {
182
+ const now = Date.now();
183
+ // 同一时刻:审计行写成带空格格式,内存是 ISO
184
+ const iso = new Date(now).toISOString();
185
+ const spaced = iso.replace('T', ' ').replace('Z', '');
186
+ cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: spaced, ms: 3, working: 2 } });
187
+ const report = cortex.maintain({ now });
188
+ const health = cortex.health({ scopeId: 'global', now });
189
+ assert.equal(health.maintain.at, report.at, '同一时刻应判为同一趟,用内存快照');
190
+ } finally {
191
+ cortex.close();
192
+ rmSync(dir, { recursive: true, force: true });
193
+ }
194
+ });
@@ -7,13 +7,13 @@ import { createCortex } from '../../src/service/cortex.js';
7
7
  import { parseMemoryMarkdown, importMarkdown } from '../../src/adapters/markdown-import.js';
8
8
 
9
9
  test('markdown parser reads frontmatter and body', () => {
10
- const parsed = parseMemoryMarkdown('---\nid: "t1"\nkind: "fact"\ntitle: "白饭"\ntags: ["白饭", "承诺"]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\nrecorded_at: "2026-11-05T10:00:00+08:00"\n---\n\n用户喜欢白饭。\n');
10
+ const parsed = parseMemoryMarkdown('---\nid: "t1"\nkind: "fact"\ntitle: "米饭"\ntags: ["米饭", "承诺"]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\nrecorded_at: "2026-11-05T10:00:00+08:00"\n---\n\n用户喜欢米饭。\n');
11
11
  assert.equal(parsed.id, 't1');
12
12
  assert.equal(parsed.kind, 'fact');
13
- assert.deepEqual(parsed.tags, ['白饭', '承诺']);
13
+ assert.deepEqual(parsed.tags, ['米饭', '承诺']);
14
14
  assert.equal(parsed.attachments.length, 1);
15
15
  assert.equal(parsed.attachments[0].uri, 'https://example.test/rice.png');
16
- assert.match(parsed.content, /用户喜欢白饭/);
16
+ assert.match(parsed.content, /用户喜欢米饭/);
17
17
  });
18
18
 
19
19
  test('markdown import writes active files idempotently', () => {
@@ -21,7 +21,7 @@ test('markdown import writes active files idempotently', () => {
21
21
  const vault = mkdtempSync(path.join(os.tmpdir(), 'cortex-vault-'));
22
22
  const cortex = createCortex({ config: { dataRoot: dataDir, dbFile: path.join(dataDir, 'cortex.sqlite') } });
23
23
  try {
24
- writeFileSync(path.join(vault, 'a.md'), '---\nid: a\nkind: utterance\ntitle: 白饭\ntags: [白饭]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\n---\n\n用户喜欢白饭。\n', 'utf8');
24
+ writeFileSync(path.join(vault, 'a.md'), '---\nid: a\nkind: utterance\ntitle: 米饭\ntags: [米饭]\nattachments: [{"kind":"image","uri":"https://example.test/rice.png"}]\n---\n\n用户喜欢米饭。\n', 'utf8');
25
25
  writeFileSync(path.join(vault, 'b.md'), '---\nid: b\nstate: archived\n---\n\n不该导入。\n', 'utf8');
26
26
  const dry = importMarkdown(cortex, vault, { dryRun: true });
27
27
  assert.equal(dry.files, 2);
@@ -34,7 +34,7 @@ test('markdown import writes active files idempotently', () => {
34
34
  assert.equal(importedTrace.metadata.attachments.length, 1);
35
35
  assert.equal(importedTrace.metadata.attachments[0].uri, 'https://example.test/rice.png');
36
36
  const again = importMarkdown(cortex, vault);
37
- assert.equal(again.items.find((item) => item.title === '白饭').skipped, true);
37
+ assert.equal(again.items.find((item) => item.title === '米饭').skipped, true);
38
38
  assert.equal(cortex.repos.traces.count(), 1);
39
39
  } finally {
40
40
  cortex.close();
@@ -10,14 +10,14 @@ test('markdown mirror exports readable files and skips secrets', () => {
10
10
  const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-md-'));
11
11
  const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
12
12
  try {
13
- cortex.write({ text: '用户说会买白饭。', title: '白饭', explicit: true, facts: [{ subject: '用户', predicate: 'likes', object: '白饭' }], attachments: [{ kind: 'image', uri: 'https://example.test/rice.png', mime: 'image/png' }] });
13
+ cortex.write({ text: '用户说会买米饭。', title: '米饭', explicit: true, facts: [{ subject: '用户', predicate: 'likes', object: '米饭' }], attachments: [{ kind: 'image', uri: 'https://example.test/rice.png', mime: 'image/png' }] });
14
14
  cortex.write({ text: '这是一个 secret:sk-abcdefghijklmnopqrstuvwxyz123456', explicit: true });
15
15
  cortex.engines.skills.create({ name: '修插件', steps: ['看日志', '改一处', '跑测试'], state: 'active' });
16
16
  const result = exportMarkdown(cortex, path.join(dir, 'mirror'));
17
17
  assert.equal(result.traces, 1);
18
18
  assert.equal(result.skippedSecrets, 1);
19
19
  const memory = readFileSync(path.join(dir, 'mirror', 'MEMORY.md'), 'utf8');
20
- assert.match(memory, /白饭/);
20
+ assert.match(memory, /米饭/);
21
21
  assert.match(memory, /Attachments \(metadata only\)/);
22
22
  assert.match(memory, /https:\/\/example\.test\/rice\.png/);
23
23
  assert.doesNotMatch(memory, /sk-abcdefghijklmnop/);
@@ -57,17 +57,17 @@ test('summon cards are built for left/right brain and can be edited after unlock
57
57
  test('manual card edits survive a rebuild and cards can be matched by a specific phrase', () => {
58
58
  const { dir, cortex } = setup();
59
59
  try {
60
- cortex.write({ text: '白饭约定:以后要一起买白饭。', title: '白饭约定', kind: 'decision', explicit: true, importance: 0.95 });
60
+ cortex.write({ text: '米饭约定:以后要一起买米饭。', title: '米饭约定', kind: 'decision', explicit: true, importance: 0.95 });
61
61
  cortex.rebuildSummonBook();
62
62
  const first = cortex.summonBook({ date: new Date().toLocaleDateString('en-CA') });
63
- const card = first.right.find((item) => item.title.includes('白饭')) ?? first.right[0];
63
+ const card = first.right.find((item) => item.title.includes('米饭')) ?? first.right[0];
64
64
  assert.ok(card);
65
65
  cortex.setMemoryEdit(true);
66
- cortex.updateSummonCard({ id: card.id, title: '用户改过的白饭卡' });
66
+ cortex.updateSummonCard({ id: card.id, title: '用户改过的米饭卡' });
67
67
  cortex.rebuildSummonBook();
68
68
  const second = cortex.summonBook({ date: new Date().toLocaleDateString('en-CA') });
69
- assert.equal(second.right.find((item) => item.id === card.id).title, '用户改过的白饭卡');
70
- const match = cortex.matchSummonCards({ text: '你还记得白饭约定吗?' });
69
+ assert.equal(second.right.find((item) => item.id === card.id).title, '用户改过的米饭卡');
70
+ const match = cortex.matchSummonCards({ text: '你还记得米饭约定吗?' });
71
71
  assert.ok(match.cards.length >= 1);
72
72
  assert.match(match.block, /召唤卡/);
73
73
  const feedback = cortex.feedbackSummonCard({ id: card.id, signal: 'helpful' });
@@ -22,7 +22,7 @@ test('migration adds facts.superseded_at and backfills invalidated rows', () =>
22
22
  hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
23
23
  );
24
24
  INSERT INTO meta VALUES ('schema_version', '5', '2026-11-01T00:00:00Z');
25
- INSERT INTO facts VALUES ('f_old','global','e1','喜欢',NULL,'白饭','2026-01-01','2026-02-01','2026-01-02',0.7,'invalidated',NULL,'f_new','[]','h','2026-01-02','2026-02-01');
25
+ INSERT INTO facts VALUES ('f_old','global','e1','喜欢',NULL,'米饭','2026-01-01','2026-02-01','2026-01-02',0.7,'invalidated',NULL,'f_new','[]','h','2026-01-02','2026-02-01');
26
26
  `);
27
27
  migrate(db);
28
28
  const columns = db.prepare('PRAGMA table_info(facts)').all().map((column) => column.name);
@@ -0,0 +1,33 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { applyMood } from '../../src/self/state.js';
4
+
5
+ const base = { valence: 0, arousal: 0.2, energy: 0.6 };
6
+
7
+ test('越接近边界,同样的好事推动越小(饱和)', () => {
8
+ const fromNeutral = applyMood({ ...base, valence: 0 }, { valence: 0.8, salience: 0.6 });
9
+ const fromHigh = applyMood({ ...base, valence: 0.9 }, { valence: 0.8, salience: 0.6 });
10
+ const deltaNeutral = fromNeutral.valence - 0;
11
+ const deltaHigh = fromHigh.valence - 0.9;
12
+ assert.ok(deltaHigh < deltaNeutral, `高处应更小:${deltaHigh} < ${deltaNeutral}`);
13
+ assert.ok(deltaHigh > 0, '仍然要往好的方向走');
14
+ });
15
+
16
+ test('反复叠加只会逼近上限,不会一次顶死', () => {
17
+ let mood = { ...base };
18
+ for (let i = 0; i < 3; i += 1) mood = applyMood(mood, { valence: 1, salience: 1, weight: 0.5 });
19
+ assert.ok(mood.valence < 0.99, `不应该顶到 1.0:${mood.valence}`);
20
+ assert.ok(mood.valence > 0.9, `但也该足够高:${mood.valence}`);
21
+ });
22
+
23
+ test('负向事件同样饱和,一次不该按到底', () => {
24
+ const mood = applyMood({ ...base, valence: -0.9 }, { valence: -1, salience: 0.9 });
25
+ assert.ok(mood.valence > -1, `一次事件不该把它按到底:${mood.valence}`);
26
+ assert.ok(mood.valence < -0.9, '但确实更低了');
27
+ });
28
+
29
+ test('唤醒度用同样的饱和规则,且不越出 0..1', () => {
30
+ const high = applyMood({ ...base, arousal: 0.95 }, { arousal: 1, salience: 1 });
31
+ assert.ok(high.arousal <= 1);
32
+ assert.ok(high.arousal > 0.95);
33
+ });