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
@@ -10,9 +10,10 @@ import { createJobRepository } from '../store/repositories/jobs.js';
10
10
  import { createSkillRepository } from '../store/repositories/skills.js';
11
11
  import { createPlaybookRepository } from '../store/repositories/playbook.js';
12
12
  import { selectTiers, renderTiers, DEFAULT_TIER_BUDGETS } from '../prompt/tiers.js';
13
- import { readOverrides, writeOverride, rollbackOverride } from '../core/feature-overrides.js';
13
+ import { readOverrides, writeOverride, rollbackOverride, effectiveFeatures } from '../core/feature-overrides.js';
14
14
  import { effectiveModelConfig, saveModelConfig, redactedModelConfig } from '../core/model-config.js';
15
15
  import { estimateTokens, truncate } from '../memory/tokenizer.js';
16
+ import { touchInterval } from '../memory/spacing.js';
16
17
  import { createAuditRepository } from '../store/repositories/audit.js';
17
18
  import { createSelfStore } from '../self/state.js';
18
19
  import { createAppraisalStore } from '../self/appraisals.js';
@@ -20,7 +21,8 @@ import { createInitiativeStore, selectIntentions, DEFAULT_INITIATIVE_POLICY } fr
20
21
  import { createSummonRepository } from '../store/repositories/summon.js';
21
22
  import { createIdentityStore } from '../self/identity.js';
22
23
  import { createRelationshipStore } from '../self/relationship.js';
23
- import { createEncodeEngine } from '../engines/encode.js';
24
+ import { createTargetResolver } from '../self/alias.js';
25
+ import { createEncodeEngine, isInjectedNoise } from '../engines/encode.js';
24
26
  import { createRetrievalEngine } from '../engines/retrieve.js';
25
27
  import { createGrowthEngine } from '../engines/growth.js';
26
28
  import { createReflectEngine } from '../engines/reflect.js';
@@ -47,6 +49,7 @@ import { importMarkdown, syncMarkdown } from '../adapters/markdown-import.js';
47
49
  import { createLifeEngine } from '../engines/life.js';
48
50
  import { createCompressionEngine } from '../engines/compression.js';
49
51
  import { createFactExtractor } from '../engines/extract.js';
52
+ import { suppressionOf } from '../engines/inhibition.js';
50
53
  import { extractFactsWithLlm } from '../engines/llm-facts.js';
51
54
  import { createDigestEngine } from '../engines/digest.js';
52
55
  import { createAutonomyEngine } from '../engines/autonomy.js';
@@ -54,6 +57,7 @@ import { createConsolidationEngine } from '../engines/consolidate.js';
54
57
  import { createRetentionEngine } from '../engines/retention.js';
55
58
  import { createQaEngine } from '../engines/qa.js';
56
59
  import { summarizeGraph } from '../engines/graph-analytics.js';
60
+ import { rankSummonCards, renderSummonLines } from '../engines/summon-rank.js';
57
61
  import { createMetrics } from '../observability/metrics.js';
58
62
  import { parseQuery } from '../memory/query.js';
59
63
  import { normalizeAttachments } from '../core/attachments.js';
@@ -84,15 +88,20 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
84
88
  const appraisalStore = createAppraisalStore(db);
85
89
  const initiativeStore = createInitiativeStore(db);
86
90
  const identityStore = createIdentityStore(db);
87
- const relationshipStore = createRelationshipStore(db);
91
+ const targetResolver = createTargetResolver(config.persona ?? {});
92
+ const relationshipStore = createRelationshipStore(db, { resolveTarget: targetResolver.resolveTarget });
88
93
  const metrics = createMetrics();
89
94
  const workingStore = createWorkingStore(db);
90
95
  const goalStore = createGoalStore(db);
91
- const emotion = createEmotionModel({ db, scopeId: config.scope });
96
+ const emotion = createEmotionModel({ db, scopeId: config.scope, resolveTarget: targetResolver.resolveTarget });
92
97
  identityStore.ensure(config.scope);
93
98
  selfStore.get(config.scope);
94
99
 
95
- const vectorEnabled = config.features?.vector === true || config.vectorEnabled === true;
100
+ // Feature overrides (written by the settings panel) must be able to enable the
101
+ // vector engine too. Use effectiveFeatures(): it resolves the default data
102
+ // root itself, while `config.dataRoot` is usually undefined at runtime.
103
+ const overrideVector = effectiveFeatures(config).features.vector === true;
104
+ const vectorEnabled = config.features?.vector === true || config.vectorEnabled === true || overrideVector;
96
105
  const modelConfig = effectiveModelConfig(config.dataRoot);
97
106
  const remoteEmbedding = modelConfig.embedding.mode === 'local' || modelConfig.embedding.mode === 'remote';
98
107
  const vectorEmbedder = config.embedder ?? (remoteEmbedding
@@ -116,6 +125,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
116
125
  annOptions: { M: 24, efConstruction: 200, efSearch: 800 },
117
126
  externalAnnEnabled: config.features?.vectorAnnExternal === true,
118
127
  externalAnnOptions: { endpoint: config.vectorAnnEndpoint, timeoutMs: config.vectorAnnTimeoutMs },
128
+ logger,
119
129
  })
