dsh-cortex-memory 0.4.22 → 0.4.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +2390 -154
  2. package/README.md +11 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +10 -10
  5. package/bench/synthetic.js +3 -3
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/client.js +1 -1
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/icon.svg +12 -2
  15. package/index.js +27 -3
  16. package/package.json +3 -3
  17. package/src/adapters/shiori.js +1 -1
  18. package/src/api/routes.js +1 -1
  19. package/src/core/feature-overrides.js +2 -2
  20. package/src/engines/compression.js +172 -3
  21. package/src/engines/consolidate.js +397 -26
  22. package/src/engines/encode.js +16 -3
  23. package/src/engines/extract.js +72 -8
  24. package/src/engines/fact-guard.js +51 -0
  25. package/src/engines/health.js +263 -3
  26. package/src/engines/inhibition.js +39 -0
  27. package/src/engines/life.js +14 -3
  28. package/src/engines/llm-facts.js +12 -9
  29. package/src/engines/narrative.js +150 -13
  30. package/src/engines/reflect.js +172 -14
  31. package/src/engines/retrieve.js +44 -5
  32. package/src/engines/summary-coverage.js +62 -0
  33. package/src/engines/summary-dedupe.js +77 -0
  34. package/src/engines/summon-rank.js +132 -0
  35. package/src/host/runtime.js +64 -4
  36. package/src/host/scheduler.js +224 -3
  37. package/src/llm/adapter.js +29 -8
  38. package/src/memory/query.js +1 -1
  39. package/src/memory/spacing.js +15 -0
  40. package/src/memory/tokenizer.js +1 -1
  41. package/src/prompt/tiers.js +88 -12
  42. package/src/self/alias.js +25 -0
  43. package/src/self/emotion.js +3 -1
  44. package/src/self/relationship.js +44 -13
  45. package/src/self/state.js +20 -2
  46. package/src/self/working.js +34 -3
  47. package/src/service/cortex.js +493 -53
  48. package/src/store/repositories/facts.js +34 -1
  49. package/src/store/repositories/summaries.js +8 -1
  50. package/src/store/repositories/traces.js +22 -2
  51. package/src/tools/definitions.js +118 -4
  52. package/src/vector/index.js +96 -7
  53. package/test/integration/_helpers.js +0 -128
  54. package/test/integration/acceptance.test.js +0 -803
  55. package/test/integration/ann-load.test.js +0 -61
  56. package/test/integration/api-contract.test.js +0 -1476
  57. package/test/integration/backup-privacy.test.js +0 -214
  58. package/test/integration/consolidate.test.js +0 -75
  59. package/test/integration/edge-cases.test.js +0 -1088
  60. package/test/integration/exchange.test.js +0 -326
  61. package/test/integration/life-loop.test.js +0 -188
  62. package/test/integration/load.test.js +0 -751
  63. package/test/integration/markdown-sync.test.js +0 -35
  64. package/test/integration/policy-query-api.test.js +0 -306
  65. package/test/integration/resilience-writes.test.js +0 -241
  66. package/test/integration/tools-contract.test.js +0 -1324
  67. package/test/unit/ann-edge.test.js +0 -102
  68. package/test/unit/ann.test.js +0 -77
  69. package/test/unit/api-client.test.js +0 -576
  70. package/test/unit/api-validate.test.js +0 -19
  71. package/test/unit/api.test.js +0 -555
  72. package/test/unit/appraisal.test.js +0 -48
  73. package/test/unit/attachments.test.js +0 -33
  74. package/test/unit/autonomy.test.js +0 -53
  75. package/test/unit/batch.test.js +0 -46
  76. package/test/unit/bench.test.js +0 -40
  77. package/test/unit/benchmark-synthetic.test.js +0 -52
  78. package/test/unit/cli-default-root.test.js +0 -21
  79. package/test/unit/client-contract.test.js +0 -32
  80. package/test/unit/compression.test.js +0 -76
  81. package/test/unit/core.test.js +0 -77
  82. package/test/unit/develop.test.js +0 -130
  83. package/test/unit/development.test.js +0 -68
  84. package/test/unit/digest.test.js +0 -26
  85. package/test/unit/dsr.test.js +0 -111
  86. package/test/unit/edges-candidates.test.js +0 -113
  87. package/test/unit/emotion.test.js +0 -61
  88. package/test/unit/encode.test.js +0 -98
  89. package/test/unit/evolution.test.js +0 -130
  90. package/test/unit/external-ann-search.test.js +0 -50
  91. package/test/unit/external-ann.test.js +0 -29
  92. package/test/unit/facts-belief.test.js +0 -32
  93. package/test/unit/facts.test.js +0 -107
  94. package/test/unit/feature-overrides.test.js +0 -42
  95. package/test/unit/fts-migration.test.js +0 -42
  96. package/test/unit/graph.test.js +0 -79
  97. package/test/unit/growth-reflect.test.js +0 -123
  98. package/test/unit/guard-runtime.test.js +0 -40
  99. package/test/unit/guardian.test.js +0 -91
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/hnsw.test.js +0 -35
  102. package/test/unit/host-runtime.test.js +0 -142
  103. package/test/unit/host.test.js +0 -58
  104. package/test/unit/identity.test.js +0 -98
  105. package/test/unit/induct-evaluate.test.js +0 -41
  106. package/test/unit/ingest-extracted.test.js +0 -35
  107. package/test/unit/initiative.test.js +0 -90
  108. package/test/unit/jobs.test.js +0 -93
  109. package/test/unit/json-snapshot.test.js +0 -57
  110. package/test/unit/life-consolidate.test.js +0 -34
  111. package/test/unit/life.test.js +0 -149
  112. package/test/unit/llm-facts-integration.test.js +0 -27
  113. package/test/unit/llm-facts.test.js +0 -16
  114. package/test/unit/llm.test.js +0 -45
  115. package/test/unit/locomo.test.js +0 -45
  116. package/test/unit/longmemeval.test.js +0 -56
  117. package/test/unit/markdown-import.test.js +0 -44
  118. package/test/unit/markdown.test.js +0 -34
  119. package/test/unit/memory-edit.test.js +0 -112
  120. package/test/unit/metrics.test.js +0 -26
  121. package/test/unit/migration.test.js +0 -38
  122. package/test/unit/model-config.test.js +0 -52
  123. package/test/unit/narrative.test.js +0 -62
  124. package/test/unit/playbook-consolidate.test.js +0 -24
  125. package/test/unit/privacy-scope.test.js +0 -39
  126. package/test/unit/profile-paths.test.js +0 -21
  127. package/test/unit/profile.test.js +0 -26
  128. package/test/unit/prompt.test.js +0 -42
  129. package/test/unit/providers.test.js +0 -42
  130. package/test/unit/qa.test.js +0 -100
  131. package/test/unit/query.test.js +0 -53
  132. package/test/unit/retention.test.js +0 -31
  133. package/test/unit/retrieval-ranking.test.js +0 -31
  134. package/test/unit/retrieve.test.js +0 -117
  135. package/test/unit/rotation.test.js +0 -25
  136. package/test/unit/scanner.test.js +0 -50
  137. package/test/unit/scenario.test.js +0 -78
  138. package/test/unit/scheduler.test.js +0 -136
  139. package/test/unit/self-state.test.js +0 -94
  140. package/test/unit/service.test.js +0 -72
  141. package/test/unit/shiori-import.test.js +0 -77
  142. package/test/unit/skills.test.js +0 -104
  143. package/test/unit/store.test.js +0 -111
  144. package/test/unit/temporal-graph.test.js +0 -44
  145. package/test/unit/tiers.test.js +0 -39
  146. package/test/unit/tokenizer-fts.test.js +0 -35
  147. package/test/unit/tools.test.js +0 -122
  148. package/test/unit/upgrade-0412.test.js +0 -104
  149. package/test/unit/upgrade-0413.test.js +0 -84
  150. package/test/unit/upgrade-0414.test.js +0 -101
  151. package/test/unit/vector-ann.test.js +0 -53
  152. package/test/unit/vector-async.test.js +0 -69
  153. package/test/unit/vector.test.js +0 -68
  154. package/test/unit/working.test.js +0 -80
