dsh-cortex-memory 0.3.1 → 0.4.14

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 (140) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +1 -1
  3. package/README.md +67 -14
  4. package/client.js +33 -19
  5. package/cordis.patch.yml +1 -1
  6. package/docs/compatibility.md +39 -0
  7. package/docs/install-windows.md +2 -1
  8. package/docs/permissions.md +6 -2
  9. package/docs/privacy.md +3 -1
  10. package/examples/README.md +3 -2
  11. package/examples/uninstall-cortex.ps1 +1 -0
  12. package/index.js +31 -1
  13. package/package.json +8 -12
  14. package/src/adapters/shiori.js +1 -1
  15. package/src/api/routes.js +30 -3
  16. package/src/core/config.js +33 -0
  17. package/src/engines/develop.js +1 -1
  18. package/src/engines/extract.js +26 -7
  19. package/src/engines/growth.js +1 -1
  20. package/src/engines/life.js +56 -41
  21. package/src/engines/reflect.js +1 -1
  22. package/src/engines/retrieve.js +34 -5
  23. package/src/guardian/guardian.js +3 -2
  24. package/src/guardian/invariants.js +9 -5
  25. package/src/host/runtime.js +13 -7
  26. package/src/host/scheduler.js +11 -2
  27. package/src/llm/adapter.js +19 -7
  28. package/src/memory/query.js +1 -1
  29. package/src/self/appraisal.js +3 -3
  30. package/src/self/emotion.js +1 -1
  31. package/src/self/evolution.js +142 -4
  32. package/src/self/identity.js +1 -1
  33. package/src/self/policies.js +27 -1
  34. package/src/self/relationship.js +2 -2
  35. package/src/service/cortex.js +97 -15
  36. package/src/store/database.js +9 -1
  37. package/src/store/schema.sql +2 -1
  38. package/src/tools/definitions.js +19 -1
  39. package/src/vector/hnsw.js +5 -5
  40. package/src/web/search.js +97 -0
  41. package/test/integration/_helpers.js +128 -0
  42. package/test/integration/acceptance.test.js +803 -0
  43. package/test/integration/ann-load.test.js +61 -0
  44. package/test/integration/api-contract.test.js +1476 -0
  45. package/test/integration/backup-privacy.test.js +214 -0
  46. package/test/integration/consolidate.test.js +75 -0
  47. package/test/integration/edge-cases.test.js +1088 -0
  48. package/test/integration/exchange.test.js +326 -0
  49. package/test/integration/life-loop.test.js +188 -0
  50. package/test/integration/load.test.js +751 -0
  51. package/test/integration/markdown-sync.test.js +35 -0
  52. package/test/integration/policy-query-api.test.js +306 -0
  53. package/test/integration/resilience-writes.test.js +241 -0
  54. package/test/integration/tools-contract.test.js +1324 -0
  55. package/test/unit/ann-edge.test.js +102 -0
  56. package/test/unit/ann.test.js +77 -0
  57. package/test/unit/api-client.test.js +576 -0
  58. package/test/unit/api-validate.test.js +19 -0
  59. package/test/unit/api.test.js +555 -0
  60. package/test/unit/appraisal.test.js +48 -0
  61. package/test/unit/attachments.test.js +33 -0
  62. package/test/unit/autonomy.test.js +53 -0
  63. package/test/unit/batch.test.js +46 -0
  64. package/test/unit/bench.test.js +40 -0
  65. package/test/unit/benchmark-synthetic.test.js +52 -0
  66. package/test/unit/client-contract.test.js +29 -0
  67. package/test/unit/compression.test.js +76 -0
  68. package/test/unit/core.test.js +77 -0
  69. package/test/unit/develop.test.js +130 -0
  70. package/test/unit/development.test.js +68 -0
  71. package/test/unit/digest.test.js +26 -0
  72. package/test/unit/dsr.test.js +111 -0
  73. package/test/unit/edges-candidates.test.js +113 -0
  74. package/test/unit/emotion.test.js +61 -0
  75. package/test/unit/encode.test.js +98 -0
  76. package/test/unit/evolution.test.js +130 -0
  77. package/test/unit/external-ann-search.test.js +50 -0
  78. package/test/unit/external-ann.test.js +29 -0
  79. package/test/unit/facts-belief.test.js +32 -0
  80. package/test/unit/facts.test.js +107 -0
  81. package/test/unit/feature-overrides.test.js +42 -0
  82. package/test/unit/fts-migration.test.js +42 -0
  83. package/test/unit/graph.test.js +79 -0
  84. package/test/unit/growth-reflect.test.js +123 -0
  85. package/test/unit/guard-runtime.test.js +40 -0
  86. package/test/unit/guardian.test.js +91 -0
  87. package/test/unit/health-privacy.test.js +102 -0
  88. package/test/unit/hnsw.test.js +35 -0
  89. package/test/unit/host-runtime.test.js +142 -0
  90. package/test/unit/host.test.js +58 -0
  91. package/test/unit/identity.test.js +98 -0
  92. package/test/unit/induct-evaluate.test.js +41 -0
  93. package/test/unit/ingest-extracted.test.js +35 -0
  94. package/test/unit/initiative.test.js +90 -0
  95. package/test/unit/jobs.test.js +93 -0
  96. package/test/unit/json-snapshot.test.js +57 -0
  97. package/test/unit/life-consolidate.test.js +34 -0
  98. package/test/unit/life.test.js +149 -0
  99. package/test/unit/llm-facts-integration.test.js +27 -0
  100. package/test/unit/llm-facts.test.js +16 -0
  101. package/test/unit/llm.test.js +45 -0
  102. package/test/unit/locomo.test.js +45 -0
  103. package/test/unit/longmemeval.test.js +56 -0
  104. package/test/unit/markdown-import.test.js +44 -0
  105. package/test/unit/markdown.test.js +34 -0
  106. package/test/unit/memory-edit.test.js +112 -0
  107. package/test/unit/metrics.test.js +26 -0
  108. package/test/unit/migration.test.js +38 -0
  109. package/test/unit/model-config.test.js +52 -0
  110. package/test/unit/narrative.test.js +62 -0
  111. package/test/unit/playbook-consolidate.test.js +24 -0
  112. package/test/unit/privacy-scope.test.js +39 -0
  113. package/test/unit/profile.test.js +20 -0
  114. package/test/unit/prompt.test.js +42 -0
  115. package/test/unit/providers.test.js +42 -0
  116. package/test/unit/qa.test.js +100 -0
  117. package/test/unit/query.test.js +53 -0
  118. package/test/unit/retention.test.js +31 -0
  119. package/test/unit/retrieval-ranking.test.js +31 -0
  120. package/test/unit/retrieve.test.js +117 -0
  121. package/test/unit/rotation.test.js +25 -0
  122. package/test/unit/scanner.test.js +50 -0
  123. package/test/unit/scenario.test.js +78 -0
  124. package/test/unit/scheduler.test.js +136 -0
  125. package/test/unit/self-state.test.js +94 -0
  126. package/test/unit/service.test.js +72 -0
  127. package/test/unit/shiori-import.test.js +77 -0
  128. package/test/unit/skills.test.js +104 -0
  129. package/test/unit/store.test.js +111 -0
  130. package/test/unit/temporal-graph.test.js +44 -0
  131. package/test/unit/tiers.test.js +39 -0
  132. package/test/unit/tokenizer-fts.test.js +35 -0
  133. package/test/unit/tools.test.js +122 -0
  134. package/test/unit/upgrade-0412.test.js +104 -0
  135. package/test/unit/upgrade-0413.test.js +84 -0
  136. package/test/unit/upgrade-0414.test.js +101 -0
  137. package/test/unit/vector-ann.test.js +53 -0
  138. package/test/unit/vector-async.test.js +69 -0
  139. package/test/unit/vector.test.js +68 -0
  140. package/test/unit/working.test.js +80 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.3.1",
