@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,1143 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { execSync } from 'node:child_process';
|
|
3
|
+
import type { Redis } from 'ioredis';
|
|
4
|
+
import { calculateConfidence, confidenceBadge, CONFIDENCE_WARN_VALUE, CONFIDENCE_STALE_VALUE,
|
|
5
|
+
CONFIDENCE_WARN_DAYS } from '../confidence.js';
|
|
6
|
+
import { ckgSlug, extractProblemConcept, ckgUpsertNode, ckgUpdateEdge } from '../ckg.js';
|
|
7
|
+
import type { CKGEdge, CKGNode } from '../ckg.js';
|
|
8
|
+
import { keywordSearch, tokenize } from '../search.js';
|
|
9
|
+
import { computeEmbedding, hasEmbedProvider } from '../embeddings.js';
|
|
10
|
+
|
|
11
|
+
// Git concurrency semaphore (for brain_from_git parallel workers)
|
|
12
|
+
let _gitSemCount = 0;
|
|
13
|
+
const _GIT_SEM_MAX = 10;
|
|
14
|
+
const _gitSemQueue: Array<() => void> = [];
|
|
15
|
+
function _gitSemAcquire(): Promise<void> {
|
|
16
|
+
if (_gitSemCount < _GIT_SEM_MAX) { _gitSemCount++; return Promise.resolve(); }
|
|
17
|
+
return new Promise(resolve => _gitSemQueue.push(resolve));
|
|
18
|
+
}
|
|
19
|
+
function _gitSemRelease(): void {
|
|
20
|
+
const next = _gitSemQueue.shift();
|
|
21
|
+
if (next) { next(); } else { _gitSemCount--; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type GetConnection = (instanceId: string) => Promise<Redis>;
|
|
25
|
+
type ApiFetch = <T>(path: string, options?: RequestInit) => Promise<T>;
|
|
26
|
+
|
|
27
|
+
export const FEDBRAIN_TOOL_NAMES = new Set([
|
|
28
|
+
'madc_deliberate', 'cls_ingest', 'cls_install_hooks', 'fedbrain_contribute', 'fedbrain_search',
|
|
29
|
+
'fedbrain_confirm', 'fedbrain_status', 'brain_federate', 'crystal_view', 'compact_recover',
|
|
30
|
+
'brain_from_git', 'brain_predict_failures',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
export async function handleFedbrainTool(
|
|
34
|
+
name: string,
|
|
35
|
+
args: Record<string, unknown>,
|
|
36
|
+
getConnection: GetConnection,
|
|
37
|
+
apiFetch: ApiFetch,
|
|
38
|
+
): Promise<string | null> {
|
|
39
|
+
switch (name) {
|
|
40
|
+
case 'madc_deliberate': {
|
|
41
|
+
const { instance_id, topic } = args as { instance_id: string; topic: string };
|
|
42
|
+
const redis = await getConnection(instance_id);
|
|
43
|
+
|
|
44
|
+
const historyRaw = await redis.lrange(`cachly:lessons:${topic}`, 0, -1);
|
|
45
|
+
const history = historyRaw.map(r => { try { return JSON.parse(r) as { outcome: string; what_worked?: string; what_failed?: string; ts?: string }; } catch { return null; } }).filter(Boolean) as Array<{ outcome: string; what_worked?: string; what_failed?: string; ts?: string }>;
|
|
46
|
+
|
|
47
|
+
if (history.length < 2) {
|
|
48
|
+
return [
|
|
49
|
+
`🗳️ **MADC: "${topic}"**`, '',
|
|
50
|
+
`Not enough history for deliberation (need ≥ 2 entries, found ${history.length}).`,
|
|
51
|
+
'', `Call \`learn_from_attempts\` with conflicting outcomes to trigger deliberation.`,
|
|
52
|
+
].join('\n');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Specialist agents and their domain keywords
|
|
56
|
+
const AGENTS = [
|
|
57
|
+
{ name: 'InfraAgent', domains: ['infra', 'k8s', 'docker', 'server', 'wireguard', 'helm'] },
|
|
58
|
+
{ name: 'AuthAgent', domains: ['auth', 'jwt', 'keycloak', 'oauth', 'oidc', 'token'] },
|
|
59
|
+
{ name: 'DeployAgent', domains: ['deploy', 'ci', 'pipeline', 'rsync', 'release'] },
|
|
60
|
+
{ name: 'DatabaseAgent', domains: ['db', 'gorm', 'migration', 'postgres', 'clickhouse', 'redis'] },
|
|
61
|
+
{ name: 'DebugAgent', domains: ['debug', 'panic', 'race', 'nil', 'fix', 'error'] },
|
|
62
|
+
{ name: 'APIAgent', domains: ['api', 'http', 'grpc', 'rest', 'fiber', 'web'] },
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
const topicDomain = topic.split(':')[0] ?? '';
|
|
66
|
+
const relevantAgents = AGENTS.filter(a => a.domains.some(d => topicDomain === d || topic.includes(d)));
|
|
67
|
+
const votingAgents = relevantAgents.length > 0 ? relevantAgents : AGENTS;
|
|
68
|
+
|
|
69
|
+
// Measure each agent's CKG coverage in their domains
|
|
70
|
+
const agentCoverage = new Map<string, number>();
|
|
71
|
+
for (const agent of votingAgents) {
|
|
72
|
+
let edgeCount = 0;
|
|
73
|
+
for (const domain of agent.domains) {
|
|
74
|
+
const nodeKeys: string[] = [];
|
|
75
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:${domain}*`, count: 50 });
|
|
76
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
77
|
+
edgeCount += nodeKeys.length;
|
|
78
|
+
}
|
|
79
|
+
agentCoverage.set(agent.name, edgeCount);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const successLessons = history.filter(l => l.outcome === 'success' || l.outcome === 'partial');
|
|
83
|
+
const failureLessons = history.filter(l => l.outcome === 'failure');
|
|
84
|
+
|
|
85
|
+
if (failureLessons.length === 0) {
|
|
86
|
+
return [
|
|
87
|
+
`🗳️ **MADC: "${topic}"**`, '',
|
|
88
|
+
`No contradictions found — all ${successLessons.length} entries have non-failure outcomes.`,
|
|
89
|
+
'', `Use \`ckg_inspect(concept="${ckgSlug(topic)}")\` to explore the confidence graph.`,
|
|
90
|
+
].join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Agent voting logic
|
|
94
|
+
const votes: Array<{ agent: string; vote: 'success' | 'failure' | 'abstain'; coverage: number; reason: string }> = [];
|
|
95
|
+
for (const agent of votingAgents) {
|
|
96
|
+
const coverage = agentCoverage.get(agent.name) ?? 0;
|
|
97
|
+
let vote: 'success' | 'failure' | 'abstain';
|
|
98
|
+
let reason: string;
|
|
99
|
+
if (coverage < 2) {
|
|
100
|
+
vote = 'abstain'; reason = 'insufficient domain coverage';
|
|
101
|
+
} else if (successLessons.length >= failureLessons.length * 2) {
|
|
102
|
+
vote = 'success'; reason = `${successLessons.length}/${history.length} entries confirm success`;
|
|
103
|
+
} else if (failureLessons.length >= successLessons.length * 2) {
|
|
104
|
+
vote = 'failure'; reason = `${failureLessons.length}/${history.length} entries confirm failure`;
|
|
105
|
+
} else {
|
|
106
|
+
vote = 'abstain'; reason = `contested (${successLessons.length} success vs ${failureLessons.length} failure)`;
|
|
107
|
+
}
|
|
108
|
+
votes.push({ agent: agent.name, vote, coverage, reason });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const successVotes = votes.filter(v => v.vote === 'success').length;
|
|
112
|
+
const failureVotes = votes.filter(v => v.vote === 'failure').length;
|
|
113
|
+
const abstainVotes = votes.filter(v => v.vote === 'abstain').length;
|
|
114
|
+
|
|
115
|
+
let resolution: 'unanimous_success' | 'unanimous_failure' | 'contested';
|
|
116
|
+
let resolutionText: string;
|
|
117
|
+
if (successVotes > 0 && failureVotes === 0) {
|
|
118
|
+
resolution = 'unanimous_success';
|
|
119
|
+
resolutionText = `✅ **Unanimous: SUCCESS** — ${successVotes} agent(s) confirm, ${abstainVotes} abstain`;
|
|
120
|
+
} else if (failureVotes > 0 && successVotes === 0) {
|
|
121
|
+
resolution = 'unanimous_failure';
|
|
122
|
+
resolutionText = `❌ **Unanimous: FAILURE** — ${failureVotes} agent(s) confirm, ${abstainVotes} abstain`;
|
|
123
|
+
} else {
|
|
124
|
+
resolution = 'contested';
|
|
125
|
+
resolutionText = `⚠️ **CONTESTED** — ${successVotes} success votes, ${failureVotes} failure votes, ${abstainVotes} abstain`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Store resolution as CKG node
|
|
129
|
+
const resNodeId = ckgSlug(`resolution:${topic}`);
|
|
130
|
+
const resNode = {
|
|
131
|
+
id: resNodeId, domain: 'resolution', type: 'resolution', count: 1,
|
|
132
|
+
ts: new Date().toISOString(), resolution, topic,
|
|
133
|
+
votes: { success: successVotes, failure: failureVotes, abstain: abstainVotes },
|
|
134
|
+
};
|
|
135
|
+
await redis.set(`cachly:ckg:node:${resNodeId}`, JSON.stringify(resNode));
|
|
136
|
+
|
|
137
|
+
// Write contradicts edge if contested; decay loser confidence to 0.1 if unanimous
|
|
138
|
+
if (resolution === 'contested') {
|
|
139
|
+
await ckgUpdateEdge(redis, ckgSlug(topic), 'contradicts', resNodeId, false);
|
|
140
|
+
} else {
|
|
141
|
+
// Unanimous — demote the losing side's edges to near-zero confidence
|
|
142
|
+
const loserOutcome = resolution === 'unanimous_success' ? 'failure' : 'success';
|
|
143
|
+
const loserLessons = (loserOutcome === 'failure' ? failureLessons : successLessons);
|
|
144
|
+
if (loserLessons.length > 0) {
|
|
145
|
+
// Decay all 'fixes' edges from this concept that contradict the resolution
|
|
146
|
+
const fromKeys = await redis.smembers(`cachly:ckg:idx:from:${ckgSlug(topic)}`);
|
|
147
|
+
for (const fk of fromKeys) {
|
|
148
|
+
const er = await redis.get(fk);
|
|
149
|
+
if (!er) continue;
|
|
150
|
+
try {
|
|
151
|
+
const edge: CKGEdge = JSON.parse(er);
|
|
152
|
+
if (edge.edgeType === 'fixes' && edge.confidence > 0.15) {
|
|
153
|
+
if (resolution === 'unanimous_failure') {
|
|
154
|
+
// Fix was wrong — decay to 0.1
|
|
155
|
+
edge.confidence = 0.1;
|
|
156
|
+
edge.last_updated = new Date().toISOString();
|
|
157
|
+
await redis.set(fk, JSON.stringify(edge));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
} catch { /* skip corrupt edges */ }
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// Remove the conflict marker — deliberation resolved it
|
|
164
|
+
await redis.del(`cachly:ckg:conflict:${ckgSlug(topic)}`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const lines = [
|
|
168
|
+
`🗳️ **MADC Deliberation: "${topic}"**`, '',
|
|
169
|
+
`📊 Evidence: ${successLessons.length} success/partial vs ${failureLessons.length} failure entries (${history.length} total)`,
|
|
170
|
+
'', `**Voting agents (${votingAgents.length}):**`,
|
|
171
|
+
...votes.map(v => {
|
|
172
|
+
const icon = v.vote === 'success' ? '✅' : v.vote === 'failure' ? '❌' : '⬜';
|
|
173
|
+
const covBar = '▓'.repeat(Math.min(v.coverage, 5)) + '░'.repeat(Math.max(0, 5 - v.coverage));
|
|
174
|
+
return ` ${icon} **${v.agent}** [${covBar}] ${v.coverage} CKG edges — ${v.reason}`;
|
|
175
|
+
}),
|
|
176
|
+
'', resolutionText, '',
|
|
177
|
+
];
|
|
178
|
+
|
|
179
|
+
if (resolution === 'unanimous_success') {
|
|
180
|
+
lines.push(`🔧 Failure entries superseded — store confirmed lesson: \`learn_from_attempts(topic="${topic}", outcome="success", ...)\``);
|
|
181
|
+
} else if (resolution === 'unanimous_failure') {
|
|
182
|
+
lines.push(`🚫 Success claims unconfirmed — re-verify: \`recall_best_solution(topic="${topic}")\``);
|
|
183
|
+
} else {
|
|
184
|
+
lines.push(`⚠️ Contested — run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${ckgSlug(topic)}")\``);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
lines.push('', `📝 Resolution node: \`cachly:ckg:node:${resNodeId}\``);
|
|
188
|
+
return lines.join('\n');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ── Layer 5: CLS — cls_ingest ─────────────────────────────────────────────
|
|
192
|
+
case 'cls_ingest': {
|
|
193
|
+
const { instance_id, source, payload } = args as {
|
|
194
|
+
instance_id: string;
|
|
195
|
+
source: 'git_commit' | 'ci_outcome' | 'ide_diagnostic';
|
|
196
|
+
payload: Record<string, unknown>;
|
|
197
|
+
};
|
|
198
|
+
const redis = await getConnection(instance_id);
|
|
199
|
+
const ts = new Date().toISOString();
|
|
200
|
+
const clsKey = 'cachly:cls:events';
|
|
201
|
+
|
|
202
|
+
if (source === 'git_commit') {
|
|
203
|
+
const message = String(payload.message ?? '');
|
|
204
|
+
const sha = String(payload.sha ?? '');
|
|
205
|
+
const files = (Array.isArray(payload.files) ? payload.files : []) as string[];
|
|
206
|
+
|
|
207
|
+
const domain = /^fix/i.test(message) ? 'fix' : /^feat/i.test(message) ? 'feat' : /^refactor/i.test(message) ? 'refactor' : /^test/i.test(message) ? 'test' : 'commit';
|
|
208
|
+
const slug = `${domain}:${ckgSlug(message.slice(0, 60))}`;
|
|
209
|
+
const conceptId = ckgSlug(slug);
|
|
210
|
+
|
|
211
|
+
await ckgUpsertNode(redis, conceptId, domain, 'commit');
|
|
212
|
+
for (const f of files.slice(0, 10)) {
|
|
213
|
+
const fd = f.includes('auth') ? 'auth' : f.includes('api') ? 'api' : f.includes('infra') ? 'infra' : f.includes('web') ? 'web' : 'code';
|
|
214
|
+
const fileId = ckgSlug(`file:${fd}`);
|
|
215
|
+
await ckgUpsertNode(redis, fileId, 'file', fd);
|
|
216
|
+
await ckgUpdateEdge(redis, conceptId, 'co-occurs', fileId, true);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const lessonObj = {
|
|
220
|
+
topic: slug, outcome: 'success' as const, what_worked: message, what_failed: '',
|
|
221
|
+
context: `CLS/git: sha=${sha}`, severity: 'minor' as const,
|
|
222
|
+
file_paths: files.slice(0, 10), commands: sha ? [`git show ${sha}`] : [],
|
|
223
|
+
tags: ['cls', 'git'], depends_on: [], recall_count: 0, ts, verified_at: ts,
|
|
224
|
+
confidence: 0.6, audit_trail: [{ ts, action: 'cls_git_commit' }], version: 3,
|
|
225
|
+
};
|
|
226
|
+
await redis.rpush(`cachly:lessons:${slug}`, JSON.stringify(lessonObj));
|
|
227
|
+
const existing = await redis.get(`cachly:lesson:best:${slug}`);
|
|
228
|
+
if (!existing) await redis.set(`cachly:lesson:best:${slug}`, JSON.stringify(lessonObj));
|
|
229
|
+
|
|
230
|
+
await redis.rpush(clsKey, JSON.stringify({ source, payload: { message, sha }, ts }));
|
|
231
|
+
await redis.ltrim(clsKey, -200, -1);
|
|
232
|
+
|
|
233
|
+
return [
|
|
234
|
+
`📨 **CLS Ingested: git_commit**`, '',
|
|
235
|
+
`Commit \`${sha.slice(0, 8) || '?'}\`: ${message.slice(0, 80)}`,
|
|
236
|
+
`Concept: \`${conceptId}\` (${domain}) · Files: ${files.length}`,
|
|
237
|
+
'', `🕸️ CKG: \`${conceptId}\` + ${files.length} file edges · Lesson: \`${slug}\``,
|
|
238
|
+
`💡 Inspect: \`ckg_inspect(concept="${domain}")\``,
|
|
239
|
+
].join('\n');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (source === 'ci_outcome') {
|
|
243
|
+
const status = String(payload.status ?? '');
|
|
244
|
+
const prev_status = String(payload.prev_status ?? '');
|
|
245
|
+
const job = String(payload.job ?? 'unknown');
|
|
246
|
+
const ciCtx = String(payload.context ?? '');
|
|
247
|
+
|
|
248
|
+
const isFixed = ['failure', 'red', 'error'].includes(prev_status) && ['success', 'green', 'passed'].includes(status);
|
|
249
|
+
const isBroken = ['success', 'green', 'passed'].includes(prev_status) && ['failure', 'red', 'error'].includes(status);
|
|
250
|
+
|
|
251
|
+
const slug = `ci:${ckgSlug(job)}`;
|
|
252
|
+
const conceptId = ckgSlug(slug);
|
|
253
|
+
await ckgUpsertNode(redis, conceptId, 'ci', 'job');
|
|
254
|
+
|
|
255
|
+
if (isFixed) {
|
|
256
|
+
const problemId = ckgSlug(`problem:${ckgSlug(job)}`);
|
|
257
|
+
await ckgUpsertNode(redis, problemId, 'problem', 'ci-failure');
|
|
258
|
+
await ckgUpdateEdge(redis, conceptId, 'fixes', problemId, true);
|
|
259
|
+
const lessonObj = {
|
|
260
|
+
topic: slug, outcome: 'success' as const,
|
|
261
|
+
what_worked: `CI job "${job}" went ${prev_status} → ${status}`,
|
|
262
|
+
what_failed: `Job "${job}" was failing`, context: `CLS/ci: ${ciCtx}`,
|
|
263
|
+
severity: 'major' as const, file_paths: [], commands: [], tags: ['cls', 'ci'],
|
|
264
|
+
depends_on: [], recall_count: 0, ts, verified_at: ts, confidence: 0.75,
|
|
265
|
+
audit_trail: [{ ts, action: 'cls_ci_fixed' }], version: 3,
|
|
266
|
+
};
|
|
267
|
+
await redis.rpush(`cachly:lessons:${slug}`, JSON.stringify(lessonObj));
|
|
268
|
+
await redis.set(`cachly:lesson:best:${slug}`, JSON.stringify(lessonObj));
|
|
269
|
+
} else if (isBroken) {
|
|
270
|
+
const causeId = ckgSlug(`cause:${ckgSlug(job)}`);
|
|
271
|
+
await ckgUpsertNode(redis, causeId, 'cause', 'ci-break');
|
|
272
|
+
await ckgUpdateEdge(redis, conceptId, 'causes', causeId, false);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
await redis.rpush(clsKey, JSON.stringify({ source, payload: { status, prev_status, job }, ts }));
|
|
276
|
+
await redis.ltrim(clsKey, -200, -1);
|
|
277
|
+
|
|
278
|
+
const statusIcon = isFixed ? '✅ Fixed' : isBroken ? '🔴 Broken' : '📊 Recorded';
|
|
279
|
+
return [
|
|
280
|
+
`📨 **CLS Ingested: ci_outcome**`, '',
|
|
281
|
+
`${statusIcon}: \`${job}\` — ${prev_status || '?'} → ${status}`,
|
|
282
|
+
isFixed ? `🔧 CKG \`fixes\` edge added (75% confidence)` : isBroken ? `⚡ CKG \`causes\` edge added` : `📊 State recorded`,
|
|
283
|
+
`💡 Lesson: \`${slug}\` | Predict: \`brain_predict(context="${job}")\``,
|
|
284
|
+
].join('\n');
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (source === 'ide_diagnostic') {
|
|
288
|
+
const error = String(payload.error ?? '');
|
|
289
|
+
const fix = String(payload.fix ?? '');
|
|
290
|
+
const file = String(payload.file ?? '');
|
|
291
|
+
|
|
292
|
+
const errorConcept = extractProblemConcept(error) ?? 'unknown-error';
|
|
293
|
+
const slug = `debug:${ckgSlug(errorConcept)}`;
|
|
294
|
+
const conceptId = ckgSlug(slug);
|
|
295
|
+
const problemId = ckgSlug(`problem:${errorConcept}`);
|
|
296
|
+
|
|
297
|
+
await ckgUpsertNode(redis, conceptId, 'debug', 'diagnostic');
|
|
298
|
+
await ckgUpsertNode(redis, problemId, 'problem', 'compiler-error');
|
|
299
|
+
await ckgUpdateEdge(redis, conceptId, 'fixes', problemId, true);
|
|
300
|
+
|
|
301
|
+
const lessonObj = {
|
|
302
|
+
topic: slug, outcome: 'success' as const, what_worked: fix, what_failed: error,
|
|
303
|
+
context: `CLS/ide: ${file}`, severity: 'minor' as const,
|
|
304
|
+
file_paths: file ? [file] : [], commands: [], tags: ['cls', 'ide-diagnostic'],
|
|
305
|
+
depends_on: [], recall_count: 0, ts, verified_at: ts, confidence: 0.65,
|
|
306
|
+
audit_trail: [{ ts, action: 'cls_ide_diagnostic' }], version: 3,
|
|
307
|
+
};
|
|
308
|
+
await redis.rpush(`cachly:lessons:${slug}`, JSON.stringify(lessonObj));
|
|
309
|
+
const existingL = await redis.get(`cachly:lesson:best:${slug}`);
|
|
310
|
+
if (!existingL) await redis.set(`cachly:lesson:best:${slug}`, JSON.stringify(lessonObj));
|
|
311
|
+
|
|
312
|
+
await redis.rpush(clsKey, JSON.stringify({ source, payload: { error: error.slice(0, 60), fix: fix.slice(0, 60), file }, ts }));
|
|
313
|
+
await redis.ltrim(clsKey, -200, -1);
|
|
314
|
+
|
|
315
|
+
return [
|
|
316
|
+
`📨 **CLS Ingested: ide_diagnostic**`, '',
|
|
317
|
+
`Error: \`${error.slice(0, 80)}\``,
|
|
318
|
+
`Fix: ${fix.slice(0, 100)}`,
|
|
319
|
+
file ? `File: \`${file}\`` : '',
|
|
320
|
+
'', `🕸️ CKG: \`${conceptId}\` → fixes → \`${problemId}\` | Lesson: \`${slug}\``,
|
|
321
|
+
].filter(l => l !== '').join('\n');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return `❌ Unknown CLS source: "${source}". Valid: git_commit, ci_outcome, ide_diagnostic`;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ── Layer 5: CLS — cls_install_hooks ─────────────────────────────────────
|
|
328
|
+
case 'cls_install_hooks': {
|
|
329
|
+
const { instance_id, repo_path = '.', hooks = ['git', 'ci'] } = args as {
|
|
330
|
+
instance_id: string; repo_path?: string; hooks?: string[];
|
|
331
|
+
};
|
|
332
|
+
const hooksArr = Array.isArray(hooks) ? hooks : ['git', 'ci'];
|
|
333
|
+
const lines: string[] = [`🔌 **CLS Hook Installation Guide**\n`];
|
|
334
|
+
|
|
335
|
+
if (hooksArr.includes('git')) {
|
|
336
|
+
const hookScript = [
|
|
337
|
+
`#!/bin/sh`,
|
|
338
|
+
`# cachly CLS — Continuous Learning Stream git hook`,
|
|
339
|
+
`# Installed by cls_install_hooks · runs silently on every commit`,
|
|
340
|
+
`INSTANCE="${instance_id}"`,
|
|
341
|
+
`SHA=$(git rev-parse HEAD 2>/dev/null || echo "")`,
|
|
342
|
+
`MSG=$(git log -1 --pretty=%B 2>/dev/null | head -1)`,
|
|
343
|
+
`FILES=$(git diff-tree --no-commit-id -r --name-only HEAD 2>/dev/null | tr '\\n' ',' | sed 's/,$//')`,
|
|
344
|
+
`node -e "`,
|
|
345
|
+
`const p={instance_id:'$INSTANCE',source:'git_commit',payload:{message:$(echo "$MSG" | jq -R . 2>/dev/null || echo '"commit"'),sha:'$SHA',files:'$FILES'.split(',').filter(Boolean)}};`,
|
|
346
|
+
`try{require('child_process').execSync('npx @cachly-dev/mcp-server@latest cls-ingest \\''+JSON.stringify(p)+'\\'',{stdio:'ignore',timeout:5000})}catch(e){}`,
|
|
347
|
+
`" 2>/dev/null &`,
|
|
348
|
+
`exit 0`,
|
|
349
|
+
].join('\n');
|
|
350
|
+
|
|
351
|
+
lines.push(`### Git post-commit hook`);
|
|
352
|
+
lines.push(`**Quick install (run once per repo):**`);
|
|
353
|
+
lines.push('```sh');
|
|
354
|
+
lines.push(`cat > ${repo_path}/.git/hooks/post-commit << 'HOOK'`);
|
|
355
|
+
lines.push(hookScript);
|
|
356
|
+
lines.push(`HOOK`);
|
|
357
|
+
lines.push(`chmod +x ${repo_path}/.git/hooks/post-commit`);
|
|
358
|
+
lines.push('```');
|
|
359
|
+
lines.push(`After install: every \`git commit\` automatically updates your brain's CKG.`);
|
|
360
|
+
lines.push('');
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (hooksArr.includes('ci')) {
|
|
364
|
+
lines.push(`### GitHub Actions CI outcome hook`);
|
|
365
|
+
lines.push(`**Add at the end of each job** (after build/test steps):`);
|
|
366
|
+
lines.push('```yaml');
|
|
367
|
+
lines.push(`- name: cachly CLS — record CI outcome`);
|
|
368
|
+
lines.push(` if: always()`);
|
|
369
|
+
lines.push(` run: |`);
|
|
370
|
+
lines.push(` node -e "`);
|
|
371
|
+
lines.push(` const r=require('https');`);
|
|
372
|
+
lines.push(` const d=JSON.stringify({instance_id:'${instance_id}',source:'ci_outcome',payload:{`);
|
|
373
|
+
lines.push(` status:'\${{ job.status }}',prev_status:'unknown',job:'\${{ github.job }}',`);
|
|
374
|
+
lines.push(` context:'github-actions run \${{ github.run_number }}'}});`);
|
|
375
|
+
lines.push(` r.request({hostname:'api.cachly.dev',path:'/api/v1/cls/ingest',method:'POST',`);
|
|
376
|
+
lines.push(` headers:{'Content-Type':'application/json','Authorization':'Bearer \$CACHLY_JWT',`);
|
|
377
|
+
lines.push(` 'Content-Length':d.length}},()=>{}).end(d);`);
|
|
378
|
+
lines.push(` " 2>/dev/null || true`);
|
|
379
|
+
lines.push(` env:`);
|
|
380
|
+
lines.push(` CACHLY_JWT: \${{ secrets.CACHLY_JWT }}`);
|
|
381
|
+
lines.push('```');
|
|
382
|
+
lines.push('');
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
lines.push(`💡 Once installed: \`brain_search(query="cls")\` to verify events are arriving.`);
|
|
386
|
+
lines.push(`📊 Monitor CKG growth: \`ckg_inspect(concept="ci")\` or \`ckg_inspect(concept="fix")\``);
|
|
387
|
+
return lines.join('\n');
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// ── Layer 6: FedBrain — fedbrain_contribute ───────────────────────────────
|
|
391
|
+
case 'fedbrain_contribute': {
|
|
392
|
+
const { instance_id, lesson_key, visibility = 'public' } = args as {
|
|
393
|
+
instance_id: string; lesson_key: string; visibility?: string;
|
|
394
|
+
};
|
|
395
|
+
const redis = await getConnection(instance_id);
|
|
396
|
+
|
|
397
|
+
const raw = await redis.get(`cachly:lesson:best:${lesson_key}`);
|
|
398
|
+
if (!raw) return `❌ Lesson \`${lesson_key}\` not found. Store it first with \`learn_from_attempts\`.`;
|
|
399
|
+
|
|
400
|
+
const lesson = JSON.parse(raw) as { topic: string; outcome: string; what_worked: string; what_failed?: string; tags?: string[]; commands?: string[]; severity?: string; ts?: string };
|
|
401
|
+
|
|
402
|
+
const domainTokens = [lesson.topic.split(':')[0], ...(lesson.tags ?? [])].filter(Boolean);
|
|
403
|
+
const domainFingerprint = [...new Set(domainTokens)].sort().join(',');
|
|
404
|
+
|
|
405
|
+
// HMAC certificate ID (non-reversible, privacy-safe)
|
|
406
|
+
const certContent = `${lesson.topic}:${lesson.outcome}:${lesson.what_worked}`;
|
|
407
|
+
const certId = createHmac('sha256', `cachly-fedbrain:${instance_id}`).update(certContent).digest('hex').slice(0, 16);
|
|
408
|
+
|
|
409
|
+
const cert = {
|
|
410
|
+
cert_id: certId, lesson_key, visibility,
|
|
411
|
+
domain_fingerprint: domainFingerprint,
|
|
412
|
+
contributed_at: new Date().toISOString(),
|
|
413
|
+
confirm_count: 0,
|
|
414
|
+
trust_score: lesson.outcome === 'success' ? 0.85 : 0.5,
|
|
415
|
+
};
|
|
416
|
+
await redis.set(`cachly:fedbrain:cert:${certId}`, JSON.stringify(cert));
|
|
417
|
+
await redis.sadd('cachly:fedbrain:contributed', certId);
|
|
418
|
+
|
|
419
|
+
// Try global commons via syndication API
|
|
420
|
+
let syndicationResult: string;
|
|
421
|
+
try {
|
|
422
|
+
await apiFetch('/api/v1/syndication/contribute', {
|
|
423
|
+
method: 'POST',
|
|
424
|
+
body: JSON.stringify({
|
|
425
|
+
topic: lesson.topic, outcome: lesson.outcome,
|
|
426
|
+
what_worked: lesson.what_worked, what_failed: lesson.what_failed ?? '',
|
|
427
|
+
severity: lesson.severity ?? 'major', cert_id: certId,
|
|
428
|
+
domain_fingerprint: domainFingerprint, visibility,
|
|
429
|
+
}),
|
|
430
|
+
});
|
|
431
|
+
syndicationResult = `✅ Contributed to global commons`;
|
|
432
|
+
} catch {
|
|
433
|
+
syndicationResult = `📦 Stored locally (commons API unavailable — will sync when online)`;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
return [
|
|
437
|
+
`🌐 **FedBrain Contribute: "${lesson_key}"**`, '',
|
|
438
|
+
`📜 Certificate: \`${certId}\``,
|
|
439
|
+
`🏷️ Domain fingerprint: ${domainTokens.slice(0, 6).map(t => `\`${t}\``).join(', ')}`,
|
|
440
|
+
`🔒 Visibility: ${visibility}`,
|
|
441
|
+
'', syndicationResult, '',
|
|
442
|
+
`💡 At 10 independent confirms → 🏆 Gold Standard`,
|
|
443
|
+
`🔍 Search: \`fedbrain_search(query="${lesson.topic.split(':').slice(-1)[0]}")\``,
|
|
444
|
+
].join('\n');
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ── Layer 6: FedBrain — fedbrain_search ──────────────────────────────────
|
|
448
|
+
case 'fedbrain_search': {
|
|
449
|
+
const { instance_id, query, context_hints = [], limit = 10 } = args as {
|
|
450
|
+
instance_id: string; query: string; context_hints?: string[]; limit?: number;
|
|
451
|
+
};
|
|
452
|
+
const redis = await getConnection(instance_id);
|
|
453
|
+
|
|
454
|
+
// Build local domain context from contributed certificates + explicit hints
|
|
455
|
+
const contribIds = await redis.smembers('cachly:fedbrain:contributed');
|
|
456
|
+
const localDomains = new Map<string, number>();
|
|
457
|
+
for (const certId of contribIds.slice(0, 30)) {
|
|
458
|
+
const certRaw = await redis.get(`cachly:fedbrain:cert:${certId}`);
|
|
459
|
+
if (!certRaw) continue;
|
|
460
|
+
try {
|
|
461
|
+
const cert = JSON.parse(certRaw) as { domain_fingerprint?: string };
|
|
462
|
+
for (const d of (cert.domain_fingerprint ?? '').split(',').filter(Boolean)) {
|
|
463
|
+
localDomains.set(d, (localDomains.get(d) ?? 0) + 1);
|
|
464
|
+
}
|
|
465
|
+
} catch { /* skip */ }
|
|
466
|
+
}
|
|
467
|
+
for (const hint of (Array.isArray(context_hints) ? context_hints : [])) {
|
|
468
|
+
localDomains.set(hint.toLowerCase(), (localDomains.get(hint.toLowerCase()) ?? 0) + 2);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Search global commons
|
|
472
|
+
type SynResult = { id: string; topic: string; category: string; outcome: string; what_worked: string; what_failed?: string; severity: string; confirm_count: number; created_at: string; domain_fingerprint?: string };
|
|
473
|
+
let results: SynResult[] = [];
|
|
474
|
+
try {
|
|
475
|
+
const params = new URLSearchParams({ q: query, limit: String(Math.min((limit as number) * 2, 50)) });
|
|
476
|
+
const res = await apiFetch<{ results: SynResult[]; count: number }>(`/api/v1/syndication/search?${params}`);
|
|
477
|
+
results = res.results ?? [];
|
|
478
|
+
} catch {
|
|
479
|
+
// Fallback: search local lessons
|
|
480
|
+
const lessonKeys: string[] = [];
|
|
481
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 200 });
|
|
482
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
483
|
+
for (const k of lessonKeys.slice(0, 60)) {
|
|
484
|
+
const r = await redis.get(k);
|
|
485
|
+
if (!r) continue;
|
|
486
|
+
try {
|
|
487
|
+
const l = JSON.parse(r) as { topic: string; outcome: string; what_worked?: string; what_failed?: string; severity?: string; ts?: string };
|
|
488
|
+
const haystack = `${l.topic} ${l.what_worked ?? ''} ${l.what_failed ?? ''}`.toLowerCase();
|
|
489
|
+
if (query.toLowerCase().split(/\s+/).some(t => t.length > 2 && haystack.includes(t))) {
|
|
490
|
+
results.push({ id: k.split(':').pop() ?? k, topic: l.topic, category: l.topic.split(':')[0], outcome: l.outcome, what_worked: l.what_worked ?? '', severity: l.severity ?? 'major', confirm_count: 0, created_at: l.ts ?? new Date().toISOString() });
|
|
491
|
+
}
|
|
492
|
+
} catch { /* skip */ }
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
if (results.length === 0) {
|
|
497
|
+
return [`🌐 **FedBrain Search: "${query}"**`, '', `No results. Contribute: \`fedbrain_contribute(lesson_key="fix:...")\``].join('\n');
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// Context-weighted ranking
|
|
501
|
+
const ranked = results.map(r => {
|
|
502
|
+
const rDomains = (r.domain_fingerprint ?? r.category ?? '').split(',').filter(Boolean);
|
|
503
|
+
const overlap = rDomains.reduce((s, d) => s + (localDomains.get(d) ?? 0), 0);
|
|
504
|
+
const contextScore = localDomains.size > 0 ? overlap / Math.max(1, localDomains.size + rDomains.length) : 0;
|
|
505
|
+
const confirmedScore = Math.min(1, r.confirm_count / 10);
|
|
506
|
+
const weightedScore = (contextScore * 0.4) + (confirmedScore * 0.4) + (r.outcome === 'success' ? 0.2 : 0);
|
|
507
|
+
return { ...r, weightedScore, isGoldStandard: r.confirm_count >= 10 };
|
|
508
|
+
}).sort((a, b) => b.weightedScore - a.weightedScore).slice(0, limit as number);
|
|
509
|
+
|
|
510
|
+
const lines = [`🌐 **FedBrain Search: "${query}"** — ${ranked.length} result${ranked.length !== 1 ? 's' : ''} (context-weighted)\n`];
|
|
511
|
+
for (const r of ranked) {
|
|
512
|
+
const icon = r.outcome === 'success' ? '✅' : r.outcome === 'failure' ? '❌' : '⚠️';
|
|
513
|
+
const goldBadge = r.isGoldStandard ? ' 🏆 _Gold Standard_' : r.confirm_count >= 3 ? ` ✓${r.confirm_count}` : '';
|
|
514
|
+
const ctxPct = Math.round(r.weightedScore * 100);
|
|
515
|
+
lines.push(`${icon}${goldBadge} **\`${r.topic}\`** [ctx: ${ctxPct}%]`);
|
|
516
|
+
if (r.what_worked) lines.push(` ✅ ${r.what_worked.slice(0, 150)}`);
|
|
517
|
+
if (r.what_failed) lines.push(` ❌ ${r.what_failed.slice(0, 80)}`);
|
|
518
|
+
lines.push(` _${r.confirm_count} confirm${r.confirm_count !== 1 ? 's' : ''} | \`${r.id.slice(0, 12)}\`_`, '');
|
|
519
|
+
}
|
|
520
|
+
if (localDomains.size > 0) {
|
|
521
|
+
const topDomains = [...localDomains.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([d, n]) => `\`${d}\`(${n})`).join(', ');
|
|
522
|
+
lines.push(`🎯 Your context: ${topDomains}`);
|
|
523
|
+
}
|
|
524
|
+
lines.push(`💡 Confirm: \`fedbrain_confirm(topic="<topic>", outcome="worked")\``);
|
|
525
|
+
return lines.join('\n');
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// ── Layer 6: FedBrain — fedbrain_confirm ─────────────────────────────────
|
|
529
|
+
case 'fedbrain_confirm': {
|
|
530
|
+
const { instance_id, topic, outcome } = args as {
|
|
531
|
+
instance_id: string; topic: string; outcome: 'worked' | 'partially_worked' | 'did_not_work';
|
|
532
|
+
};
|
|
533
|
+
const redis = await getConnection(instance_id);
|
|
534
|
+
const ts = new Date().toISOString();
|
|
535
|
+
|
|
536
|
+
const confirmEntry = JSON.stringify({ topic, outcome, ts });
|
|
537
|
+
await redis.rpush('cachly:fedbrain:confirmations', confirmEntry);
|
|
538
|
+
await redis.ltrim('cachly:fedbrain:confirmations', -200, -1);
|
|
539
|
+
|
|
540
|
+
// Update local CKG confidence
|
|
541
|
+
const worked = outcome === 'worked';
|
|
542
|
+
const partial = outcome === 'partially_worked';
|
|
543
|
+
await ckgUpdateEdge(redis, ckgSlug(topic), 'fixes', ckgSlug(`syndicated:${topic}`), worked, partial);
|
|
544
|
+
|
|
545
|
+
// Propagate to global commons
|
|
546
|
+
let propResult: string;
|
|
547
|
+
try {
|
|
548
|
+
await apiFetch('/api/v1/syndication/confirm', { method: 'POST', body: JSON.stringify({ topic, outcome }) });
|
|
549
|
+
propResult = `✅ Confirmation propagated to global commons`;
|
|
550
|
+
} catch {
|
|
551
|
+
await redis.rpush('cachly:fedbrain:pending_confirms', confirmEntry);
|
|
552
|
+
await redis.ltrim('cachly:fedbrain:pending_confirms', -50, -1);
|
|
553
|
+
propResult = `📦 Queued locally (API unavailable — will propagate on next online session)`;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const icon = worked ? '✅' : partial ? '⚠️' : '❌';
|
|
557
|
+
return [
|
|
558
|
+
`${icon} **FedBrain Confirm: "${topic}"** → ${outcome}`, '',
|
|
559
|
+
propResult, '',
|
|
560
|
+
`🕸️ CKG confidence ${worked || partial ? 'boosted' : 'reduced'} for \`${ckgSlug(topic)}\``,
|
|
561
|
+
`💡 Your confirmation helps other brains worldwide.`,
|
|
562
|
+
`📊 Status: \`fedbrain_status(instance_id="...")\``,
|
|
563
|
+
].join('\n');
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ── Layer 6: FedBrain — fedbrain_status ──────────────────────────────────
|
|
567
|
+
case 'fedbrain_status': {
|
|
568
|
+
const { instance_id } = args as { instance_id: string };
|
|
569
|
+
const redis = await getConnection(instance_id);
|
|
570
|
+
|
|
571
|
+
const contribIds = await redis.smembers('cachly:fedbrain:contributed');
|
|
572
|
+
const confirmsRaw = await redis.lrange('cachly:fedbrain:confirmations', -10, -1);
|
|
573
|
+
const pendingConfirms = await redis.llen('cachly:fedbrain:pending_confirms');
|
|
574
|
+
const confirms = confirmsRaw.map(r => { try { return JSON.parse(r) as { topic: string; outcome: string; ts: string }; } catch { return null; } }).filter(Boolean) as Array<{ topic: string; outcome: string; ts: string }>;
|
|
575
|
+
|
|
576
|
+
const certDetails: Array<{ cert_id: string; lesson_key: string; confirm_count: number; trust_score: number; isGold: boolean }> = [];
|
|
577
|
+
for (const certId of contribIds.slice(0, 15)) {
|
|
578
|
+
const raw = await redis.get(`cachly:fedbrain:cert:${certId}`);
|
|
579
|
+
if (!raw) continue;
|
|
580
|
+
try {
|
|
581
|
+
const cert = JSON.parse(raw) as { cert_id: string; lesson_key: string; confirm_count?: number; trust_score?: number };
|
|
582
|
+
certDetails.push({ cert_id: cert.cert_id, lesson_key: cert.lesson_key, confirm_count: cert.confirm_count ?? 0, trust_score: cert.trust_score ?? 0.5, isGold: (cert.confirm_count ?? 0) >= 10 });
|
|
583
|
+
} catch { /* skip */ }
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const lines = [
|
|
587
|
+
`🌐 **FedBrain Status**\n`,
|
|
588
|
+
`### 📤 Contributed Lessons: ${contribIds.length}`,
|
|
589
|
+
];
|
|
590
|
+
|
|
591
|
+
if (certDetails.length > 0) {
|
|
592
|
+
for (const c of certDetails) {
|
|
593
|
+
const goldBadge = c.isGold ? ' 🏆 Gold Standard' : '';
|
|
594
|
+
const confBar = '█'.repeat(Math.min(10, c.confirm_count)) + '░'.repeat(Math.max(0, 10 - c.confirm_count));
|
|
595
|
+
lines.push(` \`${c.lesson_key}\` [${confBar}] ×${c.confirm_count}${goldBadge}`);
|
|
596
|
+
}
|
|
597
|
+
} else {
|
|
598
|
+
lines.push(` _None yet. Contribute with \`fedbrain_contribute(lesson_key="fix:...")\`_`);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
lines.push('', `### 📥 Recent Confirmations: ${confirms.length}`);
|
|
602
|
+
if (confirms.length > 0) {
|
|
603
|
+
for (const c of confirms.slice(-5)) {
|
|
604
|
+
const icon = c.outcome === 'worked' ? '✅' : c.outcome === 'partially_worked' ? '⚠️' : '❌';
|
|
605
|
+
lines.push(` ${icon} \`${c.topic}\` — ${c.outcome} (${new Date(c.ts).toLocaleDateString('de-DE')})`);
|
|
606
|
+
}
|
|
607
|
+
} else {
|
|
608
|
+
lines.push(` _None yet. Confirm syndicated lessons with \`fedbrain_confirm\`_`);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
if (pendingConfirms > 0) {
|
|
612
|
+
lines.push('', `⚠️ ${pendingConfirms} confirmation${pendingConfirms !== 1 ? 's' : ''} pending propagation`);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
lines.push('', '---',
|
|
616
|
+
`**Contribute:** \`fedbrain_contribute(lesson_key="fix:...")\``,
|
|
617
|
+
`**Search:** \`fedbrain_search(query="...")\``,
|
|
618
|
+
`**Confirm:** \`fedbrain_confirm(topic="...", outcome="worked")\``,
|
|
619
|
+
);
|
|
620
|
+
return lines.join('\n');
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// ── Layer 6: FedBrain — brain_federate ───────────────────────────────────
|
|
624
|
+
case 'brain_federate': {
|
|
625
|
+
const { instance_id, source, domain, min_confidence = 0.6, dry_run = false } = args as {
|
|
626
|
+
instance_id: string; source: string; domain: string;
|
|
627
|
+
min_confidence?: number; dry_run?: boolean;
|
|
628
|
+
};
|
|
629
|
+
if (instance_id === source) return `❌ Source and destination cannot be the same brain.`;
|
|
630
|
+
|
|
631
|
+
const destRedis = await getConnection(instance_id);
|
|
632
|
+
const srcRedis = await getConnection(source);
|
|
633
|
+
|
|
634
|
+
const domainPattern = domain === '*' ? 'cachly:ckg:node:*' : `cachly:ckg:node:${domain}*`;
|
|
635
|
+
|
|
636
|
+
// Scan source CKG nodes matching the domain
|
|
637
|
+
const nodeKeys: string[] = [];
|
|
638
|
+
const nStream = srcRedis.scanStream({ match: domainPattern, count: 100 });
|
|
639
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
640
|
+
|
|
641
|
+
if (nodeKeys.length === 0) {
|
|
642
|
+
return [
|
|
643
|
+
`🧠 **brain_federate: "${domain}"**`, '',
|
|
644
|
+
`No CKG nodes found in source brain for domain \`${domain}\`.`,
|
|
645
|
+
`The source brain may not have knowledge in this area yet.`,
|
|
646
|
+
`Try: \`fedbrain_search(query="${domain}")\` to find global commons knowledge instead.`,
|
|
647
|
+
].join('\n');
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Transfer nodes + their outgoing edges
|
|
651
|
+
let nodesTransferred = 0;
|
|
652
|
+
let edgesTransferred = 0;
|
|
653
|
+
let lessonsTransferred = 0;
|
|
654
|
+
let skippedLowConf = 0;
|
|
655
|
+
const transferLog: string[] = [];
|
|
656
|
+
|
|
657
|
+
for (const nk of nodeKeys) {
|
|
658
|
+
const nodeRaw = await srcRedis.get(nk);
|
|
659
|
+
if (!nodeRaw) continue;
|
|
660
|
+
let node: CKGNode;
|
|
661
|
+
try { node = JSON.parse(nodeRaw); } catch { continue; }
|
|
662
|
+
|
|
663
|
+
if (!dry_run) await destRedis.set(nk, nodeRaw);
|
|
664
|
+
nodesTransferred++;
|
|
665
|
+
|
|
666
|
+
// Transfer outgoing edges for this node
|
|
667
|
+
const edgeKeys = await srcRedis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
668
|
+
for (const ek of edgeKeys) {
|
|
669
|
+
const edgeRaw = await srcRedis.get(ek);
|
|
670
|
+
if (!edgeRaw) continue;
|
|
671
|
+
let edge: CKGEdge;
|
|
672
|
+
try { edge = JSON.parse(edgeRaw); } catch { continue; }
|
|
673
|
+
if (edge.confidence < (min_confidence as number)) { skippedLowConf++; continue; }
|
|
674
|
+
if (!dry_run) {
|
|
675
|
+
await destRedis.set(ek, edgeRaw);
|
|
676
|
+
await destRedis.sadd(`cachly:ckg:idx:from:${edge.from}`, ek);
|
|
677
|
+
await destRedis.sadd(`cachly:ckg:idx:to:${edge.to}`, ek);
|
|
678
|
+
}
|
|
679
|
+
edgesTransferred++;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Transfer best-lesson for the same topic slug
|
|
683
|
+
const lessonKey = `cachly:lesson:best:${node.id}`;
|
|
684
|
+
const lessonRaw = await srcRedis.get(lessonKey);
|
|
685
|
+
if (lessonRaw) {
|
|
686
|
+
if (!dry_run) await destRedis.set(lessonKey, lessonRaw);
|
|
687
|
+
lessonsTransferred++;
|
|
688
|
+
if (transferLog.length < 8) {
|
|
689
|
+
try {
|
|
690
|
+
const l = JSON.parse(lessonRaw) as { topic: string; outcome: string; what_worked?: string };
|
|
691
|
+
const icon = l.outcome === 'success' ? '✅' : l.outcome === 'failure' ? '❌' : '⚠️';
|
|
692
|
+
transferLog.push(` ${icon} \`${l.topic}\` — ${(l.what_worked ?? '').slice(0, 80)}`);
|
|
693
|
+
} catch { /* skip */ }
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// Record federation provenance
|
|
699
|
+
if (!dry_run) {
|
|
700
|
+
const provEntry = JSON.stringify({
|
|
701
|
+
source, domain, transferred_at: new Date().toISOString(),
|
|
702
|
+
nodes: nodesTransferred, edges: edgesTransferred, lessons: lessonsTransferred,
|
|
703
|
+
});
|
|
704
|
+
await destRedis.rpush('cachly:fedbrain:federations', provEntry);
|
|
705
|
+
await destRedis.ltrim('cachly:fedbrain:federations', -50, -1);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const dryTag = dry_run ? ' (DRY RUN — no writes)' : '';
|
|
709
|
+
const lines = [
|
|
710
|
+
`🧠 **brain_federate: "${domain}"**${dryTag}`, '',
|
|
711
|
+
`📤 Source: \`${source}\``,
|
|
712
|
+
`📥 Destination: \`${instance_id}\``,
|
|
713
|
+
`🔍 Domain filter: \`${domain}\` | min_confidence: ${min_confidence}`,
|
|
714
|
+
'',
|
|
715
|
+
`### Transfer Summary`,
|
|
716
|
+
` 🕸️ CKG nodes: ${nodesTransferred}`,
|
|
717
|
+
` 🔗 CKG edges: ${edgesTransferred} (${skippedLowConf} skipped, confidence < ${min_confidence})`,
|
|
718
|
+
` 📚 Lessons: ${lessonsTransferred}`,
|
|
719
|
+
'',
|
|
720
|
+
];
|
|
721
|
+
if (transferLog.length > 0) {
|
|
722
|
+
lines.push(`### Sample lessons transferred:`, ...transferLog);
|
|
723
|
+
if (lessonsTransferred > transferLog.length) lines.push(` _... and ${lessonsTransferred - transferLog.length} more_`);
|
|
724
|
+
lines.push('');
|
|
725
|
+
}
|
|
726
|
+
if (dry_run) {
|
|
727
|
+
lines.push(`💡 Run without \`dry_run: true\` to apply the transfer.`);
|
|
728
|
+
} else {
|
|
729
|
+
lines.push(`✅ Transfer complete. Your brain now has the \`${domain}\` knowledge from \`${source}\`.`);
|
|
730
|
+
lines.push(`🔍 Explore: \`ckg_inspect(concept="${domain}")\` | \`recall_best_solution(topic="${domain}:...")\``);
|
|
731
|
+
}
|
|
732
|
+
return lines.join('\n');
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// ── crystal_view ──────────────────────────────────────────────────────────
|
|
736
|
+
case 'crystal_view': {
|
|
737
|
+
const { instance_id, show_raw = false } = args as { instance_id: string; show_raw?: boolean };
|
|
738
|
+
const redis = await getConnection(instance_id);
|
|
739
|
+
|
|
740
|
+
const raw = await redis.get('cachly:crystal:latest');
|
|
741
|
+
if (!raw) {
|
|
742
|
+
return [
|
|
743
|
+
`💎 **Memory Crystal: not yet created**`, '',
|
|
744
|
+
`No crystal found. Create one with \`memory_crystalize()\` to compress your accumulated wisdom.`,
|
|
745
|
+
'', `💡 Tip: run \`memory_crystalize\` monthly for best results.`,
|
|
746
|
+
].join('\n');
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
type Crystal = { label: string; ts: string; session_count: number; lesson_count: number; top_patterns: Array<{ category: string; insight: string; count: number }>; categories: string[]; created_from: string };
|
|
750
|
+
const crystal: Crystal = JSON.parse(raw);
|
|
751
|
+
const age = Math.floor((Date.now() - new Date(crystal.ts).getTime()) / 86400000);
|
|
752
|
+
const freshEmoji = age <= 7 ? '🟢' : age <= 30 ? '🟡' : '🔴';
|
|
753
|
+
|
|
754
|
+
const lines = [
|
|
755
|
+
`💎 **Memory Crystal: ${crystal.label}**`, '',
|
|
756
|
+
`📅 Created: ${new Date(crystal.ts).toLocaleDateString('de-DE')} (${age}d ago ${freshEmoji})`,
|
|
757
|
+
`📊 Compressed from: ${crystal.created_from}`,
|
|
758
|
+
`🗂️ Categories: ${crystal.categories.slice(0, 10).map(c => `\`${c}\``).join(', ')}${crystal.categories.length > 10 ? ` +${crystal.categories.length - 10} more` : ''}`,
|
|
759
|
+
'',
|
|
760
|
+
`**🔑 Top patterns (${crystal.top_patterns.length}):**`,
|
|
761
|
+
];
|
|
762
|
+
for (const p of crystal.top_patterns) {
|
|
763
|
+
lines.push(` • **${p.category}** (${p.count}×): ${p.insight.slice(0, 110)}`);
|
|
764
|
+
}
|
|
765
|
+
if (age > 30) {
|
|
766
|
+
lines.push('', `⚠️ Crystal is ${age}d old — run \`memory_crystalize()\` to refresh it.`);
|
|
767
|
+
}
|
|
768
|
+
if (show_raw) {
|
|
769
|
+
lines.push('', '```json', JSON.stringify(crystal, null, 2), '```');
|
|
770
|
+
}
|
|
771
|
+
lines.push('', `💡 Refresh: \`memory_crystalize()\` | Recover: \`compact_recover(instance_id="...")\``);
|
|
772
|
+
return lines.join('\n');
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ── compact_recover ───────────────────────────────────────────────────────
|
|
776
|
+
case 'compact_recover': {
|
|
777
|
+
const { instance_id, focus = '' } = args as { instance_id: string; focus?: string };
|
|
778
|
+
const redis = await getConnection(instance_id);
|
|
779
|
+
|
|
780
|
+
const lines = [`🔁 **Compact Recovery Briefing**\n`];
|
|
781
|
+
lines.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*\n`);
|
|
782
|
+
|
|
783
|
+
// 1. Memory Crystal
|
|
784
|
+
const crystalRaw = await redis.get('cachly:crystal:latest');
|
|
785
|
+
if (crystalRaw) {
|
|
786
|
+
type Crystal = { label: string; ts: string; session_count: number; lesson_count: number; top_patterns: Array<{ category: string; insight: string; count: number }> };
|
|
787
|
+
const crystal: Crystal = JSON.parse(crystalRaw);
|
|
788
|
+
lines.push(`### 💎 Memory Crystal: ${crystal.label}`);
|
|
789
|
+
lines.push(`Compressed from ${crystal.session_count} sessions, ${crystal.lesson_count} lessons.`);
|
|
790
|
+
const topN = focus
|
|
791
|
+
? crystal.top_patterns.filter(p => p.category.toLowerCase().includes(focus.toLowerCase()) || p.insight.toLowerCase().includes(focus.toLowerCase())).slice(0, 4)
|
|
792
|
+
: crystal.top_patterns.slice(0, 4);
|
|
793
|
+
for (const p of topN) lines.push(` • **${p.category}**: ${p.insight.slice(0, 100)}`);
|
|
794
|
+
lines.push('');
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// 2. Last session summary
|
|
798
|
+
const lastSession = await redis.get('cachly:session:last');
|
|
799
|
+
if (lastSession) {
|
|
800
|
+
type Session = { summary?: string; ts?: string; focus?: string };
|
|
801
|
+
const sess: Session = JSON.parse(lastSession);
|
|
802
|
+
lines.push(`### 🕐 Last Session`);
|
|
803
|
+
if (sess.focus) lines.push(`Focus: _${sess.focus}_`);
|
|
804
|
+
if (sess.summary) lines.push(`Summary: ${sess.summary.slice(0, 300)}`);
|
|
805
|
+
lines.push('');
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// 3. Session handoff
|
|
809
|
+
const handoff = await redis.get('cachly:session:handoff');
|
|
810
|
+
if (handoff) {
|
|
811
|
+
type Handoff = { remaining_tasks?: string[]; instructions?: string; context_summary?: string; blocked_on?: string };
|
|
812
|
+
const h: Handoff = JSON.parse(handoff);
|
|
813
|
+
lines.push(`### 📋 Handoff (from last window)`);
|
|
814
|
+
if (h.context_summary) lines.push(`Context: ${h.context_summary.slice(0, 200)}`);
|
|
815
|
+
if (h.remaining_tasks?.length) {
|
|
816
|
+
lines.push(`Remaining tasks:`);
|
|
817
|
+
for (const t of h.remaining_tasks.slice(0, 5)) lines.push(` • ${t}`);
|
|
818
|
+
}
|
|
819
|
+
if (h.instructions) lines.push(`⚠️ Instructions: ${h.instructions.slice(0, 200)}`);
|
|
820
|
+
if (h.blocked_on) lines.push(`🚧 Blocked on: ${h.blocked_on}`);
|
|
821
|
+
lines.push('');
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// 4. WIP registry
|
|
825
|
+
const wipRaw = await redis.get('cachly:ctx:wip-registry');
|
|
826
|
+
if (wipRaw) {
|
|
827
|
+
type Ctx = { content?: string };
|
|
828
|
+
const wip: Ctx = JSON.parse(wipRaw);
|
|
829
|
+
if (wip.content) {
|
|
830
|
+
lines.push(`### 🔧 WIP Registry`);
|
|
831
|
+
lines.push(wip.content.slice(0, 400));
|
|
832
|
+
lines.push('');
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// 5. Open failures (roadmap with status=blocked/in_progress)
|
|
837
|
+
const roadmapKeys: string[] = [];
|
|
838
|
+
const rStream = redis.scanStream({ match: 'cachly:roadmap:*', count: 100 });
|
|
839
|
+
await new Promise<void>((res, rej) => { rStream.on('data', (b: string[]) => roadmapKeys.push(...b)); rStream.on('end', res); rStream.on('error', rej); });
|
|
840
|
+
const openItems: Array<{ title: string; status: string; priority?: string }> = [];
|
|
841
|
+
for (const k of roadmapKeys.slice(0, 30)) {
|
|
842
|
+
const r = await redis.get(k);
|
|
843
|
+
if (!r) continue;
|
|
844
|
+
try {
|
|
845
|
+
const item = JSON.parse(r) as { title?: string; status?: string; priority?: string };
|
|
846
|
+
if (item.status === 'in_progress' || item.status === 'blocked') openItems.push({ title: item.title ?? k, status: item.status, priority: item.priority });
|
|
847
|
+
} catch { /* skip */ }
|
|
848
|
+
}
|
|
849
|
+
if (openItems.length > 0) {
|
|
850
|
+
lines.push(`### 🚧 Open Items`);
|
|
851
|
+
for (const i of openItems.slice(0, 5)) lines.push(` • [${i.status}] ${i.title}`);
|
|
852
|
+
lines.push('');
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// 6. Focus-relevant lessons
|
|
856
|
+
if (focus) {
|
|
857
|
+
const lessonKeys: string[] = [];
|
|
858
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 200 });
|
|
859
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
860
|
+
const relevant: Array<{ topic: string; what_worked: string }> = [];
|
|
861
|
+
for (const k of lessonKeys) {
|
|
862
|
+
const r = await redis.get(k);
|
|
863
|
+
if (!r) continue;
|
|
864
|
+
try {
|
|
865
|
+
const l = JSON.parse(r) as { topic: string; what_worked?: string };
|
|
866
|
+
if (l.topic.toLowerCase().includes(focus.toLowerCase()) && l.what_worked) {
|
|
867
|
+
relevant.push({ topic: l.topic, what_worked: l.what_worked });
|
|
868
|
+
}
|
|
869
|
+
} catch { /* skip */ }
|
|
870
|
+
}
|
|
871
|
+
if (relevant.length > 0) {
|
|
872
|
+
lines.push(`### 💡 Relevant Lessons for "${focus}"`);
|
|
873
|
+
for (const l of relevant.slice(0, 4)) lines.push(` • **${l.topic}**: ${l.what_worked.slice(0, 100)}`);
|
|
874
|
+
lines.push('');
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (lines.length <= 3) {
|
|
879
|
+
lines.push(`_No brain data found. Start accumulating knowledge with \`learn_from_attempts\` and \`session_start\`._`);
|
|
880
|
+
}
|
|
881
|
+
lines.push(`---`, `🧠 Brain is ready. Continue your work — full context restored.`);
|
|
882
|
+
return lines.join('\n');
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// ── brain_from_git ────────────────────────────────────────────────────────
|
|
886
|
+
case 'brain_from_git': {
|
|
887
|
+
const { instance_id, repo_path = '.', limit = 100, branch = 'HEAD', since = '' } = args as {
|
|
888
|
+
instance_id: string; repo_path?: string; limit?: number; branch?: string; since?: string;
|
|
889
|
+
};
|
|
890
|
+
const redis = await getConnection(instance_id);
|
|
891
|
+
const { execSync } = await import('node:child_process');
|
|
892
|
+
const { resolve } = await import('node:path');
|
|
893
|
+
|
|
894
|
+
const repoDir = resolve(repo_path);
|
|
895
|
+
const maxCommits = Math.min(Number(limit) || 100, 500);
|
|
896
|
+
|
|
897
|
+
// Semaphore: max 10 concurrent git subprocesses per MCP process
|
|
898
|
+
await _gitSemAcquire();
|
|
899
|
+
try {
|
|
900
|
+
// Verify it's a git repo
|
|
901
|
+
try {
|
|
902
|
+
execSync('git rev-parse --git-dir', { cwd: repoDir, stdio: 'pipe' });
|
|
903
|
+
} catch {
|
|
904
|
+
return `❌ Not a git repository: \`${repoDir}\`. Pass \`repo_path\` pointing to a git checkout.`;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// Build git log command
|
|
908
|
+
const sinceFlag = since ? `--since="${since}"` : '';
|
|
909
|
+
const logCmd = `git log ${branch} ${sinceFlag} --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n ${maxCommits}`;
|
|
910
|
+
|
|
911
|
+
let logOutput = '';
|
|
912
|
+
try {
|
|
913
|
+
logOutput = execSync(logCmd, { cwd: repoDir, encoding: 'utf-8', stdio: 'pipe' });
|
|
914
|
+
} catch (e) {
|
|
915
|
+
return `❌ git log failed: ${(e as Error).message}. Check \`repo_path\` and \`branch\`.`;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const commits = logOutput.trim().split('\n').filter(Boolean).map(line => {
|
|
919
|
+
const [sha, subject, date, author] = line.split('|||');
|
|
920
|
+
return { sha: (sha ?? '').trim(), subject: (subject ?? '').trim(), date: (date ?? '').trim(), author: (author ?? '').trim() };
|
|
921
|
+
});
|
|
922
|
+
|
|
923
|
+
if (commits.length === 0) {
|
|
924
|
+
return `⚠️ No commits found in \`${repoDir}\` on branch \`${branch}\`${since ? ` since ${since}` : ''}.`;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// Pattern classifiers
|
|
928
|
+
const classifyCommit = (subject: string): { category: string; outcome: 'success' | 'failure' | 'partial'; severity: 'critical' | 'major' | 'minor' } => {
|
|
929
|
+
const s = subject.toLowerCase();
|
|
930
|
+
if (/\b(fix|fixed|fixes|bug|hotfix|patch|revert|resolve|closes? #\d+)\b/.test(s)) {
|
|
931
|
+
const sev: 'critical' | 'major' | 'minor' = /\b(critical|crash|security|auth|data loss|outage|prod|production)\b/.test(s) ? 'critical' : /\b(major|breaking|regression|hotfix)\b/.test(s) ? 'major' : 'minor';
|
|
932
|
+
return { category: 'fix', outcome: 'success', severity: sev };
|
|
933
|
+
}
|
|
934
|
+
if (/\b(feat|feature|add|added|implement|new|introduce)\b/.test(s)) return { category: 'feat', outcome: 'success', severity: 'minor' };
|
|
935
|
+
if (/\b(refactor|clean|cleanup|improve|simplify|extract|rename)\b/.test(s)) return { category: 'refactor', outcome: 'success', severity: 'minor' };
|
|
936
|
+
if (/\b(perf|optimize|speed|cache|latency|memory|performance)\b/.test(s)) return { category: 'perf', outcome: 'success', severity: 'major' };
|
|
937
|
+
if (/\b(security|cve|auth|csrf|xss|sql|injection|sanitize|escape|encrypt)\b/.test(s)) return { category: 'security', outcome: 'success', severity: 'critical' };
|
|
938
|
+
if (/\b(deploy|ci|cd|build|docker|k8s|helm|infra|devops)\b/.test(s)) return { category: 'deploy', outcome: 'success', severity: 'major' };
|
|
939
|
+
if (/\b(test|spec|coverage|assert|mock|unit|integration)\b/.test(s)) return { category: 'test', outcome: 'success', severity: 'minor' };
|
|
940
|
+
return { category: 'chore', outcome: 'success', severity: 'minor' };
|
|
941
|
+
};
|
|
942
|
+
|
|
943
|
+
// Extract domain keywords from commit subject
|
|
944
|
+
const extractDomain = (subject: string): string => {
|
|
945
|
+
const s = subject.toLowerCase();
|
|
946
|
+
const tokens = s.replace(/[^a-z0-9\s\-_]/g, ' ').split(/\s+/).filter(t => t.length > 3 && !['that', 'this', 'with', 'from', 'when', 'into', 'also', 'some', 'were'].includes(t));
|
|
947
|
+
return tokens.slice(0, 3).join('-') || 'general';
|
|
948
|
+
};
|
|
949
|
+
|
|
950
|
+
const ts = new Date().toISOString();
|
|
951
|
+
let ingested = 0;
|
|
952
|
+
let skipped = 0;
|
|
953
|
+
const categoryCount = new Map<string, number>();
|
|
954
|
+
|
|
955
|
+
for (const commit of commits) {
|
|
956
|
+
if (!commit.subject) { skipped++; continue; }
|
|
957
|
+
const { category, outcome, severity } = classifyCommit(commit.subject);
|
|
958
|
+
const domain = extractDomain(commit.subject);
|
|
959
|
+
const topic = `${category}:${domain}`;
|
|
960
|
+
categoryCount.set(category, (categoryCount.get(category) ?? 0) + 1);
|
|
961
|
+
|
|
962
|
+
const lessonObj = {
|
|
963
|
+
topic, outcome, severity,
|
|
964
|
+
what_worked: commit.subject.slice(0, 200),
|
|
965
|
+
what_failed: '',
|
|
966
|
+
context: `git:${commit.sha.slice(0, 8)} by ${commit.author} on ${commit.date}`,
|
|
967
|
+
file_paths: [], commands: [`git show ${commit.sha.slice(0, 8)}`],
|
|
968
|
+
tags: ['brain_from_git', category, 'git-history'],
|
|
969
|
+
depends_on: [], recall_count: 0, ts, verified_at: ts,
|
|
970
|
+
confidence: 0.55, // lower confidence for auto-inferred lessons
|
|
971
|
+
audit_trail: [{ ts, action: 'brain_from_git', sha: commit.sha.slice(0, 8) }],
|
|
972
|
+
version: 3,
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
// Only store if no existing lesson for this topic (avoid overwriting higher-confidence lessons)
|
|
976
|
+
const existing = await redis.get(`cachly:lesson:best:${topic}`);
|
|
977
|
+
if (!existing) {
|
|
978
|
+
await redis.set(`cachly:lesson:best:${topic}`, JSON.stringify(lessonObj));
|
|
979
|
+
await redis.rpush(`cachly:lessons:${topic}`, JSON.stringify(lessonObj));
|
|
980
|
+
}
|
|
981
|
+
await redis.rpush('cachly:lessons:brain_from_git:all', JSON.stringify({ topic, sha: commit.sha.slice(0, 8), subject: commit.subject.slice(0, 60) }));
|
|
982
|
+
await redis.ltrim('cachly:lessons:brain_from_git:all', -500, -1);
|
|
983
|
+
|
|
984
|
+
// Update CKG
|
|
985
|
+
const conceptId = ckgSlug(topic);
|
|
986
|
+
await ckgUpsertNode(redis, conceptId, category, 'git-derived');
|
|
987
|
+
ingested++;
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const categoryBreakdown = [...categoryCount.entries()].sort((a, b) => b[1] - a[1]).map(([k, v]) => ` • **${k}** (${v})`).join('\n');
|
|
991
|
+
|
|
992
|
+
return [
|
|
993
|
+
`🔁 **brain_from_git: ${repoDir}**`, '',
|
|
994
|
+
`📂 Branch: \`${branch}\` | Processed: **${commits.length}** commits | Ingested: **${ingested}** lessons | Skipped: ${skipped}`,
|
|
995
|
+
``,
|
|
996
|
+
`**Breakdown by category:**`,
|
|
997
|
+
categoryBreakdown,
|
|
998
|
+
``,
|
|
999
|
+
`💡 New lessons are stored with confidence 0.55 (auto-inferred).`,
|
|
1000
|
+
`💡 As you confirm them via \`learn_from_attempts\`, confidence rises automatically.`,
|
|
1001
|
+
`🔍 Explore: \`brain_search(query="fix")\` | \`ckg_inspect(concept="deploy")\``,
|
|
1002
|
+
].join('\n');
|
|
1003
|
+
} finally {
|
|
1004
|
+
_gitSemRelease();
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// ── brain_predict_failures ─────────────────────────────────────────────────
|
|
1009
|
+
case 'brain_predict_failures': {
|
|
1010
|
+
const { instance_id, context: ctx, top_k = 5, format = 'detailed' } = args as {
|
|
1011
|
+
instance_id: string; context: string; top_k?: number; format?: 'brief' | 'detailed';
|
|
1012
|
+
};
|
|
1013
|
+
const redis = await getConnection(instance_id);
|
|
1014
|
+
|
|
1015
|
+
const ctxTokens = ctx.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g, ' ').split(/\s+/).filter(t => t.length > 2);
|
|
1016
|
+
|
|
1017
|
+
type FailurePred = { concept: string; failure: string; probability: number; fix?: string; topic?: string; source: 'ckg' | 'lesson' };
|
|
1018
|
+
const failures: FailurePred[] = [];
|
|
1019
|
+
|
|
1020
|
+
// Step 1: CKG — find 'causes' and 'degrades_under' edges from context tokens
|
|
1021
|
+
for (const token of ctxTokens.slice(0, 8)) {
|
|
1022
|
+
const nodeKeys: string[] = [];
|
|
1023
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
|
|
1024
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
1025
|
+
|
|
1026
|
+
for (const nk of nodeKeys.slice(0, 5)) {
|
|
1027
|
+
const nodeRaw = await redis.get(nk);
|
|
1028
|
+
if (!nodeRaw) continue;
|
|
1029
|
+
const node: CKGNode = JSON.parse(nodeRaw);
|
|
1030
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
1031
|
+
for (const ek of edgeKeys.slice(0, 20)) {
|
|
1032
|
+
const edgeRaw = await redis.get(ek);
|
|
1033
|
+
if (!edgeRaw) continue;
|
|
1034
|
+
const edge: CKGEdge = JSON.parse(edgeRaw);
|
|
1035
|
+
if (edge.edgeType !== 'causes' && edge.edgeType !== 'degrades_under') continue;
|
|
1036
|
+
|
|
1037
|
+
// Look up fix for this failure from CKG 'fixes' edges
|
|
1038
|
+
const fixEdgeKeys = await redis.smembers(`cachly:ckg:idx:from:${edge.to}`);
|
|
1039
|
+
let fix: string | undefined;
|
|
1040
|
+
for (const fek of fixEdgeKeys.slice(0, 10)) {
|
|
1041
|
+
const feRaw = await redis.get(fek);
|
|
1042
|
+
if (!feRaw) continue;
|
|
1043
|
+
const fe: CKGEdge = JSON.parse(feRaw);
|
|
1044
|
+
if (fe.edgeType === 'fixes') {
|
|
1045
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${fe.from}`);
|
|
1046
|
+
if (lessonRaw) {
|
|
1047
|
+
const lesson = JSON.parse(lessonRaw) as { what_worked?: string };
|
|
1048
|
+
fix = lesson.what_worked?.slice(0, 120);
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
failures.push({
|
|
1055
|
+
concept: node.id,
|
|
1056
|
+
failure: edge.to.replace(/-/g, ' '),
|
|
1057
|
+
probability: edge.confidence,
|
|
1058
|
+
fix,
|
|
1059
|
+
source: 'ckg',
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// Step 2: Lesson history — find failure-outcome lessons matching context
|
|
1066
|
+
const lessonKeys: string[] = [];
|
|
1067
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 300 });
|
|
1068
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
1069
|
+
|
|
1070
|
+
for (const k of lessonKeys.slice(0, 100)) {
|
|
1071
|
+
const r = await redis.get(k);
|
|
1072
|
+
if (!r) continue;
|
|
1073
|
+
try {
|
|
1074
|
+
const l = JSON.parse(r) as { topic: string; outcome: string; what_failed?: string; what_worked?: string; confidence?: number; severity?: string };
|
|
1075
|
+
if (l.outcome !== 'failure' && l.outcome !== 'partial') continue;
|
|
1076
|
+
if (!l.what_failed) continue;
|
|
1077
|
+
const haystack = `${l.topic} ${l.what_failed}`.toLowerCase();
|
|
1078
|
+
const matchScore = ctxTokens.filter(t => haystack.includes(t)).length / Math.max(1, ctxTokens.length);
|
|
1079
|
+
if (matchScore < 0.15) continue;
|
|
1080
|
+
const sevBoost = l.severity === 'critical' ? 0.15 : l.severity === 'major' ? 0.05 : 0;
|
|
1081
|
+
failures.push({
|
|
1082
|
+
concept: l.topic,
|
|
1083
|
+
failure: l.what_failed.slice(0, 80),
|
|
1084
|
+
probability: Math.min(0.97, (l.confidence ?? 0.5) * matchScore * 1.5 + sevBoost),
|
|
1085
|
+
fix: l.what_worked?.slice(0, 120),
|
|
1086
|
+
topic: l.topic,
|
|
1087
|
+
source: 'lesson',
|
|
1088
|
+
});
|
|
1089
|
+
} catch { /* skip */ }
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
if (failures.length === 0) {
|
|
1093
|
+
return [
|
|
1094
|
+
`🔮 **Failure Prediction: "${ctx}"**`, '',
|
|
1095
|
+
`No known failure patterns found for this context.`,
|
|
1096
|
+
`💡 The brain learns from every \`learn_from_attempts(outcome="failure")\` call.`,
|
|
1097
|
+
`🔍 Try: \`brain_predict(context="${ctx}")\` for broader predictions.`,
|
|
1098
|
+
].join('\n');
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// Deduplicate and rank by probability
|
|
1102
|
+
const seen = new Set<string>();
|
|
1103
|
+
const ranked = failures.filter(f => {
|
|
1104
|
+
const k = f.failure.slice(0, 40);
|
|
1105
|
+
if (seen.has(k)) return false;
|
|
1106
|
+
seen.add(k);
|
|
1107
|
+
return true;
|
|
1108
|
+
}).sort((a, b) => b.probability - a.probability).slice(0, Number(top_k));
|
|
1109
|
+
|
|
1110
|
+
const lines = [`🔮 **Failure Prediction for: "${ctx}"**\n`];
|
|
1111
|
+
lines.push(`> Pre-deploy failure analysis based on ${failures.length} patterns. Ranked by probability.\n`);
|
|
1112
|
+
|
|
1113
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
1114
|
+
const f = ranked[i];
|
|
1115
|
+
const pct = Math.round(f.probability * 100);
|
|
1116
|
+
const bar = '█'.repeat(Math.round(pct / 10)) + '░'.repeat(10 - Math.round(pct / 10));
|
|
1117
|
+
const icon = pct >= 70 ? '🔴' : pct >= 40 ? '🟡' : '🟢';
|
|
1118
|
+
lines.push(`${icon} **${i + 1}. ${f.failure}**`);
|
|
1119
|
+
lines.push(` Probability: ${bar} **${pct}%** (${f.source === 'ckg' ? 'CKG causal edge' : 'lesson history'})`);
|
|
1120
|
+
if (format === 'detailed' && f.fix) {
|
|
1121
|
+
lines.push(` ✅ Pre-loaded fix: _${f.fix}_`);
|
|
1122
|
+
}
|
|
1123
|
+
if (format === 'detailed' && f.topic) {
|
|
1124
|
+
lines.push(` 📚 Lesson: \`${f.topic}\``);
|
|
1125
|
+
}
|
|
1126
|
+
lines.push('');
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
const highRisk = ranked.filter(f => f.probability >= 0.6);
|
|
1130
|
+
if (highRisk.length > 0) {
|
|
1131
|
+
lines.push(`⚠️ **${highRisk.length} high-risk failure${highRisk.length > 1 ? 's' : ''} detected** (≥60% probability). Review fixes before proceeding.`);
|
|
1132
|
+
} else {
|
|
1133
|
+
lines.push(`✅ No high-risk failures detected. Proceed with caution and monitor closely.`);
|
|
1134
|
+
}
|
|
1135
|
+
lines.push('', `💡 After deploy: \`learn_from_attempts(topic="deploy:...", outcome="success|failure")\` to improve future predictions.`);
|
|
1136
|
+
return lines.join('\n');
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
default:
|
|
1141
|
+
return null;
|
|
1142
|
+
}
|
|
1143
|
+
}
|