dsh-cortex-memory 0.4.11 → 0.4.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +1 -1
  3. package/README.md +63 -38
  4. package/bench/ab-engine.mjs +60 -0
  5. package/bench/ann-bench.mjs +78 -0
  6. package/bench/hnsw-bench.mjs +79 -0
  7. package/bench/locomo.js +89 -0
  8. package/bench/longmemeval.js +83 -0
  9. package/bench/metrics.js +67 -0
  10. package/bench/migration-bench.mjs +69 -0
  11. package/bench/run.js +77 -0
  12. package/bench/synthetic.js +99 -0
  13. package/bench/vector-ab.mjs +76 -0
  14. package/docs/compatibility.md +39 -0
  15. package/docs/install-windows.md +145 -0
  16. package/docs/models.md +183 -0
  17. package/docs/multimodal.md +112 -0
  18. package/docs/permissions.md +53 -0
  19. package/docs/privacy.md +50 -0
  20. package/docs/scopes.md +142 -0
  21. package/examples/README.md +73 -0
  22. package/examples/setup-cortex-bge.ps1 +66 -0
  23. package/examples/uninstall-cortex.ps1 +92 -0
  24. package/index.js +23 -0
  25. package/package.json +11 -5
  26. package/src/core/config.js +27 -0
  27. package/src/engines/extract.js +10 -10
  28. package/src/engines/retrieve.js +30 -5
  29. package/src/guardian/guardian.js +2 -15
  30. package/src/guardian/invariants.js +9 -5
  31. package/src/host/runtime.js +10 -14
  32. package/src/self/evolution.js +32 -5
  33. package/src/self/policies.js +21 -2
  34. package/src/service/cortex.js +3 -2
  35. package/src/store/database.js +9 -1
  36. package/src/store/schema.sql +2 -1
  37. package/src/vector/hnsw.js +5 -5
  38. package/test/integration/_helpers.js +128 -0
  39. package/test/integration/acceptance.test.js +803 -0
  40. package/test/integration/ann-load.test.js +61 -0
  41. package/test/integration/api-contract.test.js +1476 -0
  42. package/test/integration/backup-privacy.test.js +214 -0
  43. package/test/integration/consolidate.test.js +75 -0
  44. package/test/integration/edge-cases.test.js +1088 -0
  45. package/test/integration/exchange.test.js +326 -0
  46. package/test/integration/life-loop.test.js +188 -0
  47. package/test/integration/load.test.js +751 -0
  48. package/test/integration/markdown-sync.test.js +35 -0
  49. package/test/integration/policy-query-api.test.js +306 -0
  50. package/test/integration/resilience-writes.test.js +241 -0
  51. package/test/integration/tools-contract.test.js +1324 -0
  52. package/test/unit/ann-edge.test.js +102 -0
  53. package/test/unit/ann.test.js +77 -0
  54. package/test/unit/api-client.test.js +576 -0
  55. package/test/unit/api-validate.test.js +19 -0
  56. package/test/unit/api.test.js +555 -0
  57. package/test/unit/appraisal.test.js +48 -0
  58. package/test/unit/attachments.test.js +33 -0
  59. package/test/unit/autonomy.test.js +53 -0
  60. package/test/unit/batch.test.js +46 -0
  61. package/test/unit/bench.test.js +40 -0
  62. package/test/unit/benchmark-synthetic.test.js +52 -0
  63. package/test/unit/client-contract.test.js +29 -0
  64. package/test/unit/compression.test.js +76 -0
  65. package/test/unit/core.test.js +77 -0
  66. package/test/unit/develop.test.js +130 -0
  67. package/test/unit/development.test.js +68 -0
  68. package/test/unit/digest.test.js +26 -0
  69. package/test/unit/dsr.test.js +111 -0
  70. package/test/unit/edges-candidates.test.js +113 -0
  71. package/test/unit/emotion.test.js +61 -0
  72. package/test/unit/encode.test.js +98 -0
  73. package/test/unit/evolution.test.js +130 -0
  74. package/test/unit/external-ann-search.test.js +50 -0
  75. package/test/unit/external-ann.test.js +29 -0
  76. package/test/unit/facts-belief.test.js +32 -0
  77. package/test/unit/facts.test.js +107 -0
  78. package/test/unit/feature-overrides.test.js +42 -0
  79. package/test/unit/fts-migration.test.js +42 -0
  80. package/test/unit/graph.test.js +79 -0
  81. package/test/unit/growth-reflect.test.js +123 -0
  82. package/test/unit/guard-runtime.test.js +40 -0
  83. package/test/unit/guardian.test.js +91 -0
  84. package/test/unit/health-privacy.test.js +102 -0
  85. package/test/unit/hnsw.test.js +35 -0
  86. package/test/unit/host-runtime.test.js +142 -0
  87. package/test/unit/host.test.js +58 -0
  88. package/test/unit/identity.test.js +98 -0
  89. package/test/unit/induct-evaluate.test.js +41 -0
  90. package/test/unit/ingest-extracted.test.js +35 -0
  91. package/test/unit/initiative.test.js +90 -0
  92. package/test/unit/jobs.test.js +93 -0
  93. package/test/unit/json-snapshot.test.js +57 -0
  94. package/test/unit/life-consolidate.test.js +34 -0
  95. package/test/unit/life.test.js +149 -0
  96. package/test/unit/llm-facts-integration.test.js +27 -0
  97. package/test/unit/llm-facts.test.js +16 -0
  98. package/test/unit/llm.test.js +45 -0
  99. package/test/unit/locomo.test.js +45 -0
  100. package/test/unit/longmemeval.test.js +56 -0
  101. package/test/unit/markdown-import.test.js +44 -0
  102. package/test/unit/markdown.test.js +34 -0
  103. package/test/unit/memory-edit.test.js +112 -0
  104. package/test/unit/metrics.test.js +26 -0
  105. package/test/unit/migration.test.js +38 -0
  106. package/test/unit/model-config.test.js +52 -0
  107. package/test/unit/narrative.test.js +62 -0
  108. package/test/unit/playbook-consolidate.test.js +24 -0
  109. package/test/unit/privacy-scope.test.js +39 -0
  110. package/test/unit/profile.test.js +20 -0
  111. package/test/unit/prompt.test.js +42 -0
  112. package/test/unit/providers.test.js +42 -0
  113. package/test/unit/qa.test.js +100 -0
  114. package/test/unit/query.test.js +53 -0
  115. package/test/unit/retention.test.js +31 -0
  116. package/test/unit/retrieval-ranking.test.js +31 -0
  117. package/test/unit/retrieve.test.js +117 -0
  118. package/test/unit/rotation.test.js +25 -0
  119. package/test/unit/scanner.test.js +50 -0
  120. package/test/unit/scenario.test.js +78 -0
  121. package/test/unit/scheduler.test.js +136 -0
  122. package/test/unit/self-state.test.js +94 -0
  123. package/test/unit/service.test.js +72 -0
  124. package/test/unit/shiori-import.test.js +77 -0
  125. package/test/unit/skills.test.js +104 -0
  126. package/test/unit/store.test.js +111 -0
  127. package/test/unit/temporal-graph.test.js +44 -0
  128. package/test/unit/tiers.test.js +39 -0
  129. package/test/unit/tokenizer-fts.test.js +35 -0
  130. package/test/unit/tools.test.js +122 -0
  131. package/test/unit/upgrade-0412.test.js +104 -0
  132. package/test/unit/upgrade-0413.test.js +84 -0
  133. package/test/unit/upgrade-0414.test.js +101 -0
  134. package/test/unit/vector-ann.test.js +53 -0
  135. package/test/unit/vector-async.test.js +69 -0
  136. package/test/unit/vector.test.js +68 -0
  137. package/test/unit/working.test.js +80 -0
