dsh-cortex-memory 0.4.146 → 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 (168) hide show
  1. package/CHANGELOG.md +2396 -2369
  2. package/README.md +8 -6
  3. package/bench/semantic-cn.js +4 -4
  4. package/bench/synthetic.js +2 -2
  5. package/bin/copy-db.mjs +1 -1
  6. package/client.js +1 -1
  7. package/docs/quota-compaction-design.md +2 -2
  8. package/icon.svg +12 -2
  9. package/package.json +1 -1
  10. package/src/engines/consolidate.js +2 -2
  11. package/src/engines/health.js +1 -1
  12. package/src/engines/life.js +2 -2
  13. package/src/engines/narrative.js +2 -2
  14. package/src/host/scheduler.js +1 -1
  15. package/src/store/repositories/traces.js +1 -1
  16. package/test/integration/_helpers.js +0 -128
  17. package/test/integration/acceptance.test.js +0 -803
  18. package/test/integration/ann-load.test.js +0 -61
  19. package/test/integration/api-contract.test.js +0 -1476
  20. package/test/integration/backup-privacy.test.js +0 -214
  21. package/test/integration/consolidate.test.js +0 -79
  22. package/test/integration/edge-cases.test.js +0 -1089
  23. package/test/integration/exchange.test.js +0 -326
  24. package/test/integration/life-loop.test.js +0 -189
  25. package/test/integration/load.test.js +0 -751
  26. package/test/integration/markdown-sync.test.js +0 -35
  27. package/test/integration/policy-query-api.test.js +0 -306
  28. package/test/integration/resilience-writes.test.js +0 -241
  29. package/test/integration/tools-contract.test.js +0 -1324
  30. package/test/unit/alias.test.js +0 -87
  31. package/test/unit/ann-edge.test.js +0 -102
  32. package/test/unit/ann.test.js +0 -77
  33. package/test/unit/api-client.test.js +0 -576
  34. package/test/unit/api-validate.test.js +0 -19
  35. package/test/unit/api.test.js +0 -555
  36. package/test/unit/appraisal.test.js +0 -48
  37. package/test/unit/attachments.test.js +0 -33
  38. package/test/unit/auto-reflect.test.js +0 -141
  39. package/test/unit/autonomy.test.js +0 -53
  40. package/test/unit/batch.test.js +0 -46
  41. package/test/unit/bench.test.js +0 -40
  42. package/test/unit/benchmark-synthetic.test.js +0 -52
  43. package/test/unit/capture-filter.test.js +0 -296
  44. package/test/unit/cli-default-root.test.js +0 -21
  45. package/test/unit/client-contract.test.js +0 -32
  46. package/test/unit/compaction-preview.test.js +0 -91
  47. package/test/unit/compression.test.js +0 -76
  48. package/test/unit/consolidate-dedupe.test.js +0 -174
  49. package/test/unit/consolidate-errors.test.js +0 -63
  50. package/test/unit/consolidate-gate.test.js +0 -26
  51. package/test/unit/consolidate-preview.test.js +0 -168
  52. package/test/unit/consolidate-protection.test.js +0 -156
  53. package/test/unit/consolidate-reason.test.js +0 -206
  54. package/test/unit/consolidate-retry.test.js +0 -91
  55. package/test/unit/consolidate-selection.test.js +0 -103
  56. package/test/unit/core.test.js +0 -77
  57. package/test/unit/coverage-rewrite.test.js +0 -38
  58. package/test/unit/dedupe-episodes.test.js +0 -34
  59. package/test/unit/dedupe-threshold.test.js +0 -14
  60. package/test/unit/develop.test.js +0 -130
  61. package/test/unit/development.test.js +0 -68
  62. package/test/unit/digest.test.js +0 -26
  63. package/test/unit/dsr.test.js +0 -111
  64. package/test/unit/edges-candidates.test.js +0 -113
  65. package/test/unit/emotion.test.js +0 -62
  66. package/test/unit/encode.test.js +0 -98
  67. package/test/unit/evolution.test.js +0 -130
  68. package/test/unit/external-ann-search.test.js +0 -50
  69. package/test/unit/external-ann.test.js +0 -29
  70. package/test/unit/extract-question.test.js +0 -41
  71. package/test/unit/fact-guard.test.js +0 -51
  72. package/test/unit/fact-noise-llm.test.js +0 -44
  73. package/test/unit/facts-belief.test.js +0 -32
  74. package/test/unit/facts-compat.test.js +0 -62
  75. package/test/unit/facts.test.js +0 -107
  76. package/test/unit/feature-overrides.test.js +0 -42
  77. package/test/unit/fts-migration.test.js +0 -42
  78. package/test/unit/graph.test.js +0 -79
  79. package/test/unit/growth-reflect.test.js +0 -124
  80. package/test/unit/guard-runtime.test.js +0 -40
  81. package/test/unit/guardian.test.js +0 -91
  82. package/test/unit/health-consolidation.test.js +0 -52
  83. package/test/unit/health-fts-scope.test.js +0 -33
  84. package/test/unit/health-privacy.test.js +0 -102
  85. package/test/unit/health-summaries.test.js +0 -24
  86. package/test/unit/health-text-maintain.test.js +0 -33
  87. package/test/unit/health-today.test.js +0 -45
  88. package/test/unit/hnsw.test.js +0 -35
  89. package/test/unit/host-runtime.test.js +0 -142
  90. package/test/unit/host.test.js +0 -58
  91. package/test/unit/identity.test.js +0 -98
  92. package/test/unit/induct-evaluate.test.js +0 -41
  93. package/test/unit/ingest-extracted.test.js +0 -35
  94. package/test/unit/inhibition.test.js +0 -90
  95. package/test/unit/initiative.test.js +0 -90
  96. package/test/unit/jobs.test.js +0 -93
  97. package/test/unit/json-snapshot.test.js +0 -57
  98. package/test/unit/label-entities-skip.test.js +0 -18
  99. package/test/unit/life-consolidate.test.js +0 -34
  100. package/test/unit/life.test.js +0 -149
  101. package/test/unit/llm-facts-integration.test.js +0 -27
  102. package/test/unit/llm-facts.test.js +0 -16
  103. package/test/unit/llm.test.js +0 -45
  104. package/test/unit/locomo.test.js +0 -45
  105. package/test/unit/longmemeval.test.js +0 -56
  106. package/test/unit/maintain-dispute.test.js +0 -62
  107. package/test/unit/maintain-duration.test.js +0 -194
  108. package/test/unit/markdown-import.test.js +0 -44
  109. package/test/unit/markdown.test.js +0 -34
  110. package/test/unit/memory-edit.test.js +0 -112
  111. package/test/unit/metrics.test.js +0 -26
  112. package/test/unit/migration.test.js +0 -38
  113. package/test/unit/model-config.test.js +0 -52
  114. package/test/unit/mood-saturation.test.js +0 -33
  115. package/test/unit/narrative-weave.test.js +0 -271
  116. package/test/unit/narrative.test.js +0 -62
  117. package/test/unit/playbook-consolidate.test.js +0 -24
  118. package/test/unit/privacy-scope.test.js +0 -39
  119. package/test/unit/profile-paths.test.js +0 -21
  120. package/test/unit/profile.test.js +0 -26
  121. package/test/unit/prompt.test.js +0 -42
  122. package/test/unit/providers.test.js +0 -42
  123. package/test/unit/qa.test.js +0 -100
  124. package/test/unit/query.test.js +0 -53
  125. package/test/unit/reflect-backfill.test.js +0 -158
  126. package/test/unit/reflect-coverage.test.js +0 -35
  127. package/test/unit/reflect-overview.test.js +0 -22
  128. package/test/unit/reflect-phrasing.test.js +0 -75
  129. package/test/unit/reflect-sampling.test.js +0 -80
  130. package/test/unit/reflect-source-budget.test.js +0 -24
  131. package/test/unit/relationship-dynamics.test.js +0 -29
  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/revive-on-read.test.js +0 -84
  136. package/test/unit/rotation.test.js +0 -25
  137. package/test/unit/scanner.test.js +0 -50
  138. package/test/unit/scenario.test.js +0 -78
  139. package/test/unit/scheduler-autoconsolidate.test.js +0 -95
  140. package/test/unit/scheduler-autodedupe.test.js +0 -52
  141. package/test/unit/scheduler-autosleep.test.js +0 -50
  142. package/test/unit/scheduler-cadence.test.js +0 -33
  143. package/test/unit/scheduler-deep.test.js +0 -62
  144. package/test/unit/scheduler-tick-gate.test.js +0 -38
  145. package/test/unit/scheduler.test.js +0 -137
  146. package/test/unit/self-state.test.js +0 -94
  147. package/test/unit/service.test.js +0 -72
  148. package/test/unit/shiori-import.test.js +0 -77
  149. package/test/unit/skills.test.js +0 -104
  150. package/test/unit/spacing.test.js +0 -14
  151. package/test/unit/store.test.js +0 -111
  152. package/test/unit/summon-left-slot.test.js +0 -51
  153. package/test/unit/summon-rank.test.js +0 -51
  154. package/test/unit/temporal-graph.test.js +0 -44
  155. package/test/unit/tiers-gist.test.js +0 -140
  156. package/test/unit/tiers.test.js +0 -39
  157. package/test/unit/tokenizer-fts.test.js +0 -35
  158. package/test/unit/tools.test.js +0 -122
  159. package/test/unit/upgrade-0412.test.js +0 -104
  160. package/test/unit/upgrade-0413.test.js +0 -84
  161. package/test/unit/upgrade-0414.test.js +0 -101
  162. package/test/unit/vector-ann.test.js +0 -53
  163. package/test/unit/vector-async.test.js +0 -69
  164. package/test/unit/vector-coverage.test.js +0 -34
  165. package/test/unit/vector-override.test.js +0 -37
  166. package/test/unit/vector-typed-array.test.js +0 -47
  167. package/test/unit/vector.test.js +0 -68
  168. package/test/unit/working.test.js +0 -99
