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