@@ -4,6 +4,27 @@ import { nowIso } from '../core/time.js';
4
4
  import { transaction } from '../store/database.js';
5
5
 
6
6
  const PROTECTED_IMPORTANCE = 0.7;
7
+
8
+ // The protection line is one fixed, explainable threshold now:
9
+ // >= 0.9 long-term identity level — only update / conflict, never archive or merge
10
+ // 0.7–0.9 important, may still be merged into a better copy
11
+ // < 0.7 eligible for archive
12
+ // 0.4.116→0.4.130 computed it as the 75th percentile of the *batch*. Candidates were
13
+ // sorted by importance descending, so p75 was always the batch maximum and the line
14
+ // covered every candidate — the model could only answer keep. Percentiles of a
15
+ // self-selected top slice do not tell you anything about the store.
16
+ const PROTECTED_LINE = 0.9;
17
+
18
+ // A trace is not worth asking about twice within a day: the answer cannot change
19
+ // unless the input changes, and an all-keep run used to burn a fresh LLM call every
20
+ // 30 minutes on the same 20 traces.
21
+ const ASKED_WINDOW_MS = 24 * 3_600_000;
22
+
23
+ // Keep a caller-supplied similarity threshold inside a sane band: 0.5 is loose enough
24
+ // to find paraphrases, 0.99 never merges anything by accident.
25
+ export function clampThreshold(value) {
26
+ return Math.min(0.99, Math.max(0.5, Number(value) || 0.8));
27
+ }
7
28
  const ALLOWED = new Set(['keep', 'merge', 'archive', 'update', 'conflict']);
8
29
 
9
30
  function digest(value) {
@@ -24,16 +45,27 @@ function parseJsonArray(text) {
24
45
  }
25
46
  }
26
47
 
