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.
- package/CHANGELOG.md +112 -0
- package/LICENSE +1 -1
- package/README.md +62 -36
- package/bench/README.md +29 -0
- package/bench/ab-engine.mjs +60 -0
- package/bench/ann-bench.mjs +78 -0
- package/bench/hnsw-bench.mjs +79 -0
- package/bench/locomo.js +89 -0
- package/bench/longmemeval.js +83 -0
- package/bench/metrics.js +67 -0
- package/bench/migration-bench.mjs +69 -0
- package/bench/results/semantic-cn.json +24 -0
- package/bench/run.js +77 -0
- package/bench/semantic-cn.js +116 -0
- package/bench/synthetic.js +99 -0
- package/bench/vector-ab.mjs +76 -0
- package/docs/compatibility.md +39 -0
- package/docs/install-windows.md +144 -0
- package/docs/models.md +183 -0
- package/docs/multimodal.md +112 -0
- package/docs/permissions.md +53 -0
- package/docs/privacy.md +50 -0
- package/docs/scopes.md +142 -0
- package/examples/README.md +72 -0
- package/examples/setup-cortex-bge.ps1 +66 -0
- package/examples/uninstall-cortex.ps1 +91 -0
- package/index.js +23 -0
- package/package.json +11 -5
- package/src/core/config.js +27 -0
- package/src/engines/extract.js +10 -10
- package/src/engines/retrieve.js +30 -5
- package/src/guardian/guardian.js +2 -15
- package/src/guardian/invariants.js +9 -5
- package/src/host/runtime.js +10 -14
- package/src/self/evolution.js +32 -5
- package/src/self/policies.js +21 -2
- package/src/service/cortex.js +3 -2
- package/src/store/database.js +9 -1
- package/src/store/schema.sql +2 -1
- package/src/vector/hnsw.js +5 -5
- package/test/integration/_helpers.js +128 -0
- package/test/integration/acceptance.test.js +803 -0
- package/test/integration/ann-load.test.js +61 -0
- package/test/integration/api-contract.test.js +1476 -0
- package/test/integration/backup-privacy.test.js +214 -0
- package/test/integration/consolidate.test.js +75 -0
- package/test/integration/edge-cases.test.js +1088 -0
- package/test/integration/exchange.test.js +326 -0
- package/test/integration/life-loop.test.js +188 -0
- package/test/integration/load.test.js +751 -0
- package/test/integration/markdown-sync.test.js +35 -0
- package/test/integration/policy-query-api.test.js +306 -0
- package/test/integration/resilience-writes.test.js +241 -0
- package/test/integration/tools-contract.test.js +1324 -0
- package/test/unit/ann-edge.test.js +102 -0
- package/test/unit/ann.test.js +77 -0
- package/test/unit/api-client.test.js +576 -0
- package/test/unit/api-validate.test.js +19 -0
- package/test/unit/api.test.js +555 -0
- package/test/unit/appraisal.test.js +48 -0
- package/test/unit/attachments.test.js +33 -0
- package/test/unit/autonomy.test.js +53 -0
- package/test/unit/batch.test.js +46 -0
- package/test/unit/bench.test.js +40 -0
- package/test/unit/benchmark-synthetic.test.js +52 -0
- package/test/unit/client-contract.test.js +29 -0
- package/test/unit/compression.test.js +76 -0
- package/test/unit/core.test.js +77 -0
- package/test/unit/develop.test.js +130 -0
- package/test/unit/development.test.js +68 -0
- package/test/unit/digest.test.js +26 -0
- package/test/unit/dsr.test.js +111 -0
- package/test/unit/edges-candidates.test.js +113 -0
- package/test/unit/emotion.test.js +61 -0
- package/test/unit/encode.test.js +98 -0
- package/test/unit/evolution.test.js +130 -0
- package/test/unit/external-ann-search.test.js +50 -0
- package/test/unit/external-ann.test.js +29 -0
- package/test/unit/facts-belief.test.js +32 -0
- package/test/unit/facts.test.js +107 -0
- package/test/unit/feature-overrides.test.js +42 -0
- package/test/unit/fts-migration.test.js +42 -0
- package/test/unit/graph.test.js +79 -0
- package/test/unit/growth-reflect.test.js +123 -0
- package/test/unit/guard-runtime.test.js +40 -0
- package/test/unit/guardian.test.js +91 -0
- package/test/unit/health-privacy.test.js +102 -0
- package/test/unit/hnsw.test.js +35 -0
- package/test/unit/host-runtime.test.js +142 -0
- package/test/unit/host.test.js +58 -0
- package/test/unit/identity.test.js +98 -0
- package/test/unit/induct-evaluate.test.js +41 -0
- package/test/unit/ingest-extracted.test.js +35 -0
- package/test/unit/initiative.test.js +90 -0
- package/test/unit/jobs.test.js +93 -0
- package/test/unit/json-snapshot.test.js +57 -0
- package/test/unit/life-consolidate.test.js +34 -0
- package/test/unit/life.test.js +149 -0
- package/test/unit/llm-facts-integration.test.js +27 -0
- package/test/unit/llm-facts.test.js +16 -0
- package/test/unit/llm.test.js +45 -0
- package/test/unit/locomo.test.js +45 -0
- package/test/unit/longmemeval.test.js +56 -0
- package/test/unit/markdown-import.test.js +44 -0
- package/test/unit/markdown.test.js +34 -0
- package/test/unit/memory-edit.test.js +112 -0
- package/test/unit/metrics.test.js +26 -0
- package/test/unit/migration.test.js +38 -0
- package/test/unit/model-config.test.js +52 -0
- package/test/unit/narrative.test.js +62 -0
- package/test/unit/playbook-consolidate.test.js +24 -0
- package/test/unit/privacy-scope.test.js +39 -0
- package/test/unit/profile.test.js +20 -0
- package/test/unit/prompt.test.js +42 -0
- package/test/unit/providers.test.js +42 -0
- package/test/unit/qa.test.js +100 -0
- package/test/unit/query.test.js +53 -0
- package/test/unit/retention.test.js +31 -0
- package/test/unit/retrieval-ranking.test.js +31 -0
- package/test/unit/retrieve.test.js +117 -0
- package/test/unit/rotation.test.js +25 -0
- package/test/unit/scanner.test.js +50 -0
- package/test/unit/scenario.test.js +78 -0
- package/test/unit/scheduler.test.js +136 -0
- package/test/unit/self-state.test.js +94 -0
- package/test/unit/service.test.js +72 -0
- package/test/unit/shiori-import.test.js +77 -0
- package/test/unit/skills.test.js +104 -0
- package/test/unit/store.test.js +111 -0
- package/test/unit/temporal-graph.test.js +44 -0
- package/test/unit/tiers.test.js +39 -0
- package/test/unit/tokenizer-fts.test.js +35 -0
- package/test/unit/tools.test.js +122 -0
- package/test/unit/upgrade-0412.test.js +104 -0
- package/test/unit/upgrade-0413.test.js +84 -0
- package/test/unit/upgrade-0414.test.js +101 -0
- package/test/unit/vector-ann.test.js +53 -0
- package/test/unit/vector-async.test.js +69 -0
- package/test/unit/vector.test.js +68 -0
- package/test/unit/working.test.js +80 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
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
|
+
|
|
112
|
+
|
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -9,33 +9,57 @@ core engine.
|
|
|
9
9
|
|
|
10
10
|
## Status
|
|
11
11
|
|
|
12
|
-
- Package: `dsh-cortex-memory@0.4.
|
|
12
|
+
- Package: `dsh-cortex-memory@0.4.15`
|
|
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:
|
|
16
|
+
- Tests: 433/433 (main)
|
|
17
17
|
- CI: GitHub Actions on Windows, Node 24
|
|
18
18
|
|
|
19
|
-
### What 0.4.
|
|
20
|
-
|
|
21
|
-
- **
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
- **
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
- **
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
-
|
|
19
|
+
### What 0.4.15 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.
|
|
81
|
+
npm i dsh-cortex-memory@0.4.15
|
|
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.
|
|
88
|
+
dsh plugin --profile desktop add dsh-cortex-memory@0.4.15
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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,
|
|
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,10 @@ MIT.
|
|
|
190
214
|
|
|
191
215
|
|
|
192
216
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
196
222
|
|
|
197
223
|
|
package/bench/README.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Cortex benchmarks
|
|
2
|
+
|
|
3
|
+
## semantic-cn.js
|
|
4
|
+
|
|
5
|
+
Reproducible controlled Chinese retrieval probe.
|
|
6
|
+
|
|
7
|
+
```powershell
|
|
8
|
+
node bench/semantic-cn.js
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
It creates a temporary Cortex database, writes 12 controlled memories, runs
|
|
12
|
+
12 queries through full search and injection-tiered recall, and reports
|
|
13
|
+
recall@3, MRR@3, nDCG@3, p50 and p95. Output is written to
|
|
14
|
+
`bench/results/semantic-cn.json`.
|
|
15
|
+
|
|
16
|
+
This is deliberately labeled **synthetic-controlled**. It is not LoCoMo,
|
|
17
|
+
LongMemEval, MemoryAgentBench or an official score.
|
|
18
|
+
|
|
19
|
+
## LoCoMo / LongMemEval
|
|
20
|
+
|
|
21
|
+
Adapters live in `bench/locomo.js` and `bench/longmemeval.js`. They evaluate
|
|
22
|
+
retrieval only; do not claim official end-to-end QA scores from them.
|
|
23
|
+
|
|
24
|
+
## OCR / ASR
|
|
25
|
+
|
|
26
|
+
OCR and ASR microbenchmarks belong to `dsh-cortex-extractors`, because the
|
|
27
|
+
engine and model choices are external. The extractor package includes its
|
|
28
|
+
layout/TSV/empty-text/link tests. Real Chinese screenshot/audio accuracy needs
|
|
29
|
+
explicit samples and environments; no numbers are fabricated here.
|
|
@@ -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));
|
package/bench/locomo.js
ADDED
|
@@ -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
|
+
}
|