@kernel.chat/kbot 3.8.2 → 3.10.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-synthesis.d.ts","sourceRoot":"","sources":["../src/memory-synthesis.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,eAAe,GACvB,cAAc,GACd,iBAAiB,GACjB,iBAAiB,GACjB,kBAAkB,GAClB,UAAU,GACV,aAAa,CAAA;AAEjB,MAAM,WAAW,OAAO;IACtB,sDAAsD;IACtD,IAAI,EAAE,MAAM,CAAA;IACZ,wBAAwB;IACxB,QAAQ,EAAE,eAAe,CAAA;IACzB,sDAAsD;IACtD,UAAU,EAAE,MAAM,CAAA;IAClB,qDAAqD;IACrD,eAAe,EAAE,MAAM,CAAA;IACvB,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,OAAO,EAAE,CAAA;IACnB,0CAA0C;IAC1C,aAAa,EAAE,MAAM,CAAA;IACrB,+DAA+D;IAC/D,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAqED;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAS1C;AAMD;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,IAAI,eAAe,CAwXlD;AAMD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,QAAQ,CAAC,EAAE,eAAe,EAAE,GAAG,GAAE,MAAW,GAAG,OAAO,EAAE,CAWnF;AAMD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAWnE;AAMD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,GAAE,MAAU,GAAG,MAAM,CASnE;AAMD;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,MAAM,CAIxC;AAMD;;GAEG;AACH,wBAAgB,iBAAiB,IAAI;IACnC,YAAY,EAAE,MAAM,CAAA;IACpB,eAAe,EAAE,MAAM,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,EAAE,MAAM,EAAE,CAAA;CACtB,CAUA"}
@@ -0,0 +1,557 @@
1
+ // kbot Memory Synthesis — Three-Tier Generative Memory
2
+ //
3
+ // Inspired by Stanford's "Generative Agents" paper (Park et al., 2023).
4
+ //
5
+ // Three tiers of memory:
6
+ // 1. OBSERVATIONS — Raw facts from interactions (patterns, solutions, knowledge in learning.ts)
7
+ // 2. REFLECTIONS — Periodic synthesis of observations into higher-level insights (THIS FILE)
8
+ // 3. IDENTITY — Long-term personality and preference evolution (temporal.ts)
9
+ //
10
+ // The Reflection tier runs a scheduled synthesis pass that reads all raw memory
11
+ // files, groups observations by theme, and produces higher-order insights using
12
+ // pure frequency analysis and pattern matching — no LLM calls required.
13
+ //
14
+ // Storage: ~/.kbot/memory/synthesis.json
15
+ // Max 50 insights, ranked by confidence.
16
+ import { homedir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
19
+ // ══════════════════════════════════════════════════════════════════════
20
+ // Constants & Paths
21
+ // ══════════════════════════════════════════════════════════════════════
22
+ const LEARN_DIR = join(homedir(), '.kbot', 'memory');
23
+ const SYNTHESIS_FILE = join(LEARN_DIR, 'synthesis.json');
24
+ const PATTERNS_FILE = join(LEARN_DIR, 'patterns.json');
25
+ const SOLUTIONS_FILE = join(LEARN_DIR, 'solutions.json');
26
+ const PROFILE_FILE = join(LEARN_DIR, 'profile.json');
27
+ const KNOWLEDGE_FILE = join(LEARN_DIR, 'knowledge.json');
28
+ const CORRECTIONS_FILE = join(LEARN_DIR, 'corrections.json');
29
+ const PROJECTS_FILE = join(LEARN_DIR, 'projects.json');
30
+ const TECH_FREQ_FILE = join(LEARN_DIR, 'tech-freq.json');
31
+ const MAX_INSIGHTS = 50;
32
+ /** Minimum raw observations before synthesis is worthwhile */
33
+ const MIN_OBSERVATIONS_FOR_SYNTHESIS = 20;
34
+ // ══════════════════════════════════════════════════════════════════════
35
+ // Helpers
36
+ // ══════════════════════════════════════════════════════════════════════
37
+ function ensureDir() {
38
+ if (!existsSync(LEARN_DIR))
39
+ mkdirSync(LEARN_DIR, { recursive: true });
40
+ }
41
+ function loadJSON(path, fallback) {
42
+ if (!existsSync(path))
43
+ return fallback;
44
+ try {
45
+ return JSON.parse(readFileSync(path, 'utf-8'));
46
+ }
47
+ catch {
48
+ return fallback;
49
+ }
50
+ }
51
+ function saveJSON(path, data) {
52
+ ensureDir();
53
+ writeFileSync(path, JSON.stringify(data, null, 2));
54
+ }
55
+ /** Load the current synthesis state from disk */
56
+ function loadSynthesis() {
57
+ return loadJSON(SYNTHESIS_FILE, {
58
+ insights: [],
59
+ synthesizedAt: '',
60
+ observationCount: 0,
61
+ });
62
+ }
63
+ /** Persist synthesis state to disk */
64
+ function saveSynthesis(synthesis) {
65
+ saveJSON(SYNTHESIS_FILE, synthesis);
66
+ }
67
+ // ══════════════════════════════════════════════════════════════════════
68
+ // Observation Counting
69
+ // ══════════════════════════════════════════════════════════════════════
70
+ /** Count total raw observations across all memory files */
71
+ function countObservations() {
72
+ const patterns = loadJSON(PATTERNS_FILE, []);
73
+ const solutions = loadJSON(SOLUTIONS_FILE, []);
74
+ const knowledge = loadJSON(KNOWLEDGE_FILE, []);
75
+ const corrections = loadJSON(CORRECTIONS_FILE, []);
76
+ return patterns.length + solutions.length + knowledge.length + corrections.length;
77
+ }
78
+ // ══════════════════════════════════════════════════════════════════════
79
+ // Core: shouldSynthesize()
80
+ // ══════════════════════════════════════════════════════════════════════
81
+ /**
82
+ * Returns true if there are enough new observations since the last
83
+ * synthesis to justify another pass (>20 new observations).
84
+ */
85
+ export function shouldSynthesize() {
86
+ const current = countObservations();
87
+ if (current < MIN_OBSERVATIONS_FOR_SYNTHESIS)
88
+ return false;
89
+ const synthesis = loadSynthesis();
90
+ if (!synthesis.synthesizedAt)
91
+ return true; // never synthesized
92
+ const newObservations = current - synthesis.observationCount;
93
+ return newObservations >= MIN_OBSERVATIONS_FOR_SYNTHESIS;
94
+ }
95
+ // ══════════════════════════════════════════════════════════════════════
96
+ // Core: synthesizeMemory()
97
+ // ══════════════════════════════════════════════════════════════════════
98
+ /**
99
+ * Run the full synthesis pass.
100
+ *
101
+ * Reads all memory files, performs frequency analysis and pattern matching,
102
+ * and produces higher-order insights. No LLM calls — pure statistics.
103
+ *
104
+ * Returns the updated MemorySynthesis.
105
+ */
106
+ export function synthesizeMemory() {
107
+ const patterns = loadJSON(PATTERNS_FILE, []);
108
+ const solutions = loadJSON(SOLUTIONS_FILE, []);
109
+ const profile = loadJSON(PROFILE_FILE, {
110
+ responseStyle: 'auto', techStack: [], taskPatterns: {},
111
+ preferredAgents: {}, totalMessages: 0, totalTokens: 0,
112
+ tokensSaved: 0, avgTokensPerMessage: 0, sessions: 0,
113
+ });
114
+ const knowledge = loadJSON(KNOWLEDGE_FILE, []);
115
+ const corrections = loadJSON(CORRECTIONS_FILE, []);
116
+ const projects = loadJSON(PROJECTS_FILE, []);
117
+ const techFreq = loadJSON(TECH_FREQ_FILE, {});
118
+ const insights = [];
119
+ const now = new Date().toISOString();
120
+ // ── 1. Tool preference analysis ─────────────────────────────────
121
+ const toolCounts = {};
122
+ for (const p of patterns) {
123
+ for (const tool of p.toolSequence) {
124
+ toolCounts[tool] = (toolCounts[tool] || 0) + p.hits;
125
+ }
126
+ }
127
+ const sortedTools = Object.entries(toolCounts).sort((a, b) => b[1] - a[1]);
128
+ if (sortedTools.length >= 2) {
129
+ const top3 = sortedTools.slice(0, 3);
130
+ const totalHits = sortedTools.reduce((sum, [, n]) => sum + n, 0);
131
+ insights.push({
132
+ text: `Most-used tools: ${top3.map(([t, n]) => `${t} (${n}x)`).join(', ')}`,
133
+ category: 'tool_preference',
134
+ confidence: clampConfidence(totalHits, 10, 100),
135
+ supportingCount: totalHits,
136
+ created: now,
137
+ });
138
+ }
139
+ // Tool pair analysis — find common two-step sequences
140
+ const pairCounts = {};
141
+ for (const p of patterns) {
142
+ for (let i = 0; i < p.toolSequence.length - 1; i++) {
143
+ const pair = `${p.toolSequence[i]} -> ${p.toolSequence[i + 1]}`;
144
+ pairCounts[pair] = (pairCounts[pair] || 0) + p.hits;
145
+ }
146
+ }
147
+ const sortedPairs = Object.entries(pairCounts).sort((a, b) => b[1] - a[1]);
148
+ if (sortedPairs.length >= 1) {
149
+ const topPair = sortedPairs[0];
150
+ if (topPair[1] >= 3) {
151
+ // Compare with other pairs to generate comparative insight
152
+ const secondPair = sortedPairs.length > 1 ? sortedPairs[1] : null;
153
+ let text = `Most common tool sequence: ${topPair[0]} (${topPair[1]}x)`;
154
+ if (secondPair && topPair[1] > secondPair[1] * 2) {
155
+ text = `Tool sequence "${topPair[0]}" is ${Math.round(topPair[1] / secondPair[1])}x more common than "${secondPair[0]}"`;
156
+ }
157
+ insights.push({
158
+ text,
159
+ category: 'workflow',
160
+ confidence: clampConfidence(topPair[1], 3, 30),
161
+ supportingCount: topPair[1],
162
+ created: now,
163
+ });
164
+ }
165
+ }
166
+ // ── 2. Agent routing analysis ──────────────────────────────────
167
+ const agentEntries = Object.entries(profile.preferredAgents);
168
+ if (agentEntries.length >= 1) {
169
+ const sorted = agentEntries.sort((a, b) => b[1] - a[1]);
170
+ const totalRoutes = sorted.reduce((sum, [, n]) => sum + n, 0);
171
+ // Top agent
172
+ const [topAgent, topCount] = sorted[0];
173
+ const pct = Math.round((topCount / totalRoutes) * 100);
174
+ insights.push({
175
+ text: `The ${topAgent} agent handles ${pct}% of tasks (${topCount}/${totalRoutes})`,
176
+ category: 'agent_preference',
177
+ confidence: clampConfidence(totalRoutes, 10, 100),
178
+ supportingCount: totalRoutes,
179
+ created: now,
180
+ });
181
+ // If there is a clear second agent, mention the distribution
182
+ if (sorted.length >= 2) {
183
+ const [secondAgent, secondCount] = sorted[1];
184
+ const secondPct = Math.round((secondCount / totalRoutes) * 100);
185
+ if (secondPct >= 10) {
186
+ insights.push({
187
+ text: `Agent distribution: ${topAgent} ${pct}%, ${secondAgent} ${secondPct}%${sorted.length > 2 ? `, ${sorted.length - 2} others ${100 - pct - secondPct}%` : ''}`,
188
+ category: 'agent_preference',
189
+ confidence: clampConfidence(totalRoutes, 15, 100),
190
+ supportingCount: totalRoutes,
191
+ created: now,
192
+ });
193
+ }
194
+ }
195
+ }
196
+ // ── 3. Tech stack / coding style analysis ──────────────────────
197
+ const techEntries = Object.entries(techFreq).sort((a, b) => b[1] - a[1]);
198
+ if (techEntries.length >= 2) {
199
+ const totalTechMentions = techEntries.reduce((sum, [, n]) => sum + n, 0);
200
+ const top5 = techEntries.slice(0, 5);
201
+ // Detect dominant language/framework
202
+ const [topTech, topTechCount] = top5[0];
203
+ const topPct = Math.round((topTechCount / totalTechMentions) * 100);
204
+ if (topPct >= 30) {
205
+ insights.push({
206
+ text: `This user works primarily in ${topTech} (${topPct}% of tech mentions)`,
207
+ category: 'coding_style',
208
+ confidence: clampConfidence(topTechCount, 5, 50),
209
+ supportingCount: topTechCount,
210
+ created: now,
211
+ });
212
+ }
213
+ // Detect stack combinations
214
+ if (top5.length >= 2) {
215
+ const stackStr = top5.map(([t]) => t).join(' + ');
216
+ insights.push({
217
+ text: `Primary tech stack: ${stackStr}`,
218
+ category: 'project_pattern',
219
+ confidence: clampConfidence(totalTechMentions, 10, 80),
220
+ supportingCount: totalTechMentions,
221
+ created: now,
222
+ });
223
+ }
224
+ // Detect paradigm preferences from tech terms
225
+ const functionalTerms = ['functional', 'map', 'reduce', 'filter', 'pipe', 'compose', 'immutable', 'pure'];
226
+ const oopTerms = ['class', 'interface', 'extends', 'inherit', 'abstract', 'override', 'polymorphism'];
227
+ const functionalScore = techEntries.filter(([t]) => functionalTerms.includes(t)).reduce((s, [, n]) => s + n, 0);
228
+ const oopScore = techEntries.filter(([t]) => oopTerms.includes(t)).reduce((s, [, n]) => s + n, 0);
229
+ if (functionalScore > 0 || oopScore > 0) {
230
+ if (functionalScore > oopScore * 2 && functionalScore >= 3) {
231
+ insights.push({
232
+ text: 'This user prefers functional programming style over OOP',
233
+ category: 'coding_style',
234
+ confidence: clampConfidence(functionalScore, 3, 20),
235
+ supportingCount: functionalScore,
236
+ created: now,
237
+ });
238
+ }
239
+ else if (oopScore > functionalScore * 2 && oopScore >= 3) {
240
+ insights.push({
241
+ text: 'This user prefers object-oriented programming style',
242
+ category: 'coding_style',
243
+ confidence: clampConfidence(oopScore, 3, 20),
244
+ supportingCount: oopScore,
245
+ created: now,
246
+ });
247
+ }
248
+ }
249
+ }
250
+ // ── 4. Task type analysis ──────────────────────────────────────
251
+ const taskEntries = Object.entries(profile.taskPatterns).sort((a, b) => b[1] - a[1]);
252
+ if (taskEntries.length >= 1) {
253
+ const totalTasks = taskEntries.reduce((sum, [, n]) => sum + n, 0);
254
+ // Dominant task type
255
+ const [topTask, topTaskCount] = taskEntries[0];
256
+ const taskPct = Math.round((topTaskCount / totalTasks) * 100);
257
+ insights.push({
258
+ text: `${taskPct}% of tasks are "${topTask}" (${topTaskCount}/${totalTasks})`,
259
+ category: 'workflow',
260
+ confidence: clampConfidence(totalTasks, 10, 100),
261
+ supportingCount: totalTasks,
262
+ created: now,
263
+ });
264
+ // Task diversity
265
+ if (taskEntries.length >= 3) {
266
+ const distribution = taskEntries.slice(0, 4)
267
+ .map(([t, n]) => `${t} ${Math.round((n / totalTasks) * 100)}%`)
268
+ .join(', ');
269
+ insights.push({
270
+ text: `Task distribution: ${distribution}`,
271
+ category: 'workflow',
272
+ confidence: clampConfidence(totalTasks, 15, 100),
273
+ supportingCount: totalTasks,
274
+ created: now,
275
+ });
276
+ }
277
+ }
278
+ // ── 5. Correction pattern analysis ─────────────────────────────
279
+ if (corrections.length >= 2) {
280
+ // Look for recurring correction themes
281
+ const correctionWords = {};
282
+ for (const c of corrections) {
283
+ const words = c.userMessage.toLowerCase()
284
+ .replace(/[^a-z0-9\s]/g, ' ')
285
+ .split(/\s+/)
286
+ .filter(w => w.length > 3);
287
+ for (const w of words) {
288
+ correctionWords[w] = (correctionWords[w] || 0) + c.occurrences;
289
+ }
290
+ }
291
+ const topCorrectionWords = Object.entries(correctionWords)
292
+ .sort((a, b) => b[1] - a[1])
293
+ .slice(0, 3)
294
+ .filter(([, n]) => n >= 2);
295
+ if (topCorrectionWords.length > 0) {
296
+ const themes = topCorrectionWords.map(([w]) => w).join(', ');
297
+ insights.push({
298
+ text: `Common correction themes: ${themes} (user frequently corrects on these topics)`,
299
+ category: 'personality',
300
+ confidence: clampConfidence(corrections.length, 2, 15),
301
+ supportingCount: corrections.length,
302
+ created: now,
303
+ });
304
+ }
305
+ // Response style preference from corrections
306
+ const conciseCorrections = corrections.filter(c => /(?:too\s+(?:long|verbose|detailed)|shorter|brief|tldr|concise)/i.test(c.userMessage));
307
+ const detailedCorrections = corrections.filter(c => /(?:more\s+detail|elaborate|explain|too\s+short|too\s+brief)/i.test(c.userMessage));
308
+ if (conciseCorrections.length > detailedCorrections.length && conciseCorrections.length >= 2) {
309
+ insights.push({
310
+ text: 'This user prefers concise responses (corrected for verbosity multiple times)',
311
+ category: 'personality',
312
+ confidence: clampConfidence(conciseCorrections.length, 2, 10),
313
+ supportingCount: conciseCorrections.length,
314
+ created: now,
315
+ });
316
+ }
317
+ else if (detailedCorrections.length > conciseCorrections.length && detailedCorrections.length >= 2) {
318
+ insights.push({
319
+ text: 'This user prefers detailed, thorough responses',
320
+ category: 'personality',
321
+ confidence: clampConfidence(detailedCorrections.length, 2, 10),
322
+ supportingCount: detailedCorrections.length,
323
+ created: now,
324
+ });
325
+ }
326
+ }
327
+ // ── 6. Project pattern analysis ────────────────────────────────
328
+ if (projects.length >= 1) {
329
+ // Detect common project stacks
330
+ const stackCounts = {};
331
+ for (const p of projects) {
332
+ for (const s of p.stack) {
333
+ stackCounts[s] = (stackCounts[s] || 0) + 1;
334
+ }
335
+ }
336
+ const commonStack = Object.entries(stackCounts)
337
+ .sort((a, b) => b[1] - a[1])
338
+ .slice(0, 5);
339
+ if (commonStack.length >= 2 && projects.length >= 2) {
340
+ const stackStr = commonStack.map(([s]) => s).join(' + ');
341
+ insights.push({
342
+ text: `Projects are mostly ${stackStr} (across ${projects.length} projects)`,
343
+ category: 'project_pattern',
344
+ confidence: clampConfidence(projects.length, 2, 10),
345
+ supportingCount: projects.length,
346
+ created: now,
347
+ });
348
+ }
349
+ // Detect frequently edited files across projects
350
+ const globalFiles = {};
351
+ for (const p of projects) {
352
+ for (const [file, count] of Object.entries(p.frequentFiles)) {
353
+ // Use just the filename, not full path, for cross-project matching
354
+ const basename = file.split('/').pop() || file;
355
+ globalFiles[basename] = (globalFiles[basename] || 0) + count;
356
+ }
357
+ }
358
+ const hotFiles = Object.entries(globalFiles)
359
+ .sort((a, b) => b[1] - a[1])
360
+ .slice(0, 5)
361
+ .filter(([, n]) => n >= 3);
362
+ if (hotFiles.length > 0) {
363
+ insights.push({
364
+ text: `Most frequently edited files: ${hotFiles.map(([f, n]) => `${f} (${n}x)`).join(', ')}`,
365
+ category: 'project_pattern',
366
+ confidence: clampConfidence(hotFiles[0][1], 3, 20),
367
+ supportingCount: hotFiles.reduce((s, [, n]) => s + n, 0),
368
+ created: now,
369
+ });
370
+ }
371
+ }
372
+ // ── 7. Knowledge base theme analysis ───────────────────────────
373
+ if (knowledge.length >= 3) {
374
+ const categoryCounts = {};
375
+ for (const k of knowledge) {
376
+ categoryCounts[k.category] = (categoryCounts[k.category] || 0) + 1;
377
+ }
378
+ const topCategory = Object.entries(categoryCounts).sort((a, b) => b[1] - a[1])[0];
379
+ if (topCategory && topCategory[1] >= 3) {
380
+ insights.push({
381
+ text: `Most knowledge entries are "${topCategory[0]}" type (${topCategory[1]}/${knowledge.length})`,
382
+ category: 'personality',
383
+ confidence: clampConfidence(knowledge.length, 3, 30),
384
+ supportingCount: knowledge.length,
385
+ created: now,
386
+ });
387
+ }
388
+ // User-taught vs extracted ratio
389
+ const taughtCount = knowledge.filter(k => k.source === 'user-taught').length;
390
+ const extractedCount = knowledge.filter(k => k.source === 'extracted' || k.source === 'observed').length;
391
+ if (taughtCount > extractedCount * 2 && taughtCount >= 3) {
392
+ insights.push({
393
+ text: 'This user actively teaches kbot (more user-taught than auto-extracted knowledge)',
394
+ category: 'personality',
395
+ confidence: clampConfidence(taughtCount, 3, 15),
396
+ supportingCount: taughtCount,
397
+ created: now,
398
+ });
399
+ }
400
+ }
401
+ // ── 8. Efficiency trend analysis ───────────────────────────────
402
+ if (profile.totalMessages > 20 && profile.avgTokensPerMessage > 0) {
403
+ const baseline = 2000;
404
+ if (profile.avgTokensPerMessage < baseline * 0.7) {
405
+ const effPct = Math.round((1 - profile.avgTokensPerMessage / baseline) * 100);
406
+ insights.push({
407
+ text: `Token efficiency is ${effPct}% above baseline (${Math.round(profile.avgTokensPerMessage)} avg vs ${baseline} baseline)`,
408
+ category: 'workflow',
409
+ confidence: clampConfidence(profile.totalMessages, 20, 200),
410
+ supportingCount: profile.totalMessages,
411
+ created: now,
412
+ });
413
+ }
414
+ }
415
+ // ── 9. Solution reuse analysis ─────────────────────────────────
416
+ const highReuseSolutions = solutions.filter(s => s.reuses >= 2);
417
+ if (highReuseSolutions.length >= 2) {
418
+ // Extract common keywords from highly-reused solutions
419
+ const solutionKeywords = {};
420
+ for (const s of highReuseSolutions) {
421
+ for (const kw of s.keywords) {
422
+ solutionKeywords[kw] = (solutionKeywords[kw] || 0) + s.reuses;
423
+ }
424
+ }
425
+ const topSolKw = Object.entries(solutionKeywords)
426
+ .sort((a, b) => b[1] - a[1])
427
+ .slice(0, 3);
428
+ if (topSolKw.length > 0) {
429
+ insights.push({
430
+ text: `Most reused solution topics: ${topSolKw.map(([k, n]) => `${k} (${n} reuses)`).join(', ')}`,
431
+ category: 'workflow',
432
+ confidence: clampConfidence(highReuseSolutions.length, 2, 20),
433
+ supportingCount: highReuseSolutions.reduce((s, sol) => s + sol.reuses, 0),
434
+ created: now,
435
+ });
436
+ }
437
+ }
438
+ // ── Finalize ───────────────────────────────────────────────────
439
+ // Sort by confidence descending, cap at MAX_INSIGHTS
440
+ insights.sort((a, b) => b.confidence - a.confidence);
441
+ const finalInsights = insights.slice(0, MAX_INSIGHTS);
442
+ const observationCount = countObservations();
443
+ const synthesis = {
444
+ insights: finalInsights,
445
+ synthesizedAt: now,
446
+ observationCount,
447
+ };
448
+ saveSynthesis(synthesis);
449
+ return synthesis;
450
+ }
451
+ // ══════════════════════════════════════════════════════════════════════
452
+ // Core: getInsights()
453
+ // ══════════════════════════════════════════════════════════════════════
454
+ /**
455
+ * Retrieve synthesized insights, optionally filtered by category.
456
+ * Returns up to `max` insights sorted by confidence.
457
+ */
458
+ export function getInsights(category, max = 10) {
459
+ const synthesis = loadSynthesis();
460
+ let results = synthesis.insights;
461
+ if (category) {
462
+ results = results.filter(i => i.category === category);
463
+ }
464
+ return results
465
+ .sort((a, b) => b.confidence - a.confidence)
466
+ .slice(0, max);
467
+ }
468
+ // ══════════════════════════════════════════════════════════════════════
469
+ // Core: formatInsightsForPrompt()
470
+ // ══════════════════════════════════════════════════════════════════════
471
+ /**
472
+ * Format insights for injection into the system prompt.
473
+ * Produces a compact, readable block that gives the agent
474
+ * deeper self-awareness about the user.
475
+ */
476
+ export function formatInsightsForPrompt(insights) {
477
+ if (insights.length === 0)
478
+ return '';
479
+ const lines = ['[Synthesized User Insights]'];
480
+ for (const insight of insights) {
481
+ const conf = Math.round(insight.confidence * 100);
482
+ lines.push(`- ${insight.text} (${conf}% confidence)`);
483
+ }
484
+ return lines.join('\n');
485
+ }
486
+ // ══════════════════════════════════════════════════════════════════════
487
+ // Integration: getSynthesisContext()
488
+ // ══════════════════════════════════════════════════════════════════════
489
+ /**
490
+ * Convenience function for the agent loop.
491
+ * Returns formatted top insights ready for system prompt injection,
492
+ * or empty string if no synthesis data exists.
493
+ */
494
+ export function getSynthesisContext(maxInsights = 8) {
495
+ const synthesis = loadSynthesis();
496
+ if (synthesis.insights.length === 0)
497
+ return '';
498
+ const top = synthesis.insights
499
+ .sort((a, b) => b.confidence - a.confidence)
500
+ .slice(0, maxInsights);
501
+ return formatInsightsForPrompt(top);
502
+ }
503
+ // ══════════════════════════════════════════════════════════════════════
504
+ // Integration: maybeSynthesize()
505
+ // ══════════════════════════════════════════════════════════════════════
506
+ /**
507
+ * Check-and-run: if synthesis is due, run it and return the count
508
+ * of new insights produced. Otherwise return 0.
509
+ * Safe to call on every session start — it is a no-op when not needed.
510
+ */
511
+ export function maybeSynthesize() {
512
+ if (!shouldSynthesize())
513
+ return 0;
514
+ const result = synthesizeMemory();
515
+ return result.insights.length;
516
+ }
517
+ // ══════════════════════════════════════════════════════════════════════
518
+ // Stats
519
+ // ══════════════════════════════════════════════════════════════════════
520
+ /**
521
+ * Get synthesis stats for display in `kbot stats` or diagnostics.
522
+ */
523
+ export function getSynthesisStats() {
524
+ const synthesis = loadSynthesis();
525
+ return {
526
+ insightCount: synthesis.insights.length,
527
+ lastSynthesized: synthesis.synthesizedAt || 'never',
528
+ observationCount: synthesis.observationCount,
529
+ topInsights: synthesis.insights
530
+ .slice(0, 5)
531
+ .map(i => i.text),
532
+ };
533
+ }
534
+ // ══════════════════════════════════════════════════════════════════════
535
+ // Internal helpers
536
+ // ══════════════════════════════════════════════════════════════════════
537
+ /**
538
+ * Map a raw count to a 0-1 confidence score.
539
+ * Uses a logarithmic curve: confidence rises steeply at first,
540
+ * then flattens as count grows beyond `high`.
541
+ *
542
+ * @param count - number of supporting observations
543
+ * @param low - count at which confidence starts being meaningful (~0.4)
544
+ * @param high - count at which confidence saturates (~0.95)
545
+ */
546
+ function clampConfidence(count, low, high) {
547
+ if (count <= 0)
548
+ return 0;
549
+ if (count >= high)
550
+ return 0.95;
551
+ // Logarithmic scaling between low and high
552
+ const normalized = (count - low) / (high - low);
553
+ const clamped = Math.max(0, Math.min(1, normalized));
554
+ // Curve: 0.4 at low end, 0.95 at high end
555
+ return parseFloat((0.4 + clamped * 0.55).toFixed(2));
556
+ }
557
+ //# sourceMappingURL=memory-synthesis.js.map
@@ -0,0 +1 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C,OAAO,CAAC,CAAC,CAAC,CAAC,CAAA;AACtD,CAAC"}
@@ -0,0 +1,33 @@
1
+ export interface Perspective {
2
+ agent: string;
3
+ critique: string;
4
+ }
5
+ export interface Reflection {
6
+ id: string;
7
+ taskMessage: string;
8
+ failureType: 'low_score' | 'error_correction' | 'user_rejection';
9
+ perspectives: Perspective[];
10
+ synthesis: string;
11
+ lesson: string;
12
+ created: string;
13
+ }
14
+ /**
15
+ * Generate reflections from 5 key specialist perspectives.
16
+ * All heuristic-based — no LLM calls.
17
+ */
18
+ export declare function generateReflections(message: string, response: string, failureType: 'low_score' | 'error_correction' | 'user_rejection'): Reflection;
19
+ /**
20
+ * Retrieve past reflections relevant to a given message.
21
+ * Uses keyword overlap to find similar past failures.
22
+ */
23
+ export declare function getRelevantReflections(message: string, max?: number): Reflection[];
24
+ /**
25
+ * Format reflections for injection into the system prompt.
26
+ * Returns an empty string if no reflections exist.
27
+ */
28
+ export declare function formatReflectionsForPrompt(reflections: Reflection[]): string;
29
+ /**
30
+ * Detect if a user message indicates rejection of the previous response.
31
+ */
32
+ export declare function isUserRejection(message: string): boolean;
33
+ //# sourceMappingURL=reflection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reflection.d.ts","sourceRoot":"","sources":["../src/reflection.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,WAAW,EAAE,MAAM,CAAA;IACnB,WAAW,EAAE,WAAW,GAAG,kBAAkB,GAAG,gBAAgB,CAAA;IAChE,YAAY,EAAE,WAAW,EAAE,CAAA;IAC3B,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;CAChB;AAiPD;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,WAAW,GAAG,kBAAkB,GAAG,gBAAgB,GAC/D,UAAU,CA4BZ;AA2BD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,MAAU,GAAG,UAAU,EAAE,CAmCrF;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,WAAW,EAAE,UAAU,EAAE,GAAG,MAAM,CAS5E;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAiCxD"}