dsh-cortex-memory 0.4.11 → 0.4.15

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 +112 -0
  2. package/LICENSE +1 -1
  3. package/README.md +62 -36
  4. package/bench/README.md +29 -0
  5. package/bench/ab-engine.mjs +60 -0
  6. package/bench/ann-bench.mjs +78 -0
  7. package/bench/hnsw-bench.mjs +79 -0
  8. package/bench/locomo.js +89 -0
  9. package/bench/longmemeval.js +83 -0
  10. package/bench/metrics.js +67 -0
  11. package/bench/migration-bench.mjs +69 -0
  12. package/bench/results/semantic-cn.json +24 -0
  13. package/bench/run.js +77 -0
  14. package/bench/semantic-cn.js +116 -0
  15. package/bench/synthetic.js +99 -0
  16. package/bench/vector-ab.mjs +76 -0
  17. package/docs/compatibility.md +39 -0
  18. package/docs/install-windows.md +144 -0
  19. package/docs/models.md +183 -0
  20. package/docs/multimodal.md +112 -0
  21. package/docs/permissions.md +53 -0
  22. package/docs/privacy.md +50 -0
  23. package/docs/scopes.md +142 -0
  24. package/examples/README.md +72 -0
  25. package/examples/setup-cortex-bge.ps1 +66 -0
  26. package/examples/uninstall-cortex.ps1 +91 -0
  27. package/index.js +23 -0
  28. package/package.json +11 -5
  29. package/src/core/config.js +27 -0
  30. package/src/engines/extract.js +10 -10
  31. package/src/engines/retrieve.js +30 -5
  32. package/src/guardian/guardian.js +2 -15
  33. package/src/guardian/invariants.js +9 -5
  34. package/src/host/runtime.js +10 -14
  35. package/src/self/evolution.js +32 -5
  36. package/src/self/policies.js +21 -2
  37. package/src/service/cortex.js +3 -2
  38. package/src/store/database.js +9 -1
  39. package/src/store/schema.sql +2 -1
  40. package/src/vector/hnsw.js +5 -5
  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
