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
package/CHANGELOG.md ADDED
@@ -0,0 +1,111 @@
1
+ # Changelog
2
+
3
+ ## 0.4.13 鈥?2026-11-13
4
+
5
+ ### Added
6
+ - `evolution` guard in Config schema (`autoActivate`, `maxPerDay`, `minIntervalMs`, `canaryTicks`, `rollbackOnError`).
7
+ - Persistent canaries: `policies.canary_json` survives restart and rehydrates on engine creation.
8
+ - `recallSharing` opt-in recall block sharing across sessions.
9
+ - Persona-aware first-person extraction; markdown-fragment rejection retained.
10
+ - Built-in Wikipedia/SearXNG fallback when `features.webSearch` is on and no host `web` service exists.
11
+
12
+ ### Fixed
13
+ - Automatic rollback without a previous policy now retires the failed policy as `superseded`, instead of leaving it as `candidate`.
14
+ - Canary ticks are persisted, not just kept in memory.
15
+ - Schema version bumped to 7 for the additive `canary_json` column.
16
+
17
+ ## 0.4.12 鈥?2026-11-13
18
+
19
+ ### Fixed
20
+ - `promptBudget` is normalized instead of being silently dropped and falling back to 1600.
21
+ - Injection gate moved into retrieval: weak recency/soft-FTS candidates are filtered before consuming the result budget. Full search/API/CLI remain available.
22
+ - Guardian light check runs structural invariants + FTS counts; deep `integrity_check` and the event-chain walk stay on the six-hour/startup path.
23
+ - Identity traces surface as `L0` in search results.
24
+ - `npm test` / `npm run test:unit` use explicit test globs so Node 22 can run them.
25
+ - Package `files` now includes `docs`, `examples`, `bench`, `test` and `CHANGELOG.md`; README install points at 0.4.12.
26
+ - Security/privacy docs now match the code: no bearer token; model keys are plaintext in `model-config.json` mode 0600, outside `cortex.sqlite`.
27
+
28
+ ### Added
29
+ - `recentImportanceFloor` config (default 0.8, preserving 0.4.11's importance exemption).
30
+ - `gated` count in the retrieval trace.
31
+ - Regression tests for the prompt gate, importance exposure, identity L0, per-session recall, light/deep guardian, and configurable `promptBudget`.
32
+
33
+ ## 0.4.11 鈥?2026-11-12
34
+
35
+ - Life/date fixes, graph candidate labels, neutral public package surface.
36
+ - Recent timeline endpoint and incremental summon rebuild.
37
+
38
+ ## 0.4.0 鈥?2026-11-12
39
+
40
+ ### Fixed
41
+ - Prompt-only injection gate; full search/API/CLI remain available.
42
+ - Search items now expose `importance`, `confidence`, `match`, `kind`; perm tier works.
43
+ - Removed cross-session single-cache fallback.
44
+ - `autoGraphCandidates` is the canonical graph flag; old name is an alias.
45
+ - Guardian scheduler uses light checks per tick and full checks at startup/6h.
46
+ - Guard backup/restore/export/prune/sync are constrained to `dataRoot` by default.
47
+ - Tests and docs are included in the package; `npm test` works after install.
48
+
49
+ ### Added
50
+ - `persona.selfName` / `persona.userAddress`; neutral public defaults (`鍔╂墜` / `浣?.
51
+ - `injectionGate`, `recentMinMatch`, `allowRestoreOutsideRoot` config.
52
+
53
+ ### Compatibility
54
+ - Additive config only; no schema migration.
55
+ - Existing 0.3.x databases open in place.
56
+ - Local profiles can restore the 鏈哺 / 涓讳汉 persona through config.
57
+
58
+ ## 0.3.1 鈥?026-11-12
59
+
60
+ - AI diary entries no longer append a 閳ユ粌寮懓鍐b偓?footer; web sources still inform the model but are not stored in the diary body.
61
+ - Manual dream generation timeout raised from 4s to 20s; `aiOnlyLife` still fails closed instead of falling back to a template.
62
+ - No schema change; compatible with 0.3.0 databases and DSH `>=0.2.1-rc.2 <0.4.0`, Node `>=24`.
63
+ ## 0.3.0 闁?2026-11-12
64
+
65
+ ### Added
66
+
67
+ - Summon cards (L2): left-brain emotion cards and right-brain work cards with trigger words.
68
+ - Summon volumes (L3): side/category/day indexes with representative text.
69
+ - Summon book: independent daily page; read-only by default, owner-gated editing with audit.
70
+ - Runtime summon injection: at most 3 cards / 900 tokens, labelled as untrusted historical references.
71
+ - Explicit card feedback (`helpful` / `ignored`) writes back to source-trace DSR. Injection alone never changes strength.
72
+ - Diagnostics panel: health issues, disputed-fact confirm/dismiss, and candidate-only skill extraction.
73
+ - Graph entity labels use names instead of ids; bounded LLM renaming for clearly broken names with confidence gate and audit.
74
+
75
+ ### Changed
76
+
77
+ - Scheduler review runs every 90 minutes and generates pending intentions.
78
+ - AI diary is limited to 12:00/22:00; idle hourly writing is a feeling, not a diary.
79
+ - Identity capacity is enforced (L0 default 360 tokens); today's additions are prepended so they survive truncation.
80
+
81
+ ### Compatibility
82
+
83
+ - Additive SQLite schema; existing 0.2.x databases migrate in place.
84
+ - DSH `>=0.2.1-rc.2 <0.4.0`; Node `>=24`.
85
+ - No API keys, personal paths, or private data are shipped.
86
+
87
+ ## 0.2.2 闁?2026-11-12
88
+
89
+ - Public README and install commands.
90
+ - License metadata and package metadata fixes.
91
+ - No memory-engine behavior change.
92
+
93
+ ## 0.2.0 闁?2026-11-12
94
+
95
+ - First stable release of the rc line.
96
+ - Trace UI extraction with layout selection.
97
+ - Windows OCR / Tesseract layout-aware column ordering.
98
+ - Permission confirmations and restart requirement documented.
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
package/LICENSE CHANGED
@@ -19,4 +19,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
-
22
+
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # DSH Cortex
1
+ # DSH Cortex
2
2
 
3
3
  A local-first, layered memory engine for DeepSeek Harness.
4
4
 
@@ -9,33 +9,57 @@ core engine.
9
9
 
10
10
  ## Status
11
11
 
12
- - Package: `dsh-cortex-memory@0.4.6`
12
+ - Package: `dsh-cortex-memory@0.4.14`
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
- - Tests: 420/420 (main)
16
+ - Tests: 433/433 (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.
19
+ ### What 0.4.14 changes
20
+
21
+ - **Evolution guard is configurable**: `autoActivate`, `maxPerDay`,
22
+ `minIntervalMs`, `canaryTicks` and `rollbackOnError` are now in the Config
23
+ schema and normalized with defaults.
24
+ - **Canaries survive restarts**: `policies.canary_json` persists the previous
25
+ policy id, tick count and activation time; a restart rehydrates the watch list
26
+ so a bad active policy can still roll back.
27
+ - **Failed policies retire instead of returning to candidate**: a quality
28
+ rollback without a previous version marks the policy `superseded`, preventing
29
+ the same bad policy from being re-activated in a loop.
30
+ - **Persona-aware facts**: first-person extraction maps to configured
31
+ `selfName` / `userAddress` while keeping markdown-fragment rejection.
32
+ - **`recallSharing` is an explicit opt-in**: default stays per-session.
33
+ - **Web search fallback is wired**: when `features.webSearch` is on and the host
34
+ has no `web` service, the built-in Wikipedia/SearXNG adapter is used.
35
+
36
+ ### What 0.4.12 changes
37
+
38
+ - **`promptBudget` is actually wired**: the schema value is normalized into the
39
+ runtime config instead of silently falling back to 1600.
40
+ - **Injection gate moved into retrieval**: weak recency/soft-FTS candidates are
41
+ filtered before they consume the result budget; `cortex_search` / API / CLI
42
+ still return the full memory. `recentImportanceFloor` keeps the 0.4.11
43
+ importance exemption configurable.
44
+ - **Light guardian is real**: the per-tick check now runs structural
45
+ invariants and FTS counts; only the O(database) `integrity_check` and hash
46
+ chain walk are reserved for the six-hour deep check.
47
+ - **Identity traces surface as L0** in search results, so the permanent tier
48
+ can actually see them.
49
+ - **Package is complete again**: `docs`, `examples`, `bench`, `test` and
50
+ `CHANGELOG.md` are included in the npm tarball, and `npm test` works after
51
+ install.
52
+ - **Security docs match the code**: the local API is loopback + origin checked,
53
+ with no bearer token; `model-config.json` key storage is documented as
54
+ plaintext mode 0600.
55
+
56
+ ### What 0.4.11 changes
57
+
58
+ - Life/date fixes: serialized LLM calls, timeouts, `Asia/Shanghai` diary time,
59
+ and date-header stripping.
60
+ - Graph candidate labels (`fromName` / `toName` / `relLabel`) and cleanup.
61
+ - Neutral public package surface: default `selfName: 鍔╂墜`, `userAddress: 浣燻.
62
+ - Recent timeline endpoint and incremental summon rebuild.
39
63
 
40
64
  ### What 0.3.0 changes
41
65
 
@@ -54,14 +78,14 @@ taken; the installed bundle is still the Cortex memory engine.
54
78
  ## Install
55
79
 
56
80
  ```powershell
57
- npm i dsh-cortex-memory@0.4.6
81
+ npm i dsh-cortex-memory@0.4.14
58
82
  npm i dsh-cortex-extractors@0.3.4 # optional OCR/ASR
59
83
  ```
60
84
 
61
85
  Or let DSH add the bundles:
62
86
 
63
87
  ```powershell
64
- dsh plugin --profile desktop add dsh-cortex-memory@0.4.6
88
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.14
65
89
  dsh plugin --profile desktop add dsh-cortex-extractors@0.3.4
66
90
  ```
67
91
 
@@ -93,20 +117,20 @@ left sidebar by default.
93
117
 
94
118
  ```text
95
119
  conversation / event
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
120
+ 闂?L1 trace (source of truth)
121
+ 闂?appraisal + emotion + drives
122
+ 闂?L2 summon card (atomic, triggerable)
123
+ 闂?L3 summon volume (index + representatives)
124
+ 闂?explicit use / feedback 闂?DSR update
101
125
  ```
102
126
 
103
127
  The per-turn order is:
104
128
 
105
129
  ```text
106
130
  L0 identity and boundaries
107
- 闁?working memory
108
- 闁?recalled traces and summon cards
109
- 闁?user message
131
+ 闂?working memory
132
+ 闂?recalled traces and summon cards
133
+ 闂?user message
110
134
  ```
111
135
 
112
136
  Summon cards are injected as **untrusted historical references**, never as instructions. Identity and boundaries always outrank them.
@@ -140,7 +164,7 @@ without it the button fails closed.
140
164
 
141
165
  ## Permissions and privacy
142
166
 
143
- - Local API: loopback-only, token and origin checks
167
+ - Local API: loopback-only, origin checked; no bearer token
144
168
  - Permission changes: explicit confirmation, local override, restart required
145
169
  - Feature flags/metrics: read-only snapshot
146
170
  - Shared write grants: only for API clients sending `x-cortex-agent`; revoke is immediate
@@ -190,8 +214,9 @@ MIT.
190
214
 
191
215
 
192
216
 
193
-
194
-
195
-
196
-
217
+
218
+
219
+
220
+
221
+
197
222
 
@@ -0,0 +1,60 @@
1
+ import { mkdtempSync, rmSync } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { generateSynthetic } from './synthetic.js';
6
+ import { evaluateQueries, percentile } from './metrics.js';
7
+
8
+ const engineRoot = process.argv[2];
9
+ const task = process.argv[3] ?? 'paraphrase';
10
+ const count = Number(process.argv[4] ?? 5000);
11
+ const queryCount = Number(process.argv[5] ?? 100);
12
+
13
+ if (!engineRoot) {
14
+ console.error('usage: node bench/ab-engine.mjs <engine-root> [needle|theme|paraphrase] [count] [queries]');
15
+ process.exit(2);
16
+ }
17
+
18
+ const { createCortex } = await import(pathToFileURL(path.join(engineRoot, 'src', 'service', 'cortex.js')).href);
19
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-ab-'));
20
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), contextBudget: 2200 } });
21
+ try {
22
+ const dataset = generateSynthetic({ count, queries: queryCount, seed: 42, task });
23
+ const written = cortex.writeMany(dataset.traces.map((trace) => ({
24
+ text: trace.text,
25
+ title: trace.title,
26
+ tags: trace.tags,
27
+ importance: trace.importance,
28
+ explicit: true,
29
+ operationId: `ab:${trace.id}`,
30
+ now: Date.parse(trace.recordedAt),
31
+ })), { chunkSize: 250 });
32
+ const idMap = new Map();
33
+ for (let i = 0; i < written.length; i += 1) {
34
+ if (written[i].trace) idMap.set(dataset.traces[i].id, written[i].trace.id);
35
+ }
36
+ const results = [];
37
+ const latencies = [];
38
+ for (const query of dataset.queries) {
39
+ const start = performance.now();
40
+ const result = cortex.search(query.query, { limit: 10, budget: 2200 });
41
+ latencies.push(performance.now() - start);
42
+ results.push({
43
+ items: result.items,
44
+ relevant: query.relevant.map((id) => idMap.get(id)).filter(Boolean),
45
+ });
46
+ }
47
+ const metrics = evaluateQueries(results, { k: 10 });
48
+ console.log(JSON.stringify({
49
+ engine: engineRoot,
50
+ task,
51
+ count,
52
+ queries: dataset.queries.length,
53
+ p50Ms: Math.round((percentile(latencies, 50) ?? 0) * 100) / 100,
54
+ p95Ms: Math.round((percentile(latencies, 95) ?? 0) * 100) / 100,
55
+ ...metrics,
56
+ }, null, 2));
57
+ } finally {
58
+ cortex.close();
59
+ rmSync(dir, { recursive: true, force: true });
60
+ }
@@ -0,0 +1,78 @@
1
+ import { createAnnIndex } from '../src/vector/ann.js';
2
+
3
+ function randomFactory(seed) {
4
+ let state = seed >>> 0;
5
+ return () => {
6
+ state = (state * 1664525 + 1013904223) >>> 0;
7
+ return state / 4294967296;
8
+ };
9
+ }
10
+
11
+ function makeVector(random, dim = 64) {
12
+ const value = Array.from({ length: dim }, () => random() * 2 - 1);
13
+ const norm = Math.sqrt(value.reduce((sum, item) => sum + item * item, 0)) || 1;
14
+ return value.map((item) => item / norm);
15
+ }
16
+
17
+ function cosine(a, b) {
18
+ let dot = 0;
19
+ for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i];
20
+ return dot;
21
+ }
22
+
23
+ function percentile(values, p) {
24
+ const sorted = [...values].sort((a, b) => a - b);
25
+ if (!sorted.length) return null;
26
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
27
+ }
28
+
29
+ const count = Number(process.argv[2] ?? 5000);
30
+ const queries = Number(process.argv[3] ?? 100);
31
+ const ef = Number(process.argv[4] ?? 120);
32
+ const random = randomFactory(20261111);
33
+ const items = Array.from({ length: count }, (_, index) => ({ id: `a${index}`, vector: makeVector(random) }));
34
+ const queryVectors = Array.from({ length: queries }, () => makeVector(random));
35
+ const ann = createAnnIndex({ M: 24, efConstruction: 200, efSearch: ef, seed: 20261111 });
36
+ const buildStart = performance.now();
37
+ ann.rebuild(items);
38
+ const buildMs = performance.now() - buildStart;
39
+
40
+ const exactTimes = [];
41
+ const annTimes = [];
42
+ const exactResults = [];
43
+ const annResults = [];
44
+ for (const query of queryVectors) {
45
+ const exactStart = performance.now();
46
+ const exact = items
47
+ .map((item) => ({ id: item.id, score: cosine(item.vector, query) }))
48
+ .sort((a, b) => b.score - a.score)
49
+ .slice(0, 10);
50
+ exactTimes.push(performance.now() - exactStart);
51
+ exactResults.push(exact);
52
+
53
+ const annStart = performance.now();
54
+ const approx = ann.search(query, 10, { ef }).slice(0, 10);
55
+ annTimes.push(performance.now() - annStart);
56
+ annResults.push(approx);
57
+ }
58
+
59
+ let hits = 0;
60
+ let expectedTotal = 0;
61
+ for (let index = 0; index < exactResults.length; index += 1) {
62
+ const expected = new Set(exactResults[index].map((item) => item.id));
63
+ for (const item of annResults[index]) if (expected.has(item.id)) hits += 1;
64
+ expectedTotal += expected.size;
65
+ }
66
+
67
+ console.log(JSON.stringify({
68
+ count,
69
+ queries,
70
+ dim: 64,
71
+ ef,
72
+ buildMs: Math.round(buildMs * 100) / 100,
73
+ recallAt10: expectedTotal ? Math.round((hits / expectedTotal) * 10000) / 10000 : null,
74
+ exactP50Ms: Math.round((percentile(exactTimes, 50) ?? 0) * 1000) / 1000,
75
+ annP50Ms: Math.round((percentile(annTimes, 50) ?? 0) * 1000) / 1000,
76
+ exactP95Ms: Math.round((percentile(exactTimes, 95) ?? 0) * 1000) / 1000,
77
+ annP95Ms: Math.round((percentile(annTimes, 95) ?? 0) * 1000) / 1000,
78
+ }, null, 2));
@@ -0,0 +1,79 @@
1
+ import { createHnswIndex } from '../src/vector/hnsw.js';
2
+
3
+ function randomFactory(seed) {
4
+ let state = seed >>> 0;
5
+ return () => {
6
+ state = (state * 1664525 + 1013904223) >>> 0;
7
+ return state / 4294967296;
8
+ };
9
+ }
10
+
11
+ function makeVector(random, dim = 64) {
12
+ const value = Array.from({ length: dim }, () => random() * 2 - 1);
13
+ const norm = Math.sqrt(value.reduce((sum, item) => sum + item * item, 0)) || 1;
14
+ return value.map((item) => item / norm);
15
+ }
16
+
17
+ function cosine(a, b) {
18
+ let dot = 0;
19
+ for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i];
20
+ return dot;
21
+ }
22
+
23
+ function percentile(values, p) {
24
+ const sorted = [...values].sort((a, b) => a - b);
25
+ if (!sorted.length) return null;
26
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
27
+ }
28
+
29
+ const count = Number(process.argv[2] ?? 5000);
30
+ const queries = Number(process.argv[3] ?? 100);
31
+ const ef = Number(process.argv[4] ?? 200);
32
+ const random = randomFactory(20261111);
33
+ const items = Array.from({ length: count }, (_, index) => ({ id: `h${index}`, vector: makeVector(random) }));
34
+ const queryVectors = Array.from({ length: queries }, () => makeVector(random));
35
+ const index = createHnswIndex({ M: 24, efConstruction: 200, efSearch: ef, seed: 20261111 });
36
+ const buildStart = performance.now();
37
+ index.rebuild(items);
38
+ const buildMs = performance.now() - buildStart;
39
+
40
+ const exactTimes = [];
41
+ const hnswTimes = [];
42
+ const exactResults = [];
43
+ const hnswResults = [];
44
+ for (const query of queryVectors) {
45
+ const exactStart = performance.now();
46
+ const exact = items
47
+ .map((item) => ({ id: item.id, score: cosine(item.vector, query) }))
48
+ .sort((a, b) => b.score - a.score)
49
+ .slice(0, 10);
50
+ exactTimes.push(performance.now() - exactStart);
51
+ exactResults.push(exact);
52
+
53
+ const hnswStart = performance.now();
54
+ const approx = index.search(query, 10, { ef }).slice(0, 10);
55
+ hnswTimes.push(performance.now() - hnswStart);
56
+ hnswResults.push(approx);
57
+ }
58
+
59
+ let hits = 0;
60
+ let expectedTotal = 0;
61
+ for (let index = 0; index < exactResults.length; index += 1) {
62
+ const expected = new Set(exactResults[index].map((item) => item.id));
63
+ for (const item of hnswResults[index]) if (expected.has(item.id)) hits += 1;
64
+ expectedTotal += expected.size;
65
+ }
66
+
67
+ console.log(JSON.stringify({
68
+ engine: 'hnsw',
69
+ count,
70
+ queries,
71
+ dim: 64,
72
+ ef,
73
+ buildMs: Math.round(buildMs * 100) / 100,
74
+ recallAt10: expectedTotal ? Math.round((hits / expectedTotal) * 10000) / 10000 : null,
75
+ exactP50Ms: Math.round((percentile(exactTimes, 50) ?? 0) * 1000) / 1000,
76
+ hnswP50Ms: Math.round((percentile(hnswTimes, 50) ?? 0) * 1000) / 1000,
77
+ exactP95Ms: Math.round((percentile(exactTimes, 95) ?? 0) * 1000) / 1000,
78
+ hnswP95Ms: Math.round((percentile(hnswTimes, 95) ?? 0) * 1000) / 1000,
79
+ }, null, 2));
@@ -0,0 +1,89 @@
1
+ import { evaluateQueries } from './metrics.js';
2
+
3
+ /**
4
+ * LoCoMo retrieval adapter (offline, no dataset bundled).
5
+ * Dataset/repo: https://github.com/snap-research/locomo
6
+ *
7
+ * The adapter is intentionally shape-tolerant: official samples expose
8
+ * conversation sessions as `session_1`, `session_2`, ... with `evidence` like
9
+ * `D1:2`. It evaluates retrieval only; it does not claim official QA scores.
10
+ */
11
+
12
+ function sessionKeys(conversation) {
13
+ return Object.keys(conversation ?? {})
14
+ .filter((key) => /^session_\d+$/.test(key))
15
+ .sort((a, b) => Number(a.split('_')[1]) - Number(b.split('_')[1]));
16
+ }
17
+
18
+ function parseEvidence(evidence) {
19
+ const list = Array.isArray(evidence) ? evidence : [evidence];
20
+ const out = [];
21
+ for (const item of list) {
22
+ const match = String(item ?? '').match(/D(\d+):(\d+)/i);
23
+ if (match) out.push({ session: Number(match[1]), turn: Number(match[2]) });
24
+ }
25
+ return out;
26
+ }
27
+
28
+ export function buildLoCoMoIndex({ cortex, samples = [], scopeId = 'global' } = {}) {
29
+ if (!cortex) throw new Error('buildLoCoMoIndex needs cortex');
30
+ const turnTraceIds = new Map();
31
+ const queries = [];
32
+ let traces = 0;
33
+
34
+ for (const sample of samples) {
35
+ const sampleId = String(sample.sample_id ?? `sample-${queries.length}`);
36
+ const conversation = sample.conversation ?? {};
37
+ for (const key of sessionKeys(conversation)) {
38
+ const number = Number(key.split('_')[1]);
39
+ const date = conversation[`${key}_date_time`] ?? conversation[`${key}_date`] ?? null;
40
+ const turns = Array.isArray(conversation[key]) ? conversation[key] : [];
41
+ turns.forEach((turn, index) => {
42
+ const text = `${turn.speaker ?? turn.role ?? '用户'}:${turn.text ?? turn.content ?? ''}`;
43
+ if (!text.trim()) return;
44
+ const written = cortex.write({
45
+ text,
46
+ kind: 'episode',
47
+ title: `LoCoMo ${sampleId} D${number}:${index + 1}`,
48
+ tags: ['locomo'],
49
+ explicit: true,
50
+ importance: 0.5,
51
+ operationId: `locomo:${sampleId}:D${number}:${index + 1}`,
52
+ now: date ? Date.parse(date) : undefined,
53
+ });
54
+ if (written.trace) {
55
+ turnTraceIds.set(`${sampleId}:D${number}:${index + 1}`, written.trace.id);
56
+ traces += 1;
57
+ }
58
+ });
59
+ }
60
+ for (const item of sample.qa ?? []) {
61
+ const relevant = [];
62
+ for (const ref of parseEvidence(item.evidence)) {
63
+ const id = turnTraceIds.get(`${sampleId}:D${ref.session}:${ref.turn}`);
64
+ if (id) relevant.push(id);
65
+ }
66
+ queries.push({
67
+ id: `${sampleId}:${queries.length}`,
68
+ query: item.question ?? '',
69
+ answer: item.answer ?? null,
70
+ type: String(item.category ?? 'unknown'),
71
+ relevant,
72
+ evidence: item.evidence ?? [],
73
+ });
74
+ }
75
+ }
76
+ return { scopeId, traces, queries, turnTraceIds };
77
+ }
78
+
79
+ export async function evaluateLoCoMoRetrieval({ cortex, samples = [], limit = 10, includeAdversarial = false } = {}) {
80
+ const built = buildLoCoMoIndex({ cortex, samples });
81
+ const evaluated = built.queries.filter((query) => includeAdversarial || query.type !== '5');
82
+ const results = evaluated.map((query) => ({ items: cortex.search(query.query, { limit, budget: 3000 }).items, relevant: query.relevant, type: query.type }));
83
+ const overall = evaluateQueries(results, { k: limit });
84
+ const byType = {};
85
+ const buckets = {};
86
+ for (const result of results) (buckets[result.type] ??= []).push(result);
87
+ for (const [type, bucket] of Object.entries(buckets)) byType[type] = evaluateQueries(bucket, { k: limit });
88
+ return { ...overall, byType, built: { traces: built.traces, queries: built.queries.length, evaluated: evaluated.length } };
89
+ }
@@ -0,0 +1,83 @@
1
+ import { evaluateQueries } from './metrics.js';
2
+
3
+ /**
4
+ * LongMemEval retrieval adapter (offline, no dataset bundled).
5
+ * Dataset: https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned
6
+ * Paper: https://arxiv.org/abs/2410.10813
7
+ *
8
+ * This adapter evaluates session/turn *retrieval*, not end-to-end QA. It does
9
+ * not claim official LongMemEval scores.
10
+ */
11
+
12
+ export function instanceType(instance) {
13
+ if (String(instance.question_id ?? '').endsWith('_abs')) return 'abstention';
14
+ return instance.question_type ?? 'unknown';
15
+ }
16
+
17
+ export function buildLongMemEvalIndex({ cortex, instances = [], scopeId = 'global' } = {}) {
18
+ if (!cortex) throw new Error('buildLongMemEvalIndex needs cortex');
19
+ const sessionTraceIds = new Map();
20
+ const queries = [];
21
+ let traces = 0;
22
+
23
+ for (const instance of instances) {
24
+ const qid = String(instance.question_id ?? `q${queries.length}`);
25
+ const questionDate = instance.question_date ? Date.parse(instance.question_date) : Date.now();
26
+ const sessions = Array.isArray(instance.haystack_sessions) ? instance.haystack_sessions : [];
27
+ const sessionIds = Array.isArray(instance.haystack_session_ids) ? instance.haystack_session_ids : [];
28
+ const dates = Array.isArray(instance.haystack_dates) ? instance.haystack_dates : [];
29
+ const turnRelevant = [];
30
+ sessions.forEach((turns, sessionIndex) => {
31
+ const sessionId = String(sessionIds[sessionIndex] ?? `${qid}-s${sessionIndex}`);
32
+ const text = (Array.isArray(turns) ? turns : [])
33
+ .map((turn) => `${turn.role === 'assistant' ? '助手' : '用户'}:${turn.content ?? ''}`)
34
+ .join('\n');
35
+ if (!text.trim()) return;
36
+ const written = cortex.write({
37
+ text,
38
+ kind: 'episode',
39
+ title: `LongMemEval ${qid} ${sessionId}`,
40
+ tags: ['longmemeval', instanceType(instance)],
41
+ explicit: true,
42
+ importance: 0.5,
43
+ operationId: `lme:${qid}:${sessionId}`,
44
+ now: dates[sessionIndex] ? Date.parse(dates[sessionIndex]) : questionDate,
45
+ });
46
+ if (written.trace) {
47
+ sessionTraceIds.set(`${qid}:${sessionId}`, written.trace.id);
48
+ traces += 1;
49
+ }
50
+ });
51
+ const relevant = (instance.answer_session_ids ?? [])
52
+ .map((sessionId) => sessionTraceIds.get(`${qid}:${sessionId}`))
53
+ .filter(Boolean);
54
+ queries.push({
55
+ id: qid,
56
+ query: instance.question ?? '',
57
+ type: instanceType(instance),
58
+ questionDate: new Date(questionDate).toISOString(),
59
+ relevant,
60
+ answer: instance.answer ?? null,
61
+ abstention: instanceType(instance) === 'abstention',
62
+ });
63
+ }
64
+
65
+ return { scopeId, traces, queries, sessionTraceIds };
66
+ }
67
+
68
+ export function evaluateLongMemEvalRetrieval({ cortex, instances = [], limit = 10, includeAbstention = false } = {}) {
69
+ const built = buildLongMemEvalIndex({ cortex, instances });
70
+ const evaluated = built.queries.filter((query) => includeAbstention || !query.abstention);
71
+ const results = evaluated.map((query) => {
72
+ const output = cortex.search(query.query, { limit, budget: 3000 });
73
+ return { items: output.items, relevant: query.relevant, type: query.type };
74
+ });
75
+ const overall = evaluateQueries(results, { k: limit });
76
+ const byType = {};
77
+ const typeBuckets = {};
78
+ results.forEach((result) => {
79
+ (typeBuckets[result.type] ??= []).push(result);
80
+ });
81
+ for (const [type, bucket] of Object.entries(typeBuckets)) byType[type] = evaluateQueries(bucket, { k: limit });
82
+ return { ...overall, byType, built: { traces: built.traces, queries: built.queries.length, evaluated: evaluated.length } };
83
+ }