dsh-cortex-memory 0.4.22 → 0.4.147

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 (154) hide show
  1. package/CHANGELOG.md +2390 -154
  2. package/README.md +11 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +10 -10
  5. package/bench/synthetic.js +3 -3
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/client.js +1 -1
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/icon.svg +12 -2
  15. package/index.js +27 -3
  16. package/package.json +3 -3
  17. package/src/adapters/shiori.js +1 -1
  18. package/src/api/routes.js +1 -1
  19. package/src/core/feature-overrides.js +2 -2
  20. package/src/engines/compression.js +172 -3
  21. package/src/engines/consolidate.js +397 -26
  22. package/src/engines/encode.js +16 -3
  23. package/src/engines/extract.js +72 -8
  24. package/src/engines/fact-guard.js +51 -0
  25. package/src/engines/health.js +263 -3
  26. package/src/engines/inhibition.js +39 -0
  27. package/src/engines/life.js +14 -3
  28. package/src/engines/llm-facts.js +12 -9
  29. package/src/engines/narrative.js +150 -13
  30. package/src/engines/reflect.js +172 -14
  31. package/src/engines/retrieve.js +44 -5
  32. package/src/engines/summary-coverage.js +62 -0
  33. package/src/engines/summary-dedupe.js +77 -0
  34. package/src/engines/summon-rank.js +132 -0
  35. package/src/host/runtime.js +64 -4
  36. package/src/host/scheduler.js +224 -3
  37. package/src/llm/adapter.js +29 -8
  38. package/src/memory/query.js +1 -1
  39. package/src/memory/spacing.js +15 -0
  40. package/src/memory/tokenizer.js +1 -1
  41. package/src/prompt/tiers.js +88 -12
  42. package/src/self/alias.js +25 -0
  43. package/src/self/emotion.js +3 -1
  44. package/src/self/relationship.js +44 -13
  45. package/src/self/state.js +20 -2
  46. package/src/self/working.js +34 -3
  47. package/src/service/cortex.js +493 -53
  48. package/src/store/repositories/facts.js +34 -1
  49. package/src/store/repositories/summaries.js +8 -1
  50. package/src/store/repositories/traces.js +22 -2
  51. package/src/tools/definitions.js +118 -4
  52. package/src/vector/index.js +96 -7
  53. package/test/integration/_helpers.js +0 -128
  54. package/test/integration/acceptance.test.js +0 -803
  55. package/test/integration/ann-load.test.js +0 -61
  56. package/test/integration/api-contract.test.js +0 -1476
  57. package/test/integration/backup-privacy.test.js +0 -214
  58. package/test/integration/consolidate.test.js +0 -75
  59. package/test/integration/edge-cases.test.js +0 -1088
  60. package/test/integration/exchange.test.js +0 -326
  61. package/test/integration/life-loop.test.js +0 -188
  62. package/test/integration/load.test.js +0 -751
  63. package/test/integration/markdown-sync.test.js +0 -35
  64. package/test/integration/policy-query-api.test.js +0 -306
  65. package/test/integration/resilience-writes.test.js +0 -241
  66. package/test/integration/tools-contract.test.js +0 -1324
  67. package/test/unit/ann-edge.test.js +0 -102
  68. package/test/unit/ann.test.js +0 -77
  69. package/test/unit/api-client.test.js +0 -576
  70. package/test/unit/api-validate.test.js +0 -19
  71. package/test/unit/api.test.js +0 -555
  72. package/test/unit/appraisal.test.js +0 -48
  73. package/test/unit/attachments.test.js +0 -33
  74. package/test/unit/autonomy.test.js +0 -53
  75. package/test/unit/batch.test.js +0 -46
  76. package/test/unit/bench.test.js +0 -40
  77. package/test/unit/benchmark-synthetic.test.js +0 -52
  78. package/test/unit/cli-default-root.test.js +0 -21
  79. package/test/unit/client-contract.test.js +0 -32
  80. package/test/unit/compression.test.js +0 -76
  81. package/test/unit/core.test.js +0 -77
  82. package/test/unit/develop.test.js +0 -130
  83. package/test/unit/development.test.js +0 -68
  84. package/test/unit/digest.test.js +0 -26
  85. package/test/unit/dsr.test.js +0 -111
  86. package/test/unit/edges-candidates.test.js +0 -113
  87. package/test/unit/emotion.test.js +0 -61
  88. package/test/unit/encode.test.js +0 -98
  89. package/test/unit/evolution.test.js +0 -130
  90. package/test/unit/external-ann-search.test.js +0 -50
  91. package/test/unit/external-ann.test.js +0 -29
  92. package/test/unit/facts-belief.test.js +0 -32
  93. package/test/unit/facts.test.js +0 -107
  94. package/test/unit/feature-overrides.test.js +0 -42
  95. package/test/unit/fts-migration.test.js +0 -42
  96. package/test/unit/graph.test.js +0 -79
  97. package/test/unit/growth-reflect.test.js +0 -123
  98. package/test/unit/guard-runtime.test.js +0 -40
  99. package/test/unit/guardian.test.js +0 -91
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/hnsw.test.js +0 -35
  102. package/test/unit/host-runtime.test.js +0 -142
  103. package/test/unit/host.test.js +0 -58
  104. package/test/unit/identity.test.js +0 -98
  105. package/test/unit/induct-evaluate.test.js +0 -41
  106. package/test/unit/ingest-extracted.test.js +0 -35
  107. package/test/unit/initiative.test.js +0 -90
  108. package/test/unit/jobs.test.js +0 -93
  109. package/test/unit/json-snapshot.test.js +0 -57
  110. package/test/unit/life-consolidate.test.js +0 -34
  111. package/test/unit/life.test.js +0 -149
  112. package/test/unit/llm-facts-integration.test.js +0 -27
  113. package/test/unit/llm-facts.test.js +0 -16
  114. package/test/unit/llm.test.js +0 -45
  115. package/test/unit/locomo.test.js +0 -45
  116. package/test/unit/longmemeval.test.js +0 -56
  117. package/test/unit/markdown-import.test.js +0 -44
  118. package/test/unit/markdown.test.js +0 -34
  119. package/test/unit/memory-edit.test.js +0 -112
  120. package/test/unit/metrics.test.js +0 -26
  121. package/test/unit/migration.test.js +0 -38
  122. package/test/unit/model-config.test.js +0 -52
  123. package/test/unit/narrative.test.js +0 -62
  124. package/test/unit/playbook-consolidate.test.js +0 -24
  125. package/test/unit/privacy-scope.test.js +0 -39
  126. package/test/unit/profile-paths.test.js +0 -21
  127. package/test/unit/profile.test.js +0 -26
  128. package/test/unit/prompt.test.js +0 -42
  129. package/test/unit/providers.test.js +0 -42
  130. package/test/unit/qa.test.js +0 -100
  131. package/test/unit/query.test.js +0 -53
  132. package/test/unit/retention.test.js +0 -31
  133. package/test/unit/retrieval-ranking.test.js +0 -31
  134. package/test/unit/retrieve.test.js +0 -117
  135. package/test/unit/rotation.test.js +0 -25
  136. package/test/unit/scanner.test.js +0 -50
  137. package/test/unit/scenario.test.js +0 -78
  138. package/test/unit/scheduler.test.js +0 -136
  139. package/test/unit/self-state.test.js +0 -94
  140. package/test/unit/service.test.js +0 -72
  141. package/test/unit/shiori-import.test.js +0 -77
  142. package/test/unit/skills.test.js +0 -104
  143. package/test/unit/store.test.js +0 -111
  144. package/test/unit/temporal-graph.test.js +0 -44
  145. package/test/unit/tiers.test.js +0 -39
  146. package/test/unit/tokenizer-fts.test.js +0 -35
  147. package/test/unit/tools.test.js +0 -122
  148. package/test/unit/upgrade-0412.test.js +0 -104
  149. package/test/unit/upgrade-0413.test.js +0 -84
  150. package/test/unit/upgrade-0414.test.js +0 -101
  151. package/test/unit/vector-ann.test.js +0 -53
  152. package/test/unit/vector-async.test.js +0 -69
  153. package/test/unit/vector.test.js +0 -68
  154. package/test/unit/working.test.js +0 -80