@@ -0,0 +1,72 @@
1
+ # Cortex bge 可选 profile
2
+
3
+ 默认 **不开启** bge。这个示例只给想要本地语义召回的人用:
4
+
5
+ - 需要本地 Ollama / OpenAI-compatible embedding 服务
6
+ - 需要 `bge-m3`(1024 维)
7
+ - 查询延迟会明显高于 FTS
8
+ - 没有服务时不要开;失败会退开放,不会假装成功
9
+
10
+ ## 一键创建独立 profile
11
+
12
+ ```powershell
13
+ powershell -ExecutionPolicy Bypass -File .\examples\setup-cortex-bge.ps1 `
14
+ -Dsh "D:\path\to\dsh.cmd" `
15
+ -Profile cortex-bge `
16
+ -Package "C:\path\to\dsh-cortex-memory-0.1.0.tgz"
17
+ ```
18
+
19
+ 首次先用 Ollama 启动模型服务:
20
+
21
+ ```powershell
22
+ ollama serve
23
+ ollama pull bge-m3
24
+ ```
25
+
26
+ 脚本会:
27
+
28
+ 1. 用 DSH 的 `web` 模板新建一个空 profile
29
+ 2. 安装 cortex 包
30
+ 3. 写独立的 `dataRoot/dbFile`
31
+ 4. 写 `features.vector: true`
32
+ 5. 写 `model-config.json`(local / bge-m3 / 1024)
33
+
34
+ 它**不会**改 desktop,也不会自动启动服务。
35
+
36
+ ## 启动
37
+
38
+ ```powershell
39
+ & $Dsh --profile cortex-bge --port 0 --no-open
40
+ ```
41
+
42
+ 打开后到 Cortex 设置里确认:
43
+
44
+ ```text
45
+ embedding mode: local
46
+ model: bge-m3
47
+ dim: 1024
48
+ ```
49
+
50
+ ## 关闭
51
+
52
+ 移除 profile 或把 `features.vector` 改回 `false`。
53
+ 不想用语义模型时,FTS 仍是默认路径。
54
+
55
+ ## 卸载 cortex
56
+
57
+ `dsh plugin remove` 不会删手写 patch。用:
58
+
59
+ ```powershell
60
+ powershell -ExecutionPolicy Bypass -File .\examples\uninstall-cortex.ps1 `
61
+ -Dsh "D:\path\to\dsh.cmd" `
62
+ -Profile cortex-bge
63
+ ```
64
+
65
+ 脚本会:
66
+
67
+ 1. 若已安装则 `plugin remove`
68
+ 2. 只删除 `- id: cortex` 段,保留其他 patch
69
+ 3. 跑一次 `--dump-config`
70
+ 4. **不删 dataRoot**
71
+
72
+ 如果已经手动移除,脚本会跳过 remove,仍清理残留 patch。
@@ -0,0 +1,66 @@
1
+ [CmdletBinding()]
2
+ param(
3
+ [string]$Dsh = 'dsh',
4
+ [string]$Profile = 'cortex-bge',
5
+ [string]$Package = 'dsh-cortex-memory',
6
+ [string]$DataRoot = (Join-Path $HOME '.dsh\cortex-bge'),
7
+ [string]$BaseUrl = 'http://127.0.0.1:11434/v1',
8
+ [string]$Model = 'bge-m3',
9
+ [int]$Dim = 1024
10
+ )
11
+
12
+ $ErrorActionPreference = 'Stop'
13
+ $dshCommand = Get-Command $Dsh -ErrorAction SilentlyContinue
14
+ if (-not $dshCommand) { throw "dsh command not found: $Dsh. Pass -Dsh with the path to dsh.cmd." }
15
+ $dshPath = $dshCommand.Source
16
+ $profilePath = Join-Path (Join-Path $HOME '.dsh\profiles') $Profile
17
+ if (Test-Path $profilePath) { throw "profile already exists: $profilePath. Choose another -Profile or remove it first." }
18
+
19
+ if ($Package -match '\.tgz$') {
20
+ $Package = (Resolve-Path $Package).Path
21
+ }
22
+
23
+ & $dshPath --profile $Profile --from-default-profile web --dump-config | Out-Null
24
+ & $dshPath plugin --profile $Profile add $Package
25
+ if ($LASTEXITCODE -ne 0) { throw "plugin install failed with exit code $LASTEXITCODE" }
26
+
27
+ New-Item -ItemType Directory -Force -Path $DataRoot | Out-Null
28
+ $modelConfig = [ordered]@{
29
+ embedding = [ordered]@{
30
+ mode = 'local'
31
+ baseUrl = $BaseUrl
32
+ model = $Model
33
+ dim = $Dim
34
+ apiKey = ''
35
+ }
36
+ rerank = [ordered]@{
37
+ enabled = $false
38
+ baseUrl = ''
39
+ model = ''
40
+ apiKey = ''
41
+ }
42
+ }
43
+ $utf8 = New-Object System.Text.UTF8Encoding($false)
44
+ [System.IO.File]::WriteAllText(
45
+ (Join-Path $DataRoot 'model-config.json'),
46
+ (($modelConfig | ConvertTo-Json -Depth 5) + "`n"),
47
+ $utf8
48
+ )
49
+
50
+ $patchFile = Join-Path $profilePath 'cordis.patch.yml'
51
+ $patch = @"
52
+ # bge profile generated by examples/setup-cortex-bge.ps1
53
+ - id: cortex
54
+ name: dsh-cortex
55
+ config:
56
+ dataRoot: '$($DataRoot.Replace('\','/'))'
57
+ dbFile: '$((Join-Path $DataRoot 'cortex.sqlite').Replace('\','/'))'
58
+ features:
59
+ vector: true
60
+ "@
61
+ [System.IO.File]::WriteAllText($patchFile, $patch + "`n", $utf8)
62
+
63
+ Write-Host "profile: $profilePath"
64
+ Write-Host "dataRoot: $DataRoot"
65
+ Write-Host "Next: & '$dshPath' --profile $Profile --port 0 --no-open"
66
+ Write-Host "Start the local embedding service first: $BaseUrl"
@@ -0,0 +1,91 @@
1
+ [CmdletBinding()]
2
+ param(
3
+ [string]$Dsh = 'dsh',
4
+ [string]$Profile = 'desktop',
5
+ [string]$Package = 'dsh-cortex',
6
+ [switch]$KeepPatch
7
+ )
8
+
9
+ $ErrorActionPreference = 'Stop'
10
+ $dshCommand = Get-Command $Dsh -ErrorAction SilentlyContinue
11
+ if (-not $dshCommand) { throw "dsh command not found: $Dsh. Pass -Dsh with the path to dsh.cmd." }
12
+ $dshPath = $dshCommand.Source
13
+ $profilePath = Join-Path (Join-Path $HOME '.dsh\profiles') $Profile
14
+ if (-not (Test-Path $profilePath)) { throw "profile not found: $profilePath" }
15
+
16
+ $packageJson = Join-Path $profilePath 'package.json'
17
+ $installed = $false
18
+ if (Test-Path $packageJson) {
19
+ try {
20
+ $manifest = Get-Content -LiteralPath $packageJson -Raw | ConvertFrom-Json
21
+ $installed = $null -ne $manifest.dependencies.$Package
22
+ } catch { $installed = $false }
23
+ }
24
+ if ($installed) {
25
+ & $dshPath plugin --profile $Profile remove $Package
26
+ if ($LASTEXITCODE -ne 0) { throw "plugin remove failed with exit code $LASTEXITCODE" }
27
+ } else {
28
+ Write-Host "$Package is not installed in $Profile; skipping remove"
29
+ }
30
+
31
+ $patchFile = Join-Path $profilePath 'cordis.patch.yml'
32
+ $configuredDataRoot = $null
33
+ if (Test-Path $patchFile) {
34
+ foreach ($line in [System.IO.File]::ReadAllLines($patchFile)) {
35
+ if ($line -match '^\s*dataRoot:\s*(.+)$') {
36
+ $configuredDataRoot = $matches[1].Trim().Trim("'").Trim('"')
37
+ break
38
+ }
39
+ }
40
+ }
41
+ if (-not $configuredDataRoot) {
42
+ $dshHome = Join-Path $HOME '.dsh'
43
+ $configuredDataRoot = if ($Profile -eq 'desktop') { Join-Path $dshHome 'cortex' } else { Join-Path (Join-Path $dshHome 'cortex\profiles') $Profile }
44
+ }
45
+
46
+ if (-not $KeepPatch) {
47
+ if (Test-Path $patchFile) {
48
+ $lines = [System.IO.File]::ReadAllLines($patchFile)
49
+ $ranges = New-Object System.Collections.Generic.List[object]
50
+ $start = -1
51
+ for ($i = 0; $i -lt $lines.Count; $i += 1) {
52
+ if ($lines[$i] -match '^- ') {
53
+ if ($start -ge 0) { $ranges.Add([pscustomobject]@{ From = $start; To = ($i - 1) }) }
54
+ $start = $i
55
+ }
56
+ }
57
+ if ($start -ge 0) { $ranges.Add([pscustomobject]@{ From = $start; To = ($lines.Count - 1) }) }
58
+
59
+ $drop = @{}
60
+ foreach ($range in $ranges) {
61
+ $from = [int]$range.From
62
+ $to = [int]$range.To
63
+ $header = $lines[$from]
64
+ $body = ($lines[$from..$to] -join "`n")
65
+ if ($header -match '^- id:\s*cortex\s*$' -and $body -match 'name:\s*[''"]?dsh-cortex') {
66
+ for ($i = $from; $i -le $to; $i += 1) { $drop[$i] = $true }
67
+ }
68
+ }
69
+
70
+ if ($drop.Count -gt 0) {
71
+ $remaining = @()
72
+ for ($i = 0; $i -lt $lines.Count; $i += 1) {
73
+ if (-not $drop.ContainsKey($i)) { $remaining += $lines[$i] }
74
+ }
75
+ $meaningful = @($remaining | Where-Object { $_.Trim() -and -not $_.Trim().StartsWith('#') })
76
+ $text = if ($meaningful.Count -eq 0) { "[]`n" } else { ($remaining -join "`n") + "`n" }
77
+ $utf8 = New-Object System.Text.UTF8Encoding($false)
78
+ [System.IO.File]::WriteAllText($patchFile, $text, $utf8)
79
+ Write-Host "removed cortex patch block from $patchFile"
80
+ } else {
81
+ Write-Host "no cortex patch block found in $patchFile"
82
+ }
83
+ }
84
+
85
+ & $dshPath --profile $Profile --dump-config | Out-Null
86
+ if ($LASTEXITCODE -ne 0) { Write-Warning "dump-config still fails; inspect $profilePath\cordis.patch.yml" }
87
+ else { Write-Host "dump-config ok" }
88
+ }
89
+
90
+ Write-Host "profile left in place: $profilePath"
91
+ Write-Host "cortex data was NOT deleted: $configuredDataRoot"
package/index.js CHANGED
@@ -6,6 +6,7 @@ import { assembleSystemPrompt } from './src/prompt/assemble.js';
6
6
  import { createLlmAdapter } from './src/llm/adapter.js';
