dsh-cortex-memory 0.4.22 → 0.4.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +2390 -154
  2. package/README.md +11 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +10 -10
  5. package/bench/synthetic.js +3 -3
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/client.js +1 -1
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/icon.svg +12 -2
  15. package/index.js +27 -3
  16. package/package.json +3 -3
  17. package/src/adapters/shiori.js +1 -1
  18. package/src/api/routes.js +1 -1
  19. package/src/core/feature-overrides.js +2 -2
  20. package/src/engines/compression.js +172 -3
  21. package/src/engines/consolidate.js +397 -26
  22. package/src/engines/encode.js +16 -3
  23. package/src/engines/extract.js +72 -8
  24. package/src/engines/fact-guard.js +51 -0
  25. package/src/engines/health.js +263 -3
  26. package/src/engines/inhibition.js +39 -0
  27. package/src/engines/life.js +14 -3
  28. package/src/engines/llm-facts.js +12 -9
  29. package/src/engines/narrative.js +150 -13
  30. package/src/engines/reflect.js +172 -14
  31. package/src/engines/retrieve.js +44 -5
  32. package/src/engines/summary-coverage.js +62 -0
  33. package/src/engines/summary-dedupe.js +77 -0
  34. package/src/engines/summon-rank.js +132 -0
  35. package/src/host/runtime.js +64 -4
  36. package/src/host/scheduler.js +224 -3
  37. package/src/llm/adapter.js +29 -8
  38. package/src/memory/query.js +1 -1
  39. package/src/memory/spacing.js +15 -0
  40. package/src/memory/tokenizer.js +1 -1
  41. package/src/prompt/tiers.js +88 -12
  42. package/src/self/alias.js +25 -0
  43. package/src/self/emotion.js +3 -1
  44. package/src/self/relationship.js +44 -13
  45. package/src/self/state.js +20 -2
  46. package/src/self/working.js +34 -3
  47. package/src/service/cortex.js +493 -53
  48. package/src/store/repositories/facts.js +34 -1
  49. package/src/store/repositories/summaries.js +8 -1
  50. package/src/store/repositories/traces.js +22 -2
  51. package/src/tools/definitions.js +118 -4
  52. package/src/vector/index.js +96 -7
  53. package/test/integration/_helpers.js +0 -128
  54. package/test/integration/acceptance.test.js +0 -803
  55. package/test/integration/ann-load.test.js +0 -61
  56. package/test/integration/api-contract.test.js +0 -1476
  57. package/test/integration/backup-privacy.test.js +0 -214
  58. package/test/integration/consolidate.test.js +0 -75
  59. package/test/integration/edge-cases.test.js +0 -1088
  60. package/test/integration/exchange.test.js +0 -326
  61. package/test/integration/life-loop.test.js +0 -188
  62. package/test/integration/load.test.js +0 -751
  63. package/test/integration/markdown-sync.test.js +0 -35
  64. package/test/integration/policy-query-api.test.js +0 -306
  65. package/test/integration/resilience-writes.test.js +0 -241
  66. package/test/integration/tools-contract.test.js +0 -1324
  67. package/test/unit/ann-edge.test.js +0 -102
  68. package/test/unit/ann.test.js +0 -77
  69. package/test/unit/api-client.test.js +0 -576
  70. package/test/unit/api-validate.test.js +0 -19
  71. package/test/unit/api.test.js +0 -555
  72. package/test/unit/appraisal.test.js +0 -48
  73. package/test/unit/attachments.test.js +0 -33
  74. package/test/unit/autonomy.test.js +0 -53
  75. package/test/unit/batch.test.js +0 -46
  76. package/test/unit/bench.test.js +0 -40
  77. package/test/unit/benchmark-synthetic.test.js +0 -52
  78. package/test/unit/cli-default-root.test.js +0 -21
  79. package/test/unit/client-contract.test.js +0 -32
  80. package/test/unit/compression.test.js +0 -76
  81. package/test/unit/core.test.js +0 -77
  82. package/test/unit/develop.test.js +0 -130
  83. package/test/unit/development.test.js +0 -68
  84. package/test/unit/digest.test.js +0 -26
  85. package/test/unit/dsr.test.js +0 -111
  86. package/test/unit/edges-candidates.test.js +0 -113
  87. package/test/unit/emotion.test.js +0 -61
  88. package/test/unit/encode.test.js +0 -98
  89. package/test/unit/evolution.test.js +0 -130
  90. package/test/unit/external-ann-search.test.js +0 -50
  91. package/test/unit/external-ann.test.js +0 -29
  92. package/test/unit/facts-belief.test.js +0 -32
  93. package/test/unit/facts.test.js +0 -107
  94. package/test/unit/feature-overrides.test.js +0 -42
  95. package/test/unit/fts-migration.test.js +0 -42
  96. package/test/unit/graph.test.js +0 -79
  97. package/test/unit/growth-reflect.test.js +0 -123
  98. package/test/unit/guard-runtime.test.js +0 -40
  99. package/test/unit/guardian.test.js +0 -91
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/hnsw.test.js +0 -35
  102. package/test/unit/host-runtime.test.js +0 -142
  103. package/test/unit/host.test.js +0 -58
  104. package/test/unit/identity.test.js +0 -98
  105. package/test/unit/induct-evaluate.test.js +0 -41
  106. package/test/unit/ingest-extracted.test.js +0 -35
  107. package/test/unit/initiative.test.js +0 -90
  108. package/test/unit/jobs.test.js +0 -93
  109. package/test/unit/json-snapshot.test.js +0 -57
  110. package/test/unit/life-consolidate.test.js +0 -34
  111. package/test/unit/life.test.js +0 -149
  112. package/test/unit/llm-facts-integration.test.js +0 -27
  113. package/test/unit/llm-facts.test.js +0 -16
  114. package/test/unit/llm.test.js +0 -45
  115. package/test/unit/locomo.test.js +0 -45
  116. package/test/unit/longmemeval.test.js +0 -56
  117. package/test/unit/markdown-import.test.js +0 -44
  118. package/test/unit/markdown.test.js +0 -34
  119. package/test/unit/memory-edit.test.js +0 -112
  120. package/test/unit/metrics.test.js +0 -26
  121. package/test/unit/migration.test.js +0 -38
  122. package/test/unit/model-config.test.js +0 -52
  123. package/test/unit/narrative.test.js +0 -62
  124. package/test/unit/playbook-consolidate.test.js +0 -24
  125. package/test/unit/privacy-scope.test.js +0 -39
  126. package/test/unit/profile-paths.test.js +0 -21
  127. package/test/unit/profile.test.js +0 -26
  128. package/test/unit/prompt.test.js +0 -42
  129. package/test/unit/providers.test.js +0 -42
  130. package/test/unit/qa.test.js +0 -100
  131. package/test/unit/query.test.js +0 -53
  132. package/test/unit/retention.test.js +0 -31
  133. package/test/unit/retrieval-ranking.test.js +0 -31
  134. package/test/unit/retrieve.test.js +0 -117
  135. package/test/unit/rotation.test.js +0 -25
  136. package/test/unit/scanner.test.js +0 -50
  137. package/test/unit/scenario.test.js +0 -78
  138. package/test/unit/scheduler.test.js +0 -136
  139. package/test/unit/self-state.test.js +0 -94
  140. package/test/unit/service.test.js +0 -72
  141. package/test/unit/shiori-import.test.js +0 -77
  142. package/test/unit/skills.test.js +0 -104
  143. package/test/unit/store.test.js +0 -111
  144. package/test/unit/temporal-graph.test.js +0 -44
  145. package/test/unit/tiers.test.js +0 -39
  146. package/test/unit/tokenizer-fts.test.js +0 -35
  147. package/test/unit/tools.test.js +0 -122
  148. package/test/unit/upgrade-0412.test.js +0 -104
  149. package/test/unit/upgrade-0413.test.js +0 -84
  150. package/test/unit/upgrade-0414.test.js +0 -101
  151. package/test/unit/vector-ann.test.js +0 -53
  152. package/test/unit/vector-async.test.js +0 -69
  153. package/test/unit/vector.test.js +0 -68
  154. package/test/unit/working.test.js +0 -80
