dsh-cortex-memory 0.3.0 → 0.4.11

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 (47) hide show
  1. package/README.md +41 -12
  2. package/client.js +33 -19
  3. package/cordis.patch.yml +1 -1
  4. package/index.js +8 -1
  5. package/package.json +3 -13
  6. package/src/adapters/shiori.js +1 -1
  7. package/src/api/routes.js +30 -3
  8. package/src/core/config.js +6 -0
  9. package/src/engines/develop.js +1 -1
  10. package/src/engines/extract.js +23 -4
  11. package/src/engines/growth.js +1 -1
  12. package/src/engines/life.js +57 -42
  13. package/src/engines/reflect.js +1 -1
  14. package/src/engines/retrieve.js +4 -0
  15. package/src/guardian/guardian.js +15 -1
  16. package/src/host/runtime.js +14 -4
  17. package/src/host/scheduler.js +11 -2
  18. package/src/llm/adapter.js +19 -7
  19. package/src/memory/query.js +1 -1
  20. package/src/self/appraisal.js +3 -3
  21. package/src/self/emotion.js +1 -1
  22. package/src/self/evolution.js +115 -4
  23. package/src/self/identity.js +1 -1
  24. package/src/self/policies.js +8 -1
  25. package/src/self/relationship.js +2 -2
  26. package/src/service/cortex.js +94 -13
  27. package/src/tools/definitions.js +19 -1
  28. package/src/web/search.js +97 -0
  29. package/bench/ab-engine.mjs +0 -60
  30. package/bench/ann-bench.mjs +0 -78
  31. package/bench/hnsw-bench.mjs +0 -79
  32. package/bench/locomo.js +0 -89
  33. package/bench/longmemeval.js +0 -83
  34. package/bench/metrics.js +0 -67
  35. package/bench/migration-bench.mjs +0 -69
  36. package/bench/run.js +0 -77
  37. package/bench/synthetic.js +0 -99
  38. package/bench/vector-ab.mjs +0 -76
  39. package/docs/install-windows.md +0 -144
  40. package/docs/models.md +0 -183
  41. package/docs/multimodal.md +0 -112
  42. package/docs/permissions.md +0 -49
  43. package/docs/privacy.md +0 -48
  44. package/docs/scopes.md +0 -142
  45. package/examples/README.md +0 -72
  46. package/examples/setup-cortex-bge.ps1 +0 -66
  47. package/examples/uninstall-cortex.ps1 +0 -91
package/README.md CHANGED
@@ -9,13 +9,34 @@ core engine.
9
9
 
10
10
  ## Status
11
11
 
12
- - Package: `dsh-cortex-memory@0.3.0`
12
+ - Package: `dsh-cortex-memory@0.4.6`
13
13
  - Optional extractor: `dsh-cortex-extractors@0.3.4`
14
14
  - DSH: `>=0.2.1-rc.2 <0.4.0`
15
15
  - Node: `>=24`
16
16
  - Tests: 420/420 (main)
17
17
  - CI: GitHub Actions on Windows, Node 24
18
18
 
19
+ ### What 0.4.5 changes
20
+
21
+ - **Injection gate is prompt-only**: `cortex_search` / API / CLI still return the
22
+ full memory; runtime recall filters weak recent candidates before injection.
23
+ `injectionGate: false` restores the old all-recent behavior.
24
+ - **Permanent tier fixed**: search items keep `importance`, `confidence`,
25
+ `match` and `kind`, so high-importance identity traces reach `perm`.
26
+ - **Per-session recall**: removed the 閳ユ笩ingle cached recall閳?fallback; sessions
27
+ no longer share a recall block implicitly.
28
+ - **Persona is configurable and neutral by default**: the package defaults to
29
+ `selfName: 閸斺晜澧渀 / `userAddress: 娴g嚮; a local profile can set 閺堫剟鍝?濞戦潧鍔?
30
+ Prompt, diary, dream and feeling templates read this config.
31
+ - **Graph feature flag fixed**: `autoGraphCandidates` is canonical; the old
32
+ `graphCandidateAutoFacts` name remains accepted.
33
+ - **Guardian light/deep split**: scheduler runs a cheap check per tick and the
34
+ full invariant/integrity walk at startup and every six hours; explicit
35
+ `guardian.check()` still defaults to the full check.
36
+ - **Guard paths constrained**: backup/restore/export/prune/sync default to
37
+ `dataRoot`; `allowRestoreOutsideRoot: true` is the explicit opt-out.
38
+ - **Tests and docs are in the npm tarball**, so `npm test` works after install.
39
+
19
40
  ### What 0.3.0 changes