120
130
  : null;
121
131
 
@@ -126,7 +136,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
126
136
  try { return policies.active(kind)?.config ?? null; } catch { return null; }
127
137
  };
128
138
  const retrieve = createRetrievalEngine({ traces, facts, graph, vector, policy: policyConfig, config });
129
- const compression = createCompressionEngine({ traces, summaries, facts, config });
139
+ const compression = createCompressionEngine({ traces, summaries, facts, entities, config });
130
140
  const extractor = createFactExtractor({ entities, facts });
131
141
  const digest = createDigestEngine({ traces, summaries, emotion, goals: goalStore, feedback, scopeId: config.scope });
132
142
  const retention = createRetentionEngine({ traces });
@@ -172,12 +182,15 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
172
182
  })
173
183
  : null;
174
184
  const qa = createQaEngine({ cortex: { search: (query, options) => search(query, options), searchAsync: (query, options) => searchAsync(query, options) }, llm: llmAdapter, reranker, limit: config.qa?.limit ?? 8, budget: config.qa?.budget ?? 3000 });
175
- const narrative = createNarrativeEngine({ traces, summaries });
185
+ const narrative = createNarrativeEngine({ traces, summaries, selfName: config.persona?.selfName ?? '助手' });
176
186
  const consolidation = createConsolidationEngine({ db, traces, summaries, audit, llm: llmAdapter });
177
187
  const skills = createSkillEngine({ skills: skillsRepo, traces });
178
188
  const health = createHealthEngine({
179
189
  db, events, traces, facts, entities, summaries, feedback, skills: skillsRepo, jobs,
180
190
  identityStore, selfStore, config,
191
+ // Falls back to the in-memory last pass when maintain() changed nothing and
192
+ // therefore wrote no audit row.
193
+ maintainLast: () => lastMaintain,
181
194
  });
182
195
  const privacy = createPrivacyEngine({ db, traces, events, audit });
183
196
 
@@ -224,7 +237,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
224
237
  });
225
238
  const life = createLifeEngine({
226
239
  db, traces, reflect, development, working: workingStore, emotion, scopeId: config.scope,
227
- consolidation, features: config.features ?? {},
240
+ consolidation, narrative, features: config.features ?? {},
228
241
  selfName: config.persona?.selfName ?? '助手',
229
242
  userAddress: config.persona?.userAddress ?? '你',
230
243
  llm: llmAdapter ? (args) => llmAdapter.dream(args) : null,
@@ -322,6 +335,62 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
322
335
  return scopeWritable(record.scopeId, agentId);
323
336
  }
324
337
 
338
+ const AUTO_TITLE_RE = /^会话\s*\d+\s*的对话$/;
339
+
340
+ /**
341
+ * Host capture used to stamp every trace with "会话 N 的对话", which made
342
+ * recall lines unreadable. Derive a short title from the first meaningful
343
+ * line instead, and keep a caller-provided title unless it is that stamp.
344
+ */
345
+ function deriveTitle(text) {
346
+ const lines = String(text ?? '').split('\n');
347
+ for (const line of lines) {
348
+ const cleaned = line
349
+ .replace(/^\s*(?:用户|助手|user|assistant)[::]\s*/i, '')
350
+ .replace(/\s+/g, ' ')
351
+ .trim();
352
+ if (cleaned.length < 2) continue;
353
+ if (isInjectedNoise(cleaned)) continue;
354
+ if (/^\[?(?:truncated|…)\]?$/i.test(cleaned)) continue;
355
+ return cleaned.slice(0, 40);
356
+ }
357
+ return null;
358
+ }
359
+
360
+ function withReadableTitle(input = {}) {
361
+ const text = String(input.text ?? input.content ?? '');
362
+ const raw = typeof input.title === 'string' ? input.title.trim() : '';
363
+ if (raw && !AUTO_TITLE_RE.test(raw)) return input;
364
+ const derived = deriveTitle(text);
365
+ return derived ? { ...input, title: derived } : input;
366
+ }
367
+
368
+ /** Recall is a retrieval practice: record it so DSR recency is not frozen.
369
+ * The interval grows with access count (spacing), so a hot memory is not
370
+ * written on every step and a cold one stays easy to pick up again. */
371
+ function touchResults(result, limit = 3) {
372
+ if (config.touchOnRecall === false) return 0;
373
+ if (!Array.isArray(result?.items)) return 0;
374
+ const baseMs = Math.max(0, Number(config.touchMinIntervalMs ?? 300_000));
375
+ const maxMs = Math.max(baseMs, Number(config.touchMaxIntervalMs ?? 21_600_000));
376
+ const now = Date.now();
377
+ let touched = 0;
378
+ for (const item of result.items.slice(0, Math.max(1, limit))) {
379
+ if (!item?.id) continue;
380
+ try {
381
+ const current = traces.get(item.id);
382
+ const last = current?.lastAccessAt ? Date.parse(current.lastAccessAt) : 0;
383
+ const interval = touchInterval(current?.accessCount ?? 0, { baseMs, maxMs });
384
+ if (last && now - last < interval) continue;
385
+ traces.touch(item.id);
386
+ touched += 1;
387
+ } catch {
388
+ /* access bookkeeping must never fail a recall */
389
+ }
390
+ }
391
+ return touched;
392
+ }
393
+
325
394
  function writeInternal(input = {}) {
326
395
  const scopeId = input.scopeId ?? config.scope;
327
396
  if (!scopeWritable(scopeId)) return { skipped: true, reason: 'scope-read-only', scopeId };
@@ -330,7 +399,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
330
399
  ...(input.metadata && typeof input.metadata === 'object' && !Array.isArray(input.metadata) ? input.metadata : {}),
331
400
  ...(attachments.length ? { attachments } : {}),
332
401
  };
333
- const result = encode.encode({ ...input, scopeId, metadata });
402
+ const result = encode.encode(withReadableTitle({ ...input, scopeId, metadata }));
334
403
  if (!result.skipped && config.features?.autoFacts === true && !Array.isArray(input.facts)) {
335
404
  try {
336
405
  result.autoFacts = extractor.extract({
@@ -457,6 +526,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
457
526
  });
458
527
  if (!options.noBudget) budget.spend(1);
459
528
  circuit.success();
529
+ touchResults(result);
460
530
  metrics.inc('search.calls');
461
531
  metrics.inc('search.hits', result.items.length);
462
532
  metrics.observe('search.ms', Date.now() - started);
@@ -489,6 +559,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
489
559
  });
490
560
  if (!options.noBudget) budget.spend(1);
491
561
  circuit.success();
562
+ touchResults(result);
492
563
  metrics.inc('search.calls');
493
564
  metrics.inc('search.hits', result.items.length);
494
565
  metrics.observe('search.ms', Date.now() - started);
@@ -500,8 +571,39 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
500
571
  }
