dsh-cortex-memory 0.4.22 → 0.4.146

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 (165) hide show
  1. package/CHANGELOG.md +2216 -7
  2. package/README.md +9 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +7 -7
  5. package/bench/synthetic.js +2 -2
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/cordis.patch.yml +1 -1
  10. package/docs/install-windows.md +2 -2
  11. package/docs/models.md +1 -1
  12. package/docs/quota-compaction-design.md +175 -0
  13. package/index.js +27 -3
  14. package/package.json +3 -3
  15. package/src/adapters/shiori.js +1 -1
  16. package/src/api/routes.js +1 -1
  17. package/src/core/feature-overrides.js +2 -2
  18. package/src/engines/compression.js +172 -3
  19. package/src/engines/consolidate.js +397 -26
  20. package/src/engines/encode.js +16 -3
  21. package/src/engines/extract.js +72 -8
  22. package/src/engines/fact-guard.js +51 -0
  23. package/src/engines/health.js +263 -3
  24. package/src/engines/inhibition.js +39 -0
  25. package/src/engines/life.js +12 -1
  26. package/src/engines/llm-facts.js +12 -9
  27. package/src/engines/narrative.js +150 -13
  28. package/src/engines/reflect.js +172 -14
  29. package/src/engines/retrieve.js +44 -5
  30. package/src/engines/summary-coverage.js +62 -0
  31. package/src/engines/summary-dedupe.js +77 -0
  32. package/src/engines/summon-rank.js +132 -0
  33. package/src/host/runtime.js +64 -4
  34. package/src/host/scheduler.js +224 -3
  35. package/src/llm/adapter.js +29 -8
  36. package/src/memory/query.js +1 -1
  37. package/src/memory/spacing.js +15 -0
  38. package/src/memory/tokenizer.js +1 -1
  39. package/src/prompt/tiers.js +88 -12
  40. package/src/self/alias.js +25 -0
  41. package/src/self/emotion.js +3 -1
  42. package/src/self/relationship.js +44 -13
  43. package/src/self/state.js +20 -2
  44. package/src/self/working.js +34 -3
  45. package/src/service/cortex.js +493 -53
  46. package/src/store/repositories/facts.js +34 -1
  47. package/src/store/repositories/summaries.js +8 -1
  48. package/src/store/repositories/traces.js +22 -2
  49. package/src/tools/definitions.js +118 -4
  50. package/src/vector/index.js +96 -7
  51. package/test/integration/acceptance.test.js +47 -47
  52. package/test/integration/api-contract.test.js +17 -17
  53. package/test/integration/backup-privacy.test.js +10 -10
  54. package/test/integration/consolidate.test.js +6 -2
  55. package/test/integration/edge-cases.test.js +16 -15
  56. package/test/integration/exchange.test.js +26 -26
  57. package/test/integration/life-loop.test.js +7 -6
  58. package/test/integration/load.test.js +4 -4
  59. package/test/integration/policy-query-api.test.js +4 -4
  60. package/test/integration/resilience-writes.test.js +7 -7
  61. package/test/integration/tools-contract.test.js +57 -57
  62. package/test/unit/alias.test.js +87 -0
  63. package/test/unit/api-client.test.js +3 -3
  64. package/test/unit/api-validate.test.js +3 -3
  65. package/test/unit/api.test.js +3 -3
  66. package/test/unit/auto-reflect.test.js +141 -0
  67. package/test/unit/capture-filter.test.js +296 -0
  68. package/test/unit/compaction-preview.test.js +91 -0
  69. package/test/unit/compression.test.js +4 -4
  70. package/test/unit/consolidate-dedupe.test.js +174 -0
  71. package/test/unit/consolidate-errors.test.js +63 -0
  72. package/test/unit/consolidate-gate.test.js +26 -0
  73. package/test/unit/consolidate-preview.test.js +168 -0
  74. package/test/unit/consolidate-protection.test.js +156 -0
  75. package/test/unit/consolidate-reason.test.js +206 -0
  76. package/test/unit/consolidate-retry.test.js +91 -0
  77. package/test/unit/consolidate-selection.test.js +103 -0
  78. package/test/unit/core.test.js +11 -11
  79. package/test/unit/coverage-rewrite.test.js +38 -0
  80. package/test/unit/dedupe-episodes.test.js +34 -0
  81. package/test/unit/dedupe-threshold.test.js +14 -0
  82. package/test/unit/develop.test.js +4 -4
  83. package/test/unit/edges-candidates.test.js +2 -2
  84. package/test/unit/emotion.test.js +2 -1
  85. package/test/unit/encode.test.js +6 -6
  86. package/test/unit/evolution.test.js +5 -5
  87. package/test/unit/extract-question.test.js +41 -0
  88. package/test/unit/fact-guard.test.js +51 -0
  89. package/test/unit/fact-noise-llm.test.js +44 -0
  90. package/test/unit/facts-belief.test.js +4 -4
  91. package/test/unit/facts-compat.test.js +62 -0
  92. package/test/unit/facts.test.js +5 -5
  93. package/test/unit/fts-migration.test.js +6 -6
  94. package/test/unit/growth-reflect.test.js +4 -3
  95. package/test/unit/guardian.test.js +1 -1
  96. package/test/unit/health-consolidation.test.js +52 -0
  97. package/test/unit/health-fts-scope.test.js +33 -0
  98. package/test/unit/health-privacy.test.js +6 -6
  99. package/test/unit/health-summaries.test.js +24 -0
  100. package/test/unit/health-text-maintain.test.js +33 -0
  101. package/test/unit/health-today.test.js +45 -0
  102. package/test/unit/host-runtime.test.js +8 -8
  103. package/test/unit/host.test.js +1 -1
  104. package/test/unit/induct-evaluate.test.js +3 -3
  105. package/test/unit/ingest-extracted.test.js +3 -3
  106. package/test/unit/inhibition.test.js +90 -0
  107. package/test/unit/jobs.test.js +4 -4
  108. package/test/unit/json-snapshot.test.js +1 -1
  109. package/test/unit/label-entities-skip.test.js +18 -0
  110. package/test/unit/llm-facts-integration.test.js +2 -2
  111. package/test/unit/llm-facts.test.js +3 -3
  112. package/test/unit/llm.test.js +5 -5
  113. package/test/unit/locomo.test.js +2 -2
  114. package/test/unit/longmemeval.test.js +2 -2
  115. package/test/unit/maintain-dispute.test.js +62 -0
  116. package/test/unit/maintain-duration.test.js +194 -0
  117. package/test/unit/markdown-import.test.js +5 -5
  118. package/test/unit/markdown.test.js +2 -2
  119. package/test/unit/memory-edit.test.js +5 -5
  120. package/test/unit/migration.test.js +1 -1
  121. package/test/unit/mood-saturation.test.js +33 -0
  122. package/test/unit/narrative-weave.test.js +271 -0
  123. package/test/unit/privacy-scope.test.js +1 -1
  124. package/test/unit/prompt.test.js +1 -1
  125. package/test/unit/providers.test.js +2 -2
  126. package/test/unit/qa.test.js +9 -9
  127. package/test/unit/query.test.js +10 -10
  128. package/test/unit/reflect-backfill.test.js +158 -0
  129. package/test/unit/reflect-coverage.test.js +35 -0
  130. package/test/unit/reflect-overview.test.js +22 -0
  131. package/test/unit/reflect-phrasing.test.js +75 -0
  132. package/test/unit/reflect-sampling.test.js +80 -0
  133. package/test/unit/reflect-source-budget.test.js +24 -0
  134. package/test/unit/relationship-dynamics.test.js +29 -0
  135. package/test/unit/retrieve.test.js +9 -9
  136. package/test/unit/revive-on-read.test.js +84 -0
  137. package/test/unit/scanner.test.js +2 -2
  138. package/test/unit/scenario.test.js +2 -2
  139. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  140. package/test/unit/scheduler-autodedupe.test.js +52 -0
  141. package/test/unit/scheduler-autosleep.test.js +50 -0
  142. package/test/unit/scheduler-cadence.test.js +33 -0
  143. package/test/unit/scheduler-deep.test.js +62 -0
  144. package/test/unit/scheduler-tick-gate.test.js +38 -0
  145. package/test/unit/scheduler.test.js +2 -1
  146. package/test/unit/service.test.js +5 -5
  147. package/test/unit/shiori-import.test.js +4 -4
  148. package/test/unit/spacing.test.js +14 -0
  149. package/test/unit/store.test.js +13 -13
  150. package/test/unit/summon-left-slot.test.js +51 -0
  151. package/test/unit/summon-rank.test.js +51 -0
  152. package/test/unit/tiers-gist.test.js +140 -0
  153. package/test/unit/tiers.test.js +1 -1
  154. package/test/unit/tokenizer-fts.test.js +6 -6
  155. package/test/unit/tools.test.js +5 -5
  156. package/test/unit/upgrade-0412.test.js +10 -10
  157. package/test/unit/upgrade-0413.test.js +5 -5
  158. package/test/unit/upgrade-0414.test.js +5 -5
  159. package/test/unit/vector-ann.test.js +3 -3
  160. package/test/unit/vector-async.test.js +7 -7
  161. package/test/unit/vector-coverage.test.js +34 -0
  162. package/test/unit/vector-override.test.js +37 -0
  163. package/test/unit/vector-typed-array.test.js +47 -0
  164. package/test/unit/vector.test.js +8 -8
  165. package/test/unit/working.test.js +19 -0
