dsh-cortex-memory 0.4.11 → 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 (137) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +1 -1
  3. package/README.md +63 -38
  4. package/bench/ab-engine.mjs +60 -0
  5. package/bench/ann-bench.mjs +78 -0
  6. package/bench/hnsw-bench.mjs +79 -0
  7. package/bench/locomo.js +89 -0
  8. package/bench/longmemeval.js +83 -0
  9. package/bench/metrics.js +67 -0
  10. package/bench/migration-bench.mjs +69 -0
  11. package/bench/run.js +77 -0
  12. package/bench/synthetic.js +99 -0
  13. package/bench/vector-ab.mjs +76 -0
  14. package/docs/compatibility.md +39 -0
  15. package/docs/install-windows.md +145 -0
  16. package/docs/models.md +183 -0
  17. package/docs/multimodal.md +112 -0
  18. package/docs/permissions.md +53 -0
  19. package/docs/privacy.md +50 -0
  20. package/docs/scopes.md +142 -0
  21. package/examples/README.md +73 -0
  22. package/examples/setup-cortex-bge.ps1 +66 -0
  23. package/examples/uninstall-cortex.ps1 +92 -0
  24. package/index.js +23 -0
  25. package/package.json +11 -5
  26. package/src/core/config.js +27 -0
  27. package/src/engines/extract.js +10 -10
  28. package/src/engines/retrieve.js +30 -5
  29. package/src/guardian/guardian.js +2 -15
  30. package/src/guardian/invariants.js +9 -5
  31. package/src/host/runtime.js +10 -14
  32. package/src/self/evolution.js +32 -5
  33. package/src/self/policies.js +21 -2
  34. package/src/service/cortex.js +3 -2
  35. package/src/store/database.js +9 -1
  36. package/src/store/schema.sql +2 -1
  37. package/src/vector/hnsw.js +5 -5
  38. package/test/integration/_helpers.js +128 -0
  39. package/test/integration/acceptance.test.js +803 -0
  40. package/test/integration/ann-load.test.js +61 -0
  41. package/test/integration/api-contract.test.js +1476 -0
  42. package/test/integration/backup-privacy.test.js +214 -0
  43. package/test/integration/consolidate.test.js +75 -0
  44. package/test/integration/edge-cases.test.js +1088 -0
  45. package/test/integration/exchange.test.js +326 -0
  46. package/test/integration/life-loop.test.js +188 -0
  47. package/test/integration/load.test.js +751 -0
  48. package/test/integration/markdown-sync.test.js +35 -0
  49. package/test/integration/policy-query-api.test.js +306 -0
  50. package/test/integration/resilience-writes.test.js +241 -0
  51. package/test/integration/tools-contract.test.js +1324 -0
  52. package/test/unit/ann-edge.test.js +102 -0
  53. package/test/unit/ann.test.js +77 -0
  54. package/test/unit/api-client.test.js +576 -0
  55. package/test/unit/api-validate.test.js +19 -0
  56. package/test/unit/api.test.js +555 -0
  57. package/test/unit/appraisal.test.js +48 -0
  58. package/test/unit/attachments.test.js +33 -0
  59. package/test/unit/autonomy.test.js +53 -0
  60. package/test/unit/batch.test.js +46 -0
  61. package/test/unit/bench.test.js +40 -0
  62. package/test/unit/benchmark-synthetic.test.js +52 -0
  63. package/test/unit/client-contract.test.js +29 -0
  64. package/test/unit/compression.test.js +76 -0
  65. package/test/unit/core.test.js +77 -0
  66. package/test/unit/develop.test.js +130 -0
  67. package/test/unit/development.test.js +68 -0
  68. package/test/unit/digest.test.js +26 -0
  69. package/test/unit/dsr.test.js +111 -0
  70. package/test/unit/edges-candidates.test.js +113 -0
  71. package/test/unit/emotion.test.js +61 -0
  72. package/test/unit/encode.test.js +98 -0
  73. package/test/unit/evolution.test.js +130 -0
  74. package/test/unit/external-ann-search.test.js +50 -0
  75. package/test/unit/external-ann.test.js +29 -0
  76. package/test/unit/facts-belief.test.js +32 -0
  77. package/test/unit/facts.test.js +107 -0
  78. package/test/unit/feature-overrides.test.js +42 -0
  79. package/test/unit/fts-migration.test.js +42 -0
  80. package/test/unit/graph.test.js +79 -0
  81. package/test/unit/growth-reflect.test.js +123 -0
  82. package/test/unit/guard-runtime.test.js +40 -0
  83. package/test/unit/guardian.test.js +91 -0
  84. package/test/unit/health-privacy.test.js +102 -0
  85. package/test/unit/hnsw.test.js +35 -0
  86. package/test/unit/host-runtime.test.js +142 -0
  87. package/test/unit/host.test.js +58 -0
  88. package/test/unit/identity.test.js +98 -0
  89. package/test/unit/induct-evaluate.test.js +41 -0
  90. package/test/unit/ingest-extracted.test.js +35 -0
  91. package/test/unit/initiative.test.js +90 -0
  92. package/test/unit/jobs.test.js +93 -0
  93. package/test/unit/json-snapshot.test.js +57 -0
  94. package/test/unit/life-consolidate.test.js +34 -0
  95. package/test/unit/life.test.js +149 -0
  96. package/test/unit/llm-facts-integration.test.js +27 -0
  97. package/test/unit/llm-facts.test.js +16 -0
  98. package/test/unit/llm.test.js +45 -0
  99. package/test/unit/locomo.test.js +45 -0
  100. package/test/unit/longmemeval.test.js +56 -0
  101. package/test/unit/markdown-import.test.js +44 -0
  102. package/test/unit/markdown.test.js +34 -0
  103. package/test/unit/memory-edit.test.js +112 -0
  104. package/test/unit/metrics.test.js +26 -0
  105. package/test/unit/migration.test.js +38 -0
  106. package/test/unit/model-config.test.js +52 -0
  107. package/test/unit/narrative.test.js +62 -0
  108. package/test/unit/playbook-consolidate.test.js +24 -0
  109. package/test/unit/privacy-scope.test.js +39 -0
  110. package/test/unit/profile.test.js +20 -0
  111. package/test/unit/prompt.test.js +42 -0
  112. package/test/unit/providers.test.js +42 -0
  113. package/test/unit/qa.test.js +100 -0
  114. package/test/unit/query.test.js +53 -0
  115. package/test/unit/retention.test.js +31 -0
  116. package/test/unit/retrieval-ranking.test.js +31 -0
  117. package/test/unit/retrieve.test.js +117 -0
  118. package/test/unit/rotation.test.js +25 -0
  119. package/test/unit/scanner.test.js +50 -0
  120. package/test/unit/scenario.test.js +78 -0
  121. package/test/unit/scheduler.test.js +136 -0
  122. package/test/unit/self-state.test.js +94 -0
  123. package/test/unit/service.test.js +72 -0
  124. package/test/unit/shiori-import.test.js +77 -0
  125. package/test/unit/skills.test.js +104 -0
  126. package/test/unit/store.test.js +111 -0
  127. package/test/unit/temporal-graph.test.js +44 -0
  128. package/test/unit/tiers.test.js +39 -0
  129. package/test/unit/tokenizer-fts.test.js +35 -0
  130. package/test/unit/tools.test.js +122 -0
  131. package/test/unit/upgrade-0412.test.js +104 -0
  132. package/test/unit/upgrade-0413.test.js +84 -0
  133. package/test/unit/upgrade-0414.test.js +101 -0
  134. package/test/unit/vector-ann.test.js +53 -0
  135. package/test/unit/vector-async.test.js +69 -0
  136. package/test/unit/vector.test.js +68 -0
  137. package/test/unit/working.test.js +80 -0