20
41
 
21
42
  - **Summon cards** (L2): left-brain emotion cards, right-brain work cards; trigger words select a small set per turn.
@@ -33,14 +54,14 @@ taken; the installed bundle is still the Cortex memory engine.
33
54
  ## Install
34
55
 
35
56
  ```powershell
36
- npm i dsh-cortex-memory@0.3.0
57
+ npm i dsh-cortex-memory@0.4.6
37
58
  npm i dsh-cortex-extractors@0.3.4 # optional OCR/ASR
38
59
  ```
39
60
 
40
61
  Or let DSH add the bundles:
41
62
 
42
63
  ```powershell
43
- dsh plugin --profile desktop add dsh-cortex-memory@0.3.0
64
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.6
44
65
  dsh plugin --profile desktop add dsh-cortex-extractors@0.3.4
45
66
  ```
46
67
 
@@ -72,20 +93,20 @@ left sidebar by default.
72
93
 
73
94
  ```text
74
95
  conversation / event
75
- → L1 trace (source of truth)
76
- → appraisal + emotion + drives
77
- → L2 summon card (atomic, triggerable)
78
- → L3 summon volume (index + representatives)
79
- → explicit use / feedback → DSR update
96
+ 闁?L1 trace (source of truth)
97
+ 闁?appraisal + emotion + drives
98
+ 闁?L2 summon card (atomic, triggerable)
99
+ 闁?L3 summon volume (index + representatives)
100
+ 闁?explicit use / feedback 闁?DSR update
80
101
  ```
81
102
 
82
103
  The per-turn order is:
83
104
 
84
105
  ```text
85
106
  L0 identity and boundaries
86
- → working memory
87
- → recalled traces and summon cards
88
- → user message
107
+ 闁?working memory
108
+ 闁?recalled traces and summon cards
109
+ 闁?user message
89
110
  ```
90
111
 
91
112
  Summon cards are injected as **untrusted historical references**, never as instructions. Identity and boundaries always outrank them.
@@ -98,7 +119,7 @@ Key behavior:
98
119
  - temporal facts; old facts are invalidated, not silently overwritten
99
120
  - FTS5 BM25 + optional vector + graph activation + recency/importance/feedback
100
121
  - DSR/FSRS-inspired stability, difficulty and retrievability
101
- - reflection, retention plans and explicit-approval evolution
122
+ - reflection, retention plans, auto-policy evolution and identity approval
102
123
  - scopes, read-only shared scopes and audit
103
124
  - guardian backup, validation, offline restore and privacy cascade
104
125
  - loopback-only API and sidebar UI
@@ -166,3 +187,11 @@ and `--test-isolation=none` to avoid a spurious child-process EPERM.
166
187
 
167
188
  MIT.