@@ -1,751 +0,0 @@
1
- /**
2
- * Load, concurrency and durability integration tests for dsh-cortex.
3
- *
4
- * These tests are intentionally black-box: every cortex below is real, every
5
- * database is a throwaway SQLite file under the OS temp directory, and nothing
6
- * is mocked. The goal is to catch realistic regressions that small unit tests
7
- * miss: a 1000-3000 trace ingestion, several live instances, budget exhaustion,
8
- * vector + FTS search under repetitive use, backup/restore and retention/privacy
9
- * over a full-sized database.
10
- *
11
- * Timing policy
12
- * -------------
13
- * Only loose upper bounds are asserted (60 seconds). A load test that fails
14
- * because CI is having a slow minute is worse than no load test; the exact
15
- * throughput is reported with t.diagnostic so a human can still notice drift.
16
- *
17
- * Same-database concurrency
18
- * -------------------------
19
- * This suite never opens two cortex instances on the same database file. The
20
- * service's SQLite setup (WAL, foreign keys, BEGIN IMMEDIATE, 5 second busy
21
- * timeout) is safe for sequential host use, but it has no cross-instance
22
- * coordination, retry loop or process-wide lock. Two independent cortex
23
- * objects sharing one file can therefore hit SQLITE_BUSY, race a write against
24
- * a read, or observe each other's half-finished logical operations. Rather than
25
- * treating that as a supported mode, the concurrency test uses one database per
26
- * instance and documents the limitation here. If shared-database access is ever
27
- * required it should be designed and tested explicitly, not inferred.
28
- *
29
- * Cleanup
30
- * -------
31
- * Every cortex is closed in a finally block before its temp directory is
32
- * removed. The concurrency test also closes every instance independently so a
33
- * single failure cannot leak a handle into the shared root.
34
- */
35
- import test from 'node:test';
36
- import assert from 'node:assert/strict';
37
- import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
38
- import os from 'node:os';
39
- import path from 'node:path';
40
- import { performance } from 'node:perf_hooks';
41
- import { DatabaseSync } from 'node:sqlite';
42
- import { createCortex } from '../../src/service/cortex.js';
43
- import { createScheduler } from '../../src/host/scheduler.js';
44
-
45
- const DAY_MS = 86_400_000;
46
- /** Fixed reference instant: 2026-11-11T10:00:00+08:00, matching the suite. */
47
- const BASE_MS = Date.parse('2026-11-11T10:00:00+08:00');
48
- /** Loose CI ceiling for a single load phase. Never tighten this to benchmark. */
49
- const LOAD_BOUND_MS = 60_000;
50
- const SCOPE = 'global';
51
-
52
- const LOAD_WORDS = [
53
- '鲸鱼', '白饭', '潮汐', '星图', '海风', '灯塔',
54
- '月光', '小鱼', '用户', '薄荷', '玻璃', '海盐',
55
- ];
56
-
57
- const LOAD_ACTIONS = [
58
- '记录', '想起', '数着', '藏着', '写着', '整理', '等待', '看见',
59
- ];
60
-
61
- function mulberry32(seed) {
62
- let state = seed >>> 0;
63
- return function random() {
64
- state = (state + 0x6D2B79F5) >>> 0;
65
- let value = state;
66
- value = Math.imul(value ^ (value >>> 15), value | 1);
67
- value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
68
- return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
69
- };
70
- }
71
-
72
- /**
73
- * Build deterministic, short, unique trace inputs.
74
- *
75
- * The index is embedded in both the text and the operationId so every trace has
76
- * a different content hash and every replay can be checked by its own ledger
77
- * key. Randomness is only used to vary shape; the seed makes the dataset stable
78
- * across runs and machines.
79
- */
80
- function syntheticInputs({
81
- count,
82
- seed = 42,
83
- prefix = 'load',
84
- startMs = BASE_MS,
85
- stepMs = 1_000,
86
- importance = null,
87
- confidence = null,
88
- extraTokens = [],
89
- titlePrefix = null,
90
- } = {}) {
91
- const random = mulberry32(seed);
92
- const extra = extraTokens.length ? ` ${extraTokens.join(' ')}` : '';
93
- return Array.from({ length: count }, (_, index) => {
94
- const first = LOAD_WORDS[Math.floor(random() * LOAD_WORDS.length)];
95
- const second = LOAD_WORDS[Math.floor(random() * LOAD_WORDS.length)];
96
- const action = LOAD_ACTIONS[Math.floor(random() * LOAD_ACTIONS.length)];
97
- const input = {
98
- text: `${prefix}-${index} ${first}${action}${second}${extra}`,
99
- title: `${titlePrefix ?? prefix}-${index}`,
100
- tags: [prefix, first],
101
- explicit: true,
102
- operationId: `${prefix}:${index}`,
103
- now: startMs + index * stepMs,
104
- };
105
- if (importance != null) input.importance = importance;
106
- if (confidence != null) input.confidence = confidence;
107
- return input;
108
- });
109
- }
110
-
111
- /** Unique temporary root for one test; callers own its removal. */
112
- function makeRoot(label) {
113
- return mkdtempSync(path.join(os.tmpdir(), `cortex-load-${label}-`));
114
- }
115
-
116
- /** Open a real cortex against a fresh data directory inside root. */
117
- function openCortex(root, overrides = {}) {
118
- const dataRoot = path.join(root, 'data');
119
- const dbFile = path.join(dataRoot, 'cortex.sqlite');
120
- return createCortex({ config: { dataRoot, dbFile, ...overrides } });
121
- }
122
-
123
- function closeQuietly(cortex) {
124
- if (!cortex) return;
125
- try {
126
- cortex.close();
127
- } catch {
128
- /* best-effort close: cleanup must not mask the real test failure */
129
- }
130
- }
131
-
132
- function removeQuietly(root) {
133
- if (!root) return;
134
- try {
135
- rmSync(root, { recursive: true, force: true });
136
- } catch {
137
- /* temporary directories are disposable; never fail a test on cleanup */
138
- }
139
- }
140
-
141
- function countTraces(cortex, state = null) {
142
- return cortex.repos.traces.count({ scopeId: SCOPE, state });
143
- }
144
-
145
- /**
146
- * Duplicate hashes are the write path's dedupe signal and a strong integrity
147
- * check for synthetic data. Both the repository helper and a direct SQL count
148
- * are checked so a bug in either path is visible.
149
- */
150
- function assertUniqueHashes(cortex, expectedCount = null) {
151
- const duplicates = cortex.repos.traces.duplicateHashes(SCOPE, { limit: 100 });
152
- assert.deepEqual(duplicates, [], `found duplicate content hashes: ${JSON.stringify(duplicates)}`);
153
- const row = cortex.db
154
- .prepare('SELECT COUNT(DISTINCT hash) AS c FROM traces WHERE scope_id = ?')
155
- .get(SCOPE);
156
- const distinct = Number(row?.c ?? 0);
157
- assert.equal(distinct, expectedCount ?? countTraces(cortex));
158
- }
159
-
160
- /** Search must report its failures in the trace, not silently mislabel a source. */
161
- function assertNoFailedSources(result) {
162
- for (const source of result.trace?.sources ?? []) {
163
- assert.notEqual(
164
- source.ok,
165
- false,
166
- `retrieval source ${source.source} failed: ${source.error ?? 'unknown error'}`,
167
- );
168
- }
169
- }
170
-
171
- /** Shape checks shared by successful and blocked search results. */
172
- function assertWellFormedSearch(result, expectedQuery) {
173
- assert.equal(result.query, expectedQuery);
174
- assert.equal(result.scopeId, SCOPE);
175
- assert.ok(Array.isArray(result.items));
176
- assert.ok(Array.isArray(result.trace?.sources));
177
- assert.ok(result.trace?.elapsedMs >= 0);
178
- const ids = result.items.map((item) => item.id);
179
- assert.equal(new Set(ids).size, ids.length);
180
- assert.ok(result.budget.total >= result.budget.used);
181
- }
182
-
183
- test('writeMany ingests 2000 deterministic traces within the loose load bound', (t) => {
184
- const root = makeRoot('write-many');
185
- let cortex = null;
186
- try {
187
- cortex = openCortex(root);
188
- const count = 2000;
189
- const inputs = syntheticInputs({ count, seed: 20261111, prefix: 'load' });
190
-
191
- const started = performance.now();
192
- const results = cortex.writeMany(inputs, { chunkSize: 250 });
193
- const elapsedMs = performance.now() - started;
194
-
195
- assert.equal(results.length, count);
196
- assert.equal(results.filter((result) => result.skipped === false).length, count);
197
- assert.equal(results.every((result) => result.trace), true);
198
- assert.equal(countTraces(cortex), count);
199
- assert.equal(cortex.repos.events.count(), count);
200
- assert.equal(cortex.repos.traces.ftsCount(), count);
201
- assertUniqueHashes(cortex, count);
202
-
203
- // Every returned trace id is distinct, and the order matches the input order.
204
- assert.equal(new Set(results.map((result) => result.trace.id)).size, count);
205
- for (const index of [0, Math.floor(count / 2), count - 1]) {
206
- assert.equal(results[index].trace.content, inputs[index].text);
207
- assert.equal(cortex.get(results[index].trace.id).title, inputs[index].title);
208
- }
209
-
210
- // Metrics are attempt-level; a chunked run must at least account for every
211
- // created trace. Do not assert an exact value here: rollback accounting is
212
- // covered by the unit suite and is not the point of this load test.
213
- assert.ok((cortex.metrics().counters['writes.created'] ?? 0) >= count);
214
-
215
- t.diagnostic(
216
- `writeMany: ${count} traces in ${Math.round(elapsedMs)} ms `
217
- + `(${Math.round((count / Math.max(1, elapsedMs)) * 1000)} writes/s)`,
218
- );
219
- assert.ok(
220
- elapsedMs < LOAD_BOUND_MS,
221
- `writeMany took ${Math.round(elapsedMs)} ms, exceeding the ${LOAD_BOUND_MS} ms loose bound`,
222
- );
223
- assert.equal(cortex.guardian.check().ok, true);
224
- } finally {
225
- closeQuietly(cortex);
226
- removeQuietly(root);
227
- }
228
- });
229
-
230
- test('Promise.all over independent cortex instances on distinct DBs completes without cross-talk', async (t) => {
231
- const root = makeRoot('concurrent');
232
- const base = path.join(root, 'instances');
233
- const instanceCount = 4;
234
- const perInstance = 300;
235
- const started = performance.now();
236
- try {
237
- mkdirSync(base, { recursive: true });
238
- const results = await Promise.all(
239
- Array.from({ length: instanceCount }, async (_, index) => {
240
- const dir = path.join(base, `instance-${index}`);
241
- const cortex = openCortex(dir);
242
- try {
243
- // Let all four instances finish opening before any of them writes.
244
- // This is scheduling, not a barrier; the instances still never share
245
- // a database or a service object.
246
- await new Promise((resolve) => setTimeout(resolve, index * 5));
247
-
248
- const marker = `marker${index}alpha`;
249
- const inputs = syntheticInputs({
250
- count: perInstance,
251
- seed: 5000 + index,
252
- prefix: `concurrent${index}`,
253
- startMs: BASE_MS + index * DAY_MS,
254
- extraTokens: [marker],
255
- });
256
- const written = cortex.writeMany(inputs, { chunkSize: 100 });
257
-
258
- assert.equal(written.length, perInstance);
259
- assert.equal(countTraces(cortex), perInstance);
260
- assert.equal(cortex.repos.events.count(), perInstance);
261
- assertUniqueHashes(cortex, perInstance);
262
-
263
- const ownHits = cortex.repos.traces.searchFts(marker, {
264
- scopeId: SCOPE,
265
- limit: 5,
266
- });
267
- assert.ok(ownHits.length >= 1, `instance ${index} cannot find its own marker`);
268
-
269
- // Cross-contamination is checked at the FTS projection instead of
270
- // through cortex.search(), because search always adds recent traces
271
- // as a fallback source even when the query has no lexical hit.
272
- const otherMarker = `marker${(index + 1) % instanceCount}alpha`;
273
- const foreignHits = cortex.repos.traces.searchFts(otherMarker, {
274
- scopeId: SCOPE,
275
- limit: 5,
276
- });
277
- assert.deepEqual(foreignHits, [], `instance ${index} sees another instance's marker`);
278
-
279
- const found = cortex.search(marker, { limit: 5 });
280
- assertWellFormedSearch(found, marker);
281
- assert.ok(found.items.length >= 1);
282
- assertNoFailedSources(found);
283
-
284
- return {
285
- index,
286
- dbFile: cortex.config.dbFile,
287
- traces: countTraces(cortex),
288
- events: cortex.repos.events.count(),
289
- ownHits: ownHits.length,
290
- };
291
- } finally {
292
- closeQuietly(cortex);
293
- }
294
- }),
295
- );
296
-
297
- const elapsedMs = performance.now() - started;
298
- assert.equal(results.length, instanceCount);
299
-
300
- // The whole point of the test: distinct databases, not a shared file.
301
- assert.equal(new Set(results.map((result) => result.dbFile)).size, instanceCount);
302
- for (const result of results) {
303
- assert.equal(result.traces, perInstance);
304
- assert.equal(result.events, perInstance);
305
- assert.ok(result.ownHits >= 1);
306
- }
307
-
308
- // Reopen each cluster's database independently after every cortex is
309
- // closed. A count of exactly 300 here proves the instances did not write
310
- // into each other's file and that close() did not lose committed rows.
311
- for (const result of results) {
312
- const snapshot = new DatabaseSync(result.dbFile);
313
- try {
314
- assert.equal(
315
- Number(snapshot.prepare('SELECT COUNT(*) AS c FROM traces').get().c),
316
- perInstance,
317
- );
318
- assert.equal(
319
- Number(snapshot.prepare('SELECT COUNT(*) AS c FROM events').get().c),
320
- perInstance,
321
- );
322
- } finally {
323
- snapshot.close();
324
- }
325
- }
326
-
327
- t.diagnostic(
328
- `concurrent: ${instanceCount} instances x ${perInstance} traces in `
329
- + `${Math.round(elapsedMs)} ms on distinct DB files`,
330
- );
331
- assert.ok(
332
- elapsedMs < LOAD_BOUND_MS,
333
- `concurrent run took ${Math.round(elapsedMs)} ms, exceeding the ${LOAD_BOUND_MS} ms loose bound`,
334
- );
335
- } finally {
336
- removeQuietly(root);
337
- }
338
- });
339
-
340
- test('search budget exhaustion returns blocked traces and scheduler.runOnce survives load', async (t) => {
341
- const root = makeRoot('budget-scheduler');
342
- let cortex = null;
343
- try {
344
- // Six successful searches per hour is enough to exercise the guard without
345
- // writing a hundred traces just to spend the budget.
346
- cortex = openCortex(root, { maxCallsPerHour: 6 });
347
- const count = 1000;
348
- cortex.writeMany(syntheticInputs({ count, seed: 31, prefix: 'budget' }), {
349
- chunkSize: 250,
350
- });
351
- assert.equal(countTraces(cortex), count);
352
-
353
- const query = '鲸鱼';
354
- for (let index = 0; index < 6; index += 1) {
355
- const result = cortex.search(query, { limit: 5 });
356
- assertWellFormedSearch(result, query);
357
- assert.equal(result.trace.blocked, undefined);
358
- assert.ok(result.items.length >= 1);
359
- assertNoFailedSources(result);
360
- }
361
- assert.equal(cortex.budget.snapshot().calls, 6);
362
- assert.equal(cortex.budget.snapshot().remainingCalls, 0);
363
-
364
- // Every call after exhaustion must be a clean blocked result. Repeating it
365
- // is important: a blocked path must not leak state or throw on later calls.
366
- for (let index = 0; index < 10; index += 1) {
367
- const result = cortex.search(query, { limit: 5 });
368
- assertWellFormedSearch(result, query);
369
- assert.equal(result.trace.blocked, 'budget');
370
- assert.equal(result.trace.candidates, 0);
371
- assert.equal(result.trace.selected, 0);
372
- assert.deepEqual(result.items, []);
373
- assert.deepEqual(result.budget, { used: 0, total: 0 });
374
- }
375
- assert.equal(cortex.budget.snapshot().calls, 6);
376
-
377
- assert.doesNotThrow(() => {
378
- const repeated = cortex.search(query, { limit: 5 });
379
- assert.equal(repeated.trace.blocked, 'budget');
380
- });
381
-
382
- // The scheduler is a host heartbeat, not a search caller. Its runOnce must
383
- // remain safe on a large database even when search is currently blocked,
384
- // and it must drain jobs through the real runner API.
385
- const scheduler = createScheduler({ cortex, intervalMs: 60_000 });
386
- const reports = [];
387
- for (let index = 0; index < 3; index += 1) {
388
- reports.push(await scheduler.runOnce());
389
- }
390
- assert.equal(reports.length, 3);
391
- for (const report of reports) {
392
- assert.ok(report.at);
393
- assert.ok(report.steps.autonomy);
394
- assert.ok(report.steps.jobs);
395
- assert.ok(report.steps.retention);
396
- assert.equal(report.steps.retention.active, count);
397
- assert.ok(report.steps.retention.candidates <= 20);
398
- assert.ok(report.steps.guardian);
399
- assert.equal(report.steps.guardian.ok, true);
400
- assert.ok(['ok', 'light', 'skipped'].includes(report.steps.guardian.integrity));
401
- assert.deepEqual(report.steps.guardian.issues, []);
402
- }
403
-
404
- // A scheduler tick must not reset the search budget behind the caller's
405
- // back. The next search is still blocked, and the service still does not
406
- // throw after the ticks.
407
- const afterScheduler = cortex.search(query, { limit: 5 });
408
- assert.equal(afterScheduler.trace.blocked, 'budget');
409
- assert.deepEqual(afterScheduler.items, []);
410
- assert.equal(scheduler.status().running, false);
411
-
412
- t.diagnostic(
413
- `budget: ${count} traces, 6 allowed searches, 11 blocked searches, 3 scheduler ticks`,
414
- );
415
- } finally {
416
- closeQuietly(cortex);
417
- removeQuietly(root);
418
- }
419
- });
420
-
421
- test('writeMany replay at scale is idempotent for every operationId', (t) => {
422
- const root = makeRoot('idempotency');
423
- let cortex = null;
424
- try {
425
- cortex = openCortex(root);
426
- const count = 1200;
427
- const inputs = syntheticInputs({ count, seed: 777, prefix: 'idem' });
428
-
429
- const first = cortex.writeMany(inputs, { chunkSize: 173 });
430
- assert.equal(first.length, count);
431
- assert.equal(first.filter((result) => result.skipped === false).length, count);
432
- assert.equal(countTraces(cortex), count);
433
- assert.equal(cortex.repos.events.count(), count);
434
- assertUniqueHashes(cortex, count);
435
-
436
- const firstIds = first.map((result) => result.trace.id);
437
- const eventsAfterFirst = cortex.repos.events.count();
438
-
439
- // Replay the entire batch with a different chunk size. The ledger key is
440
- // the operationId, so every item must resolve to the original trace and
441
- // neither the trace count nor the append-only event count may move.
442
- const started = performance.now();
443
- const second = cortex.writeMany(inputs, { chunkSize: 97 });
444
- const replayMs = performance.now() - started;
445
-
446
- assert.equal(second.length, count);
447
- assert.equal(second.every((result) => result.skipped === true), true);
448
- assert.equal(second.every((result) => result.reason === 'idempotent'), true);
449
- assert.equal(second.every((result) => Boolean(result.event) && Boolean(result.trace)), true);
450
- assert.deepEqual(
451
- second.map((result) => result.trace.id),
452
- firstIds,
453
- 'a replay must resolve every operationId back to its original trace',
454
- );
455
- assert.equal(countTraces(cortex), count);
456
- assert.equal(cortex.repos.events.count(), eventsAfterFirst);
457
- assertUniqueHashes(cortex, count);
458
-
459
- t.diagnostic(
460
- `idempotency: ${count} traces replayed in ${Math.round(replayMs)} ms `
461
- + `with no count change`,
462
- );
463
- assert.ok(
464
- replayMs < LOAD_BOUND_MS,
465
- `replay took ${Math.round(replayMs)} ms, exceeding the ${LOAD_BOUND_MS} ms loose bound`,
466
- );
467
- assert.equal(cortex.guardian.check().ok, true);
468
- } finally {
469
- closeQuietly(cortex);
470
- removeQuietly(root);
471
- }
472
- });
473
-
474
- test('FTS plus hash-vector retrieval stays healthy across 1000 writes and 50 searches', (t) => {
475
- const root = makeRoot('vector-search');
476
- let cortex = null;
477
- try {
478
- cortex = openCortex(root, { vectorEnabled: true });
479
- assert.ok(cortex.vector);
480
- assert.equal(cortex.vector.model, 'hash-256');
481
- assert.equal(cortex.vector.dim, 256);
482
- assert.equal(cortex.vector.status().count, 0);
483
-
484
- const count = 1000;
485
- const inputs = syntheticInputs({
486
- count,
487
- seed: 909,
488
- prefix: 'vector',
489
- extraTokens: ['鲸鱼', '白饭', '记忆', 'alpha', 'beta'],
490
- importance: 0.6,
491
- confidence: 0.8,
492
- });
493
- cortex.writeMany(inputs, { chunkSize: 200 });
494
- assert.equal(countTraces(cortex), count);
495
- assert.equal(cortex.repos.traces.ftsCount(), count);
496
- assert.equal(cortex.vector.status().count, count);
497
-
498
- const queries = ['鲸鱼', '白饭', '记忆', 'alpha', 'beta'];
499
- const started = performance.now();
500
- let totalItems = 0;
501
- for (let index = 0; index < 50; index += 1) {
502
- const query = queries[index % queries.length];
503
- const result = cortex.search(query, { limit: 10 });
504
- assertWellFormedSearch(result, query);
505
- assert.equal(result.trace.blocked, undefined);
506
- assertNoFailedSources(result);
507
-
508
- const sources = new Map(result.trace.sources.map((source) => [source.source, source]));
509
- assert.ok(sources.has('fts'), 'FTS source should participate in retrieval');
510
- assert.ok(sources.has('vector'), 'vector source should participate in retrieval');
511
- assert.equal(sources.get('fts').ok, true);
512
- assert.ok(sources.get('fts').count >= 1);
513
- assert.equal(sources.get('vector').ok, true);
514
- assert.ok(sources.get('vector').count >= 1);
515
- totalItems += result.items.length;
516
- }
517
- const searchMs = performance.now() - started;
518
-
519
- assert.ok(totalItems > 0);
520
- assert.equal(cortex.metrics().counters['search.errors'] ?? 0, 0);
521
- assert.equal(cortex.metrics().counters['search.calls'] ?? 0, 50);
522
-
523
- // rebuildVector must re-embed every active trace, report the same count,
524
- // and leave the index usable. The hash embedder makes this deterministic
525
- // and dependency-free.
526
- const rebuilt = cortex.rebuildVector();
527
- assert.equal(rebuilt.rebuilt, count);
528
- assert.equal(rebuilt.count, count);
529
- assert.equal(rebuilt.model, 'hash-256');
530
- assert.equal(rebuilt.dim, 256);
531
- assert.equal(cortex.vector.status().count, count);
532
- assert.equal(cortex.settings().vector.model, 'hash-256');
533
-
534
- const afterRebuild = cortex.search('鲸鱼', { limit: 10 });
535
- assertWellFormedSearch(afterRebuild, '鲸鱼');
536
- assert.ok(afterRebuild.items.length >= 1);
537
- assertNoFailedSources(afterRebuild);
538
-
539
- t.diagnostic(
540
- `vector: ${count} writes, 50 searches in ${Math.round(searchMs)} ms, `
541
- + `rebuildVector rebuilt=${rebuilt.rebuilt}`,
542
- );
543
- assert.ok(
544
- searchMs < LOAD_BOUND_MS,
545
- `50 vector searches took ${Math.round(searchMs)} ms, exceeding the ${LOAD_BOUND_MS} ms loose bound`,
546
- );
547
- assert.equal(cortex.guardian.check().ok, true);
548
- } finally {
549
- closeQuietly(cortex);
550
- removeQuietly(root);
551
- }
552
- });
553
-
554
- test('backup of a 1000-trace DB validates and restores to a temporary path', (t) => {
555
- const root = makeRoot('backup');
556
- let cortex = null;
557
- try {
558
- cortex = openCortex(root);
559
- const count = 1000;
560
- cortex.writeMany(syntheticInputs({ count, seed: 404, prefix: 'backup' }), {
561
- chunkSize: 250,
562
- });
563
- assert.equal(countTraces(cortex), count);
564
- assert.equal(cortex.repos.events.count(), count);
565
- assert.equal(cortex.guardian.integrity(), 'ok');
566
-
567
- const backupPath = path.join(root, 'backups', 'load-backup.sqlite');
568
- const started = performance.now();
569
- const backup = cortex.guardian.backup(backupPath);
570
- const backupMs = performance.now() - started;
571
-
572
- assert.equal(backup.path, path.resolve(backupPath));
573
- assert.ok(backup.bytes > 0);
574
- assert.ok(backup.at);
575
-
576
- const validation = cortex.guardian.validateBackup(backupPath);
577
- assert.equal(validation.ok, true);
578
- assert.equal(validation.integrity, 'ok');
579
- assert.deepEqual(validation.missing, []);
580
- assert.ok(validation.tables >= 20);
581
-
582
- const offline = path.join(root, 'restored', 'restored.sqlite');
583
- const restored = cortex.guardian.restore(backupPath, offline);
584
- assert.equal(restored.restored, true);
585
- assert.equal(restored.target, path.resolve(offline));
586
- assert.equal(restored.validation.ok, true);
587
- assert.equal(cortex.guardian.validateBackup(offline).ok, true);
588
-
589
- // The restored file is a real, standalone database with the complete
590
- // trace/event/FTS projection, not just a copy that happens to exist.
591
- const snapshot = new DatabaseSync(offline);
592
- try {
593
- assert.equal(snapshot.prepare('PRAGMA integrity_check').get().integrity_check, 'ok');
594
- assert.equal(
595
- Number(snapshot.prepare('SELECT COUNT(*) AS c FROM traces').get().c),
596
- count,
597
- );
598
- assert.equal(
599
- Number(snapshot.prepare('SELECT COUNT(*) AS c FROM events').get().c),
600
- count,
601
- );
602
- assert.equal(
603
- Number(snapshot.prepare('SELECT COUNT(*) AS c FROM traces_fts_index').get().c),
604
- count,
605
- );
606
- assert.equal(
607
- snapshot.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value,
608
- '7',
609
- );
610
- } finally {
611
- snapshot.close();
612
- }
613
-
614
- // Restoring over the live database is refused before any copy happens.
615
- const liveAttempt = cortex.guardian.restore(backupPath, cortex.config.dbFile);
616
- assert.equal(liveAttempt.restored, false);
617
- assert.equal(liveAttempt.reason, 'live-db');
618
- assert.equal(countTraces(cortex), count);
619
-
620
- // The live service is still writable and its own database stayed intact.
621
- const post = cortex.write({
622
- text: 'backup test: the live database still accepts writes.',
623
- explicit: true,
624
- operationId: 'backup:post',
625
- now: BASE_MS + 10_000,
626
- });
627
- assert.equal(post.skipped, false);
628
- assert.equal(countTraces(cortex), count + 1);
629
- assert.equal(cortex.repos.events.count(), count + 1);
630
- assert.equal(cortex.guardian.check().ok, true);
631
-
632
- t.diagnostic(
633
- `backup: ${count} traces backed up in ${Math.round(backupMs)} ms, `
634
- + `validated and restored ${count} traces`,
635
- );
636
- } finally {
637
- closeQuietly(cortex);
638
- removeQuietly(root);
639
- }
640
- });
641
-
642
- test('retention is bounded on 1000 traces and privacy deleteScope keeps the event ledger', (t) => {
643
- const root = makeRoot('retention-privacy');
644
- let cortex = null;
645
- try {
646
- cortex = openCortex(root);
647
- const count = 1000;
648
- // 800 days old, low importance, below the default confidence gate: exactly
649
- // the traces retention is allowed to archive, and nothing more.
650
- const inputs = syntheticInputs({
651
- count,
652
- seed: 808,
653
- prefix: 'retention',
654
- startMs: BASE_MS - 800 * DAY_MS,
655
- stepMs: 1_000,
656
- importance: 0.04,
657
- confidence: 0.5,
658
- extraTokens: ['鲸鱼', '白饭'],
659
- });
660
- cortex.writeMany(inputs, { chunkSize: 250 });
661
-
662
- assert.equal(countTraces(cortex), count);
663
- const eventsBefore = cortex.repos.events.count();
664
- assert.equal(eventsBefore, count);
665
- assertUniqueHashes(cortex, count);
666
-
667
- const plan = cortex.retention.plan({
668
- now: BASE_MS,
669
- maxAgeDays: 365,
670
- minImportance: 0.2,
671
- limit: 50,
672
- });
673
- assert.equal(plan.active, count);
674
- assert.equal(plan.count, plan.candidates.length);
675
- assert.ok(plan.count > 0, 'aged low-value traces should produce retention candidates');
676
- assert.ok(plan.count <= 50, 'retention plan must respect its limit');
677
- assert.equal(new Set(plan.candidates.map((candidate) => candidate.id)).size, plan.count);
678
- for (const candidate of plan.candidates) {
679
- assert.equal(candidate.reason, 'over-age');
680
- assert.ok(candidate.ageDays > 365);
681
- assert.ok(candidate.importance < 0.2);
682
- assert.ok(candidate.confidence < 0.75);
683
- assert.ok(cortex.get(candidate.id), 'every plan candidate must still exist');
684
- }
685
-
686
- // Dry-run is a pure projection: no state changes and no event changes.
687
- const dry = cortex.retention.apply(plan, { dryRun: true });
688
- assert.equal(dry.dryRun, true);
689
- assert.equal(dry.archived, plan.count);
690
- assert.deepEqual(dry.ids, plan.candidates.map((candidate) => candidate.id));
691
- for (const id of dry.ids) assert.equal(cortex.get(id).state, 'active');
692
- assert.equal(cortex.repos.events.count(), eventsBefore);
693
-
694
- const applied = cortex.retention.apply(plan);
695
- assert.equal(applied.archived, plan.count);
696
- assert.deepEqual(applied.ids, dry.ids);
697
- assert.equal(
698
- cortex.repos.traces.count({ scopeId: SCOPE, state: 'active' }),
699
- count - plan.count,
700
- );
701
- assert.equal(
702
- cortex.repos.traces.count({ scopeId: SCOPE, state: 'archived' }),
703
- plan.count,
704
- );
705
- assert.equal(countTraces(cortex), count);
706
- assert.equal(cortex.repos.events.count(), eventsBefore);
707
- for (const id of applied.ids) {
708
- assert.equal(cortex.get(id).state, 'archived');
709
- assert.equal(cortex.get(id).compression, 'retention');
710
- }
711
-
712
- // A second plan is still bounded and no longer offers the archived rows.
713
- const secondPlan = cortex.retention.plan({
714
- now: BASE_MS,
715
- maxAgeDays: 365,
716
- minImportance: 0.2,
717
- limit: 50,
718
- });
719
- assert.equal(secondPlan.active, count - plan.count);
720
- assert.ok(secondPlan.count <= 50);
721
- for (const candidate of secondPlan.candidates) {
722
- assert.equal(cortex.get(candidate.id).state, 'active');
723
- }
724
-
725
- // Privacy deleteScope removes every trace (active and archived) and every
726
- // derived index, while preserving the append-only event ledger exactly.
727
- const deleted = cortex.privacy.deleteScope(SCOPE, {
728
- actor: 'integration-test',
729
- reason: 'load-retention',
730
- });
731
- assert.equal(deleted.scopeId, SCOPE);
732
- assert.equal(deleted.removed, true);
733
- assert.equal(deleted.counts.traces, count);
734
- assert.equal(countTraces(cortex), 0);
735
- assert.equal(cortex.repos.traces.ftsCount(), 0);
736
- assert.equal(cortex.repos.events.count(), eventsBefore);
737
- const chain = cortex.repos.events.verifyChain();
738
- assert.equal(chain.ok, true);
739
- assert.equal(chain.count, eventsBefore);
740
- assert.equal(cortex.repos.events.list({ limit: 10 }).length, 10);
741
- assert.equal(cortex.search('鲸鱼').items.length, 0);
742
-
743
- t.diagnostic(
744
- `retention/privacy: planned ${plan.count} of ${count} traces, `
745
- + `archived ${applied.archived}, deleted scope, kept ${eventsBefore} events`,
746
- );
747
- } finally {
748
- closeQuietly(cortex);
749
- removeQuietly(root);
750
- }
751
- });