@@ -0,0 +1,92 @@
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"
92
+
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.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",
@@ -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) {
@@ -34,6 +34,28 @@ export function createEvolutionEngine({
34
34
  let dayKey = '';
35
35
  let dayCount = 0;
36
36
 
37
+ // Rehydrate canaries after a process restart. Without this, an active
38
+ // policy that was still inside its observation window would never roll back.
39
+ for (const policy of policies.listCanaries?.() ?? []) {
40
+ const canary = policy.canary;
41
+ if (!canary || typeof canary !== 'object') continue;
42
+ canaries.set(policy.id, {
43
+ kind: policy.kind,
44
+ previousId: canary.previousId ?? null,
45
+ ticks: Number(canary.ticks) || 0,
46
+ activatedAt: Number(canary.activatedAt) || Date.now(),
47
+ });
48
+ }
49
+
50
+ function localDay(value) {
51
+ const date = new Date(value);
52
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
53
+ }
54
+
55
+ function persistCanary(id, canary) {
56
+ try { policies.setCanary?.(id, canary); } catch { /* persistence must not break evolution */ }
57
+ }
58
+
37
59
  function propose({ kind, config, rationale = '', metrics = null, scopeId = 'global' } = {}) {
38
60
  const policy = policies.create({ kind, config, rationale, metrics });
39
61
  audit?.record?.({
@@ -136,7 +158,7 @@ export function createEvolutionEngine({
136
158
  if (guardConfig.autoActivate !== true) {
137
159
  return { ...optimized, activated: [], deferred: 'auto-activate-off', guard: { ...guardConfig } };
138
160
  }
139
- const today = nowIso().slice(0, 10);
161
+ const today = localDay(Date.now());
140
162
  if (today !== dayKey) { dayKey = today; dayCount = 0; }
141
163
  const activated = [];
142
164
  const errors = [];
@@ -153,7 +175,7 @@ export function createEvolutionEngine({
153
175
  ? evaluateQuality({ scopeId, phase: 'after', baseline })
154
176
  : null;
155
177
  if (quality && quality.ok === false) {
156
- const target = previous?.id ? policies.rollback(policy.kind, previous.id) : policies.deactivate(policy.kind);
178
+ const target = previous?.id ? policies.rollback(policy.kind, previous.id) : policies.retire(policy.id);
157
179
  audit?.record?.({
158
180
  actor: 'self:autoEvolve',
159
181
  action: 'policy.autoevolve.quality-rollback',
@@ -164,12 +186,14 @@ export function createEvolutionEngine({
164
186
  errors.push({ id: proposal.id, error: 'quality-guard', quality });
165
187
  continue;
166
188
  }
167
- canaries.set(policy.id, {
189
+ const canary = {
168
190
  kind: policy.kind,
169
191
  previousId: previous?.id ?? null,
170
192
  ticks: 0,
171
193
  activatedAt: Date.now(),
172
- });
194
+ };
195
+ canaries.set(policy.id, canary);
196
+ persistCanary(policy.id, canary);
173
197
  lastActivatedAt = Date.now();
174
198
  dayCount += 1;
175
199
  activated.push(policy);
@@ -189,7 +213,7 @@ export function createEvolutionEngine({
189
213
  if (failed) {
190
214
  for (const [id, canary] of [...canaries.entries()]) {
191
215
  try {
192
- const target = canary.previousId ? policies.rollback(canary.kind, canary.previousId) : policies.deactivate(canary.kind);
216
+ const target = canary.previousId ? policies.rollback(canary.kind, canary.previousId) : policies.retire(id);
193
217
  audit?.record?.({
194
218
  actor: 'self:autoRollback',
195
219
  action: 'policy.autoevolve.rollback',
@@ -199,6 +223,7 @@ export function createEvolutionEngine({
199
223
  });
200
224
  rolledBack.push({ id, kind: canary.kind, to: target?.id ?? null });
201
225
  canaries.delete(id);
226
+ persistCanary(id, null);
202
227
  } catch (error) {
203
228
  rolledBack.push({ id, kind: canary.kind, error: error instanceof Error ? error.message : String(error) });
204
229
  }
@@ -209,6 +234,7 @@ export function createEvolutionEngine({
209
234
  canary.ticks += 1;
210
235
  if (canary.ticks >= guardConfig.canaryTicks) {
211
236
  canaries.delete(id);
237
+ persistCanary(id, null);
212
238
  audit?.record?.({
213
239
  actor: 'self:canary',
214
240
  action: 'policy.autoevolve.promote',
@@ -218,6 +244,7 @@ export function createEvolutionEngine({
218
244
  });
219
245
  } else {
220
246
  canaries.set(id, canary);
247
+ persistCanary(id, canary);
221
248
  }
222
249
  }
223
250
  return { rolledBack, pending: canaries.size };
@@ -13,6 +13,7 @@ function rowToPolicy(row) {
13
13
  status: row.status,
14
14
  createdAt: row.created_at,
15
15
  activatedAt: row.activated_at,
16
+ canary: row.canary_json ? JSON.parse(row.canary_json) : null,
16
17
  };
17
18
  }
18
19
 
@@ -72,10 +73,28 @@ export function createPolicyRepository(db) {
72
73
  function deactivate(kind) {
73
74
  const current = active(kind);
74
75
  if (!current) return null;
75
- db.prepare("UPDATE policies SET status = 'candidate', activated_at = NULL WHERE id = ?").run(current.id);
76
+ db.prepare("UPDATE policies SET status = 'candidate', activated_at = NULL, canary_json = NULL WHERE id = ?").run(current.id);
76
77
  return get(current.id);
77
78
  }
78
79
 
80
+ function retire(id) {
81
+ const target = get(id);
82
+ if (!target) return null;
83
+ db.prepare("UPDATE policies SET status = 'superseded', activated_at = NULL, canary_json = NULL WHERE id = ?").run(id);
84
+ return get(id);
85
+ }
86
+
87
+ function setCanary(id, canary) {
88
+ const policy = get(id);
89
+ if (!policy) throw new Error(`policy not found: ${id}`);
90
+ db.prepare('UPDATE policies SET canary_json = ? WHERE id = ?').run(canary == null ? null : stableStringify(canary), id);
91
+ return get(id);
92
+ }
93
+
94
+ function listCanaries() {
95
+ return db.prepare("SELECT * FROM policies WHERE status = 'active' AND canary_json IS NOT NULL ORDER BY activated_at DESC").all().map(rowToPolicy);
96
+ }
97
+
79
98
  function updateMetrics(id, metrics) {
80
99
  const policy = get(id);
81
100
  if (!policy) throw new Error(`policy not found: ${id}`);
@@ -83,5 +102,5 @@ export function createPolicyRepository(db) {
83
102
  return get(id);
84
103
  }
85
104
 
86
- return { get, list, active, create, activate, rollback, deactivate, updateMetrics };
105
+ return { get, list, active, create, activate, rollback, deactivate, retire, setCanary, listCanaries, updateMetrics };
87
106
  }
@@ -339,6 +339,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
339
339
  traceId: result.trace?.id ?? null,
340
340
  eventId: result.event?.id ?? null,
341
341
  recordedAt: result.trace?.recordedAt ?? null,
342
+ persona: config.persona,
342
343
  });
343
344
  if (config.features?.autoGraphCandidates === true || config.features?.graphCandidateAutoFacts === true) {
344
345
  const queued = [];
@@ -1455,12 +1456,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1455
1456
  },
1456
1457
  flushLlmFacts,
1457
1458
  recallTiered: ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
1458
- const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
1459
+ const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
1459
1460
  const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
1460
1461
  return { query, result, selection, text: renderTiers(selection) };
1461
1462
  },
1462
1463
  recallTieredAsync: async ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
1463
- const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
1464
+ const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
1464
1465
  const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
1465
1466
  return { query, result, selection, text: renderTiers(selection) };
1466
1467
  },