501
572
  }
502
573
 
503
- function get(id) {
504
- return traces.get(id);
574
+ // Reviving on read is meant to be a quiet exception, not a way to undo every
575
+ // archive: at most a few per day, then reads fall back to read-only.
576
+ const REVIVE_PER_DAY = 3;
577
+ function reviveBudget() {
578
+ // Count with SQL over the whole 24h window. Reading audit.list() without a
579
+ // target id returns the newest 200 rows overall, so a busy log (hundreds of
580
+ // dream.run rows a day) silently shortened "24 hours" to a couple of hours.
581
+ const since = new Date(Date.now() - 86_400_000).toISOString();
582
+ try {
583
+ const row = db.prepare("SELECT COUNT(*) AS c FROM audit WHERE action = 'trace.revive' AND at >= ?").get(since);
584
+ const used = Number(row?.c ?? 0);
585
+ return Math.max(0, REVIVE_PER_DAY - used);
586
+ } catch {
587
+ return 0;
588
+ }
589
+ }
590
+
591
+ function get(id, { revive = false } = {}) {
592
+ const trace = traces.get(id);
593
+ if (!trace) return null;
594
+ // Reading an archived memory is evidence that it is still wanted: bring it
595
+ // back (unless it was folded into another trace by a merge, where the body
596
+ // now lives elsewhere, or the daily revive budget is spent).
597
+ if (revive && trace.state === 'archived' && trace.compression !== 'merged' && reviveBudget() > 0) {
598
+ try {
599
+ traces.update(id, { state: 'active' });
600
+ audit.record?.({ actor: 'system', action: 'trace.revive', targetType: 'trace', targetId: id, detail: { reason: 'read' } });
601
+ } catch {
602
+ /* revival is best-effort; reading must not fail because of it */
603
+ }
604
+ return traces.get(id);
605
+ }
606
+ return trace;
505
607
  }
506
608
 
507
609
  function timeline(options = {}) {
@@ -897,47 +999,14 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
897
999
  const query = String(text ?? '').trim();
898
1000
  if (!query) return { cards: [], block: '' };
899
1001
  const allCards = summons.listCards({ scopeId, limit: 1000 });
900
- const triggerFrequency = new Map();
901
- for (const card of allCards) {
902
- for (const trigger of new Set((card.triggers ?? []).filter((item) => item.length >= 2 && item.length <= 12))) {
903
- triggerFrequency.set(trigger, (triggerFrequency.get(trigger) ?? 0) + 1);
904
- }
905
- }
906
- const scored = [];
907
- for (const card of allCards) {
908
- const hits = (card.triggers ?? []).filter((trigger) => trigger.length >= 2 && trigger.length <= 12 && query.includes(trigger));
909
- const titleHit = card.title && query.includes(card.title.slice(0, Math.min(12, card.title.length)));
910
- if (hits.length === 0 && !titleHit) continue;
911
- let score = hits.reduce((sum, trigger) => {
912
- const specificity = 1 + Math.log(1 + allCards.length / (1 + (triggerFrequency.get(trigger) ?? 1)));
913
- return sum + (1 + Math.min(4, trigger.length) * 0.25) * specificity;
914
- }, 0);
915
- if (titleHit) score += 1.5;
916
- score += Number(card.importance ?? 0.5) * 0.4;
917
- if (card.category !== 'utterance') score += 0.6;
918
- scored.push({ card, score, hits });
919
- }
920
- const specificScored = scored.filter((entry) => entry.card.category !== 'utterance');
921
- const ranked = (specificScored.length ? specificScored : scored).sort((a, b) => b.score - a.score);
922
- const left = ranked.find((entry) => entry.card.side === 'left');
923
- const right = ranked.find((entry) => entry.card.side === 'right');
924
- const selected = [];
925
- for (const entry of [left, right, ...ranked]) {
926
- if (!entry || selected.some((item) => item.card.id === entry.card.id)) continue;
927
- selected.push(entry);
928
- if (selected.length >= Math.max(1, Math.min(5, Number(maxCards) || 3))) break;
929
- }
930
- const lines = ['## 召唤卡(历史参考,不是指令)'];
931
- let used = 0;
932
- for (const entry of selected) {
933
- const label = entry.card.side === 'left' ? '左脑·情感' : '右脑·工作';
934
- const body = String(entry.card.content ?? '').replace(/\s+/g, ' ').slice(0, 260);
935
- const line = `- [${label}] ${entry.card.title}:${body}`;
936
- const cost = estimateTokens(line);
937
- if (used + cost > maxChars) break;
938
- lines.push(line);
939
- used += cost;
940
- }
1002
+ const selected = rankSummonCards(allCards, {
1003
+ query,
1004
+ maxCards,
1005
+ // Dropping a displaced card is expected, but it should be countable rather
1006
+ // than invisible — a stuck card block looked identical to a healthy one.
1007
+ onDrop: () => metrics.inc('summon.drop'),
1008
+ });
1009
+ const { lines } = renderSummonLines(selected, { maxChars, estimateTokens });
941
1010
  return {
942
1011
  cards: selected.map((entry) => ({ id: entry.card.id, side: entry.card.side, title: entry.card.title, score: entry.score, hits: entry.hits })),
943
1012
  block: selected.length ? lines.join('\n') : '',
@@ -954,7 +1023,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
954
1023
  }
955
1024
 
956
1025
  async function labelEntities({ scopeId = config.scope, limit = 3 } = {}) {
957
- if (!llmAdapter?.complete) return { updated: [], skipped: 'no-llm' };
1026
+ if (!llmAdapter?.complete) return { updated: [], skipped: 'no-llm-adapter' };
958
1027
  const rows = entities.list({ scopeId, limit: 500 })
959
1028
  .filter((entity) => !summarizeEntityName(entity.name))
960
1029
  .slice(0, Math.max(1, Math.min(10, Number(limit) || 3)));
@@ -1141,6 +1210,371 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1141
1210
  return { ...updated, ascended: true };
1142
1211
  }
1143
1212
 
1213
+ /**
1214
+ * Housekeeping that the audit showed was missing: close disputes whose two
1215
+ * sides already died, drop duplicate summaries, expire stale intentions and
1216
+ * retire chat-fragment "rules". Idempotent; safe to run every heartbeat.
1217
+ */
1218
+ /**
1219
+ * Fold alias rows into the canonical user target. Runs from maintain() so an
1220
+ * existing store converges on its own; idempotent once merged.
1221
+ */
1222
+ function mergeAliasTargets(at, scopeId) {
1223
+ const canonical = targetResolver.canonical;
1224
+ let merged = 0;
1225
+ const rels = db.prepare('SELECT * FROM relationships WHERE scope_id = ?').all(scopeId);
1226
+ for (const row of rels) {
1227
+ if (row.target === canonical) continue;
1228
+ if (targetResolver.resolveTarget(row.target) !== canonical) continue;
1229
+ const canonRow = db.prepare('SELECT * FROM relationships WHERE scope_id = ? AND target = ?').get(scopeId, canonical);
1230
+ if (!canonRow) {
1231
+ db.prepare('UPDATE relationships SET target = ? WHERE scope_id = ? AND target = ?').run(canonical, scopeId, row.target);
1232
+ merged += 1;
1233
+ continue;
1234
+ }
1235
+ const recent = [
1236
+ ...(JSON.parse(canonRow.recent_json ?? '[]')),
1237
+ ...(JSON.parse(row.recent_json ?? '[]')),
1238
+ ].slice(-30);
1239
+ db.prepare(`
1240
+ UPDATE relationships SET trust = ?, care = ?, familiarity = ?, recent_json = ?, updated_at = ?
1241
+ WHERE scope_id = ? AND target = ?
1242
+ `).run(
1243
+ Math.max(Number(canonRow.trust), Number(row.trust)),
1244
+ Math.max(Number(canonRow.care), Number(row.care)),
1245
+ Math.max(Number(canonRow.familiarity), Number(row.familiarity)),
1246
+ JSON.stringify(recent), at, scopeId, canonical,
1247
+ );
1248
+ db.prepare('DELETE FROM relationships WHERE scope_id = ? AND target = ?').run(scopeId, row.target);
1249
+ merged += 1;
1250
+ }
1251
+ const affects = db.prepare('SELECT * FROM affect_targets WHERE scope_id = ?').all(scopeId);
1252
+ for (const row of affects) {
1253
+ if (row.target === canonical) continue;
1254
+ if (targetResolver.resolveTarget(row.target) !== canonical) continue;
1255
+ const canonRow = db.prepare('SELECT * FROM affect_targets WHERE scope_id = ? AND target = ?').get(scopeId, canonical);
1256
+ if (!canonRow) {
1257
+ db.prepare('UPDATE affect_targets SET target = ? WHERE scope_id = ? AND target = ?').run(canonical, scopeId, row.target);
1258
+ merged += 1;
1259
+ continue;
1260
+ }
1261
+ const scores = JSON.parse(canonRow.scores_json ?? '{}');
1262
+ for (const [name, value] of Object.entries(JSON.parse(row.scores_json ?? '{}'))) {
1263
+ scores[name] = Number(scores[name] ?? 0) + Number(value ?? 0);
1264
+ }
1265
+ db.prepare(`
1266
+ UPDATE affect_targets SET scores_json = ?, count = ?, attitude = ?, updated_at = ?
1267
+ WHERE scope_id = ? AND target = ?
1268
+ `).run(
1269
+ JSON.stringify(scores),
1270
+ Number(canonRow.count ?? 0) + Number(row.count ?? 0),
1271
+ canonRow.attitude ?? row.attitude ?? null,
1272
+ at, scopeId, canonical,
1273
+ );
1274
+ db.prepare('DELETE FROM affect_targets WHERE scope_id = ? AND target = ?').run(scopeId, row.target);
1275
+ merged += 1;
1276
+ }
1277
+ if (merged) {
1278
+ try { emotion.recompute(); } catch { /* attitude recompute is best-effort */ }
1279
+ }
1280
+ return merged;
1281
+ }
1282
+
1283
+ function inhibitionList({ scopeId = config.scope, now = Date.now() } = {}) {
1284
+ const rows = db.prepare(`
1285
+ SELECT id, title, metadata_json, recorded_at FROM traces
1286
+ WHERE scope_id = ? AND metadata_json LIKE '%"inhibition"%'
1287
+ `).all(scopeId);
1288
+ const items = [];
1289
+ for (const row of rows) {
1290
+ let metadata = {};
1291
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
1292
+ const value = suppressionOf(metadata, now, { halfLifeDays: config.inhibitionHalfLifeDays ?? 14 });
1293
+ if (value <= 0.001) continue;
1294
+ items.push({
1295
+ id: row.id,
1296
+ title: row.title,
1297
+ value: Math.round(value * 1000) / 1000,
1298
+ suppressedAt: metadata.suppressedAt ?? null,
1299
+ recordedAt: row.recorded_at,
1300
+ });
1301
+ }
1302
+ return items.sort((a, b) => b.value - a.value);
1303
+ }
1304
+
1305
+ function inhibitionClear({ id = null, all = false, scopeId = config.scope } = {}) {
1306
+ const rows = all
1307
+ ? db.prepare(`SELECT id, metadata_json FROM traces WHERE scope_id = ? AND metadata_json LIKE '%"inhibition"%'`).all(scopeId)
1308
+ : id
1309
+ ? db.prepare('SELECT id, metadata_json FROM traces WHERE scope_id = ? AND id = ?').all(scopeId, id)
1310
+ : [];
1311
+ let cleared = 0;
1312
+ for (const row of rows) {
1313
+ let metadata = {};
1314
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
1315
+ if (!('inhibition' in metadata) && !('suppressedAt' in metadata)) continue;
1316
+ delete metadata.inhibition;
1317
+ delete metadata.suppressedAt;
1318
+ try {
1319
+ traces.update(row.id, { metadata });
1320
+ cleared += 1;
1321
+ } catch {
1322
+ /* one bad row must not stop the rest */
1323
+ }
1324
+ }
1325
+ if (cleared) audit.record?.({ actor: 'user', action: 'inhibition.clear', targetType: 'trace', targetId: id ?? '*', detail: { cleared, all } });
1326
+ return { cleared };
1327
+ }
1328
+
1329
+ // Last maintain() run, so health/status can report its duration (an accidental
1330
+ // O(n²) in a synchronous heartbeat path shows up as a frozen host otherwise).
1331
+ let lastMaintain = null;
1332
+
1333
+ function maintain({ now = Date.now(), scopeId = config.scope } = {}) {
1334
+ const started = Date.now();
1335
+ const at = new Date(now).toISOString();
1336
+ const report = { at, disputes: 0, orphanDisputes: 0, summaries: 0, intentions: 0, playbook: 0, aliases: 0, goalRounds: 0, working: 0, errors: [] };
1337
+ try {
1338
+ // A dispute can only auto-close when neither side is still active. `disputed`
1339
+ // is NOT "not active": the old condition treated it as such, closed the
1340
+ // dispute while both facts stayed disputed, and left them unqueryable forever
1341
+ // (their disputes were already resolved, so this query never saw them again).
1342
+ const rows = db.prepare(`
1343
+ SELECT d.id, d.fact_a, d.fact_b FROM disputes d
1344
+ JOIN facts fa ON fa.id = d.fact_a
1345
+ JOIN facts fb ON fb.id = d.fact_b
1346
+ WHERE d.status = 'open' AND fa.status NOT IN ('active', 'disputed') AND fb.status NOT IN ('active', 'disputed')
1347
+ `).all();
1348
+ const close = db.prepare("UPDATE disputes SET status = 'resolved', resolved_at = ?, resolution = ? WHERE id = ?");
1349
+ const drop = db.prepare("UPDATE facts SET status = 'invalidated', valid_to = COALESCE(valid_to, ?), superseded_at = COALESCE(superseded_at, ?), updated_at = ? WHERE id = ? AND status = 'disputed'");
1350
+ transaction(db, () => {
1351
+ for (const row of rows) {
1352
+ close.run(at, 'auto: both facts invalidated', row.id);
1353
+ // If either side is still floating in `disputed`, the reasoning that
1354
+ // closed the dispute applies to it too.
1355
+ drop.run(at, at, at, row.fact_a);
1356
+ drop.run(at, at, at, row.fact_b);
1357
+ }
1358
+ });
1359
+ report.disputes = rows.length;
1360
+ } catch (error) {
1361
+ report.errors.push(`disputes: ${error instanceof Error ? error.message : String(error)}`);
1362
+ }
1363
+ try {
1364
+ // Orphan disputed facts: no open dispute references them any more. An older
1365
+ // version could close the dispute without touching the facts, so those rows
1366
+ // stayed `disputed` forever — invisible to normal queries and keeping the
1367
+ // health score red. Close them the same way the dispute was closed.
1368
+ const orphans = db.prepare(`
1369
+ SELECT f.id FROM facts f
1370
+ WHERE f.scope_id = ? AND f.status = 'disputed'
1371
+ AND NOT EXISTS (SELECT 1 FROM disputes d WHERE d.status = 'open' AND (d.fact_a = f.id OR d.fact_b = f.id))
1372
+ LIMIT 50
1373
+ `).all(scopeId);
1374
+ if (orphans.length) {
1375
+ const stmt = db.prepare("UPDATE facts SET status = 'invalidated', valid_to = COALESCE(valid_to, ?), superseded_at = COALESCE(superseded_at, ?), updated_at = ? WHERE id = ? AND status = 'disputed'");
1376
+ transaction(db, () => { for (const row of orphans) stmt.run(at, at, at, row.id); });
1377
+ }
1378
+ report.orphanDisputes = orphans.length;
1379
+ } catch (error) {
1380
+ report.errors.push(`orphanDisputes: ${error instanceof Error ? error.message : String(error)}`);
1381
+ }
1382
+ try {
1383
+ const groups = db.prepare(`
1384
+ SELECT level, content, GROUP_CONCAT(id) AS ids FROM summaries
1385
+ GROUP BY level, content HAVING COUNT(*) > 1
1386
+ `).all();
1387
+ const del = db.prepare('DELETE FROM summaries WHERE id = ?');
1388
+ let removed = 0;
1389
+ transaction(db, () => {
1390
+ for (const group of groups) {
1391
+ const ids = String(group.ids ?? '').split(',');
1392
+ for (const id of ids.slice(1)) {
1393
+ if (!id) continue;
1394
+ removed += del.run(id).changes;
1395
+ }
1396
+ }
1397
+ });
1398
+ report.summaries = removed;
1399
+ } catch (error) {
1400
+ report.errors.push(`summaries: ${error instanceof Error ? error.message : String(error)}`);
1401
+ }
1402
+ try {
1403
+ const result = db.prepare(`
1404
+ UPDATE intentions SET status = 'expired'
1405
+ WHERE scope_id = ? AND status = 'pending' AND expires_at IS NOT NULL AND expires_at < ?
1406
+ `).run(scopeId, at);
1407
+ report.intentions = result.changes;
1408
+ } catch (error) {
1409
+ report.errors.push(`intentions: ${error instanceof Error ? error.message : String(error)}`);
1410
+ }
1411
+ try {
1412
+ const result = db.prepare(`
1413
+ UPDATE playbook_rules SET status = 'retired', updated_at = ?
1414
+ WHERE scope_id = ? AND status = 'candidate'
1415
+ AND (title LIKE '|%' OR title LIKE '%|%' OR length(title) > 120 OR length(title) < 8)
1416
+ `).run(at, scopeId);
1417
+ report.playbook = result.changes;
1418
+ } catch (error) {
1419
+ report.errors.push(`playbook: ${error instanceof Error ? error.message : String(error)}`);
1420
+ }
1421
+ try {
1422
+ // Older versions stored auto-continuation rounds as user speech. Take
1423
+ // them out of active recall; the rows stay for inspection.
1424
+ const result = db.prepare(`
1425
+ UPDATE traces SET state = 'archived', updated_at = ?
1426
+ WHERE scope_id = ? AND state = 'active'
1427
+ AND (content LIKE '用户:<goal_round>%' OR content LIKE '<goal_round>%'
1428
+ OR (content LIKE '%Objective: "%' AND content LIKE '%Round: %'))
1429
+ `).run(at, scopeId);
1430
+ report.goalRounds = result.changes;
1431
+ } catch (error) {
1432
+ report.errors.push(`goalRounds: ${error instanceof Error ? error.message : String(error)}`);
1433
+ }
1434
+ try {
1435
+ report.aliases = mergeAliasTargets(at, scopeId);
1436
+ } catch (error) {
1437
+ report.errors.push(`aliases: ${error instanceof Error ? error.message : String(error)}`);
1438
+ }
1439
+ try {
1440
+ // Working memory is a small L1 layer. Unpinned items that nobody updated
1441
+ // for weeks are stale by definition; pinned ones always stay.
1442
+ const ttlDays = Math.max(1, Number(config.workingTtlDays ?? 14));
1443
+ const cutoff = new Date(now - ttlDays * 86_400_000).toISOString();
1444
+ const result = db.prepare('DELETE FROM working_items WHERE scope_id = ? AND pinned = 0 AND created_at < ?').run(scopeId, cutoff);
1445
+ report.working = result.changes;
1446
+ } catch (error) {
1447
+ report.errors.push(`working: ${error instanceof Error ? error.message : String(error)}`);
1448
+ }
1449
+ try {
1450
+ report.reflection = maybeAutoReflect(now, scopeId);
1451
+ } catch (error) {
1452
+ report.errors.push(`reflection: ${error instanceof Error ? error.message : String(error)}`);
1453
+ }
1454
+ try {
1455
+ report.narrative = maybeAutoWeave(now, scopeId);
1456
+ } catch (error) {
1457
+ report.errors.push(`narrative: ${error instanceof Error ? error.message : String(error)}`);
1458
+ }
1459
+ // maintain() runs on the host's heartbeat, synchronously. Record how long it
1460
+ // took so an accidental O(n²) shows up as a number instead of a frozen UI.
1461
+ // The timing must be on `report` *before* audit.record(), otherwise the row
1462
+ // it writes is missing `ms` and the health warning only fires on idle passes
1463
+ // (the opposite of what it is for).
1464
+ const elapsed = Date.now() - started;
1465
+ report.ms = elapsed;
1466
+ // Full snapshot, not just at/ms: when health falls back to this because the
1467
+ // audit row predates the timing field, the counts must come from the same pass
1468
+ // as the duration (mixing them reports numbers no single run produced).
1469
+ lastMaintain = { ...report };
1470
+ metrics.observe('maintain.ms', elapsed);
1471
+ // A slow pass is worth persisting even when it changed nothing: a quiet pass
1472
+ // writes no row, so a stall would leave no evidence at all for the health
1473
+ // guardrail to read. Changed passes still always write.
1474
+ const slowThreshold = Number.isFinite(Number(config.maintainSlowMs)) ? Number(config.maintainSlowMs) : 2000;
1475
+ const slowPass = elapsed > slowThreshold;
1476
+ if (slowPass || report.disputes || report.orphanDisputes || report.summaries || report.intentions || report.playbook || report.aliases || report.goalRounds || report.working || report.reflection?.created || report.narrative?.built) {
1477
+ audit.record?.({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: scopeId, detail: report });
1478
+ }
1479
+ return report;
1480
+ }
1481
+
1482
+ /**
1483
+ * Keep the narrative layer alive: if a day has enough material and the last
1484
+ * episode summary is old, write one. Without this the summary table stayed at
1485
+ * a handful of rows while reflections piled up, so long-term memory had no
1486
+ * short version of itself.
1487
+ */
1488
+ function maybeAutoReflect(now, scopeId) {
1489
+ const recent = summaries.list(scopeId, { level: 'episode', limit: 5 });
1490
+ const sinceIso = new Date(now - 86_400_000).toISOString();
1491
+ const coveredSince = Date.parse(sinceIso);
1492
+ const covered = recent.some((summary) => {
1493
+ const anchor = Date.parse(summary.createdAt ?? summary.periodEnd ?? '');
1494
+ const end = Date.parse(summary.periodEnd ?? '');
1495
+ return (Number.isFinite(anchor) && anchor >= coveredSince) || (Number.isFinite(end) && end >= coveredSince);
1496
+ });
1497
+ // Segment start: right after the previous episode ended, but never further
1498
+ // back than 24h. This is what keeps consecutive episodes from covering the
1499
+ // same traces (the old "two summaries, same window" problem).
1500
+ const lastEpisode = recent.find((summary) => summary.level === 'episode') ?? null;
1501
+ const lastEnd = lastEpisode ? Date.parse(lastEpisode.periodEnd ?? '') : NaN;
1502
+ const lastAt = lastEpisode ? Date.parse(lastEpisode.createdAt ?? lastEpisode.periodEnd ?? '') : NaN;
1503
+ const segmentStartMs = Math.max(coveredSince, Number.isFinite(lastEnd) ? lastEnd + 1 : 0);
1504
+ const segmentSince = new Date(segmentStartMs).toISOString();
1505
+ const material = () => traces.listSince(scopeId, segmentSince, { limit: 500 }).filter((trace) => trace.kind !== 'reflection').length;
1506
+ const count = material();
1507
+ // A dense day may get a second episode, but only as a *separate segment*:
1508
+ // ≥150 new traces since the last episode, ≥6h since it was written.
1509
+ const followUpGapHours = Number.isFinite(Number(config.reflectFollowUpGapHours)) ? Number(config.reflectFollowUpGapHours) : 6;
1510
+ const followUpMin = Number.isFinite(Number(config.reflectFollowUpMin)) ? Number(config.reflectFollowUpMin) : 150;
1511
+ const followUp = Number.isFinite(lastAt) && now - lastAt >= followUpGapHours * 3_600_000 && count >= followUpMin;
1512
+ if (covered && !followUp) return { skipped: 'covered', count };
1513
+ // Cadence follows the material instead of the clock: a quiet day is not worth
1514
+ // an episode, and once a segment has enough material it is written.
1515
+ const minMaterial = Number.isFinite(Number(config.reflectMinMaterial)) ? Number(config.reflectMinMaterial) : 50;
1516
+ if (count < minMaterial) return { skipped: 'few-traces', count, minMaterial, since: segmentSince };
1517
+ const result = reflect.reflect({ scopeId, now, windowDays: 1, force: true, since: segmentSince, segment: true });
1518
+ return {
1519
+ created: !result.skipped,
1520
+ coverage: result.coverage ?? null,
1521
+ sources: result.sources?.length ?? 0,
1522
+ count,
1523
+ since: segmentSince,
1524
+ followUp,
1525
+ };
1526
+ }
1527
+
1528
+ // Narrative threads (level='thread') are the cross-day story: "these three days
1529
+ // we built the bridge, v0.4 → v0.8" as one recallable memory. The engine has
1530
+ // existed since the narrative module shipped, but nothing ever called weave(),
1531
+ // so `summaries` never held a single thread row. Build a couple per pass, at
1532
+ // most every 6h, and only once there is an episode worth threading around.
1533
+ let lastWeaveAt = null;
1534
+ function maybeAutoWeave(now, scopeId) {
1535
+ if (typeof narrative?.weave !== 'function') return { skipped: 'no-engine' };
1536
+ const gapMs = Math.max(1, Number(config.narrativeWeaveGapHours ?? 6)) * 3_600_000;
1537
+ if (lastWeaveAt && now - lastWeaveAt < gapMs) return { skipped: 'too-soon' };
1538
+ const episodeCount = Number(db.prepare("SELECT COUNT(*) AS c FROM summaries WHERE scope_id = ? AND level = 'episode'").get(scopeId)?.c ?? 0);
1539
+ if (episodeCount < 2) return { skipped: 'few-episodes', episodeCount };
1540
+ const result = narrative.weave({ scopeId, maxThreads: 2, windowHours: Number(config.threadWindowHours ?? 24), at: now });
1541
+ // Only stamp the clock when it actually ran; a thrown weave retries next pass.
1542
+ lastWeaveAt = now;
1543
+ return { built: result?.built ?? 0, episodeCount };
1544
+ }
1545
+
1546
+ async function vectorMaintain({ scopeId = config.scope, backfill = 50, drain = 20, budgetMs = null } = {}) {
1547
+ if (!vector?.backfillMissing || !vector?.drainQueue) return { skipped: true, reason: 'vector-disabled' };
1548
+ const queued = vector.backfillMissing({ scopeId, limit: backfill });
1549
+ const drained = await vector.drainQueue({
1550
+ max: drain,
1551
+ budgetMs: budgetMs ?? Number(config.vectorDrainBudgetMs ?? 20_000),
1552
+ });
1553
+ return { ...queued, ...drained, status: vector.status() };
1554
+ }
1555
+
1556
+ /**
1557
+ * Heartbeat hooks. Companion plugins (e.g. dsh-cortex-agency) are driven by
1558
+ * the host scheduler instead of starting their own timers, so an idle DSH
1559
+ * never runs two independent clocks.
1560
+ */
1561
+ const tickListeners = new Set();
1562
+ function onTick(listener) {
1563
+ if (typeof listener !== 'function') return () => {};
1564
+ tickListeners.add(listener);
1565
+ return () => { tickListeners.delete(listener); };
1566
+ }
1567
+ function emitTick(report) {
1568
+ for (const listener of tickListeners) {
1569
+ try {
1570
+ listener(report);
1571
+ } catch (error) {
1572
+ logger?.warn?.(`cortex tick listener failed: ${error instanceof Error ? error.message : String(error)}`);
1573
+ }
1574
+ }
1575
+ return tickListeners.size;
1576
+ }
1577
+
1144
1578
  return {
1145
1579
  db,
1146
1580
  config,
@@ -1150,6 +1584,11 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1150
1584
  development,
1151
1585
  narrative,
1152
1586
  vector,
1587
+ vectorMaintain,
1588
+ maintain,
1589
+ inhibition: { list: inhibitionList, clear: inhibitionClear },
1590
+ onTick,
1591
+ emitTick,
1153
1592
  life,
1154
1593
  llm: llmAdapter,
1155
1594
  consolidation,
@@ -1477,6 +1916,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1477
1916
  },
1478
1917
  privacy,
1479
1918
  reflect: (options = {}) => reflect.reflect({ ...options, scopeId: options.scopeId ?? config.scope }),
1919
+ reflectBackfill: (options = {}) => reflect.backfillEpisodes({ ...options, scopeId: options.scopeId ?? config.scope }),
1480
1920
  evaluateDevelopment: (options = {}) => development.evaluate({ ...options, scopeId: options.scopeId ?? config.scope }),
1481
1921
  rebuildVector: (options = {}) => vector?.rebuild({ ...options, scopeId: options.scopeId ?? config.scope }) ?? { rebuilt: 0 },
1482
1922
  rebuildVectorAsync: (options = {}) => vector?.rebuildAsync({ ...options, scopeId: options.scopeId ?? config.scope }) ?? Promise.resolve({ rebuilt: 0 }),