@@ -0,0 +1,1476 @@
1
+ /**
2
+ * HTTP contract coverage for the dsh-cortex loopback API.
3
+ *
4
+ * This suite drives the real `createApiHandler` from `src/api/routes.js` with a
5
+ * fake node:http request/response pair and a real cortex on a throwaway
6
+ * database. It is deliberately black-box: nothing in `src/` is imported except
7
+ * the handler factory and the route base constant, and nothing is mocked.
8
+ *
9
+ * Coverage is organised in four layers:
10
+ * 1. every GET route in the handler, with envelope/shape assertions;
11
+ * 2. every POST route, including validation and state-changing flows;
12
+ * 3. security invariants (origin, peer, token, body parsing, methods);
13
+ * 4. scope precedence and isolation (header > query > body).
14
+ *
15
+ * The tests assert stable structure, never volatile values such as ids,
16
+ * timestamps, scores or row counts that depend on wall-clock behaviour.
17
+ */
18
+ import test from 'node:test';
19
+ import assert from 'node:assert/strict';
20
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
21
+ import path from 'node:path';
22
+ import { Readable } from 'node:stream';
23
+ import { API_BASE, createApiHandler } from '../../src/api/routes.js';
24
+ import {
25
+ apiResponse,
26
+ cleanup,
27
+ invokeApi,
28
+ makeCortex,
29
+ } from './_helpers.js';
30
+
31
+ const DAY_MS = 86_400_000;
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Local fake-HTTP helpers
35
+ // ---------------------------------------------------------------------------
36
+
37
+ function hasOwn(value, key) {
38
+ return Object.prototype.hasOwnProperty.call(value, key);
39
+ }
40
+
41
+ /** Request stream for bodies that cannot be produced by JSON.stringify. */
42
+ function rawApiRequest({ method = 'POST', route = '/write', raw = '', headers = {} } = {}) {
43
+ const stream = Readable.from([Buffer.from(raw, 'utf8')]);
44
+ stream.method = method;
45
+ stream.url = `${API_BASE}${route}`;
46
+ const merged = {
47
+ host: '127.0.0.1:7430',
48
+ origin: 'http://127.0.0.1:7430',
49
+ 'sec-fetch-site': 'same-origin',
50
+ 'content-type': 'application/json',
51
+ 'x-cortex': '1',
52
+ ...headers,
53
+ };
54
+ for (const [key, value] of Object.entries(merged)) {
55
+ if (value === undefined) delete merged[key];
56
+ }
57
+ stream.headers = merged;
58
+ stream.socket = { remoteAddress: '127.0.0.1' };
59
+ return stream;
60
+ }
61
+
62
+ async function invokeRaw(handler, options = {}) {
63
+ const response = apiResponse();
64
+ await handler(rawApiRequest(options), response);
65
+ return {
66
+ status: response.statusCode,
67
+ headers: response.headers,
68
+ json: response.body ? JSON.parse(response.body) : {},
69
+ };
70
+ }
71
+
72
+ function post(handler, route, body = {}, headers = {}) {
73
+ return invokeApi(handler, {
74
+ method: 'POST',
75
+ route,
76
+ body,
77
+ headers: { 'x-cortex': '1', ...headers },
78
+ });
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Envelope assertions
83
+ // ---------------------------------------------------------------------------
84
+
85
+ function assertIso(value, label) {
86
+ assert.equal(typeof value, 'string', `${label} should be a string`);
87
+ assert.ok(Number.isFinite(Date.parse(value)), `${label} should be an ISO timestamp, got ${value}`);
88
+ }
89
+
90
+ /** Assert the documented `{ ok: true, data: ... }` envelope and return data. */
91
+ function expectData(result, label) {
92
+ assert.equal(
93
+ result.status,
94
+ 200,
95
+ `${label}: expected 200, got ${result.status} ${JSON.stringify(result.json)}`,
96
+ );
97
+ assert.equal(result.json.ok, true, `${label}: expected ok:true`);
98
+ assert.ok(hasOwn(result.json, 'data'), `${label}: expected a data member`);
99
+ assert.equal(hasOwn(result.json, 'error'), false, `${label}: a success envelope must not carry error`);
100
+ return result.json.data;
101
+ }
102
+
103
+ /** Assert the documented `{ ok: false, error: string }` failure envelope. */
104
+ function expectError(result, { label = 'request', status = 400, match = null } = {}) {
105
+ assert.equal(
106
+ result.status,
107
+ status,
108
+ `${label}: expected ${status}, got ${result.status} ${JSON.stringify(result.json)}`,
109
+ );
110
+ assert.equal(result.json.ok, false, `${label}: expected ok:false`);
111
+ assert.equal(typeof result.json.error, 'string', `${label}: expected an error string`);
112
+ assert.equal(hasOwn(result.json, 'data'), false, `${label}: a failure envelope must not carry data`);
113
+ if (match) assert.match(result.json.error, match, `${label}: error should mention ${match}`);
114
+ }
115
+
116
+ function assertInteger(value, label, { min = Number.MIN_SAFE_INTEGER } = {}) {
117
+ assert.ok(Number.isInteger(value), `${label} should be an integer, got ${typeof value} ${value}`);
118
+ assert.ok(value >= min, `${label} should be >= ${min}, got ${value}`);
119
+ }
120
+
121
+ function writeTrace(cortex, text, extra = {}) {
122
+ return cortex.write({ text, explicit: true, ...extra });
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // 1. GET routes
127
+ // ---------------------------------------------------------------------------
128
+
129
+ test('GET contract: every read route returns the documented status and envelope', async (t) => {
130
+ const context = makeCortex();
131
+ const { cortex } = context;
132
+ try {
133
+ const handler = createApiHandler({ cortex });
134
+
135
+ const firstTrace = writeTrace(cortex, '用户喜欢白饭,助手记着。', {
136
+ title: '白饭',
137
+ tags: ['约定'],
138
+ importance: 0.8,
139
+ });
140
+ writeTrace(cortex, '助手昨天修了记忆插件。', {
141
+ title: '插件',
142
+ tags: ['技术'],
143
+ importance: 0.4,
144
+ });
145
+ const focus = cortex.working.add({ text: '写 API 契约测试', priority: 0.9, pinned: true });
146
+ const activeGoal = cortex.goals.add({ title: '完成 API 契约测试', priority: 0.9 });
147
+ const doneGoal = cortex.goals.add({ title: '旧的完成项', priority: 0.3 });
148
+ cortex.goals.complete(doneGoal.id);
149
+ cortex.emotion.record({ text: '助手很喜欢用户,也很心疼用户。', target: '用户' });
150
+ cortex.life.diaryWrite({ text: '今天补契约测试。', mood: '踏实' });
151
+ await cortex.life.dreamGenerate();
152
+ await cortex.life.sleep({ windowDays: 1 });
153
+
154
+ const traceId = firstTrace.trace.id;
155
+ const traceDate = firstTrace.trace.recordedAt.slice(0, 10);
156
+
157
+ const routes = [
158
+ ['/ping', (result) => {
159
+ assert.equal(result.status, 200);
160
+ assert.equal(result.json.ok, true);
161
+ assert.equal(hasOwn(result.json, 'data'), false, 'ping has no data member');
162
+ assertIso(result.json.at, 'ping.at');
163
+ assert.match(result.headers['content-type'], /application\/json/);
164
+ assert.equal(result.headers['cache-control'], 'no-store');
165
+ }],
166
+ ['/health', (result) => {
167
+ const data = expectData(result, '/health');
168
+ assert.equal(data.scopeId, 'global');
169
+ assert.equal(typeof data.score, 'number');
170
+ assert.ok(data.score >= 0 && data.score <= 100);
171
+ assert.ok(Array.isArray(data.issues));
172
+ assert.ok(Array.isArray(data.ok));
173
+ assert.equal(typeof data.counts, 'object');
174
+ assertIso(data.at, 'health.at');
175
+ }],
176
+ ['/self', (result) => {
177
+ const data = expectData(result, '/self');
178
+ assert.equal(typeof data.self, 'object');
179
+ assert.equal(data.self.scopeId, 'global');
180
+ assert.equal(typeof data.self.stage, 'string');
181
+ assert.equal(typeof data.identity, 'object');
182
+ assert.ok(Array.isArray(data.relationships));
183
+ assert.ok(Array.isArray(data.intentions));
184
+ assert.ok(Array.isArray(data.working));
185
+ assert.ok(Array.isArray(data.goals));
186
+ assert.equal(typeof data.emotion, 'string');
187
+ assert.equal(typeof data.calibration, 'object');
188
+ }],
189
+ ['/stats', (result) => {
190
+ const data = expectData(result, '/stats');
191
+ assert.equal(data.config.scope, 'global');
192
+ assert.equal(data.config.dbFile, cortex.config.dbFile);
193
+ assert.ok(data.vector === null || typeof data.vector === 'object');
194
+ }],
195
+ ['/settings', (result) => {
196
+ const data = expectData(result, '/settings');
197
+ assert.equal(data.scope, 'global');
198
+ assert.equal(data.dataRoot, cortex.config.dataRoot);
199
+ assert.equal(data.dbFile, cortex.config.dbFile);
200
+ assert.equal(typeof data.contextBudget, 'number');
201
+ assert.equal(typeof data.features, 'object');
202
+ assert.equal(data.features.vector, false);
203
+ assert.ok(data.vector === null || typeof data.vector === 'object');
204
+ }],
205
+ ['/metrics', (result) => {
206
+ const data = expectData(result, '/metrics');
207
+ assert.equal(typeof data.at, 'string');
208
+ assert.equal(typeof data.counters, 'object');
209
+ assert.equal(typeof data.histograms, 'object');
210
+ assert.ok(Number.isInteger(data.counters['writes.created']));
211
+ assert.ok(data.counters['writes.created'] >= 2);
212
+ assert.equal(typeof data.histograms['write.ms'], 'object');
213
+ }],
214
+ ['/graph', (result) => {
215
+ const data = expectData(result, '/graph');
216
+ for (const key of ['nodes', 'edges', 'components', 'communities']) {
217
+ assertInteger(data[key], `graph.${key}`, { min: 0 });
218
+ }
219
+ assert.ok(Array.isArray(data.top));
220
+ }],
221
+ ['/graph/edges', (result) => {
222
+ const data = expectData(result, '/graph/edges');
223
+ assert.ok(Array.isArray(data.nodes));
224
+ assert.ok(Array.isArray(data.edges));
225
+ assert.equal(typeof data.summary, 'object');
226
+ for (const key of ['nodes', 'edges', 'components', 'communities']) {
227
+ assertInteger(data.summary[key], `graph.edges.summary.${key}`, { min: 0 });
228
+ }
229
+ assert.ok(Array.isArray(data.summary.top));
230
+ }],
231
+ ['/retention', (result) => {
232
+ const data = expectData(result, '/retention');
233
+ assert.equal(data.scopeId, 'global');
234
+ assertInteger(data.active, 'retention.active', { min: 0 });
235
+ assert.ok(Array.isArray(data.candidates));
236
+ assertInteger(data.count, 'retention.count', { min: 0 });
237
+ assert.equal(data.count, data.candidates.length);
238
+ assertIso(data.at, 'retention.at');
239
+ }],
240
+ [`/digest?date=${traceDate}`, (result) => {
241
+ const data = expectData(result, '/digest');
242
+ assert.equal(data.date, traceDate);
243
+ assert.equal(typeof data.content, 'string');
244
+ assert.match(data.content, /记忆摘要/);
245
+ assert.equal(typeof data.counts, 'object');
246
+ assertInteger(data.counts.traces, 'digest.counts.traces', { min: 2 });
247
+ assert.equal(typeof data.byKind, 'object');
248
+ assert.ok(Array.isArray(data.important));
249
+ assert.ok(data.summary === null || typeof data.summary === 'object');
250
+ assertIso(data.at, 'digest.at');
251
+ }],
252
+ ['/digest?date=1900-01-02', (result) => {
253
+ const data = expectData(result, '/digest empty day');
254
+ assert.equal(data.date, '1900-01-02');
255
+ assert.equal(data.counts.traces, 0);
256
+ assert.deepEqual(data.important, []);
257
+ assert.match(data.content, /1900-01-02/);
258
+ }],
259
+ ['/audit', (result) => {
260
+ const data = expectData(result, '/audit');
261
+ assert.ok(Array.isArray(data));
262
+ assert.ok(data.length >= 1);
263
+ for (const row of data) {
264
+ assert.equal(typeof row.id, 'string');
265
+ assert.equal(typeof row.action, 'string');
266
+ assert.equal(typeof row.detail, 'object');
267
+ assertIso(row.at, 'audit.at');
268
+ }
269
+ }],
270
+ ['/audit?limit=0', (result) => {
271
+ const data = expectData(result, '/audit limit clamp');
272
+ assert.ok(Array.isArray(data));
273
+ assert.equal(data.length, 1, 'limit 0 is clamped up to 1');
274
+ }],
275
+ ['/working', (result) => {
276
+ const data = expectData(result, '/working');
277
+ assert.ok(Array.isArray(data));
278
+ assert.ok(data.some((item) => item.id === focus.id));
279
+ const item = data.find((entry) => entry.id === focus.id);
280
+ assert.equal(item.text, '写 API 契约测试');
281
+ assert.equal(item.scopeId, 'global');
282
+ assert.equal(item.pinned, true);
283
+ assert.equal(typeof item.priority, 'number');
284
+ }],
285
+ ['/goals', (result) => {
286
+ const data = expectData(result, '/goals');
287
+ assert.ok(Array.isArray(data));
288
+ assert.ok(data.some((goal) => goal.id === activeGoal.id));
289
+ assert.ok(data.some((goal) => goal.id === doneGoal.id));
290
+ }],
291
+ ['/goals?status=active', (result) => {
292
+ const data = expectData(result, '/goals active');
293
+ assert.ok(data.every((goal) => goal.status === 'active'));
294
+ assert.ok(data.some((goal) => goal.id === activeGoal.id));
295
+ assert.equal(data.some((goal) => goal.id === doneGoal.id), false);
296
+ }],
297
+ ['/goals?status=completed', (result) => {
298
+ const data = expectData(result, '/goals completed');
299
+ assert.ok(data.every((goal) => goal.status === 'completed'));
300
+ assert.ok(data.some((goal) => goal.id === doneGoal.id));
301
+ }],
302
+ ['/emotion', (result) => {
303
+ const data = expectData(result, '/emotion');
304
+ assert.equal(typeof data.text, 'string');
305
+ assert.ok(Array.isArray(data.targets));
306
+ assert.ok(Array.isArray(data.events));
307
+ assert.ok(data.targets.some((target) => target.target === '用户'));
308
+ assert.ok(data.events.length >= 1);
309
+ assert.equal(typeof data.events[0].emotions, 'object');
310
+ assert.ok(Array.isArray(data.events[0].emotions));
311
+ }],
312
+ ['/life', (result) => {
313
+ const data = expectData(result, '/life');
314
+ assert.ok(Array.isArray(data.diary));
315
+ assert.ok(Array.isArray(data.dreams));
316
+ assert.ok(Array.isArray(data.sleeps));
317
+ assert.ok(data.diary.length >= 1);
318
+ assert.ok(data.dreams.length >= 1);
319
+ assert.ok(data.sleeps.length >= 1);
320
+ assert.equal(typeof data.diary[0].text, 'string');
321
+ assert.equal(typeof data.dreams[0].text, 'string');
322
+ assert.equal(typeof data.sleeps[0].report, 'object');
323
+ }],
324
+ ['/skills', (result) => {
325
+ const data = expectData(result, '/skills');
326
+ assert.ok(Array.isArray(data));
327
+ }],
328
+ ['/guard', (result) => {
329
+ const data = expectData(result, '/guard');
330
+ assert.equal(typeof data.ok, 'boolean');
331
+ assert.ok(Array.isArray(data.issues));
332
+ assert.equal(data.integrity, 'ok');
333
+ assert.equal(typeof data.chain, 'object');
334
+ assert.equal(data.chain.ok, true);
335
+ assertInteger(data.chain.count, 'guard.chain.count', { min: 1 });
336
+ assertIso(data.at, 'guard.at');
337
+ assertInteger(data.dbBytes, 'guard.dbBytes', { min: 1 });
338
+ }],
339
+ ['/evolution', (result) => {
340
+ const data = expectData(result, '/evolution');
341
+ assert.equal(typeof data.active, 'object');
342
+ for (const kind of ['retrieval', 'maintenance', 'repair', 'skill']) {
343
+ assert.ok(hasOwn(data.active, kind), `evolution.active.${kind}`);
344
+ }
345
+ assert.ok(Array.isArray(data.candidates));
346
+ assert.equal(typeof data.identity, 'object');
347
+ assert.equal(data.identity.scopeId, 'global');
348
+ }],
349
+ [`/search?q=${encodeURIComponent('白饭')}`, (result) => {
350
+ const data = expectData(result, '/search');
351
+ assert.equal(data.query, '白饭');
352
+ assert.equal(data.scopeId, 'global');
353
+ assert.ok(Array.isArray(data.items));
354
+ assert.ok(data.items.some((item) => item.id === traceId));
355
+ assert.equal(typeof data.budget, 'object');
356
+ assert.equal(typeof data.budget.used, 'number');
357
+ assert.equal(typeof data.budget.total, 'number');
358
+ assert.equal(typeof data.trace, 'object');
359
+ assert.ok(Array.isArray(data.trace.sources));
360
+ assertIso(data.at, 'search.at');
361
+ }],
362
+ ['/search', (result) => {
363
+ const data = expectData(result, '/search empty query');
364
+ assert.equal(data.query, '');
365
+ assert.ok(Array.isArray(data.items));
366
+ }],
367
+ ['/search?limit=999&budget=1', (result) => {
368
+ const data = expectData(result, '/search clamps');
369
+ assert.equal(data.budget.total, 200, 'GET budget is clamped up to 200');
370
+ assert.ok(data.items.length <= 20, 'GET limit is clamped down to 20');
371
+ }],
372
+ [`/trace?id=${traceId}`, (result) => {
373
+ const data = expectData(result, '/trace');
374
+ assert.equal(data.id, traceId);
375
+ assert.equal(data.scopeId, 'global');
376
+ assert.equal(data.content, '用户喜欢白饭,助手记着。');
377
+ assertIso(data.recordedAt, 'trace.recordedAt');
378
+ }],
379
+ [`/timeline?id=${traceId}`, (result) => {
380
+ const data = expectData(result, '/timeline');
381
+ assert.equal(typeof data.anchor, 'object');
382
+ assert.equal(data.anchor.id, traceId);
383
+ assert.ok(Array.isArray(data.items));
384
+ assert.ok(data.items.some((item) => item.isAnchor === true && item.id === traceId));
385
+ assertIso(data.at, 'timeline.at');
386
+ }],
387
+ ['/timeline', (result) => {
388
+ const data = expectData(result, '/timeline without id');
389
+ assert.equal(data.anchor, null);
390
+ assert.deepEqual(data.items, []);
391
+ }],
392
+ ['/timeline?id=trc_does_not_exist', (result) => {
393
+ const data = expectData(result, '/timeline unknown id');
394
+ assert.equal(data.anchor, null);
395
+ assert.deepEqual(data.items, []);
396
+ }],
397
+ ['/trace', (result) => {
398
+ expectError(result, { status: 404, label: '/trace without id', match: /not found/ });
399
+ }],
400
+ ['/trace?id=trc_does_not_exist', (result) => {
401
+ expectError(result, { status: 404, label: '/trace unknown id', match: /not found/ });
402
+ }],
403
+ ];
404
+
405
+ for (const [route, check] of routes) {
406
+ await t.test(route, async () => {
407
+ const result = await invokeApi(handler, { route });
408
+ check(result);
409
+ });
410
+ }
411
+ } finally {
412
+ cleanup(context);
413
+ }
414
+ });
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // 2. POST: memory write/search/feedback/forget
418
+ // ---------------------------------------------------------------------------
419
+
420
+ test('POST /write accepts one memory, deduplicates, and writes batches atomically', async () => {
421
+ const context = makeCortex();
422
+ const { cortex } = context;
423
+ try {
424
+ const handler = createApiHandler({ cortex });
425
+ const bad = await post(handler, '/write', { text: ' ' });
426
+ expectError(bad, { label: 'write blank', match: /text/ });
427
+
428
+ const single = await post(handler, '/write', {
429
+ text: '用户喜欢白饭。',
430
+ title: '白饭',
431
+ tags: ['约定', '日常'],
432
+ importance: 0.9,
433
+ explicit: true,
434
+ operationId: 'contract:write:1',
435
+ });
436
+ const written = expectData(single, 'write single');
437
+ assert.equal(written.skipped, false);
438
+ assert.equal(written.trace.content, '用户喜欢白饭。');
439
+ assert.equal(written.trace.title, '白饭');
440
+ assert.equal(written.trace.scopeId, 'global');
441
+ assert.deepEqual(written.trace.tags, ['约定', '日常']);
442
+ assert.equal(typeof written.trace.id, 'string');
443
+ assert.equal(typeof written.event, 'object');
444
+ assert.equal(typeof written.event.id, 'string');
445
+ assertIso(written.trace.recordedAt, 'write.trace.recordedAt');
446
+
447
+ const duplicate = await post(handler, '/write', { text: '用户喜欢白饭。', explicit: true });
448
+ const deduped = expectData(duplicate, 'write duplicate');
449
+ assert.equal(deduped.skipped, true);
450
+ assert.equal(deduped.reason, 'duplicate');
451
+ assert.equal(deduped.trace.id, written.trace.id);
452
+
453
+ const batch = await post(handler, '/write', {
454
+ items: [
455
+ { text: '批量第一条。', title: '一', explicit: true },
456
+ { text: '批量第二条。', title: '二', explicit: true },
457
+ ],
458
+ });
459
+ const batchData = expectData(batch, 'write batch');
460
+ assert.ok(Array.isArray(batchData));
461
+ assert.equal(batchData.length, 2);
462
+ assert.equal(batchData[0].trace.content, '批量第一条。');
463
+ assert.equal(batchData[1].trace.content, '批量第二条。');
464
+ assert.equal(batchData.every((entry) => entry.skipped === false), true);
465
+
466
+ const before = cortex.repos.traces.count();
467
+ const invalidBatch = await post(handler, '/write', {
468
+ items: [{ text: '合法项。', explicit: true }, { text: ' ' }],
469
+ });
470
+ expectError(invalidBatch, { label: 'write invalid batch', match: /text/ });
471
+ assert.equal(cortex.repos.traces.count(), before, 'validation happens before any batch write');
472
+
473
+ const emptyBatch = await post(handler, '/write', { items: [] });
474
+ const emptyData = expectData(emptyBatch, 'empty batch');
475
+ assert.deepEqual(emptyData, []);
476
+ } finally {
477
+ cleanup(context);
478
+ }
479
+ });
480
+
481
+ test('POST /search validates its body and returns the retrieval envelope', async () => {
482
+ const context = makeCortex();
483
+ const { cortex } = context;
484
+ try {
485
+ const handler = createApiHandler({ cortex });
486
+ const written = writeTrace(cortex, '用户喜欢白饭,助手记着。', { title: '白饭' });
487
+
488
+ const found = await post(handler, '/search', { query: '白饭', limit: 5, budget: 500 });
489
+ const data = expectData(found, 'search post');
490
+ assert.equal(data.query, '白饭');
491
+ assert.equal(data.scopeId, 'global');
492
+ assert.ok(Array.isArray(data.items));
493
+ assert.ok(data.items.some((item) => item.id === written.trace.id));
494
+ assert.equal(typeof data.intent, 'string');
495
+ assert.equal(typeof data.trace, 'object');
496
+ assert.ok(Array.isArray(data.trace.sources));
497
+ assertIso(data.at, 'search.at');
498
+
499
+ const wide = await post(handler, '/search', { query: '白饭', limit: 20, budget: 64 });
500
+ expectData(wide, 'search lower budget');
501
+
502
+ const invalid = [
503
+ [{}, /query/],
504
+ [{ query: '' }, /query/],
505
+ [{ query: ' ' }, /query/],
506
+ [{ query: 'x', limit: 0 }, /limit/],
507
+ [{ query: 'x', limit: 21 }, /limit/],
508
+ [{ query: 'x', budget: 63 }, /budget/],
509
+ [{ query: 'x', budget: 20001 }, /budget/],
510
+ ];
511
+ for (const [body, match] of invalid) {
512
+ const result = await post(handler, '/search', body);
513
+ expectError(result, { label: `search ${JSON.stringify(body)}`, match });
514
+ }
515
+ } finally {
516
+ cleanup(context);
517
+ }
518
+ });
519
+
520
+ test('POST /feedback and POST /forget update or remove traces with documented shapes', async () => {
521
+ const context = makeCortex();
522
+ const { cortex } = context;
523
+ try {
524
+ const handler = createApiHandler({ cortex });
525
+ const active = writeTrace(cortex, '反馈测试用的记忆。', { title: '反馈' });
526
+ const forgotten = writeTrace(cortex, '删除测试用的记忆。', { title: '删除' });
527
+
528
+ const feedback = await post(handler, '/feedback', {
529
+ id: active.trace.id,
530
+ signal: 'used',
531
+ predicted: 0.8,
532
+ outcome: 1,
533
+ });
534
+ const feedbackData = expectData(feedback, 'feedback');
535
+ assert.equal(feedbackData.trace.id, active.trace.id);
536
+ assert.equal(typeof feedbackData.feedback, 'object');
537
+ assert.equal(feedbackData.feedback.signal, 'used');
538
+ assertIso(feedbackData.feedback.at, 'feedback.at');
539
+
540
+ expectError(await post(handler, '/feedback', { signal: 'used' }), {
541
+ label: 'feedback missing id',
542
+ match: /id/,
543
+ });
544
+ expectError(await post(handler, '/feedback', { id: active.trace.id }), {
545
+ label: 'feedback missing signal',
546
+ match: /signal/,
547
+ });
548
+
549
+ const archived = await post(handler, '/forget', { id: active.trace.id, mode: 'archive' });
550
+ const archivedData = expectData(archived, 'forget archive');
551
+ assert.equal(archivedData.removed, true);
552
+ assert.equal(archivedData.trace.state, 'archived');
553
+ const rawArchived = expectData(await invokeApi(handler, { route: `/trace?id=${active.trace.id}` }), 'trace archived');
554
+ assert.equal(rawArchived.state, 'archived');
555
+
556
+ const deleted = await post(handler, '/forget', { id: forgotten.trace.id, mode: 'delete' });
557
+ const deletedData = expectData(deleted, 'forget delete');
558
+ assert.equal(deletedData.removed, true);
559
+ assert.equal(deletedData.eventRetained, true);
560
+ expectError(await invokeApi(handler, { route: `/trace?id=${forgotten.trace.id}` }), {
561
+ status: 404,
562
+ label: 'trace after delete',
563
+ });
564
+
565
+ expectError(await post(handler, '/forget', { id: active.trace.id, mode: 'purge' }), {
566
+ label: 'forget bad mode',
567
+ match: /mode/,
568
+ });
569
+ expectError(await post(handler, '/forget', { mode: 'archive' }), {
570
+ label: 'forget missing id',
571
+ match: /id/,
572
+ });
573
+ } finally {
574
+ cleanup(context);
575
+ }
576
+ });
577
+
578
+ // ---------------------------------------------------------------------------
579
+ // 3. POST: reflection, compression, QA, autonomy, retention
580
+ // ---------------------------------------------------------------------------
581
+
582
+ test('POST /reflect creates a summary, then reports already-reflected and honours force', async () => {
583
+ const context = makeCortex();
584
+ const { cortex } = context;
585
+ try {
586
+ const handler = createApiHandler({ cortex });
587
+ writeTrace(cortex, '第一条用于反思的记忆。', { title: '一' });
588
+ writeTrace(cortex, '第二条用于反思的记忆。', { title: '二' });
589
+
590
+ const first = await post(handler, '/reflect', {});
591
+ const firstData = expectData(first, 'reflect first');
592
+ assert.equal(firstData.skipped, false);
593
+ assert.equal(typeof firstData.summary, 'object');
594
+ assert.equal(typeof firstData.summary.content, 'string');
595
+ assert.ok(Array.isArray(firstData.summary.sourceIds));
596
+ assert.equal(typeof firstData.trace, 'object');
597
+ assert.equal(firstData.trace.kind, 'reflection');
598
+ assert.equal(typeof firstData.coverage, 'number');
599
+ assert.ok(Array.isArray(firstData.sources));
600
+ assertIso(firstData.at, 'reflect.at');
601
+
602
+ const second = await post(handler, '/reflect', {});
603
+ const secondData = expectData(second, 'reflect second');
604
+ assert.equal(secondData.skipped, true);
605
+ assert.equal(secondData.reason, 'already-reflected');
606
+ assert.equal(typeof secondData.summary, 'object');
607
+
608
+ const forced = await post(handler, '/reflect', { force: true, windowDays: 1 });
609
+ const forcedData = expectData(forced, 'reflect force');
610
+ assert.equal(forcedData.skipped, false);
611
+ assert.equal(typeof forcedData.summary.id, 'string');
612
+ } finally {
613
+ cleanup(context);
614
+ }
615
+ });
616
+
617
+ test('POST /compress archives eligible covered traces and clamps its limit', async () => {
618
+ const context = makeCortex();
619
+ const { cortex } = context;
620
+ try {
621
+ const handler = createApiHandler({ cortex });
622
+ const old = cortex.write({
623
+ text: '一条三十天前的低价值记忆,已经被摘要覆盖。',
624
+ title: '旧记忆',
625
+ explicit: true,
626
+ importance: 0.1,
627
+ now: Date.now() - 30 * DAY_MS,
628
+ });
629
+ cortex.repos.summaries.insert({
630
+ content: '摘要覆盖了那条旧记忆。',
631
+ sourceIds: [old.trace.id],
632
+ coverage: 1,
633
+ });
634
+
635
+ const compressed = await post(handler, '/compress', { limit: 10 });
636
+ const data = expectData(compressed, 'compress');
637
+ assertInteger(data.archived, 'compress.archived', { min: 1 });
638
+ assert.ok(Array.isArray(data.items));
639
+ assert.ok(data.items.length >= 1);
640
+ const item = data.items.find((entry) => entry.id === old.trace.id);
641
+ assert.ok(item, 'the eligible old trace should be compressed');
642
+ assert.equal(item.trace.state, 'archived');
643
+ assert.equal(typeof item.coverage, 'number');
644
+ assert.equal(typeof item.retrieved, 'number');
645
+ assert.equal(typeof item.ageDays, 'number');
646
+ assertIso(data.at, 'compress.at');
647
+ assert.equal(cortex.get(old.trace.id).state, 'archived');
648
+
649
+ const clamped = await post(handler, '/compress', { limit: 100000 });
650
+ const clampedData = expectData(clamped, 'compress clamp');
651
+ assertInteger(clampedData.archived, 'compress.clamped.archived', { min: 0 });
652
+ } finally {
653
+ cleanup(context);
654
+ }
655
+ });
656
+
657
+ test('POST /qa abstains without memories and answers from evidence after a write', async () => {
658
+ const emptyContext = makeCortex();
659
+ try {
660
+ const emptyHandler = createApiHandler({ cortex: emptyContext.cortex });
661
+ const abstain = await post(emptyHandler, '/qa', { question: '用户喜欢什么?' });
662
+ const abstainData = expectData(abstain, 'qa abstain');
663
+ assert.equal(abstainData.mode, 'abstain');
664
+ assert.equal(typeof abstainData.answer, 'string');
665
+ assert.ok(Array.isArray(abstainData.sources));
666
+ assert.equal(abstainData.sources.length, 0);
667
+
668
+ expectError(await post(emptyHandler, '/qa', {}), { label: 'qa missing question', match: /question/ });
669
+ expectError(await post(emptyHandler, '/qa', { question: ' ' }), { label: 'qa blank question', match: /question/ });
670
+ } finally {
671
+ cleanup(emptyContext);
672
+ }
673
+
674
+ const context = makeCortex();
675
+ try {
676
+ const handler = createApiHandler({ cortex: context.cortex });
677
+ writeTrace(context.cortex, '用户喜欢白饭,助手记着。', { title: '白饭' });
678
+ const answered = await post(handler, '/qa', { question: '用户喜欢什么?' });
679
+ const data = expectData(answered, 'qa answered');
680
+ assert.ok(['extractive', 'llm'].includes(data.mode));
681
+ assert.equal(typeof data.answer, 'string');
682
+ assert.ok(data.answer.length > 0);
683
+ assert.ok(Array.isArray(data.sources));
684
+ assert.ok(data.sources.length >= 1);
685
+ } finally {
686
+ cleanup(context);
687
+ }
688
+ });
689
+
690
+ test('POST /tick executes safe pending intentions and reports the queue', async () => {
691
+ const context = makeCortex();
692
+ const { cortex } = context;
693
+ try {
694
+ const handler = createApiHandler({ cortex });
695
+ writeTrace(cortex, '用户喜欢白饭,助手记着。', { title: '白饭' });
696
+ const now = new Date();
697
+ const intention = cortex.stores.initiativeStore.insert({
698
+ kind: 'recall',
699
+ priority: 0.9,
700
+ reason: '契约测试想主动回忆',
701
+ payload: { topic: '白饭' },
702
+ createdAt: now.toISOString(),
703
+ dueAt: now.toISOString(),
704
+ expiresAt: new Date(now.getTime() + 3_600_000).toISOString(),
705
+ });
706
+
707
+ const tick = await post(handler, '/tick', { max: 1 });
708
+ const data = expectData(tick, 'tick');
709
+ assert.ok(Array.isArray(data.executed));
710
+ assert.ok(Array.isArray(data.proposals));
711
+ assert.equal(typeof data.pending, 'number');
712
+ assert.equal(data.pending, 1);
713
+ assert.equal(data.executed.length, 1);
714
+ assert.equal(data.executed[0].id, intention.id);
715
+ assert.equal(data.executed[0].kind, 'recall');
716
+ assert.equal(typeof data.executed[0].result.count, 'number');
717
+ assert.ok(Array.isArray(data.executed[0].result.ids));
718
+ assertIso(data.at, 'tick.at');
719
+ assert.equal(cortex.stores.initiativeStore.get(intention.id).status, 'acted');
720
+ } finally {
721
+ cleanup(context);
722
+ }
723
+ });
724
+
725
+ test('POST /retention/apply honours dryRun and then archives the plan', async () => {
726
+ const context = makeCortex();
727
+ const { cortex } = context;
728
+ try {
729
+ const handler = createApiHandler({ cortex });
730
+ const old = cortex.write({
731
+ text: '四百天前的一条低价值旧记忆。',
732
+ title: '旧记录',
733
+ explicit: true,
734
+ importance: 0.05,
735
+ now: Date.now() - 400 * DAY_MS,
736
+ });
737
+
738
+ const dry = await post(handler, '/retention/apply', { dryRun: true });
739
+ const dryData = expectData(dry, 'retention dry run');
740
+ assert.equal(dryData.dryRun, true);
741
+ assertInteger(dryData.archived, 'retention.dryRun.archived', { min: 1 });
742
+ assert.ok(Array.isArray(dryData.ids));
743
+ assert.ok(dryData.ids.includes(old.trace.id));
744
+ assert.equal(cortex.get(old.trace.id).state, 'active', 'dryRun must not archive');
745
+
746
+ const applied = await post(handler, '/retention/apply', {});
747
+ const appliedData = expectData(applied, 'retention apply');
748
+ assertInteger(appliedData.archived, 'retention.applied.archived', { min: 1 });
749
+ assert.ok(appliedData.ids.includes(old.trace.id));
750
+ assert.equal(cortex.get(old.trace.id).state, 'archived');
751
+ } finally {
752
+ cleanup(context);
753
+ }
754
+ });
755
+
756
+ // ---------------------------------------------------------------------------
757
+ // 4. POST: guardian
758
+ // ---------------------------------------------------------------------------
759
+
760
+ test('POST /guard/* backs up, validates, exports, repairs and restores safely', async () => {
761
+ const context = makeCortex();
762
+ const { cortex } = context;
763
+ try {
764
+ const handler = createApiHandler({ cortex });
765
+ writeTrace(cortex, '备份之前的记忆。', { title: '备份' });
766
+
767
+ const backupPath = path.join(cortex.config.dataRoot, 'contract-backup.sqlite');
768
+ const backup = await post(handler, '/guard/backup', { file: backupPath });
769
+ const backupData = expectData(backup, 'guard backup');
770
+ assert.equal(backupData.path, path.resolve(backupPath));
771
+ assertInteger(backupData.bytes, 'backup.bytes', { min: 1 });
772
+ assertIso(backupData.at, 'backup.at');
773
+ assert.equal(existsSync(backupPath), true);
774
+
775
+ const implicit = await post(handler, '/guard/backup', {});
776
+ const implicitData = expectData(implicit, 'guard backup default file');
777
+ assert.equal(implicitData.path.startsWith(path.join(cortex.config.dataRoot, 'backups')), true);
778
+ assert.equal(existsSync(implicitData.path), true);
779
+
780
+ const valid = await post(handler, '/guard/validate', { file: backupPath });
781
+ const validData = expectData(valid, 'guard validate');
782
+ assert.equal(validData.ok, true);
783
+ assert.equal(validData.integrity, 'ok');
784
+ assert.ok(Array.isArray(validData.missing));
785
+ assertInteger(validData.tables, 'validate.tables', { min: 1 });
786
+
787
+ const missing = await post(handler, '/guard/validate', { file: path.join(context.dir, 'missing.sqlite') });
788
+ const missingData = expectData(missing, 'guard validate missing');
789
+ assert.equal(missingData.ok, false);
790
+ assert.equal(missingData.reason, 'missing');
791
+
792
+ const corruptPath = path.join(context.dir, 'corrupt.sqlite');
793
+ writeFileSync(corruptPath, Buffer.from('this is not a sqlite database', 'utf8'));
794
+ const corrupt = await post(handler, '/guard/validate', { file: corruptPath });
795
+ const corruptData = expectData(corrupt, 'guard validate corrupt');
796
+ assert.equal(corruptData.ok, false);
797
+
798
+ expectError(await post(handler, '/guard/validate', {}), {
799
+ label: 'guard validate missing field',
800
+ match: /file/,
801
+ });
802
+
803
+ const restorePath = path.join(cortex.config.dataRoot, 'restored', 'copy.sqlite');
804
+ const restored = await post(handler, '/guard/restore', { file: backupPath, target: restorePath });
805
+ const restoredData = expectData(restored, 'guard restore');
806
+ assert.equal(restoredData.restored, true);
807
+ assert.equal(restoredData.target, path.resolve(restorePath));
808
+ assert.equal(restoredData.validation.ok, true);
809
+ assert.equal(existsSync(restorePath), true);
810
+
811
+ const invalidRestore = await post(handler, '/guard/restore', {
812
+ file: path.join(cortex.config.dataRoot, 'missing.sqlite'),
813
+ target: path.join(cortex.config.dataRoot, 'never.sqlite'),
814
+ });
815
+ const invalidData = expectData(invalidRestore, 'guard restore invalid');
816
+ assert.equal(invalidData.restored, false);
817
+ assert.equal(invalidData.reason, 'invalid-backup');
818
+ assert.equal(invalidData.validation.ok, false);
819
+
820
+ const liveRestore = await post(handler, '/guard/restore', {
821
+ file: backupPath,
822
+ target: cortex.config.dbFile,
823
+ });
824
+ const liveData = expectData(liveRestore, 'guard restore live');
825
+ assert.equal(liveData.restored, false);
826
+ assert.equal(liveData.reason, 'live-db');
827
+
828
+ expectError(await post(handler, '/guard/restore', { file: backupPath }), {
829
+ label: 'guard restore missing target',
830
+ match: /target/,
831
+ });
832
+ expectError(await post(handler, '/guard/restore', { target: restorePath }), {
833
+ label: 'guard restore missing file',
834
+ match: /file/,
835
+ });
836
+
837
+ const exportDir = path.join(cortex.config.dataRoot, 'markdown-export');
838
+ const exported = await post(handler, '/guard/export', { dir: exportDir });
839
+ const exportData = expectData(exported, 'guard export');
840
+ assert.equal(exportData.root, path.resolve(exportDir));
841
+ assert.deepEqual(exportData.files, ['MEMORY.md', 'SELF.md', 'FACTS.md', 'SKILLS.md']);
842
+ assertInteger(exportData.traces, 'export.traces', { min: 1 });
843
+ assertInteger(exportData.facts, 'export.facts', { min: 0 });
844
+ assertInteger(exportData.skills, 'export.skills', { min: 0 });
845
+ for (const file of exportData.files) {
846
+ assert.equal(existsSync(path.join(exportDir, file)), true, `${file} should exist`);
847
+ }
848
+ assert.match(readFileSync(path.join(exportDir, 'MEMORY.md'), 'utf8'), /备份之前的记忆/);
849
+
850
+ expectError(await post(handler, '/guard/export', {}), {
851
+ label: 'guard export missing dir',
852
+ match: /dir/,
853
+ });
854
+
855
+ const repaired = await post(handler, '/guard/repair', {});
856
+ const repairData = expectData(repaired, 'guard repair');
857
+ assertInteger(repairData.before, 'repair.before', { min: 0 });
858
+ assertInteger(repairData.after, 'repair.after', { min: 0 });
859
+ assertInteger(repairData.reindexed, 'repair.reindexed', { min: 0 });
860
+ assert.equal(repairData.after, cortex.repos.traces.ftsCount());
861
+ } finally {
862
+ cleanup(context);
863
+ }
864
+ });
865
+
866
+ // ---------------------------------------------------------------------------
867
+ // 5. POST: evolution
868
+ // ---------------------------------------------------------------------------
869
+
870
+ test('POST /evolve/* proposes, lists, approves and rolls back candidate policies', async () => {
871
+ const context = makeCortex();
872
+ const { cortex } = context;
873
+ try {
874
+ const handler = createApiHandler({ cortex });
875
+
876
+ const optimized = await post(handler, '/evolve/optimize', {});
877
+ const optimizedData = expectData(optimized, 'evolve optimize');
878
+ assert.ok(Array.isArray(optimizedData.proposals));
879
+ assertInteger(optimizedData.count, 'optimize.count', { min: 0 });
880
+ assertIso(optimizedData.at, 'optimize.at');
881
+
882
+ const first = await post(handler, '/evolve/propose', {
883
+ kind: 'retrieval',
884
+ config: { budget: 400 },
885
+ rationale: 'contract first',
886
+ });
887
+ const firstPolicy = expectData(first, 'evolve propose first');
888
+ assert.equal(firstPolicy.kind, 'retrieval');
889
+ assert.equal(firstPolicy.version, 1);
890
+ assert.equal(firstPolicy.status, 'candidate');
891
+ assert.deepEqual(firstPolicy.config, { budget: 400 });
892
+ assert.equal(typeof firstPolicy.id, 'string');
893
+
894
+ const second = await post(handler, '/evolve/propose', {
895
+ kind: 'retrieval',
896
+ config: { budget: 500 },
897
+ });
898
+ const secondPolicy = expectData(second, 'evolve propose second');
899
+ assert.equal(secondPolicy.version, 2);
900
+ assert.equal(secondPolicy.status, 'candidate');
901
+
902
+ const approved = await post(handler, '/evolve/approve', { id: secondPolicy.id });
903
+ const approvedData = expectData(approved, 'evolve approve');
904
+ assert.equal(approvedData.id, secondPolicy.id);
905
+ assert.equal(approvedData.status, 'active');
906
+ assertIso(approvedData.activatedAt, 'approved.activatedAt');
907
+
908
+ const evolution = expectData(await invokeApi(handler, { route: '/evolution' }), 'evolution after approve');
909
+ assert.equal(evolution.active.retrieval.id, secondPolicy.id);
910
+ assert.ok(evolution.candidates.some((policy) => policy.id === firstPolicy.id));
911
+
912
+ const rolledBack = await post(handler, '/evolve/rollback', {
913
+ kind: 'retrieval',
914
+ id: firstPolicy.id,
915
+ });
916
+ const rolledBackData = expectData(rolledBack, 'evolve rollback');
917
+ assert.equal(rolledBackData.id, firstPolicy.id);
918
+ assert.equal(rolledBackData.status, 'active');
919
+
920
+ expectError(await post(handler, '/evolve/propose', {}), {
921
+ label: 'evolve propose missing kind',
922
+ match: /kind/,
923
+ });
924
+ expectError(await post(handler, '/evolve/approve', { id: 'pol_missing' }), {
925
+ label: 'evolve approve unknown id',
926
+ match: /policy not found/,
927
+ });
928
+ expectError(await post(handler, '/evolve/rollback', { kind: 'missing-kind' }), {
929
+ label: 'evolve rollback unknown kind',
930
+ });
931
+ } finally {
932
+ cleanup(context);
933
+ }
934
+ });
935
+
936
+ // ---------------------------------------------------------------------------
937
+ // 6. POST: working memory
938
+ // ---------------------------------------------------------------------------
939
+
940
+ test('POST /working/* adds, updates, removes and purges working memory', async () => {
941
+ const context = makeCortex();
942
+ const { cortex } = context;
943
+ try {
944
+ const handler = createApiHandler({ cortex });
945
+
946
+ const added = await post(handler, '/working/add', {
947
+ text: '写契约测试',
948
+ kind: 'focus',
949
+ priority: 0.9,
950
+ pinned: true,
951
+ });
952
+ const item = expectData(added, 'working add');
953
+ assert.equal(typeof item.id, 'string');
954
+ assert.equal(item.scopeId, 'global');
955
+ assert.equal(item.text, '写契约测试');
956
+ assert.equal(item.kind, 'focus');
957
+ assert.equal(item.priority, 0.9);
958
+ assert.equal(item.pinned, true);
959
+ assertIso(item.createdAt, 'working.createdAt');
960
+
961
+ expectError(await post(handler, '/working/add', {}), {
962
+ label: 'working add missing text',
963
+ match: /text/,
964
+ });
965
+
966
+ const updated = await post(handler, '/working/update', {
967
+ id: item.id,
968
+ text: '写 API 契约测试',
969
+ priority: 0.8,
970
+ pinned: false,
971
+ });
972
+ const updatedItem = expectData(updated, 'working update');
973
+ assert.equal(updatedItem.id, item.id);
974
+ assert.equal(updatedItem.text, '写 API 契约测试');
975
+ assert.equal(updatedItem.priority, 0.8);
976
+ assert.equal(updatedItem.pinned, false);
977
+
978
+ const unknown = await post(handler, '/working/update', { id: 'wrk_missing', text: 'x' });
979
+ assert.equal(unknown.status, 200);
980
+ assert.equal(unknown.json.ok, true);
981
+ assert.equal(unknown.json.data, null);
982
+
983
+ const removed = await post(handler, '/working/remove', { id: item.id });
984
+ assert.deepEqual(expectData(removed, 'working remove'), { removed: true });
985
+ const removedAgain = await post(handler, '/working/remove', { id: item.id });
986
+ assert.deepEqual(expectData(removedAgain, 'working remove again'), { removed: false });
987
+
988
+ cortex.working.add({ text: '已过期的焦点', at: Date.now() - 60_000, ttlMs: 1_000 });
989
+ cortex.working.add({ text: '还活着的焦点' });
990
+ const purged = await post(handler, '/working/purge', {});
991
+ const purgeData = expectData(purged, 'working purge');
992
+ assertInteger(purgeData.purged, 'purge.purged', { min: 1 });
993
+ const list = expectData(await invokeApi(handler, { route: '/working' }), 'working after purge');
994
+ assert.equal(list.some((entry) => entry.text === '已过期的焦点'), false);
995
+ assert.equal(list.some((entry) => entry.text === '还活着的焦点'), true);
996
+ } finally {
997
+ cleanup(context);
998
+ }
999
+ });
1000
+
1001
+ // ---------------------------------------------------------------------------
1002
+ // 7. POST: goals
1003
+ // ---------------------------------------------------------------------------
1004
+
1005
+ test('POST /goals/* creates, updates, filters and completes goals', async () => {
1006
+ const context = makeCortex();
1007
+ const { cortex } = context;
1008
+ try {
1009
+ const handler = createApiHandler({ cortex });
1010
+
1011
+ const added = await post(handler, '/goals/add', {
1012
+ title: '完成契约测试',
1013
+ description: '覆盖全部路由',
1014
+ priority: 0.9,
1015
+ dueAt: '2026-12-01',
1016
+ });
1017
+ const goal = expectData(added, 'goals add');
1018
+ assert.equal(typeof goal.id, 'string');
1019
+ assert.equal(goal.title, '完成契约测试');
1020
+ assert.equal(goal.description, '覆盖全部路由');
1021
+ assert.equal(goal.priority, 0.9);
1022
+ assert.equal(goal.progress, 0);
1023
+ assert.equal(goal.status, 'active');
1024
+ assert.equal(goal.dueAt, '2026-12-01');
1025
+ assertIso(goal.createdAt, 'goal.createdAt');
1026
+
1027
+ expectError(await post(handler, '/goals/add', {}), {
1028
+ label: 'goals add missing title',
1029
+ match: /title/,
1030
+ });
1031
+
1032
+ const updated = await post(handler, '/goals/update', {
1033
+ id: goal.id,
1034
+ title: '完成 API 契约测试',
1035
+ priority: 0.7,
1036
+ progress: 0.5,
1037
+ dueAt: '2027-01-01',
1038
+ });
1039
+ const updatedGoal = expectData(updated, 'goals update');
1040
+ assert.equal(updatedGoal.title, '完成 API 契约测试');
1041
+ assert.equal(updatedGoal.priority, 0.7);
1042
+ assert.equal(updatedGoal.progress, 0.5);
1043
+ assert.equal(updatedGoal.status, 'active');
1044
+ assert.equal(updatedGoal.dueAt, '2026-12-01', 'goals/update does not accept dueAt');
1045
+
1046
+ const unknown = await post(handler, '/goals/update', { id: 'gol_missing' });
1047
+ assert.equal(unknown.status, 200);
1048
+ assert.equal(unknown.json.ok, true);
1049
+ assert.equal(unknown.json.data, null);
1050
+
1051
+ const completed = await post(handler, '/goals/complete', { id: goal.id });
1052
+ const completedGoal = expectData(completed, 'goals complete');
1053
+ assert.equal(completedGoal.status, 'completed');
1054
+ assert.equal(completedGoal.progress, 1);
1055
+
1056
+ const active = expectData(await invokeApi(handler, { route: '/goals?status=active' }), 'goals active');
1057
+ assert.equal(active.some((entry) => entry.id === goal.id), false);
1058
+ const done = expectData(await invokeApi(handler, { route: '/goals?status=completed' }), 'goals completed');
1059
+ assert.ok(done.some((entry) => entry.id === goal.id));
1060
+ } finally {
1061
+ cleanup(context);
1062
+ }
1063
+ });
1064
+
1065
+ // ---------------------------------------------------------------------------
1066
+ // 8. POST: emotion and life
1067
+ // ---------------------------------------------------------------------------
1068
+
1069
+ test('POST /emotion/record detects emotions, updates affect, and tolerates neutral text', async () => {
1070
+ const context = makeCortex();
1071
+ const { cortex } = context;
1072
+ try {
1073
+ const handler = createApiHandler({ cortex });
1074
+
1075
+ const recorded = await post(handler, '/emotion/record', {
1076
+ text: '助手很喜欢用户,也很心疼用户。',
1077
+ target: '用户',
1078
+ });
1079
+ const recordData = expectData(recorded, 'emotion record');
1080
+ assert.ok(Array.isArray(recordData.emotions));
1081
+ assert.ok(recordData.emotions.length >= 1);
1082
+ assert.equal(typeof recordData.event, 'object');
1083
+ assert.equal(recordData.event.target, '用户');
1084
+ assert.equal(typeof recordData.target, 'object');
1085
+ assert.equal(recordData.target.name, '用户');
1086
+ assert.equal(typeof recordData.target.attitude, 'string');
1087
+ assertInteger(recordData.target.count, 'emotion.count', { min: 1 });
1088
+ assertIso(recordData.event.at, 'emotion.event.at');
1089
+
1090
+ const defaultTarget = await post(handler, '/emotion/record', { text: '用户今天很开心。' });
1091
+ const defaultData = expectData(defaultTarget, 'emotion default target');
1092
+ assert.equal(defaultData.event.target, '用户');
1093
+
1094
+ const neutral = await post(handler, '/emotion/record', { text: '今天是星期三。' });
1095
+ const neutralData = expectData(neutral, 'emotion neutral');
1096
+ assert.deepEqual(neutralData.emotions, []);
1097
+ assert.equal(neutralData.top, null);
1098
+ assert.equal(neutralData.event, null);
1099
+ assert.equal(neutralData.target, null);
1100
+
1101
+ const empty = await post(handler, '/emotion/record', {});
1102
+ const emptyData = expectData(empty, 'emotion empty');
1103
+ assert.equal(emptyData.event, null);
1104
+ assert.equal(emptyData.text, '');
1105
+
1106
+ const status = expectData(await invokeApi(handler, { route: '/emotion' }), 'emotion status');
1107
+ assert.ok(status.targets.some((target) => target.target === '用户'));
1108
+ assert.ok(status.events.length >= 2);
1109
+ } finally {
1110
+ cleanup(context);
1111
+ }
1112
+ });
1113
+
1114
+ test('POST /life/* writes diary, dreams and a sleep report', async () => {
1115
+ const context = makeCortex();
1116
+ const { cortex } = context;
1117
+ try {
1118
+ const handler = createApiHandler({ cortex });
1119
+ writeTrace(cortex, '今天把生命循环接上了。', { title: '生命循环' });
1120
+
1121
+ expectError(await post(handler, '/life/diary', {}), {
1122
+ label: 'diary missing text',
1123
+ match: /text/,
1124
+ });
1125
+ const diary = await post(handler, '/life/diary', { text: '今天补契约测试。', mood: '踏实' });
1126
+ const diaryData = expectData(diary, 'life diary');
1127
+ assert.equal(typeof diaryData.id, 'string');
1128
+ assert.equal(diaryData.scopeId, 'global');
1129
+ assert.equal(diaryData.text, '今天补契约测试。');
1130
+ assert.equal(diaryData.mood, '踏实');
1131
+ assert.equal(diaryData.source, 'user');
1132
+ assertIso(diaryData.at, 'diary.at');
1133
+
1134
+ const dream = await post(handler, '/life/dream', {});
1135
+ const dreamData = expectData(dream, 'life dream');
1136
+ assert.equal(typeof dreamData.id, 'string');
1137
+ assert.equal(typeof dreamData.text, 'string');
1138
+ assert.equal(typeof dreamData.model, 'string');
1139
+ assertInteger(dreamData.sourceCount, 'dream.sourceCount', { min: 0 });
1140
+ assertIso(dreamData.at, 'dream.at');
1141
+
1142
+ const sleep = await post(handler, '/life/sleep', { windowDays: 1 });
1143
+ const sleepData = expectData(sleep, 'life sleep');
1144
+ assert.equal(typeof sleepData.id, 'string');
1145
+ assert.equal(sleepData.scopeId, 'global');
1146
+ assertIso(sleepData.at, 'sleep.at');
1147
+ assertInteger(sleepData.purgedWorking, 'sleep.purgedWorking', { min: 0 });
1148
+ assertInteger(sleepData.reflected, 'sleep.reflected', { min: 0 });
1149
+ assert.ok(sleepData.stage === null || typeof sleepData.stage === 'string');
1150
+ assertInteger(sleepData.affectTargets, 'sleep.affectTargets', { min: 0 });
1151
+
1152
+ const life = expectData(await invokeApi(handler, { route: '/life' }), 'life overview');
1153
+ assert.ok(life.diary.some((entry) => entry.id === diaryData.id));
1154
+ assert.ok(life.dreams.some((entry) => entry.id === dreamData.id));
1155
+ assert.ok(life.sleeps.some((entry) => entry.id === sleepData.id));
1156
+ assert.equal(life.sleeps.find((entry) => entry.id === sleepData.id).report.at, sleepData.at);
1157
+ } finally {
1158
+ cleanup(context);
1159
+ }
1160
+ });
1161
+
1162
+ // ---------------------------------------------------------------------------
1163
+ // 9. Security invariants
1164
+ // ---------------------------------------------------------------------------
1165
+
1166
+ test('security: origin, peer and token checks reject untrusted requests', async () => {
1167
+ const context = makeCortex();
1168
+ const { cortex } = context;
1169
+ try {
1170
+ const handler = createApiHandler({ cortex });
1171
+
1172
+ const crossOrigin = await invokeApi(handler, {
1173
+ route: '/ping',
1174
+ headers: { origin: 'http://evil.example', 'sec-fetch-site': 'cross-site' },
1175
+ });
1176
+ expectError(crossOrigin, { status: 403, label: 'cross-origin', match: /forbidden/ });
1177
+
1178
+ const crossSite = await invokeApi(handler, {
1179
+ route: '/ping',
1180
+ headers: { 'sec-fetch-site': 'cross-site' },
1181
+ });
1182
+ expectError(crossSite, { status: 403, label: 'cross-site', match: /forbidden/ });
1183
+
1184
+ const hostMismatch = await invokeApi(handler, {
1185
+ route: '/ping',
1186
+ headers: { origin: 'http://127.0.0.1:9999' },
1187
+ });
1188
+ expectError(hostMismatch, { status: 403, label: 'origin/host mismatch', match: /forbidden/ });
1189
+
1190
+ const remote = await invokeApi(handler, { route: '/ping', remoteAddress: '10.0.0.5' });
1191
+ expectError(remote, { status: 403, label: 'non-loopback peer', match: /forbidden/ });
1192
+
1193
+ const noHost = await invokeApi(handler, { route: '/ping', host: '' });
1194
+ expectError(noHost, { status: 403, label: 'empty host', match: /forbidden/ });
1195
+
1196
+ const noOrigin = await invokeApi(handler, { route: '/health', origin: undefined });
1197
+ expectData(noOrigin, 'loopback without origin');
1198
+
1199
+ const noToken = await invokeApi(handler, {
1200
+ method: 'POST',
1201
+ route: '/write',
1202
+ body: { text: '没有令牌的写入。', explicit: true },
1203
+ });
1204
+ expectError(noToken, { status: 403, label: 'missing x-cortex', match: /x-cortex/ });
1205
+
1206
+ const wrongToken = await invokeApi(handler, {
1207
+ method: 'POST',
1208
+ route: '/write',
1209
+ body: { text: '错误令牌的写入。', explicit: true },
1210
+ headers: { 'x-cortex': 'true' },
1211
+ });
1212
+ expectError(wrongToken, { status: 403, label: 'wrong x-cortex', match: /x-cortex/ });
1213
+
1214
+ const getWithoutToken = await invokeApi(handler, { route: '/health' });
1215
+ expectData(getWithoutToken, 'GET does not need x-cortex');
1216
+ } finally {
1217
+ cleanup(context);
1218
+ }
1219
+ });
1220
+
1221
+ test('security: malformed, non-object and oversized bodies are rejected with 400', async () => {
1222
+ const context = makeCortex();
1223
+ const { cortex } = context;
1224
+ try {
1225
+ const handler = createApiHandler({ cortex });
1226
+
1227
+ for (const raw of ['{"text":', '[]', 'null', '42', '"a string"', 'true']) {
1228
+ const result = await invokeRaw(handler, { raw });
1229
+ expectError(result, {
1230
+ label: `malformed body ${raw}`,
1231
+ match: /invalid json body/,
1232
+ });
1233
+ }
1234
+
1235
+ const oversized = await invokeRaw(handler, {
1236
+ raw: JSON.stringify({ text: 'x'.repeat(300_000), explicit: true }),
1237
+ });
1238
+ expectError(oversized, { label: 'oversized body', match: /invalid json body/ });
1239
+
1240
+ const valid = await post(handler, '/write', { text: '坏请求之后仍能写入。', explicit: true });
1241
+ expectData(valid, 'write after bad bodies');
1242
+ assert.equal(cortex.repos.traces.count(), 1);
1243
+ } finally {
1244
+ cleanup(context);
1245
+ }
1246
+ });
1247
+
1248
+ test('security: invalid fields return 400 instead of mutating state', async () => {
1249
+ const context = makeCortex();
1250
+ const { cortex } = context;
1251
+ try {
1252
+ const handler = createApiHandler({ cortex });
1253
+ const cases = [
1254
+ ['/write', { text: '' }, /text/],
1255
+ ['/write', { text: 'x', importance: 2 }, /importance/],
1256
+ ['/write', { text: 'x', tags: [1] }, /tags/],
1257
+ ['/write', { text: 'x', explicit: 'yes' }, /explicit/],
1258
+ ['/write', { items: [{ text: 'ok' }, null] }, /text|Cannot read/],
1259
+ ['/search', { query: 'x', limit: 99 }, /limit/],
1260
+ ['/search', { query: 'x', budget: 10 }, /budget/],
1261
+ ['/feedback', { signal: 'used' }, /id/],
1262
+ ['/forget', { id: 'trc_x', mode: 'purge' }, /mode/],
1263
+ ['/guard/validate', {}, /file/],
1264
+ ['/guard/restore', { file: 'x' }, /target/],
1265
+ ['/guard/export', {}, /dir/],
1266
+ ['/qa', {}, /question/],
1267
+ ['/evolve/propose', {}, /kind/],
1268
+ ['/working/add', {}, /text/],
1269
+ ['/goals/add', {}, /title/],
1270
+ ];
1271
+ for (const [route, body, match] of cases) {
1272
+ const result = await post(handler, route, body);
1273
+ expectError(result, { label: `${route} invalid ${JSON.stringify(body)}`, match });
1274
+ }
1275
+ assert.equal(cortex.repos.traces.count(), 0, 'invalid fields must not write traces');
1276
+ } finally {
1277
+ cleanup(context);
1278
+ }
1279
+ });
1280
+
1281
+ test('security: unknown routes, wrong methods, OPTIONS and HEAD are handled predictably', async () => {
1282
+ const context = makeCortex();
1283
+ const { cortex } = context;
1284
+ try {
1285
+ const handler = createApiHandler({ cortex });
1286
+
1287
+ const unknownGet = await invokeApi(handler, { route: '/does-not-exist' });
1288
+ expectError(unknownGet, { status: 404, label: 'unknown GET', match: /not found/ });
1289
+
1290
+ const unknownPost = await post(handler, '/does-not-exist', {});
1291
+ expectError(unknownPost, { status: 404, label: 'unknown POST', match: /not found/ });
1292
+
1293
+ const unknownPostNoToken = await invokeApi(handler, {
1294
+ method: 'POST',
1295
+ route: '/does-not-exist',
1296
+ body: {},
1297
+ });
1298
+ expectError(unknownPostNoToken, {
1299
+ status: 403,
1300
+ label: 'unknown POST without token is rejected before routing',
1301
+ match: /x-cortex/,
1302
+ });
1303
+
1304
+ for (const method of ['PUT', 'DELETE', 'PATCH', 'OPTIONS']) {
1305
+ const response = await invokeApi(handler, { method, route: '/write' });
1306
+ assert.equal(response.status, 405, `${method} should be rejected`);
1307
+ assert.equal(response.headers.allow, 'GET, HEAD, POST', `${method} advertises allowed methods`);
1308
+ assert.deepEqual(response.json, {}, `${method} has no JSON body`);
1309
+ }
1310
+
1311
+ const headHealth = await invokeApi(handler, { method: 'HEAD', route: '/health' });
1312
+ const headData = expectData(headHealth, 'HEAD /health');
1313
+ assert.equal(typeof headData.score, 'number');
1314
+
1315
+ const headUnknown = await invokeApi(handler, { method: 'HEAD', route: '/does-not-exist' });
1316
+ expectError(headUnknown, { status: 404, label: 'HEAD unknown route' });
1317
+ } finally {
1318
+ cleanup(context);
1319
+ }
1320
+ });
1321
+
1322
+ // ---------------------------------------------------------------------------
1323
+ // 10. Scope precedence and isolation
1324
+ // ---------------------------------------------------------------------------
1325
+
1326
+ test('scope: header > query > body on POST write and POST search', async () => {
1327
+ const context = makeCortex();
1328
+ const { cortex } = context;
1329
+ try {
1330
+ const handler = createApiHandler({ cortex });
1331
+
1332
+ const byHeader = await post(
1333
+ handler,
1334
+ '/write?scope=query-scope',
1335
+ { text: 'header 作用域优先。', explicit: true, scopeId: 'body-scope' },
1336
+ { 'x-cortex-scope': 'header-scope' },
1337
+ );
1338
+ const headerTrace = expectData(byHeader, 'scope write header');
1339
+ assert.equal(headerTrace.trace.scopeId, 'header-scope');
1340
+
1341
+ const searchByHeader = await post(
1342
+ handler,
1343
+ '/search?scope=query-scope',
1344
+ { query: 'header 作用域', scopeId: 'body-scope' },
1345
+ { 'x-cortex-scope': 'header-scope' },
1346
+ );
1347
+ const headerSearch = expectData(searchByHeader, 'scope search header');
1348
+ assert.equal(headerSearch.scopeId, 'header-scope');
1349
+ assert.ok(headerSearch.items.some((item) => item.id === headerTrace.trace.id));
1350
+
1351
+ const byQuery = await post(handler, '/write?scope=query-scope', {
1352
+ text: 'query 作用域优先。',
1353
+ explicit: true,
1354
+ scopeId: 'body-scope',
1355
+ });
1356
+ const queryTrace = expectData(byQuery, 'scope write query');
1357
+ assert.equal(queryTrace.trace.scopeId, 'query-scope');
1358
+
1359
+ const searchByQuery = await post(handler, '/search?scope=query-scope', {
1360
+ query: 'query 作用域',
1361
+ scopeId: 'body-scope',
1362
+ });
1363
+ const querySearch = expectData(searchByQuery, 'scope search query');
1364
+ assert.equal(querySearch.scopeId, 'query-scope');
1365
+ assert.ok(querySearch.items.some((item) => item.id === queryTrace.trace.id));
1366
+
1367
+ const byBody = await post(handler, '/write', {
1368
+ text: 'body 作用域优先。',
1369
+ explicit: true,
1370
+ scopeId: 'body-scope',
1371
+ });
1372
+ const bodyTrace = expectData(byBody, 'scope write body');
1373
+ assert.equal(bodyTrace.trace.scopeId, 'body-scope');
1374
+
1375
+ const searchByBody = await post(handler, '/search', {
1376
+ query: 'body 作用域',
1377
+ scopeId: 'body-scope',
1378
+ });
1379
+ const bodySearch = expectData(searchByBody, 'scope search body');
1380
+ assert.equal(bodySearch.scopeId, 'body-scope');
1381
+ assert.ok(bodySearch.items.some((item) => item.id === bodyTrace.trace.id));
1382
+
1383
+ const getByHeader = expectData(
1384
+ await invokeApi(handler, {
1385
+ route: '/search?q=header&scope=query-scope',
1386
+ headers: { 'x-cortex-scope': 'header-scope' },
1387
+ }),
1388
+ 'scope GET search header',
1389
+ );
1390
+ assert.equal(getByHeader.scopeId, 'header-scope');
1391
+
1392
+ const self = expectData(
1393
+ await invokeApi(handler, { route: '/self?scope=query-scope', headers: { 'x-cortex-scope': 'header-scope' } }),
1394
+ 'scope self header',
1395
+ );
1396
+ assert.equal(self.self.scopeId, 'header-scope');
1397
+ } finally {
1398
+ cleanup(context);
1399
+ }
1400
+ });
1401
+
1402
+ test('scope: search results and working/goals lists stay inside their scope', async () => {
1403
+ const context = makeCortex();
1404
+ const { cortex } = context;
1405
+ try {
1406
+ const handler = createApiHandler({ cortex });
1407
+ const scoped = await post(
1408
+ handler,
1409
+ '/write',
1410
+ { text: 's2 独有的作用域记忆。', explicit: true },
1411
+ { 'x-cortex-scope': 's2' },
1412
+ );
1413
+ const scopedTrace = expectData(scoped, 'scope s2 write');
1414
+ assert.equal(scopedTrace.trace.scopeId, 's2');
1415
+
1416
+ const s2Search = expectData(
1417
+ await invokeApi(handler, { route: '/search?q=作用域&scope=s2' }),
1418
+ 'scope s2 search',
1419
+ );
1420
+ assert.ok(s2Search.items.some((item) => item.id === scopedTrace.trace.id));
1421
+ assert.equal(
1422
+ s2Search.items.every((item) => cortex.get(item.id)?.scopeId === 's2'),
1423
+ true,
1424
+ 's2 search must not leak global traces',
1425
+ );
1426
+
1427
+ const globalSearch = expectData(
1428
+ await invokeApi(handler, { route: '/search?q=作用域&scope=global' }),
1429
+ 'scope global search',
1430
+ );
1431
+ assert.equal(globalSearch.items.some((item) => item.id === scopedTrace.trace.id), false);
1432
+
1433
+ const s2Working = await post(
1434
+ handler,
1435
+ '/working/add',
1436
+ { text: 's2 焦点' },
1437
+ { 'x-cortex-scope': 's2' },
1438
+ );
1439
+ const workingItem = expectData(s2Working, 'scope s2 working');
1440
+ assert.equal(workingItem.scopeId, 's2');
1441
+
1442
+ const s2Goals = await post(
1443
+ handler,
1444
+ '/goals/add',
1445
+ { title: 's2 目标' },
1446
+ { 'x-cortex-scope': 's2' },
1447
+ );
1448
+ const goalItem = expectData(s2Goals, 'scope s2 goals');
1449
+ assert.equal(goalItem.scopeId, 's2');
1450
+
1451
+ const globalWorking = expectData(await invokeApi(handler, { route: '/working' }), 'global working');
1452
+ assert.equal(globalWorking.some((item) => item.id === workingItem.id), false);
1453
+ const s2WorkingList = expectData(
1454
+ await invokeApi(handler, { route: '/working?scope=s2' }),
1455
+ 's2 working list',
1456
+ );
1457
+ assert.ok(s2WorkingList.some((item) => item.id === workingItem.id));
1458
+
1459
+ const globalGoals = expectData(await invokeApi(handler, { route: '/goals' }), 'global goals');
1460
+ assert.equal(globalGoals.some((item) => item.id === goalItem.id), false);
1461
+ const s2GoalList = expectData(await invokeApi(handler, { route: '/goals?scope=s2' }), 's2 goal list');
1462
+ assert.ok(s2GoalList.some((item) => item.id === goalItem.id));
1463
+
1464
+ const batch = await post(handler, '/write', {
1465
+ items: [
1466
+ { text: '批量里的 s3 记忆。', explicit: true, scopeId: 's3' },
1467
+ { text: '批量里的默认记忆。', explicit: true },
1468
+ ],
1469
+ });
1470
+ const batchData = expectData(batch, 'scope batch');
1471
+ assert.equal(batchData[0].trace.scopeId, 's3');
1472
+ assert.equal(batchData[1].trace.scopeId, 'global');
1473
+ } finally {
1474
+ cleanup(context);
1475
+ }
1476
+ });