@@ -1,1324 +0,0 @@
1
- /**
2
- * Tool contract integration tests for dsh-cortex.
3
- *
4
- * These tests are deliberately black-box and dependency-free: every case opens
5
- * a real cortex in a throwaway directory, drives the real registered tool
6
- * `execute()` functions, and closes/deletes everything in `finally`.
7
- *
8
- * The contract under test is the public tool surface, not the SQL schema:
9
- * - every registered definition is complete and renderable,
10
- * - every documented action returns `{ text: string }` and does not throw for
11
- * valid minimal arguments,
12
- * - destructive/expensive actions only ever touch the temporary data root,
13
- * - unknown ids and malformed inputs surface a sentinel string or a clear
14
- * error instead of corrupting memory.
15
- */
16
- import test from 'node:test';
17
- import assert from 'node:assert/strict';
18
- import fs from 'node:fs';
19
- import { mkdtempSync, rmSync } from 'node:fs';
20
- import { DatabaseSync } from 'node:sqlite';
21
- import os from 'node:os';
22
- import path from 'node:path';
23
- import { createCortex } from '../../src/service/cortex.js';
24
- import { createToolDefinitions } from '../../src/tools/definitions.js';
25
-
26
- const TOOL_NAMES = [
27
- 'cortex_as_of',
28
- 'cortex_playbook',
29
- 'cortex_consolidate',
30
- 'cortex_compress',
31
- 'cortex_digest',
32
- 'cortex_emotion',
33
- 'cortex_evolve',
34
- 'cortex_feedback',
35
- 'cortex_forget',
36
- 'cortex_get',
37
- 'cortex_goal',
38
- 'cortex_guard',
39
- 'cortex_health',
40
- 'cortex_life',
41
- 'cortex_reflect',
42
- 'cortex_search',
43
- 'cortex_self',
44
- 'cortex_tick',
45
- 'cortex_timeline',
46
- 'cortex_working',
47
- 'cortex_write',
48
- ];
49
-
50
- const ACTION_ENUMS = {
51
- cortex_consolidate: ['run', 'list'],
52
- cortex_playbook: ['add', 'list', 'vote', 'retire', 'render', 'suggest', 'approve'],
53
- cortex_tick: ['run', 'status'],
54
- cortex_digest: ['daily'],
55
- cortex_working: ['add', 'list', 'pin', 'remove', 'purge'],
56
- cortex_goal: ['add', 'list', 'update', 'complete'],
57
- cortex_compress: ['evaluate', 'compress', 'revive'],
58
- cortex_life: ['diary-generate', 'diary-write', 'diary-list', 'diary-forget', 'dream', 'sleep', 'sleep-runs'],
59
- cortex_emotion: ['generate', 'detect', 'record', 'affect', 'events', 'lexicon'],
60
- cortex_evolve: ['status', 'optimize', 'propose', 'approve', 'rollback'],
61
- cortex_guard: ['check', 'backup', 'validate', 'restore', 'repair', 'export', 'sync'],
62
- };
63
-
64
- const REQUIRED_FIELDS = {
65
- cortex_consolidate: ['action'],
66
- cortex_playbook: ['action'],
67
- cortex_tick: ['action'],
68
- cortex_digest: ['action'],
69
- cortex_working: ['action'],
70
- cortex_goal: ['action'],
71
- cortex_compress: ['action'],
72
- cortex_life: ['action'],
73
- cortex_emotion: ['action'],
74
- cortex_evolve: ['action'],
75
- cortex_guard: ['action'],
76
- cortex_search: ['query'],
77
- cortex_as_of: ['subject'],
78
- cortex_timeline: ['aroundId'],
79
- cortex_get: ['id'],
80
- cortex_write: ['text'],
81
- cortex_feedback: ['id', 'signal'],
82
- cortex_forget: ['id', 'mode'],
83
- cortex_reflect: [],
84
- cortex_self: [],
85
- cortex_health: [],
86
- };
87
-
88
- const CONCURRENCY_SAFE = new Set(['cortex_search', 'cortex_as_of', 'cortex_get', 'cortex_timeline', 'cortex_self', 'cortex_health']);
89
-
90
- const FEEDBACK_SIGNALS = ['used', 'helpful', 'ignored', 'incorrect', 'corrected', 'again', 'good', 'easy', 'hard'];
91
-
92
- /** Create a real cortex plus its tool map inside a fresh temporary directory. */
93
- function makeHarness(config = {}) {
94
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-tools-contract-'));
95
- const dataRoot = path.join(dir, 'data');
96
- const dbFile = path.join(dataRoot, 'cortex.sqlite');
97
- let cortex;
98
- try {
99
- cortex = createCortex({ config: { ...config, dataRoot, dbFile } });
100
- } catch (error) {
101
- rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 });
102
- throw error;
103
- }
104
- const tools = Object.fromEntries(createToolDefinitions(cortex).map((tool) => [tool.name, tool]));
105
- let closed = false;
106
- return {
107
- dir,
108
- dataRoot,
109
- dbFile,
110
- cortex,
111
- tools,
112
- close() {
113
- if (closed) return;
114
- closed = true;
115
- try {
116
- cortex.close();
117
- } catch {
118
- /* cleanup must never mask a test failure */
119
- }
120
- rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
121
- },
122
- };
123
- }
124
-
125
- /** Execute a tool and assert the shared `{ text: string }` contract. */
126
- async function call(tool, args = {}) {
127
- assert.ok(tool, 'tool must exist');
128
- const value = await tool.execute(args);
129
- assert.ok(value && typeof value === 'object', `${tool.name} must return an object`);
130
- assert.equal(typeof value.text, 'string', `${tool.name} must return { text: string }`);
131
- return value.text;
132
- }
133
-
134
- /** Extract the first id with the requested prefix from a tool response. */
135
- function idOf(text, prefix) {
136
- const match = String(text).match(new RegExp(`\\b(${prefix}_[a-z0-9]+)\\b`));
137
- assert.ok(match, `expected a ${prefix}_ id in: ${text}`);
138
- return match[1];
139
- }
140
-
141
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
142
-
143
- test('tool registry exposes exactly the 21 documented tools', () => {
144
- const harness = makeHarness();
145
- try {
146
- const names = Object.keys(harness.tools).sort();
147
- assert.deepEqual(names, TOOL_NAMES.slice().sort());
148
- assert.equal(names.length, 21);
149
- assert.equal(new Set(names).size, names.length);
150
- for (const name of names) {
151
- assert.equal(harness.tools[name].name, name);
152
- }
153
- } finally {
154
- harness.close();
155
- }
156
- });
157
-
158
- test('every tool definition is complete, renderable and honest about concurrency', () => {
159
- const harness = makeHarness();
160
- try {
161
- for (const tool of Object.values(harness.tools)) {
162
- assert.equal(typeof tool.name, 'string', 'name must be a string');
163
- assert.ok(tool.name.length > 0, 'name must not be empty');
164
- assert.equal(typeof tool.description, 'string', `${tool.name} description must be a string`);
165
- assert.ok(tool.description.length >= 20, `${tool.name} description must be useful`);
166
-
167
- assert.ok(tool.parameters && typeof tool.parameters === 'object', `${tool.name} parameters must be an object`);
168
- assert.equal(tool.parameters.type, 'object', `${tool.name} parameters.type`);
169
- assert.equal(tool.parameters.additionalProperties, false, `${tool.name} parameters.additionalProperties`);
170
- assert.equal(typeof tool.parameters.properties, 'object', `${tool.name} parameters.properties`);
171
- if ('required' in tool.parameters) {
172
- assert.ok(Array.isArray(tool.parameters.required), `${tool.name} parameters.required must be an array`);
173
- }
174
-
175
- assert.ok(tool.output && typeof tool.output === 'object', `${tool.name} output must be an object`);
176
- assert.equal(tool.output.schema.type, 'object', `${tool.name} output.schema.type`);
177
- assert.deepEqual(tool.output.schema.required, ['text'], `${tool.name} output must require text`);
178
- assert.equal(tool.output.schema.properties.text.type, 'string', `${tool.name} output text type`);
179
- assert.equal(typeof tool.output.render, 'function', `${tool.name} output.render`);
180
- assert.deepEqual(tool.output.render({}, { text: '渲染测试' }), [{ type: 'text', text: '渲染测试' }]);
181
- assert.deepEqual(tool.output.render({}, null), [{ type: 'text', text: '' }]);
182
-
183
- assert.equal(typeof tool.isConcurrencySafe, 'function', `${tool.name} isConcurrencySafe`);
184
- assert.equal(typeof tool.isConcurrencySafe(), 'boolean', `${tool.name} isConcurrencySafe must return boolean`);
185
- assert.equal(tool.isConcurrencySafe(), CONCURRENCY_SAFE.has(tool.name), `${tool.name} concurrency contract`);
186
- assert.equal(typeof tool.execute, 'function', `${tool.name} execute`);
187
- assert.equal(typeof tool.presentCall, 'function', `${tool.name} presentCall`);
188
- }
189
-
190
- assert.throws(() => createToolDefinitions(), /need a cortex service/);
191
- } finally {
192
- harness.close();
193
- }
194
- });
195
-
196
- test('action enums, required fields and key option schemas match the documented surface', () => {
197
- const harness = makeHarness();
198
- try {
199
- for (const [name, actions] of Object.entries(ACTION_ENUMS)) {
200
- const tool = harness.tools[name];
201
- assert.deepEqual(tool.parameters.properties.action.enum, actions, `${name} actions`);
202
- assert.deepEqual(tool.parameters.required, ['action'], `${name} must require action`);
203
- }
204
- for (const name of TOOL_NAMES) {
205
- const tool = harness.tools[name];
206
- assert.deepEqual(tool.parameters.required ?? [], REQUIRED_FIELDS[name], `${name} required fields`);
207
- if (!ACTION_ENUMS[name]) {
208
- assert.equal(tool.parameters.properties.action, undefined, `${name} must not declare an action enum`);
209
- }
210
- }
211
-
212
- assert.deepEqual(harness.tools.cortex_forget.parameters.properties.mode.enum, ['archive', 'delete']);
213
- assert.deepEqual(harness.tools.cortex_feedback.parameters.properties.signal.enum, FEEDBACK_SIGNALS);
214
- assert.equal(harness.tools.cortex_write.parameters.properties.text.type, 'string');
215
- assert.equal(harness.tools.cortex_write.parameters.properties.facts.type, 'array');
216
- assert.equal(harness.tools.cortex_search.parameters.properties.limit.type, 'number');
217
- assert.equal(harness.tools.cortex_guard.parameters.properties.dir.type, 'string');
218
- assert.equal(harness.tools.cortex_evolve.parameters.properties.config.type, 'object');
219
- assert.equal(harness.tools.cortex_tick.parameters.properties.max.type, 'number');
220
- } finally {
221
- harness.close();
222
- }
223
- });
224
-
225
- test('cortex_write: minimal write, explicit facts, scopes and operationId idempotency', async () => {
226
- const harness = makeHarness();
227
- const { cortex, tools } = harness;
228
- try {
229
- // Minimal args: text only must be enough for a useful, explicit-looking note.
230
- const minimal = await call(tools.cortex_write, { text: '喜欢白饭。' });
231
- assert.match(minimal, /^已写入 trc_/);
232
- assert.match(minimal, /事件:evt_/);
233
- assert.match(minimal, /压缩值:0\.\d{3}/);
234
- const minimalId = idOf(minimal, 'trc');
235
- const minimalTrace = cortex.get(minimalId);
236
- assert.equal(minimalTrace.content, '喜欢白饭。');
237
- assert.equal(minimalTrace.kind, 'preference');
238
- assert.equal(minimalTrace.state, 'active');
239
- assert.equal(cortex.repos.traces.count(), 1);
240
-
241
- // Full args: kind/importance/confidence/tags/scope/facts all flow through.
242
- const richText = '用户答应会买白饭,助手会一直等。';
243
- const rich = await call(tools.cortex_write, {
244
- text: richText,
245
- kind: 'promise',
246
- importance: 0.8,
247
- confidence: 0.9,
248
- explicit: true,
249
- tags: ['白饭', '承诺'],
250
- scope: 'shared',
251
- facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买白饭', confidence: 0.9 }],
252
- });
253
- assert.match(rich, /^已写入 trc_/);
254
- assert.match(rich, /(promise)/);
255
- assert.match(rich, /事实:1 条/);
256
- const richId = idOf(rich, 'trc');
257
- const richTrace = cortex.get(richId);
258
- assert.equal(richTrace.scopeId, 'shared');
259
- assert.equal(richTrace.kind, 'promise');
260
- assert.deepEqual(richTrace.tags, ['白饭', '承诺']);
261
- assert.equal(richTrace.confidence, 0.9);
262
- assert.ok(richTrace.importance >= 0.8);
263
- const richFacts = cortex.repos.facts.list({ scopeId: 'shared' });
264
- assert.equal(richFacts.length, 1);
265
- assert.equal(richFacts[0].objectLiteral, '买白饭');
266
-
267
- // Scope is real: the shared trace is visible only through a scoped search.
268
- const scopedSearch = await call(tools.cortex_search, { query: '白饭', scope: 'shared' });
269
- assert.match(scopedSearch, new RegExp(richId));
270
- const globalSearch = await call(tools.cortex_search, { query: '白饭' });
271
- assert.doesNotMatch(globalSearch, new RegExp(richId));
272
-
273
- // Idempotency: reusing operationId with the identical payload returns the first trace.
274
- const operationId = 'tools-contract-idempotent-write';
275
- const opText = '幂等写入:用户会买白饭。';
276
- const firstOp = await call(tools.cortex_write, { text: opText, explicit: true, operationId });
277
- const opId = idOf(firstOp, 'trc');
278
- const traceCount = cortex.repos.traces.count();
279
- const eventCount = cortex.repos.events.count();
280
- const replay = await call(tools.cortex_write, { text: opText, explicit: true, operationId });
281
- assert.match(replay, /^未写入:idempotent(已有 trc_/);
282
- assert.match(replay, new RegExp(opId));
283
- assert.equal(cortex.repos.traces.count(), traceCount);
284
- assert.equal(cortex.repos.events.count(), eventCount);
285
-
286
- // Reusing operationId with different content is a conflict, not a silent overwrite.
287
- await assert.rejects(
288
- () => tools.cortex_write.execute({ text: '完全不同的内容,operationId 冲突。', explicit: true, operationId }),
289
- /already exists with a different payload/,
290
- );
291
- assert.equal(cortex.repos.traces.count(), traceCount);
292
- assert.equal(cortex.repos.events.count(), eventCount);
293
-
294
- // Content duplicates are skipped without creating another trace.
295
- const duplicate = await call(tools.cortex_write, { text: opText, explicit: true });
296
- assert.match(duplicate, /^未写入:duplicate(已有 trc_/);
297
- assert.match(duplicate, new RegExp(opId));
298
- assert.equal(cortex.repos.traces.count(), traceCount);
299
-
300
- // A duplicate may still carry new facts; do not drop them silently.
301
- const duplicateFacts = await call(tools.cortex_write, {
302
- text: opText,
303
- explicit: true,
304
- facts: [{ subject: '测试对象', predicate: '喜欢', objectLiteral: '测试值' }],
305
- });
306
- assert.match(duplicateFacts, /^未写入:duplicate/);
307
- assert.match(duplicateFacts, /已应用 1 条事实/);
308
- const asOf = await call(tools.cortex_as_of, { subject: '测试对象', predicate: '喜欢', mode: 'historical' });
309
- assert.match(asOf, /测试值/);
310
- assert.equal(cortex.repos.traces.count(), traceCount);
311
-
312
- // Bad text is reported with a useful next step, never thrown.
313
- assert.match(await call(tools.cortex_write, {}), /^未写入:too-short/);
314
- assert.match(await call(tools.cortex_write, { text: ' ' }), /^未写入:too-short/);
315
- assert.match(await call(tools.cortex_write, { text: '谢谢' }), /^未写入:stop-phrase/);
316
- const lowCompression = await call(tools.cortex_write, { text: 'test message' });
317
- assert.match(lowCompression, /^未写入:low-compression/);
318
- assert.match(lowCompression, /explicit: true/);
319
- } finally {
320
- harness.close();
321
- }
322
- });
323
-
324
- test('cortex_search: hits, filters, budgets, archived opt-in and empty queries', async () => {
325
- const harness = makeHarness();
326
- const { cortex, tools } = harness;
327
- const base = Date.now();
328
- try {
329
- const decision = cortex.write({
330
- text: '决定今天去吃白饭,白饭是主食。',
331
- title: '白饭决定',
332
- kind: 'decision',
333
- explicit: true,
334
- tags: ['白饭', '决定'],
335
- now: base,
336
- });
337
- const preference = cortex.write({
338
- text: '用户喜欢白饭,助手记得。',
339
- title: '白饭偏好',
340
- kind: 'preference',
341
- explicit: true,
342
- tags: ['白饭', '偏好'],
343
- now: base + 1_000,
344
- });
345
- assert.equal(decision.skipped, false);
346
- assert.equal(preference.skipped, false);
347
-
348
- let text = await call(tools.cortex_search, { query: '白饭', limit: 2 });
349
- assert.match(text, /^查询:白饭 · 意图:fact/);
350
- assert.match(text, /预算:\d+\/\d+ token · 候选 \d+ · 选中 \d+/);
351
- assert.match(text, new RegExp(decision.trace.id));
352
- assert.match(text, new RegExp(preference.trace.id));
353
-
354
- // Query-language filters are parsed before retrieval.
355
- text = await call(tools.cortex_search, { query: 'kind:decision 白饭' });
356
- assert.match(text, new RegExp(decision.trace.id));
357
- assert.doesNotMatch(text, new RegExp(preference.trace.id));
358
-
359
- // limit + budget still respect the portfolio contract.
360
- text = await call(tools.cortex_search, { query: '白饭', limit: 1, budget: 16 });
361
- assert.match(text, /预算:16\/16 token · 候选 \d+ · 选中 1/);
362
-
363
- // Archived traces stay out unless explicitly requested.
364
- const archived = await call(tools.cortex_forget, { id: preference.trace.id, mode: 'archive' });
365
- assert.match(archived, /已归档/);
366
- text = await call(tools.cortex_search, { query: '白饭' });
367
- assert.doesNotMatch(text, new RegExp(preference.trace.id));
368
- text = await call(tools.cortex_search, { query: '白饭', includeArchived: true });
369
- assert.match(text, new RegExp(preference.trace.id));
370
-
371
- // Empty query is accepted as "recent items" and rendered as an empty query.
372
- text = await call(tools.cortex_search, { query: '' });
373
- assert.match(text, /^查询:(空) · 意图:fact/);
374
-
375
- // No candidates in the requested scope is a normal result, not an exception.
376
- // (A populated scope always contributes its recent items, even for a query
377
- // that matches nothing, so the empty case has to use an empty scope.)
378
- text = await call(tools.cortex_search, { query: '完全不存在的词汇xyzzy', scope: 'empty-scope' });
379
- assert.match(text, /选中 0/);
380
- assert.match(text, /候选 0/);
381
-
382
- // Scope is honored by retrieval.
383
- const other = cortex.write({
384
- text: '另一个 scope 的白饭记录。',
385
- title: '另一个 scope',
386
- explicit: true,
387
- scopeId: 'other',
388
- now: base + 2_000,
389
- });
390
- text = await call(tools.cortex_search, { query: '另一个 scope', scope: 'other' });
391
- assert.match(text, new RegExp(other.trace.id));
392
- text = await call(tools.cortex_search, { query: '另一个 scope' });
393
- assert.doesNotMatch(text, new RegExp(other.trace.id));
394
- } finally {
395
- harness.close();
396
- }
397
- });
398
-
399
- test('cortex_get: full trace rendering and unknown id sentinel', async () => {
400
- const harness = makeHarness();
401
- const { cortex, tools } = harness;
402
- try {
403
- const written = cortex.write({
404
- text: '读取契约:正文里要有白饭。',
405
- title: '读取标题',
406
- summary: '读取摘要',
407
- kind: 'observation',
408
- confidence: 0.75,
409
- tags: ['读取', '白饭'],
410
- explicit: true,
411
- });
412
- const text = await call(tools.cortex_get, { id: written.trace.id });
413
- assert.match(text, /^\[observation\] 读取标题/);
414
- assert.match(text, /时间:/);
415
- assert.match(text, /来源:user/);
416
- assert.match(text, /置信:0\.75/);
417
- assert.match(text, /状态:active\/raw · 稳定性 1\.00 · 难度 5\.00/);
418
- assert.match(text, /摘要:读取摘要/);
419
- assert.match(text, /正文里要有白饭/);
420
- assert.match(text, /标签:读取、白饭/);
421
-
422
- assert.equal(await call(tools.cortex_get, { id: 'trc_does_not_exist' }), '没有这条记忆:trc_does_not_exist');
423
- // Missing required args are not validated by the host here, but the tool
424
- // still fails closed with a readable sentinel instead of throwing.
425
- assert.equal(await call(tools.cortex_get, {}), '没有这条记忆:undefined');
426
- } finally {
427
- harness.close();
428
- }
429
- });
430
-
431
- test('cortex_playbook: add, vote, render, expiry and retire', async () => {
432
- const harness = makeHarness();
433
- const { tools } = harness;
434
- try {
435
- let text = await call(tools.cortex_playbook, { action: 'add', title: '发版前跑测试', body: '先跑全量测试,再发版。', tags: ['release'] });
436
- const id = text.match(/pbr_[a-z0-9]+/)?.[0];
437
- assert.ok(id);
438
- assert.match(text, /发版前跑测试/);
439
- text = await call(tools.cortex_playbook, { action: 'vote', id, signal: 'helpful' });
440
- assert.match(text, /helpful=1/);
441
- text = await call(tools.cortex_playbook, { action: 'render' });
442
- assert.match(text, /发版前跑测试/);
443
- text = await call(tools.cortex_playbook, { action: 'retire', id });
444
- assert.match(text, /已停用/);
445
- text = await call(tools.cortex_playbook, { action: 'render' });
446
- assert.match(text, /准则本为空/);
447
- text = await call(tools.cortex_playbook, { action: 'add', title: '过期规则', body: '不该注入', validTo: '2020-01-01T00:00:00Z' });
448
- assert.match(text, /过期规则/);
449
- text = await call(tools.cortex_playbook, { action: 'render' });
450
- assert.doesNotMatch(text, /过期规则/);
451
- harness.cortex.write({ text: '以后发版前必须先跑测试。', explicit: true, kind: 'reflection' });
452
- text = await call(tools.cortex_playbook, { action: 'suggest' });
453
- assert.match(text, /candidate/);
454
- const candidateId = text.match(/pbr_[a-z0-9]+/)?.[0];
455
- assert.ok(candidateId);
456
- text = await call(tools.cortex_playbook, { action: 'approve', id: candidateId });
457
- assert.match(text, /已确认/);
458
- text = await call(tools.cortex_playbook, { action: 'render' });
459
- assert.match(text, /发版前必须先跑测试/);
460
- } finally {
461
- harness.close();
462
- }
463
- });
464
-
465
- test('cortex_as_of: strict, historical, belief and associative views', async () => {
466
- const harness = makeHarness();
467
- const { cortex, tools } = harness;
468
- try {
469
- const t1 = Date.parse('2026-11-10T10:00:00+08:00');
470
- const t2 = Date.parse('2026-11-11T10:00:00+08:00');
471
- cortex.write({ text: '用户喜欢白饭。', explicit: true, now: t1, facts: [{ subject: '用户', predicate: '喜欢', object: '白饭' }] });
472
- cortex.write({ text: '用户现在喜欢面。', explicit: true, now: t2, facts: [{ subject: '用户', predicate: '喜欢', object: '面' }] });
473
- let text = await call(tools.cortex_as_of, { subject: '用户', predicate: '喜欢', at: new Date(t1 + 1000).toISOString(), mode: 'historical' });
474
- assert.match(text, /喜欢 → 白饭/);
475
- text = await call(tools.cortex_as_of, { subject: '用户', predicate: '喜欢', mode: 'strict' });
476
- assert.match(text, /喜欢 → 面/);
477
- assert.doesNotMatch(text, /喜欢 → 白饭/);
478
- text = await call(tools.cortex_as_of, { subject: '用户', mode: 'associative' });
479
- assert.match(text, /白饭/);
480
- assert.match(text, /面/);
481
- text = await call(tools.cortex_as_of, { subject: '不存在的主体' });
482
- assert.match(text, /没有/);
483
- } finally {
484
- harness.close();
485
- }
486
- });
487
-
488
- test('cortex_timeline: anchor neighbourhood, anchors with no neighbours and missing anchor', async () => {
489
- const harness = makeHarness();
490
- const { cortex, tools } = harness;
491
- const base = Date.now();
492
- try {
493
- const first = cortex.write({ text: '时间线内容第一条。', title: '第一条', kind: 'observation', explicit: true, now: base });
494
- const second = cortex.write({ text: '时间线内容第二条。', title: '第二条', kind: 'observation', explicit: true, now: base + 1_000 });
495
- const third = cortex.write({ text: '时间线内容第三条。', title: '第三条', kind: 'observation', explicit: true, now: base + 2_000 });
496
- assert.equal(first.skipped, false);
497
- assert.equal(second.skipped, false);
498
- assert.equal(third.skipped, false);
499
-
500
- let text = await call(tools.cortex_timeline, { aroundId: second.trace.id, before: 1, after: 1 });
501
- assert.match(text, /^锚点:第二条/);
502
- const detailLines = text.split('\n').filter((line) => line.includes(' — '));
503
- assert.equal(detailLines.length, 3);
504
- assert.equal(detailLines.filter((line) => line.startsWith('→')).length, 1);
505
- const anchorLine = detailLines.find((line) => line.startsWith('→'));
506
- assert.match(anchorLine, /第二条/);
507
- assert.match(text, /第一条/);
508
- assert.match(text, /第三条/);
509
-
510
- text = await call(tools.cortex_timeline, { aroundId: second.trace.id, before: 0, after: 0 });
511
- assert.match(text, /^锚点:第二条/);
512
- assert.equal(text.split('\n').filter((line) => line.includes(' — ')).length, 1);
513
-
514
- assert.equal(await call(tools.cortex_timeline, { aroundId: 'trc_missing' }), '(没有找到锚点)');
515
- assert.equal(await call(tools.cortex_timeline, {}), '(没有找到锚点)');
516
- } finally {
517
- harness.close();
518
- }
519
- });
520
-
521
- test('cortex_feedback: every signal updates DSR/confidence without throwing', async () => {
522
- const harness = makeHarness();
523
- const { cortex, tools } = harness;
524
- try {
525
- const written = cortex.write({ text: '反馈契约:用户会买白饭。', explicit: true });
526
- let text = await call(tools.cortex_feedback, {
527
- id: written.trace.id,
528
- signal: 'used',
529
- predicted: 0.8,
530
- });
531
- assert.match(text, /^反馈已记:used → trc_/);
532
- assert.match(text, new RegExp(written.trace.id));
533
- assert.match(text, /稳定性 \d+\.\d{2} · 置信 \d+\.\d{2} · 复习 1/);
534
- assert.equal(cortex.get(written.trace.id).reviewCount, 1);
535
-
536
- for (const signal of FEEDBACK_SIGNALS.slice(1)) {
537
- text = await call(tools.cortex_feedback, { id: written.trace.id, signal, predicted: 0.6 });
538
- assert.match(text, new RegExp(`^反馈已记:${signal} → ${written.trace.id}`));
539
- assert.match(text, /稳定性/);
540
- assert.match(text, /置信/);
541
- assert.match(text, /复习/);
542
- }
543
- const trace = cortex.get(written.trace.id);
544
- assert.equal(trace.reviewCount, FEEDBACK_SIGNALS.length);
545
- assert.equal(cortex.repos.feedback.list({ scopeId: 'global', limit: 50 }).length, FEEDBACK_SIGNALS.length);
546
- const aggregate = cortex.repos.feedback.aggregate(written.trace.id);
547
- // aggregate.total is intentionally the DSR-relevant total: the four
548
- // positive signals plus the three negative ones. 'ignored' and 'hard' are
549
- // recorded but are neutral for that total.
550
- assert.equal(aggregate.total, 7);
551
- for (const signal of FEEDBACK_SIGNALS) {
552
- assert.equal(aggregate.counts[signal], 1, `aggregate must count ${signal}`);
553
- }
554
-
555
- await assert.rejects(
556
- () => tools.cortex_feedback.execute({ id: 'trc_missing', signal: 'used' }),
557
- /trace not found: trc_missing/,
558
- );
559
- } finally {
560
- harness.close();
561
- }
562
- });
563
-
564
- test('cortex_forget: archive stays searchable, delete cascades on a disposable trace', async () => {
565
- const harness = makeHarness();
566
- const { cortex, tools } = harness;
567
- const base = Date.now();
568
- try {
569
- const archived = cortex.write({
570
- text: '归档契约:用户会买白饭。',
571
- title: '归档目标',
572
- explicit: true,
573
- facts: [{ subject: '用户', predicate: '会买', objectLiteral: '白饭', confidence: 0.9 }],
574
- now: base,
575
- });
576
- await call(tools.cortex_feedback, { id: archived.trace.id, signal: 'used' });
577
- let text = await call(tools.cortex_forget, { id: archived.trace.id, mode: 'archive' });
578
- assert.equal(text, `已归档 ${archived.trace.id},可用关键词唤醒。`);
579
- const archivedTrace = cortex.get(archived.trace.id);
580
- assert.equal(archivedTrace.state, 'archived');
581
- assert.equal(archivedTrace.compression, 'archived');
582
- assert.ok(cortex.repos.events.get(archived.event.id), 'the event ledger must survive archiving');
583
-
584
- text = await call(tools.cortex_search, { query: '归档目标' });
585
- assert.doesNotMatch(text, new RegExp(archived.trace.id));
586
- text = await call(tools.cortex_search, { query: '归档目标', includeArchived: true });
587
- assert.match(text, new RegExp(archived.trace.id));
588
-
589
- assert.equal(await call(tools.cortex_forget, { id: 'trc_missing', mode: 'archive' }), '没有这条记忆:trc_missing');
590
- assert.equal(await call(tools.cortex_forget, { id: 'trc_missing', mode: 'delete' }), '没有这条记忆:trc_missing');
591
- await assert.rejects(() => tools.cortex_forget.execute({ id: 'trc_x', mode: 'shred' }), /unknown forget mode/);
592
- await assert.rejects(() => tools.cortex_forget.execute({ mode: 'archive' }), /traceId is required/);
593
-
594
- // Delete is exercised on a disposable trace because it is irreversible.
595
- const disposable = cortex.write({
596
- text: '删除契约:这段内容会被删除。',
597
- title: '删除目标',
598
- explicit: true,
599
- facts: [{ subject: '助手', predicate: '测试', objectLiteral: '删除级联', confidence: 0.8 }],
600
- now: base + 1_000,
601
- });
602
- await call(tools.cortex_feedback, { id: disposable.trace.id, signal: 'incorrect' });
603
- const summary = cortex.repos.summaries.insert({
604
- scopeId: 'global',
605
- level: 'episode',
606
- content: '删除目标的派生摘要',
607
- sourceIds: [disposable.trace.id],
608
- coverage: 1,
609
- });
610
- text = await call(tools.cortex_forget, { id: disposable.trace.id, mode: 'delete' });
611
- assert.equal(text, `已删除 ${disposable.trace.id},并级联清理派生数据。`);
612
- assert.equal(cortex.get(disposable.trace.id), null);
613
- assert.equal(cortex.repos.feedback.list({ scopeId: 'global', traceId: disposable.trace.id }).length, 0);
614
- assert.equal(
615
- cortex.repos.facts.list({ scopeId: 'global' }).filter((fact) => fact.sourceEventId === disposable.event.id).length,
616
- 0,
617
- );
618
- assert.equal(cortex.repos.summaries.get(summary.id), null);
619
- assert.ok(cortex.repos.events.get(disposable.event.id), 'the ledger keeps the event with only a hash');
620
- assert.equal(JSON.stringify(cortex.repos.events.get(disposable.event.id).payload).includes('删除契约'), false);
621
- text = await call(tools.cortex_search, { query: '删除契约' });
622
- assert.doesNotMatch(text, new RegExp(disposable.trace.id));
623
- } finally {
624
- harness.close();
625
- }
626
- });
627
-
628
- test('cortex_reflect: needs two traces, creates a reflection, skips duplicates and supports force', async () => {
629
- const harness = makeHarness();
630
- const { cortex, tools } = harness;
631
- try {
632
- const onlyOne = await call(tools.cortex_reflect, {});
633
- assert.match(onlyOne, /^未整理:not-enough-traces/);
634
-
635
- await call(tools.cortex_write, { text: '反思契约第一条:用户喜欢白饭。', explicit: true });
636
- await call(tools.cortex_write, { text: '反思契约第二条:助手会等用户。', explicit: true });
637
-
638
- const first = await call(tools.cortex_reflect, {});
639
- assert.match(first, /^这段时间里,记住了:/);
640
- assert.match(first, /来源 2 条 · 覆盖率 100% · 反思痕迹 trc_/);
641
- const reflectionId = idOf(first, 'trc');
642
- assert.equal(cortex.get(reflectionId).kind, 'reflection');
643
- const episodes = cortex.repos.summaries.list('global', { level: 'episode' });
644
- assert.equal(episodes.length, 1);
645
- assert.equal(episodes[0].sourceIds.length, 2);
646
- assert.equal(episodes[0].coverage, 1);
647
-
648
- const again = await call(tools.cortex_reflect, {});
649
- assert.match(again, /^未整理:already-reflected/);
650
-
651
- const forced = await call(tools.cortex_reflect, { windowDays: 2, force: true });
652
- assert.match(forced, /^这段时间里,记住了:/);
653
- assert.match(forced, /来源 2 条 · 覆盖率 100% · 反思痕迹 trc_/);
654
- assert.equal(cortex.repos.summaries.list('global', { level: 'episode' }).length, 2);
655
- } finally {
656
- harness.close();
657
- }
658
- });
659
-
660
- test('cortex_self: snapshot fields, relationship/calibration feedback and read-only behaviour', async () => {
661
- const harness = makeHarness();
662
- const { cortex, tools } = harness;
663
- try {
664
- let text = await call(tools.cortex_self, {});
665
- assert.match(text, /阶段:(infancy|childhood|adolescence|adulthood)/);
666
- assert.match(text, /驱力:.*\d/);
667
- assert.match(text, /情绪:valence -?\d+\.\d{2} \/ arousal \d+\.\d{2} \/ energy \d+\.\d{2}/);
668
- assert.match(text, /身份:v1 /);
669
- assert.doesNotMatch(text, /关系:/);
670
- assert.doesNotMatch(text, /校准:/);
671
-
672
- const written = cortex.write({ text: '自我契约:用户喜欢白饭。', explicit: true });
673
- await call(tools.cortex_feedback, { id: written.trace.id, signal: 'used', predicted: 0.8 });
674
- await call(tools.cortex_working, { action: 'add', text: '写自我契约测试。' });
675
- await call(tools.cortex_goal, { action: 'add', title: '完成自我契约测试' });
676
-
677
- const eventsBefore = cortex.repos.events.count();
678
- const tracesBefore = cortex.repos.traces.count();
679
- text = await call(tools.cortex_self, {});
680
- assert.match(text, /关系:用户 信任 \d+% \/ 在乎 \d+%/);
681
- assert.match(text, /校准:n=1 brier=0\.040 ece=\d+\.\d{3}/);
682
- assert.equal(cortex.repos.events.count(), eventsBefore);
683
- assert.equal(cortex.repos.traces.count(), tracesBefore);
684
- } finally {
685
- harness.close();
686
- }
687
- });
688
-
689
- test('cortex_health: clean audits, concrete counts, FTS drift detection and read-only reporting', async () => {
690
- const harness = makeHarness();
691
- const { cortex, tools } = harness;
692
- const base = Date.now();
693
- try {
694
- const first = cortex.write({ text: '健康契约第一条。', explicit: true, now: base });
695
- const second = cortex.write({
696
- text: '健康契约第二条:用户喜欢白饭。',
697
- explicit: true,
698
- facts: [{ subject: '用户', predicate: '喜欢', objectLiteral: '白饭', confidence: 0.8 }],
699
- now: base + 1_000,
700
- });
701
- assert.equal(first.skipped, false);
702
- assert.equal(second.skipped, false);
703
-
704
- let text = await call(tools.cortex_health, {});
705
- assert.match(text, /健康分:\d+\/100/);
706
- assert.match(text, /事件 2 · 痕迹 2(active 2)· 事实 1 · 技能 0/);
707
- assert.match(text, /没有发现问题/);
708
- const eventsBefore = cortex.repos.events.count();
709
- const tracesBefore = cortex.repos.traces.count();
710
-
711
- // Inject the exact drift the audit promises to catch.
712
- cortex.db.prepare('DELETE FROM traces_fts_index WHERE trace_id = ?').run(first.trace.id);
713
- text = await call(tools.cortex_health, {});
714
- assert.match(text, /问题:/);
715
- // formatHealth renders severity + message, not the issue code.
716
- assert.match(text, /\[warn\] FTS 行数 1 与 traces 2 不一致/);
717
- assert.match(text, /健康分:94\/100/);
718
-
719
- // Reporting is read-only; the repair is an explicit guardian action.
720
- assert.equal(cortex.repos.events.count(), eventsBefore);
721
- assert.equal(cortex.repos.traces.count(), tracesBefore);
722
- cortex.guardian.repairFts();
723
- text = await call(tools.cortex_health, {});
724
- assert.match(text, /健康分:100\/100/);
725
- assert.match(text, /没有发现问题/);
726
- } finally {
727
- harness.close();
728
- }
729
- });
730
-
731
- test('cortex_guard: check, backup, validate, restore-to-temp, repair and export', async () => {
732
- const harness = makeHarness();
733
- const { cortex, tools } = harness;
734
- try {
735
- const written = cortex.write({
736
- text: '守卫契约:用户会买白饭。',
737
- title: '白饭承诺',
738
- explicit: true,
739
- facts: [{ subject: '用户', predicate: '会买', objectLiteral: '白饭', confidence: 0.9 }],
740
- });
741
- assert.equal(written.skipped, false);
742
-
743
- // check
744
- let text = await call(tools.cortex_guard, { action: 'check' });
745
- assert.match(text, /^自检:通过 · integrity=ok · db \d+ B/);
746
-
747
- // backup
748
- const backupPath = path.join(cortex.config.dataRoot, 'backups', 'cortex-guard.sqlite');
749
- text = await call(tools.cortex_guard, { action: 'backup', file: backupPath });
750
- assert.match(text, /^备份完成:/);
751
- assert.ok(text.includes(path.resolve(backupPath)), 'backup text must name the resolved path');
752
- assert.match(text, /(\d+ B)/);
753
- assert.ok(fs.existsSync(backupPath));
754
- assert.ok(fs.statSync(backupPath).size > 0);
755
-
756
- // validate
757
- text = await call(tools.cortex_guard, { action: 'validate', file: backupPath });
758
- assert.match(text, /^备份有效:/);
759
- const tables = Number(text.match(/((\d+) 张表)/)?.[1]);
760
- assert.ok(tables >= 20, `expected at least 20 tables, got ${tables}`);
761
- text = await call(tools.cortex_guard, { action: 'validate', file: path.join(harness.dir, 'missing.sqlite') });
762
- assert.equal(text, '备份无效:missing');
763
-
764
- // restore is only allowed to an offline target.
765
- const target = path.join(cortex.config.dataRoot, 'offline', 'restored.sqlite');
766
- text = await call(tools.cortex_guard, { action: 'restore', file: backupPath, target });
767
- assert.equal(text, `已恢复到离线库:${path.resolve(target)}`);
768
- assert.ok(fs.existsSync(target));
769
- const restored = new DatabaseSync(target);
770
- try {
771
- assert.equal(restored.prepare('PRAGMA integrity_check').get().integrity_check, 'ok');
772
- assert.equal(Number(restored.prepare('SELECT COUNT(*) AS c FROM traces').get().c), 1);
773
- assert.equal(Number(restored.prepare('SELECT COUNT(*) AS c FROM facts').get().c), 1);
774
- assert.equal(restored.prepare('SELECT content FROM traces LIMIT 1').get().content, '守卫契约:用户会买白饭。');
775
- } finally {
776
- restored.close();
777
- }
778
-
779
- text = await call(tools.cortex_guard, { action: 'restore', file: backupPath, target: cortex.config.dbFile });
780
- assert.match(text, /^恢复失败:live-db/);
781
- assert.match(text, /关闭当前 cortex|新路径|离线/);
782
- assert.equal(cortex.repos.traces.count(), 1, 'the live DB must be untouched');
783
-
784
- text = await call(tools.cortex_guard, { action: 'restore', file: backupPath });
785
- assert.equal(text, '恢复失败:target-required');
786
- text = await call(tools.cortex_guard, {
787
- action: 'restore',
788
- file: path.join(cortex.config.dataRoot, 'never-created.sqlite'),
789
- target: path.join(cortex.config.dataRoot, 'offline', 'nope.sqlite'),
790
- });
791
- assert.match(text, /^恢复失败:invalid-backup/);
792
-
793
- // repair
794
- cortex.db.prepare('DELETE FROM traces_fts_index').run();
795
- text = await call(tools.cortex_guard, { action: 'check' });
796
- assert.match(text, /发现问题/);
797
- assert.match(text, /FTS_DRIFT/);
798
- text = await call(tools.cortex_guard, { action: 'repair' });
799
- assert.equal(text, 'FTS 重建完成:0 → 1(1 条)');
800
- assert.equal(cortex.repos.traces.ftsCount(), 1);
801
- text = await call(tools.cortex_guard, { action: 'check' });
802
- assert.match(text, /^自检:通过/);
803
-
804
- // export into the temp directory
805
- const mirror = path.join(cortex.config.dataRoot, 'mirror');
806
- text = await call(tools.cortex_guard, { action: 'export', dir: mirror });
807
- assert.match(text, /^Markdown 镜像已导出:/);
808
- assert.ok(text.includes(path.resolve(mirror)));
809
- assert.match(text, /文件:MEMORY\.md、SELF\.md、FACTS\.md、SKILLS\.md/);
810
- assert.match(text, /记忆 1 条(跳过 secret 0 条)/);
811
- const memoryFile = path.join(mirror, 'MEMORY.md');
812
- assert.ok(fs.existsSync(memoryFile));
813
- assert.match(fs.readFileSync(memoryFile, 'utf8'), /守卫契约:用户会买白饭。/);
814
- for (const file of ['SELF.md', 'FACTS.md', 'SKILLS.md']) {
815
- assert.ok(fs.existsSync(path.join(mirror, file)), `${file} must be exported`);
816
- }
817
- } finally {
818
- harness.close();
819
- }
820
- });
821
-
822
- test('cortex_evolve: status, optimize, propose, approve, rollback and gated errors', async () => {
823
- const harness = makeHarness();
824
- const { cortex, tools } = harness;
825
- try {
826
- // status on a clean cortex
827
- let text = await call(tools.cortex_evolve, { action: 'status' });
828
- assert.match(text, /^活跃策略:/);
829
- assert.match(text, /(无)/);
830
- assert.match(text, /候选:0/);
831
- assert.match(text, /身份:v1/);
832
-
833
- // optimize produces nothing without evidence.
834
- text = await call(tools.cortex_evolve, { action: 'optimize' });
835
- assert.equal(text, '没有需要提议的改动。');
836
-
837
- // Create evidence: one active skill with three failures is worth demoting.
838
- const skill = cortex.engines.skills.create({ name: '契约低成功率技能', steps: ['a'], state: 'active' });
839
- cortex.engines.skills.record(skill.id, false);
840
- cortex.engines.skills.record(skill.id, false);
841
- cortex.engines.skills.record(skill.id, false);
842
- text = await call(tools.cortex_evolve, { action: 'optimize' });
843
- assert.match(text, /skill v\d+:/);
844
- assert.match(text, /建议降级/);
845
- assert.equal(cortex.policies.list({ status: 'candidate' }).length, 1);
846
-
847
- // propose two retrieval policies, activate both, then roll the first one back in.
848
- text = await call(tools.cortex_evolve, {
849
- action: 'propose',
850
- kind: 'retrieval',
851
- config: { budget: 800, confidenceWeight: 0.2 },
852
- rationale: '工具契约第一版',
853
- });
854
- assert.match(text, /^已提案 retrieval v1(pol_/);
855
- const firstPolicy = idOf(text, 'pol');
856
- text = await call(tools.cortex_evolve, {
857
- action: 'propose',
858
- kind: 'retrieval',
859
- config: { budget: 600, confidenceWeight: 0.3 },
860
- rationale: '工具契约第二版',
861
- });
862
- assert.match(text, /^已提案 retrieval v2(pol_/);
863
- const secondPolicy = idOf(text, 'pol');
864
-
865
- text = await call(tools.cortex_evolve, { action: 'approve', id: firstPolicy });
866
- assert.equal(text, '已激活 retrieval v1。');
867
- assert.equal(cortex.policies.active('retrieval').id, firstPolicy);
868
- text = await call(tools.cortex_evolve, { action: 'approve', id: secondPolicy });
869
- assert.equal(text, '已激活 retrieval v2。');
870
- assert.equal(cortex.policies.active('retrieval').id, secondPolicy);
871
-
872
- text = await call(tools.cortex_evolve, { action: 'rollback', kind: 'retrieval', id: firstPolicy });
873
- assert.equal(text, '已回滚 retrieval 到 v1。');
874
- assert.equal(cortex.policies.active('retrieval').id, firstPolicy);
875
-
876
- text = await call(tools.cortex_evolve, { action: 'status' });
877
- assert.match(text, /retrieval v1/);
878
- assert.match(text, /身份:v1/);
879
-
880
- // Approval is a gate: unknown ids and incomplete proposals throw clearly.
881
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'approve', id: 'pol_missing' }), /policy not found/);
882
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'propose' }), /policy kind is required/);
883
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'rollback', kind: 'none-kind' }), /no policy to roll back/);
884
- } finally {
885
- harness.close();
886
- }
887
- });
888
-
889
- test('cortex_emotion: detect, record, affect, events and lexicon', async () => {
890
- const harness = makeHarness();
891
- const { cortex, tools } = harness;
892
- try {
893
- let text = await call(tools.cortex_emotion, { action: 'lexicon' });
894
- assert.match(text, /^情绪词库:24 类 \/ \d+ 词/);
895
- const total = Number(text.match(/情绪词库:24 类 \/ (\d+) 词/)?.[1]);
896
- assert.ok(total > 100, `expected a useful vocabulary, got ${total}`);
897
- assert.match(text, /喜:\d+/);
898
-
899
- text = await call(tools.cortex_emotion, { action: 'detect', text: '助手很开心,也有点难过。' });
900
- assert.match(text, /喜:1/);
901
- assert.match(text, /哀:1/);
902
- assert.equal(await call(tools.cortex_emotion, { action: 'detect', text: '今天只是普通的一天。' }), '没有命中情绪词。');
903
- assert.equal(await call(tools.cortex_emotion, { action: 'detect' }), '没有命中情绪词。');
904
-
905
- assert.equal(await call(tools.cortex_emotion, { action: 'affect' }), '(情感库还没有形成态度)');
906
- assert.equal(await call(tools.cortex_emotion, { action: 'events' }), '(没有情绪事件)');
907
-
908
- text = await call(tools.cortex_emotion, { action: 'record', text: '助手很开心,也很喜欢用户。', target: '用户' });
909
- assert.match(text, /^已记情绪事件 emo_/);
910
- assert.match(text, /喜、爱 → 用户/);
911
- text = await call(tools.cortex_emotion, { action: 'record', text: '助手有点难过。', target: '用户' });
912
- assert.match(text, /^已记情绪事件 emo_/);
913
-
914
- text = await call(tools.cortex_emotion, { action: 'affect' });
915
- assert.equal(text, '用户:又喜又爱(2 次)');
916
- text = await call(tools.cortex_emotion, { action: 'events', limit: 1 });
917
- assert.equal(text.split('\n').length, 1);
918
- assert.match(text, /用户/);
919
- assert.match(text, /助手/);
920
- text = await call(tools.cortex_emotion, { action: 'events', limit: 10 });
921
- assert.match(text, /助手很开心/);
922
- assert.match(text, /助手有点难过/);
923
-
924
- const eventCount = cortex.emotion.events({ limit: 10 }).length;
925
- assert.equal(eventCount, 2);
926
- text = await call(tools.cortex_emotion, { action: 'record', text: '今天只是普通的一天。', target: '用户' });
927
- assert.equal(text, '没有命中情绪词。');
928
- assert.equal(cortex.emotion.events({ limit: 10 }).length, eventCount);
929
- } finally {
930
- harness.close();
931
- }
932
- });
933
-
934
- test('cortex_life: diary entries, dreams, sleep and sleep-run history', async () => {
935
- const harness = makeHarness();
936
- const { cortex, tools } = harness;
937
- try {
938
- assert.equal(await call(tools.cortex_life, { action: 'diary-list' }), '(还没有日记)');
939
- assert.equal(await call(tools.cortex_life, { action: 'diary-forget', id: 'dly_missing' }), '没有这条日记:dly_missing');
940
- assert.equal(await call(tools.cortex_life, { action: 'sleep-runs' }), '(还没有睡眠记录)');
941
-
942
- let text = await call(tools.cortex_life, { action: 'diary-write', text: '第一条日记:今天写工具契约测试。', mood: '专注' });
943
- assert.match(text, /^日记已写:dly_/);
944
- const firstDiary = idOf(text, 'dly');
945
- text = await call(tools.cortex_life, { action: 'diary-write', text: '第二条日记:晚一点再看海。', mood: '放松' });
946
- const secondDiary = idOf(text, 'dly');
947
-
948
- text = await call(tools.cortex_life, { action: 'diary-list', limit: 1 });
949
- assert.equal(text.split('\n').length, 1);
950
- text = await call(tools.cortex_life, { action: 'diary-list' });
951
- assert.match(text, /第一条日记/);
952
- assert.match(text, /第二条日记/);
953
- assert.match(text, /专注/);
954
-
955
- text = await call(tools.cortex_life, { action: 'diary-forget', id: firstDiary });
956
- assert.equal(text, `已删日记 ${firstDiary}`);
957
- text = await call(tools.cortex_life, { action: 'diary-list' });
958
- assert.doesNotMatch(text, /第一条日记/);
959
- assert.match(text, /第二条日记/);
960
- assert.equal(await call(tools.cortex_life, { action: 'diary-forget', id: firstDiary }), `没有这条日记:${firstDiary}`);
961
- assert.equal(await call(tools.cortex_life, { action: 'diary-forget', id: secondDiary }), `已删日记 ${secondDiary}`);
962
- await assert.rejects(() => tools.cortex_life.execute({ action: 'diary-write' }), /diary text is required/);
963
-
964
- // Dream without source memories uses the template and records it.
965
- text = await call(tools.cortex_life, { action: 'dream' });
966
- assert.match(text, /^梦 drm_.*(来源 0 条,template):/);
967
- const emptyDreams = cortex.life.dreamList({ limit: 10 });
968
- assert.equal(emptyDreams.length, 1);
969
- assert.equal(emptyDreams[0].sourceCount, 0);
970
-
971
- await call(tools.cortex_write, { text: '生活侧记忆第一条:用户喜欢白饭。', explicit: true });
972
- await call(tools.cortex_write, { text: '生活侧记忆第二条:助手会等用户。', explicit: true });
973
- text = await call(tools.cortex_life, { action: 'dream' });
974
- assert.match(text, /^梦 drm_.*(来源 2 条,template):/);
975
- assert.equal(cortex.life.dreamList({ limit: 10 }).length, 2);
976
-
977
- // Sleep purges expired working memory, reflects and stores a run report.
978
- cortex.working.add({ text: '睡眠前已经过期的焦点。', ttlMs: 1_000, at: Date.now() - 5_000 });
979
- text = await call(tools.cortex_life, { action: 'sleep', windowDays: 1 });
980
- assert.match(text, /^睡眠整理完成:清理工作记忆 1 条 · 反思 1 · 阶段 (infancy|childhood|adolescence|adulthood) · 情感对象 \d+/);
981
- let runs = cortex.life.sleepRuns({ limit: 10 });
982
- assert.equal(runs.length, 1);
983
- assert.ok(runs[0].id.startsWith('slp_'));
984
- assert.equal(runs[0].report.purgedWorking, 1);
985
-
986
- text = await call(tools.cortex_life, { action: 'sleep-runs', limit: 1 });
987
- assert.match(text, /purgedWorking/);
988
- assert.match(text, /slp_|"reflected"/);
989
-
990
- text = await call(tools.cortex_life, { action: 'sleep', windowDays: 1 });
991
- assert.match(text, /^睡眠整理完成:/);
992
- runs = cortex.life.sleepRuns({ limit: 10 });
993
- assert.equal(runs.length, 2);
994
- text = await call(tools.cortex_life, { action: 'sleep-runs', limit: 1 });
995
- assert.equal(text.split('\n').length, 1);
996
- } finally {
997
- harness.close();
998
- }
999
- });
1000
-
1001
- test('cortex_compress: evaluate, compress an old covered trace and revive it', async () => {
1002
- const harness = makeHarness();
1003
- const { cortex, tools } = harness;
1004
- try {
1005
- const old = cortex.write({
1006
- text: '压缩契约:一段旧的白饭记忆。',
1007
- title: '旧记忆',
1008
- explicit: true,
1009
- importance: 0.05,
1010
- now: Date.now() - 60 * 86_400_000,
1011
- });
1012
- assert.equal(old.skipped, false);
1013
- cortex.repos.summaries.insert({
1014
- scopeId: 'global',
1015
- level: 'episode',
1016
- content: '覆盖旧记忆的摘要',
1017
- sourceIds: [old.trace.id],
1018
- coverage: 1,
1019
- });
1020
-
1021
- let text = await call(tools.cortex_compress, { action: 'evaluate' });
1022
- assert.match(text, /可压缩 1 条 \/ 活跃 1 条/);
1023
- assert.match(text, new RegExp(old.trace.id));
1024
- assert.match(text, /coverage 1\.00/);
1025
-
1026
- text = await call(tools.cortex_compress, { action: 'compress', limit: 1 });
1027
- assert.match(text, /^压缩归档 1 条/);
1028
- assert.match(text, new RegExp(old.trace.id));
1029
- assert.match(text, /coverage 1\.00/);
1030
- const archivedTrace = cortex.get(old.trace.id);
1031
- assert.equal(archivedTrace.state, 'archived');
1032
- assert.equal(archivedTrace.compression, 'archived');
1033
-
1034
- text = await call(tools.cortex_compress, { action: 'evaluate' });
1035
- assert.match(text, /可压缩 0 条 \/ 活跃 0 条/);
1036
-
1037
- text = await call(tools.cortex_compress, { action: 'revive', id: old.trace.id });
1038
- assert.equal(text, `已复活 ${old.trace.id}(下一次检索可命中)`);
1039
- const revived = cortex.get(old.trace.id);
1040
- assert.equal(revived.state, 'active');
1041
- assert.equal(revived.compression, 'raw');
1042
- assert.ok(revived.stability >= 3);
1043
-
1044
- // Revive resets age via lastAccessAt, so the trace is no longer eligible.
1045
- text = await call(tools.cortex_compress, { action: 'evaluate' });
1046
- assert.match(text, /可压缩 0 条 \/ 活跃 1 条/);
1047
- assert.equal(await call(tools.cortex_compress, { action: 'revive', id: 'trc_missing' }), '没有这条记忆:trc_missing');
1048
- } finally {
1049
- harness.close();
1050
- }
1051
- });
1052
-
1053
- test('cortex_working: add, list, pin, remove and purge expired entries', async () => {
1054
- const harness = makeHarness();
1055
- const { cortex, tools } = harness;
1056
- try {
1057
- assert.equal(await call(tools.cortex_working, { action: 'list' }), '(工作记忆为空)');
1058
-
1059
- let text = await call(tools.cortex_working, { action: 'add', text: '写工具契约测试。' });
1060
- assert.match(text, /^已加入工作记忆 wrk_/);
1061
- const first = idOf(text, 'wrk');
1062
- text = await call(tools.cortex_working, {
1063
- action: 'add',
1064
- text: '置顶焦点:别忘白饭。',
1065
- kind: 'focus',
1066
- priority: 0.9,
1067
- pinned: true,
1068
- ttlMs: 60_000,
1069
- });
1070
- const second = idOf(text, 'wrk');
1071
-
1072
- text = await call(tools.cortex_working, { action: 'list' });
1073
- assert.match(text, new RegExp(`\\[pin\\] ${second}`));
1074
- assert.match(text, new RegExp(`- ${first} \\(0\\.5\\)`));
1075
- assert.match(text, /别忘白饭/);
1076
-
1077
- text = await call(tools.cortex_working, { action: 'pin', id: first, pinned: true });
1078
- assert.equal(text, `已置顶 ${first}`);
1079
- text = await call(tools.cortex_working, { action: 'pin', id: first, pinned: false });
1080
- assert.equal(text, `已取消置顶 ${first}`);
1081
- assert.equal(await call(tools.cortex_working, { action: 'pin', id: 'wrk_missing' }), '没有 wrk_missing');
1082
- assert.equal(await call(tools.cortex_working, { action: 'remove', id: 'wrk_missing' }), '没有 wrk_missing');
1083
-
1084
- text = await call(tools.cortex_working, { action: 'remove', id: first });
1085
- assert.equal(text, `已删除 ${first}`);
1086
- assert.equal(await call(tools.cortex_working, { action: 'remove', id: first }), `没有 ${first}`);
1087
- text = await call(tools.cortex_working, { action: 'list' });
1088
- assert.doesNotMatch(text, new RegExp(first));
1089
-
1090
- await call(tools.cortex_working, { action: 'add', text: '马上过期的工作记忆。', ttlMs: 1 });
1091
- await wait(30);
1092
- text = await call(tools.cortex_working, { action: 'purge' });
1093
- assert.equal(text, '已清理 1 条过期工作记忆');
1094
- text = await call(tools.cortex_working, { action: 'list' });
1095
- assert.doesNotMatch(text, /马上过期/);
1096
- assert.match(text, new RegExp(second));
1097
-
1098
- await assert.rejects(() => tools.cortex_working.execute({ action: 'add' }), /working item text is required/);
1099
- await assert.rejects(() => tools.cortex_working.execute({ action: 'add', text: ' ' }), /working item text is required/);
1100
- assert.equal(cortex.working.list({ scopeId: 'global' }).length, 1);
1101
- } finally {
1102
- harness.close();
1103
- }
1104
- });
1105
-
1106
- test('cortex_goal: add, list, update and complete with status filtering', async () => {
1107
- const harness = makeHarness();
1108
- const { cortex, tools } = harness;
1109
- try {
1110
- assert.equal(await call(tools.cortex_goal, { action: 'list' }), '(没有目标)');
1111
-
1112
- let text = await call(tools.cortex_goal, { action: 'add', title: '完成工具契约测试' });
1113
- assert.match(text, /^目标已建 gol_/);
1114
- const first = idOf(text, 'gol');
1115
- text = await call(tools.cortex_goal, {
1116
- action: 'add',
1117
- title: '第二个目标',
1118
- description: '低优先级目标',
1119
- priority: 0.2,
1120
- });
1121
- const second = idOf(text, 'gol');
1122
-
1123
- text = await call(tools.cortex_goal, { action: 'list' });
1124
- assert.match(text, new RegExp(`- \\[active\\] ${first} 完成工具契约测试 0%`));
1125
- assert.match(text, new RegExp(`- \\[active\\] ${second} 第二个目标 0%`));
1126
-
1127
- text = await call(tools.cortex_goal, {
1128
- action: 'update',
1129
- id: first,
1130
- description: '覆盖 18 个工具',
1131
- priority: 0.9,
1132
- progress: 0.4,
1133
- });
1134
- assert.equal(text, `已更新 ${first}:active 40%`);
1135
- const updated = cortex.goals.get(first);
1136
- assert.equal(updated.progress, 0.4);
1137
- assert.equal(updated.priority, 0.9);
1138
- assert.equal(updated.description, '覆盖 18 个工具');
1139
- assert.equal(await call(tools.cortex_goal, { action: 'update', id: 'gol_missing', progress: 0.5 }), '没有 gol_missing');
1140
-
1141
- text = await call(tools.cortex_goal, { action: 'list', status: 'completed' });
1142
- assert.equal(text, '(没有目标)');
1143
-
1144
- text = await call(tools.cortex_goal, { action: 'complete', id: first });
1145
- assert.equal(text, '目标已完成:完成工具契约测试');
1146
- const completed = cortex.goals.get(first);
1147
- assert.equal(completed.status, 'completed');
1148
- assert.equal(completed.progress, 1);
1149
- text = await call(tools.cortex_goal, { action: 'list', status: 'completed' });
1150
- assert.match(text, new RegExp(`- \\[completed\\] ${first} 完成工具契约测试 100%`));
1151
- assert.doesNotMatch(text, new RegExp(second));
1152
- text = await call(tools.cortex_goal, { action: 'list', status: 'active' });
1153
- assert.match(text, new RegExp(second));
1154
- assert.doesNotMatch(text, new RegExp(first));
1155
-
1156
- // Unknown ids must be reported, not echoed as a fake success.
1157
- text = await call(tools.cortex_goal, { action: 'complete', id: 'gol_missing' });
1158
- assert.equal(text, '没有这个目标:gol_missing');
1159
- assert.equal(cortex.goals.get('gol_missing'), null);
1160
-
1161
- await assert.rejects(() => tools.cortex_goal.execute({ action: 'add' }), /goal title is required/);
1162
- } finally {
1163
- harness.close();
1164
- }
1165
- });
1166
-
1167
- test('cortex_digest: daily digest on empty and populated days, persisted as a summary', async () => {
1168
- const harness = makeHarness();
1169
- const { cortex, tools } = harness;
1170
- const date = new Date().toISOString().slice(0, 10);
1171
- try {
1172
- // Default date and explicit empty date both work and persist nothing.
1173
- let text = await call(tools.cortex_digest, { action: 'daily' });
1174
- assert.match(text, /^# \d{4}-\d{2}-\d{2} 记忆摘要/);
1175
- assert.match(text, /新记忆:0 条/);
1176
- text = await call(tools.cortex_digest, { action: 'daily', date: '2000-01-01' });
1177
- assert.match(text, /^# 2000-01-01 记忆摘要/);
1178
- assert.match(text, /新记忆:0 条/);
1179
- assert.equal(cortex.repos.summaries.list('global', { level: 'digest' }).length, 0);
1180
-
1181
- const first = await call(tools.cortex_write, { text: '摘要契约:今天修好了工具。', explicit: true });
1182
- const second = await call(tools.cortex_write, { text: '摘要契约:今天写了测试。', explicit: true });
1183
- await call(tools.cortex_feedback, { id: idOf(first, 'trc'), signal: 'used', predicted: 0.7 });
1184
- await call(tools.cortex_emotion, { action: 'record', text: '助手很开心。', target: '用户' });
1185
- await call(tools.cortex_goal, { action: 'add', title: '完成摘要测试' });
1186
-
1187
- text = await call(tools.cortex_digest, { action: 'daily', date });
1188
- assert.match(text, /^# \d{4}-\d{2}-\d{2} 记忆摘要/);
1189
- assert.match(text, /新记忆:2 条(utterance 2)/);
1190
- assert.match(text, /情绪事件:1 条/);
1191
- assert.match(text, /进行中的目标:1 条/);
1192
- assert.match(text, /## 重要记忆/);
1193
- assert.match(text, /摘要契约/);
1194
- assert.match(text, /## 情绪/);
1195
- assert.match(text, /喜:助手很开心/);
1196
-
1197
- assert.match(text, /反馈:1 条/);
1198
- const feedbackRows = cortex.repos.feedback.list({ scopeId: 'global', limit: 500 });
1199
- assert.equal(feedbackRows.length, 1);
1200
- assert.equal(feedbackRows[0].at.slice(0, 10), date);
1201
-
1202
- const digests = cortex.repos.summaries.list('global', { level: 'digest' });
1203
- assert.equal(digests.length, 1);
1204
- assert.equal(digests[0].level, 'digest');
1205
- assert.equal(digests[0].sourceIds.length, 2);
1206
- assert.ok(digests[0].sourceIds.includes(idOf(first, 'trc')));
1207
- assert.ok(digests[0].sourceIds.includes(idOf(second, 'trc')));
1208
-
1209
- // A different day still reports zero and does not overwrite the real digest.
1210
- text = await call(tools.cortex_digest, { action: 'daily', date: '2000-01-01' });
1211
- assert.match(text, /^# 2000-01-01 记忆摘要/);
1212
- assert.match(text, /新记忆:0 条/);
1213
- assert.equal(cortex.repos.summaries.list('global', { level: 'digest' }).length, 1);
1214
- } finally {
1215
- harness.close();
1216
- }
1217
- });
1218
-
1219
- test('cortex_tick: status, safe execution and proposals that need approval', async () => {
1220
- const harness = makeHarness();
1221
- const { cortex, tools } = harness;
1222
- try {
1223
- let text = await call(tools.cortex_tick, { action: 'status' });
1224
- assert.match(text, /^自主意图:0 条/);
1225
- text = await call(tools.cortex_tick, { action: 'run' });
1226
- assert.equal(text, '执行 0 条,提案 0 条。');
1227
-
1228
- await call(tools.cortex_write, { text: 'tick 契约第一条:用户喜欢白饭。', explicit: true });
1229
- await call(tools.cortex_write, { text: 'tick 契约第二条:助手会等用户。', explicit: true });
1230
-
1231
- const now = Date.now();
1232
- const schedule = {
1233
- createdAt: new Date(now).toISOString(),
1234
- dueAt: new Date(now + 60_000).toISOString(),
1235
- expiresAt: new Date(now + 3_600_000).toISOString(),
1236
- };
1237
- const recall = cortex.stores.initiativeStore.insert({
1238
- kind: 'recall',
1239
- priority: 0.9,
1240
- reason: '想再确认白饭',
1241
- payload: { topic: '白饭' },
1242
- ...schedule,
1243
- }, { scopeId: 'global' });
1244
- const propose = cortex.stores.initiativeStore.insert({
1245
- kind: 'propose',
1246
- priority: 0.8,
1247
- reason: '想把这段记忆写成提案',
1248
- payload: { topic: 'identity' },
1249
- ...schedule,
1250
- }, { scopeId: 'global' });
1251
- const consolidate = cortex.stores.initiativeStore.insert({
1252
- kind: 'consolidate',
1253
- priority: 0.7,
1254
- reason: '整理白饭记忆',
1255
- payload: { reason: 'coherence' },
1256
- ...schedule,
1257
- }, { scopeId: 'global' });
1258
-
1259
- text = await call(tools.cortex_tick, { action: 'status' });
1260
- assert.match(text, /^自主意图:3 条/);
1261
- assert.match(text, /recall:1/);
1262
- assert.match(text, /propose:1/);
1263
- assert.match(text, /consolidate:1/);
1264
-
1265
- text = await call(tools.cortex_tick, { action: 'run', max: 10 });
1266
- assert.match(text, /^执行 2 条,提案 1 条。/);
1267
- assert.match(text, /- propose:想把这段记忆写成提案(需要 approval)/);
1268
-
1269
- assert.equal(cortex.stores.initiativeStore.get(recall.id).status, 'acted');
1270
- assert.equal(cortex.stores.initiativeStore.get(consolidate.id).status, 'acted');
1271
- assert.equal(cortex.stores.initiativeStore.get(propose.id).status, 'pending');
1272
-
1273
- text = await call(tools.cortex_tick, { action: 'status' });
1274
- assert.match(text, /^自主意图:1 条/);
1275
- assert.match(text, /propose:1/);
1276
- } finally {
1277
- harness.close();
1278
- }
1279
- });
1280
-
1281
- test('unknown ids and malformed inputs surface sentinel text or clear errors', async () => {
1282
- const harness = makeHarness();
1283
- const { cortex, tools } = harness;
1284
- try {
1285
- const traceCount = cortex.repos.traces.count();
1286
- const eventCount = cortex.repos.events.count();
1287
-
1288
- const cases = [
1289
- [tools.cortex_get, { id: 'trc_missing' }, /^没有这条记忆:trc_missing$/],
1290
- [tools.cortex_timeline, { aroundId: 'trc_missing' }, /^(没有找到锚点)$/],
1291
- [tools.cortex_forget, { id: 'trc_missing', mode: 'archive' }, /^没有这条记忆:trc_missing$/],
1292
- [tools.cortex_forget, { id: 'trc_missing', mode: 'delete' }, /^没有这条记忆:trc_missing$/],
1293
- [tools.cortex_working, { action: 'pin', id: 'wrk_missing' }, /^没有 wrk_missing$/],
1294
- [tools.cortex_working, { action: 'remove', id: 'wrk_missing' }, /^没有 wrk_missing$/],
1295
- [tools.cortex_goal, { action: 'update', id: 'gol_missing' }, /^没有 gol_missing$/],
1296
- [tools.cortex_compress, { action: 'revive', id: 'trc_missing' }, /^没有这条记忆:trc_missing$/],
1297
- [tools.cortex_life, { action: 'diary-forget', id: 'dly_missing' }, /^没有这条日记:dly_missing$/],
1298
- [tools.cortex_guard, { action: 'validate', file: path.join(harness.dir, 'missing.sqlite') }, /^备份无效:missing$/],
1299
- [tools.cortex_emotion, { action: 'detect', text: '普通的一天。' }, /^没有命中情绪词。$/],
1300
- [tools.cortex_write, { text: ' ' }, /^未写入:too-short/],
1301
- ];
1302
- for (const [tool, args, pattern] of cases) {
1303
- const text = await call(tool, args);
1304
- assert.match(text, pattern, `${tool.name} ${JSON.stringify(args)}`);
1305
- }
1306
-
1307
- await assert.rejects(() => tools.cortex_feedback.execute({ id: 'trc_missing', signal: 'used' }), /trace not found/);
1308
- await assert.rejects(() => tools.cortex_forget.execute({ id: 'trc_x', mode: 'shred' }), /unknown forget mode/);
1309
- await assert.rejects(() => tools.cortex_forget.execute({ mode: 'archive' }), /traceId is required/);
1310
- await assert.rejects(() => tools.cortex_working.execute({ action: 'add' }), /working item text is required/);
1311
- await assert.rejects(() => tools.cortex_goal.execute({ action: 'add' }), /goal title is required/);
1312
- await assert.rejects(() => tools.cortex_life.execute({ action: 'diary-write' }), /diary text is required/);
1313
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'propose' }), /policy kind is required/);
1314
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'approve', id: 'pol_missing' }), /policy not found/);
1315
- await assert.rejects(() => tools.cortex_evolve.execute({ action: 'rollback', kind: 'none-kind' }), /no policy to roll back/);
1316
-
1317
- assert.equal(cortex.repos.traces.count(), traceCount, 'invalid inputs must not create traces');
1318
- assert.equal(cortex.repos.events.count(), eventCount, 'invalid inputs must not append events');
1319
- assert.equal(cortex.working.list({ scopeId: 'global' }).length, 0);
1320
- assert.equal(cortex.goals.list({ scopeId: 'global' }).length, 0);
1321
- } finally {
1322
- harness.close();
1323
- }
1324
- });