7
7
  import { createScheduler } from './src/host/scheduler.js';
8
8
  import { effectiveFeatures } from './src/core/feature-overrides.js';
9
+ import { createWebSearch } from './src/web/search.js';
9
10
 
10
11
  export const name = 'cortex';
11
12
  export const inject = ['tools', 'systemPrompt'];
@@ -42,7 +43,20 @@ export const Config = Schema ? Schema.object({
42
43
  schedulerIntervalMs: Schema.natural().default(60000).description('心跳间隔毫秒'),
43
44
  injectionGate: Schema.boolean().default(true).description('只过滤注入 prompt 的弱相关候选;cortex_search 仍返回全量'),
44
45
  recentMinMatch: Schema.number().default(0.12).description('注入层近期候选最低匹配度'),
46
+ recentImportanceFloor: Schema.number().default(0.8).description('注入层允许重要度豁免的最低重要度;默认保持 0.4.11 行为'),
47
+ recallSharing: Schema.boolean().default(false).description('允许所有会话共享同一份召回块;默认按 session 隔离'),
48
+ evolution: Schema.object({
49
+ autoActivate: Schema.boolean().default(true).description('允许自我进化在护栏内自动激活候选策略'),
50
+ maxPerDay: Schema.natural().default(4).description('每天自动激活上限'),
51
+ minIntervalMs: Schema.natural().default(3600000).description('两次自动激活的最小间隔毫秒'),
52
+ canaryTicks: Schema.natural().default(3).description('候选策略观察多少个健康心跳后才算稳定'),
53
+ rollbackOnError: Schema.boolean().default(true).description('观察期内自检失败则自动回滚'),
54
+ }).description('自我进化的护栏(保留自主性,只限制爆炸半径)'),
45
55
  allowRestoreOutsideRoot: Schema.boolean().default(false).description('允许 guard 恢复到 dataRoot 外;默认禁止'),
56
+ webSearchProvider: Schema.string().default('wikipedia').description('无宿主 web 服务时的兜底:wikipedia | searxng | none'),
57
+ webSearchEndpoint: Schema.string().default('http://127.0.0.1:8080').description('SearXNG endpoint(provider=searxng 时使用)'),
58
+ webSearchLanguage: Schema.string().default('zh').description('联网检索语言'),
59
+ webSearchMaxResults: Schema.natural().default(3).description('每次联网检索返回条数上限'),
46
60
  maxCallsPerHour: Schema.natural().default(120).description('检索调用预算(宿主 prefetch 不计入)'),
47
61
  rerankEnabled: Schema.boolean().default(false).description('QA 可选 HTTP rerank(默认关)'),
48
62
  rerankBaseUrl: Schema.string().default('').description('rerank 服务根地址,例如 http://127.0.0.1:9000/v1'),
@@ -115,6 +129,15 @@ export async function apply(ctx, config = {}) {
115
129
  try {
116
130
  const web = ctx.get?.('web') ?? null;
117
131
  if (web && typeof web.search === 'function') webSearch = (request) => web.search(request);
132
+ else if (config.features?.webSearch === true && config.webSearchProvider !== 'none') {
133
+ const fallback = createWebSearch({
134
+ provider: config.webSearchProvider ?? 'wikipedia',
135
+ endpoint: config.webSearchEndpoint ?? 'http://127.0.0.1:8080',
136
+ language: config.webSearchLanguage ?? 'zh',
137
+ maxResults: config.webSearchMaxResults ?? 3,
138
+ });
139
+ webSearch = (request) => fallback.search(request);
140
+ }
118
141
  } catch {
119
142
  webSearch = null;
120
143
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-cortex-memory",
3
- "version": "0.4.11",
4
- "description": "Local-first layered memory engine for DeepSeek Harness",
3
+ "version": "0.4.15",
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",
@@ -20,17 +20,23 @@
20
20
  "index.js",
21
21
  "client.js",
22
22
  "src",
23
+ "bench",
24
+ "bin",
23
25
  "cordis.patch.yml",
24
26
  "locale/*.json",
25
27
  "icon.svg",
26
28
  "README.md",
29
+ "examples",
27
30
  "LICENSE",
28
- "bin"
31
+ "test",
32
+ "CHANGELOG.md",
33
+ "docs"
29
34
  ],
30
35
  "scripts": {
31
- "test:unit": "node --test test/unit/",
36
+ "test:unit": "node --test test/unit/*.test.js",
32
37
  "bench": "node bench/run.js",
33
- "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"
34
40
  },
35
41
  "engines": {
36
42
  "node": ">=24",
@@ -12,11 +12,24 @@ export const DEFAULT_CONFIG = Object.freeze({
12
12
  scope: 'global',
13
13
  persona: Object.freeze({ selfName: '助手', userAddress: '你' }),
14
14
  contextBudget: 2200,
15
+ promptBudget: 1600,
15
16
  readOnlyScopes: Object.freeze([]),
16
17
  scopeWriteGrants: Object.freeze([]),
17
18
  identityBudget: 360,
18
19
  workingBudget: 800,
19
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,
20
33
  ftsLimit: 40,
21
34
  vectorEnabled: false,
22
35
  vectorAnnMin: 20000,
@@ -81,6 +94,7 @@ export function normalizeConfig(raw = {}) {
81
94
  const compressionInput = input.compression && typeof input.compression === 'object' ? input.compression : {};
82
95
  const featuresInput = input.features && typeof input.features === 'object' ? input.features : {};
83
96
  const personaInput = input.persona && typeof input.persona === 'object' ? input.persona : {};
97
+ const evolutionInput = input.evolution && typeof input.evolution === 'object' ? input.evolution : {};
84
98
  const scope = typeof input.scope === 'string' && input.scope.trim() ? input.scope.trim() : DEFAULT_CONFIG.scope;
85
99
 
86
100
  return Object.freeze({
@@ -119,9 +133,22 @@ export function normalizeConfig(raw = {}) {
119
133
  return out;
120
134
  })()),
121
135
  contextBudget: numeric(input.contextBudget, DEFAULT_CONFIG.contextBudget, 256, 20000),
136
+ promptBudget: numeric(input.promptBudget, DEFAULT_CONFIG.promptBudget, 256, 8000),
122
137
  identityBudget: numeric(input.identityBudget, DEFAULT_CONFIG.identityBudget, 64, 4000),
123
138
  workingBudget: numeric(input.workingBudget, DEFAULT_CONFIG.workingBudget, 128, 8000),
124
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,
125
152
  ftsLimit: numeric(input.ftsLimit, DEFAULT_CONFIG.ftsLimit, 1, 200),
126
153
  vectorEnabled: input.vectorEnabled === true,
127
154
  llmEnabled: input.llmEnabled === true,
@@ -10,12 +10,6 @@ const RULES = [
10
10
  const NEGATED_TAIL = /[不没别未]\s*$/;
11
11
 
12
12
  const STOP_SUBJECTS = new Set(['他', '她', '它', '这', '那', '今天', '昨天', '明天']);
13
- const SUBJECT_ALIASES = new Map([
14
- ['我', '用户'],
15
- ['自己', '用户'],
16
- ['我们', '用户'],
17
- ['你', '助手'],
18
- ]);
19
13
 
20
14
  function clean(value) {
21
15
  return String(value ?? '').trim().replace(/^(?:今天|昨天|明天|刚才|然后|所以|但是|而且)/, '').trim();
@@ -29,11 +23,15 @@ function plausibleName(value, max = 16) {
29
23
  return true;
30
24
  }
31
25
 
32
- export function extractFactCandidates(text) {
26
+ export function extractFactCandidates(text, persona = {}) {
33
27
  const value = String(text ?? '');
34
28
  // Assistant replies and copied notes are often markdown-heavy; those are
35
29
  // not clean fact sources and produce sentence-fragment entities.
36
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]);
37
35
  const out = [];
38
36
  const seen = new Set();
39
37
  for (const rule of RULES) {
@@ -41,7 +39,9 @@ export function extractFactCandidates(text) {
41
39
  let match;
42
40
  while ((match = rule.pattern.exec(value)) !== null) {
43
41
  const rawSubject = clean(match[1]);
44
- const subject = SUBJECT_ALIASES.get(rawSubject) ?? rawSubject;
42
+ let subject = rawSubject;
43
+ if (selfAliases.has(rawSubject)) subject = selfName;
44
+ else if (userAliases.has(rawSubject)) subject = userAddress;
45
45
  const object = clean(match[2]);
46
46
  if (!subject || !object || subject.length < 1 || object.length < 1) continue;
47
47
  if (STOP_SUBJECTS.has(rawSubject)) continue;
@@ -61,8 +61,8 @@ export function extractFactCandidates(text) {
61
61
  export function createFactExtractor({ entities, facts } = {}) {
62
62
  if (!entities || !facts) throw new Error('fact extractor needs entities and facts');
63
63
 
64
- function extract({ scopeId = 'global', text, traceId = null, eventId = null, recordedAt = null } = {}) {
65
- const candidates = extractFactCandidates(text);
64
+ function extract({ scopeId = 'global', text, traceId = null, eventId = null, recordedAt = null, persona = null } = {}) {
65
+ const candidates = extractFactCandidates(text, persona ?? {});
66
66
  const resolved = [];
67
67
  for (const candidate of candidates) {
68
68
  try {
@@ -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,
@@ -295,6 +319,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
295
319
  trace: {
296
320
  elapsedMs: Date.now() - started,
297
321
  candidates: sources.candidates.length,
322
+ gated: sources.gated ?? 0,
298
323
  selected: items.length,
299
324
  dropped: portfolio.dropped.length,
300
325
  sources: sources.sourceTrace,
@@ -39,23 +39,10 @@ export function createGuardian({ db, config = {}, events, traces, selfStore = nu
39
39
  }
40
40
 
41
41
  function check({ deep = true } = {}) {
42
- if (deep !== true) {
43
- return {
44
- ok: true,
45
- score: 100,
46
- issues: [],
47
- integrity: 'light',
48
- light: true,
49
- at: nowIso(),
50
- dbBytes: (() => {
51
- try { return config.dbFile && config.dbFile !== ':memory:' ? fs.statSync(config.dbFile).size : 0; } catch { return 0; }
52
- })(),
53
- };
54
- }
55
- const invariants = checkInvariants({ db, events, traces, selfStore, identityStore });
42
+ const invariants = checkInvariants({ db, events, traces, selfStore, identityStore, deep });
56
43
  return {
57
44
  ...invariants,
58
- light: false,
45
+ light: deep !== true,
59
46
  at: nowIso(),
60
47
  dbBytes: (() => {
61
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 状态非法`);
@@ -37,6 +37,10 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
37
37
  return String(session?.id ?? 'unknown');
38
38
  }
39
39
 
40
+ function recallKeyOf(session) {
41
+ return config.recallSharing === true ? 'shared' : keyOf(session);
42
+ }
43
+
40
44
  function turnOf(session, fallback = 0) {
41
45
  return Number(currentTurns.get(keyOf(session)) ?? fallback ?? 0);
42
46
  }
@@ -49,21 +53,12 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
49
53
  budget: config.contextBudget ?? 1200,
50
54
  limit: config.recallLimit ?? 6,
51
55
  scopeId: config.scope,
56
+ gate: config.injectionGate === false ? 'none' : 'inject',
52
57
  noBudget: true,
53
58
  });
54
59
  let recallBlock = '';
55
60
  if (result?.items?.length) {
56
- let items = result.items;
57
- if (config.injectionGate !== false) {
58
- const strongSources = new Set(['fts', 'vector', 'graph']);
59
- const minMatch = Number(config.recentMinMatch ?? 0.12);
60
- const gated = items.filter((item) => {
61
- const sources = new Set((item.sources ?? []).map((source) => source.name));
62
- const strong = [...sources].some((name) => strongSources.has(name));
63
- return strong || Number(item.match ?? 0) >= minMatch || Number(item.importance ?? 0) >= 0.8;
64
- });
65
- items = gated.length ? gated : [items.slice().sort((a, b) => Number(b.importance ?? 0) - Number(a.importance ?? 0))[0]];
66
- }
61
+ const items = result.items;
67
62
  const lines = items.map((item) => `- [${item.layer}] ${item.title}:${item.snippet}`);
68
63
  const tiered = config.features?.tieredRecall !== false
69
64
  ? renderTiers(selectTiers(items, {
@@ -81,10 +76,10 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
81
76
  : { block: '' };
82
77
  const block = [recallBlock, summon.block].filter(Boolean).join('\n\n').slice(0, config.recallMaxChars ?? 2200);
83
78
  if (!block) {
84
- recalls.delete(keyOf(session));
79
+ recalls.delete(recallKeyOf(session));
85
80
  return null;
86
81
  }
87
- recalls.set(keyOf(session), block);
82
+ recalls.set(recallKeyOf(session), block);
88
83
  return block;
89
84
  } catch (error) {
90
85
  logger?.warn?.(`cortex prefetch failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -95,6 +90,7 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
95
90
  function recallText(context) {
96
91
  const sessionId = String(context?.session?.id ?? context?.agent?.id ?? context?.sessionId ?? '');
97
92
  if (sessionId && recalls.has(sessionId)) return recalls.get(sessionId);
93
+ if (config.recallSharing === true) return recalls.get('shared') ?? '';
98
94
  return '';
99
95
  }
100
96
 
@@ -176,7 +172,7 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
176
172
  if (config.autonomyOnTurnEnd !== false && typeof cortex.autonomy?.tick === 'function') {
177
173
  try { cortex.autonomy.tick({ at: event.time ?? Date.now(), max: 1 }); } catch { /* fail open */ }
178
174
  }
179
- recalls.delete(keyOf(session));
175
+ recalls.delete(recallKeyOf(session));
180
176
  currentTurns.delete(keyOf(session));
181
177
  }
182
178
  } catch (error) {