@@ -1,1089 +0,0 @@
1
- /**
2
- * Adversarial integration coverage for cross-cutting edges the happy-path
3
- * suite does not exercise: scopes across every entry point, guardian failure
4
- * modes, API input boundaries and per-scope self state.
5
- *
6
- * Everything here uses a real cortex on a throwaway database; nothing is mocked
7
- * except the one collaborator under test (retrieval / vector), and every patch
8
- * is restored in a finally block.
9
- */
10
- import test from 'node:test';
11
- import assert from 'node:assert/strict';
12
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
13
- import path from 'node:path';
14
- import { Readable } from 'node:stream';
15
- import { setTimeout as delay } from 'node:timers/promises';
16
- import { API_BASE, createApiHandler } from '../../src/api/routes.js';
17
- import {
18
- BASE_MS,
19
- DAY_MS,
20
- apiResponse,
21
- cleanup,
22
- invokeApi,
23
- makeCortex,
24
- } from './_helpers.js';
25
-
26
- function idsOf(result) {
27
- return result.items.map((item) => item.id).sort();
28
- }
29
-
30
- function scopesOf(result, cortex) {
31
- return result.items.map((item) => cortex.get(item.id).scopeId);
32
- }
33
-
34
- function sourceOf(result, source) {
35
- return result.trace.sources.find((entry) => entry.source === source);
36
- }
37
-
38
- /** Request stream for bodies that cannot be expressed through JSON.stringify. */
39
- function rawRequest({ method = 'POST', route = '/write', raw = '', headers = {} } = {}) {
40
- const stream = Readable.from([Buffer.from(raw, 'utf8')]);
41
- stream.method = method;
42
- stream.url = `${API_BASE}${route}`;
43
- const merged = {
44
- host: '127.0.0.1:7430',
45
- origin: 'http://127.0.0.1:7430',
46
- 'sec-fetch-site': 'same-origin',
47
- 'content-type': 'application/json',
48
- 'x-cortex': '1',
49
- ...headers,
50
- };
51
- for (const [key, value] of Object.entries(merged)) if (value === undefined) delete merged[key];
52
- stream.headers = merged;
53
- stream.socket = { remoteAddress: '127.0.0.1' };
54
- return stream;
55
- }
56
-
57
- async function invokeRaw(handler, options = {}) {
58
- const response = apiResponse();
59
- await handler(rawRequest(options), response);
60
- return {
61
- status: response.statusCode,
62
- headers: response.headers,
63
- json: response.body ? JSON.parse(response.body) : {},
64
- };
65
- }
66
-
67
- // ---------------------------------------------------------------------------
68
- // 1. Scope isolation across write / search / working / goals
69
- // ---------------------------------------------------------------------------
70
-
71
- test('scope isolation keeps writes, search, working memory and goals inside their scope', () => {
72
- const context = makeCortex();
73
- const { cortex } = context;
74
- try {
75
- const shared = '用户喜欢米饭,这是同一条跨 scope 文本。';
76
- const globalWrite = cortex.write({ text: shared, title: 'global copy', explicit: true, scopeId: 'global', now: BASE_MS });
77
- const s2Write = cortex.write({ text: shared, title: 's2 copy', explicit: true, scopeId: 's2', now: BASE_MS + 1_000 });
78
- const s2Extra = cortex.write({ text: '只有 s2 能看到的技术记录。', title: 's2 tech', explicit: true, scopeId: 's2', now: BASE_MS + 2_000 });
79
- const s2Duplicate = cortex.write({ text: shared, title: 's2 duplicate', explicit: true, scopeId: 's2', now: BASE_MS + 3_000 });
80
-
81
- assert.equal(globalWrite.skipped, false);
82
- assert.equal(s2Write.skipped, false);
83
- assert.equal(s2Extra.skipped, false);
84
- // Content dedupe is per scope: the same text exists twice, but only once per scope.
85
- assert.equal(s2Duplicate.skipped, true);
86
- assert.equal(s2Duplicate.reason, 'duplicate');
87
- assert.equal(s2Duplicate.trace.id, s2Write.trace.id);
88
- assert.notEqual(globalWrite.trace.id, s2Write.trace.id);
89
- assert.equal(globalWrite.trace.scopeId, 'global');
90
- assert.equal(s2Write.trace.scopeId, 's2');
91
- assert.equal(cortex.repos.traces.count({ scopeId: 'global' }), 1);
92
- assert.equal(cortex.repos.traces.count({ scopeId: 's2' }), 2);
93
- assert.equal(cortex.repos.traces.count(), 3);
94
- // The duplicate attempt is still recorded in the scoped event ledger.
95
- assert.equal(cortex.repos.events.count('global'), 1);
96
- assert.equal(cortex.repos.events.count('s2'), 3);
97
- assert.equal(cortex.repos.events.count(), 4);
98
-
99
- const globalHits = cortex.search('米饭', { scopeId: 'global', now: BASE_MS + 4_000, limit: 10 });
100
- const s2Hits = cortex.search('米饭', { scopeId: 's2', now: BASE_MS + 4_000, limit: 10 });
101
- const defaultHits = cortex.search('米饭', { now: BASE_MS + 4_000, limit: 10 });
102
- assert.equal(globalHits.scopeId, 'global');
103
- assert.equal(s2Hits.scopeId, 's2');
104
- // Retrieval merges a scoped recency source, so assert scope membership
105
- // rather than exact lexical hits.
106
- assert.equal(scopesOf(globalHits, cortex).every((scopeId) => scopeId === 'global'), true);
107
- assert.equal(scopesOf(s2Hits, cortex).every((scopeId) => scopeId === 's2'), true);
108
- assert.equal(scopesOf(defaultHits, cortex).every((scopeId) => scopeId === 'global'), true);
109
- assert.ok(globalHits.items.some((item) => item.id === globalWrite.trace.id));
110
- assert.ok(s2Hits.items.some((item) => item.id === s2Write.trace.id));
111
- assert.equal(globalHits.items.some((item) => item.id === s2Write.trace.id), false);
112
- assert.equal(s2Hits.items.some((item) => item.id === globalWrite.trace.id), false);
113
- const globalTechnical = cortex.search('技术记录', { scopeId: 'global', now: BASE_MS + 4_000 });
114
- const s2Technical = cortex.search('技术记录', { scopeId: 's2', now: BASE_MS + 4_000 });
115
- assert.equal(globalTechnical.items.some((item) => item.id === s2Extra.trace.id), false);
116
- assert.ok(s2Technical.items.some((item) => item.id === s2Extra.trace.id));
117
- assert.equal(s2Technical.items.some((item) => item.id === globalWrite.trace.id), false);
118
- assert.equal(scopesOf(globalTechnical, cortex).every((scopeId) => scopeId === 'global'), true);
119
- assert.equal(scopesOf(s2Technical, cortex).every((scopeId) => scopeId === 's2'), true);
120
-
121
- const globalFocus = cortex.working.add({ scopeId: 'global', text: '全局焦点:写测试。', priority: 0.9, at: BASE_MS });
122
- const s2Focus = cortex.working.add({ scopeId: 's2', text: 's2 焦点:整理记录。', priority: 0.9, at: BASE_MS });
123
- assert.deepEqual(cortex.working.list({ scopeId: 'global' }).map((item) => item.id), [globalFocus.id]);
124
- assert.deepEqual(cortex.working.list({ scopeId: 's2' }).map((item) => item.id), [s2Focus.id]);
125
- assert.equal(cortex.working.get(globalFocus.id).scopeId, 'global');
126
- assert.equal(cortex.working.get(s2Focus.id).scopeId, 's2');
127
-
128
- const globalGoal = cortex.goals.add({ scopeId: 'global', title: '完成全局测试', priority: 0.8 });
129
- const s2Goal = cortex.goals.add({ scopeId: 's2', title: '完成 s2 测试', priority: 0.7 });
130
- assert.deepEqual(cortex.goals.list({ scopeId: 'global' }).map((goal) => goal.id), [globalGoal.id]);
131
- assert.deepEqual(cortex.goals.list({ scopeId: 's2' }).map((goal) => goal.id), [s2Goal.id]);
132
- cortex.goals.update(s2Goal.id, { progress: 0.5 });
133
- assert.equal(cortex.goals.get(globalGoal.id).progress, 0);
134
- assert.equal(cortex.goals.get(s2Goal.id).progress, 0.5);
135
-
136
- const globalSelf = cortex.self();
137
- const s2Self = cortex.self('s2');
138
- assert.equal(globalSelf.self.scopeId, 'global');
139
- assert.equal(s2Self.self.scopeId, 's2');
140
- assert.deepEqual(globalSelf.working.map((item) => item.id), [globalFocus.id]);
141
- assert.deepEqual(s2Self.working.map((item) => item.id), [s2Focus.id]);
142
- assert.deepEqual(globalSelf.goals.map((goal) => goal.id), [globalGoal.id]);
143
- assert.deepEqual(s2Self.goals.map((goal) => goal.id), [s2Goal.id]);
144
-
145
- cortex.goals.complete(s2Goal.id);
146
- assert.equal(cortex.goals.list({ scopeId: 'global', status: 'active' }).length, 1);
147
- assert.equal(cortex.goals.list({ scopeId: 's2', status: 'active' }).length, 0);
148
- assert.equal(cortex.goals.get(s2Goal.id).status, 'completed');
149
- assert.equal(cortex.goals.get(globalGoal.id).status, 'active');
150
-
151
- assert.equal(cortex.working.remove(s2Focus.id), true);
152
- assert.equal(cortex.working.list({ scopeId: 'global' }).length, 1);
153
- assert.equal(cortex.working.list({ scopeId: 's2' }).length, 0);
154
-
155
- const guard = cortex.guardian.check();
156
- assert.equal(guard.ok, true);
157
- assert.deepEqual(guard.issues, []);
158
- assert.equal(guard.chain.count, 4);
159
- } finally {
160
- cleanup(context);
161
- }
162
- });
163
-
164
- // ---------------------------------------------------------------------------
165
- // 2. Invalid scopes from every API channel fall back to global
166
- // ---------------------------------------------------------------------------
167
-
168
- test('invalid scope values from header, query and body fall back to global', async () => {
169
- const context = makeCortex();
170
- const { cortex } = context;
171
- try {
172
- const handler = createApiHandler({ cortex });
173
- const postWrite = (route, text, headers = {}, extra = {}) => invokeApi(handler, {
174
- method: 'POST',
175
- route,
176
- body: { text, explicit: true, ...extra },
177
- headers: { 'x-cortex': '1', ...headers },
178
- });
179
- const write = (text, headers = {}, extra = {}) => postWrite('/write', text, headers, extra);
180
- const traceScope = (result) => {
181
- assert.equal(result.status, 200, JSON.stringify(result.json));
182
- return result.json.data.trace.scopeId;
183
- };
184
- const longScope = 'x'.repeat(121);
185
- const allowedScope = 'team.a_1:x-2';
186
-
187
- assert.equal(traceScope(await write('team-a fallback scope edge', { 'x-cortex-scope': 'team-a' })), 'team-a');
188
- assert.equal(traceScope(await write('bad-header fallback scope edge', { 'x-cortex-scope': 'bad scope!' })), 'global');
189
- assert.equal(traceScope(await write('blank-header fallback scope edge', { 'x-cortex-scope': ' ' })), 'global');
190
- assert.equal(traceScope(await write('long-header fallback scope edge', { 'x-cortex-scope': longScope })), 'global');
191
- assert.equal(traceScope(await write('traversal-header fallback scope edge', { 'x-cortex-scope': '../etc' })), 'global');
192
- assert.equal(traceScope(await write('body-good fallback scope edge', {}, { scopeId: 'body-scope' })), 'body-scope');
193
- assert.equal(traceScope(await write('body-bad fallback scope edge', {}, { scopeId: 'bad/scope' })), 'global');
194
- assert.equal(
195
- traceScope(await postWrite('/write?scope=query-scope', 'header precedence fallback scope edge', { 'x-cortex-scope': 'header-scope' }, { scopeId: 'body-scope' })),
196
- 'header-scope',
197
- );
198
- assert.equal(
199
- traceScope(await postWrite('/write?scope=query-scope', 'query precedence fallback scope edge', {}, { scopeId: 'body-scope' })),
200
- 'query-scope',
201
- );
202
- assert.equal(
203
- traceScope(await postWrite('/write?scope=query-scope', 'invalid-header-with-query fallback scope edge', { 'x-cortex-scope': 'bad scope!' }, { scopeId: 'body-scope' })),
204
- 'global',
205
- );
206
- assert.equal(traceScope(await write('allowed-chars fallback scope edge', { 'x-cortex-scope': allowedScope })), allowedScope);
207
-
208
- const scopes = cortex.db.prepare('SELECT DISTINCT scope_id FROM traces ORDER BY scope_id').all().map((row) => row.scope_id);
209
- assert.deepEqual(scopes, ['body-scope', 'global', 'header-scope', 'query-scope', 'team-a', allowedScope]);
210
- assert.equal(scopes.every((scope) => /^[A-Za-z0-9._:-]+$/.test(scope)), true);
211
- assert.equal(cortex.repos.traces.count({ scopeId: 'global' }), 6);
212
- assert.equal(cortex.repos.traces.count({ scopeId: 'team-a' }), 1);
213
- assert.equal(cortex.repos.traces.count({ scopeId: 'body-scope' }), 1);
214
- assert.equal(cortex.repos.traces.count({ scopeId: 'header-scope' }), 1);
215
- assert.equal(cortex.repos.traces.count({ scopeId: 'query-scope' }), 1);
216
- assert.equal(cortex.repos.traces.count({ scopeId: allowedScope }), 1);
217
-
218
- const globalSearch = await invokeApi(handler, { route: '/search?q=fallback&limit=20' });
219
- assert.equal(globalSearch.status, 200);
220
- assert.equal(globalSearch.json.data.scopeId, 'global');
221
- assert.equal(globalSearch.json.data.items.length, 6);
222
- const invalidSearchScope = await invokeApi(handler, { route: '/search?q=fallback&limit=20&scope=bad%20scope' });
223
- assert.equal(invalidSearchScope.status, 200);
224
- assert.equal(invalidSearchScope.json.data.scopeId, 'global');
225
- assert.equal(invalidSearchScope.json.data.items.length, 6);
226
- const bodySearchScope = await invokeApi(handler, {
227
- method: 'POST',
228
- route: '/search',
229
- body: { query: 'fallback', limit: 20, scopeId: 'bad/scope' },
230
- headers: { 'x-cortex': '1' },
231
- });
232
- assert.equal(bodySearchScope.status, 200);
233
- assert.equal(bodySearchScope.json.data.scopeId, 'global');
234
- assert.equal(bodySearchScope.json.data.items.length, 6);
235
-
236
- const invalidWorking = await invokeApi(handler, {
237
- method: 'POST',
238
- route: '/working/add',
239
- body: { text: 'fallback working item' },
240
- headers: { 'x-cortex': '1', 'x-cortex-scope': 'bad scope!' },
241
- });
242
- assert.equal(invalidWorking.status, 200);
243
- assert.equal(invalidWorking.json.data.scopeId, 'global');
244
- const globalWorking = await invokeApi(handler, { route: '/working' });
245
- assert.equal(globalWorking.json.data.length, 1);
246
- const teamWorking = await invokeApi(handler, { route: '/working?scope=team-a' });
247
- assert.equal(teamWorking.json.data.length, 0);
248
-
249
- const invalidGoal = await invokeApi(handler, {
250
- method: 'POST',
251
- route: '/goals/add',
252
- body: { title: 'fallback goal' },
253
- headers: { 'x-cortex': '1', 'x-cortex-scope': 'bad scope!' },
254
- });
255
- assert.equal(invalidGoal.status, 200);
256
- assert.equal(invalidGoal.json.data.scopeId, 'global');
257
- const globalGoals = await invokeApi(handler, { route: '/goals' });
258
- assert.equal(globalGoals.json.data.length, 1);
259
- const teamGoals = await invokeApi(handler, { route: '/goals?scope=team-a' });
260
- assert.equal(teamGoals.json.data.length, 0);
261
- } finally {
262
- cleanup(context);
263
- }
264
- });
265
-
266
- // ---------------------------------------------------------------------------
267
- // 3. Budget guard blocks before retrieval and reports it explicitly
268
- // ---------------------------------------------------------------------------
269
-
270
- test('search over the per-hour call budget returns a blocked trace and does not touch retrieval', () => {
271
- const context = makeCortex({ maxCallsPerHour: 2 });
272
- const { cortex } = context;
273
- try {
274
- cortex.write({ text: '预算测试:这条记忆只用于搜索。', explicit: true, now: BASE_MS });
275
- const first = cortex.search('预算测试', { now: BASE_MS, limit: 5 });
276
- const second = cortex.search('预算测试', { now: BASE_MS + 1, limit: 5 });
277
- assert.ok(first.items.length >= 1);
278
- assert.ok(second.items.length >= 1);
279
- assert.equal(cortex.budget.snapshot().calls, 2);
280
- assert.equal(cortex.budget.snapshot().remainingCalls, 0);
281
-
282
- const original = cortex.engines.retrieve.search;
283
- let retrieveCalls = 0;
284
- try {
285
- cortex.engines.retrieve.search = () => {
286
- retrieveCalls += 1;
287
- throw new Error('retrieval must not run when the budget is exhausted');
288
- };
289
- const blocked = cortex.search('预算测试', { now: BASE_MS + 2, limit: 5 });
290
- assert.equal(retrieveCalls, 0);
291
- assert.equal(blocked.query, '预算测试');
292
- assert.equal(blocked.intent, 'fact');
293
- assert.equal(blocked.scopeId, 'global');
294
- assert.deepEqual(blocked.items, []);
295
- assert.deepEqual(blocked.budget, { used: 0, total: 0 });
296
- assert.equal(blocked.trace.blocked, 'budget');
297
- assert.equal(blocked.trace.elapsedMs, 0);
298
- assert.equal(blocked.trace.candidates, 0);
299
- assert.equal(blocked.trace.selected, 0);
300
- assert.equal(blocked.trace.dropped, 0);
301
- assert.deepEqual(blocked.trace.sources, []);
302
- assert.ok(Number.isFinite(Date.parse(blocked.at)));
303
- const again = cortex.search('预算测试', { now: BASE_MS + 3, limit: 5 });
304
- assert.equal(again.trace.blocked, 'budget');
305
- assert.equal(retrieveCalls, 0);
306
- } finally {
307
- cortex.engines.retrieve.search = original;
308
- }
309
-
310
- const metrics = cortex.metrics();
311
- assert.equal(metrics.counters['search.calls'], 2);
312
- assert.equal(metrics.counters['search.blocked.budget'], 2);
313
- assert.equal(metrics.counters['search.errors'], undefined);
314
- assert.equal(metrics.histograms['search.ms'].count, 2);
315
- assert.equal(cortex.budget.snapshot().calls, 2);
316
- // Search is guarded, writes are not: the service remains usable.
317
- const written = cortex.write({ text: '预算耗尽后仍然可以写入。', explicit: true, now: BASE_MS + 4 });
318
- assert.equal(written.skipped, false);
319
- assert.equal(cortex.repos.traces.count(), 2);
320
- } finally {
321
- cleanup(context);
322
- }
323
- });
324
-
325
- // ---------------------------------------------------------------------------
326
- // 4. Circuit breaker opens, blocks, then recovers after the cooldown
327
- // ---------------------------------------------------------------------------
328
-
329
- test('circuit breaker opens on repeated retrieval errors, blocks with a circuit trace and recovers', async () => {
330
- const context = makeCortex({ maxCallsPerHour: 100, circuitThreshold: 2, circuitCooldownMs: 120 });
331
- const { cortex } = context;
332
- try {
333
- cortex.write({ text: '熔断测试:这条记忆用于恢复。', explicit: true, now: BASE_MS });
334
- const original = cortex.engines.retrieve.search;
335
- let attempts = 0;
336
- try {
337
- cortex.engines.retrieve.search = () => {
338
- attempts += 1;
339
- throw new Error('retrieval exploded');
340
- };
341
- assert.throws(() => cortex.search('熔断测试', { now: BASE_MS }), /retrieval exploded/);
342
- assert.equal(cortex.circuit.snapshot().state, 'closed');
343
- assert.throws(() => cortex.search('熔断测试', { now: BASE_MS + 1 }), /retrieval exploded/);
344
- const opened = cortex.circuit.snapshot();
345
- assert.equal(opened.state, 'open');
346
- assert.equal(opened.failures, 2);
347
- assert.ok(opened.remainingMs > 0);
348
-
349
- const blocked = cortex.search('熔断测试', { now: BASE_MS + 2, limit: 5 });
350
- assert.equal(attempts, 2, 'blocked search must not call retrieval again');
351
- assert.equal(blocked.items.length, 0);
352
- assert.equal(blocked.trace.blocked, 'circuit');
353
- assert.equal(blocked.trace.elapsedMs, 0);
354
- assert.equal(blocked.trace.candidates, 0);
355
- assert.deepEqual(blocked.trace.sources, []);
356
- assert.deepEqual(blocked.budget, { used: 0, total: 0 });
357
- // Failed searches never spend budget, and blocked calls do not either.
358
- assert.equal(cortex.budget.snapshot().calls, 0);
359
- } finally {
360
- cortex.engines.retrieve.search = original;
361
- }
362
-
363
- const metrics = cortex.metrics();
364
- assert.equal(metrics.counters['search.errors'], 2);
365
- assert.equal(metrics.counters['search.blocked.circuit'], 1);
366
- assert.equal(metrics.counters['search.calls'], undefined);
367
-
368
- await delay(200); // > circuitCooldownMs
369
- const recovered = cortex.search('熔断测试', { now: BASE_MS + 3, limit: 5 });
370
- assert.ok(recovered.items.length >= 1);
371
- assert.equal('blocked' in recovered.trace, false);
372
- assert.equal(cortex.circuit.snapshot().state, 'closed');
373
- assert.equal(cortex.circuit.snapshot().failures, 0);
374
- assert.equal(cortex.budget.snapshot().calls, 1);
375
- assert.equal(cortex.metrics().counters['search.calls'], 1);
376
- } finally {
377
- cleanup(context);
378
- }
379
- });
380
-
381
- // ---------------------------------------------------------------------------
382
- // 5. Privacy deleteScope empties every derived store but keeps the ledger
383
- // ---------------------------------------------------------------------------
384
-
385
- test('privacy.deleteScope wipes diary, dreams, sleep, emotion, feedback and facts while preserving events', async () => {
386
- const context = makeCortex({ features: { vector: true } });
387
- const { cortex } = context;
388
- try {
389
- const first = cortex.write({
390
- text: '用户答应买米饭,这是隐私删除测试。',
391
- title: '米饭承诺',
392
- explicit: true,
393
- now: BASE_MS,
394
- facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买米饭', confidence: 0.9 }],
395
- });
396
- const second = cortex.write({
397
- text: '用户想给助手一个实体。',
398
- title: '实体',
399
- explicit: true,
400
- now: BASE_MS + 1_000,
401
- facts: [{ subject: '用户', predicate: '想给', object: '助手', confidence: 0.8 }],
402
- });
403
- const otherScope = cortex.write({ text: '另一个 scope 必须活下来。', explicit: true, scopeId: 's2', now: BASE_MS + 2_000 });
404
- cortex.feedback({ traceId: first.trace.id, signal: 'used', predicted: 0.8, now: BASE_MS + 3_000 });
405
- cortex.working.add({ text: '隐私删除前的焦点。', priority: 0.9, at: BASE_MS });
406
- cortex.working.add({ text: '已过期的焦点。', at: BASE_MS, ttlMs: 1_000 });
407
- cortex.working.add({ text: 's2 焦点。', scopeId: 's2', at: BASE_MS });
408
- cortex.goals.add({ title: '完成隐私测试', priority: 0.8 });
409
- cortex.goals.add({ title: '另一个目标', priority: 0.4 });
410
- cortex.goals.add({ title: 's2 目标', scopeId: 's2' });
411
- cortex.emotion.record({ text: '助手有点心疼用户。', target: '用户', at: new Date(BASE_MS + 4_000).toISOString() });
412
- cortex.emotion.record({ text: '用户很开心,助手也喜欢。', target: '用户', at: new Date(BASE_MS + 5_000).toISOString() });
413
- cortex.life.diaryWrite({ text: '今天把隐私删除测了一遍。', mood: '踏实', at: new Date(BASE_MS + 6_000).toISOString() });
414
- await cortex.life.dreamGenerate({ at: BASE_MS + 3_600_000 });
415
- const sleep = await cortex.life.sleep({ at: BASE_MS + 7_200_000, windowDays: 1 });
416
- assert.ok(sleep.id);
417
- assert.equal(sleep.purgedWorking, 1);
418
- assert.equal(sleep.reflected, 1);
419
-
420
- const countTable = (table, scopeId = 'global') => Number(
421
- cortex.db.prepare(`SELECT COUNT(*) AS c FROM ${table} WHERE scope_id = ?`).get(scopeId).c,
422
- );
423
- const before = {
424
- traces: countTable('traces'),
425
- facts: countTable('facts'),
426
- entities: countTable('entities'),
427
- edges: countTable('edges'),
428
- summaries: countTable('summaries'),
429
- feedback: countTable('feedback'),
430
- appraisals: countTable('appraisals'),
431
- emotionEvents: countTable('emotion_events'),
432
- working: countTable('working_items'),
433
- goals: countTable('goals'),
434
- skills: countTable('skills'),
435
- identity: countTable('identity_versions'),
436
- relationships: countTable('relationships'),
437
- intentions: countTable('intentions'),
438
- growth: countTable('growth_metrics'),
439
- disputes: countTable('disputes'),
440
- jobs: countTable('jobs'),
441
- diary: countTable('diary_entries'),
442
- dreams: countTable('dreams'),
443
- sleeps: countTable('sleep_runs'),
444
- };
445
- assert.equal(before.traces, 3, 'two writes plus one reflection');
446
- assert.equal(before.facts, 2);
447
- assert.equal(before.entities, 2);
448
- // episode(sleep 里的 reflect)+ 一条叙事线(sleep 里的 weave)
449
- assert.equal(before.summaries, 2);
450
- assert.equal(before.feedback, 1);
451
- assert.equal(before.emotionEvents, 2);
452
- assert.equal(before.working, 1, 'sleep purged the expired item');
453
- assert.equal(before.goals, 2);
454
- assert.equal(before.identity, 1);
455
- assert.equal(before.relationships, 1);
456
- assert.equal(before.growth, 1);
457
- assert.equal(before.diary, 1);
458
- assert.equal(before.dreams, 1);
459
- assert.equal(before.sleeps, 1);
460
- assert.equal(second.skipped, false);
461
- assert.equal(otherScope.skipped, false);
462
- assert.equal(countTable('affect_targets'), 1);
463
- assert.equal(countTable('self_state'), 1);
464
- const embeddingsGlobalBefore = Number(cortex.db.prepare(
465
- "SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id WHERE t.scope_id = 'global'",
466
- ).get().c);
467
- const embeddingsS2Before = Number(cortex.db.prepare(
468
- "SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id WHERE t.scope_id = 's2'",
469
- ).get().c);
470
- assert.equal(embeddingsGlobalBefore, 3);
471
- assert.equal(embeddingsS2Before, 1);
472
- before.affectTargets = 1;
473
- before.embeddings = embeddingsGlobalBefore;
474
- before.memoryLinks = 0;
475
- before.selfState = 1;
476
-
477
- const eventsBefore = cortex.repos.events.count();
478
- const globalEventsBefore = cortex.repos.events.count('global');
479
- const s2EventsBefore = cortex.repos.events.count('s2');
480
- assert.equal(eventsBefore, 4);
481
- assert.equal(globalEventsBefore, 3);
482
- assert.equal(s2EventsBefore, 1);
483
- assert.equal(JSON.stringify(cortex.repos.events.list({ limit: 100 }).map((event) => event.payload)).includes('米饭'), false);
484
-
485
- const deleted = cortex.privacy.deleteScope('global', { actor: 'user', reason: 'edge-privacy' });
486
- assert.equal(deleted.scopeId, 'global');
487
- assert.equal(deleted.removed, true);
488
- assert.deepEqual(deleted.counts, before);
489
- assert.equal(Object.values(deleted.counts).every((value) => Number.isInteger(value)), true);
490
-
491
- // Every derived store is empty for the deleted scope.
492
- assert.equal(cortex.repos.traces.count({ scopeId: 'global' }), 0);
493
- assert.equal(cortex.get(first.trace.id), null);
494
- assert.equal(cortex.get(second.trace.id), null);
495
- assert.equal(cortex.repos.facts.list({ scopeId: 'global' }).length, 0);
496
- assert.equal(cortex.repos.entities.list({ scopeId: 'global' }).length, 0);
497
- assert.equal(cortex.repos.feedback.list({ scopeId: 'global' }).length, 0);
498
- assert.equal(cortex.working.list({ scopeId: 'global', includeExpired: true }).length, 0);
499
- assert.equal(cortex.goals.list({ scopeId: 'global' }).length, 0);
500
- assert.equal(cortex.emotion.events().length, 0);
501
- assert.equal(cortex.emotion.targets().length, 0);
502
- assert.equal(cortex.life.diaryList().length, 0);
503
- assert.equal(cortex.life.dreamList().length, 0);
504
- assert.equal(cortex.life.sleepRuns().length, 0);
505
- assert.equal(cortex.repos.summaries.list('global').length, 0);
506
- assert.equal(countTable('affect_targets'), 0);
507
- assert.equal(countTable('self_state'), 0);
508
- assert.equal(countTable('memory_links'), 0);
509
- assert.equal(cortex.repos.traces.ftsCount(), 1, 'the surviving s2 trace keeps its FTS row');
510
- assert.equal(Number(cortex.db.prepare(
511
- "SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id WHERE t.scope_id = 'global'",
512
- ).get().c), 0);
513
- assert.equal(Number(cortex.db.prepare(
514
- "SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id WHERE t.scope_id = 's2'",
515
- ).get().c), 1);
516
-
517
- // Other scopes are untouched.
518
- assert.equal(cortex.repos.traces.count({ scopeId: 's2' }), 1);
519
- assert.equal(cortex.get(otherScope.trace.id).content, '另一个 scope 必须活下来。');
520
- assert.equal(cortex.working.list({ scopeId: 's2' }).length, 1);
521
- assert.equal(cortex.goals.list({ scopeId: 's2' }).length, 1);
522
- assert.equal(cortex.repos.events.count('s2'), s2EventsBefore);
523
-
524
- // The event ledger is append-only and still verifiable.
525
- assert.equal(cortex.repos.events.count(), eventsBefore);
526
- assert.equal(cortex.repos.events.count('global'), globalEventsBefore);
527
- const chain = cortex.repos.events.verifyChain();
528
- assert.equal(chain.ok, true);
529
- assert.equal(chain.count, eventsBefore);
530
- assert.equal(JSON.stringify(cortex.repos.events.list({ limit: 100 }).map((event) => event.payload)).includes('米饭'), false);
531
-
532
- // The deletion is audited with the exact counts returned.
533
- const auditRecord = cortex.repos.audit.list({ limit: 200 })
534
- .find((entry) => entry.action === 'privacy.delete-scope' && entry.targetId === 'global');
535
- assert.ok(auditRecord);
536
- assert.equal(auditRecord.detail.reason, 'edge-privacy');
537
- assert.deepEqual(auditRecord.detail.counts, deleted.counts);
538
- assert.equal(Object.values(auditRecord.detail.counts).every((value) => Number.isInteger(value)), true);
539
-
540
- // Deleting an unknown scope is a no-op on data and a valid audit event.
541
- const emptyDelete = cortex.privacy.deleteScope('never-existed', { reason: 'edge-empty' });
542
- assert.equal(emptyDelete.removed, true);
543
- assert.equal(Object.values(emptyDelete.counts).every((value) => value === 0), true);
544
- assert.equal(cortex.repos.events.count(), eventsBefore);
545
- assert.throws(() => cortex.privacy.deleteScope(''), /scopeId is required/);
546
-
547
- const guard = cortex.guardian.check();
548
- assert.equal(guard.ok, true);
549
- assert.equal(guard.chain.count, eventsBefore);
550
- } finally {
551
- cleanup(context);
552
- }
553
- });
554
-
555
- // ---------------------------------------------------------------------------
556
- // 6. Corrupt backups fail open; restore refuses invalid / live targets
557
- // ---------------------------------------------------------------------------
558
-
559
- test('corrupt backups are rejected without throwing and restore refuses invalid or live targets', () => {
560
- const context = makeCortex();
561
- const { cortex, dir } = context;
562
- try {
563
- cortex.write({ text: '备份前的第一条记忆。', explicit: true, now: BASE_MS });
564
- cortex.write({ text: '备份前的第二条记忆。', explicit: true, now: BASE_MS + 1_000 });
565
- const backupPath = path.join(dir, 'valid.sqlite');
566
- const backup = cortex.guardian.backup(backupPath);
567
- assert.ok(backup.bytes > 0);
568
- assert.equal(cortex.guardian.validateBackup(backupPath).ok, true);
569
- const validBytes = readFileSync(backupPath);
570
-
571
- const truncatedPath = path.join(dir, 'truncated.sqlite');
572
- writeFileSync(truncatedPath, validBytes.subarray(0, Math.floor(validBytes.length / 2)));
573
- const truncated = cortex.guardian.validateBackup(truncatedPath);
574
- assert.equal(truncated.ok, false);
575
- assert.equal(truncated.reason, 'corrupt-or-unreadable');
576
- assert.equal(typeof truncated.error, 'string');
577
-
578
- const randomPath = path.join(dir, 'random.sqlite');
579
- writeFileSync(randomPath, Buffer.from('SQLite format 3\0 this is not a real database'));
580
- const random = cortex.guardian.validateBackup(randomPath);
581
- assert.equal(random.ok, false);
582
- assert.equal(random.reason, 'corrupt-or-unreadable');
583
-
584
- const emptyPath = path.join(dir, 'empty.sqlite');
585
- writeFileSync(emptyPath, '');
586
- const empty = cortex.guardian.validateBackup(emptyPath);
587
- assert.equal(empty.ok, false);
588
- assert.equal(empty.integrity, 'ok');
589
- assert.equal(empty.tables, 0);
590
- for (const required of ['events', 'traces', 'facts', 'entities', 'self_state', 'identity_versions']) {
591
- assert.ok(empty.missing.includes(required), required);
592
- }
593
-
594
- const rejectedTarget = path.join(dir, 'rejected.sqlite');
595
- const rejected = cortex.guardian.restore(truncatedPath, rejectedTarget);
596
- assert.equal(rejected.restored, false);
597
- assert.equal(rejected.reason, 'invalid-backup');
598
- assert.equal(rejected.validation.ok, false);
599
- assert.equal(existsSync(rejectedTarget), false);
600
-
601
- const corruptNoTarget = cortex.guardian.restore(truncatedPath);
602
- assert.equal(corruptNoTarget.restored, false);
603
- assert.equal(corruptNoTarget.reason, 'invalid-backup', 'validation happens before the target check');
604
-
605
- const noTarget = cortex.guardian.restore(backupPath);
606
- assert.equal(noTarget.restored, false);
607
- assert.equal(noTarget.reason, 'target-required');
608
-
609
- const liveAttempt = cortex.guardian.restore(backupPath, cortex.config.dbFile);
610
- assert.equal(liveAttempt.restored, false);
611
- assert.equal(liveAttempt.reason, 'live-db');
612
- assert.match(liveAttempt.message, /新路径|离线|关闭/);
613
- assert.equal(cortex.repos.traces.count(), 2);
614
- assert.equal(cortex.guardian.validateBackup(cortex.config.dbFile).ok, true);
615
-
616
- const missing = cortex.guardian.restore(path.join(dir, 'missing.sqlite'), path.join(dir, 'missing-target.sqlite'));
617
- assert.equal(missing.restored, false);
618
- assert.equal(missing.reason, 'invalid-backup');
619
- assert.equal(missing.validation.reason, 'missing');
620
-
621
- const offline = path.join(dir, 'offline', 'restored.sqlite');
622
- const restored = cortex.guardian.restore(backupPath, offline);
623
- assert.equal(restored.restored, true);
624
- assert.equal(restored.target, path.resolve(offline));
625
- assert.equal(restored.validation.ok, true);
626
- assert.equal(cortex.guardian.validateBackup(offline).ok, true);
627
-
628
- const guard = cortex.guardian.check();
629
- assert.equal(guard.ok, true);
630
- assert.equal(cortex.repos.traces.count(), 2);
631
- } finally {
632
- cleanup(context);
633
- }
634
- });
635
-
636
- // ---------------------------------------------------------------------------
637
- // 7. Malformed HTTP bodies and route/method edges
638
- // ---------------------------------------------------------------------------
639
-
640
- test('API rejects malformed JSON, unsafe bodies, oversized payloads, unknown routes and wrong methods', async () => {
641
- const context = makeCortex();
642
- const { cortex } = context;
643
- try {
644
- const handler = createApiHandler({ cortex });
645
-
646
- for (const raw of ['{"text":', '[]', 'null', '"a string"']) {
647
- const response = await invokeRaw(handler, { raw });
648
- assert.equal(response.status, 400, raw);
649
- assert.equal(response.json.ok, false);
650
- assert.equal(response.json.error, 'invalid json body');
651
- }
652
-
653
- const invalidJsonNoHeader = await invokeRaw(handler, { raw: '{"text":', headers: { 'x-cortex': undefined } });
654
- assert.equal(invalidJsonNoHeader.status, 403);
655
- assert.equal(invalidJsonNoHeader.json.error, 'missing x-cortex header');
656
-
657
- const missingHeader = await invokeApi(handler, {
658
- method: 'POST',
659
- route: '/write',
660
- body: { text: '没有 x-cortex 的写入。', explicit: true },
661
- });
662
- assert.equal(missingHeader.status, 403);
663
- assert.equal(missingHeader.json.error, 'missing x-cortex header');
664
-
665
- const oversized = await invokeRaw(handler, {
666
- raw: JSON.stringify({ text: 'x'.repeat(300_000), explicit: true }),
667
- });
668
- assert.equal(oversized.status, 400);
669
- assert.equal(oversized.json.error, 'invalid json body');
670
-
671
- const unknownGet = await invokeApi(handler, { route: '/does-not-exist' });
672
- assert.equal(unknownGet.status, 404);
673
- assert.equal(unknownGet.json.error, 'not found');
674
- const unknownHead = await invokeApi(handler, { method: 'HEAD', route: '/does-not-exist' });
675
- assert.equal(unknownHead.status, 404);
676
- const unknownPost = await invokeApi(handler, {
677
- method: 'POST',
678
- route: '/does-not-exist',
679
- body: {},
680
- headers: { 'x-cortex': '1' },
681
- });
682
- assert.equal(unknownPost.status, 404);
683
-
684
- for (const method of ['PUT', 'DELETE', 'PATCH']) {
685
- const response = await invokeApi(handler, { method, route: '/write' });
686
- assert.equal(response.status, 405, method);
687
- assert.equal(response.headers.allow, 'GET, HEAD, POST');
688
- assert.deepEqual(response.json, {});
689
- }
690
-
691
- const badWrites = [
692
- { body: { text: ' ' }, error: /text/ },
693
- { body: { text: '合法但重要度越界', importance: 2 }, error: /importance/ },
694
- { body: { text: '合法但标签不是数组', tags: [1] }, error: /tags/ },
695
- { body: { text: '合法但 explicit 不是布尔', explicit: 'yes' }, error: /explicit/ },
696
- ];
697
- for (const { body, error } of badWrites) {
698
- const response = await invokeApi(handler, { method: 'POST', route: '/write', body, headers: { 'x-cortex': '1' } });
699
- assert.equal(response.status, 400);
700
- assert.match(response.json.error, error);
701
- }
702
- const badSearchLimit = await invokeApi(handler, {
703
- method: 'POST', route: '/search', body: { query: 'x', limit: 99 }, headers: { 'x-cortex': '1' },
704
- });
705
- assert.equal(badSearchLimit.status, 400);
706
- assert.match(badSearchLimit.json.error, /limit/);
707
- const badSearchBudget = await invokeApi(handler, {
708
- method: 'POST', route: '/search', body: { query: 'x', budget: 10 }, headers: { 'x-cortex': '1' },
709
- });
710
- assert.equal(badSearchBudget.status, 400);
711
- assert.match(badSearchBudget.json.error, /budget/);
712
- const badForget = await invokeApi(handler, {
713
- method: 'POST', route: '/forget', body: { id: 'trc_missing', mode: 'purge' }, headers: { 'x-cortex': '1' },
714
- });
715
- assert.equal(badForget.status, 400);
716
- assert.match(badForget.json.error, /mode/);
717
-
718
- assert.equal(cortex.repos.traces.count(), 0);
719
- assert.equal(cortex.repos.events.count(), 0);
720
-
721
- const valid = await invokeApi(handler, {
722
- method: 'POST',
723
- route: '/write',
724
- body: { text: '所有坏请求之后仍然可以正常写入。', explicit: true },
725
- headers: { 'x-cortex': '1' },
726
- });
727
- assert.equal(valid.status, 200);
728
- assert.equal(valid.json.data.skipped, false);
729
- assert.equal(valid.json.data.trace.content, '所有坏请求之后仍然可以正常写入。');
730
- assert.equal(cortex.repos.traces.count(), 1);
731
- assert.equal(cortex.repos.events.count(), 1);
732
- const ping = await invokeApi(handler);
733
- assert.equal(ping.status, 200);
734
- assert.equal(ping.json.ok, true);
735
- } finally {
736
- cleanup(context);
737
- }
738
- });
739
-
740
- // ---------------------------------------------------------------------------
741
- // 8. FTS repair restores missing rows and drops stale ones
742
- // ---------------------------------------------------------------------------
743
-
744
- test('guardian.repairFts rebuilds a fully missing or stale FTS projection', () => {
745
- const context = makeCortex();
746
- const { cortex } = context;
747
- try {
748
- const first = cortex.write({ text: '第一条用于 FTS 修复。', title: '一', explicit: true, now: BASE_MS });
749
- const second = cortex.write({ text: '第二条用于 FTS 修复。', title: '二', explicit: true, now: BASE_MS + 1_000 });
750
- const archived = cortex.write({ text: '第三条已归档,也应有修复索引。', title: '三', explicit: true, now: BASE_MS + 2_000 });
751
- cortex.forget({ traceId: archived.trace.id, mode: 'archive' });
752
- assert.equal(cortex.repos.traces.count(), 3);
753
- assert.equal(cortex.repos.traces.ftsCount(), 3);
754
-
755
- cortex.db.exec('DELETE FROM traces_fts_index');
756
- cortex.db.prepare('INSERT INTO traces_fts_index(trace_id, text) VALUES (?, ?)').run('ghost-trace', '幽灵索引');
757
- assert.equal(cortex.repos.traces.ftsCount(), 1);
758
- const drifted = cortex.guardian.check();
759
- assert.equal(drifted.ok, false);
760
- const issue = drifted.issues.find((entry) => entry.code === 'FTS_DRIFT');
761
- assert.ok(issue);
762
- assert.match(issue.message, /FTS 1 \/ traces 3/);
763
- assert.equal(drifted.integrity, 'ok');
764
- assert.equal(drifted.chain.ok, true);
765
-
766
- const repaired = cortex.guardian.repairFts();
767
- assert.equal(repaired.before, 1);
768
- assert.equal(repaired.after, 3);
769
- assert.equal(repaired.reindexed, 3);
770
- assert.equal(Number(cortex.db.prepare("SELECT COUNT(*) AS c FROM traces_fts_index WHERE trace_id = 'ghost-trace'").get().c), 0);
771
- const clean = cortex.guardian.check();
772
- assert.equal(clean.ok, true);
773
- assert.deepEqual(clean.issues, []);
774
-
775
- const activeHits = cortex.search('修复', { now: BASE_MS + 3_000, limit: 10 });
776
- assert.deepEqual(idsOf(activeHits), [first.trace.id, second.trace.id].sort());
777
- const allHits = cortex.search('修复', { now: BASE_MS + 3_000, limit: 10, includeArchived: true });
778
- assert.ok(allHits.items.some((item) => item.id === archived.trace.id));
779
-
780
- const again = cortex.guardian.repairFts();
781
- assert.equal(again.before, 3);
782
- assert.equal(again.after, 3);
783
- assert.equal(again.reindexed, 3);
784
- assert.equal(cortex.guardian.check().ok, true);
785
- } finally {
786
- cleanup(context);
787
- }
788
- });
789
-
790
- // ---------------------------------------------------------------------------
791
- // 9. Duplicate operationId / duplicate content never duplicate traces
792
- // ---------------------------------------------------------------------------
793
-
794
- test('duplicate operationIds and duplicate content keep traces unique and metrics plausible', () => {
795
- const context = makeCortex();
796
- const { cortex } = context;
797
- try {
798
- const first = cortex.write({
799
- text: '重复测试:用户喜欢米饭。',
800
- title: '重复',
801
- explicit: true,
802
- operationId: 'edge:dup-1',
803
- now: BASE_MS,
804
- });
805
- assert.equal(first.skipped, false);
806
- const replay = cortex.write({
807
- text: '重复测试:用户喜欢米饭。',
808
- title: '重复',
809
- explicit: true,
810
- operationId: 'edge:dup-1',
811
- now: BASE_MS + 1_000,
812
- });
813
- assert.equal(replay.skipped, true);
814
- assert.equal(replay.reason, 'idempotent');
815
- assert.equal(replay.trace.id, first.trace.id);
816
- assert.equal(cortex.repos.traces.count(), 1);
817
- assert.equal(cortex.repos.events.count(), 1);
818
-
819
- const duplicate = cortex.write({
820
- text: '重复测试:用户喜欢米饭。',
821
- explicit: true,
822
- operationId: 'edge:dup-2',
823
- now: BASE_MS + 2_000,
824
- });
825
- assert.equal(duplicate.skipped, true);
826
- assert.equal(duplicate.reason, 'duplicate');
827
- assert.equal(duplicate.trace.id, first.trace.id);
828
- assert.equal(cortex.repos.traces.count(), 1);
829
- assert.equal(cortex.repos.events.count(), 2);
830
- const duplicateAudit = cortex.repos.audit.list({ limit: 50 }).find((entry) => entry.action === 'trace.duplicate');
831
- assert.ok(duplicateAudit);
832
- assert.equal(duplicateAudit.targetId, first.trace.id);
833
- assert.equal(duplicateAudit.detail.eventId, duplicate.event.id);
834
-
835
- const beforeConflict = { traces: cortex.repos.traces.count(), events: cortex.repos.events.count() };
836
- assert.throws(
837
- () => cortex.write({ text: '同一 operationId 的不同内容。', explicit: true, operationId: 'edge:dup-1' }),
838
- /already exists with a different payload/,
839
- );
840
- assert.deepEqual({ traces: cortex.repos.traces.count(), events: cortex.repos.events.count() }, beforeConflict);
841
-
842
- const metrics = cortex.metrics();
843
- assert.equal(metrics.counters['writes.created'], 1);
844
- assert.equal(metrics.counters['writes.skipped'], 2);
845
- assert.equal(metrics.counters['writes.created'] + metrics.counters['writes.skipped'], 3);
846
- assert.equal(metrics.histograms['write.ms'].count, 3);
847
- assert.deepEqual(cortex.repos.traces.duplicateHashes('global'), []);
848
- assert.equal(cortex.repos.events.verifyChain().ok, true);
849
-
850
- // Dedupe is scoped: identical text in a second scope is a real new trace.
851
- const scoped = cortex.write({
852
- text: '重复测试:用户喜欢米饭。',
853
- explicit: true,
854
- scopeId: 's2',
855
- now: BASE_MS + 3_000,
856
- });
857
- assert.equal(scoped.skipped, false);
858
- assert.equal(cortex.repos.traces.count(), 2);
859
- assert.equal(cortex.repos.traces.count({ scopeId: 'global' }), 1);
860
- assert.equal(cortex.repos.traces.count({ scopeId: 's2' }), 1);
861
- assert.deepEqual(cortex.repos.traces.duplicateHashes('global'), []);
862
- assert.deepEqual(cortex.repos.traces.duplicateHashes('s2'), []);
863
- assert.equal(cortex.repos.events.count(), 3);
864
- } finally {
865
- cleanup(context);
866
- }
867
- });
868
-
869
- // ---------------------------------------------------------------------------
870
- // 10. Vector failures degrade writes and searches without failing the service
871
- // ---------------------------------------------------------------------------
872
-
873
- test('vector failures never fail writes or searches and surface in the search source trace', () => {
874
- const context = makeCortex({ features: { vector: true } });
875
- const { cortex } = context;
876
- try {
877
- assert.ok(cortex.vector);
878
- const first = cortex.write({ text: '向量失败测试:用户喜欢米饭。', title: '向量一', explicit: true, now: BASE_MS });
879
- assert.equal(first.skipped, false);
880
- assert.equal(cortex.vector.status().count, 1);
881
-
882
- const originalUpsert = cortex.vector.upsert;
883
- try {
884
- cortex.vector.upsert = () => { throw new Error('embed failed'); };
885
- const second = cortex.write({ text: '向量失败测试:第二条记忆。', title: '向量二', explicit: true, now: BASE_MS + 1_000 });
886
- assert.equal(second.skipped, false);
887
- assert.ok(second.trace);
888
- assert.equal(second.trace.content, '向量失败测试:第二条记忆。');
889
- assert.equal(cortex.repos.traces.count(), 2);
890
- assert.equal(cortex.vector.status().count, 1, 'the failed upsert did not add an embedding');
891
- assert.equal(cortex.circuit.snapshot().state, 'closed');
892
- } finally {
893
- cortex.vector.upsert = originalUpsert;
894
- }
895
-
896
- const beforeSearch = cortex.search('向量失败测试', { now: BASE_MS + 2_000, limit: 5 });
897
- assert.equal(beforeSearch.items.length, 2);
898
- assert.equal(cortex.metrics().counters['search.calls'], 1);
899
-
900
- const originalSearch = cortex.vector.search;
901
- try {
902
- cortex.vector.search = () => { throw new Error('vector search failed'); };
903
- const degraded = cortex.search('向量失败测试', { now: BASE_MS + 3_000, limit: 5 });
904
- assert.ok(degraded.items.length >= 1);
905
- const vectorSource = sourceOf(degraded, 'vector');
906
- assert.ok(vectorSource);
907
- assert.equal(vectorSource.ok, false);
908
- assert.match(vectorSource.error, /vector search failed/);
909
- assert.equal(cortex.circuit.snapshot().state, 'closed', 'a vector error must not open the retrieval circuit');
910
- assert.equal(cortex.metrics().counters['search.errors'], undefined);
911
- assert.equal(cortex.metrics().counters['search.calls'], 2);
912
- assert.ok(degraded.items.some((item) => item.id === first.trace.id || item.id === cortex.repos.traces.list({ scopeId: 'global', limit: 5 })[0]?.id));
913
- } finally {
914
- cortex.vector.search = originalSearch;
915
- }
916
-
917
- const rebuilt = cortex.rebuildVector({ scopeId: 'global' });
918
- assert.equal(rebuilt.rebuilt, 2);
919
- assert.equal(cortex.vector.status().count, 2);
920
- assert.equal(cortex.settings().vector.count, 2);
921
- const healthy = cortex.search('向量失败测试', { now: BASE_MS + 4_000, limit: 5 });
922
- const healthyVector = sourceOf(healthy, 'vector');
923
- assert.equal(healthyVector.ok, true);
924
- assert.ok(healthyVector.count >= 1);
925
- assert.equal(cortex.guardian.check().ok, true);
926
- } finally {
927
- cleanup(context);
928
- }
929
- });
930
-
931
- // ---------------------------------------------------------------------------
932
- // 11. Identity versions are per-scope and do not trip the guardian invariant
933
- // ---------------------------------------------------------------------------
934
-
935
- test('identity versions are per-scope and the guardian does not false-positive IDENTITY_ACTIVE', () => {
936
- const context = makeCortex();
937
- const { cortex } = context;
938
- try {
939
- const globalActive = cortex.stores.identityStore.active('global');
940
- const s2v1 = cortex.stores.identityStore.ensure('s2');
941
- assert.equal(globalActive.scopeId, 'global');
942
- assert.equal(globalActive.status, 'active');
943
- assert.equal(s2v1.scopeId, 's2');
944
- assert.equal(s2v1.status, 'active');
945
- assert.equal(s2v1.version, 1);
946
-
947
- const clean = cortex.guardian.check();
948
- assert.equal(clean.ok, true);
949
- assert.equal(clean.issues.some((issue) => issue.code === 'IDENTITY_ACTIVE'), false);
950
-
951
- const s2v2 = cortex.stores.identityStore.propose(
952
- 's2',
953
- { narrative: 's2 的第二版身份。', values: ['独立', '诚实'] },
954
- { activate: true, rationale: 'edge-case second scope' },
955
- );
956
- assert.equal(s2v2.status, 'active');
957
- const s2History = cortex.stores.identityStore.list('s2');
958
- assert.equal(s2History.length, 2);
959
- assert.equal(s2History.filter((item) => item.status === 'active').length, 1);
960
- assert.equal(cortex.stores.identityStore.active('s2').id, s2v2.id);
961
- assert.equal(cortex.stores.identityStore.active('global').id, globalActive.id);
962
- assert.equal(cortex.self('s2').identity.id, s2v2.id);
963
- assert.equal(cortex.self('global').identity.id, globalActive.id);
964
- assert.equal(cortex.guardian.check().ok, true);
965
-
966
- // Negative control: a genuinely duplicated active row is still caught,
967
- // and the issue names the offending scope instead of blaming the global one.
968
- cortex.db.prepare(`
969
- INSERT INTO identity_versions(id, scope_id, version, content, rationale, proposed_by, approved_by, created_at, status)
970
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
971
- `).run(
972
- 'idv_edge_duplicate_active',
973
- 's2',
974
- 99,
975
- JSON.stringify({ narrative: 'forced duplicate', values: [], boundaries: [], traits: {} }),
976
- 'forced duplicate for negative control',
977
- 'test',
978
- 'test',
979
- new Date(BASE_MS).toISOString(),
980
- 'active',
981
- );
982
- const broken = cortex.guardian.check();
983
- assert.equal(broken.ok, false);
984
- const issue = broken.issues.find((entry) => entry.code === 'IDENTITY_ACTIVE');
985
- assert.ok(issue);
986
- assert.equal(issue.detail.scopeId, 's2');
987
- assert.match(issue.message, /scope s2 的 active 身份版本数 2/);
988
- cortex.db.prepare("DELETE FROM identity_versions WHERE id = 'idv_edge_duplicate_active'").run();
989
- assert.equal(cortex.guardian.check().ok, true);
990
- } finally {
991
- cleanup(context);
992
- }
993
- });
994
-
995
- // ---------------------------------------------------------------------------
996
- // 12. Retention boundaries and over-count explanations
997
- // ---------------------------------------------------------------------------
998
-
999
- test('retention excludes important, reflection, fresh and high-confidence traces and explains over-count', () => {
1000
- const context = makeCortex();
1001
- const { cortex } = context;
1002
- try {
1003
- const now = BASE_MS;
1004
- const write = (text, extra = {}) => cortex.write({
1005
- text,
1006
- explicit: true,
1007
- importance: 0.05,
1008
- now: now - 400 * DAY_MS,
1009
- ...extra,
1010
- });
1011
- const oldLow = write('保留边界:四百天前的低价值记忆。');
1012
- const boundaryImportance = write('保留边界:重要度刚好等于阈值。', { importance: 0.2 });
1013
- const boundaryConfidence = write('保留边界:置信度刚好等于阈值。');
1014
- const boundaryAge = write('保留边界:年龄刚好等于阈值。', { now: now - 365 * DAY_MS });
1015
- const highImportance = write('保留边界:重要旧记忆。', { importance: 0.9 });
1016
- const reflection = write('保留边界:旧反思。', { kind: 'reflection' });
1017
- const freshLow = write('保留边界:昨天的低价值记忆。', { now: now - DAY_MS });
1018
- const archivedLow = write('保留边界:已经归档的低价值记忆。');
1019
- const pin = (trace, importance, confidence = 0.65) => {
1020
- cortex.repos.traces.update(trace.trace.id, { importance, confidence });
1021
- };
1022
- pin(oldLow, 0.05);
1023
- pin(boundaryImportance, 0.2);
1024
- pin(boundaryConfidence, 0.05, 0.75);
1025
- pin(boundaryAge, 0.05);
1026
- pin(highImportance, 0.9);
1027
- pin(reflection, 0.05);
1028
- pin(freshLow, 0.05);
1029
- pin(archivedLow, 0.05);
1030
- cortex.forget({ traceId: archivedLow.trace.id, mode: 'archive' });
1031
-
1032
- const plan = cortex.retention.plan({ now, maxTraces: 10_000, maxAgeDays: 365, minImportance: 0.2, limit: 100 });
1033
- assert.equal(plan.scopeId, 'global');
1034
- assert.equal(plan.active, 7, 'the archived trace is not active');
1035
- assert.deepEqual(plan.candidates.map((candidate) => candidate.id), [oldLow.trace.id]);
1036
- const candidate = plan.candidates[0];
1037
- assert.equal(candidate.reason, 'over-age');
1038
- assert.ok(candidate.ageDays > 365);
1039
- assert.ok(candidate.importance < 0.2);
1040
- assert.ok(candidate.confidence < 0.75);
1041
-
1042
- const eventsBefore = cortex.repos.events.count();
1043
- const dry = cortex.retention.apply(plan, { dryRun: true });
1044
- assert.equal(dry.dryRun, true);
1045
- assert.equal(dry.archived, 1);
1046
- assert.deepEqual(dry.ids, [oldLow.trace.id]);
1047
- for (const trace of [oldLow, boundaryImportance, boundaryConfidence, boundaryAge, highImportance, reflection, freshLow]) {
1048
- assert.equal(cortex.get(trace.trace.id).state, 'active', trace.trace.content);
1049
- }
1050
- assert.equal(cortex.repos.events.count(), eventsBefore);
1051
-
1052
- const applied = cortex.retention.apply(plan);
1053
- assert.equal(applied.archived, 1);
1054
- assert.deepEqual(applied.ids, [oldLow.trace.id]);
1055
- assert.equal(cortex.get(oldLow.trace.id).state, 'archived');
1056
- assert.equal(cortex.get(oldLow.trace.id).compression, 'retention');
1057
- for (const trace of [boundaryImportance, boundaryConfidence, boundaryAge, highImportance, reflection, freshLow]) {
1058
- assert.equal(cortex.get(trace.trace.id).state, 'active', trace.trace.content);
1059
- }
1060
- assert.equal(cortex.get(archivedLow.trace.id).state, 'archived');
1061
- assert.equal(cortex.repos.traces.ftsCount(), 8);
1062
- assert.equal(cortex.repos.traces.count(), 8);
1063
- assert.equal(cortex.guardian.check().ok, true);
1064
-
1065
- const secondPlan = cortex.retention.plan({ now, maxTraces: 10_000, maxAgeDays: 365, minImportance: 0.2 });
1066
- assert.equal(secondPlan.active, 6);
1067
- assert.deepEqual(secondPlan.candidates, []);
1068
-
1069
- // Over-count is a separate explicit branch: force it with maxTraces: 0,
1070
- // keep the age threshold loose, and check the reason is explainable.
1071
- pin(freshLow, 0.9);
1072
- const overCount = cortex.retention.plan({ now, maxTraces: 0, maxAgeDays: 3_650, minImportance: 0.2, limit: 100 });
1073
- assert.equal(overCount.active, 6);
1074
- assert.deepEqual(overCount.candidates.map((item) => item.id), [boundaryAge.trace.id]);
1075
- assert.equal(overCount.candidates[0].reason, 'over-count');
1076
- assert.ok(overCount.candidates[0].ageDays <= 3_650);
1077
- const overDry = cortex.retention.apply(overCount, { dryRun: true });
1078
- assert.equal(overDry.archived, 1);
1079
- assert.deepEqual(overDry.ids, [boundaryAge.trace.id]);
1080
- assert.equal(cortex.get(boundaryAge.trace.id).state, 'active');
1081
- const overApplied = cortex.retention.apply(overCount);
1082
- assert.equal(overApplied.archived, 1);
1083
- assert.equal(cortex.get(boundaryAge.trace.id).state, 'archived');
1084
- assert.equal(cortex.get(boundaryAge.trace.id).compression, 'retention');
1085
- assert.equal(cortex.guardian.check().ok, true);
1086
- } finally {
1087
- cleanup(context);
1088
- }
1089
- });