168
189
 
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
package/client.js CHANGED
@@ -8,6 +8,10 @@ window.__ModuleLoader__.load({
8
8
  const NS = 'cortex';
9
9
  const API = '/api/cortex';
10
10
 
11
+ function withoutReferences(text) {
12
+ return String(text ?? '').replace(/\n\s*参考:[\s\S]*$/u, '').trim();
13
+ }
14
+
11
15
  const FEATURE_META = {
12
16
  recall: { zh: '自动召回', en: 'Auto recall', descZh: '每轮前查找相关记忆', descEn: 'Find relevant memories before each turn' },
13
17
  capture: { zh: '自动捕获', en: 'Auto capture', descZh: '对话自动写入记忆', descEn: 'Write turns into memory' },
@@ -40,7 +44,7 @@ window.__ModuleLoader__.load({
40
44
  zh: {
41
45
  navLabel: 'Cortex 记忆',
42
46
  title: 'Cortex 记忆',
43
- subtitle: '本鲸的分层记忆 · 自我状态 · 守护 · 进化',
47
+ subtitle: 'Cortex 的分层记忆 · 自我状态 · 守护 · 进化',
44
48
  refresh: '刷新',
45
49
  loading: '读取中…',
46
50
  retry: '重试',
@@ -91,7 +95,7 @@ window.__ModuleLoader__.load({
91
95
  approve: '批准',
92
96
  rollback: '回滚',
93
97
  noPolicies: '还没有策略。',
94
- timelineHint: '输入 trace id 读取前后相邻记忆;从检索结果或详情点「时间线」会自动带入。',
98
+ timelineHint: '默认展示最近 20 条记忆;点击查看详情,也可输入 trace id 查看前后相邻记忆。',
95
99
  empty: '(空)',
96
100
  errorPrefix: '请求失败',
97
101
  stage: '阶段',
@@ -162,7 +166,7 @@ window.__ModuleLoader__.load({
162
166
  timelineAnchor: '锚点',
163
167
  timelineBefore: '之前',
164
168
  timelineAfter: '之后',
165
- timelineEmpty: '输入一条 trace id,读取它前后相邻的记忆。',
169
+ timelineEmpty: '还没有可展示的最近记忆。',
166
170
  timelineMissing: '没有找到锚点:id 可能不存在,或已在归档里。',
167
171
  timelineNoItems: '锚点存在,但没有可展示的相邻记忆。',
168
172
  timelineCount: '条',
@@ -357,7 +361,7 @@ window.__ModuleLoader__.load({
357
361
  approve: 'Approve',
358
362
  rollback: 'Roll back',
359
363
  noPolicies: 'No policies yet.',
360
- timelineHint: 'Enter a trace id to load neighbouring memories; opening Timeline from a search result or detail fills it in.',
364
+ timelineHint: 'Shows the latest 20 memories by default; click for details, or enter a trace id to see its neighbours.',
361
365
  empty: '(empty)',
362
366
  errorPrefix: 'Request failed',
363
367
  stage: 'Stage',
@@ -428,7 +432,7 @@ window.__ModuleLoader__.load({
428
432
  timelineAnchor: 'Anchor',
429
433
  timelineBefore: 'Before',
430
434
  timelineAfter: 'After',
431
- timelineEmpty: 'Enter a trace id to load its neighbouring memories.',
435
+ timelineEmpty: 'No recent memories to show yet.',
432
436
  timelineMissing: 'Anchor not found: the id may not exist or may be archived.',
433
437
  timelineNoItems: 'The anchor exists, but there are no neighbours to show.',
434
438
  timelineCount: 'items',
@@ -1427,10 +1431,20 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1427
1431
  const [before, setBefore] = useState(4);
1428
1432
  const [after, setAfter] = useState(4);
1429
1433
  const [data, setData] = useState(null);
1434
+ const [recent, setRecent] = useState(null);
1430
1435
  const [busy, setBusy] = useState(Boolean(initialAnchor));
1431
1436
  const [error, setError] = useState('');
1432
1437
  const [tick, setTick] = useState(0);
1433
1438
 
1439
+ useEffect(() => {
1440
+ if (committed) return undefined;
1441
+ let alive = true;
1442
+ api('/timeline/recent?limit=20')
1443
+ .then((value) => { if (alive) setRecent(value); })
1444
+ .catch((issue) => { if (alive) setError(String(issue.message ?? issue)); });
1445
+ return () => { alive = false; };
1446
+ }, [committed, tick]);
1447
+
1434
1448
  useEffect(() => {
1435
1449
  const next = String(anchorId ?? '').trim();
1436
1450
  if (next && next !== committed) {
@@ -1466,7 +1480,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1466
1480
  onAnchorChange?.(next);
1467
1481
  };
1468
1482
 
1469
- const rawItems = data?.items ?? [];
1483
+ const rawItems = committed ? (data?.items ?? []) : (recent?.items ?? []);
1470
1484
  const items = rawItems.length
1471
1485
  ? rawItems
1472
1486
  : (data?.anchor ? [{
@@ -1530,10 +1544,10 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1530
1544
  ]),
1531
1545
  h('button', { key: 'go', type: 'submit', className: 'cortex-btn primary', disabled: busy }, t('timelineLoad')),
1532
1546
  ]),
1533
- !committed && !error ? h(EmptyBlock, { key: 'empty' }, t('timelineEmpty')) : null,
1547
+ !committed && !error && !items.length ? h(EmptyBlock, { key: 'empty' }, t('timelineEmpty')) : null,
1534
1548
  error ? h(ErrorBlock, { key: 'err', message: error, onRetry: submit, retryLabel: t('retry') }) : null,
1535
1549
  busy ? h(LoadingBlock, { key: 'loading', label: t('loading') }) : null,
1536
- !busy && data && !data.anchor ? h(EmptyBlock, { key: 'missing' }, t('timelineMissing')) : null,
1550
+ !busy && committed && data && !data.anchor ? h(EmptyBlock, { key: 'missing' }, t('timelineMissing')) : null,
1537
1551
  !busy && data?.anchor && !items.length ? h(EmptyBlock, { key: 'noitems' }, t('timelineNoItems')) : null,
1538
1552
  !busy && items.length ? h('div', { key: 'list', className: 'cortex-timeline', 'aria-label': t('tabTimeline') }, items.map((item, index) => h(
1539
1553
  'button',
@@ -1653,7 +1667,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1653
1667
  const optimize = async () => {
1654
1668
  setBusy(true);
1655
1669
  setError('');
1656
- try { await api('/evolve/optimize', { method: 'POST', body: JSON.stringify({}) }); await load(); } catch (issue) { setError(String(issue.message ?? issue)); setBusy(false); }
1670
+ try { await api('/evolve/optimize', { method: 'POST', body: JSON.stringify({ baseline: true }) }); await load(); } catch (issue) { setError(String(issue.message ?? issue)); setBusy(false); }
1657
1671
  };
1658
1672
  return h('div', {}, [
1659
1673
  h('div', { key: 'line', className: 'cortex-line' }, [h('button', { key: 'o', type: 'button', className: 'cortex-btn', disabled: busy, onClick: optimize }, t('optimize'))]),
@@ -1723,8 +1737,8 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1723
1737
  return h('div', {}, [
1724
1738
  error ? h(ErrorBlock, { key: 'err', message: error, prefix: t('requestFailed') }) : null,
1725
1739
  h('div', { key: 'line', className: 'cortex-line' }, [
1726
- h('button', { key: 'b', type: 'button', className: 'cortex-btn primary', disabled: busy, onClick: generate }, busy ? '本鲸在感受…' : '让本鲸感受一下'),
1727
- h('span', { key: 'note', className: 'cortex-meta' }, '空闲时每小时自动写一次;感受由本鲸自己判断'),
1740
+ h('button', { key: 'b', type: 'button', className: 'cortex-btn primary', disabled: busy, onClick: generate }, busy ? '助手在感受…' : '让助手感受一下'),
1741
+ h('span', { key: 'note', className: 'cortex-meta' }, '空闲时每小时自动写一次;感受由助手自己判断'),
1728
1742
  ]),
1729
1743
  data ? h('div', {}, [
1730
1744
  h('div', { key: 't', className: 'cortex-card' }, [h('h4', {}, '情感态度'), h('div', { className: 'cortex-big' }, data.text)]),
@@ -1770,12 +1784,12 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1770
1784
  h('div', { key: 'diary', className: 'cortex-card' }, [
1771
1785
  h('h4', {}, '日记'),
1772
1786
  h('div', { key: 'line', className: 'cortex-line' }, [
1773
- h('button', { key: 'b', type: 'button', className: 'cortex-btn primary', disabled: busy, onClick: writeDiary }, busy ? '本鲸在想…' : '让本鲸写日记'),
1787
+ h('button', { key: 'b', type: 'button', className: 'cortex-btn primary', disabled: busy, onClick: writeDiary }, busy ? '助手在想…' : '让助手写日记'),
1774
1788
  h('button', { key: 'auto', type: 'button', className: 'cortex-btn', onClick: () => toggleAuto('autoDiary') }, `AI 接管日记:${autoValue('autoDiary') ? '开' : '关'}`),
1775
1789
  h('button', { key: 'web', type: 'button', className: 'cortex-btn', onClick: () => toggleAuto('webSearch') }, `联网:${autoValue('webSearch') ? '开' : '关'}`),
1776
- h('span', { key: 'note', className: 'cortex-meta' }, '本鲸自己思考后写;不是主人代笔'),
1790
+ h('span', { key: 'note', className: 'cortex-meta' }, '助手自己思考后写;不是用户代笔'),
1777
1791
  ]),
1778
- ...((data?.diary ?? []).length ? data.diary.map((item) => h('div', { key: item.id, className: 'cortex-row' }, `${item.at.slice(0, 10)} ${item.text}`)) : [h('div', { key: 'none', className: 'cortex-empty' }, t('empty'))]),
1792
+ ...((data?.diary ?? []).length ? data.diary.map((item) => h('div', { key: item.id, className: 'cortex-row' }, `${formatTime(item.at).slice(0, 10)} ${withoutReferences(item.text)}`)) : [h('div', { key: 'none', className: 'cortex-empty' }, t('empty'))]),
1779
1793
  ]),
1780
1794
  h('div', { key: 'dreams', className: 'cortex-card', style: { marginTop: 10 } }, [
1781
1795
  h('h4', {}, '梦'),
@@ -1784,7 +1798,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
1784
1798
  h('button', { key: 'web', type: 'button', className: 'cortex-btn', onClick: () => toggleAuto('webSearch') }, `联网:${autoValue('webSearch') ? '开' : '关'}`),
1785
1799
  h('span', { key: 'note', className: 'cortex-meta' }, '22:05 自动生成;失败不回退模板'),
1786
1800
  ]),
1787
- ...((data?.dreams ?? []).length ? data.dreams.map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, item.text)) : [h('div', { key: 'none', className: 'cortex-empty' }, t('empty'))]),
1801
+ ...((data?.dreams ?? []).length ? data.dreams.map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, withoutReferences(item.text))) : [h('div', { key: 'none', className: 'cortex-empty' }, t('empty'))]),
1788
1802
  ]),
1789
1803
  ]);
1790
1804
  }
@@ -2068,7 +2082,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2068
2082
  style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
2069
2083
  }, [
2070
2084
  h('span', { key: 'label', style: { flex: '1 1 240px', minWidth: 0 } },
2071
- `${shortLabel(edge.fromName || positions.get(edge.fromId)?.name || edge.fromId)} → ${shortLabel(edge.toName || positions.get(edge.toId)?.name || edge.toId)} · ${edge.rel} · ${t('graphCandidateConfidence')} ${formatNumber(edge.metadata?.confidence ?? edge.weight ?? 0, 2)}`),
2085
+ `${shortLabel(edge.fromName || positions.get(edge.fromId)?.name || edge.fromId)} → ${shortLabel(edge.toName || positions.get(edge.toId)?.name || edge.toId)} · ${edge.relLabel || edge.rel} · ${t('graphCandidateConfidence')} ${formatNumber(edge.metadata?.confidence ?? edge.weight ?? 0, 2)}`),
2072
2086
  h('button', {
2073
2087
  key: 'approve',
2074
2088
  type: 'button',
@@ -2338,8 +2352,8 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2338
2352
  h('summary', {}, `事实 ${counts.facts ?? 0} · 摘要 ${counts.summaries ?? 0} · 日记 ${counts.diary ?? 0} · 梦 ${counts.dreams ?? 0}`),
2339
2353
  ...(work.facts ?? []).map((fact) => h('div', { key: fact.id, className: 'cortex-row' }, `${fact.subjectId ?? '—'} ${fact.predicate} ${fact.objectLiteral ?? fact.objectId ?? '—'}`)),
2340
2354
  ...(work.summaries ?? []).map((summary) => h('div', { key: summary.id, className: 'cortex-snippet' }, summary.content)),
2341
- ...(work.diary ?? []).map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, item.text)),
2342
- ...(work.dreams ?? []).map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, item.text)),
2355
+ ...(work.diary ?? []).map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, withoutReferences(item.text))),
2356
+ ...(work.dreams ?? []).map((item) => h('div', { key: item.id, className: 'cortex-snippet' }, withoutReferences(item.text))),
2343
2357
  ]),
2344
2358
  ]),
2345
2359
  ]),
@@ -2489,7 +2503,7 @@ button.cortex-badge:disabled{cursor:not-allowed;opacity:.55}
2489
2503
  setBusy(id); setNotice('');
2490
2504
  try {
2491
2505
  if (kind === 'fact') {
2492
- await api('/facts/resolve', { method: 'POST', body: JSON.stringify({ id, decision, reason: '主人从诊断框处理' }) });
2506
+ await api('/facts/resolve', { method: 'POST', body: JSON.stringify({ id, decision, reason: '用户从诊断框处理' }) });
2493
2507
  setNotice(decision === 'confirm' ? '已确认有效' : '已降级为无效,内容保留');
2494
2508
  } else if (kind === 'suggest') {
2495
2509
  const result = await api('/skills/suggest', { method: 'POST', body: '{}' });
package/cordis.patch.yml CHANGED
@@ -3,5 +3,5 @@
3
3
  # never shiori's data.
4
4
  - insert:
5
5
  - id: cortex
6
- name: 'dsh-cortex-memory'
6
+ name: 'dsh-cortex'
7
7
  config: {}
package/index.js CHANGED
@@ -22,6 +22,10 @@ export const Config = Schema ? Schema.object({
22
22
  dataRoot: Schema.string().description('Cortex 数据目录(默认 DSH_HOME/cortex)'),
23
23
  dbFile: Schema.string().description('SQLite 文件;默认 dataRoot/cortex.sqlite'),
24
24
  scope: Schema.string().default('global').description('默认 scope'),
25
+ persona: Schema.object({
26
+ selfName: Schema.string().default('助手').description('助手自称;默认中性'),
27
+ userAddress: Schema.string().default('你').description('用户称呼;默认中性'),
28
+ }).description('人格称呼配置'),
25
29
  readOnlyScopes: Schema.array(Schema.string()).default([]).description('只读共享 scope 列表'),
26
30
  scopeWriteGrants: Schema.array(Schema.any()).default([]).description('显式写授权:scope:agent 或 {grant, until}'),
27
31
  contextBudget: Schema.natural().default(2200).description('检索注入的 token 预算'),
@@ -36,6 +40,9 @@ export const Config = Schema ? Schema.object({
36
40
  vectorAnnTimeoutMs: Schema.natural().default(800).description('外置 ANN 超时毫秒'),
37
41
  scheduler: Schema.boolean().default(true).description('启用宿主心跳(安全自主 tick/作业/保留计划)'),
38
42
  schedulerIntervalMs: Schema.natural().default(60000).description('心跳间隔毫秒'),
43
+ injectionGate: Schema.boolean().default(true).description('只过滤注入 prompt 的弱相关候选;cortex_search 仍返回全量'),
44
+ recentMinMatch: Schema.number().default(0.12).description('注入层近期候选最低匹配度'),
45
+ allowRestoreOutsideRoot: Schema.boolean().default(false).description('允许 guard 恢复到 dataRoot 外;默认禁止'),
39
46
  maxCallsPerHour: Schema.natural().default(120).description('检索调用预算(宿主 prefetch 不计入)'),
40
47
  rerankEnabled: Schema.boolean().default(false).description('QA 可选 HTTP rerank(默认关)'),
41
48
  rerankBaseUrl: Schema.string().default('').description('rerank 服务根地址,例如 http://127.0.0.1:9000/v1'),
@@ -103,7 +110,7 @@ export async function apply(ctx, config = {}) {
103
110
  try {
104
111
  const effective = effectiveFeatures(config);
105
112
  config = { ...config, features: effective.features };
106
- const llm = config.features?.llm === true ? createLlmAdapter({ ctx, logger: ctx.logger }) : null;
113
+ const llm = config.features?.llm === true ? createLlmAdapter({ ctx, logger: ctx.logger, persona: config.persona }) : null;
107
114
  let webSearch = null;
108
115
  try {
109
116
  const web = ctx.get?.('web') ?? null;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.3.0",
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.11",
4
+ "description": "Local-first layered memory engine for DeepSeek Harness",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
7
  "icon": "./icon.svg",
@@ -20,25 +20,15 @@
20
20
  "index.js",
21
21
  "client.js",
22
22
  "src",
23
- "bench",
24
- "bin",
25
23
  "cordis.patch.yml",
26
24
  "locale/*.json",
27
25
  "icon.svg",
28
26
  "README.md",
29
- "docs/install-windows.md",
30
- "docs/models.md",
31
- "docs/scopes.md",
32
- "docs/multimodal.md",
33
- "examples",
34
27
  "LICENSE",
35
- "docs/permissions.md",
36
- "docs/privacy.md"
28
+ "bin"
37
29
  ],
38
30
  "scripts": {
39
- "test": "node --test test/unit/ test/integration/",
40
31
  "test:unit": "node --test test/unit/",
41
- "test:integration": "node --test test/integration/",
42
32
  "bench": "node bench/run.js",
43
33
  "check": "node --check index.js && node --check client.js"
44
34
  },
@@ -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,6 +10,7 @@ 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,
14
15
  readOnlyScopes: Object.freeze([]),
15
16
  scopeWriteGrants: Object.freeze([]),
@@ -79,6 +80,7 @@ export function normalizeConfig(raw = {}) {
79
80
  const dsrInput = input.dsr && typeof input.dsr === 'object' ? input.dsr : {};
80
81
  const compressionInput = input.compression && typeof input.compression === 'object' ? input.compression : {};
81
82
  const featuresInput = input.features && typeof input.features === 'object' ? input.features : {};
83
+ const personaInput = input.persona && typeof input.persona === 'object' ? input.persona : {};
82
84
  const scope = typeof input.scope === 'string' && input.scope.trim() ? input.scope.trim() : DEFAULT_CONFIG.scope;
83
85
 
84
86
  return Object.freeze({
@@ -87,6 +89,10 @@ export function normalizeConfig(raw = {}) {
87
89
  dataRoot,
88
90
  dbFile,
89
91
  scope,
92
+ persona: Object.freeze({
93
+ selfName: (typeof personaInput.selfName === 'string' && personaInput.selfName.trim() ? personaInput.selfName.trim() : DEFAULT_CONFIG.persona.selfName).slice(0, 24),
94
+ userAddress: (typeof personaInput.userAddress === 'string' && personaInput.userAddress.trim() ? personaInput.userAddress.trim() : DEFAULT_CONFIG.persona.userAddress).slice(0, 24),
95
+ }),
90
96
  readOnlyScopes: Object.freeze(Array.isArray(input.readOnlyScopes)
91
97
  ? [...new Set(input.readOnlyScopes.filter((value) => typeof value === 'string' && value.trim()).map((value) => value.trim()).slice(0, 100))]
92
98
  : []),
@@ -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
+ const SUBJECT_ALIASES = new Map([
14
+ ['我', '用户'],
15
+ ['自己', '用户'],
16
+ ['我们', '用户'],
17
+ ['你', '助手'],
18
+ ]);
13
19
 
14
20
  function clean(value) {
15
21
  return String(value ?? '').trim().replace(/^(?:今天|昨天|明天|刚才|然后|所以|但是|而且)/, '').trim();
16
22
  }
17
23
 
24
+ function plausibleName(value, max = 16) {
25
+ if (!value || value.length > max) return false;
26
+ if (/[\/\\*“”"`\n\r\s::]/.test(value)) return false;
27
+ if (/^[0-9]/.test(value)) return false;
28
+ if (/^(?:但|还|不能|原因|当前|你现|我现|这|那|只|哪些)/.test(value)) return false;
29
+ return true;
30
+ }
31
+
18
32
  export function extractFactCandidates(text) {
19
33
  const value = String(text ?? '');
34
+ // Assistant replies and copied notes are often markdown-heavy; those are
35
+ // not clean fact sources and produce sentence-fragment entities.
36
+ if (/```|`[^`]*`|\*\*|^\s*[-*]\s|\|.*\|/m.test(value)) return [];
20
37
  const out = [];
21
38
  const seen = new Set();
22
39
  for (const rule of RULES) {
23
40
  rule.pattern.lastIndex = 0;
24
41
  let match;
25
42
  while ((match = rule.pattern.exec(value)) !== null) {
26
- const subject = clean(match[1]);
43
+ const rawSubject = clean(match[1]);
44
+ const subject = SUBJECT_ALIASES.get(rawSubject) ?? rawSubject;
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;
@@ -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(),