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
@@ -1,3 +1,5 @@
1
+ import { guardFactCandidate } from './fact-guard.js';
2
+
1
3
  const RULES = [
2
4
  // Negative predicates must be seen first; otherwise "不喜欢" also matches likes.
3
5
  { predicate: 'dislikes', pattern: /([^,。;\n]{1,20})(?:讨厌|不喜欢)([^,。;\n]{1,20})/g, confidence: 0.6 },
@@ -9,7 +11,46 @@ const RULES = [
9
11
 
10
12
  const NEGATED_TAIL = /[不没别未]\s*$/;
11
13
 
14
+ // Design discussions and status posts talk about what *might* happen; they are
15
+ // not statements of fact. They usually arrive as a pasted draft, so both the
16
+ // vocabulary and the quote markers are signals.
17
+ const DISCUSSION_DOC = /(?:新坑|设计草案|方案稿|设计文档|TODO|待办|路线图|架构设计|接口设计|需求草案)/;
18
+
19
+ // Sentence-level guards. The rule extractor is deliberately dumb, so the text it
20
+ // reads has to be checked as a whole: "你会有感觉吗" and "要是想聊两句" both used to
21
+ // produce facts because the patterns matched inside a question or an if-clause.
22
+ const SENTENCE_END = /[。!?!?;;\n]/;
23
+ const SINGLE_SUBJECT_OK = new Set(['我', '你', '他', '她', '它', '咱', '您']);
24
+
25
+ function sentenceAround(text, index, length) {
26
+ let start = index;
27
+ while (start > 0 && !SENTENCE_END.test(text[start - 1])) start -= 1;
28
+ let end = index + length;
29
+ while (end < text.length && !SENTENCE_END.test(text[end])) end += 1;
30
+ return text.slice(start, end);
31
+ }
32
+
33
+ function isQuestionSentence(sentence) {
34
+ const text = String(sentence ?? '').trim();
35
+ if (!text) return false;
36
+ if (/[??]\s*$/.test(text)) return true;
37
+ return /(?:吗|呢|吧|麼|么)\s*$/.test(text);
38
+ }
39
+
40
+ function isConditionalSentence(sentence) {
41
+ return /^\s*(?:要是|如果|假如|万一|倘若|若是|若)/.test(String(sentence ?? ''));
42
+ }
43
+
44
+ // An instruction is not a fact: "记得明天把接口补上" describes what to do, not what
45
+ // is. The opener matters — imperative verbs inside a statement are fine.
46
+ function isImperativeSentence(sentence) {
47
+ return /^\s*(?:去|把|帮我|给我|记得|别|请|麻烦|快|赶紧|先帮)/.test(String(sentence ?? ''));
48
+ }
49
+
12
50
  const STOP_SUBJECTS = new Set(['他', '她', '它', '这', '那', '今天', '昨天', '明天']);
51
+ // Fragments that only look like objects:他们来自被硬切成三元组的叙述句,
52
+ // 入库后会变成「at→等」「will→收一收」这种噪音事实。
53
+ const NOISE_OBJECTS = new Set(['等', '等等', '收一收', '水里', '那里', '这里', '一下子', '一点', '一些', '什么', '怎么', '那样', '这样', '儿', '会儿']);
13
54
 
14
55
  function clean(value) {
15
56
  return String(value ?? '').trim().replace(/^(?:今天|昨天|明天|刚才|然后|所以|但是|而且)/, '').trim();
@@ -27,25 +68,46 @@ export function extractFactCandidates(text, persona = {}) {
27
68
  const value = String(text ?? '');
28
69
  // Assistant replies and copied notes are often markdown-heavy; those are
29
70
  // not clean fact sources and produce sentence-fragment entities.
30
- if (/```|`[^`]*`|\*\*|^\s*[-*]\s|\|.*\|/m.test(value)) return [];
71
+ if (/```|`[^`]*`|\*\*|^\s*[-*]\s|^\s*>\s|\|.*\|/m.test(value)) return [];
72
+ // A pasted design draft is a discussion, not a fact: "新坑 3:…" describes a
73
+ // problem to think about, not something that happened.
74
+ if (DISCUSSION_DOC.test(value)) return [];
31
75
  const selfName = typeof persona?.selfName === 'string' && persona.selfName.trim() ? persona.selfName.trim().slice(0, 24) : '助手';
32
76
  const userAddress = typeof persona?.userAddress === 'string' && persona.userAddress.trim() ? persona.userAddress.trim().slice(0, 24) : '你';
33
- const selfAliases = new Set(['你', '本鲸', selfName]);
34
- const userAliases = new Set(['我', '自己', '我们', '咱', '主人', '用户', '您', userAddress]);
77
+ // Quoted speech is someone else's words, not a fact about the speaker.
78
+ const quoteSpans = [];
79
+ for (const match of value.matchAll(/[「“"]([^「」“”"]{1,300})[」”"]/g)) {
80
+ quoteSpans.push([match.index, match.index + match[0].length]);
81
+ }
82
+ const inQuote = (index) => quoteSpans.some(([start, end]) => index >= start && index < end);
83
+ const selfAliases = new Set(['你', selfName]);
84
+ const userAliases = new Set(['我', '自己', '我们', '咱', '用户', '您', userAddress]);
35
85
  const out = [];
36
86
  const seen = new Set();
37
87
  for (const rule of RULES) {
38
88
  rule.pattern.lastIndex = 0;
39
89
  let match;
40
90
  while ((match = rule.pattern.exec(value)) !== null) {
91
+ // 引号里是别人的话,不是关于说话者的事实。
92
+ if (inQuote(match.index)) continue;
93
+ // 问句、假设句、命令句都不是事实来源。
94
+ const sentence = sentenceAround(value, match.index, match[0].length);
95
+ if (isQuestionSentence(sentence) || isConditionalSentence(sentence) || isImperativeSentence(sentence)) continue;
41
96
  const rawSubject = clean(match[1]);
97
+ // 单字主语几乎都是被切碎的功能词("要"、"还"、"只");只有代词/称呼
98
+ // 允许单独作主语。这条挡掉 is(要 → 想聊两句) 这类碎片三元组。
99
+ if (rawSubject.length === 1 && !SINGLE_SUBJECT_OK.has(rawSubject)) continue;
42
100
  let subject = rawSubject;
43
101
  if (selfAliases.has(rawSubject)) subject = selfName;
44
102
  else if (userAliases.has(rawSubject)) subject = userAddress;
45
103
  const object = clean(match[2]);
46
104
  if (!subject || !object || subject.length < 1 || object.length < 1) continue;
105
+ // Single function words are not objects ("会 儿", "在 等" are split sentences).
106
+ if (object.length === 1 && '的了着过等儿啊吗呢吧嘛'.includes(object)) continue;
107
+ if (subject.length === 1 && '的了着过等儿啊吗呢吧嘛'.includes(subject)) continue;
47
108
  if (STOP_SUBJECTS.has(rawSubject)) continue;
48
109
  if (!plausibleName(subject, 12) || !plausibleName(object, 18)) continue;
110
+ if (NOISE_OBJECTS.has(object)) continue;
49
111
  // "用户不喜欢猫" yields subject "用户不"; never turn that into likes.
50
112
  if ((rule.predicate === 'likes' || rule.predicate === 'is') && NEGATED_TAIL.test(match[1])) continue;
51
113
  const key = `${subject}|${rule.predicate}|${object}`;
@@ -65,19 +127,21 @@ export function createFactExtractor({ entities, facts } = {}) {
65
127
  const candidates = extractFactCandidates(text, persona ?? {});
66
128
  const resolved = [];
67
129
  for (const candidate of candidates) {
130
+ const guarded = guardFactCandidate(candidate);
131
+ if (!guarded) continue;
68
132
  try {
69
- const subject = entities.upsert({ scopeId, name: candidate.subject });
70
- const object = entities.upsert({ scopeId, name: candidate.object });
133
+ const subject = entities.upsert({ scopeId, name: guarded.subject });
134
+ const object = entities.upsert({ scopeId, name: guarded.object });
71
135
  const result = facts.resolve({
72
136
  scopeId,
73
137
  subjectId: subject.id,
74
- predicate: candidate.predicate,
138
+ predicate: guarded.predicate,
75
139
  objectId: object.id,
76
140
  validFrom: recordedAt ?? undefined,
77
141
  recordedAt: recordedAt ?? undefined,
78
- confidence: candidate.confidence,
142
+ confidence: guarded.confidence,
79
143
  sourceEventId: eventId,
80
- evidence: [{ eventId, traceId, weight: candidate.confidence, text: candidate.evidence }],
144
+ evidence: [{ eventId, traceId, weight: guarded.confidence, text: candidate.evidence }],
81
145
  });
82
146
  resolved.push({ candidate, ...result });
83
147
  } catch {
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Fact guard. The 0.4.22 store had facts whose subject was a stray character
3
+ * ("现", "只", "还") and whose object was punctuation. They came from the LLM
4
+ * extractor, which trusted whatever JSON it got back. This module is the single
5
+ * place that decides whether a candidate is a fact at all.
6
+ */
7
+ const PUNCT_ONLY = /^[\s\p{P}\p{S}]+$/u;
8
+ const FORBIDDEN_ENTITY = /[|`<>{}\[\]\\\n\r]/;
9
+ const FUNCTION_WORDS = new Set([
10
+ '他', '她', '它', '这', '那', '现', '只', '还', '也', '就', '又', '都',
11
+ '和', '与', '或', '但', '而', '所以', '因为', '如果', '然后', '而且', '但是',
12
+ ]);
13
+
14
+ function entityOk(value, max = 24) {
15
+ const text = String(value ?? '').trim();
16
+ if (!text || text.length > max) return false;
17
+ if (PUNCT_ONLY.test(text)) return false;
18
+ if (FORBIDDEN_ENTITY.test(text)) return false;
19
+ if (FUNCTION_WORDS.has(text)) return false;
20
+ if (/^[0-9]{1,2}$/.test(text)) return false;
21
+ return true;
22
+ }
23
+
24
+ function predicateOk(value) {
25
+ const text = String(value ?? '').trim().toLowerCase().replace(/\s+/g, '_');
26
+ if (!/^[a-z][a-z0-9_]{1,31}$/.test(text)) return null;
27
+ return text;
28
+ }
29
+
30
+ /**
31
+ * Returns a normalized candidate, or null when the triple is not worth storing.
32
+ * A null here is the expected outcome for most extracted junk.
33
+ */
34
+ export function guardFactCandidate(candidate = {}) {
35
+ const subject = String(candidate.subject ?? '').trim();
36
+ const object = String(candidate.object ?? '').trim();
37
+ const predicate = predicateOk(candidate.predicate);
38
+ if (!predicate) return null;
39
+ if (!entityOk(subject, 24)) return null;
40
+ if (!entityOk(object, 40)) return null;
41
+ const raw = Number(candidate.confidence ?? 0.6);
42
+ if (!Number.isFinite(raw)) return null;
43
+ return {
44
+ subject,
45
+ predicate,
46
+ object,
47
+ confidence: Math.min(1, Math.max(0, raw)),
48
+ };
49
+ }
50
+
51
+ export { entityOk, predicateOk };
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import { integrityCheck } from '../store/database.js';
3
3
  import { nowIso } from '../core/time.js';
4
+ import { suppressionOf } from './inhibition.js';
4
5
 
5
6
  /**
6
7
  * Health is an audit, not a score for its own sake. Every issue must point to a
@@ -13,8 +14,8 @@ export function createHealthEngine({
13
14
  facts = null,
14
15
  entities = null,
15
16
  summaries = null,
16
- feedback = null,
17
- skills = null,
17
+ maintainLast = null,
18
+ feedback = null, skills = null,
18
19
  jobs = null,
19
20
  identityStore = null,
20
21
  selfStore = null,
@@ -26,6 +27,148 @@ export function createHealthEngine({
26
27
  return Number(db.prepare(sql).get(...params)?.c ?? 0);
27
28
  }
28
29
 
30
+ function inhibitionReport(scopeId, now) {
31
+ const rows = db.prepare(`
32
+ SELECT id, title, metadata_json FROM traces
33
+ WHERE scope_id = ? AND state = 'active' AND metadata_json LIKE '%"inhibition"%'
34
+ `).all(scopeId);
35
+ const items = [];
36
+ for (const row of rows) {
37
+ let metadata = {};
38
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
39
+ const value = suppressionOf(metadata, now, { halfLifeDays: config.inhibitionHalfLifeDays ?? 14 });
40
+ if (value > 0.001) items.push({ id: row.id, title: row.title, value: Math.round(value * 1000) / 1000 });
41
+ }
42
+ items.sort((a, b) => b.value - a.value);
43
+ return {
44
+ enabled: config.features?.inhibition === true,
45
+ count: items.length,
46
+ average: items.length ? Math.round((items.reduce((sum, item) => sum + item.value, 0) / items.length) * 1000) / 1000 : 0,
47
+ top: items.slice(0, 3),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Capture hygiene: how many host turns were stored, and how many of them
53
+ * needed the injected-context stripper. This is the number that proves the
54
+ * 0.4.23 pollution fix is actually doing something.
55
+ */
56
+ function captureReport(scopeId) {
57
+ const rows = db.prepare(`
58
+ SELECT metadata_json, recorded_at FROM traces
59
+ WHERE scope_id = ? AND source = 'host:turn'
60
+ `).all(scopeId);
61
+ let stripped = 0;
62
+ let truncated = 0;
63
+ const byDay = new Map();
64
+ for (const row of rows) {
65
+ let metadata = {};
66
+ try { metadata = JSON.parse(row.metadata_json); } catch { continue; }
67
+ const capture = metadata?.capture ?? {};
68
+ // Metadata is stored flat ({capture:'host', stripped:true}); accept the
69
+ // nested shape too so an older/newer writer cannot silently report zero.
70
+ const wasStripped = metadata?.stripped === true || capture.stripped === true;
71
+ const wasTruncated = metadata?.truncated === true || capture.truncated === true;
72
+ if (wasStripped) stripped += 1;
73
+ if (wasTruncated) truncated += 1;
74
+ const day = String(row.recorded_at ?? '').slice(0, 10);
75
+ const bucket = byDay.get(day) ?? { day, total: 0, stripped: 0, truncated: 0 };
76
+ bucket.total += 1;
77
+ if (wasStripped) bucket.stripped += 1;
78
+ if (wasTruncated) bucket.truncated += 1;
79
+ byDay.set(day, bucket);
80
+ }
81
+ const days = [...byDay.values()].sort((a, b) => b.day.localeCompare(a.day)).slice(0, 14);
82
+ return { total: rows.length, stripped, truncated, clean: rows.length - stripped, days };
83
+ }
84
+
85
+ /**
86
+ * The last consolidation run and the last sleep pass. `dream_runs.error` is the
87
+ * only place that says *why* consolidation did nothing, so surface it instead
88
+ * of leaving it to whoever remembers to query the table.
89
+ */
90
+ function consolidationReport(scopeId = 'global', now = Date.now()) {
91
+ try {
92
+ // Preview rows are rehearsals, not consolidation history: showing one as
93
+ // "the last consolidation" hides when a real pass last ran.
94
+ const dream = db.prepare("SELECT at, status, error, decisions_json, applied_json FROM dream_runs WHERE scope_id = ? AND (model IS NULL OR model <> 'dedupe') AND status != 'preview' ORDER BY created_at DESC LIMIT 1").get(scopeId);
95
+ const sleep = db.prepare("SELECT at, report_json FROM sleep_runs WHERE scope_id = ? ORDER BY at DESC LIMIT 1").get(scopeId);
96
+ let sleepReport = null;
97
+ if (sleep) {
98
+ try { sleepReport = JSON.parse(sleep.report_json ?? '{}'); } catch { sleepReport = null; }
99
+ }
100
+ // Today's housekeeping since local midnight: how many traces were archived
101
+ // or merged. A pass that changed nothing is not counted as a run, so the
102
+ // number answers "did the memory actually get tidier today".
103
+ const today = { runs: 0, archived: 0, merged: 0 };
104
+ try {
105
+ const dayStart = new Date(now);
106
+ dayStart.setHours(0, 0, 0, 0);
107
+ const rows = db.prepare("SELECT applied_json FROM dream_runs WHERE scope_id = ? AND (model IS NULL OR model <> 'dedupe') AND status != 'preview' AND created_at >= ?").all(scopeId, dayStart.toISOString());
108
+ for (const row of rows) {
109
+ let applied = [];
110
+ try { applied = JSON.parse(row.applied_json ?? '[]'); } catch { applied = []; }
111
+ if (!Array.isArray(applied) || applied.length === 0) continue;
112
+ today.runs += 1;
113
+ for (const item of applied) {
114
+ if (item?.action === 'archive') today.archived += 1;
115
+ else if (item?.action === 'merge') today.merged += 1;
116
+ }
117
+ }
118
+ } catch { /* the daily tally is best effort */ }
119
+ return {
120
+ today,
121
+ dream: dream ? {
122
+ at: dream.at,
123
+ status: dream.status,
124
+ error: dream.error ?? null,
125
+ decisions: (() => { try { return JSON.parse(dream.decisions_json ?? '[]').length; } catch { return 0; } })(),
126
+ // `status: applied` with every decision `keep` and `applied: 0` is a
127
+ // no-op, not a consolidation. Keep the count so a reader can tell.
128
+ keep: (() => { try { return JSON.parse(dream.decisions_json ?? '[]').filter((item) => item?.action === 'keep').length; } catch { return 0; } })(),
129
+ applied: (() => { try { return JSON.parse(dream.applied_json ?? '[]').length; } catch { return 0; } })(),
130
+ } : null,
131
+ sleep: sleep ? {
132
+ at: sleep.at,
133
+ consolidation: sleepReport?.consolidation ?? null,
134
+ consolidated: Number(sleepReport?.consolidated ?? 0),
135
+ reflected: Number(sleepReport?.reflected ?? 0),
136
+ } : null,
137
+ };
138
+ } catch {
139
+ return { dream: null, sleep: null };
140
+ }
141
+ }
142
+
143
+ /**
144
+ * The last maintenance pass, as recorded by maintain(). A silent maintain is
145
+ * indistinguishable from a maintenance that never ran, so surface it.
146
+ */
147
+ function maintainReport() {
148
+ try {
149
+ const row = db.prepare("SELECT at, detail_json FROM audit WHERE action = 'maintain.run' ORDER BY at DESC LIMIT 1").get();
150
+ if (!row) return null;
151
+ let detail = {};
152
+ try { detail = JSON.parse(row.detail_json); } catch { detail = {}; }
153
+ return {
154
+ at: row.at,
155
+ passAt: typeof detail.at === 'string' ? detail.at : row.at,
156
+ disputes: Number(detail.disputes ?? 0),
157
+ summaries: Number(detail.summaries ?? 0),
158
+ intentions: Number(detail.intentions ?? 0),
159
+ playbook: Number(detail.playbook ?? 0),
160
+ goalRounds: Number(detail.goalRounds ?? 0),
161
+ aliases: Number(detail.aliases ?? 0),
162
+ working: Number(detail.working ?? 0),
163
+ // maintain() runs synchronously on the host heartbeat; a slow one is a
164
+ // user-visible freeze, so carry the duration through.
165
+ ms: Number.isFinite(Number(detail.ms)) ? Number(detail.ms) : null,
166
+ };
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+
29
172
  function audit({ scopeId = 'global', now = Date.now() } = {}) {
30
173
  const issues = [];
31
174
  const ok = [];
@@ -44,13 +187,41 @@ export function createHealthEngine({
44
187
  archived: traces.count({ scopeId, state: 'archived' }),
45
188
  total: traces.count({ scopeId }),
46
189
  };
47
- const fts = traces.ftsCount();
190
+ const fts = traces.ftsCount({ scopeId });
48
191
  if (fts !== traceCounts.total) add('warn', 'FTS_DRIFT', `FTS 行数 ${fts} 与 traces ${traceCounts.total} 不一致`, { fts, traces: traceCounts.total });
49
192
  else ok.push(`FTS 与 traces 对齐(${fts})`);
50
193
 
194
+ // Vector coverage: an index that lags behind the trace table is invisible
195
+ // in every other metric, so surface it here.
196
+ const embedded = Number(db.prepare(`
197
+ SELECT COUNT(*) AS c FROM embeddings e JOIN traces t ON t.id = e.trace_id
198
+ WHERE t.scope_id = ? AND t.state = 'active'
199
+ `).get(scopeId)?.c ?? 0);
200
+ const vectorCoverage = traceCounts.active ? Math.round((embedded / traceCounts.active) * 1000) / 1000 : 0;
201
+ const vectors = { embedded, coverage: vectorCoverage };
202
+ if (traceCounts.active >= 100 && vectorCoverage < 0.5) {
203
+ add('warn', 'VECTOR_COVERAGE', `向量覆盖 ${Math.round(vectorCoverage * 100)}%(${embedded}/${traceCounts.active}),回填可能还没跑完`, vectors);
204
+ } else if (traceCounts.active > 0) {
205
+ ok.push(`向量覆盖 ${Math.round(vectorCoverage * 100)}%(${embedded}/${traceCounts.active})`);
206
+ }
207
+
51
208
  const duplicates = traces.duplicateHashes(scopeId, { limit: 10 });
52
209
  if (duplicates.length) add('warn', 'DUPLICATE_TRACES', `发现 ${duplicates.length} 组重复 hash`, duplicates);
53
210
 
211
+ // Narrative layer: reflections pile up on their own, but the short version of
212
+ // them (episode summaries) is what makes long-term memory readable. Surface
213
+ // the counts so a thin layer is visible instead of silent.
214
+ const summaryCounts = {
215
+ episode: count("SELECT COUNT(*) AS c FROM summaries WHERE scope_id = ? AND level = 'episode'", scopeId),
216
+ merge: count("SELECT COUNT(*) AS c FROM summaries WHERE scope_id = ? AND level = 'merge'", scopeId),
217
+ thread: count("SELECT COUNT(*) AS c FROM summaries WHERE scope_id = ? AND level = 'thread'", scopeId),
218
+ };
219
+ const lastEpisode = db.prepare("SELECT MAX(created_at) AS at FROM summaries WHERE scope_id = ? AND level = 'episode'").get(scopeId)?.at ?? null;
220
+ const summaryLayers = { ...summaryCounts, lastEpisodeAt: lastEpisode };
221
+ if (summaryCounts.episode === 0 && traceCounts.active >= 100) {
222
+ add('warn', 'NO_EPISODE_SUMMARIES', '一条每日摘要都没有,长期记忆缺少短版本', summaryLayers);
223
+ }
224
+
54
225
  const factCounts = {
55
226
  active: count("SELECT COUNT(*) AS c FROM facts WHERE scope_id = ? AND status = 'active'", scopeId),
56
227
  disputed: count("SELECT COUNT(*) AS c FROM facts WHERE scope_id = ? AND status = 'disputed'", scopeId),
@@ -80,6 +251,86 @@ export function createHealthEngine({
80
251
  const feedbackCount = feedback?.list?.(scopeId, { limit: 1000 })?.length ?? count('SELECT COUNT(*) AS c FROM feedback WHERE scope_id = ?', scopeId);
81
252
  const skillCount = skills?.list?.({ scopeId, limit: 100 })?.length ?? count('SELECT COUNT(*) AS c FROM skills WHERE scope_id = ?', scopeId);
82
253
  const entityCount = entities?.list?.({ scopeId, limit: 500 })?.length ?? count('SELECT COUNT(*) AS c FROM entities WHERE scope_id = ?', scopeId);
254
+ const inhibition = inhibitionReport(scopeId, now);
255
+ const capture = captureReport(scopeId);
256
+ // Pick by recency, not by "has ms": after a change pass followed by a quiet
257
+ // one, the change row is newer than nothing but older than the quiet pass, and
258
+ // preferring it made the "最近一趟" line point at the older run.
259
+ const recorded = maintainReport();
260
+ const memory = typeof maintainLast === 'function' ? maintainLast() : null;
261
+ const recordedPassAt = recorded?.passAt ?? recorded?.at ?? null;
262
+ const memoryAt = typeof memory?.at === 'string' ? memory.at : null;
263
+ // Compare parsed timestamps, not strings: an injected `2026-11-15 14:36:00`
264
+ // sorts before `2026-11-15T14:36:00Z` purely because of the space, which made
265
+ // the same instant look older. Unparsable input is treated as "unknown".
266
+ const recordedMs = Number.isFinite(Date.parse(recordedPassAt ?? '')) ? Date.parse(recordedPassAt) : null;
267
+ const memoryMs = Number.isFinite(Date.parse(memoryAt ?? '')) ? Date.parse(memoryAt) : null;
268
+ let maintain = null;
269
+ if (recorded && recordedMs !== null && (memoryMs === null || recordedMs > memoryMs)) maintain = recorded;
270
+ else if (memory) maintain = memory;
271
+ else maintain = recorded;
272
+ const stamp = (value) => (typeof value === 'string' ? value.slice(0, 19) : '—');
273
+ if (maintain) ok.push(`最近一趟维护:${stamp(maintain.at)}(清意图 ${maintain.intentions} / 工作记忆 ${maintain.working}${Number.isFinite(maintain.ms) ? ` / ${maintain.ms}ms` : ''})`);
274
+ // A quiet pass writes no audit row, so the newest row can be hours old. Say
275
+ // both instead of letting one stale timestamp read as "nothing ran".
276
+ if (recorded && maintain && recordedMs !== null && memoryMs !== null && recordedMs < memoryMs) {
277
+ ok.push(`最近一次有变更的维护:${stamp(recordedPassAt)}(清意图 ${recorded.intentions} / 工作记忆 ${recorded.working})`);
278
+ }
279
+ // A configured LLM that keeps returning nothing is a different failure from a
280
+ // missing adapter; surface it instead of letting dream_runs pile up silently.
281
+ try {
282
+ const dreamSince = new Date(now - 6 * 3_600_000).toISOString();
283
+ // Labels now carry the reason (`llm-empty:empty-text:length`,
284
+ // `llm-empty-retry:no-selection`, …), so match the family and show buckets.
285
+ const emptyRows = db.prepare("SELECT error, COUNT(*) AS c FROM dream_runs WHERE error LIKE 'llm-empty%' AND created_at >= ? GROUP BY error").all(dreamSince);
286
+ const emptyRuns = emptyRows.reduce((sum, row) => sum + Number(row.c ?? 0), 0);
287
+ if (emptyRuns >= 5) {
288
+ // Keep the retry bit visible: `llm-empty:empty-text:max-tokens` and
289
+ // `llm-empty-retry:empty-text:max-tokens` are different stories and used
290
+ // to render as two identical buckets.
291
+ const pretty = (error) => {
292
+ const raw = String(error ?? '');
293
+ const retried = raw.startsWith('llm-empty-retry');
294
+ const reason = raw.replace(/^llm-empty(-retry)?:?/, '') || 'unknown';
295
+ return `${reason}${retried ? '(重试)' : ''}`;
296
+ };
297
+ const buckets = emptyRows.map((row) => `${pretty(row.error)}×${row.c}`).join(' · ');
298
+ add('warn', 'LLM_EMPTY', `最近 6 小时有 ${emptyRuns} 次巩固调用返回空(${buckets})`, { count: emptyRuns, buckets: Object.fromEntries(emptyRows.map((row) => [row.error, Number(row.c ?? 0)])) });
299
+ }
300
+ } catch { /* ignore */ }
301
+ if (config?.features?.llm !== true) {
302
+ // Without this the consolidation/dream path silently records no-llm on every
303
+ // tick (1914 rows in the live store) and the memory layer never solidifies.
304
+ add('warn', 'LLM_DISABLED', 'LLM 功能未开启(features.llm=false):巩固/做梦只会空转,记得在 profile 配置里打开', { feature: 'llm' });
305
+ }
306
+ const slowMs = Number.isFinite(Number(config?.maintainSlowMs)) ? Number(config.maintainSlowMs) : 2000;
307
+ const slowWindowHours = Number.isFinite(Number(config?.maintainSlowWindowHours)) ? Number(config.maintainSlowWindowHours) : 6;
308
+ // A slow pass is usually followed by a quiet one within minutes (maintain runs
309
+ // on the heartbeat), so judging only the newest pass would hide every real
310
+ // stall. Consider both, but only recent ones: a stall from yesterday is
311
+ // history, not "currently stalling".
312
+ const windowStart = now - slowWindowHours * 3_600_000;
313
+ const withinWindow = (pass) => {
314
+ const at = Date.parse(pass?.passAt ?? pass?.at ?? '');
315
+ return !Number.isFinite(at) || at >= windowStart;
316
+ };
317
+ const slowest = [maintain, recorded]
318
+ .filter((pass) => Number.isFinite(pass?.ms) && withinWindow(pass))
319
+ .sort((left, right) => right.ms - left.ms)[0] ?? null;
320
+ if (slowest && slowest.ms > slowMs) {
321
+ const slowAt = slowest.passAt ?? slowest.at ?? null;
322
+ const slowParsed = Date.parse(slowAt ?? '');
323
+ const ageMinutes = Number.isFinite(slowParsed) ? Math.max(0, Math.round((now - slowParsed) / 60_000)) : null;
324
+ const ageText = ageMinutes === null ? '' : `,距现在 ${ageMinutes} 分钟`;
325
+ add('warn', 'SLOW_MAINTAIN', `维护耗时 ${slowest.ms}ms(${stamp(slowAt)}${ageText}),可能卡住宿主心跳`, { ms: slowest.ms, at: slowAt, ageMinutes });
326
+ }
327
+ if (capture.total > 0) {
328
+ ok.push(`捕获过滤:${capture.total} 轮宿主对话中,剥掉注入 ${capture.stripped} 轮、截断 ${capture.truncated} 轮`);
329
+ }
330
+ if (inhibition.enabled) {
331
+ ok.push(`抑制在线:${inhibition.count} 条被压制(均值 ${inhibition.average})`);
332
+ if (inhibition.count > 60) add('warn', 'INHIBITION_HIGH', `${inhibition.count} 条记忆正被抑制,可能压得太狠`, { count: inhibition.count });
333
+ }
83
334
 
84
335
  let dbBytes = 0;
85
336
  try { dbBytes = config.dbFile && config.dbFile !== ':memory:' ? fs.statSync(config.dbFile).size : 0; } catch { dbBytes = 0; }
@@ -106,6 +357,15 @@ export function createHealthEngine({
106
357
  jobs: jobs?.counts?.() ?? {},
107
358
  },
108
359
  dbBytes,
360
+ inhibition,
361
+ capture,
362
+ vectors,
363
+ maintain,
364
+ consolidation: consolidationReport(scopeId, now),
365
+ // Last pass that actually changed something (audit row), so callers can
366
+ // distinguish "quiet heartbeat" from "nothing has run in hours".
367
+ maintainLastChanged: recorded,
368
+ summaryLayers,
109
369
  };
110
370
  }
111
371
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Retrieval-induced forgetting, engineering edition.
3
+ *
4
+ * Anderson & Spellman showed that practising one item suppresses its
5
+ * competitors, and that the suppression decays. This module keeps that as a
6
+ * small, explicit penalty stored in trace metadata: when a recall selects one
7
+ * memory and drops a near-duplicate competitor, the competitor gets a small
8
+ * inhibition that halves every `halfLifeDays`. It is off by default.
9
+ */
10
+ const DAY_MS = 86_400_000;
11
+
12
+ function clamp01(value) {
13
+ const n = Number(value);
14
+ if (!Number.isFinite(n)) return 0;
15
+ return Math.max(0, Math.min(1, n));
16
+ }
17
+
18
+ export function suppressionOf(metadata, now = Date.now(), { halfLifeDays = 14 } = {}) {
19
+ const raw = clamp01(metadata?.inhibition ?? 0);
20
+ if (!raw) return 0;
21
+ const at = Date.parse(metadata?.suppressedAt ?? '');
22
+ if (!Number.isFinite(at)) return raw;
23
+ const days = Math.max(0, (now - at) / DAY_MS);
24
+ const life = Math.max(1, Number(halfLifeDays) || 14);
25
+ return clamp01(raw * Math.pow(0.5, days / life));
26
+ }
27
+
28
+ export function withSuppression(metadata, now = Date.now(), { step = 0.15, cap = 1, halfLifeDays = 14 } = {}) {
29
+ const current = suppressionOf(metadata, now, { halfLifeDays });
30
+ return {
31
+ ...(metadata && typeof metadata === 'object' ? metadata : {}),
32
+ inhibition: clamp01(Math.min(Number(cap) || 1, current + (Number(step) || 0.15))),
33
+ suppressedAt: new Date(now).toISOString(),
34
+ };
35
+ }
36
+
37
+ export function competingFactor(metadata, now = Date.now(), { strength = 0.35, halfLifeDays = 14 } = {}) {
38
+ return 1 - suppressionOf(metadata, now, { halfLifeDays }) * (Number(strength) || 0);
39
+ }
@@ -22,6 +22,7 @@ export function createLifeEngine({
22
22
  working = null,
23
23
  emotion = null,
24
24
  consolidation = null,
25
+ narrative = null,
25
26
  features = {},
26
27
  llm = null,
27
28
  diaryLlm = null,
@@ -293,11 +294,20 @@ export function createLifeEngine({
293
294
  let consolidationRun = null;
294
295
  if (consolidation && features?.llm === true && features?.consolidateOnSleep !== false) {
295
296
  try {
296
- consolidationRun = await consolidation.run({ scopeId, now: at, limit: 10 });
297
+ consolidationRun = await consolidation.run({ scopeId, now: at, limit: 10, caller: 'sleep' });
297
298
  } catch {
298
299
  consolidationRun = null;
299
300
  }
300
301
  }
302
+ // Sleep is when the day gets woven together: build a couple of narrative
303
+ // threads from the episodes that now exist. Idempotent — weave() skips seeds
304
+ // an existing thread already cites.
305
+ let narrativeRun = null;
306
+ try {
307
+ narrativeRun = narrative?.weave?.({ scopeId, maxThreads: 2, windowHours: Number(features?.threadWindowHours ?? 24), at }) ?? null;
308
+ } catch {
309
+ narrativeRun = null;
310
+ }
301
311
  const report = {
302
312
  at: new Date(at).toISOString(),
303
313
  purgedWorking: purged,
@@ -306,6 +316,7 @@ export function createLifeEngine({
306
316
  affectTargets: affect?.length ?? 0,
307
317
  consolidation: consolidationRun?.run?.status ?? null,
308
318
  consolidated: consolidationRun?.applied?.length ?? 0,
319
+ narrative: narrativeRun?.built ?? null,
309
320
  };
310
321
  const id = makeId('slp');
311
322
  db.prepare('INSERT INTO sleep_runs(id, scope_id, at, report_json) VALUES (?, ?, ?, ?)')
@@ -1,5 +1,6 @@
1
- function stripJson(text) {
2
- const source = String(text ?? '').trim();
1
+ import { guardFactCandidate } from './fact-guard.js';
2
+
3
+ function stripJson(text) { const source = String(text ?? '').trim();
3
4
  const start = source.indexOf('{');
4
5
  const end = source.lastIndexOf('}');
5
6
  if (start < 0 || end <= start) return null;
@@ -34,15 +35,17 @@ export async function extractFactsWithLlm({ llm, text, maxFacts = 8 } = {}) {
34
35
  const candidates = [];
35
36
  for (const item of parsed.facts.slice(0, Math.max(1, Math.min(20, maxFacts)))) {
36
37
  if (!item || typeof item !== 'object') continue;
37
- const subject = String(item.subject ?? '').trim().slice(0, 40);
38
- const predicate = String(item.predicate ?? '').trim().slice(0, 60);
39
- const object = String(item.object ?? '').trim().slice(0, 120);
40
- const confidence = Number(item.confidence);
41
- if (!subject || !predicate || !object || !Number.isFinite(confidence) || confidence < 0.6) continue;
42
- const key = `${subject}|${predicate}|${object}`;
38
+ const guarded = guardFactCandidate({
39
+ subject: item.subject,
40
+ predicate: item.predicate,
41
+ object: item.object,
42
+ confidence: item.confidence,
43
+ });
44
+ if (!guarded || guarded.confidence < 0.6) continue;
45
+ const key = `${guarded.subject}|${guarded.predicate}|${guarded.object}`;
43
46
  if (seen.has(key)) continue;
44
47
  seen.add(key);
45
- candidates.push({ subject, predicate, object, confidence: Math.min(1, confidence) });
48
+ candidates.push(guarded);
46
49
  }
47
50
  return { candidates, error: null };
48
51
  }