@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
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
+
import type { Redis } from 'ioredis';
|
|
3
|
+
import { calculateConfidence } from '../confidence.js';
|
|
4
|
+
import { ckgSlug, ckgUpdateEdge } from '../ckg.js';
|
|
5
|
+
import type { CKGEdge, CKGNode } from '../ckg.js';
|
|
6
|
+
import { keywordSearch, tokenize } 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 SYNDICATE_TOOL_NAMES = new Set([
|
|
12
|
+
'syndicate', 'syndicate_search', 'syndicate_stats', 'syndicate_trending',
|
|
13
|
+
'brain_search', 'ckg_inspect', 'brain_predict',
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
export async function handleSyndicateTool(
|
|
17
|
+
name: string,
|
|
18
|
+
args: Record<string, unknown>,
|
|
19
|
+
getConnection: GetConnection,
|
|
20
|
+
apiFetch: ApiFetch,
|
|
21
|
+
): Promise<string | null> {
|
|
22
|
+
switch (name) {
|
|
23
|
+
case 'syndicate': {
|
|
24
|
+
const { topic, outcome = 'success', what_worked, what_failed = '', severity = 'minor', tags = [], scope = 'public' } = args as {
|
|
25
|
+
topic: string; outcome?: string; what_worked: string; what_failed?: string; severity?: string; tags?: string[]; scope?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
if (!topic || !what_worked) {
|
|
29
|
+
throw new McpError(ErrorCode.InvalidParams, 'topic and what_worked are required');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const body = { topic, outcome, what_worked, what_failed, severity, tags, scope };
|
|
33
|
+
const res = await apiFetch<{ id: string; topic: string; outcome: string; message: string; deduped?: boolean }>(
|
|
34
|
+
'/api/v1/syndication/contribute',
|
|
35
|
+
{ method: 'POST', body: JSON.stringify(body) }
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const scopeLabel = scope === 'org' ? '๐ข org-private' : '๐ global commons';
|
|
39
|
+
const dedupNote = res.deduped
|
|
40
|
+
? `\n> โป๏ธ Duplicate detected โ trust score incremented for the existing lesson.`
|
|
41
|
+
: '';
|
|
42
|
+
|
|
43
|
+
return [
|
|
44
|
+
`${scope === 'org' ? '๐ข' : '๐'} **Lesson syndicated to the ${scope === 'org' ? 'org Knowledge Commons' : 'global Knowledge Commons'}**${dedupNote}`,
|
|
45
|
+
``,
|
|
46
|
+
`**ID:** \`${res.id}\``,
|
|
47
|
+
`**Topic:** \`${res.topic}\` ยท **Outcome:** ${res.outcome} ยท **Scope:** ${scopeLabel}`,
|
|
48
|
+
``,
|
|
49
|
+
scope === 'org'
|
|
50
|
+
? `This lesson is visible only within your organisation. Use \`syndicate_search(scope="org")\` to find it.`
|
|
51
|
+
: `Your lesson is now searchable by every AI brain in the network.`,
|
|
52
|
+
`When another instance confirms it works, its trust score rises โ and so does your contributor reputation.`,
|
|
53
|
+
``,
|
|
54
|
+
`**Tip:** Use \`syndicate_search(q="${topic}")\` to see all community lessons on this topic.`,
|
|
55
|
+
].join('\n');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// โโ v0.7 Knowledge Syndication: syndicate_search โโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
59
|
+
case 'syndicate_search': {
|
|
60
|
+
const { q = '', limit = 20, category = '', scope = '' } = args as { q?: string; limit?: number; category?: string; scope?: string };
|
|
61
|
+
|
|
62
|
+
const params = new URLSearchParams();
|
|
63
|
+
if (q) params.set('q', q);
|
|
64
|
+
if (category) params.set('category', category);
|
|
65
|
+
if (scope) params.set('scope', scope);
|
|
66
|
+
params.set('limit', String(Math.min(Math.max(1, limit), 50)));
|
|
67
|
+
|
|
68
|
+
const res = await apiFetch<{ results: Array<{
|
|
69
|
+
id: string; topic: string; category: string; outcome: string;
|
|
70
|
+
what_worked: string; what_failed: string; severity: string;
|
|
71
|
+
confirm_count: number; created_at: string;
|
|
72
|
+
}>; count: number; query: string }>(`/api/v1/syndication/search?${params}`);
|
|
73
|
+
|
|
74
|
+
if (!res.results || res.results.length === 0) {
|
|
75
|
+
return q
|
|
76
|
+
? `No lessons found for "${q}" in the global Knowledge Commons yet.\n\nBe the first to contribute: \`syndicate(topic="...", what_worked="...")\``
|
|
77
|
+
: `The global Knowledge Commons is empty. Be the first contributor:\n\`syndicate(topic="deploy:api", what_worked="...")\``;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const outcomeIcon = (o: string) => o === 'success' ? 'โ
' : o === 'failure' ? 'โ' : 'โ ๏ธ';
|
|
81
|
+
const severityLabel = (s: string) => s === 'critical' ? '๐ด' : s === 'major' ? '๐ก' : '๐ข';
|
|
82
|
+
const confirmBar = (n: number) => {
|
|
83
|
+
const filled = Math.min(10, Math.round(n / 5));
|
|
84
|
+
return 'โ'.repeat(filled) + 'โ'.repeat(10 - filled) + ` ร${n}`;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const header = [q, category].filter(Boolean).join(' ยท ');
|
|
88
|
+
const lines: string[] = [
|
|
89
|
+
`## ๐ Global Knowledge Commons${header ? ` โ ${header}` : ' โ Recent'}`,
|
|
90
|
+
`*${res.count} lesson${res.count === 1 ? '' : 's'} found*`,
|
|
91
|
+
``,
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
for (const lesson of res.results) {
|
|
95
|
+
lines.push(
|
|
96
|
+
`### ${outcomeIcon(lesson.outcome)} \`${lesson.topic}\` ${severityLabel(lesson.severity)}`,
|
|
97
|
+
`**Trust:** ${confirmBar(lesson.confirm_count)}`,
|
|
98
|
+
lesson.what_worked ? `**What worked:** ${lesson.what_worked}` : '',
|
|
99
|
+
lesson.what_failed ? `**What failed:** ${lesson.what_failed}` : '',
|
|
100
|
+
`*Contributed ${new Date(lesson.created_at).toLocaleDateString('de-DE')} ยท ID: \`${lesson.id}\`*`,
|
|
101
|
+
``,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
lines.push(
|
|
106
|
+
`---`,
|
|
107
|
+
`**Confirm** (this helped you): \`syndicate(topic="${res.results[0]?.topic ?? '...'}", what_worked="...")\` โ auto-deduped, trust +1`,
|
|
108
|
+
`**Contribute your own:** \`syndicate(topic="fix:...", what_worked="...")\``,
|
|
109
|
+
`**Filter by category:** \`syndicate_search(category="fix")\``,
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
return lines.filter(l => l !== '').join('\n');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// โโ v0.7 Knowledge Syndication: syndicate_stats โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
116
|
+
case 'syndicate_stats': {
|
|
117
|
+
const res = await apiFetch<{
|
|
118
|
+
total_lessons: number;
|
|
119
|
+
total_confirms: number;
|
|
120
|
+
added_last_7_days: number;
|
|
121
|
+
top_categories: Array<{ category: string; count: number }>;
|
|
122
|
+
most_trusted: Array<{
|
|
123
|
+
id: string; topic: string; outcome: string;
|
|
124
|
+
what_worked: string; confirm_count: number; created_at: string;
|
|
125
|
+
}>;
|
|
126
|
+
}>('/api/v1/syndication/stats');
|
|
127
|
+
|
|
128
|
+
const confirmBar = (n: number) => {
|
|
129
|
+
const filled = Math.min(10, Math.round(n / 5));
|
|
130
|
+
return 'โ'.repeat(filled) + 'โ'.repeat(10 - filled) + ` ร${n}`;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const lines: string[] = [
|
|
134
|
+
`## ๐ Global Knowledge Commons โ Stats`,
|
|
135
|
+
``,
|
|
136
|
+
`| Metric | Value |`,
|
|
137
|
+
`|---|---|`,
|
|
138
|
+
`| Total lessons | **${res.total_lessons.toLocaleString()}** |`,
|
|
139
|
+
`| Total confirms | **${res.total_confirms.toLocaleString()}** |`,
|
|
140
|
+
`| Added last 7 days | **${res.added_last_7_days}** |`,
|
|
141
|
+
``,
|
|
142
|
+
`### Top Categories`,
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
for (const cat of res.top_categories ?? []) {
|
|
146
|
+
lines.push(`- \`${cat.category}\` โ ${cat.count} lesson${cat.count === 1 ? '' : 's'}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
lines.push(``, `### Most Trusted Lessons`);
|
|
150
|
+
|
|
151
|
+
for (const lesson of res.most_trusted ?? []) {
|
|
152
|
+
lines.push(
|
|
153
|
+
`**\`${lesson.topic}\`** ${confirmBar(lesson.confirm_count)}`,
|
|
154
|
+
`> ${lesson.what_worked.slice(0, 120)}${lesson.what_worked.length > 120 ? 'โฆ' : ''}`,
|
|
155
|
+
``,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
lines.push(
|
|
160
|
+
`---`,
|
|
161
|
+
`**Contribute:** \`syndicate(topic="...", what_worked="...")\` | **Search:** \`syndicate_search(q="your problem")\``,
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
// Top contributors (anonymous scores)
|
|
165
|
+
if ((res as any).top_contributors?.length) {
|
|
166
|
+
lines.push(``, `### ๐
Top Contributors (anonymous)`);
|
|
167
|
+
for (const c of (res as any).top_contributors) {
|
|
168
|
+
lines.push(`- Trust **${c.trust_score}** ยท ${c.lessons_count} lesson${c.lessons_count === 1 ? '' : 's'} ยท ${c.confirms_received} confirms received`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return lines.join('\n');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// โโ v0.8 Knowledge Syndication: syndicate_trending โโโโโโโโโโโโโโโโโโโโโโโ
|
|
176
|
+
case 'syndicate_trending': {
|
|
177
|
+
const { limit = 10 } = args as { limit?: number };
|
|
178
|
+
|
|
179
|
+
const params = new URLSearchParams({ limit: String(Math.min(Math.max(1, limit), 50)) });
|
|
180
|
+
const res = await apiFetch<{ results: Array<{
|
|
181
|
+
id: string; topic: string; category: string; outcome: string;
|
|
182
|
+
what_worked: string; what_failed: string; severity: string;
|
|
183
|
+
confirm_count: number; trend_score: number; created_at: string;
|
|
184
|
+
}>; count: number }>(`/api/v1/syndication/trending?${params}`);
|
|
185
|
+
|
|
186
|
+
if (!res.results || res.results.length === 0) {
|
|
187
|
+
return [
|
|
188
|
+
`## ๐ Trending in the Knowledge Commons`,
|
|
189
|
+
``,
|
|
190
|
+
`No trending lessons yet (need at least 2 confirms in the last 7 days).`,
|
|
191
|
+
``,
|
|
192
|
+
`Contribute and confirm lessons to see them trend: \`syndicate(topic="...", what_worked="...")\``,
|
|
193
|
+
].join('\n');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const outcomeIcon = (o: string) => o === 'success' ? 'โ
' : o === 'failure' ? 'โ' : 'โ ๏ธ';
|
|
197
|
+
const severityLabel = (s: string) => s === 'critical' ? '๐ด' : s === 'major' ? '๐ก' : '๐ข';
|
|
198
|
+
const confirmBar = (n: number) => {
|
|
199
|
+
const filled = Math.min(10, Math.round(n / 5));
|
|
200
|
+
return 'โ'.repeat(filled) + 'โ'.repeat(10 - filled) + ` ร${n}`;
|
|
201
|
+
};
|
|
202
|
+
const trendBar = (score: number) => {
|
|
203
|
+
const filled = Math.min(10, Math.round(score * 2));
|
|
204
|
+
return 'โฒ'.repeat(filled) + 'โณ'.repeat(10 - filled) + ` ${score.toFixed(2)}/day`;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const lines: string[] = [
|
|
208
|
+
`## ๐ Trending in the Knowledge Commons`,
|
|
209
|
+
`*Lessons with the fastest confirmation velocity in the last 7 days*`,
|
|
210
|
+
``,
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
for (const lesson of res.results) {
|
|
214
|
+
lines.push(
|
|
215
|
+
`### ${outcomeIcon(lesson.outcome)} \`${lesson.topic}\` ${severityLabel(lesson.severity)}`,
|
|
216
|
+
`**Trend:** ${trendBar(lesson.trend_score)} | **Trust:** ${confirmBar(lesson.confirm_count)}`,
|
|
217
|
+
lesson.what_worked ? `**What worked:** ${lesson.what_worked.slice(0, 200)}${lesson.what_worked.length > 200 ? 'โฆ' : ''}` : '',
|
|
218
|
+
`*ID: \`${lesson.id}\` ยท ${new Date(lesson.created_at).toLocaleDateString('de-DE')}*`,
|
|
219
|
+
``,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
lines.push(
|
|
224
|
+
`---`,
|
|
225
|
+
`**Confirm** (if this helped you): \`syndicate(topic="${res.results[0]?.topic ?? '...'}", what_worked="...")\` โ auto-deduped, trust +1`,
|
|
226
|
+
`**All trending:** \`syndicate_trending(limit=50)\` | **Search:** \`syndicate_search(q="...")\``,
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
return lines.filter(l => l !== '').join('\n');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// โโ Layer 1: brain_search โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
233
|
+
case 'brain_search': {
|
|
234
|
+
const { instance_id, query, limit = 15 } = args as { instance_id: string; query: string; limit?: number };
|
|
235
|
+
const redis = await getConnection(instance_id);
|
|
236
|
+
|
|
237
|
+
// BM25+ over ALL brain key namespaces
|
|
238
|
+
const allMatches = await keywordSearch(
|
|
239
|
+
redis,
|
|
240
|
+
[
|
|
241
|
+
'cachly:lesson:best:*',
|
|
242
|
+
'cachly:ctx:*',
|
|
243
|
+
'cachly:idx:*',
|
|
244
|
+
'cachly:session:last',
|
|
245
|
+
'cachly:session:handoff',
|
|
246
|
+
'cachly:roadmap:*',
|
|
247
|
+
'cachly:ckg:node:*',
|
|
248
|
+
],
|
|
249
|
+
query,
|
|
250
|
+
limit,
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
if (allMatches.length === 0) {
|
|
254
|
+
return [`๐ **Brain Search: "${query}"**`, '', `No results found across all brain data.`, '', `๐ก Try \`smart_recall\` or check \`list_remembered\`.`].join('\n');
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const lines = [`๐ **Brain Search: "${query}"** โ ${allMatches.length} result${allMatches.length !== 1 ? 's' : ''} across all brain data\n`];
|
|
258
|
+
for (const m of allMatches.slice(0, limit)) {
|
|
259
|
+
const ns = m.key.startsWith('cachly:lesson:') ? '๐ก lesson'
|
|
260
|
+
: m.key.startsWith('cachly:ctx:') ? '๐ context'
|
|
261
|
+
: m.key.startsWith('cachly:idx:') ? '๐ index'
|
|
262
|
+
: m.key.startsWith('cachly:session:') ? '๐ session'
|
|
263
|
+
: m.key.startsWith('cachly:roadmap:') ? '๐บ๏ธ roadmap'
|
|
264
|
+
: m.key.startsWith('cachly:ckg:node:') ? '๐ธ๏ธ ckg-node'
|
|
265
|
+
: '๐๏ธ data';
|
|
266
|
+
const preview = m.content.slice(0, 280).replace(/\n/g, ' ');
|
|
267
|
+
lines.push(`**${ns}** \`${m.key.split(':').slice(2).join(':')}\` _(BM25: ${m.score.toFixed(2)})_`);
|
|
268
|
+
lines.push(`> ${preview}${m.content.length > 280 ? 'โฆ' : ''}\n`);
|
|
269
|
+
}
|
|
270
|
+
return lines.join('\n');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// โโ Layer 1: ckg_inspect โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
274
|
+
case 'ckg_inspect': {
|
|
275
|
+
const { instance_id, concept, max_hops = 2 } = args as { instance_id: string; concept: string; max_hops?: number };
|
|
276
|
+
const redis = await getConnection(instance_id);
|
|
277
|
+
|
|
278
|
+
const conceptId = ckgSlug(concept);
|
|
279
|
+
const visited = new Set<string>();
|
|
280
|
+
const allEdges: CKGEdge[] = [];
|
|
281
|
+
|
|
282
|
+
// BFS traversal of CKG
|
|
283
|
+
const queue: Array<{ id: string; hop: number }> = [{ id: conceptId, hop: 0 }];
|
|
284
|
+
while (queue.length > 0) {
|
|
285
|
+
const { id, hop } = queue.shift()!;
|
|
286
|
+
if (visited.has(id) || hop > max_hops) continue;
|
|
287
|
+
visited.add(id);
|
|
288
|
+
|
|
289
|
+
const fromKeys = await redis.smembers(`cachly:ckg:idx:from:${id}`);
|
|
290
|
+
const toKeys = await redis.smembers(`cachly:ckg:idx:to:${id}`);
|
|
291
|
+
|
|
292
|
+
for (const ek of [...fromKeys, ...toKeys].slice(0, 50)) {
|
|
293
|
+
const raw = await redis.get(ek);
|
|
294
|
+
if (!raw) continue;
|
|
295
|
+
const edge: CKGEdge = JSON.parse(raw);
|
|
296
|
+
allEdges.push(edge);
|
|
297
|
+
if (hop < max_hops) {
|
|
298
|
+
if (!visited.has(edge.from)) queue.push({ id: edge.from, hop: hop + 1 });
|
|
299
|
+
if (!visited.has(edge.to)) queue.push({ id: edge.to, hop: hop + 1 });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (allEdges.length === 0) {
|
|
305
|
+
// Try fuzzy: scan for nodes matching the concept as substring
|
|
306
|
+
const nodeKeys: string[] = [];
|
|
307
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${conceptId}*`, count: 100 });
|
|
308
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
309
|
+
if (nodeKeys.length === 0) {
|
|
310
|
+
return [`๐ธ๏ธ **CKG Inspect: "${concept}"**`, '', `No CKG nodes found. The graph builds automatically as you call \`learn_from_attempts\`.`, '', `๐ก Once you have lessons stored, CKG edges will appear here.`].join('\n');
|
|
311
|
+
}
|
|
312
|
+
const nodeList = nodeKeys.slice(0, 10).map(k => ` โข \`${k.replace('cachly:ckg:node:', '')}\``).join('\n');
|
|
313
|
+
return [`๐ธ๏ธ **CKG Inspect: "${concept}"**`, '', `No edges found for \`${conceptId}\`, but found similar nodes:`, nodeList, '', `Try: \`ckg_inspect(concept="<exact-node-id>")\``].join('\n');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Sort by confidence desc, deduplicate
|
|
317
|
+
const edgeSeen = new Set<string>();
|
|
318
|
+
const unique = allEdges.filter(e => {
|
|
319
|
+
const k = `${e.from}:${e.edgeType}:${e.to}`;
|
|
320
|
+
if (edgeSeen.has(k)) return false;
|
|
321
|
+
edgeSeen.add(k);
|
|
322
|
+
return true;
|
|
323
|
+
}).sort((a, b) => b.confidence - a.confidence);
|
|
324
|
+
|
|
325
|
+
const EDGE_ICON: Record<string, string> = { fixes: '๐ง', requires: '๐', 'co-occurs': '๐', causes: 'โก', contradicts: 'โ ๏ธ', degrades_under: '๐' };
|
|
326
|
+
|
|
327
|
+
const lines = [`๐ธ๏ธ **CKG Inspect: "${concept}"** (${unique.length} edge${unique.length !== 1 ? 's' : ''}, ${visited.size} node${visited.size !== 1 ? 's' : ''} traversed)\n`];
|
|
328
|
+
|
|
329
|
+
// Group by edge type
|
|
330
|
+
const byType = new Map<string, CKGEdge[]>();
|
|
331
|
+
for (const e of unique) {
|
|
332
|
+
if (!byType.has(e.edgeType)) byType.set(e.edgeType, []);
|
|
333
|
+
byType.get(e.edgeType)!.push(e);
|
|
334
|
+
}
|
|
335
|
+
for (const [eType, edges] of byType) {
|
|
336
|
+
const icon = EDGE_ICON[eType] ?? 'โ';
|
|
337
|
+
lines.push(`**${icon} ${eType}** (${edges.length})`);
|
|
338
|
+
for (const e of edges.slice(0, 8)) {
|
|
339
|
+
const confPct = Math.round(e.confidence * 100);
|
|
340
|
+
const bar = 'โ'.repeat(Math.round(confPct / 10)) + 'โ'.repeat(10 - Math.round(confPct / 10));
|
|
341
|
+
lines.push(` \`${e.from}\` โ \`${e.to}\` ${bar} ${confPct}% (${e.successes.toFixed(1)}/${e.trials} trials)`);
|
|
342
|
+
}
|
|
343
|
+
lines.push('');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
lines.push(`๐ก Expand: \`ckg_inspect(concept="${concept}", max_hops=3)\` | Predict: \`brain_predict(context="${concept}")\``);
|
|
347
|
+
return lines.join('\n');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// โโ Layer 4: brain_predict (PPE) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
351
|
+
case 'brain_predict': {
|
|
352
|
+
const { instance_id, context: ctx, top_k = 5 } = args as { instance_id: string; context: string; top_k?: number };
|
|
353
|
+
const redis = await getConnection(instance_id);
|
|
354
|
+
|
|
355
|
+
const ctxTokens = ctx.toLowerCase().replace(/[^a-z0-9\s\-_:]/g, ' ').split(/\s+/).filter(t => t.length > 2);
|
|
356
|
+
|
|
357
|
+
// Step 1: Find CKG nodes matching context tokens
|
|
358
|
+
type Prediction = { concept: string; edgeType: string; target: string; confidence: number; lesson?: { what_worked?: string; topic: string } };
|
|
359
|
+
const predictions: Prediction[] = [];
|
|
360
|
+
|
|
361
|
+
for (const token of ctxTokens.slice(0, 6)) {
|
|
362
|
+
const nodeKeys: string[] = [];
|
|
363
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
|
|
364
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
365
|
+
|
|
366
|
+
for (const nk of nodeKeys.slice(0, 5)) {
|
|
367
|
+
const nodeRaw = await redis.get(nk);
|
|
368
|
+
if (!nodeRaw) continue;
|
|
369
|
+
const node: CKGNode = JSON.parse(nodeRaw);
|
|
370
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
371
|
+
for (const ek of edgeKeys.slice(0, 20)) {
|
|
372
|
+
const edgeRaw = await redis.get(ek);
|
|
373
|
+
if (!edgeRaw) continue;
|
|
374
|
+
const edge: CKGEdge = JSON.parse(edgeRaw);
|
|
375
|
+
// Only interested in fixes and co-occurs for prediction
|
|
376
|
+
if (edge.edgeType !== 'fixes' && edge.edgeType !== 'co-occurs' && edge.edgeType !== 'causes') continue;
|
|
377
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${edge.from}`);
|
|
378
|
+
const lesson = lessonRaw ? JSON.parse(lessonRaw) : undefined;
|
|
379
|
+
predictions.push({ concept: node.id, edgeType: edge.edgeType, target: edge.to, confidence: edge.confidence, lesson });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Step 2: Text-based fallback โ scan lessons for matching topics
|
|
385
|
+
const textPredictions: Array<{ topic: string; what_worked?: string; what_failed?: string; outcome: string; severity?: string; confidence: number }> = [];
|
|
386
|
+
const lessonKeys: string[] = [];
|
|
387
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 200 });
|
|
388
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
389
|
+
for (const k of lessonKeys) {
|
|
390
|
+
const raw = await redis.get(k);
|
|
391
|
+
if (!raw) continue;
|
|
392
|
+
try {
|
|
393
|
+
const l = JSON.parse(raw) as { topic: string; what_worked?: string; what_failed?: string; outcome: string; severity?: string; ts: string; verified_at?: string; recall_count?: number };
|
|
394
|
+
const haystack = [l.topic, l.what_failed ?? '', l.what_worked ?? ''].join(' ').toLowerCase();
|
|
395
|
+
const score = ctxTokens.reduce((s, t) => s + (haystack.includes(t) ? 1 : 0), 0);
|
|
396
|
+
if (score >= 1 && l.outcome !== 'failure') {
|
|
397
|
+
const conf = calculateConfidence(l);
|
|
398
|
+
textPredictions.push({ ...l, confidence: conf });
|
|
399
|
+
}
|
|
400
|
+
} catch { /* skip */ }
|
|
401
|
+
}
|
|
402
|
+
textPredictions.sort((a, b) => b.confidence - a.confidence);
|
|
403
|
+
|
|
404
|
+
if (predictions.length === 0 && textPredictions.length === 0) {
|
|
405
|
+
return [
|
|
406
|
+
`๐ฎ **Brain Predict: "${ctx}"**`,
|
|
407
|
+
``,
|
|
408
|
+
`No predictions yet โ the brain hasn't seen this domain.`,
|
|
409
|
+
``,
|
|
410
|
+
`๐ก As you solve problems in this area and call \`learn_from_attempts\`, the CKG builds up and predictions become available.`,
|
|
411
|
+
].join('\n');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const lines = [`๐ฎ **Brain Predict: "${ctx}"**\n`];
|
|
415
|
+
|
|
416
|
+
// CKG-based predictions
|
|
417
|
+
if (predictions.length > 0) {
|
|
418
|
+
const pSeen = new Set<string>();
|
|
419
|
+
const pUniq = predictions.filter(p => { const k = `${p.concept}:${p.edgeType}:${p.target}`; if (pSeen.has(k)) return false; pSeen.add(k); return true; })
|
|
420
|
+
.sort((a, b) => b.confidence - a.confidence).slice(0, top_k);
|
|
421
|
+
|
|
422
|
+
lines.push(`### ๐ธ๏ธ CKG Predictions (based on ${pUniq.length} known edges)`);
|
|
423
|
+
for (const p of pUniq) {
|
|
424
|
+
const confPct = Math.round(p.confidence * 100);
|
|
425
|
+
const icon = p.edgeType === 'fixes' ? '๐ง' : p.edgeType === 'co-occurs' ? '๐' : 'โก';
|
|
426
|
+
lines.push(`${icon} **${confPct}%** \`${p.concept}\` _${p.edgeType}_ \`${p.target}\``);
|
|
427
|
+
if (p.lesson?.what_worked) lines.push(` โ
${p.lesson.what_worked.slice(0, 120)}`);
|
|
428
|
+
}
|
|
429
|
+
lines.push('');
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Text-based lesson predictions
|
|
433
|
+
if (textPredictions.length > 0) {
|
|
434
|
+
lines.push(`### ๐ Relevant Lessons (${Math.min(textPredictions.length, top_k)} pre-loaded)`);
|
|
435
|
+
for (const l of textPredictions.slice(0, top_k)) {
|
|
436
|
+
const confPct = Math.round(l.confidence * 100);
|
|
437
|
+
lines.push(` โ
**${confPct}%** \`${l.topic}\` โ ${(l.what_worked ?? '').slice(0, 120)}`);
|
|
438
|
+
}
|
|
439
|
+
lines.push('');
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
lines.push(`๐ก Outcome confirmed? \`learn_from_attempts(topic="fix:...", outcome="success", ...)\` โ improves future predictions`);
|
|
443
|
+
return lines.join('\n');
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// โโ Layer 3: MADC โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
447
|
+
|
|
448
|
+
default:
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
}
|