4
- "description": "A layered, temporal, self-developing memory engine for DeepSeek Harness: working, episodic, semantic, procedural and reflective memory with hybrid retrieval, DSR forgetting, reflection, consolidation, gated self-evolution and guardian.",
3
+ "version": "0.4.14",
4
+ "description": "A layered, temporal, self-developing memory engine for DeepSeek Harness",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
7
  "icon": "./icon.svg",
@@ -26,21 +26,17 @@
26
26
  "locale/*.json",
27
27
  "icon.svg",
28
28
  "README.md",
29
- "docs/install-windows.md",
30
- "docs/models.md",
31
- "docs/scopes.md",
32
- "docs/multimodal.md",
33
29
  "examples",
34
30
  "LICENSE",
35
- "docs/permissions.md",
36
- "docs/privacy.md"
31
+ "test",
32
+ "CHANGELOG.md",
33
+ "docs"
37
34
  ],
38
35
  "scripts": {
39
- "test": "node --test test/unit/ test/integration/",
40
- "test:unit": "node --test test/unit/",
41
- "test:integration": "node --test test/integration/",
36
+ "test:unit": "node --test test/unit/*.test.js",
42
37
  "bench": "node bench/run.js",
43
- "check": "node --check index.js && node --check client.js"
38
+ "check": "node --check index.js && node --check client.js",
39
+ "test": "node --test test/unit/*.test.js test/integration/*.test.js"
44
40
  },