27
- export function createConsolidationEngine({ db, traces, summaries = null, audit = null, llm = null } = {}) {
48
+ export function createConsolidationEngine({ db, traces, summaries = null, audit = null, llm = null, logger = null } = {}) {
28
49
  if (!db || !traces) throw new Error('consolidation engine needs db and traces');
29
50
 
30
- function record({ scopeId, at, status, model = null, inputDigest, input, decisions = [], applied = [], error = null }) {
51
+ function record({ scopeId, at, status, model = null, inputDigest, input, decisions = [], applied = [], error = null, caller = 'unknown', groups = null, groupsDropped = null }) {
31
52
  const id = makeId('drn');
32
53
  db.prepare(`
33
54
  INSERT INTO dream_runs(id, scope_id, at, status, model, input_digest, input_json, decisions_json, applied_json, error, created_at)
34
55
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
35
56
  `).run(id, scopeId, at, status, model, inputDigest, JSON.stringify(input), JSON.stringify(decisions), JSON.stringify(applied), error, nowIso());
36
- return get(id);
57
+ // `dream_runs` has no caller column (adding one means a migration), and two
58
+ // runs a minute apart used to be unexplainable. The audit row keeps the actor.
59
+ try {
60
+ audit?.record?.({
61
+ actor: 'system',
62
+ action: 'consolidation.run',
63
+ targetType: 'consolidation',
64
+ targetId: id,
65
+ detail: { caller, status, model, error, decisions: decisions.length, applied: applied.length, groups: groups ?? null, groupsDropped: groupsDropped ?? null },
66
+ });
67
+ } catch { /* audit is best effort, never fail a run for it */ }
68
+ return { ...get(id), groups, groupsDropped };
37
69
  }
38
70
 
39
71
  function get(id) {
@@ -52,21 +84,34 @@ export function createConsolidationEngine({ db, traces, summaries = null, audit
52
84
  .map((row) => get(row.id));
53
85
  }
54
86
 
55
- function validateDecision(decision, byId) {
87
+ // One predicate for "may not be touched". The archive branch and the merge branch
88
+ // used to spell this out separately, and the merge branch forgot reflections: a
89
+ // low-importance reflection could be merged away as a source.
90
+ function isProtected(trace, protect = PROTECTED_IMPORTANCE) {
91
+ return Number(trace?.importance ?? 0) >= protect || trace?.kind === 'reflection';
92
+ }
93
+
94
+ function validateDecision(decision, byId, protect = PROTECTED_IMPORTANCE, { allowProtectedMerge = false } = {}) {
56
95
  if (!decision || typeof decision !== 'object') return { ok: false, reason: 'not-an-object' };
57
96
  const action = String(decision.action ?? '').toLowerCase();
58
97
  if (!ALLOWED.has(action)) return { ok: false, reason: 'unknown-action' };
59
98
  const ids = Array.isArray(decision.ids) ? decision.ids.map(String) : [];
60
99
  if (ids.length === 0) return { ok: false, reason: 'missing-ids' };
61
100
  if (ids.some((id) => !byId.has(id))) return { ok: false, reason: 'unknown-id' };
62
- if (action === 'archive' && ids.some((id) => byId.get(id).importance >= PROTECTED_IMPORTANCE || byId.get(id).kind === 'reflection')) {
101
+ if (action === 'archive' && ids.some((id) => isProtected(byId.get(id), protect))) {
63
102
  return { ok: false, reason: 'protected' };
64
103
  }
65
104
  if (action === 'merge') {
66
105
  if (ids.length < 2) return { ok: false, reason: 'merge-needs-two' };
67
106
  const targetId = decision.targetId ? String(decision.targetId) : ids[0];
68
107
  if (!ids.includes(targetId)) return { ok: false, reason: 'merge-target-not-in-ids' };
69
- if (ids.some((id) => byId.get(id).importance >= PROTECTED_IMPORTANCE && id !== targetId)) return { ok: false, reason: 'protected-merge' };
108
+ if (ids.some((id) => {
109
+ if (id === targetId) return false;
110
+ const trace = byId.get(id);
111
+ // Reflections are never merge sources. High-importance traces may be sources
112
+ // only when the caller already proved near-duplication (deterministic dedupe).
113
+ return trace?.kind === 'reflection' || (!allowProtectedMerge && isProtected(trace, protect));
114
+ })) return { ok: false, reason: 'protected-merge' };
70
115
  return { ok: true, action, ids, targetId, reason: String(decision.reason ?? '') };
71
116
  }
72
117
  if (action === 'update') {
@@ -77,51 +122,242 @@ export function createConsolidationEngine({ db, traces, summaries = null, audit
77
122
  return { ok: true, action, ids, reason: String(decision.reason ?? '') };
78
123
  }
79
124
 
80
- async function run({ scopeId = 'global', now = Date.now(), limit = 30, dryRun = false, model = null } = {}) {
125
+ // Trace ids that were already shown to the model during the window. dream_runs
126
+ // keeps its input, so this needs no new table: read the recent rows and collect
127
+ // the ids. A run with a broken input row is skipped, never fatal.
128
+ // Preview rows are excluded: a dry run only rehearses, it does not consolidate,
129
+ // so its candidates must stay available for the real pass.
130
+ function askedIdsSince({ scopeId, sinceMs, maxRuns = 64 }) {
131
+ const asked = new Set();
132
+ try {
133
+ const rows = db.prepare("SELECT input_json FROM dream_runs WHERE scope_id = ? AND at >= ? AND status != 'preview' ORDER BY at DESC LIMIT ?")
134
+ .all(scopeId, new Date(sinceMs).toISOString(), Math.max(1, Math.min(200, Number(maxRuns) || 64)));
135
+ for (const row of rows) {
136
+ try {
137
+ for (const item of JSON.parse(row.input_json)) {
138
+ if (item && typeof item.id === 'string') asked.add(item.id);
139
+ }
140
+ } catch { /* one broken row must not hide the rest */ }
141
+ }
142
+ } catch { /* no run history means nothing was asked yet */ }
143
+ return asked;
144
+ }
145
+
146
+ // Every trace already cited by a summary (episode, merge or thread) has a short
147
+ // version of itself; re-summarising it buys nothing. This is the same "closed
148
+ // loop" idea as profile coverage, measured in trace ids.
149
+ function summarisedIds(scopeId) {
150
+ const covered = new Set();
151
+ try {
152
+ for (const summary of (summaries?.list?.(scopeId, { limit: 500 }) ?? [])) {
153
+ for (const sourceId of Array.isArray(summary.sourceIds) ? summary.sourceIds : []) covered.add(sourceId);
154
+ }
155
+ } catch { /* coverage is an optimisation, never a reason to fail a run */ }
156
+ return covered;
157
+ }
158
+
159
+ async function run({ scopeId = 'global', now = Date.now(), limit = 30, dryRun = false, model = null, force = false, caller = 'unknown', spread = false } = {}) {
81
160
  const at = nowIso(now);
82
- const candidates = traces.list({ scopeId, state: 'active', limit: 200 })
83
- .sort((a, b) => Number(b.importance) - Number(a.importance) || String(a.recordedAt).localeCompare(String(b.recordedAt)))
84
- .slice(0, Math.max(1, Math.min(80, Number(limit) || 30)));
161
+ // 500, not 200: the old pool silently hid anything older than the newest 200
162
+ // active traces from consolidation (the LLM still receives at most `limit`).
163
+ //
164
+ // Selection is the opposite of 0.4.116→0.4.130: those versions sorted by
165
+ // importance descending, so the model was always handed the batch its own
166
+ // prompt protects (99% of a production store is >= 0.7 and the top slice is all
167
+ // 1.0) and could only answer keep. Rank the other end first instead:
168
+ // 1. no summary covers the trace yet,
169
+ // 2. it was not shown to the model in the last 24h,
170
+ // 3. lowest importance, oldest first.
171
+ // Asked traces sink to the bottom rather than disappear: when every trace has
172
+ // been asked, the run rotates back over the stale end instead of going idle.
173
+ const pool = traces.list({ scopeId, state: 'active', limit: 500 });
174
+ const covered = summarisedIds(scopeId);
175
+ const asked = askedIdsSince({ scopeId, sinceMs: now - ASKED_WINDOW_MS });
176
+ const ranked = pool
177
+ .slice()
178
+ .sort((a, b) => {
179
+ const coveredA = covered.has(a.id) ? 1 : 0;
180
+ const coveredB = covered.has(b.id) ? 1 : 0;
181
+ const askedA = asked.has(a.id) ? 1 : 0;
182
+ const askedB = asked.has(b.id) ? 1 : 0;
183
+ return coveredA - coveredB
184
+ || askedA - askedB
185
+ || Number(a.importance) - Number(b.importance)
186
+ || String(a.recordedAt).localeCompare(String(b.recordedAt));
187
+ });
188
+ const count = Math.max(1, Math.min(80, Number(limit) || 30));
189
+ // A daily deep pass needs spread, not depth in one band: ranking from the low
190
+ // end put all 60 candidates at importance 0.7 (the next untouched band). Spread
191
+ // takes half from the low end and samples the rest evenly, so one pass sees the
192
+ // whole store's shape.
193
+ let candidates;
194
+ if (spread && ranked.length > count) {
195
+ const half = Math.ceil(count / 2);
196
+ const low = ranked.slice(0, half);
197
+ const rest = ranked.slice(half);
198
+ const remainder = Math.min(count - low.length, rest.length);
199
+ const sampled = [];
200
+ if (remainder > 0) {
201
+ const stride = rest.length / remainder;
202
+ for (let index = 0; index < remainder; index += 1) {
203
+ sampled.push(rest[Math.min(rest.length - 1, Math.floor(index * stride))]);
204
+ }
205
+ }
206
+ candidates = [...low, ...sampled];
207
+ } else {
208
+ candidates = ranked.slice(0, count);
209
+ }
85
210
  const input = candidates.map((trace) => ({ id: trace.id, kind: trace.kind, title: trace.title, content: String(trace.content).slice(0, 600), importance: trace.importance, recordedAt: trace.recordedAt }));
86
- const inputDigest = digest(JSON.stringify(input));
211
+ const protect = PROTECTED_LINE;
212
+ const protectedCount = input.filter((item) => isProtected(item, protect)).length;
213
+ // Capture already rejects byte-identical traces, so exact matching finds
214
+ // nothing. Group by shared 2-gram shingles instead: rephrased repeats are what
215
+ // actually reaches consolidation.
216
+ const shingles = (value) => {
217
+ const flat = String(value ?? '').replace(/\s+/g, '');
218
+ const set = new Set();
219
+ for (let i = 0; i + 2 <= flat.length; i += 1) set.add(flat.slice(i, i + 2));
220
+ return set;
221
+ };
222
+ const jaccard = (a, b) => {
223
+ if (a.size === 0 || b.size === 0) return 0;
224
+ let shared = 0;
225
+ for (const gram of a) if (b.has(gram)) shared += 1;
226
+ return shared / (a.size + b.size - shared);
227
+ };
228
+ const grams = candidates.map((trace) => shingles(`${trace.title ?? ''}${trace.content ?? ''}`));
229
+ const parent = candidates.map((_, index) => index);
230
+ const find = (index) => (parent[index] === index ? index : (parent[index] = find(parent[index])));
231
+ for (let i = 0; i < candidates.length; i += 1) {
232
+ for (let j = i + 1; j < candidates.length; j += 1) {
233
+ if (jaccard(grams[i], grams[j]) >= 0.6) parent[find(j)] = find(i);
234
+ }
235
+ }
236
+ const clusters = new Map();
237
+ candidates.forEach((trace, index) => {
238
+ const root = find(index);
239
+ const bucket = clusters.get(root) ?? [];
240
+ bucket.push(trace.id);
241
+ clusters.set(root, bucket);
242
+ });
243
+ const protectedIds = new Set(input.filter((item) => isProtected(item, protect)).map((item) => item.id));
244
+ // validateDecision rejects a merge whose non-target member is protected, so a
245
+ // group with two protected members can never be applied. Drop those instead of
246
+ // handing the model a decision that is guaranteed to fail. When exactly one is
247
+ // protected it must be the merge target — say so structurally instead of hoping
248
+ // the model guesses which one is on the protection line.
249
+ const allGroups = [...clusters.values()].filter((ids) => ids.length > 1);
250
+ const duplicateGroups = [];
251
+ let droppedGroups = 0;
252
+ for (const ids of allGroups) {
253
+ const protectedIn = ids.filter((id) => protectedIds.has(id));
254
+ if (protectedIn.length >= 2) {
255
+ droppedGroups += 1;
256
+ continue;
257
+ }
258
+ duplicateGroups.push(protectedIn.length === 1 ? { ids, mustBeTarget: protectedIn[0] } : { ids });
259
+ }
260
+ const inputDigest = digest(`run:${JSON.stringify(input)}`);
261
+ // Idempotence gate. Only a run the model actually answered means "this batch
262
+ // was handled": `applied` and `degraded` both carry a real answer. A preview
263
+ // (rehearsal) and a rejected batch (the model's own bad output) always let the
264
+ // next pass through. A skipped row is special only while there is no adapter:
265
+ // without one, every tick would otherwise rewrite the same "no-llm" row.
266
+ // 0.4.130 short-circuited skipped rows unconditionally, so an applied keep-only
267
+ // run still cost a fresh LLM call every 30 minutes on an identical input.
268
+ const hasAdapter = Boolean(llm && typeof llm.complete === 'function');
269
+ const previous = list({ scopeId, limit: 1 })[0] ?? null;
270
+ const answered = Boolean(previous) && (previous.status === 'applied' || previous.status === 'degraded');
271
+ const noisySkip = !hasAdapter && Boolean(previous) && previous.status === 'skipped' && previous.inputDigest === inputDigest;
272
+ const unchanged = !force && Boolean(previous) && previous.inputDigest === inputDigest && (answered || noisySkip);
273
+ if (unchanged) {
274
+ return { run: previous, applied: [], decisions: [], skipped: 'unchanged' };
275
+ }
87
276
  if (!input.length) {
88
- return { run: record({ scopeId, at, status: 'skipped', model, inputDigest, input, error: 'no-active-traces' }), applied: [], decisions: [] };
277
+ return { run: record({ scopeId, at, caller, status: 'skipped', model, inputDigest, input, error: 'no-active-traces' }), applied: [], decisions: [] };
89
278
  }
90
279
 
91
280
  let raw = null;
92
- if (llm && typeof llm.complete === 'function') {
281
+ let retried = false;
282
+ let bounded = false;
283
+ let failureReason = null;
284
+ const ask = async (items, maxContent, maxTokens = 900) => {
285
+ const payload = items.map((item) => ({ ...item, content: String(item.content ?? '').slice(0, maxContent) }));
93
286
  try {
94
- raw = await llm.complete({
95
- system: '你是记忆巩固器。只输出 JSON 数组,不要解释。允许 action: keep/merge/archive/update/conflict。每条必须有 ids;merge 还要 targetId;update 还要 content。不得归档 importance>=0.7 或 reflection。',
96
- prompt: `候选记忆:\n${JSON.stringify(input, null, 2)}\n\n输出决策数组。`,
97
- maxTokens: 900,
287
+ return await llm.complete({
288
+ system: `你是记忆巩固器。只输出 JSON 数组,不要解释。允许 action: keep/merge/archive/update/conflict。每条必须有 ids;merge 的 ids 至少两条(合并方 + 被合并方),targetId 必须是 ids 里的一条、通常是保留信息最全的那条,只带一条 id 的 merge 会被拒绝;update 还要 content。不得归档 importance>=${protect} 或 reflection。`,
289
+ prompt: `候选记忆:\n${JSON.stringify(payload, null, 2)}\n\n本次保护线 importance>=${protect},共 ${protectedCount} 条受保护;低于保护线、且内容与他条重复或被已有摘要覆盖的,优先 merge,其次 archive;没有可合并的就 keep。merge 必须一次给出所有参与合并的 ids(至少两条),并把要保留的那条写进 targetId。${allProtected ? '\n注意:本批全部在保护线上,不要提出 archive 或 merge;如某条内容需要更正,用 update(提供 content),矛盾则用 conflict。' : ''}${duplicateGroups.length ? `\n已检测到这些重复组,请用 merge 合并;带 mustBeTarget 的组,targetId 必须是 mustBeTarget 指定的那条:${JSON.stringify(duplicateGroups)}` : ''}输出决策数组。`,
290
+ maxTokens: Math.max(900, maxTokens),
98
291
  temperature: 0.1,
99
292
  purpose: 'cortex-consolidate',
293
+ // A per-call callback keeps the reason scoped to this run; a shared
294
+ // adapter field could be reset or overwritten by an interleaved
295
+ // dream / feeling / summarize call.
296
+ onReason: (reason) => { failureReason = reason; },
100
297
  });
101
- } catch {
102
- raw = null;
298
+ } catch (error) {
299
+ failureReason = 'exception-outer';
300
+ try { logger?.warn?.(`cortex consolidate ask failed: ${error instanceof Error ? error.message : String(error)}`); } catch { /* logging is best effort */ }
301
+ return null;
302
+ }
303
+ };
304
+ // Everything on the protection line: archive/merge would only be rejected, but
305
+ // update/conflict are non-destructive and must stay available, so the batch is
306
+ // still sent — with a prompt that excludes the doomed actions.
307
+ const allProtected = protectedCount === input.length;
308
+ if (hasAdapter) {
309
+ // Live evidence (2026-11-16): the installed 0.4.103 recorded
310
+ // `llm-empty:empty-text:max-tokens` — the answer was cut off by the output
311
+ // budget, not rejected. So the fix is a bigger budget plus a bounded prompt:
312
+ // rounding 900 was simply too small once reasoning tokens are counted.
313
+ const big = JSON.stringify(input).length > 5000;
314
+ if (big && input.length > 20) {
315
+ bounded = true;
316
+ raw = await ask(input.slice(0, 20), 300, 6000);
317
+ if (!raw) {
318
+ retried = true;
319
+ raw = await ask(input.slice(0, 10), 220, 6000);
320
+ }
321
+ } else {
322
+ raw = await ask(input, 600, 3000);
323
+ if (!raw && input.length > 10) {
324
+ retried = true;
325
+ raw = await ask(input.slice(0, 10), 220, 6000);
326
+ }
103
327
  }
104
328
  }
105
329
  if (!raw) {
106
- return { run: record({ scopeId, at, status: 'skipped', model, inputDigest, input, error: 'no-llm' }), applied: [], decisions: [] };
330
+ // "No adapter at all" and "adapter answered nothing" need different fixes;
331
+ // the old shared `no-llm` label hid which one was happening. Carry the
332
+ // adapter's own reason too, and mark whether the slim retry already ran —
333
+ // otherwise "retried and still empty" looks identical to "empty first try".
334
+ const reason = hasAdapter ? (failureReason ?? (typeof llm.lastFailure === 'function' ? llm.lastFailure() : null)) : null;
335
+ const label = hasAdapter ? `llm-empty${retried ? '-retry' : ''}${reason ? `:${reason}` : ''}` : 'no-llm-adapter';
336
+ return { run: record({ scopeId, at, caller, status: 'skipped', model, inputDigest, input, error: label, groups: duplicateGroups.length, groupsDropped: droppedGroups }), applied: [], decisions: [] };
107
337
  }
108
338
  const parsed = parseJsonArray(raw);
109
339
  if (!parsed) {
110
- return { run: record({ scopeId, at, status: 'rejected', model, inputDigest, input, error: 'invalid-json' }), applied: [], decisions: [] };
340
+ return { run: record({ scopeId, at, caller, status: 'rejected', model, inputDigest, input, error: 'invalid-json', groups: duplicateGroups.length, groupsDropped: droppedGroups }), applied: [], decisions: [] };
111
341
  }
112
342
 
113
343
  const byId = new Map(candidates.map((trace) => [trace.id, trace]));
114
344
  const decisions = [];
115
345
  const applied = [];
116
346
  const rejected = [];
347
+ const rejectReason = (reason) => {
348
+ const tally = rejected.reduce((acc, item) => { acc[item.reason] = (acc[item.reason] ?? 0) + 1; return acc; }, {});
349
+ return `(${Object.entries(tally).map(([key, count]) => `${key}×${count}`).join(' · ')})`;
350
+ };
117
351
  for (const decision of parsed.slice(0, 20)) {
118
- const valid = validateDecision(decision, byId);
352
+ const valid = validateDecision(decision, byId, protect);
119
353
  if (!valid.ok) { rejected.push({ decision, reason: valid.reason }); continue; }
120
354
  decisions.push(valid);
121
355
  }
122
356
  if (dryRun) {
123
- const status = rejected.length ? (decisions.length ? 'degraded' : 'rejected') : 'applied';
124
- const run = record({ scopeId, at, status, model, inputDigest, input, decisions, applied: [], error: rejected.length ? `dry-run; rejected ${rejected.length}` : null });
357
+ // Dry runs are recorded as `preview`, never as `degraded`/`applied`: a
358
+ // rehearsal must not count as "asked" (it would push the batch out of the
359
+ // next real pass) and must not satisfy the idempotence gate.
360
+ const run = record({ scopeId, at, caller, status: 'preview', model: retried ? `${model ?? 'llm'}-retry` : (bounded ? `${model ?? 'llm'}-bounded` : model), inputDigest, input, decisions, applied: [], error: rejected.length ? `dry-run; rejected ${rejected.length}${rejectReason()}` : 'dry-run', groups: duplicateGroups.length, groupsDropped: droppedGroups });
125
361
  return { run, applied: [], decisions, rejected, dryRun: true };
126
362
  }
127
363
 
@@ -154,10 +390,145 @@ export function createConsolidationEngine({ db, traces, summaries = null, audit
154
390
  });
155
391
 
156
392
  const status = rejected.length ? (decisions.length ? 'degraded' : 'rejected') : 'applied';
157
- const run = record({ scopeId, at, status, model, inputDigest, input, decisions, applied, error: rejected.length ? `rejected ${rejected.length}` : null });
393
+ const run = record({ scopeId, at, caller, status, model: retried ? `${model ?? 'llm'}-retry` : (bounded ? `${model ?? 'llm'}-bounded` : model), inputDigest, input, decisions, applied, error: rejected.length ? `rejected ${rejected.length}${rejectReason()}` : null, groups: duplicateGroups.length, groupsDropped: droppedGroups });
158
394
  audit?.record?.({ actor: 'system', action: 'dream.run', targetType: 'dream-run', targetId: run.id, detail: { status, applied: applied.length, rejected: rejected.length, digest: inputDigest } });
159
395
  return { run, applied, decisions, rejected };
160
396
  }
161
397
 
162
- return { run, list, get, parseJsonArray };
398
+
399
+ function shinglesOf(value) {
400
+ const flat = String(value ?? '').replace(/\s+/g, '');
401
+ const set = new Set();
402
+ for (let i = 0; i + 2 <= flat.length; i += 1) set.add(flat.slice(i, i + 2));
403
+ return set;
404
+ }
405
+
406
+ function jaccardOf(a, b) {
407
+ if (a.size === 0 || b.size === 0) return 0;
408
+ let shared = 0;
409
+ for (const gram of a) if (b.has(gram)) shared += 1;
410
+ return shared / (a.size + b.size - shared);
411
+ }
412
+
413
+ /**
414
+ * Deterministic dedupe: merge near-duplicate traces without asking the model.
415
+ * The LLM kept answering "keep" even when it was handed duplicate groups, so the
416
+ * mechanical part of consolidation must not depend on its mood. A protected trace
417
+ * can only ever be the merge target, never a source.
418
+ */
419
+ async function dedupe({ scopeId = 'global', now = Date.now(), limit = 30, threshold = 0.8, dryRun = false, caller = 'unknown', force = false } = {}) {
420
+ const at = nowIso(now);
421
+ const preview = Boolean(dryRun);
422
+ const simThreshold = clampThreshold(threshold);
423
+ // Near-duplicates cluster at the low-importance end ("重复投递不再念" receipts,
424
+ // one-off acknowledgements, fragments), but they are not exclusive to it. Take
425
+ // half from the lowest-importance end and sample the other half evenly across
426
+ // the rest, so a duplicate pair in the middle of the distribution is still seen.
427
+ // The merge target is still chosen by highest importance (most informative copy).
428
+ const pool = traces.list({ scopeId, state: 'active', limit: 500 });
429
+ const count = Math.max(2, Math.min(160, Number(limit) || 30));
430
+ const sortedAsc = pool.slice().sort((a, b) => Number(a.importance) - Number(b.importance) || String(a.recordedAt).localeCompare(String(b.recordedAt)));
431
+ const half = Math.ceil(count / 2);
432
+ const lowHalf = sortedAsc.slice(0, Math.min(half, sortedAsc.length));
433
+ const rest = sortedAsc.slice(lowHalf.length);
434
+ const sampled = [];
435
+ const remaining = Math.min(count - lowHalf.length, rest.length);
436
+ if (remaining > 0) {
437
+ const stride = rest.length / remaining;
438
+ for (let index = 0; index < remaining; index += 1) {
439
+ sampled.push(rest[Math.min(rest.length - 1, Math.floor(index * stride))]);
440
+ }
441
+ }
442
+ const candidates = [...lowHalf, ...sampled];
443
+ const protect = PROTECTED_LINE;
444
+ // A reflection is a synthesis, not a duplicate: it never takes part in dedupe.
445
+ const dedupePool = candidates.filter((trace) => trace.kind !== 'reflection');
446
+ const grams = new Map(dedupePool.map((trace) => [trace.id, shinglesOf(`${trace.title ?? ''}${trace.content ?? ''}`)]));
447
+ const parent = new Map(dedupePool.map((trace) => [trace.id, trace.id]));
448
+ const find = (id) => {
449
+ const next = parent.get(id);
450
+ if (!next || next === id) return id;
451
+ const root = find(next);
452
+ parent.set(id, root);
453
+ return root;
454
+ };
455
+ for (let i = 0; i < dedupePool.length; i += 1) {
456
+ for (let j = i + 1; j < dedupePool.length; j += 1) {
457
+ if (jaccardOf(grams.get(dedupePool[i].id), grams.get(dedupePool[j].id)) >= simThreshold) {
458
+ parent.set(find(dedupePool[j].id), find(dedupePool[i].id));
459
+ }
460
+ }
461
+ }
462
+ const clusters = new Map();
463
+ for (const trace of dedupePool) {
464
+ const root = find(trace.id);
465
+ const bucket = clusters.get(root) ?? [];
466
+ bucket.push(trace);
467
+ clusters.set(root, bucket);
468
+ }
469
+ const decisions = [];
470
+ let droppedGroups = 0;
471
+ for (const group of clusters.values()) {
472
+ if (group.length < 2) continue;
473
+ // A production store has 75% of active traces at importance >= 0.95, so "two protected
474
+ // members" is the normal case, not the exception. Dedupe has already proved the
475
+ // members are near-duplicates (Jaccard >= simThreshold), so keeping N copies buys
476
+ // nothing; reflections were excluded from the pool above.
477
+ const target = [...group].sort((a, b) => Number(b.importance) - Number(a.importance) || String(b.content ?? '').length - String(a.content ?? '').length)[0];
478
+ // Union-find is transitive: A~B and B~C can pull in an A that is not similar to
479
+ // C at all. Only merge members that are near-duplicates *of the target*.
480
+ const members = group.filter((trace) => trace.id === target.id || jaccardOf(grams.get(trace.id), grams.get(target.id)) >= simThreshold);
481
+ if (members.length < 2) {
482
+ droppedGroups += 1;
483
+ continue;
484
+ }
485
+ const ids = [target.id, ...members.filter((trace) => trace.id !== target.id).map((trace) => trace.id)];
486
+ const valid = validateDecision({ action: 'merge', ids, targetId: target.id, reason: 'dedupe' }, new Map(candidates.map((trace) => [trace.id, trace])), protect, { allowProtectedMerge: true });
487
+ if (!valid.ok) {
488
+ droppedGroups += 1;
489
+ continue;
490
+ }
491
+ decisions.push(valid);
492
+ }
493
+
494
+ const inputDigest = digest(`dedupe:${JSON.stringify(decisions.map((decision) => decision.ids))}`);
495
+ // Same idempotence gate as run(), with the same rule: a preview row is a
496
+ // rehearsal and must not block the real pass on the identical decision set.
497
+ if (!force) {
498
+ const previous = db.prepare("SELECT id, input_digest FROM dream_runs WHERE scope_id = ? AND model = 'dedupe' AND status != 'preview' ORDER BY at DESC LIMIT 1").get(scopeId);
499
+ if (previous && previous.input_digest === inputDigest) {
500
+ return { run: { ...get(previous.id), groups: decisions.length, groupsDropped: droppedGroups }, applied: [], decisions, dryRun: preview, skipped: 'unchanged' };
501
+ }
502
+ }
503
+ const applied = [];
504
+ if (!preview && decisions.length) {
505
+ transaction(db, () => {
506
+ for (const decision of decisions) {
507
+ const losers = decision.ids.filter((id) => id !== decision.targetId);
508
+ for (const id of losers) {
509
+ traces.update(id, { state: 'archived', compression: 'merged' });
510
+ applied.push({ action: 'merge', id, targetId: decision.targetId });
511
+ }
512
+ if (summaries && losers.length) {
513
+ try {
514
+ summaries.insert({
515
+ scopeId, level: 'merge', content: `去重合并 ${losers.length} 条到 ${decision.targetId}${losers.length ? `(含:${losers.map((id) => String(candidates.find((trace) => trace.id === id)?.title ?? id).slice(0, 40)).join(' / ')})` : ''}`,
516
+ sourceIds: [...decision.ids], coverage: 1, model: 'dedupe',
517
+ });
518
+ } catch { /* provenance is best effort */ }
519
+ }
520
+ }
521
+ });
522
+ }
523
+
524
+ const run = record({
525
+ scopeId, at, caller, status: dryRun ? 'preview' : (applied.length ? 'applied' : 'skipped'),
526
+ model: 'dedupe', inputDigest, input: candidates.map((trace) => ({ id: trace.id, title: trace.title })),
527
+ decisions, applied, error: null,
528
+ groups: decisions.length, groupsDropped: droppedGroups,
529
+ });
530
+ return { run, applied, decisions, dryRun: preview };
531
+ }
532
+
533
+ return { run, dedupe, list, get, parseJsonArray };
163
534
  }
@@ -19,6 +19,15 @@ const EMOTION_VALENCE = [
19
19
 
20
20
  const STOP_PHRASES = new Set(['嗯', '好', '好的', '谢谢', '在吗', '收到', 'ok', 'okay']);
21
21
 
22
+ // Second line of defense: capture paths that bypass the host runtime must not
23
+ // store raw host-injected context. Only a strong marker at the very start
24
+ // counts, so a user talking *about* these markers is still stored.
25
+ const INJECTED_HEAD = /^(?:Time sampled|Elapsed since the preceding|Current runtime context\.|Browser time zone for this request:|<system-reminder>|<goal_round>|<goal_complete|\[SCHEDULE REMINDER|This is a scheduled message from the user|reminders_json:|Objective:\s*")/i;
26
+
27
+ export function isInjectedNoise(value) {
28
+ return INJECTED_HEAD.test(String(value ?? '').trimStart().slice(0, 160));
29
+ }
30
+
22
31
  export function scoreTraceText(text, { kind = null, importance = null } = {}) {
23
32
  const value = String(text ?? '').trim();
24
33
  let importanceScore = Number.isFinite(importance) ? clamp(importance, 0, 1) : 0.42;
@@ -125,9 +134,13 @@ export function createEncodeEngine({
125
134
  function encode(input = {}) {
126
135
  const original = String(input.text ?? input.content ?? '').trim();
127
136
  const scanned = scanText(original);
128
- const text = scanned.text.trim();
137
+ let text = scanned.text.trim();
129
138
  if (text.length < minChars) return { skipped: true, reason: 'too-short' };
130
139
  if (STOP_PHRASES.has(text.toLowerCase())) return { skipped: true, reason: 'stop-phrase' };
140
+ if (!input.explicit && isInjectedNoise(text)) return { skipped: true, reason: 'injected-context' };
141
+ const maxChars = Math.max(500, Number(config.maxContentChars) || 8000);
142
+ const truncated = text.length > maxChars;
143
+ if (truncated) text = `${text.slice(0, maxChars)} [truncated]`;
131
144
  const sensitivity = scanned.hasSecret ? 'secret' : (input.sensitivity || 'personal');
132
145
  const scopeId = input.scopeId || 'global';
133
146
  const now = input.now || Date.now();
@@ -208,7 +221,7 @@ export function createEncodeEngine({
208
221
  action: 'trace.create',
209
222
  targetType: 'trace',
210
223
  targetId: trace.id,
211
- detail: { eventId: event.id, kind: trace.kind, compression, findings: scanned.findings.map((item) => ({ type: item.type, rule: item.rule, severity: item.severity })) },
224
+ detail: { eventId: event.id, kind: trace.kind, compression, truncated, findings: scanned.findings.map((item) => ({ type: item.type, rule: item.rule, severity: item.severity })) },
212
225
  });
213
226
 
214
227
  for (const resolution of resolvedFacts) {
@@ -230,7 +243,7 @@ export function createEncodeEngine({
230
243
  }
231
244
  }
232
245
 
233
- return { skipped: false, event, trace, facts: resolvedFacts, edgeCandidates, compression, score: scored };
246
+ return { skipped: false, event, trace, facts: resolvedFacts, edgeCandidates, compression, score: scored, truncated };
234
247
  }
235
248
 
236
249
  return { encode, scoreTraceText, compressionValue };