@cachly-dev/mcp-server 0.9.19 → 0.9.21
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.
- package/.github/workflows/publish.yml +42 -0
- package/LICENSE +202 -0
- package/dist/handlers/advanced.d.ts +6 -0
- package/dist/handlers/advanced.js +586 -0
- package/dist/handlers/advanced.js.map +1 -0
- package/dist/handlers/cache.d.ts +6 -0
- package/dist/handlers/cache.js +520 -0
- package/dist/handlers/cache.js.map +1 -0
- package/dist/handlers/context.d.ts +6 -0
- package/dist/handlers/context.js +177 -0
- package/dist/handlers/context.js.map +1 -0
- package/dist/handlers/fedbrain.d.ts +6 -0
- package/dist/handlers/fedbrain.js +1078 -0
- package/dist/handlers/fedbrain.js.map +1 -0
- package/dist/handlers/instances.d.ts +9 -0
- package/dist/handlers/instances.js +153 -0
- package/dist/handlers/instances.js.map +1 -0
- package/dist/handlers/roadmap.d.ts +6 -0
- package/dist/handlers/roadmap.js +165 -0
- package/dist/handlers/roadmap.js.map +1 -0
- package/dist/handlers/syndicate.d.ts +6 -0
- package/dist/handlers/syndicate.js +339 -0
- package/dist/handlers/syndicate.js.map +1 -0
- package/dist/handlers/team.d.ts +6 -0
- package/dist/handlers/team.js +1048 -0
- package/dist/handlers/team.js.map +1 -0
- package/dist/index.js +38 -4018
- package/dist/index.js.map +1 -1
- package/glama.json +6 -0
- package/package.json +1 -1
- package/src/handlers/advanced.ts +637 -0
- package/src/handlers/cache.ts +634 -0
- package/src/handlers/context.ts +218 -0
- package/src/handlers/fedbrain.ts +1143 -0
- package/src/handlers/instances.ts +180 -0
- package/src/handlers/roadmap.ts +192 -0
- package/src/handlers/syndicate.ts +451 -0
- package/src/handlers/team.ts +1163 -0
- package/src/index.ts +44 -4465
package/glama.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cachly-dev/mcp-server",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.21",
|
|
4
4
|
"mcpName": "io.github.cachly-dev/cachly-mcp",
|
|
5
5
|
"description": "Your AI forgets everything between sessions. cachly fixes that permanently. A causal brain that learns WHY things break — built from every bug fix, git commit, and CI run, without any explicit calls. Arrives pre-briefed each session. Predicts failures before they happen. Never re-researches the same problem. 63 MCP tools · Claude Code · Cursor · GitHub Copilot · Windsurf · Free tier · EU servers.",
|
|
6
6
|
"type": "module",
|
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
import type { Redis } from 'ioredis';
|
|
2
|
+
import { calculateConfidence, confidenceBadge, CONFIDENCE_STALE_VALUE, CONFIDENCE_WARN_VALUE,
|
|
3
|
+
CONFIDENCE_WARN_DAYS } from '../confidence.js';
|
|
4
|
+
import { ckgSlug, ckgUpdateEdge } from '../ckg.js';
|
|
5
|
+
import type { CKGEdge, CKGNode } from '../ckg.js';
|
|
6
|
+
import { keywordSearch } from '../search.js';
|
|
7
|
+
|
|
8
|
+
type GetConnection = (instanceId: string) => Promise<Redis>;
|
|
9
|
+
type ApiFetch = <T>(path: string, options?: RequestInit) => Promise<T>;
|
|
10
|
+
|
|
11
|
+
export const ADVANCED_TOOL_NAMES = new Set([
|
|
12
|
+
'memory_consolidate', 'brain_diff', 'causal_trace', 'knowledge_decay', 'autopilot',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
export async function handleAdvancedTool(
|
|
16
|
+
name: string,
|
|
17
|
+
args: Record<string, unknown>,
|
|
18
|
+
getConnection: GetConnection,
|
|
19
|
+
apiFetch: ApiFetch,
|
|
20
|
+
): Promise<string | null> {
|
|
21
|
+
switch (name) {
|
|
22
|
+
case 'memory_consolidate': {
|
|
23
|
+
const { instance_id, dry_run = false, stale_days = 90 } = args as {
|
|
24
|
+
instance_id: string; dry_run?: boolean; stale_days?: number;
|
|
25
|
+
};
|
|
26
|
+
const redis = await getConnection(instance_id);
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
const staleMs = stale_days * 86400 * 1000;
|
|
29
|
+
|
|
30
|
+
// Scan all lessons
|
|
31
|
+
let cursor = 0;
|
|
32
|
+
const lessonKeys: string[] = [];
|
|
33
|
+
do {
|
|
34
|
+
const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
|
|
35
|
+
cursor = parseInt(next);
|
|
36
|
+
lessonKeys.push(...keys);
|
|
37
|
+
} while (cursor !== 0);
|
|
38
|
+
|
|
39
|
+
if (lessonKeys.length === 0) {
|
|
40
|
+
return '🧠 **Brain is empty** — no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type Lesson = { topic: string; outcome: string; what_worked?: string; what_failed?: string; ts: string; recall_count?: number; severity?: string; tags?: string[] };
|
|
44
|
+
const lessons: Map<string, Lesson> = new Map();
|
|
45
|
+
for (const k of lessonKeys) {
|
|
46
|
+
const raw = await redis.get(k);
|
|
47
|
+
if (!raw) continue;
|
|
48
|
+
try { lessons.set(k, JSON.parse(raw) as Lesson); } catch { /* skip malformed */ }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Detect duplicates: same topic prefix (e.g. deploy:api vs deploy:api-v2)
|
|
52
|
+
const duplicates: string[][] = [];
|
|
53
|
+
const topicGroups = new Map<string, string[]>();
|
|
54
|
+
for (const [k, l] of lessons) {
|
|
55
|
+
const prefix = l.topic.split(':')[0];
|
|
56
|
+
const group = topicGroups.get(prefix) ?? [];
|
|
57
|
+
group.push(k);
|
|
58
|
+
topicGroups.set(prefix, group);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Detect contradictions: same exact topic, different outcomes
|
|
62
|
+
const contradictions: Array<{ topic: string; keys: string[] }> = [];
|
|
63
|
+
const exactTopics = new Map<string, string[]>();
|
|
64
|
+
for (const [k, l] of lessons) {
|
|
65
|
+
const arr = exactTopics.get(l.topic) ?? [];
|
|
66
|
+
arr.push(k);
|
|
67
|
+
exactTopics.set(l.topic, arr);
|
|
68
|
+
}
|
|
69
|
+
for (const [topic, keys] of exactTopics) {
|
|
70
|
+
const outcomes = new Set(keys.map(k => lessons.get(k)?.outcome));
|
|
71
|
+
if (outcomes.size > 1) contradictions.push({ topic, keys });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Detect stale: not recalled in stale_days
|
|
75
|
+
const stale: string[] = [];
|
|
76
|
+
for (const [k, l] of lessons) {
|
|
77
|
+
const age = now - new Date(l.ts).getTime();
|
|
78
|
+
const recalls = l.recall_count ?? 0;
|
|
79
|
+
if (age > staleMs && recalls === 0) stale.push(k);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Merge duplicates by prefix: keep the success/highest-severity one
|
|
83
|
+
let merged = 0;
|
|
84
|
+
if (!dry_run) {
|
|
85
|
+
for (const [, keys] of topicGroups) {
|
|
86
|
+
if (keys.length < 2) continue;
|
|
87
|
+
const bySuccess = keys.filter(k => lessons.get(k)?.outcome === 'success');
|
|
88
|
+
const winner = bySuccess[0] ?? keys[0];
|
|
89
|
+
for (const k of keys) {
|
|
90
|
+
if (k !== winner) { await redis.del(k); merged++; }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Resolve contradictions: keep success, delete failure for same topic
|
|
94
|
+
for (const { keys } of contradictions) {
|
|
95
|
+
const success = keys.find(k => lessons.get(k)?.outcome === 'success');
|
|
96
|
+
if (success) {
|
|
97
|
+
for (const k of keys) {
|
|
98
|
+
if (k !== success) { await redis.del(k); }
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// Flag stale entries with a TTL of 30 days (not deleted, just expiring)
|
|
103
|
+
for (const k of stale) {
|
|
104
|
+
await redis.expire(k, 86400 * 30);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const lines = [
|
|
109
|
+
`🔬 **Memory Consolidation Report** ${dry_run ? '(dry run — no changes made)' : '✅ Applied'}`,
|
|
110
|
+
``,
|
|
111
|
+
`📊 **Before:** ${lessonKeys.length} lessons`,
|
|
112
|
+
``,
|
|
113
|
+
`🔁 **Contradictions detected:** ${contradictions.length}`,
|
|
114
|
+
...contradictions.slice(0, 5).map(c => ` → \`${c.topic}\`: ${c.keys.length} conflicting entries (kept: success)`),
|
|
115
|
+
contradictions.length > 5 ? ` … and ${contradictions.length - 5} more` : '',
|
|
116
|
+
``,
|
|
117
|
+
`♻️ **Duplicate clusters:** ${Array.from(topicGroups.values()).filter(v => v.length > 1).length}` +
|
|
118
|
+
(merged > 0 ? ` → ${merged} entries merged` : ''),
|
|
119
|
+
``,
|
|
120
|
+
`🕰️ **Stale entries (${stale_days}d, 0 recalls):** ${stale.length}` +
|
|
121
|
+
(stale.length > 0 && !dry_run ? ` → set to expire in 30 days` : ''),
|
|
122
|
+
``,
|
|
123
|
+
`📊 **After:** ${dry_run ? lessonKeys.length : lessonKeys.length - merged} lessons`,
|
|
124
|
+
``,
|
|
125
|
+
dry_run
|
|
126
|
+
? `💡 Re-run without dry_run=true to apply changes.`
|
|
127
|
+
: `✨ Brain consolidated. Run \`brain_diff(since="1h")\` to see the delta.`,
|
|
128
|
+
].filter(s => s !== '').join('\n');
|
|
129
|
+
return lines;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ── v0.6 Cognitive Cache: brain_diff ─────────────────────────────────────
|
|
133
|
+
case 'brain_diff': {
|
|
134
|
+
const { instance_id, since = '7d', format = 'summary' } = args as {
|
|
135
|
+
instance_id: string; since?: string; format?: 'summary' | 'detailed';
|
|
136
|
+
};
|
|
137
|
+
const redis = await getConnection(instance_id);
|
|
138
|
+
|
|
139
|
+
// Parse since
|
|
140
|
+
let sinceMs: number;
|
|
141
|
+
const match = since.match(/^(\d+)([dhm])$/);
|
|
142
|
+
if (match) {
|
|
143
|
+
const n = parseInt(match[1]);
|
|
144
|
+
const unit = match[2];
|
|
145
|
+
const mult = unit === 'd' ? 86400000 : unit === 'h' ? 3600000 : 60000;
|
|
146
|
+
sinceMs = Date.now() - n * mult;
|
|
147
|
+
} else {
|
|
148
|
+
sinceMs = new Date(since).getTime() || Date.now() - 7 * 86400000;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Scan all lessons
|
|
152
|
+
let cursor = 0;
|
|
153
|
+
const lessonKeys: string[] = [];
|
|
154
|
+
do {
|
|
155
|
+
const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
|
|
156
|
+
cursor = parseInt(next);
|
|
157
|
+
lessonKeys.push(...keys);
|
|
158
|
+
} while (cursor !== 0);
|
|
159
|
+
|
|
160
|
+
type Lesson = { topic: string; outcome: string; what_worked?: string; ts: string; recall_count?: number; severity?: string };
|
|
161
|
+
const added: Lesson[] = [];
|
|
162
|
+
const updated: Lesson[] = [];
|
|
163
|
+
const recalled: Lesson[] = [];
|
|
164
|
+
const total = lessonKeys.length;
|
|
165
|
+
|
|
166
|
+
for (const k of lessonKeys) {
|
|
167
|
+
const raw = await redis.get(k);
|
|
168
|
+
if (!raw) continue;
|
|
169
|
+
try {
|
|
170
|
+
const l = JSON.parse(raw) as Lesson;
|
|
171
|
+
const ts = new Date(l.ts).getTime();
|
|
172
|
+
if (ts >= sinceMs) {
|
|
173
|
+
// Check history to determine add vs update
|
|
174
|
+
const histKey = `cachly:lesson:history:${l.topic}`;
|
|
175
|
+
const histLen = await redis.llen(histKey);
|
|
176
|
+
if (histLen <= 1) added.push(l);
|
|
177
|
+
else updated.push(l);
|
|
178
|
+
}
|
|
179
|
+
if ((l.recall_count ?? 0) > 0) {
|
|
180
|
+
// We can't easily know when last recalled without extra metadata, so include
|
|
181
|
+
// lessons with recalls as "active"
|
|
182
|
+
recalled.push(l);
|
|
183
|
+
}
|
|
184
|
+
} catch { /* skip */ }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const sinceLabel = match ? `last ${since}` : new Date(sinceMs).toLocaleDateString('de-DE');
|
|
188
|
+
const lines: string[] = [
|
|
189
|
+
`📊 **Brain Diff** — ${sinceLabel}`,
|
|
190
|
+
``,
|
|
191
|
+
`Total lessons in brain: **${total}**`,
|
|
192
|
+
``,
|
|
193
|
+
`✅ **New** (${added.length}):`,
|
|
194
|
+
...added.slice(0, format === 'detailed' ? 20 : 5).map(l =>
|
|
195
|
+
` + \`${l.topic}\` — ${l.outcome} ${l.severity === 'critical' ? '🔴' : l.severity === 'major' ? '🟠' : '🟢'}`
|
|
196
|
+
),
|
|
197
|
+
added.length > 5 && format === 'summary' ? ` … and ${added.length - 5} more` : '',
|
|
198
|
+
``,
|
|
199
|
+
`🔄 **Updated** (${updated.length}):`,
|
|
200
|
+
...updated.slice(0, format === 'detailed' ? 20 : 5).map(l =>
|
|
201
|
+
` ~ \`${l.topic}\` — now: ${l.outcome}`
|
|
202
|
+
),
|
|
203
|
+
updated.length > 5 && format === 'summary' ? ` … and ${updated.length - 5} more` : '',
|
|
204
|
+
``,
|
|
205
|
+
`🔍 **Active** (recalled at least once): ${recalled.length}`,
|
|
206
|
+
``,
|
|
207
|
+
].filter(s => s !== '');
|
|
208
|
+
|
|
209
|
+
// ── 10X brain_diff extensions ──────────────────────────────────────────
|
|
210
|
+
// 1. Contested → Established (resolution nodes created in window)
|
|
211
|
+
const resolutionKeys: string[] = [];
|
|
212
|
+
const rsStream = redis.scanStream({ match: 'cachly:ckg:node:resolution-*', count: 100 });
|
|
213
|
+
await new Promise<void>((res, rej) => { rsStream.on('data', (b: string[]) => resolutionKeys.push(...b)); rsStream.on('end', res); rsStream.on('error', rej); });
|
|
214
|
+
const recentResolutions: Array<{ topic: string; resolution: string; ts: string }> = [];
|
|
215
|
+
for (const rk of resolutionKeys) {
|
|
216
|
+
const rr = await redis.get(rk);
|
|
217
|
+
if (!rr) continue;
|
|
218
|
+
try {
|
|
219
|
+
const rn = JSON.parse(rr) as { topic?: string; resolution?: string; ts?: string };
|
|
220
|
+
if (rn.ts && new Date(rn.ts).getTime() >= sinceMs) recentResolutions.push({ topic: rn.topic ?? rk, resolution: rn.resolution ?? 'unknown', ts: rn.ts });
|
|
221
|
+
} catch { /* skip */ }
|
|
222
|
+
}
|
|
223
|
+
if (recentResolutions.length > 0) {
|
|
224
|
+
lines.push(`🗳️ **MADC Resolutions** (${recentResolutions.length} contested beliefs resolved):`);
|
|
225
|
+
for (const r of recentResolutions.slice(0, 5)) {
|
|
226
|
+
const rIcon = r.resolution === 'unanimous_success' ? '✅' : r.resolution === 'unanimous_failure' ? '❌' : '⚠️';
|
|
227
|
+
lines.push(` ${rIcon} \`${r.topic}\` → ${r.resolution}`);
|
|
228
|
+
}
|
|
229
|
+
lines.push('');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// 2. New domains bootstrapped (domains in added lessons that weren't in older lessons)
|
|
233
|
+
const existingDomains = new Set(updated.concat(recalled).map(l => l.topic.split(':')[0]));
|
|
234
|
+
const newDomains = [...new Set(added.map(l => l.topic.split(':')[0]))].filter(d => !existingDomains.has(d));
|
|
235
|
+
if (newDomains.length > 0) {
|
|
236
|
+
lines.push(`🌱 **New domains bootstrapped:** ${newDomains.map(d => `\`${d}\``).join(', ')}`, '');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// 3. FedBrain transfers received in window
|
|
240
|
+
const fedHistRaw = await redis.lrange('cachly:fedbrain:federations', -20, -1);
|
|
241
|
+
const recentFeds = fedHistRaw.map(r => { try { return JSON.parse(r) as { source: string; domain: string; transferred_at: string; nodes: number; edges: number }; } catch { return null; } })
|
|
242
|
+
.filter(f => f && new Date(f!.transferred_at).getTime() >= sinceMs) as Array<{ source: string; domain: string; transferred_at: string; nodes: number; edges: number }>;
|
|
243
|
+
if (recentFeds.length > 0) {
|
|
244
|
+
lines.push(`🧠 **FedBrain transfers received (${recentFeds.length}):**`);
|
|
245
|
+
for (const f of recentFeds.slice(0, 3)) {
|
|
246
|
+
lines.push(` 📥 domain \`${f.domain}\` from \`${f.source.slice(0, 16)}…\` — ${f.nodes} nodes, ${f.edges} edges`);
|
|
247
|
+
}
|
|
248
|
+
lines.push('');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
lines.push(`💡 Run \`memory_consolidate\` to merge duplicates · \`knowledge_decay\` to see confidence scores.`);
|
|
252
|
+
return lines.join('\n');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// ── v0.6 Cognitive Cache: causal_trace ───────────────────────────────────
|
|
256
|
+
case 'causal_trace': {
|
|
257
|
+
const { instance_id, problem, max_depth = 5, tags: filterTags = [] } = args as {
|
|
258
|
+
instance_id: string; problem: string; max_depth?: number; tags?: string[];
|
|
259
|
+
};
|
|
260
|
+
const redis = await getConnection(instance_id);
|
|
261
|
+
|
|
262
|
+
// Normalize problem to keyword tokens
|
|
263
|
+
const tokens = problem.toLowerCase()
|
|
264
|
+
.replace(/[^a-z0-9\s\-_:]/g, ' ')
|
|
265
|
+
.split(/\s+/)
|
|
266
|
+
.filter(t => t.length > 2);
|
|
267
|
+
|
|
268
|
+
const SEV_ICON: Record<string, string> = { critical: '🔴', major: '🟠', minor: '🟡' };
|
|
269
|
+
|
|
270
|
+
// ── Layer 1: CKG graph traversal (if graph data exists) ─────────────────
|
|
271
|
+
type CKGResult = { conceptId: string; edge: CKGEdge; lesson?: { topic: string; what_worked?: string; ts: string; outcome: string; recall_count?: number; severity?: string } };
|
|
272
|
+
const ckgResults: CKGResult[] = [];
|
|
273
|
+
try {
|
|
274
|
+
for (const token of tokens.slice(0, 4)) {
|
|
275
|
+
// Search for CKG nodes matching this token
|
|
276
|
+
const fromKeys = await redis.smembers(`cachly:ckg:idx:from:${ckgSlug(token)}`);
|
|
277
|
+
const toKeys = await redis.smembers(`cachly:ckg:idx:to:${ckgSlug(token)}`);
|
|
278
|
+
// Also try pattern: scan nodes containing the token
|
|
279
|
+
const nodeKeys: string[] = [];
|
|
280
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
|
|
281
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
282
|
+
for (const nodeKey of nodeKeys.slice(0, 10)) {
|
|
283
|
+
const nodeRaw = await redis.get(nodeKey);
|
|
284
|
+
if (!nodeRaw) continue;
|
|
285
|
+
const node: CKGNode = JSON.parse(nodeRaw);
|
|
286
|
+
// Get edges from this node
|
|
287
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
288
|
+
for (const ek of edgeKeys.slice(0, 20)) {
|
|
289
|
+
const edgeRaw = await redis.get(ek);
|
|
290
|
+
if (!edgeRaw) continue;
|
|
291
|
+
const edge: CKGEdge = JSON.parse(edgeRaw);
|
|
292
|
+
if (edge.edgeType !== 'fixes' && edge.edgeType !== 'requires') continue;
|
|
293
|
+
// Find lesson for this concept
|
|
294
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${edge.from.replace(/-/g, ':').replace(/^fix:/, 'fix:')}`);
|
|
295
|
+
const lesson = lessonRaw ? JSON.parse(lessonRaw) : undefined;
|
|
296
|
+
ckgResults.push({ conceptId: node.id, edge, lesson });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
for (const ek of [...fromKeys, ...toKeys].slice(0, 20)) {
|
|
300
|
+
const edgeRaw = await redis.get(ek);
|
|
301
|
+
if (!edgeRaw) continue;
|
|
302
|
+
const edge: CKGEdge = JSON.parse(edgeRaw);
|
|
303
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${edge.from}`);
|
|
304
|
+
const lesson = lessonRaw ? JSON.parse(lessonRaw) : undefined;
|
|
305
|
+
ckgResults.push({ conceptId: edge.from, edge, lesson });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
} catch { /* CKG traversal non-critical */ }
|
|
309
|
+
|
|
310
|
+
// Deduplicate CKG results and sort by confidence
|
|
311
|
+
const ckgSeen = new Set<string>();
|
|
312
|
+
const ckgDeduped = ckgResults.filter(r => {
|
|
313
|
+
const key = `${r.edge.from}:${r.edge.edgeType}:${r.edge.to}`;
|
|
314
|
+
if (ckgSeen.has(key)) return false;
|
|
315
|
+
ckgSeen.add(key);
|
|
316
|
+
return true;
|
|
317
|
+
}).sort((a, b) => b.edge.confidence - a.edge.confidence).slice(0, max_depth);
|
|
318
|
+
|
|
319
|
+
// ── Layer 2 (fallback): text similarity over all lessons ─────────────────
|
|
320
|
+
let cursor = 0;
|
|
321
|
+
const lessonKeys: string[] = [];
|
|
322
|
+
do {
|
|
323
|
+
const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:*', 'COUNT', 200);
|
|
324
|
+
cursor = parseInt(next);
|
|
325
|
+
lessonKeys.push(...keys);
|
|
326
|
+
} while (cursor !== 0);
|
|
327
|
+
|
|
328
|
+
type Lesson = {
|
|
329
|
+
topic: string; outcome: string; what_worked?: string; what_failed?: string;
|
|
330
|
+
ts: string; recall_count?: number; severity?: string; tags?: string[];
|
|
331
|
+
context?: string;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
// Score each lesson by token overlap with problem description
|
|
335
|
+
const scored: Array<{ score: number; lesson: Lesson; key: string }> = [];
|
|
336
|
+
for (const k of lessonKeys) {
|
|
337
|
+
const raw = await redis.get(k);
|
|
338
|
+
if (!raw) continue;
|
|
339
|
+
try {
|
|
340
|
+
const l = JSON.parse(raw) as Lesson;
|
|
341
|
+
if (filterTags.length > 0 && !(l.tags ?? []).some((t: string) => filterTags.includes(t))) continue;
|
|
342
|
+
const haystack = [l.topic, l.what_failed ?? '', l.what_worked ?? '', l.context ?? '']
|
|
343
|
+
.join(' ').toLowerCase();
|
|
344
|
+
const score = tokens.reduce((s, t) => s + (haystack.includes(t) ? 1 : 0), 0);
|
|
345
|
+
if (score > 0) scored.push({ score, lesson: l, key: k });
|
|
346
|
+
} catch { /* skip */ }
|
|
347
|
+
}
|
|
348
|
+
scored.sort((a, b) => b.score - a.score);
|
|
349
|
+
const chain = scored.slice(0, max_depth);
|
|
350
|
+
|
|
351
|
+
if (chain.length === 0 && ckgDeduped.length === 0) {
|
|
352
|
+
return [
|
|
353
|
+
`🔍 **Causal Trace: "${problem}"**`,
|
|
354
|
+
``,
|
|
355
|
+
`No matching lessons found in brain.`,
|
|
356
|
+
``,
|
|
357
|
+
`💡 After you solve this, call:`,
|
|
358
|
+
`\`\`\``,
|
|
359
|
+
`learn_from_attempts(`,
|
|
360
|
+
` instance_id = "${instance_id}",`,
|
|
361
|
+
` topic = "fix:${tokens[0] ?? 'issue'}",`,
|
|
362
|
+
` outcome = "success",`,
|
|
363
|
+
` what_worked = "...",`,
|
|
364
|
+
` what_failed = "${problem}",`,
|
|
365
|
+
`)`,
|
|
366
|
+
`\`\`\``,
|
|
367
|
+
].join('\n');
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const lines: string[] = [
|
|
371
|
+
`🔍 **Causal Trace: "${problem}"**`,
|
|
372
|
+
``,
|
|
373
|
+
];
|
|
374
|
+
|
|
375
|
+
// Show CKG graph results first if available
|
|
376
|
+
if (ckgDeduped.length > 0) {
|
|
377
|
+
lines.push(`### 🕸️ CKG Graph (confidence-ranked)`);
|
|
378
|
+
for (const r of ckgDeduped) {
|
|
379
|
+
const confPct = Math.round(r.edge.confidence * 100);
|
|
380
|
+
const confBar = '▓'.repeat(Math.round(confPct / 10)) + '░'.repeat(10 - Math.round(confPct / 10));
|
|
381
|
+
lines.push(` ${r.edge.from} **→[${r.edge.edgeType}]→** ${r.edge.to}`);
|
|
382
|
+
lines.push(` ${confBar} ${confPct}% confidence (${r.edge.successes}/${r.edge.trials} confirmed)`);
|
|
383
|
+
if (r.lesson?.what_worked) lines.push(` ✅ Fix: ${r.lesson.what_worked.slice(0, 150)}`);
|
|
384
|
+
lines.push('');
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Build text-based causal chain narrative
|
|
389
|
+
if (chain.length > 0) {
|
|
390
|
+
lines.push(ckgDeduped.length > 0 ? `### 📚 Text Search (${chain.length} related lessons)` : `Found **${chain.length}** related lessons. Reconstructed causal chain:`, '');
|
|
391
|
+
const failures = chain.filter(c => c.lesson.outcome !== 'success');
|
|
392
|
+
const solutions = chain.filter(c => c.lesson.outcome === 'success');
|
|
393
|
+
|
|
394
|
+
if (failures.length > 0) {
|
|
395
|
+
lines.push(`**Root causes & failure chain:**`);
|
|
396
|
+
failures.forEach((c, i) => {
|
|
397
|
+
const l = c.lesson;
|
|
398
|
+
const sev = SEV_ICON[l.severity ?? 'minor'] ?? '🟡';
|
|
399
|
+
lines.push(`${i === 0 ? ' Root:' : ' → :'} ${sev} \`${l.topic}\``);
|
|
400
|
+
if (l.what_failed) lines.push(` ↳ ${l.what_failed.slice(0, 120)}`);
|
|
401
|
+
});
|
|
402
|
+
lines.push('');
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (solutions.length > 0) {
|
|
406
|
+
lines.push(`**Solutions that worked before:**`);
|
|
407
|
+
solutions.forEach((c, i) => {
|
|
408
|
+
const l = c.lesson;
|
|
409
|
+
const date = new Date(l.ts).toLocaleDateString('de-DE');
|
|
410
|
+
lines.push(` ${i + 1}. ✅ \`${l.topic}\` — ${date} · recalled ${l.recall_count ?? 0}×`);
|
|
411
|
+
if (l.what_worked) lines.push(` ${l.what_worked.slice(0, 200)}`);
|
|
412
|
+
});
|
|
413
|
+
lines.push('');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const topSolution = solutions[0]?.lesson;
|
|
417
|
+
if (topSolution?.what_worked) {
|
|
418
|
+
lines.push(`**⚡ Most likely fix:**`);
|
|
419
|
+
lines.push(`\`\`\``);
|
|
420
|
+
lines.push(topSolution.what_worked.slice(0, 500));
|
|
421
|
+
lines.push(`\`\`\``);
|
|
422
|
+
lines.push('');
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
lines.push(`💡 After applying: \`learn_from_attempts(topic="fix:${tokens[0] ?? 'issue'}", outcome="success", ...)\``);
|
|
427
|
+
if (ckgDeduped.length > 0) lines.push(`🕸️ Explore graph: \`ckg_inspect(concept="${tokens[0] ?? 'fix'}")\``);
|
|
428
|
+
return lines.join('\n');
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
case 'knowledge_decay': {
|
|
433
|
+
const { instance_id, min_age_days = 0, show_top = 20 } = args as {
|
|
434
|
+
instance_id: string; min_age_days?: number; show_top?: number;
|
|
435
|
+
};
|
|
436
|
+
const redis = await getConnection(instance_id);
|
|
437
|
+
const now = Date.now();
|
|
438
|
+
const minAgeMs = min_age_days * 86400000;
|
|
439
|
+
|
|
440
|
+
let cursor = 0;
|
|
441
|
+
const lessonKeys: string[] = [];
|
|
442
|
+
do {
|
|
443
|
+
const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
|
|
444
|
+
cursor = parseInt(next);
|
|
445
|
+
lessonKeys.push(...keys);
|
|
446
|
+
} while (cursor !== 0);
|
|
447
|
+
|
|
448
|
+
type Lesson = { topic: string; outcome: string; ts: string; recall_count?: number; severity?: string };
|
|
449
|
+
type Scored = { topic: string; confidence: number; age_days: number; recalls: number; outcome: string };
|
|
450
|
+
|
|
451
|
+
const scores: Scored[] = [];
|
|
452
|
+
for (const k of lessonKeys) {
|
|
453
|
+
const raw = await redis.get(k);
|
|
454
|
+
if (!raw) continue;
|
|
455
|
+
try {
|
|
456
|
+
const l = JSON.parse(raw) as Lesson;
|
|
457
|
+
const ageMs = now - new Date(l.ts).getTime();
|
|
458
|
+
if (ageMs < minAgeMs) continue;
|
|
459
|
+
const age_days = Math.floor(ageMs / 86400000);
|
|
460
|
+
const recalls = l.recall_count ?? 0;
|
|
461
|
+
|
|
462
|
+
// Confidence formula:
|
|
463
|
+
// base = 100 → decays by 1pt/day after 7 days, floored at 5
|
|
464
|
+
// boost: +5 per recall, capped at +50
|
|
465
|
+
// penalty: failure outcome → -20
|
|
466
|
+
const decayPts = Math.max(0, age_days - 7);
|
|
467
|
+
const base = Math.max(5, 100 - decayPts);
|
|
468
|
+
const recallBoost = Math.min(50, recalls * 5);
|
|
469
|
+
const outcomePenalty = l.outcome === 'failure' ? -20 : 0;
|
|
470
|
+
const confidence = Math.min(100, Math.max(0, base + recallBoost + outcomePenalty));
|
|
471
|
+
|
|
472
|
+
scores.push({ topic: l.topic, confidence, age_days, recalls, outcome: l.outcome });
|
|
473
|
+
} catch { /* skip */ }
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Sort by lowest confidence first
|
|
477
|
+
scores.sort((a, b) => a.confidence - b.confidence);
|
|
478
|
+
const shown = scores.slice(0, show_top);
|
|
479
|
+
|
|
480
|
+
function bar(pct: number): string {
|
|
481
|
+
const filled = Math.round(pct / 10);
|
|
482
|
+
return '█'.repeat(filled) + '░'.repeat(10 - filled) + ` ${pct}%`;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const avgConf = scores.length > 0
|
|
486
|
+
? Math.round(scores.reduce((s, e) => s + e.confidence, 0) / scores.length)
|
|
487
|
+
: 0;
|
|
488
|
+
const critical = scores.filter(s => s.confidence < 30).length;
|
|
489
|
+
const healthy = scores.filter(s => s.confidence >= 70).length;
|
|
490
|
+
|
|
491
|
+
const lines: string[] = [
|
|
492
|
+
`🧪 **Knowledge Decay Report** — ${scores.length} lessons`,
|
|
493
|
+
``,
|
|
494
|
+
`Average confidence: **${bar(avgConf)}**`,
|
|
495
|
+
`🔴 Critical (<30%): ${critical} 🟢 Healthy (≥70%): ${healthy}`,
|
|
496
|
+
``,
|
|
497
|
+
`Lowest confidence lessons (fix these first):`,
|
|
498
|
+
``,
|
|
499
|
+
...shown.map((s, i) =>
|
|
500
|
+
`${(i + 1).toString().padStart(2)}. \`${s.topic}\`\n ${bar(s.confidence)} · ${s.age_days}d old · ${s.recalls} recalls · ${s.outcome}`
|
|
501
|
+
),
|
|
502
|
+
``,
|
|
503
|
+
scores.length > show_top ? `… and ${scores.length - show_top} more lessons` : '',
|
|
504
|
+
``,
|
|
505
|
+
critical > 0
|
|
506
|
+
? `⚠️ ${critical} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`
|
|
507
|
+
: `✅ Brain confidence is healthy overall.`,
|
|
508
|
+
``,
|
|
509
|
+
`💡 Run \`memory_consolidate\` to prune stale entries · \`causal_trace\` to find root causes.`,
|
|
510
|
+
].filter(s => s !== '');
|
|
511
|
+
return lines.join('\n');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// ── v0.6 Cognitive Cache: autopilot ──────────────────────────────────────
|
|
515
|
+
case 'autopilot': {
|
|
516
|
+
const { instance_id, editor = 'claude', project_name = 'this project', style = 'full' } = args as {
|
|
517
|
+
instance_id: string; editor?: string; project_name?: string; style?: 'minimal' | 'full';
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
const minimal = `## Cachly AI Brain — Autopilot
|
|
521
|
+
|
|
522
|
+
**Instance:** \`${instance_id}\`
|
|
523
|
+
|
|
524
|
+
> Sessions are fully automatic. The Brain starts when you call any tool and saves a summary when you close.
|
|
525
|
+
|
|
526
|
+
### MANDATORY hooks (always fire, no exceptions):
|
|
527
|
+
- **Window opens** → call \`session_start(instance_id="${instance_id}", focus="<today's goal>")\`
|
|
528
|
+
- **Bug fixed / deployed / discovered** → call \`learn_from_attempts(instance_id="${instance_id}", topic="fix:<area>", outcome="success", what_worked="...")\`
|
|
529
|
+
- **Window closes** → call \`session_end(instance_id="${instance_id}", summary="...", files_changed=[...])\`
|
|
530
|
+
`;
|
|
531
|
+
|
|
532
|
+
const full = `## Cachly AI Brain — Autopilot for ${project_name}
|
|
533
|
+
|
|
534
|
+
**Instance:** \`${instance_id}\`
|
|
535
|
+
|
|
536
|
+
---
|
|
537
|
+
|
|
538
|
+
## 🔴 MANDATORY RULES — No exceptions, no prompting needed
|
|
539
|
+
|
|
540
|
+
### Rule 1 — Session Start (FIRST thing in every window)
|
|
541
|
+
\`\`\`
|
|
542
|
+
session_start(
|
|
543
|
+
instance_id = "${instance_id}",
|
|
544
|
+
focus = "<what you plan to work on today>",
|
|
545
|
+
)
|
|
546
|
+
\`\`\`
|
|
547
|
+
Returns: last session summary, handoff tasks, recent lessons, open failures.
|
|
548
|
+
|
|
549
|
+
### Rule 2 — Learn After Every Fix/Deploy/Discovery (AUTOMATIC)
|
|
550
|
+
**After EVERY** bug fix, deployment, or technical discovery — call immediately:
|
|
551
|
+
\`\`\`
|
|
552
|
+
learn_from_attempts(
|
|
553
|
+
instance_id = "${instance_id}",
|
|
554
|
+
topic = "category:keyword",
|
|
555
|
+
outcome = "success" | "failure" | "partial",
|
|
556
|
+
what_worked = "exact command or approach",
|
|
557
|
+
what_failed = "what failed (if applicable)",
|
|
558
|
+
severity = "critical" | "major" | "minor",
|
|
559
|
+
commands = ["the exact command that worked"],
|
|
560
|
+
file_paths = ["path/to/file"],
|
|
561
|
+
tags = ["relevant", "tags"],
|
|
562
|
+
)
|
|
563
|
+
\`\`\`
|
|
564
|
+
|
|
565
|
+
**Triggers:**
|
|
566
|
+
- ✅ Deployed → \`topic="deploy:web", outcome="success"\`
|
|
567
|
+
- ✅ Fixed bug → \`topic="fix:auth-race", outcome="success"\`
|
|
568
|
+
- ✅ Got error → \`topic="debug:docker", outcome="partial"\`
|
|
569
|
+
|
|
570
|
+
### Rule 3 — Session End (LAST thing before closing)
|
|
571
|
+
\`\`\`
|
|
572
|
+
session_end(
|
|
573
|
+
instance_id = "${instance_id}",
|
|
574
|
+
summary = "What was accomplished (2-3 sentences)",
|
|
575
|
+
files_changed = ["list", "of", "changed", "files"],
|
|
576
|
+
lessons_learned = <number of learn_from_attempts calls>,
|
|
577
|
+
)
|
|
578
|
+
\`\`\`
|
|
579
|
+
|
|
580
|
+
### Rule 4 — Before any non-trivial task
|
|
581
|
+
\`\`\`
|
|
582
|
+
smart_recall(
|
|
583
|
+
instance_id = "${instance_id}",
|
|
584
|
+
query = "<describe what you are about to do>",
|
|
585
|
+
)
|
|
586
|
+
\`\`\`
|
|
587
|
+
|
|
588
|
+
---
|
|
589
|
+
|
|
590
|
+
## ⚡ Cognitive Tools (v0.6)
|
|
591
|
+
|
|
592
|
+
| When | Call |
|
|
593
|
+
|---|---|
|
|
594
|
+
| Brain feeling cluttered | \`memory_consolidate(instance_id="${instance_id}")\` |
|
|
595
|
+
| Weekly review | \`brain_diff(instance_id="${instance_id}", since="7d")\` |
|
|
596
|
+
| Weird bug, no idea why | \`causal_trace(instance_id="${instance_id}", problem="<symptom>")\` |
|
|
597
|
+
| Before big refactor | \`knowledge_decay(instance_id="${instance_id}")\` |
|
|
598
|
+
|
|
599
|
+
---
|
|
600
|
+
|
|
601
|
+
*Cachly v0.6 · Generated ${new Date().toISOString().slice(0, 10)}*
|
|
602
|
+
`;
|
|
603
|
+
|
|
604
|
+
const content = style === 'minimal' ? minimal : full;
|
|
605
|
+
const filename = editor === 'copilot'
|
|
606
|
+
? '.github/copilot-instructions.md'
|
|
607
|
+
: editor === 'continue'
|
|
608
|
+
? '.continue/cachly-autopilot.md'
|
|
609
|
+
: 'CLAUDE.md';
|
|
610
|
+
|
|
611
|
+
return [
|
|
612
|
+
`🤖 **Autopilot instructions generated** for **${editor === 'all' ? 'all editors' : editor}**`,
|
|
613
|
+
``,
|
|
614
|
+
`**File to create:** \`${filename}\``,
|
|
615
|
+
``,
|
|
616
|
+
`\`\`\`markdown`,
|
|
617
|
+
content,
|
|
618
|
+
`\`\`\``,
|
|
619
|
+
``,
|
|
620
|
+
`**How to apply:**`,
|
|
621
|
+
`\`\`\`bash`,
|
|
622
|
+
`# Copy to your project root:`,
|
|
623
|
+
`cat > ${filename} << 'EOF'`,
|
|
624
|
+
content,
|
|
625
|
+
`EOF`,
|
|
626
|
+
`\`\`\``,
|
|
627
|
+
``,
|
|
628
|
+
`✨ Once this file is in place, **${editor === 'copilot' ? 'GitHub Copilot' : editor === 'continue' ? 'Continue.dev' : 'Claude/Cursor/Windsurf'}** will manage the Brain automatically — no manual calls needed, ever.`,
|
|
629
|
+
].join('\n');
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// ── v0.7 Knowledge Syndication: syndicate ────────────────────────────────
|
|
633
|
+
|
|
634
|
+
default:
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
}
|