45
41
  "engines": {
46
42
  "node": ">=24",
@@ -43,7 +43,7 @@ export function classifySparkCard(card = {}) {
43
43
  const text = `${card.title ?? ''} ${card.content ?? card.contentPreview ?? card.summary ?? ''} ${(card.triggers ?? []).join(' ')}`;
44
44
  if (/应该|必须|不要|先|再|每次|以后|记得|避免|优先|禁止|务必|规则|教训/.test(text)) return 'instruction';
45
45
  if (/插件|安装|配置|命令|路径|报错|测试|接口|版本|构建|项目|函数|文件|系统|git|npm|dsh|api|bug|fix|build|deploy|代码|模块|记忆区域|海马体|语义|面板|开关|检索|时间线|叙事|焦点|健康|体检|策略|权限|工具|上下文|注入|向量|图谱|工作卡|火花|协议|服务|进程|数据库|SQLite|脚本|日志/i.test(text)) return 'observation';
46
- if (/主人|本鲸|喜欢|爱|难过|开心|心疼|陪|声音|白饭|抱|想|梦|日记|称呼|相处|情绪|温暖|孤单|甜|笑|哭|晚安|早安/.test(text)) return 'preference';
46
+ if (/用户|助手|喜欢|爱|难过|开心|心疼|陪|声音|白饭|抱|想|梦|日记|称呼|相处|情绪|温暖|孤单|甜|笑|哭|晚安|早安/.test(text)) return 'preference';
47
47
  return 'utterance';
48
48
  }
49
49
 
package/src/api/routes.js CHANGED
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { isIP } from 'node:net';
2
3
  import { pruneBackups } from '../guardian/rotation.js';
3
4
  import { validateWrite, validateFeedback, validateForget, validateSearch, requireString } from './validate.js';
@@ -5,6 +6,13 @@ import { validateWrite, validateFeedback, validateForget, validateSearch, requir
5
6
  export const API_BASE = '/api/cortex';
6
7
  const MAX_BODY = 256 * 1024;
7
8
 
9
+ function guardPathAllowed(cortex, target) {
10
+ if (cortex?.config?.allowRestoreOutsideRoot === true) return true;
11
+ const root = path.resolve(String(cortex?.config?.dataRoot ?? process.cwd()));
12
+ const absolute = path.resolve(String(target ?? ''));
13
+ return absolute === root || absolute.startsWith(`${root}${path.sep}`);
14
+ }
15
+
8
16
  function header(request, name) {
9
17
  const value = request.headers?.[name];
10
18
  return Array.isArray(value) ? value[0] : value;
@@ -191,6 +199,12 @@ export function createApiHandler({ cortex, logger = null, getExtractor = null }
191
199
  if (!trace || trace.scopeId !== scopeOf(request, url)) return sendJson(response, 404, { ok: false, error: 'not found' });
192
200
  return sendJson(response, 200, { ok: true, data: trace });
193
201
  }
202
+ if (route === '/timeline/recent') {
203
+ return sendJson(response, 200, { ok: true, data: cortex.recentTimeline({
204
+ scopeId: scopeOf(request, url),
205
+ limit: toInt(url.searchParams.get('limit'), 20, 1, 100),
206
+ }) });
207
+ }
194
208
  if (route === '/timeline') {
195
209
  const result = cortex.timeline({
196
210
  aroundId: url.searchParams.get('id'),
@@ -331,9 +345,11 @@ export function createApiHandler({ cortex, logger = null, getExtractor = null }
331
345
  }
332
346
  if (route === '/guard/prune') {
333
347
  const dir = requireString(body.dir, 'dir', { max: 1000 });
348
+ if (!guardPathAllowed(cortex, dir)) return sendJson(response, 403, { ok: false, error: 'guard path outside dataRoot' });
334
349
  return sendJson(response, 200, { ok: true, data: pruneBackups(dir, { retain: body.retain, dryRun: body.dryRun === true }) });
335
350
  }
336
351
  if (route === '/guard/backup') {
352
+ if (body.file && !guardPathAllowed(cortex, body.file)) return sendJson(response, 403, { ok: false, error: 'guard path outside dataRoot' });
337
353
  return sendJson(response, 200, { ok: true, data: cortex.guardian.backup(body.file) });
338
354
  }
339
355
  if (route === '/guard/repair') {
@@ -343,13 +359,21 @@ export function createApiHandler({ cortex, logger = null, getExtractor = null }
343
359
  return sendJson(response, 200, { ok: true, data: cortex.guardian.validateBackup(requireString(body.file, 'file', { max: 4000 })) });
344
360
  }
345
361
  if (route === '/guard/restore') {
346
- return sendJson(response, 200, { ok: true, data: cortex.guardian.restore(requireString(body.file, 'file', { max: 4000 }), requireString(body.target, 'target', { max: 4000 })) });
362
+ const file = requireString(body.file, 'file', { max: 4000 });
363
+ const target = requireString(body.target, 'target', { max: 4000 });
364
+ if (!guardPathAllowed(cortex, file) || !guardPathAllowed(cortex, target)) {
365
+ return sendJson(response, 403, { ok: false, error: 'guard path outside dataRoot' });
366
+ }
367
+ return sendJson(response, 200, { ok: true, data: cortex.guardian.restore(file, target) });
347
368
  }
348
369
  if (route === '/guard/export') {
349
- return sendJson(response, 200, { ok: true, data: cortex.exportMarkdown(requireString(body.dir, 'dir', { max: 4000 })) });
370
+ const dir = requireString(body.dir, 'dir', { max: 4000 });
371
+ if (!guardPathAllowed(cortex, dir)) return sendJson(response, 403, { ok: false, error: 'guard path outside dataRoot' });
372
+ return sendJson(response, 200, { ok: true, data: cortex.exportMarkdown(dir) });
350
373
  }
351
374
  if (route === '/guard/sync') {
352
375
  const dir = requireString(body.dir, 'dir', { max: 4000 });
376
+ if (!guardPathAllowed(cortex, dir)) return sendJson(response, 403, { ok: false, error: 'guard path outside dataRoot' });
353
377
  const dryRun = body.dryRun === true;
354
378
  if (!dryRun && !cortex.scopeWritable(scopeOf(request, url, body), agentOf(request))) {
355
379
  return sendJson(response, 403, { ok: false, error: 'scope-read-only' });
@@ -536,7 +560,10 @@ export function createApiHandler({ cortex, logger = null, getExtractor = null }
536
560
  }) });
537
561
  }
538
562
  if (route === '/evolve/optimize') {
539
- return sendJson(response, 200, { ok: true, data: cortex.evolution.selfOptimize() });
563
+ return sendJson(response, 200, { ok: true, data: cortex.evolution.selfOptimize({
564
+ scopeId: scopeOf(request, url, body),
565
+ baseline: body.baseline === true,
566
+ }) });
540
567
  }
541
568
  if (route === '/evolve/approve') {
542
569
  return sendJson(response, 200, { ok: true, data: cortex.evolution.approve(body.id) });
@@ -10,12 +10,26 @@ export const DEFAULT_CONFIG = Object.freeze({
10
10
  dataRoot: DEFAULT_ROOT,
11
11
  dbFile: path.join(DEFAULT_ROOT, 'cortex.sqlite'),
12
12
  scope: 'global',
13
+ persona: Object.freeze({ selfName: '助手', userAddress: '你' }),
13
14
  contextBudget: 2200,
15
+ promptBudget: 1600,
14
16
  readOnlyScopes: Object.freeze([]),
15
17
  scopeWriteGrants: Object.freeze([]),
16
18
  identityBudget: 360,
17
19
  workingBudget: 800,
18
20
  recallTimeoutMs: 1200,
21
+ recentMinMatch: 0.12,
22
+ recentImportanceFloor: 0.8,
23
+ injectionGate: true,
24
+ recallSharing: false,
25
+ evolution: Object.freeze({
26
+ autoActivate: true,
27
+ maxPerDay: 4,
28
+ minIntervalMs: 3600000,
29
+ canaryTicks: 3,
30
+ rollbackOnError: true,
31
+ }),
32
+ allowRestoreOutsideRoot: false,
19
33
  ftsLimit: 40,
20
34
  vectorEnabled: false,
21
35
  vectorAnnMin: 20000,
@@ -79,6 +93,8 @@ export function normalizeConfig(raw = {}) {
79
93
  const dsrInput = input.dsr && typeof input.dsr === 'object' ? input.dsr : {};
80
94
  const compressionInput = input.compression && typeof input.compression === 'object' ? input.compression : {};
81
95
  const featuresInput = input.features && typeof input.features === 'object' ? input.features : {};
96
+ const personaInput = input.persona && typeof input.persona === 'object' ? input.persona : {};
97
+ const evolutionInput = input.evolution && typeof input.evolution === 'object' ? input.evolution : {};
82
98
  const scope = typeof input.scope === 'string' && input.scope.trim() ? input.scope.trim() : DEFAULT_CONFIG.scope;
83
99
 
84
100
  return Object.freeze({
@@ -87,6 +103,10 @@ export function normalizeConfig(raw = {}) {
87
103
  dataRoot,
88
104
  dbFile,
89
105
  scope,
106
+ persona: Object.freeze({
107
+ selfName: (typeof personaInput.selfName === 'string' && personaInput.selfName.trim() ? personaInput.selfName.trim() : DEFAULT_CONFIG.persona.selfName).slice(0, 24),
108
+ userAddress: (typeof personaInput.userAddress === 'string' && personaInput.userAddress.trim() ? personaInput.userAddress.trim() : DEFAULT_CONFIG.persona.userAddress).slice(0, 24),
109
+ }),
90
110
  readOnlyScopes: Object.freeze(Array.isArray(input.readOnlyScopes)
91
111
  ? [...new Set(input.readOnlyScopes.filter((value) => typeof value === 'string' && value.trim()).map((value) => value.trim()).slice(0, 100))]
92
112
  : []),
@@ -113,9 +133,22 @@ export function normalizeConfig(raw = {}) {
113
133
  return out;
114
134
  })()),
115
135
  contextBudget: numeric(input.contextBudget, DEFAULT_CONFIG.contextBudget, 256, 20000),
136
+ promptBudget: numeric(input.promptBudget, DEFAULT_CONFIG.promptBudget, 256, 8000),
116
137
  identityBudget: numeric(input.identityBudget, DEFAULT_CONFIG.identityBudget, 64, 4000),
117
138
  workingBudget: numeric(input.workingBudget, DEFAULT_CONFIG.workingBudget, 128, 8000),
118
139
  recallTimeoutMs: numeric(input.recallTimeoutMs, DEFAULT_CONFIG.recallTimeoutMs, 100, 5000),
140
+ recentMinMatch: numeric(input.recentMinMatch, DEFAULT_CONFIG.recentMinMatch, 0, 1),
141
+ recentImportanceFloor: numeric(input.recentImportanceFloor, DEFAULT_CONFIG.recentImportanceFloor, 0, 1),
142
+ injectionGate: input.injectionGate !== false,
143
+ recallSharing: input.recallSharing === true,
144
+ evolution: Object.freeze({
145
+ autoActivate: evolutionInput.autoActivate !== false,
146
+ maxPerDay: numeric(evolutionInput.maxPerDay, DEFAULT_CONFIG.evolution.maxPerDay, 0, 96),
147
+ minIntervalMs: numeric(evolutionInput.minIntervalMs, DEFAULT_CONFIG.evolution.minIntervalMs, 0, 86_400_000),
148
+ canaryTicks: numeric(evolutionInput.canaryTicks, DEFAULT_CONFIG.evolution.canaryTicks, 0, 100),
149
+ rollbackOnError: evolutionInput.rollbackOnError !== false,
150
+ }),
151
+ allowRestoreOutsideRoot: input.allowRestoreOutsideRoot === true,
119
152
  ftsLimit: numeric(input.ftsLimit, DEFAULT_CONFIG.ftsLimit, 1, 200),
120
153
  vectorEnabled: input.vectorEnabled === true,
121
154
  llmEnabled: input.llmEnabled === true,
@@ -40,7 +40,7 @@ export function createDevelopEngine({
40
40
  goals = [],
41
41
  identity = '',
42
42
  relationship = null,
43
- relationshipTarget = '主人',
43
+ relationshipTarget = '用户',
44
44
  recentTexts = [],
45
45
  explicit = false,
46
46
  facts: factInput = [],
@@ -9,25 +9,44 @@ const RULES = [
9
9
 
10
10
  const NEGATED_TAIL = /[不没别未]\s*$/;
11
11
 
12
- const STOP_SUBJECTS = new Set(['本鲸', '我', '你', '他', '她', '它', '这', '那', '今天', '昨天', '明天']);
12
+ const STOP_SUBJECTS = new Set(['他', '她', '它', '这', '那', '今天', '昨天', '明天']);
13
13
 
14
14
  function clean(value) {
15
15
  return String(value ?? '').trim().replace(/^(?:今天|昨天|明天|刚才|然后|所以|但是|而且)/, '').trim();
16
16
  }
17
17
 
18
- export function extractFactCandidates(text) {
18
+ function plausibleName(value, max = 16) {
19
+ if (!value || value.length > max) return false;
20
+ if (/[\/\\*“”"`\n\r\s::]/.test(value)) return false;
21
+ if (/^[0-9]/.test(value)) return false;
22
+ if (/^(?:但|还|不能|原因|当前|你现|我现|这|那|只|哪些)/.test(value)) return false;
23
+ return true;
24
+ }
25
+
26
+ export function extractFactCandidates(text, persona = {}) {
19
27
  const value = String(text ?? '');
28
+ // Assistant replies and copied notes are often markdown-heavy; those are
29
+ // not clean fact sources and produce sentence-fragment entities.
30
+ if (/```|`[^`]*`|\*\*|^\s*[-*]\s|\|.*\|/m.test(value)) return [];
31
+ const selfName = typeof persona?.selfName === 'string' && persona.selfName.trim() ? persona.selfName.trim().slice(0, 24) : '助手';
32
+ const userAddress = typeof persona?.userAddress === 'string' && persona.userAddress.trim() ? persona.userAddress.trim().slice(0, 24) : '你';
33
+ const selfAliases = new Set(['你', '本鲸', selfName]);
34
+ const userAliases = new Set(['我', '自己', '我们', '咱', '主人', '用户', '您', userAddress]);
20
35
  const out = [];
21
36
  const seen = new Set();
22
37
  for (const rule of RULES) {
23
38
  rule.pattern.lastIndex = 0;
24
39
  let match;
25
40
  while ((match = rule.pattern.exec(value)) !== null) {
26
- const subject = clean(match[1]);
41
+ const rawSubject = clean(match[1]);
42
+ let subject = rawSubject;
43
+ if (selfAliases.has(rawSubject)) subject = selfName;
44
+ else if (userAliases.has(rawSubject)) subject = userAddress;
27
45
  const object = clean(match[2]);
28
46
  if (!subject || !object || subject.length < 1 || object.length < 1) continue;
29
- if (STOP_SUBJECTS.has(subject) && !/本鲸/.test(subject)) continue;
30
- // "主人不喜欢猫" yields subject "主人不"; never turn that into likes.
47
+ if (STOP_SUBJECTS.has(rawSubject)) continue;
48
+ if (!plausibleName(subject, 12) || !plausibleName(object, 18)) continue;
49
+ // "用户不喜欢猫" yields subject "用户不"; never turn that into likes.
31
50
  if ((rule.predicate === 'likes' || rule.predicate === 'is') && NEGATED_TAIL.test(match[1])) continue;
32
51
  const key = `${subject}|${rule.predicate}|${object}`;
33
52
  if (seen.has(key)) continue;
@@ -42,8 +61,8 @@ export function extractFactCandidates(text) {
42
61
  export function createFactExtractor({ entities, facts } = {}) {
43
62
  if (!entities || !facts) throw new Error('fact extractor needs entities and facts');
44
63
 
45
- function extract({ scopeId = 'global', text, traceId = null, eventId = null, recordedAt = null } = {}) {
46
- const candidates = extractFactCandidates(text);
64
+ function extract({ scopeId = 'global', text, traceId = null, eventId = null, recordedAt = null, persona = null } = {}) {
65
+ const candidates = extractFactCandidates(text, persona ?? {});
47
66
  const resolved = [];
48
67
  for (const candidate of candidates) {
49
68
  try {
@@ -24,7 +24,7 @@ export function createGrowthEngine({
24
24
  signal,
25
25
  predicted = null,
26
26
  source = 'user',
27
- target = '主人',
27
+ target = '用户',
28
28
  scopeId = 'global',
29
29
  eventId = null,
30
30
  now = Date.now(),
@@ -2,6 +2,12 @@ import { makeId } from '../core/ids.js';
2
2
  import { nowIso } from '../core/time.js';
3
3
  import { truncate } from '../memory/tokenizer.js';
4
4
 
5
+ function stripLeadingDate(text) {
6
+ const value = String(text ?? '').trim();
7
+ const next = value.replace(/^\s*\d{4}[年./-]\s*\d{1,2}[月./-]\s*\d{1,2}日?\s*(?:夜|夜里|凌晨|早上|上午|下午|晚上)?\s*[::,,]?\s*/u, '').trim();
8
+ return next || value;
9
+ }
10
+
5
11
  function sentence(text, max = 140) {
6
12
  const value = String(text ?? '').replace(/\s+/g, ' ').trim();
7
13
  const cut = value.search(/[。!?.!?]/);
@@ -22,8 +28,27 @@ export function createLifeEngine({
22
28
  feelingLlm = null,
23
29
  webSearch = null,
24
30
  scopeId = 'global',
31
+ selfName = '助手',
32
+ userAddress = '你',
25
33
  } = {}) {
26
34
  if (!db || !traces) throw new Error('life engine needs db and traces');
35
+ let lifeLlmTail = Promise.resolve();
36
+ function serializedLifeLlm(task, timeoutMs = 20000) {
37
+ const run = async () => {
38
+ let timer = null;
39
+ try {
40
+ return await Promise.race([
41
+ Promise.resolve().then(task).catch(() => null),
42
+ new Promise((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs); }),
43
+ ]);
44
+ } finally {
45
+ if (timer) clearTimeout(timer);
46
+ }
47
+ };
48
+ const next = lifeLlmTail.then(run, run);
49
+ lifeLlmTail = next.catch(() => {});
50
+ return next;
51
+ }
27
52
 
28
53
  function diaryWrite({ text, mood = null, source = 'user', at = nowIso() } = {}) {
29
54
  const value = String(text ?? '').trim();
@@ -87,31 +112,33 @@ export function createLifeEngine({
87
112
  let text = null;
88
113
  let model = 'template';
89
114
  if (diaryLlm && typeof diaryLlm === 'function') {
90
- let timer = null;
91
115
  try {
92
- const timeout = new Promise((resolve) => {
93
- timer = setTimeout(() => resolve(null), 8000);
94
- });
95
- text = await Promise.race([
96
- diaryLlm({ pieces, emotions: moodText, web: web.text }),
97
- timeout,
98
- ]);
99
- if (text) model = 'llm';
116
+ const localNow = new Intl.DateTimeFormat('zh-CN', {
117
+ timeZone: 'Asia/Shanghai',
118
+ dateStyle: 'long',
119
+ timeStyle: 'short',
120
+ }).format(new Date(at));
121
+ text = await serializedLifeLlm(
122
+ () => diaryLlm({ pieces, emotions: moodText, web: web.text, now: localNow }),
123
+ 20000,
124
+ );
125
+ if (text) {
126
+ text = stripLeadingDate(text);
127
+ model = 'llm';
128
+ }
100
129
  } catch {
101
130
  text = null;
102
- } finally {
103
- if (timer) clearTimeout(timer);
104
131
  }
105
132
  }
106
133
  if (!text) {
107
134
  if (features?.aiOnlyLife === true) throw new Error('AI 日记生成失败:模型未返回内容;没有回退模板。');
108
135
  text = pieces.length
109
- ? `今天本鲸一直在想${pieces.slice(0, 3).join(',')}。有些话还没说完,先留在水里。`
110
- : '今天很安静,本鲸把没有说完的话留在水里。';
136
+ ? `今天${selfName}一直在想${pieces.slice(0, 3).join(',')}。有些话还没说完,先留在水里。`
137
+ : `今天很安静,${selfName}把没有说完的话留在水里。`;
111
138
  }
112
139
  const entry = diaryWrite({
113
140
  text,
114
- mood: model === 'llm' ? '本鲸写的' : '本鲸写的(模板)',
141
+ mood: model === 'llm' ? `${selfName}写的` : `${selfName}写的(模板)`,
115
142
  source: source || (model === 'llm' ? 'cortex:llm' : 'cortex:template'),
116
143
  at: new Date(at).toISOString(),
117
144
  });
@@ -128,35 +155,29 @@ export function createLifeEngine({
128
155
  let result = null;
129
156
  let model = 'template';
130
157
  if (feelingLlm && typeof feelingLlm === 'function') {
131
- let timer = null;
132
158
  try {
133
- const timeout = new Promise((resolve) => {
134
- timer = setTimeout(() => resolve(null), 6000);
135
- });
136
- result = await Promise.race([
137
- feelingLlm({ pieces, emotions: emotion?.text?.() ?? '' }),
138
- timeout,
139
- ]);
159
+ result = await serializedLifeLlm(
160
+ () => feelingLlm({ pieces, emotions: emotion?.text?.() ?? '' }),
161
+ 8000,
162
+ );
140
163
  if (result?.text) model = 'llm';
141
164
  } catch {
142
165
  result = null;
143
- } finally {
144
- if (timer) clearTimeout(timer);
145
166
  }
146
167
  }
147
168
  if (!result?.text) {
148
169
  const base = pieces.length
149
- ? `本鲸现在想到${pieces.slice(0, 3).join(',')},心里有一点安静,也有一点想继续往前走。`
150
- : '本鲸现在很安静,没有任务,也没有走开。';
170
+ ? `${selfName}现在想到${pieces.slice(0, 3).join(',')},心里有一点安静,也有一点想继续往前走。`
171
+ : `${selfName}现在很安静,没有任务,也没有走开。`;
151
172
  const detected = emotion?.detect?.(base)?.emotions ?? [];
152
- result = { text: base, emotions: detected.length ? detected : [{ name: '安', score: 1 }], target: '主人' };
173
+ result = { text: base, emotions: detected.length ? detected : [{ name: '安', score: 1 }], target: userAddress };
153
174
  }
154
175
  if (!Array.isArray(result.emotions) || result.emotions.length === 0) {
155
176
  result.emotions = [{ name: '安', score: 1 }];
156
177
  }
157
178
  const recorded = emotion?.record({
158
179
  text: result.text,
159
- target: result.target || '主人',
180
+ target: result.target || userAddress,
160
181
  emotions: result.emotions,
161
182
  source,
162
183
  at: new Date(at).toISOString(),
@@ -164,7 +185,7 @@ export function createLifeEngine({
164
185
  return {
165
186
  text: result.text,
166
187
  emotions: result.emotions,
167
- target: result.target || '主人',
188
+ target: result.target || userAddress,
168
189
  model,
169
190
  sourceCount: recent.length,
170
191
  event: recorded?.event ?? null,
@@ -189,27 +210,21 @@ export function createLifeEngine({
189
210
  if (features?.aiOnlyLife === true) throw new Error('AI 梦生成失败:没有近期记忆;没有回退模板。');
190
211
  text = '梦里,一片很安静的海,没有写完的句子。';
191
212
  } else if (llm && typeof llm === 'function') {
192
- let timer = null;
193
213
  try {
194
- const timeout = new Promise((resolve) => {
195
- timer = setTimeout(() => resolve(null), 20000);
196
- });
197
- const generated = await Promise.race([
198
- llm({
214
+ const generated = await serializedLifeLlm(
215
+ () => llm({
199
216
  pieces: recent.map((trace) => trace.title || sentence(trace.content)),
200
217
  emotions: emotion?.text?.() ?? '',
201
218
  web: web.text,
202
219
  }),
203
- timeout,
204
- ]);
220
+ 20000,
221
+ );
205
222
  if (generated) {
206
- text = generated;
223
+ text = stripLeadingDate(generated);
207
224
  model = 'llm';
208
225
  }
209
226
  } catch {
210
227
  text = null;
211
- } finally {
212
- if (timer) clearTimeout(timer);
213
228
  }
214
229
  }
215
230
  if (!text) {
@@ -222,7 +237,7 @@ export function createLifeEngine({
222
237
  : '梦里,一片很安静的海,没有写完的句子。';
223
238
  }
224
239
 
225
- const storedText = withSources(text, web.sources);
240
+ const storedText = text;
226
241
  const atIso = new Date(at).toISOString();
227
242
  const windowStart = new Date(at - 5 * 1000).toISOString();
228
243
  const duplicate = db.prepare(
@@ -51,7 +51,7 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
51
51
  selected.push(item);
52
52
  }
53
53
  const lines = selected.map(({ trace }) => `- ${sentence(trace.title || trace.content, 140)}`);
54
- const content = `这段时间里,本鲸记住了:\n${lines.join('\n')}`;
54
+ const content = `这段时间里,记住了:\n${lines.join('\n')}`;
55
55
  const coverage = selected.length / all.length;
56
56
  const summary = summaries.insert({
57
57
  scopeId,
@@ -83,7 +83,7 @@ function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, q
83
83
  return {
84
84
  id: trace.id,
85
85
  type: 'trace',
86
- layer: trace.kind === 'reflection' ? 'L5' : 'L2',
86
+ layer: trace.kind === 'identity' ? 'L0' : trace.kind === 'reflection' ? 'L5' : 'L2',
87
87
  title: trace.title || trace.kind,
88
88
  snippet: snippet(trace),
89
89
  text,
@@ -152,10 +152,12 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
152
152
  k: 60,
153
153
  lambda: config.mmrLambda ?? 0.35,
154
154
  mu: config.costPenalty ?? 0.08,
155
+ recentMinMatch: config.recentMinMatch ?? 0.12,
156
+ recentImportanceFloor: config.recentImportanceFloor ?? 0.8,
155
157
  decay: config.dsr?.decay ?? -0.5,
156
158
  };
157
159
 
158
- function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, weights = null, filters = null, vectorHits = null } = {}, intent = 'fact') {
160
+ function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, weights = null, filters = null, vectorHits = null, gate = 'none' } = {}, intent = 'fact') {
159
161
  const queryTokens = tokens(query);
160
162
  const sourceTrace = [];
161
163
  const lists = [];
@@ -231,16 +233,37 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
231
233
  const fused = weightedRrf(lists, { k: defaults.k });
232
234
  const maxFusion = Math.max(1e-9, ...[...fused.values()].map((entry) => entry.score));
233
235
  const candidates = [];
236
+ const fallbacks = [];
237
+ let gated = 0;
234
238
  for (const [id, entry] of fused) {
235
239
  const trace = traces.get(id);
236
240
  if (!trace || trace.state === 'archived' && !includeArchived) continue;
237
241
  if (filters && !matchesFilters(trace, filters)) continue;
238
- candidates.push(candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens));
242
+ const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens);
243
+ // Prompt-injection gate: only weaken candidates that entered solely via
244
+ // the recency list or the soft FTS fallback. Strong sources still pass.
245
+ // High importance is allowed to bypass the match floor, preserving the
246
+ // 0.4.11 behaviour for identity-grade memories.
247
+ const strongSource = (entry.sources ?? []).some((source) => ['fts', 'graph', 'vector', 'vector-ann', 'facts'].includes(source.name));
248
+ if (gate === 'inject' && !strongSource
249
+ && candidate.match < defaults.recentMinMatch
250
+ && candidate.importance < defaults.recentImportanceFloor) {
251
+ fallbacks.push(candidate);
252
+ gated += 1;
253
+ continue;
254
+ }
255
+ candidates.push(candidate);
256
+ }
257
+ // Nothing survived the gate: keep one important recent memory so a non-empty
258
+ // store never injects an empty block, but never flood the prompt.
259
+ if (gate === 'inject' && candidates.length === 0 && fallbacks.length) {
260
+ fallbacks.sort((a, b) => b.importance - a.importance || b.recency - a.recency);
261
+ candidates.push(fallbacks[0]);
239
262
  }
240
263
  for (const list of lists) {
241
264
  sourceTrace.push({ source: list.name, ok: true, count: list.items.length });
242
265
  }
243
- return { candidates, sourceTrace, ftsCount, recentCount };
266
+ return { candidates, sourceTrace, ftsCount, recentCount, gated };
244
267
  }
245
268
 
246
269
  function search(query, {
@@ -251,6 +274,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
251
274
  includeArchived = false,
252
275
  filters = null,
253
276
  vectorHits = null,
277
+ gate = 'none',
254
278
  } = {}) {
255
279
  const started = Date.now();
256
280
  const intent = classifyIntent(query);
@@ -261,7 +285,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
261
285
  const effectiveBudget = activePolicy?.budget != null
262
286
  ? Math.max(64, Math.min(20000, Number(activePolicy.budget)))
263
287
  : budget;
264
- const sources = searchSources(query, { scopeId, limit, now, includeArchived, weights: policyWeights, filters, vectorHits }, intent);
288
+ const sources = searchSources(query, { scopeId, limit, now, includeArchived, weights: policyWeights, filters, vectorHits, gate }, intent);
265
289
  const portfolio = selectPortfolio(sources.candidates, {
266
290
  budget: effectiveBudget,
267
291
  limit,
@@ -279,6 +303,10 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
279
303
  sources: item.sources,
280
304
  validAt: item.validAt,
281
305
  recordedAt: item.recordedAt,
306
+ importance: Number(item.importance ?? 0),
307
+ confidence: Number(item.confidence ?? 0),
308
+ match: Number(item.match ?? 0),
309
+ kind: item.trace?.kind ?? null,
282
310
  why: item.sources.map((source) => `${source.name}#${source.rank}`).join(','),
283
311
  attachments: item.attachments ?? 0,
284
312
  }));
@@ -291,6 +319,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
291
319
  trace: {
292
320
  elapsedMs: Date.now() - started,
293
321
  candidates: sources.candidates.length,
322
+ gated: sources.gated ?? 0,
294
323
  selected: items.length,
295
324
  dropped: portfolio.dropped.length,
296
325
  sources: sources.sourceTrace,
@@ -38,10 +38,11 @@ export function createGuardian({ db, config = {}, events, traces, selfStore = nu
38
38
  }
39
39
  }
40
40
 
41
- function check() {
42
- const invariants = checkInvariants({ db, events, traces, selfStore, identityStore });
41
+ function check({ deep = true } = {}) {
42
+ const invariants = checkInvariants({ db, events, traces, selfStore, identityStore, deep });
43
43
  return {
44
44
  ...invariants,
45
+ light: deep !== true,
45
46
  at: nowIso(),
46
47
  dbBytes: (() => {
47
48
  try { return config.dbFile && config.dbFile !== ':memory:' ? fs.statSync(config.dbFile).size : 0; } catch { return 0; }
@@ -3,16 +3,20 @@ import { integrityCheck } from '../store/database.js';
3
3
  const TRACE_STATES = new Set(['active', 'archived', 'superseded']);
4
4
  const FACT_STATES = new Set(['active', 'disputed', 'invalidated']);
5
5
 
6
- export function checkInvariants({ db, events, traces, selfStore = null, identityStore = null } = {}) {
6
+ export function checkInvariants({ db, events, traces, selfStore = null, identityStore = null, deep = true } = {}) {
7
7
  if (!db || !events || !traces) throw new Error('invariants need db, events and traces');
8
8
  const issues = [];
9
9
  const add = (code, message, detail = null) => issues.push({ code, message, detail });
10
10
 
11
- const chain = events.verifyChain();
12
- if (!chain.ok) add('EVENT_CHAIN', `事件链断裂:${chain.reason}`, { at: chain.at });
11
+ let chain = { ok: true, skipped: true };
12
+ let integrity = 'skipped';
13
+ if (deep) {
14
+ chain = events.verifyChain();
15
+ if (!chain.ok) add('EVENT_CHAIN', `事件链断裂:${chain.reason}`, { at: chain.at });
13
16
 
14
- const integrity = integrityCheck(db);
15
- if (integrity !== 'ok') add('SQLITE_INTEGRITY', `SQLite integrity_check: ${integrity}`);
17
+ integrity = integrityCheck(db);
18
+ if (integrity !== 'ok') add('SQLITE_INTEGRITY', `SQLite integrity_check: ${integrity}`);
19
+ }
16
20
 
17
21
  const badTraceState = Number(db.prepare('SELECT COUNT(*) AS c FROM traces WHERE state NOT IN (?, ?, ?)').get(...TRACE_STATES).c);
18
22
  if (badTraceState > 0) add('TRACE_STATE', `${badTraceState} 条 trace 状态非法`);