@@ -227,28 +227,28 @@ test('cortex_write: minimal write, explicit facts, scopes and operationId idempo
227
227
  const { cortex, tools } = harness;
228
228
  try {
229
229
  // Minimal args: text only must be enough for a useful, explicit-looking note.
230
- const minimal = await call(tools.cortex_write, { text: '喜欢白饭。' });
230
+ const minimal = await call(tools.cortex_write, { text: '喜欢米饭。' });
231
231
  assert.match(minimal, /^已写入 trc_/);
232
232
  assert.match(minimal, /事件:evt_/);
233
233
  assert.match(minimal, /压缩值:0\.\d{3}/);
234
234
  const minimalId = idOf(minimal, 'trc');
235
235
  const minimalTrace = cortex.get(minimalId);
236
- assert.equal(minimalTrace.content, '喜欢白饭。');
236
+ assert.equal(minimalTrace.content, '喜欢米饭。');
237
237
  assert.equal(minimalTrace.kind, 'preference');
238
238
  assert.equal(minimalTrace.state, 'active');
239
239
  assert.equal(cortex.repos.traces.count(), 1);
240
240
 
241
241
  // Full args: kind/importance/confidence/tags/scope/facts all flow through.
242
- const richText = '用户答应会买白饭,助手会一直等。';
242
+ const richText = '用户答应会买米饭,助手会一直等。';
243
243
  const rich = await call(tools.cortex_write, {
244
244
  text: richText,
245
245
  kind: 'promise',
246
246
  importance: 0.8,
247
247
  confidence: 0.9,
248
248
  explicit: true,
249
- tags: ['白饭', '承诺'],
249
+ tags: ['米饭', '承诺'],
250
250
  scope: 'shared',
251
- facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买白饭', confidence: 0.9 }],
251
+ facts: [{ subject: '用户', predicate: '答应', objectLiteral: '买米饭', confidence: 0.9 }],
252
252
  });
253
253
  assert.match(rich, /^已写入 trc_/);
254
254
  assert.match(rich, /(promise)/);
@@ -257,22 +257,22 @@ test('cortex_write: minimal write, explicit facts, scopes and operationId idempo
257
257
  const richTrace = cortex.get(richId);
258
258
  assert.equal(richTrace.scopeId, 'shared');
259
259
  assert.equal(richTrace.kind, 'promise');
260
- assert.deepEqual(richTrace.tags, ['白饭', '承诺']);
260
+ assert.deepEqual(richTrace.tags, ['米饭', '承诺']);
261
261
  assert.equal(richTrace.confidence, 0.9);
262
262
  assert.ok(richTrace.importance >= 0.8);
263
263
  const richFacts = cortex.repos.facts.list({ scopeId: 'shared' });
264
264
  assert.equal(richFacts.length, 1);
265
- assert.equal(richFacts[0].objectLiteral, '买白饭');
265
+ assert.equal(richFacts[0].objectLiteral, '买米饭');
266
266
 
267
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' });
268
+ const scopedSearch = await call(tools.cortex_search, { query: '米饭', scope: 'shared' });
269
269
  assert.match(scopedSearch, new RegExp(richId));
270
- const globalSearch = await call(tools.cortex_search, { query: '白饭' });
270
+ const globalSearch = await call(tools.cortex_search, { query: '米饭' });
271
271
  assert.doesNotMatch(globalSearch, new RegExp(richId));
272
272
 
273
273
  // Idempotency: reusing operationId with the identical payload returns the first trace.
274
274
  const operationId = 'tools-contract-idempotent-write';
275
- const opText = '幂等写入:用户会买白饭。';
275
+ const opText = '幂等写入:用户会买米饭。';
276
276
  const firstOp = await call(tools.cortex_write, { text: opText, explicit: true, operationId });
277
277
  const opId = idOf(firstOp, 'trc');
278
278
  const traceCount = cortex.repos.traces.count();
@@ -327,45 +327,45 @@ test('cortex_search: hits, filters, budgets, archived opt-in and empty queries',
327
327
  const base = Date.now();
328
328
  try {
329
329
  const decision = cortex.write({
330
- text: '决定今天去吃白饭,白饭是主食。',
331
- title: '白饭决定',
330
+ text: '决定今天去吃米饭,米饭是主食。',
331
+ title: '米饭决定',
332
332
  kind: 'decision',
333
333
  explicit: true,
334
- tags: ['白饭', '决定'],
334
+ tags: ['米饭', '决定'],
335
335
  now: base,
336
336
  });
337
337
  const preference = cortex.write({
338
- text: '用户喜欢白饭,助手记得。',
339
- title: '白饭偏好',
338
+ text: '用户喜欢米饭,助手记得。',
339
+ title: '米饭偏好',
340
340
  kind: 'preference',
341
341
  explicit: true,
342
- tags: ['白饭', '偏好'],
342
+ tags: ['米饭', '偏好'],
343
343
  now: base + 1_000,
344
344
  });
345
345
  assert.equal(decision.skipped, false);
346
346
  assert.equal(preference.skipped, false);
347
347
 
348
- let text = await call(tools.cortex_search, { query: '白饭', limit: 2 });
349
- assert.match(text, /^查询:白饭 · 意图:fact/);
348
+ let text = await call(tools.cortex_search, { query: '米饭', limit: 2 });
349
+ assert.match(text, /^查询:米饭 · 意图:fact/);
350
350
  assert.match(text, /预算:\d+\/\d+ token · 候选 \d+ · 选中 \d+/);
351
351
  assert.match(text, new RegExp(decision.trace.id));
352
352
  assert.match(text, new RegExp(preference.trace.id));
353
353
 
354
354
  // Query-language filters are parsed before retrieval.
355
- text = await call(tools.cortex_search, { query: 'kind:decision 白饭' });
355
+ text = await call(tools.cortex_search, { query: 'kind:decision 米饭' });
356
356
  assert.match(text, new RegExp(decision.trace.id));
357
357
  assert.doesNotMatch(text, new RegExp(preference.trace.id));
358
358
 
359
359
  // limit + budget still respect the portfolio contract.
360
- text = await call(tools.cortex_search, { query: '白饭', limit: 1, budget: 16 });
360
+ text = await call(tools.cortex_search, { query: '米饭', limit: 1, budget: 16 });
361
361
  assert.match(text, /预算:16\/16 token · 候选 \d+ · 选中 1/);
362
362
 
363
363
  // Archived traces stay out unless explicitly requested.
364
364
  const archived = await call(tools.cortex_forget, { id: preference.trace.id, mode: 'archive' });
365
365
  assert.match(archived, /已归档/);
366
- text = await call(tools.cortex_search, { query: '白饭' });
366
+ text = await call(tools.cortex_search, { query: '米饭' });
367
367
  assert.doesNotMatch(text, new RegExp(preference.trace.id));
368
- text = await call(tools.cortex_search, { query: '白饭', includeArchived: true });
368
+ text = await call(tools.cortex_search, { query: '米饭', includeArchived: true });
369
369
  assert.match(text, new RegExp(preference.trace.id));
370
370
 
371
371
  // Empty query is accepted as "recent items" and rendered as an empty query.
@@ -381,7 +381,7 @@ test('cortex_search: hits, filters, budgets, archived opt-in and empty queries',
381
381
 
382
382
  // Scope is honored by retrieval.
383
383
  const other = cortex.write({
384
- text: '另一个 scope 的白饭记录。',
384
+ text: '另一个 scope 的米饭记录。',
385
385
  title: '另一个 scope',
386
386
  explicit: true,
387
387
  scopeId: 'other',
@@ -401,12 +401,12 @@ test('cortex_get: full trace rendering and unknown id sentinel', async () => {
401
401
  const { cortex, tools } = harness;
402
402
  try {
403
403
  const written = cortex.write({
404
- text: '读取契约:正文里要有白饭。',
404
+ text: '读取契约:正文里要有米饭。',
405
405
  title: '读取标题',
406
406
  summary: '读取摘要',
407
407
  kind: 'observation',
408
408
  confidence: 0.75,
409
- tags: ['读取', '白饭'],
409
+ tags: ['读取', '米饭'],
410
410
  explicit: true,
411
411
  });
412
412
  const text = await call(tools.cortex_get, { id: written.trace.id });
@@ -416,8 +416,8 @@ test('cortex_get: full trace rendering and unknown id sentinel', async () => {
416
416
  assert.match(text, /置信:0\.75/);
417
417
  assert.match(text, /状态:active\/raw · 稳定性 1\.00 · 难度 5\.00/);
418
418
  assert.match(text, /摘要:读取摘要/);
419
- assert.match(text, /正文里要有白饭/);
420
- assert.match(text, /标签:读取、白饭/);
419
+ assert.match(text, /正文里要有米饭/);
420
+ assert.match(text, /标签:读取、米饭/);
421
421
 
422
422
  assert.equal(await call(tools.cortex_get, { id: 'trc_does_not_exist' }), '没有这条记忆:trc_does_not_exist');
423
423
  // Missing required args are not validated by the host here, but the tool
@@ -468,15 +468,15 @@ test('cortex_as_of: strict, historical, belief and associative views', async ()
468
468
  try {
469
469
  const t1 = Date.parse('2026-11-10T10:00:00+08:00');
470
470
  const t2 = Date.parse('2026-11-11T10:00:00+08:00');
471
- cortex.write({ text: '用户喜欢白饭。', explicit: true, now: t1, facts: [{ subject: '用户', predicate: '喜欢', object: '白饭' }] });
471
+ cortex.write({ text: '用户喜欢米饭。', explicit: true, now: t1, facts: [{ subject: '用户', predicate: '喜欢', object: '米饭' }] });
472
472
  cortex.write({ text: '用户现在喜欢面。', explicit: true, now: t2, facts: [{ subject: '用户', predicate: '喜欢', object: '面' }] });
473
473
  let text = await call(tools.cortex_as_of, { subject: '用户', predicate: '喜欢', at: new Date(t1 + 1000).toISOString(), mode: 'historical' });
474
- assert.match(text, /喜欢 → 白饭/);
474
+ assert.match(text, /喜欢 → 米饭/);
475
475
  text = await call(tools.cortex_as_of, { subject: '用户', predicate: '喜欢', mode: 'strict' });
476
476
  assert.match(text, /喜欢 → 面/);
477
- assert.doesNotMatch(text, /喜欢 → 白饭/);
477
+ assert.doesNotMatch(text, /喜欢 → 米饭/);
478
478
  text = await call(tools.cortex_as_of, { subject: '用户', mode: 'associative' });
479
- assert.match(text, /白饭/);
479
+ assert.match(text, /米饭/);
480
480
  assert.match(text, /面/);
481
481
  text = await call(tools.cortex_as_of, { subject: '不存在的主体' });
482
482
  assert.match(text, /没有/);
@@ -522,7 +522,7 @@ test('cortex_feedback: every signal updates DSR/confidence without throwing', as
522
522
  const harness = makeHarness();
523
523
  const { cortex, tools } = harness;
524
524
  try {
525
- const written = cortex.write({ text: '反馈契约:用户会买白饭。', explicit: true });
525
+ const written = cortex.write({ text: '反馈契约:用户会买米饭。', explicit: true });
526
526
  let text = await call(tools.cortex_feedback, {
527
527
  id: written.trace.id,
528
528
  signal: 'used',
@@ -567,10 +567,10 @@ test('cortex_forget: archive stays searchable, delete cascades on a disposable t
567
567
  const base = Date.now();
568
568
  try {
569
569
  const archived = cortex.write({
570
- text: '归档契约:用户会买白饭。',
570
+ text: '归档契约:用户会买米饭。',
571
571
  title: '归档目标',
572
572
  explicit: true,
573
- facts: [{ subject: '用户', predicate: '会买', objectLiteral: '白饭', confidence: 0.9 }],
573
+ facts: [{ subject: '用户', predicate: '会买', objectLiteral: '米饭', confidence: 0.9 }],
574
574
  now: base,
575
575
  });
576
576
  await call(tools.cortex_feedback, { id: archived.trace.id, signal: 'used' });
@@ -632,7 +632,7 @@ test('cortex_reflect: needs two traces, creates a reflection, skips duplicates a
632
632
  const onlyOne = await call(tools.cortex_reflect, {});
633
633
  assert.match(onlyOne, /^未整理:not-enough-traces/);
634
634
 
635
- await call(tools.cortex_write, { text: '反思契约第一条:用户喜欢白饭。', explicit: true });
635
+ await call(tools.cortex_write, { text: '反思契约第一条:用户喜欢米饭。', explicit: true });
636
636
  await call(tools.cortex_write, { text: '反思契约第二条:助手会等用户。', explicit: true });
637
637
 
638
638
  const first = await call(tools.cortex_reflect, {});
@@ -669,7 +669,7 @@ test('cortex_self: snapshot fields, relationship/calibration feedback and read-o
669
669
  assert.doesNotMatch(text, /关系:/);
670
670
  assert.doesNotMatch(text, /校准:/);
671
671
 
672
- const written = cortex.write({ text: '自我契约:用户喜欢白饭。', explicit: true });
672
+ const written = cortex.write({ text: '自我契约:用户喜欢米饭。', explicit: true });
673
673
  await call(tools.cortex_feedback, { id: written.trace.id, signal: 'used', predicted: 0.8 });
674
674
  await call(tools.cortex_working, { action: 'add', text: '写自我契约测试。' });
675
675
  await call(tools.cortex_goal, { action: 'add', title: '完成自我契约测试' });
@@ -693,9 +693,9 @@ test('cortex_health: clean audits, concrete counts, FTS drift detection and read
693
693
  try {
694
694
  const first = cortex.write({ text: '健康契约第一条。', explicit: true, now: base });
695
695
  const second = cortex.write({
696
- text: '健康契约第二条:用户喜欢白饭。',
696
+ text: '健康契约第二条:用户喜欢米饭。',
697
697
  explicit: true,
698
- facts: [{ subject: '用户', predicate: '喜欢', objectLiteral: '白饭', confidence: 0.8 }],
698
+ facts: [{ subject: '用户', predicate: '喜欢', objectLiteral: '米饭', confidence: 0.8 }],
699
699
  now: base + 1_000,
700
700
  });
701
701
  assert.equal(first.skipped, false);
@@ -733,10 +733,10 @@ test('cortex_guard: check, backup, validate, restore-to-temp, repair and export'
733
733
  const { cortex, tools } = harness;
734
734
  try {
735
735
  const written = cortex.write({
736
- text: '守卫契约:用户会买白饭。',
737
- title: '白饭承诺',
736
+ text: '守卫契约:用户会买米饭。',
737
+ title: '米饭承诺',
738
738
  explicit: true,
739
- facts: [{ subject: '用户', predicate: '会买', objectLiteral: '白饭', confidence: 0.9 }],
739
+ facts: [{ subject: '用户', predicate: '会买', objectLiteral: '米饭', confidence: 0.9 }],
740
740
  });
741
741
  assert.equal(written.skipped, false);
742
742
 
@@ -771,7 +771,7 @@ test('cortex_guard: check, backup, validate, restore-to-temp, repair and export'
771
771
  assert.equal(restored.prepare('PRAGMA integrity_check').get().integrity_check, 'ok');
772
772
  assert.equal(Number(restored.prepare('SELECT COUNT(*) AS c FROM traces').get().c), 1);
773
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, '守卫契约:用户会买白饭。');
774
+ assert.equal(restored.prepare('SELECT content FROM traces LIMIT 1').get().content, '守卫契约:用户会买米饭。');
775
775
  } finally {
776
776
  restored.close();
777
777
  }
@@ -810,7 +810,7 @@ test('cortex_guard: check, backup, validate, restore-to-temp, repair and export'
810
810
  assert.match(text, /记忆 1 条(跳过 secret 0 条)/);
811
811
  const memoryFile = path.join(mirror, 'MEMORY.md');
812
812
  assert.ok(fs.existsSync(memoryFile));
813
- assert.match(fs.readFileSync(memoryFile, 'utf8'), /守卫契约:用户会买白饭。/);
813
+ assert.match(fs.readFileSync(memoryFile, 'utf8'), /守卫契约:用户会买米饭。/);
814
814
  for (const file of ['SELF.md', 'FACTS.md', 'SKILLS.md']) {
815
815
  assert.ok(fs.existsSync(path.join(mirror, file)), `${file} must be exported`);
816
816
  }
@@ -905,17 +905,17 @@ test('cortex_emotion: detect, record, affect, events and lexicon', async () => {
905
905
  assert.equal(await call(tools.cortex_emotion, { action: 'affect' }), '(情感库还没有形成态度)');
906
906
  assert.equal(await call(tools.cortex_emotion, { action: 'events' }), '(没有情绪事件)');
907
907
 
908
- text = await call(tools.cortex_emotion, { action: 'record', text: '助手很开心,也很喜欢用户。', target: '用户' });
908
+ text = await call(tools.cortex_emotion, { action: 'record', text: '助手很开心,也很喜欢阿澈。', target: '阿澈' });
909
909
  assert.match(text, /^已记情绪事件 emo_/);
910
- assert.match(text, /喜、爱 → 用户/);
911
- text = await call(tools.cortex_emotion, { action: 'record', text: '助手有点难过。', target: '用户' });
910
+ assert.match(text, /喜、爱 → 阿澈/);
911
+ text = await call(tools.cortex_emotion, { action: 'record', text: '助手有点难过。', target: '阿澈' });
912
912
  assert.match(text, /^已记情绪事件 emo_/);
913
913
 
914
914
  text = await call(tools.cortex_emotion, { action: 'affect' });
915
- assert.equal(text, '用户:又喜又爱(2 次)');
915
+ assert.equal(text, '阿澈:又喜又爱(2 次)');
916
916
  text = await call(tools.cortex_emotion, { action: 'events', limit: 1 });
917
917
  assert.equal(text.split('\n').length, 1);
918
- assert.match(text, /用户/);
918
+ assert.match(text, /阿澈/);
919
919
  assert.match(text, /助手/);
920
920
  text = await call(tools.cortex_emotion, { action: 'events', limit: 10 });
921
921
  assert.match(text, /助手很开心/);
@@ -923,7 +923,7 @@ test('cortex_emotion: detect, record, affect, events and lexicon', async () => {
923
923
 
924
924
  const eventCount = cortex.emotion.events({ limit: 10 }).length;
925
925
  assert.equal(eventCount, 2);
926
- text = await call(tools.cortex_emotion, { action: 'record', text: '今天只是普通的一天。', target: '用户' });
926
+ text = await call(tools.cortex_emotion, { action: 'record', text: '今天只是普通的一天。', target: '阿澈' });
927
927
  assert.equal(text, '没有命中情绪词。');
928
928
  assert.equal(cortex.emotion.events({ limit: 10 }).length, eventCount);
929
929
  } finally {
@@ -968,7 +968,7 @@ test('cortex_life: diary entries, dreams, sleep and sleep-run history', async ()
968
968
  assert.equal(emptyDreams.length, 1);
969
969
  assert.equal(emptyDreams[0].sourceCount, 0);
970
970
 
971
- await call(tools.cortex_write, { text: '生活侧记忆第一条:用户喜欢白饭。', explicit: true });
971
+ await call(tools.cortex_write, { text: '生活侧记忆第一条:用户喜欢米饭。', explicit: true });
972
972
  await call(tools.cortex_write, { text: '生活侧记忆第二条:助手会等用户。', explicit: true });
973
973
  text = await call(tools.cortex_life, { action: 'dream' });
974
974
  assert.match(text, /^梦 drm_.*(来源 2 条,template):/);
@@ -1003,7 +1003,7 @@ test('cortex_compress: evaluate, compress an old covered trace and revive it', a
1003
1003
  const { cortex, tools } = harness;
1004
1004
  try {
1005
1005
  const old = cortex.write({
1006
- text: '压缩契约:一段旧的白饭记忆。',
1006
+ text: '压缩契约:一段旧的米饭记忆。',
1007
1007
  title: '旧记忆',
1008
1008
  explicit: true,
1009
1009
  importance: 0.05,
@@ -1061,7 +1061,7 @@ test('cortex_working: add, list, pin, remove and purge expired entries', async (
1061
1061
  const first = idOf(text, 'wrk');
1062
1062
  text = await call(tools.cortex_working, {
1063
1063
  action: 'add',
1064
- text: '置顶焦点:别忘白饭。',
1064
+ text: '置顶焦点:别忘米饭。',
1065
1065
  kind: 'focus',
1066
1066
  priority: 0.9,
1067
1067
  pinned: true,
@@ -1072,7 +1072,7 @@ test('cortex_working: add, list, pin, remove and purge expired entries', async (
1072
1072
  text = await call(tools.cortex_working, { action: 'list' });
1073
1073
  assert.match(text, new RegExp(`\\[pin\\] ${second}`));
1074
1074
  assert.match(text, new RegExp(`- ${first} \\(0\\.5\\)`));
1075
- assert.match(text, /别忘白饭/);
1075
+ assert.match(text, /别忘米饭/);
1076
1076
 
1077
1077
  text = await call(tools.cortex_working, { action: 'pin', id: first, pinned: true });
1078
1078
  assert.equal(text, `已置顶 ${first}`);
@@ -1225,7 +1225,7 @@ test('cortex_tick: status, safe execution and proposals that need approval', asy
1225
1225
  text = await call(tools.cortex_tick, { action: 'run' });
1226
1226
  assert.equal(text, '执行 0 条,提案 0 条。');
1227
1227
 
1228
- await call(tools.cortex_write, { text: 'tick 契约第一条:用户喜欢白饭。', explicit: true });
1228
+ await call(tools.cortex_write, { text: 'tick 契约第一条:用户喜欢米饭。', explicit: true });
1229
1229
  await call(tools.cortex_write, { text: 'tick 契约第二条:助手会等用户。', explicit: true });
1230
1230
 
1231
1231
  const now = Date.now();
@@ -1237,8 +1237,8 @@ test('cortex_tick: status, safe execution and proposals that need approval', asy
1237
1237
  const recall = cortex.stores.initiativeStore.insert({
1238
1238
  kind: 'recall',
1239
1239
  priority: 0.9,
1240
- reason: '想再确认白饭',
1241
- payload: { topic: '白饭' },
1240
+ reason: '想再确认米饭',
1241
+ payload: { topic: '米饭' },
1242
1242
  ...schedule,
1243
1243
  }, { scopeId: 'global' });
1244
1244
  const propose = cortex.stores.initiativeStore.insert({
@@ -1251,7 +1251,7 @@ test('cortex_tick: status, safe execution and proposals that need approval', asy
1251
1251
  const consolidate = cortex.stores.initiativeStore.insert({
1252
1252
  kind: 'consolidate',
1253
1253
  priority: 0.7,
1254
- reason: '整理白饭记忆',
1254
+ reason: '整理米饭记忆',
1255
1255
  payload: { reason: 'coherence' },
1256
1256
  ...schedule,
1257
1257
  }, { scopeId: 'global' });
@@ -0,0 +1,87 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createCortex } from '../../src/service/cortex.js';
7
+ import { createTargetResolver } from '../../src/self/alias.js';
8
+ import { openDatabase, migrate, closeDatabase } from '../../src/store/database.js';
9
+ import { createRelationshipStore } from '../../src/self/relationship.js';
10
+ import { createEmotionModel } from '../../src/self/emotion.js';
11
+
12
+ function tempDb() {
13
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-alias-'));
14
+ const { db } = openDatabase({ dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') });
15
+ migrate(db);
16
+ return { dir, db };
17
+ }
18
+
19
+ test('resolver folds common aliases onto the configured user address', () => {
20
+ const { resolveTarget, canonical } = createTargetResolver({ userAddress: '用户' });
21
+ assert.equal(canonical, '用户');
22
+ assert.equal(resolveTarget('用户'), '用户');
23
+ assert.equal(resolveTarget('用户'), '用户');
24
+ assert.equal(resolveTarget(' 用户 '), '用户');
25
+ assert.equal(resolveTarget('小忆'), '小忆');
26
+ const custom = createTargetResolver({ userAddress: '用户', userAliases: ['阿澈'] });
27
+ assert.equal(custom.resolveTarget('阿澈'), '用户');
28
+ });
29
+
30
+ test('relationship writes through an alias land on the canonical target', () => {
31
+ const { dir, db } = tempDb();
32
+ try {
33
+ const { resolveTarget } = createTargetResolver({ userAddress: '用户' });
34
+ const store = createRelationshipStore(db, { resolveTarget });
35
+ store.applyDelta('global', '用户', { trustDelta: 0.2, careDelta: 0.3 }, { event: 'feedback:helpful' });
36
+ assert.equal(store.list('global').length, 1);
37
+ assert.equal(store.list('global')[0].target, '用户');
38
+ assert.ok(store.get('global', '用户').trust > 0.5);
39
+ } finally {
40
+ closeDatabase(db);
41
+ rmSync(dir, { recursive: true, force: true });
42
+ }
43
+ });
44
+
45
+ test('emotion records through an alias land on the canonical target', () => {
46
+ const { dir, db } = tempDb();
47
+ try {
48
+ const { resolveTarget } = createTargetResolver({ userAddress: '用户' });
49
+ const emotion = createEmotionModel({ db, resolveTarget });
50
+ emotion.record({ text: '用户说今天很开心。', target: '用户' });
51
+ const targets = emotion.targets();
52
+ assert.equal(targets.length, 1);
53
+ assert.equal(targets[0].target, '用户');
54
+ } finally {
55
+ closeDatabase(db);
56
+ rmSync(dir, { recursive: true, force: true });
57
+ }
58
+ });
59
+
60
+ test('maintain merges pre-existing alias rows into the canonical target', () => {
61
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-alias-merge-'));
62
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), persona: { userAddress: '用户' } } });
63
+ try {
64
+ const at = '2026-11-15T05:00:00.000Z';
65
+ cortex.db.prepare(`
66
+ INSERT INTO relationships(id, scope_id, target, trust, care, familiarity, expectations_json, boundaries_json, recent_json, updated_at)
67
+ VALUES ('rel_a', 'global', '用户', 0.6, 0.6, 0.2, '[]', '[]', '[]', ?), ('rel_b', 'global', '你', 0.7, 0.5, 0.3, '[]', '[]', '[]', ?)
68
+ `).run(at, at);
69
+ cortex.db.prepare(`
70
+ INSERT INTO affect_targets(scope_id, target, scores_json, count, attitude, updated_at)
71
+ VALUES ('global', '用户', '{"暖":3}', 3, '暖', ?), ('global', '你', '{"甜":2}', 2, '甜', ?)
72
+ `).run(at, at);
73
+ const report = cortex.maintain({ now: Date.parse(at), scopeId: 'global' });
74
+ assert.equal(report.aliases, 2);
75
+ const rels = cortex.stores.relationshipStore.list('global');
76
+ assert.equal(rels.length, 1);
77
+ assert.equal(rels[0].target, '用户');
78
+ assert.ok(rels[0].trust >= 0.7, 'trust keeps the higher value');
79
+ const affect = cortex.emotion.targets();
80
+ assert.equal(affect.length, 1);
81
+ assert.equal(affect[0].target, '用户');
82
+ assert.equal(affect[0].count, 5);
83
+ } finally {
84
+ cortex.close();
85
+ rmSync(dir, { recursive: true, force: true });
86
+ }
87
+ });
@@ -164,7 +164,7 @@ test('POST write sends JSON, x-cortex and the exact body', async () => {
164
164
  const { client, calls, queue } = harness();
165
165
  queue.push(ok({ trace: { id: 'tr1' } }));
166
166
 
167
- const input = { text: '用户说会买白饭。', tags: ['白饭'], explicit: true };
167
+ const input = { text: '用户说会买米饭。', tags: ['米饭'], explicit: true };
168
168
  const result = await client.write(input);
169
169
 
170
170
  assert.deepEqual(result, { trace: { id: 'tr1' } });
@@ -188,7 +188,7 @@ test('custom tokenHeader is sent as the x-cortex value', async () => {
188
188
  test('scopeId is sent on every request and validated', async () => {
189
189
  const { client, calls, queue } = harness({ scopeId: 'session:42' });
190
190
  queue.push(ok({ items: [] }));
191
- await client.search('白饭');
191
+ await client.search('米饭');
192
192
  assert.equal(calls[0].init.headers['x-cortex-scope'], 'session:42');
193
193
  assert.throws(() => createApiClient({ fetchImpl: async () => new Response('{}'), scopeId: 'bad scope' }), /scopeId/);
194
194
  });
@@ -240,7 +240,7 @@ test('feedback, forget, reflect and compress send only supported fields', async
240
240
  await client.compress();
241
241
  assert.deepEqual(parseBody(calls.at(-1)), {});
242
242
 
243
- queue.push(ok({ answer: '白饭 [1]', mode: 'extractive' }));
243
+ queue.push(ok({ answer: '米饭 [1]', mode: 'extractive' }));
244
244
  await client.qa({ question: '用户喜欢什么?' });
245
245
  assert.equal(pathOf(calls.at(-1)), '/api/cortex/qa');
246
246
  assert.deepEqual(parseBody(calls.at(-1)), { question: '用户喜欢什么?' });
@@ -3,9 +3,9 @@ import assert from 'node:assert/strict';
3
3
  import { validateWrite, validateFeedback, validateForget, validateSearch } from '../../src/api/validate.js';
4
4
 
5
5
  test('write validation accepts and normalizes a body', () => {
6
- const value = validateWrite({ text: ' 用户喜欢白饭。 ', tags: [' 白饭 ', ''], importance: 0.8, explicit: false });
7
- assert.equal(value.text, '用户喜欢白饭。');
8
- assert.deepEqual(value.tags, ['白饭']);
6
+ const value = validateWrite({ text: ' 用户喜欢米饭。 ', tags: [' 米饭 ', ''], importance: 0.8, explicit: false });
7
+ assert.equal(value.text, '用户喜欢米饭。');
8
+ assert.deepEqual(value.tags, ['米饭']);
9
9
  assert.equal(value.importance, 0.8);
10
10
  assert.equal(value.explicit, false);
11
11
  });
@@ -55,10 +55,10 @@ test('api serves health/self/search and writes through POST', async () => {
55
55
  const health = await invoke(handler, { route: '/health' });
56
56
  assert.equal(health.status, 200);
57
57
  assert.ok(health.json.data.score > 0);
58
- const write = await invoke(handler, { method: 'POST', route: '/write', body: { text: '用户说会买白饭。', explicit: true } });
58
+ const write = await invoke(handler, { method: 'POST', route: '/write', body: { text: '用户说会买米饭。', explicit: true } });
59
59
  assert.equal(write.status, 200);
60
- assert.equal(write.json.data.trace.content, '用户说会买白饭。');
61
- const search = await invoke(handler, { route: '/search?q=白饭' });
60
+ assert.equal(write.json.data.trace.content, '用户说会买米饭。');
61
+ const search = await invoke(handler, { route: '/search?q=米饭' });
62
62
  assert.equal(search.status, 200);
63
63
  assert.ok(search.json.data.items.length >= 1);
64
64
 
@@ -0,0 +1,141 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createCortex } from '../../src/service/cortex.js';
7
+
8
+ function setup() {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-auto-reflect-'));
10
+ const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
11
+ return { dir, cortex };
12
+ }
13
+
14
+ function fill(cortex, count, now, prefix = '日常') {
15
+ for (let i = 0; i < count; i += 1) {
16
+ cortex.write({ text: `用户:${prefix}第 ${i} 条,记录一下天气和心情。`, kind: 'utterance', title: `${prefix} ${i}`, explicit: true, now });
17
+ }
18
+ }
19
+
20
+ test('材料够时自动写一条 episode,同一窗口内不再写第二条', () => {
21
+ const { dir, cortex } = setup();
22
+ try {
23
+ const now = Date.now();
24
+ fill(cortex, 60, now);
25
+ const first = cortex.maintain({ now });
26
+ assert.equal(first.reflection?.created, true, '材料够时应该生成摘要');
27
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 1);
28
+
29
+ const second = cortex.maintain({ now: now + 60_000 });
30
+ assert.equal(second.reflection?.skipped, 'covered', '同一 24h 窗口只写一条');
31
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 1);
32
+ } finally {
33
+ cortex.close();
34
+ rmSync(dir, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ test('材料不足以下界时不写,并报出下界', () => {
39
+ const { dir, cortex } = setup();
40
+ try {
41
+ const now = Date.now();
42
+ fill(cortex, 40, now, '稀疏');
43
+ const report = cortex.maintain({ now });
44
+ assert.equal(report.reflection?.skipped, 'few-traces');
45
+ assert.equal(report.reflection?.minMaterial, 50);
46
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 0);
47
+ } finally {
48
+ cortex.close();
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ });
52
+
53
+ test('真实形态:痕迹铺满 24 小时时,7 小时后仍判为已覆盖', () => {
54
+ const { dir, cortex } = setup();
55
+ try {
56
+ const now = Date.now();
57
+ // 铺满整整一天:periodStart 会落在 now-24h 附近,这正是线上真实数据的形状。
58
+ for (let i = 0; i < 60; i += 1) {
59
+ cortex.write({ text: `用户:铺满窗口的第 ${i} 条记录,间隔二十四分钟。`, kind: 'utterance', title: `铺满 ${i}`, explicit: true, now: now - i * 24 * 60_000 });
60
+ }
61
+ assert.equal(cortex.maintain({ now }).reflection?.created, true);
62
+ const later = cortex.maintain({ now: now + 7 * 3_600_000 });
63
+ assert.equal(later.reflection?.skipped, 'covered', '铺满窗口时也必须按写入时间去重');
64
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 1);
65
+ } finally {
66
+ cortex.close();
67
+ rmSync(dir, { recursive: true, force: true });
68
+ }
69
+ });
70
+
71
+ test('跨过 24 小时之后可以再写一条', () => {
72
+ const { dir, cortex } = setup();
73
+ try {
74
+ const now = Date.now();
75
+ fill(cortex, 60, now, '跨天');
76
+ assert.equal(cortex.maintain({ now }).reflection?.created, true);
77
+ fill(cortex, 60, now + 25 * 3_600_000, '第二天');
78
+ const nextDay = cortex.maintain({ now: now + 25 * 3_600_000 });
79
+ assert.equal(nextDay.reflection?.created, true, '第二天应该允许再写一条');
80
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 2);
81
+ } finally {
82
+ cortex.close();
83
+ rmSync(dir, { recursive: true, force: true });
84
+ }
85
+ });
86
+
87
+ test('窗口已覆盖但新增材料 ≥150 且距上次 ≥6h,可以再写一段不重叠的', () => {
88
+ const { dir, cortex } = setup();
89
+ try {
90
+ const now = Date.now();
91
+ fill(cortex, 60, now, '第一段');
92
+ assert.equal(cortex.maintain({ now }).reflection?.created, true);
93
+ const first = cortex.repos.summaries.list('global', { level: 'episode', limit: 5 })[0];
94
+
95
+ const later = now + 7 * 3_600_000;
96
+ fill(cortex, 160, later, '第二段');
97
+ const report = cortex.maintain({ now: later });
98
+ assert.equal(report.reflection?.created, true, '材料够就该写第二段');
99
+ const episodes = cortex.repos.summaries.list('global', { level: 'episode', limit: 5 });
100
+ assert.equal(episodes.length, 2);
101
+ const second = episodes[0];
102
+ assert.ok(Date.parse(second.periodStart) > Date.parse(first.periodEnd), '第二段必须接在第一段结束之后,不重叠');
103
+ assert.equal(second.model, 'extractive-v2-segment', '分段摘要要打上标记');
104
+ } finally {
105
+ cortex.close();
106
+ rmSync(dir, { recursive: true, force: true });
107
+ }
108
+ });
109
+
110
+ test('新增材料不够 150 时仍是 covered,不写第二段', () => {
111
+ const { dir, cortex } = setup();
112
+ try {
113
+ const now = Date.now();
114
+ fill(cortex, 60, now, '第一段');
115
+ assert.equal(cortex.maintain({ now }).reflection?.created, true);
116
+ const later = now + 7 * 3_600_000;
117
+ fill(cortex, 60, later, '第二段');
118
+ const report = cortex.maintain({ now: later });
119
+ assert.equal(report.reflection?.skipped, 'covered');
120
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 1);
121
+ } finally {
122
+ cortex.close();
123
+ rmSync(dir, { recursive: true, force: true });
124
+ }
125
+ });
126
+
127
+ test('材料极少时一条都不写', () => {
128
+ const { dir, cortex } = setup();
129
+ try {
130
+ const now = Date.now();
131
+ for (let i = 0; i < 3; i += 1) {
132
+ cortex.write({ text: `用户:只有第 ${i} 条。`, kind: 'utterance', title: `少量 ${i}`, explicit: true, now });
133
+ }
134
+ const report = cortex.maintain({ now });
135
+ assert.equal(report.reflection?.skipped, 'few-traces');
136
+ assert.equal(cortex.repos.summaries.list('global', { level: 'episode', limit: 5 }).length, 0);
137
+ } finally {
138
+ cortex.close();
139
+ rmSync(dir, { recursive: true, force: true });
140
+ }
141
+ });