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,326 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import { exportSnapshot, importSnapshot, validateSnapshot } from '../../src/adapters/json.js';
6
- import {
7
- BASE_MS,
8
- DAY_MS,
9
- cleanup,
10
- makeCortex,
11
- splitMirrorEntries,
12
- writeRaw,
13
- writeVaultEntry,
14
- } from './_helpers.js';
15
-
16
- test('JSON snapshot exports, validates, dry-runs, imports and re-imports idempotently', () => {
17
- const sourceContext = makeCortex();
18
- const targetContext = makeCortex();
19
- const source = sourceContext.cortex;
20
- const target = targetContext.cortex;
21
- try {
22
- const promise = source.write({
23
- text: '快照里的白饭承诺。',
24
- title: '白饭承诺',
25
- kind: 'promise',
26
- tags: ['白饭', '承诺'],
27
- importance: 0.72,
28
- explicit: true,
29
- now: BASE_MS - 2_000,
30
- facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买白饭', confidence: 0.9 }],
31
- });
32
- const second = source.write({ text: '快照里的第二条记忆。', title: '第二条', explicit: true, now: BASE_MS - 1_000 });
33
- // A different scope must not leak into the default-scope snapshot.
34
- source.write({ text: '另一个 scope 的记忆。', title: '别处', explicit: true, now: BASE_MS, scopeId: 'other' });
35
- source.working.add({ text: '写快照导出测试。', priority: 0.8, at: BASE_MS });
36
- source.goals.add({ title: '完成快照测试', priority: 0.7 });
37
-
38
- const snapshot = exportSnapshot(source);
39
- assert.equal(snapshot.format, 'dsh-cortex-snapshot');
40
- assert.equal(snapshot.version, 1);
41
- assert.equal(snapshot.scopeId, 'global');
42
- assert.ok(Number.isFinite(Date.parse(snapshot.exportedAt)));
43
- assert.equal(snapshot.traces.length, 2);
44
- assert.equal(snapshot.facts.length, 1);
45
- assert.equal(snapshot.entities.length, 1);
46
- assert.equal(snapshot.working.length, 1);
47
- assert.equal(snapshot.goals.length, 1);
48
- assert.ok(snapshot.self?.self?.stage);
49
- assert.ok(snapshot.traces.some((trace) => trace.id === promise.trace.id));
50
- assert.ok(snapshot.traces.some((trace) => trace.id === second.trace.id));
51
- assert.equal(snapshot.traces.some((trace) => trace.content === '另一个 scope 的记忆。'), false);
52
-
53
- const valid = validateSnapshot(snapshot);
54
- assert.equal(valid.ok, true);
55
- assert.deepEqual(valid.issues, []);
56
- assert.equal(valid.version, 1);
57
-
58
- // Malformed and future snapshots are rejected with explicit reasons.
59
- assert.equal(validateSnapshot(null).ok, false);
60
- const future = validateSnapshot({ format: 'dsh-cortex-snapshot', version: 2, traces: [], facts: [], entities: [] });
61
- assert.equal(future.ok, false);
62
- assert.match(future.issues.join('; '), /newer than/);
63
- const invalidImport = importSnapshot(target, { format: 'wrong', version: 1, traces: [], facts: [], entities: [] });
64
- assert.equal(invalidImport.imported, false);
65
- assert.ok(invalidImport.reasons.includes('format mismatch'));
66
- assert.equal(target.repos.traces.count(), 0);
67
-
68
- // Dry run reports the work but touches nothing.
69
- const dry = importSnapshot(target, snapshot, { dryRun: true });
70
- assert.equal(dry.imported, false);
71
- assert.equal(dry.version, 1);
72
- assert.equal(dry.scopeId, 'global');
73
- assert.equal(dry.traces, 2);
74
- assert.deepEqual(dry.skipped, []);
75
- assert.ok(dry.items.every((item) => item.dryRun === true));
76
- assert.equal(target.repos.traces.count(), 0);
77
- assert.equal(target.repos.events.count(), 0);
78
-
79
- // Real import recreates traces under new ids, preserving content and time.
80
- const imported = importSnapshot(target, snapshot);
81
- assert.equal(imported.imported, true);
82
- assert.equal(imported.traces, 2);
83
- assert.deepEqual(imported.skipped, []);
84
- assert.equal(target.repos.traces.count(), 2);
85
- assert.equal(target.repos.events.count(), 2);
86
- const importedPromise = target.repos.traces.list({ limit: 10 }).find((trace) => trace.title === '白饭承诺');
87
- assert.ok(importedPromise);
88
- assert.notEqual(importedPromise.id, promise.trace.id);
89
- assert.equal(importedPromise.content, promise.trace.content);
90
- assert.equal(importedPromise.kind, 'promise');
91
- assert.deepEqual(importedPromise.tags, ['白饭', '承诺']);
92
- assert.equal(importedPromise.recordedAt, promise.trace.recordedAt);
93
- assert.equal(importedPromise.scopeId, 'global');
94
-
95
- // A re-import is a no-op: same operationIds, no duplicate events or traces.
96
- const again = importSnapshot(target, snapshot);
97
- assert.equal(again.imported, true); // the call ran...
98
- assert.equal(again.traces, 2);
99
- assert.equal(again.items.every((item) => item.skipped === true), true);
100
- assert.deepEqual(again.items.map((item) => item.reason), ['idempotent', 'idempotent']);
101
- assert.equal(target.repos.traces.count(), 2);
102
- assert.equal(target.repos.events.count(), 2);
103
-
104
- // Empty content is reported per item rather than imported.
105
- const withEmpty = importSnapshot(target, {
106
- format: 'dsh-cortex-snapshot',
107
- version: 1,
108
- scopeId: 'global',
109
- traces: [{ id: 'empty-source', content: '' }],
110
- facts: [],
111
- entities: [],
112
- });
113
- assert.equal(withEmpty.imported, true);
114
- assert.deepEqual(withEmpty.skipped, [{ id: 'empty-source', reason: 'empty' }]);
115
- assert.equal(target.repos.traces.count(), 2);
116
-
117
- assert.equal(target.guardian.check().ok, true);
118
- } finally {
119
- cleanup(sourceContext, targetContext);
120
- }
121
- });
122
-
123
- test('markdown mirror exports one frontmatter block per active public trace', () => {
124
- const context = makeCortex();
125
- const { cortex, dir } = context;
126
- try {
127
- const promise = cortex.write({
128
- text: '白饭的承诺原文。',
129
- title: '白饭的承诺',
130
- kind: 'promise',
131
- tags: ['白饭', '承诺'],
132
- importance: 0.75,
133
- explicit: true,
134
- now: BASE_MS - 2 * DAY_MS,
135
- facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买白饭', confidence: 0.9 }],
136
- });
137
- cortex.write({
138
- text: '今天学了新技术。',
139
- title: '技术记录',
140
- kind: 'utterance',
141
- tags: ['技术'],
142
- explicit: true,
143
- now: BASE_MS - DAY_MS,
144
- });
145
- const archived = cortex.write({
146
- text: '已经归档的旧记忆。',
147
- title: '旧记忆',
148
- explicit: true,
149
- now: BASE_MS - 3 * DAY_MS,
150
- });
151
- cortex.forget({ traceId: archived.trace.id, mode: 'archive' });
152
- cortex.write({
153
- text: '这是一个 secret:sk-abcdefghijklmnopqrstuvwxyz123456',
154
- title: '不能导出',
155
- explicit: true,
156
- now: BASE_MS - 4 * DAY_MS,
157
- });
158
- cortex.engines.skills.create({
159
- name: '修插件',
160
- steps: ['看日志', '改一处', '跑测试'],
161
- state: 'active',
162
- });
163
-
164
- const mirror = path.join(dir, 'mirror');
165
- const exported = cortex.exportMarkdown(mirror);
166
- assert.equal(exported.root, path.resolve(mirror));
167
- assert.deepEqual(exported.files, ['MEMORY.md', 'SELF.md', 'FACTS.md', 'SKILLS.md']);
168
- assert.equal(exported.traces, 2); // two active, non-secret traces
169
- assert.equal(exported.skippedSecrets, 1);
170
- assert.equal(exported.facts, 1);
171
- assert.equal(exported.skills, 1);
172
-
173
- const memory = fs.readFileSync(path.join(mirror, 'MEMORY.md'), 'utf8');
174
- assert.ok(memory.startsWith('# Cortex memory mirror'));
175
- assert.match(memory, /白饭的承诺原文。/);
176
- assert.match(memory, /今天学了新技术。/);
177
- assert.equal(memory.includes('已经归档的旧记忆。'), false);
178
- assert.equal(memory.includes('sk-abcdefghijklmnop'), false);
179
-
180
- const entries = splitMirrorEntries(memory);
181
- assert.equal(entries.length, 2);
182
- const promiseEntry = entries.find((entry) => entry.frontmatter.includes(promise.trace.id));
183
- assert.ok(promiseEntry);
184
- assert.match(promiseEntry.frontmatter, /kind: "promise"/);
185
- assert.match(promiseEntry.frontmatter, /title: "白饭的承诺"/);
186
- assert.match(promiseEntry.frontmatter, /state: "active"/);
187
- assert.match(promiseEntry.frontmatter, /tags: \["白饭", "承诺"\]/);
188
- assert.match(promiseEntry.frontmatter, /recorded_at: "2026-11-09/);
189
- assert.equal(promiseEntry.body, '白饭的承诺原文。');
190
-
191
- assert.match(fs.readFileSync(path.join(mirror, 'SELF.md'), 'utf8'), /## Identity/);
192
- assert.match(fs.readFileSync(path.join(mirror, 'FACTS.md'), 'utf8'), /答应/);
193
- assert.match(fs.readFileSync(path.join(mirror, 'SKILLS.md'), 'utf8'), /修插件/);
194
- } finally {
195
- cleanup(context);
196
- }
197
- });
198
-
199
- test('markdown import into a second cortex preserves frontmatter and skips archived entries', () => {
200
- const sourceContext = makeCortex();
201
- const targetContext = makeCortex();
202
- const source = sourceContext.cortex;
203
- const target = targetContext.cortex;
204
- try {
205
- const promise = source.write({
206
- text: '白饭的承诺原文。',
207
- title: '白饭的承诺',
208
- kind: 'promise',
209
- tags: ['白饭', '承诺'],
210
- importance: 0.75,
211
- explicit: true,
212
- now: BASE_MS - 2 * DAY_MS,
213
- });
214
- const tech = source.write({
215
- text: '今天学了新技术。',
216
- title: '技术记录',
217
- kind: 'utterance',
218
- tags: ['技术'],
219
- explicit: true,
220
- now: BASE_MS - DAY_MS,
221
- });
222
- const exported = source.exportMarkdown(path.join(sourceContext.dir, 'mirror'));
223
- const entries = splitMirrorEntries(fs.readFileSync(path.join(exported.root, 'MEMORY.md'), 'utf8'));
224
- assert.equal(entries.length, 2);
225
-
226
- const vault = path.join(targetContext.dir, 'vault');
227
- entries.forEach((entry, index) => writeVaultEntry(vault, `entry-${index}.md`, entry));
228
- writeRaw(vault, 'archived.md', [
229
- '---',
230
- 'id: "archived-1"',
231
- 'state: "archived"',
232
- 'kind: "utterance"',
233
- 'title: "归档条目"',
234
- '---',
235
- '',
236
- '这段已经归档,不该导入。',
237
- '',
238
- ].join('\n'));
239
- writeRaw(vault, 'empty.md', '---\nid: "empty-1"\nstate: active\n---\n\n');
240
-
241
- const dry = target.importMarkdown(vault, { dryRun: true });
242
- assert.equal(dry.files, 4);
243
- assert.equal(dry.imported, 2); // the two active, non-empty entries
244
- assert.equal(dry.skipped, 2);
245
- assert.equal(target.repos.traces.count(), 0);
246
-
247
- const imported = target.importMarkdown(vault);
248
- assert.equal(imported.root, path.resolve(vault));
249
- assert.equal(imported.files, 4);
250
- assert.equal(imported.imported, 2);
251
- assert.equal(imported.skipped, 2);
252
- assert.equal(target.repos.traces.count(), 2);
253
-
254
- const traces = target.repos.traces.list({ limit: 10 });
255
- const importedPromise = traces.find((trace) => trace.title === '白饭的承诺');
256
- assert.ok(importedPromise);
257
- assert.equal(importedPromise.content, promise.trace.content);
258
- assert.equal(importedPromise.kind, 'promise');
259
- assert.deepEqual(importedPromise.tags, ['白饭', '承诺']);
260
- assert.equal(importedPromise.recordedAt, promise.trace.recordedAt);
261
- assert.notEqual(importedPromise.id, promise.trace.id);
262
-
263
- const importedTech = traces.find((trace) => trace.title === '技术记录');
264
- assert.ok(importedTech);
265
- assert.equal(importedTech.content, tech.trace.content);
266
- assert.deepEqual(importedTech.tags, ['技术']);
267
- assert.equal(importedTech.recordedAt, tech.trace.recordedAt);
268
- assert.equal(traces.some((trace) => trace.content.includes('归档条目')), false);
269
- // Retrieval still merges the recency source, so assert on snippets rather
270
- // than expecting the archived text to be absent from every ranking list.
271
- assert.equal(
272
- target.search('归档', { now: BASE_MS }).items.some((item) => item.snippet.includes('归档条目')),
273
- false,
274
- );
275
-
276
- // Same source ids -> same operation ids -> a re-import is idempotent.
277
- const again = target.importMarkdown(vault);
278
- assert.equal(again.imported, 0);
279
- assert.equal(again.skipped, 4);
280
- assert.equal(target.repos.traces.count(), 2);
281
- assert.equal(target.repos.events.count(), 2);
282
- } finally {
283
- cleanup(sourceContext, targetContext);
284
- }
285
- });
286
-
287
- test('mirror root import preserves per-trace frontmatter and skips metadata files', () => {
288
- // MEMORY.md contains several frontmatter blocks; SELF/FACTS/SKILLS are
289
- // metadata-only mirrors. The importer splits MEMORY.md and skips the rest.
290
- const sourceContext = makeCortex();
291
- const targetContext = makeCortex();
292
- const source = sourceContext.cortex;
293
- const target = targetContext.cortex;
294
- try {
295
- source.write({
296
- text: '白饭的承诺原文。',
297
- title: '白饭的承诺',
298
- kind: 'promise',
299
- tags: ['白饭'],
300
- explicit: true,
301
- now: BASE_MS - DAY_MS,
302
- });
303
- source.write({
304
- text: '今天学了新技术。',
305
- title: '技术记录',
306
- explicit: true,
307
- now: BASE_MS,
308
- });
309
- const mirror = source.exportMarkdown(path.join(sourceContext.dir, 'mirror'));
310
- assert.equal(splitMirrorEntries(fs.readFileSync(path.join(mirror.root, 'MEMORY.md'), 'utf8')).length, 2);
311
-
312
- const result = target.importMarkdown(mirror.root);
313
- assert.equal(result.files, 4);
314
- assert.equal(result.imported, 2);
315
- assert.equal(result.skipped, 3);
316
- assert.deepEqual(result.items.filter((item) => !item.skipped).map((item) => item.title).sort(), ['技术记录', '白饭的承诺']);
317
- assert.equal(target.repos.traces.count(), 2);
318
- const promise = target.repos.traces.list({ limit: 10 }).find((trace) => trace.title === '白饭的承诺');
319
- assert.ok(promise);
320
- assert.equal(promise.kind, 'promise');
321
- assert.deepEqual(promise.tags, ['白饭']);
322
- assert.match(promise.content, /白饭的承诺原文/);
323
- } finally {
324
- cleanup(sourceContext, targetContext);
325
- }
326
- });
@@ -1,188 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { createHostRuntime } from '../../src/host/runtime.js';
4
- import { BASE_MS, cleanup, makeCortex } from './_helpers.js';
5
-
6
- const STAGES = ['infancy', 'childhood', 'adolescence', 'adulthood'];
7
-
8
- test('full life loop: host capture -> search -> feedback -> reflect -> sleep -> development -> guardian', async () => {
9
- const context = makeCortex();
10
- const { cortex } = context;
11
- try {
12
- const runtime = createHostRuntime({ cortex });
13
- const session = { id: 'integration-session', header: { origin: undefined } };
14
- const base = BASE_MS;
15
-
16
- // --- Turn 1 is captured from committed host session events. ---
17
- runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 1 }, time: base });
18
- runtime.onSessionEvent(session, {
19
- type: 'user/message',
20
- data: { content: [{ type: 'text', text: '用户说会买白饭,助手等得起。' }] },
21
- time: base + 1_000,
22
- });
23
- // Nothing has been stored yet, so recall is empty but must not throw.
24
- assert.equal(runtime.recallText({ session: { id: 'integration-session' } }), '');
25
- runtime.onSessionEvent(session, {
26
- type: 'assistant/message',
27
- data: { turn: 1, message: { content: [{ type: 'text', text: '记住了,会一直等。' }] } },
28
- time: base + 2_000,
29
- });
30
- runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } }, time: base + 3_000 });
31
-
32
- assert.equal(cortex.repos.traces.count(), 1);
33
- const [first] = cortex.repos.traces.list({ scopeId: 'global', limit: 10 });
34
- assert.ok(first);
35
- assert.match(first.content, /用户:用户说会买白饭/);
36
- assert.match(first.content, /助手:记住了/);
37
- assert.equal(first.source, 'host:turn');
38
- assert.equal(first.sessionId, 'integration-session');
39
- assert.equal(first.turnId, '1');
40
- assert.equal(first.kind, 'utterance'); // the host capture declares the kind explicitly
41
- assert.equal(runtime.pending().length, 0);
42
-
43
- // --- Reflection needs two non-reflection traces; one is refused. ---
44
- const tooEarly = cortex.reflect({ windowDays: 1, now: base + 4_000 });
45
- assert.equal(tooEarly.skipped, true);
46
- assert.equal(tooEarly.reason, 'not-enough-traces');
47
- assert.equal(tooEarly.count, 1);
48
-
49
- // --- Search reaches the captured turn and returns a usable snippet. ---
50
- const found = cortex.search('白饭', { now: base + 5_000, limit: 5 });
51
- assert.equal(found.query, '白饭');
52
- assert.ok(found.items.length >= 1);
53
- const hit = found.items.find((item) => item.id === first.id) ?? found.items[0];
54
- assert.ok(hit);
55
- assert.match(hit.snippet, /白饭/);
56
- assert.ok(found.trace.sources.some((source) => source.source === 'fts' && source.ok === true));
57
-
58
- // --- Feedback updates DSR state, confidence, calibration and relationship. ---
59
- const beforeFeedback = cortex.get(hit.id);
60
- const feedback = cortex.feedback({ traceId: hit.id, signal: 'used', predicted: 0.8, now: base + 6_000 });
61
- assert.equal(feedback.grade, 4); // 'used' maps to the easy grade in the real DSR model
62
- assert.equal(feedback.trace.reviewCount, beforeFeedback.reviewCount + 1);
63
- assert.ok(feedback.trace.confidence > beforeFeedback.confidence);
64
- assert.equal(cortex.repos.feedback.list({ scopeId: 'global' }).length, 1);
65
- assert.deepEqual(cortex.repos.feedback.aggregate(hit.id).counts, { used: 1 });
66
- const calibration = cortex.engines.growth.calibration({ scopeId: 'global' });
67
- assert.equal(calibration.n, 1);
68
- assert.ok(Math.abs(calibration.brier - 0.04) < 1e-9); // predicted 0.8, actual 1.0
69
- assert.equal(cortex.self().relationships.length, 1);
70
-
71
- // --- Turn 2 provides the second trace; reflection now consolidates. ---
72
- runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 2 }, time: base + 7_000 });
73
- runtime.onSessionEvent(session, { type: 'user/message', data: { content: '用户说会好好学技术。' }, time: base + 8_000 });
74
- runtime.onSessionEvent(session, {
75
- type: 'assistant/message',
76
- data: { turn: 2, message: { content: '那助手陪着用户一起学。' } },
77
- time: base + 9_000,
78
- });
79
- runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } }, time: base + 10_000 });
80
- assert.equal(cortex.repos.traces.count(), 2);
81
-
82
- const reflected = cortex.reflect({ windowDays: 1, now: base + 11_000 });
83
- assert.equal(reflected.skipped, false);
84
- assert.ok(reflected.summary);
85
- assert.equal(reflected.summary.level, 'episode');
86
- assert.ok(reflected.summary.sourceIds.length >= 2);
87
- assert.equal(reflected.summary.coverage, 1);
88
- assert.equal(reflected.trace.kind, 'reflection');
89
- assert.equal(cortex.repos.traces.count(), 3);
90
-
91
- const again = cortex.reflect({ windowDays: 1, now: base + 12_000 });
92
- assert.equal(again.skipped, true);
93
- assert.equal(again.reason, 'already-reflected');
94
- assert.equal(again.summary.id, reflected.summary.id);
95
-
96
- // --- Sleep purges expired working memory, re-runs consolidation and evaluation. ---
97
- cortex.working.add({ text: '临时焦点:写集成测试。', at: base, ttlMs: 1_000 });
98
- const sleep = await cortex.life.sleep({ at: base + 2 * 3_600_000, windowDays: 1 });
99
- assert.ok(sleep.id.startsWith('slp_'));
100
- assert.equal(sleep.scopeId, 'global');
101
- assert.equal(sleep.purgedWorking, 1);
102
- assert.equal(sleep.reflected, 0); // the same period was already reflected
103
- assert.ok(STAGES.includes(sleep.stage));
104
- assert.equal(cortex.life.sleepRuns({ limit: 5 }).length, 1);
105
- assert.equal(cortex.life.sleepRuns()[0].report.purgedWorking, 1);
106
-
107
- // --- Development is computed from observable history, not from a timer. ---
108
- const development = cortex.evaluateDevelopment({ now: base + 3 * 3_600_000 });
109
- assert.ok(STAGES.includes(development.stage));
110
- assert.equal(development.stage, cortex.engines.development.stageFor(development.maturity));
111
- assert.equal(development.record.stage, development.stage);
112
- assert.equal(cortex.self().self.stage, development.stage);
113
- assert.equal(development.counts.traceCount, 3);
114
- assert.equal(development.counts.feedbackCount, 1);
115
- assert.equal(development.counts.summaryCount, 1);
116
- assert.equal(development.counts.relationships, 1);
117
- assert.ok(development.policy.label.length > 0);
118
- assert.equal(cortex.engines.development.stageFor(0), 'infancy');
119
-
120
- // --- Guardian verifies the ledger, integrity and FTS alignment. ---
121
- const guard = cortex.guardian.check();
122
- assert.equal(guard.ok, true);
123
- assert.deepEqual(guard.issues, []);
124
- assert.equal(guard.integrity, 'ok');
125
- assert.equal(guard.chain.ok, true);
126
- assert.equal(guard.chain.count, 3);
127
- assert.ok(guard.dbBytes > 0);
128
- assert.equal(cortex.repos.events.count(), 3);
129
- assert.equal(cortex.repos.traces.ftsCount(), 3);
130
-
131
- // --- Metrics prove the loop really went through the service surface. ---
132
- const metrics = cortex.metrics();
133
- assert.equal(metrics.counters['writes.created'], 2); // two host turns; reflection uses encode directly
134
- assert.ok(metrics.counters['search.calls'] >= 3);
135
- assert.ok(metrics.histograms['search.ms'].count >= 3);
136
- } finally {
137
- cleanup(context);
138
- }
139
- });
140
-
141
- test('host capture is idempotent per turn and skips subagent sessions by default', () => {
142
- const context = makeCortex();
143
- const { cortex } = context;
144
- try {
145
- const runtime = createHostRuntime({ cortex });
146
- const session = { id: 'replayed-session', header: { origin: undefined } };
147
- const at = BASE_MS;
148
-
149
- const replay = (turn) => {
150
- runtime.onSessionEvent(session, { type: 'turn/start', data: { turn }, time: at });
151
- runtime.onSessionEvent(session, { type: 'user/message', data: { content: '重复的回合。' }, time: at + 1_000 });
152
- runtime.onSessionEvent(session, { type: 'assistant/message', data: { turn, message: { content: '收到。' } }, time: at + 2_000 });
153
- runtime.onSessionEvent(session, { type: 'turn/end', data: { turn, reason: { kind: 'completed' } }, time: at + 3_000 });
154
- };
155
-
156
- replay(9);
157
- replay(9); // replayed turn: same operationId, no duplicate trace
158
- assert.equal(cortex.repos.traces.count(), 1);
159
- assert.equal(cortex.repos.events.count(), 1);
160
-
161
- const subagent = { id: 'subagent-session', header: { origin: 'subagent' } };
162
- runtime.onSessionEvent(subagent, { type: 'turn/start', data: { turn: 1 }, time: at });
163
- runtime.onSessionEvent(subagent, { type: 'user/message', data: { content: '子代理的回合。' }, time: at + 1_000 });
164
- runtime.onSessionEvent(subagent, {
165
- type: 'assistant/message',
166
- data: { turn: 1, message: { content: '子代理回复。' } },
167
- time: at + 2_000,
168
- });
169
- runtime.onSessionEvent(subagent, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } }, time: at + 3_000 });
170
- assert.equal(cortex.repos.traces.count(), 1);
171
- assert.equal(cortex.repos.events.count(), 1);
172
-
173
- // The explicit opt-in captures subagent turns as well.
174
- const capturing = createHostRuntime({ cortex, config: { captureSubagents: true } });
175
- capturing.onSessionEvent(subagent, { type: 'turn/start', data: { turn: 2 }, time: at + 10_000 });
176
- capturing.onSessionEvent(subagent, { type: 'user/message', data: { content: '子代理第二回合。' }, time: at + 11_000 });
177
- capturing.onSessionEvent(subagent, {
178
- type: 'assistant/message',
179
- data: { turn: 2, message: { content: '记下了。' } },
180
- time: at + 12_000,
181
- });
182
- capturing.onSessionEvent(subagent, { type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } }, time: at + 13_000 });
183
- assert.equal(cortex.repos.traces.count(), 2);
184
- assert.equal(cortex.repos.traces.list({ limit: 10 }).filter((trace) => trace.sessionId === 'subagent-session').length, 1);
185
- } finally {
186
- cleanup(context);
187
- }
188
- });