@cachly-dev/mcp-server 0.9.6 → 0.9.7
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/dist/index.js +444 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/server.json +3 -3
- package/src/index.ts +465 -1
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cachly-dev/mcp-server",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.7",
|
|
4
4
|
"mcpName": "io.github.cachly-dev/cachly-mcp",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Your AI forgets everything between sessions. cachly fixes that permanently. A causal brain that learns WHY things break — built from every bug fix, git commit, and CI run, without any explicit calls. Arrives pre-briefed each session. Predicts failures before they happen. Never re-researches the same problem. 63 MCP tools · Claude Code · Cursor · GitHub Copilot · Windsurf · Free tier · EU servers.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"cachly-mcp": "dist/index.js"
|
package/server.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.cachly-dev/cachly-mcp",
|
|
4
|
-
"description": "
|
|
4
|
+
"description": "Your AI forgets everything between sessions. cachly fixes that permanently. A causal brain that learns WHY things break — built from every bug fix, git commit, and CI run, without any explicit calls. Arrives pre-briefed each session. Predicts failures before they happen. Never re-researches the same problem. 63 MCP tools · Free tier · EU servers.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"url": "https://github.com/cachly-dev/cachly-mcp",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.9.
|
|
9
|
+
"version": "0.9.7",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"name": "@cachly-dev/mcp-server",
|
|
14
14
|
"identifier": "@cachly-dev/mcp-server",
|
|
15
|
-
"version": "0.9.
|
|
15
|
+
"version": "0.9.7",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|
package/src/index.ts
CHANGED
|
@@ -55,7 +55,7 @@ import { Redis } from 'ioredis';
|
|
|
55
55
|
const API_URL = process.env.CACHLY_API_URL ?? 'https://api.cachly.dev';
|
|
56
56
|
let JWT = process.env.CACHLY_JWT ?? '';
|
|
57
57
|
const EMBED_MODEL = process.env.CACHLY_EMBED_MODEL ?? '';
|
|
58
|
-
const CURRENT_VERSION = '0.9.
|
|
58
|
+
const CURRENT_VERSION = '0.9.7';
|
|
59
59
|
|
|
60
60
|
// ── Default Instance Resolution (for Smithery & single-credential setups) ────
|
|
61
61
|
// When CACHLY_BRAIN_INSTANCE_ID is set, tools can omit the instance_id parameter.
|
|
@@ -3919,6 +3919,72 @@ const TOOLS = [
|
|
|
3919
3919
|
required: ['instance_id'],
|
|
3920
3920
|
},
|
|
3921
3921
|
},
|
|
3922
|
+
{
|
|
3923
|
+
name: 'crystal_view',
|
|
3924
|
+
description:
|
|
3925
|
+
'Inspect the current Memory Crystal — the compressed wisdom distilled from all past sessions. ' +
|
|
3926
|
+
'Shows top patterns per category, lesson count, and when the crystal was last refreshed. ' +
|
|
3927
|
+
'Call after session_start when you want to quickly see accumulated wisdom across all past work.',
|
|
3928
|
+
inputSchema: {
|
|
3929
|
+
type: 'object',
|
|
3930
|
+
properties: {
|
|
3931
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3932
|
+
show_raw: { type: 'boolean', description: 'Include raw JSON crystal data (default: false)' },
|
|
3933
|
+
},
|
|
3934
|
+
required: ['instance_id'],
|
|
3935
|
+
},
|
|
3936
|
+
},
|
|
3937
|
+
{
|
|
3938
|
+
name: 'compact_recover',
|
|
3939
|
+
description:
|
|
3940
|
+
'Call FIRST after any context limit hit / compaction. Reconstructs full context from Memory Crystal + ' +
|
|
3941
|
+
'recent sessions + WIP registry + open failures. Returns a condensed briefing so the new context ' +
|
|
3942
|
+
'window starts exactly where the previous one left off — no lost progress.',
|
|
3943
|
+
inputSchema: {
|
|
3944
|
+
type: 'object',
|
|
3945
|
+
properties: {
|
|
3946
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3947
|
+
focus: { type: 'string', description: 'What you were working on (helps filter relevant context)' },
|
|
3948
|
+
},
|
|
3949
|
+
required: ['instance_id'],
|
|
3950
|
+
},
|
|
3951
|
+
},
|
|
3952
|
+
{
|
|
3953
|
+
name: 'brain_from_git',
|
|
3954
|
+
description:
|
|
3955
|
+
'Bootstrap brain lessons from git history. Parses commit messages and infers fix/feature/refactor ' +
|
|
3956
|
+
'lessons automatically. Great for onboarding an existing codebase — run once and the brain instantly ' +
|
|
3957
|
+
'knows your team\'s accumulated patterns. Supports limit and branch options.',
|
|
3958
|
+
inputSchema: {
|
|
3959
|
+
type: 'object',
|
|
3960
|
+
properties: {
|
|
3961
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3962
|
+
repo_path: { type: 'string', description: 'Path to git repository (default: current directory)' },
|
|
3963
|
+
limit: { type: 'number', description: 'Max commits to process (default: 100, max: 500)' },
|
|
3964
|
+
branch: { type: 'string', description: 'Git branch to parse (default: current branch / HEAD)' },
|
|
3965
|
+
since: { type: 'string', description: 'Only commits after this date, e.g. "2024-01-01" (optional)' },
|
|
3966
|
+
},
|
|
3967
|
+
required: ['instance_id'],
|
|
3968
|
+
},
|
|
3969
|
+
},
|
|
3970
|
+
{
|
|
3971
|
+
name: 'brain_predict_failures',
|
|
3972
|
+
description:
|
|
3973
|
+
'Pre-deploy failure prediction with probability percentages. Given a change context (e.g. ' +
|
|
3974
|
+
'"upgrading Keycloak 21→24" or "deploying Redis 7 to prod"), returns the top likely failure modes ' +
|
|
3975
|
+
'ranked by probability, with pre-loaded fixes. Uses CKG causal edges + lesson history. ' +
|
|
3976
|
+
'Call before any significant deploy, migration, or infrastructure change.',
|
|
3977
|
+
inputSchema: {
|
|
3978
|
+
type: 'object',
|
|
3979
|
+
properties: {
|
|
3980
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3981
|
+
context: { type: 'string', description: 'What you are about to do, e.g. "upgrading Keycloak 21 to 24"' },
|
|
3982
|
+
top_k: { type: 'number', description: 'Number of failure predictions to return (default: 5)' },
|
|
3983
|
+
format: { type: 'string', enum: ['brief', 'detailed'], description: 'Output format (default: detailed)' },
|
|
3984
|
+
},
|
|
3985
|
+
required: ['instance_id', 'context'],
|
|
3986
|
+
},
|
|
3987
|
+
},
|
|
3922
3988
|
] as const;
|
|
3923
3989
|
|
|
3924
3990
|
// ── Handlers ──────────────────────────────────────────────────────────────────
|
|
@@ -9176,6 +9242,404 @@ smart_recall(
|
|
|
9176
9242
|
return lines.join('\n');
|
|
9177
9243
|
}
|
|
9178
9244
|
|
|
9245
|
+
// ── crystal_view ──────────────────────────────────────────────────────────
|
|
9246
|
+
case 'crystal_view': {
|
|
9247
|
+
const { instance_id, show_raw = false } = args as { instance_id: string; show_raw?: boolean };
|
|
9248
|
+
const redis = await getConnection(instance_id);
|
|
9249
|
+
|
|
9250
|
+
const raw = await redis.get('cachly:crystal:latest');
|
|
9251
|
+
if (!raw) {
|
|
9252
|
+
return [
|
|
9253
|
+
`💎 **Memory Crystal: not yet created**`, '',
|
|
9254
|
+
`No crystal found. Create one with \`memory_crystalize()\` to compress your accumulated wisdom.`,
|
|
9255
|
+
'', `💡 Tip: run \`memory_crystalize\` monthly for best results.`,
|
|
9256
|
+
].join('\n');
|
|
9257
|
+
}
|
|
9258
|
+
|
|
9259
|
+
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 };
|
|
9260
|
+
const crystal: Crystal = JSON.parse(raw);
|
|
9261
|
+
const age = Math.floor((Date.now() - new Date(crystal.ts).getTime()) / 86400000);
|
|
9262
|
+
const freshEmoji = age <= 7 ? '🟢' : age <= 30 ? '🟡' : '🔴';
|
|
9263
|
+
|
|
9264
|
+
const lines = [
|
|
9265
|
+
`💎 **Memory Crystal: ${crystal.label}**`, '',
|
|
9266
|
+
`📅 Created: ${new Date(crystal.ts).toLocaleDateString('de-DE')} (${age}d ago ${freshEmoji})`,
|
|
9267
|
+
`📊 Compressed from: ${crystal.created_from}`,
|
|
9268
|
+
`🗂️ Categories: ${crystal.categories.slice(0, 10).map(c => `\`${c}\``).join(', ')}${crystal.categories.length > 10 ? ` +${crystal.categories.length - 10} more` : ''}`,
|
|
9269
|
+
'',
|
|
9270
|
+
`**🔑 Top patterns (${crystal.top_patterns.length}):**`,
|
|
9271
|
+
];
|
|
9272
|
+
for (const p of crystal.top_patterns) {
|
|
9273
|
+
lines.push(` • **${p.category}** (${p.count}×): ${p.insight.slice(0, 110)}`);
|
|
9274
|
+
}
|
|
9275
|
+
if (age > 30) {
|
|
9276
|
+
lines.push('', `⚠️ Crystal is ${age}d old — run \`memory_crystalize()\` to refresh it.`);
|
|
9277
|
+
}
|
|
9278
|
+
if (show_raw) {
|
|
9279
|
+
lines.push('', '```json', JSON.stringify(crystal, null, 2), '```');
|
|
9280
|
+
}
|
|
9281
|
+
lines.push('', `💡 Refresh: \`memory_crystalize()\` | Recover: \`compact_recover(instance_id="...")\``);
|
|
9282
|
+
return lines.join('\n');
|
|
9283
|
+
}
|
|
9284
|
+
|
|
9285
|
+
// ── compact_recover ───────────────────────────────────────────────────────
|
|
9286
|
+
case 'compact_recover': {
|
|
9287
|
+
const { instance_id, focus = '' } = args as { instance_id: string; focus?: string };
|
|
9288
|
+
const redis = await getConnection(instance_id);
|
|
9289
|
+
|
|
9290
|
+
const lines = [`🔁 **Compact Recovery Briefing**\n`];
|
|
9291
|
+
lines.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*\n`);
|
|
9292
|
+
|
|
9293
|
+
// 1. Memory Crystal
|
|
9294
|
+
const crystalRaw = await redis.get('cachly:crystal:latest');
|
|
9295
|
+
if (crystalRaw) {
|
|
9296
|
+
type Crystal = { label: string; ts: string; session_count: number; lesson_count: number; top_patterns: Array<{ category: string; insight: string; count: number }> };
|
|
9297
|
+
const crystal: Crystal = JSON.parse(crystalRaw);
|
|
9298
|
+
lines.push(`### 💎 Memory Crystal: ${crystal.label}`);
|
|
9299
|
+
lines.push(`Compressed from ${crystal.session_count} sessions, ${crystal.lesson_count} lessons.`);
|
|
9300
|
+
const topN = focus
|
|
9301
|
+
? crystal.top_patterns.filter(p => p.category.toLowerCase().includes(focus.toLowerCase()) || p.insight.toLowerCase().includes(focus.toLowerCase())).slice(0, 4)
|
|
9302
|
+
: crystal.top_patterns.slice(0, 4);
|
|
9303
|
+
for (const p of topN) lines.push(` • **${p.category}**: ${p.insight.slice(0, 100)}`);
|
|
9304
|
+
lines.push('');
|
|
9305
|
+
}
|
|
9306
|
+
|
|
9307
|
+
// 2. Last session summary
|
|
9308
|
+
const lastSession = await redis.get('cachly:session:last');
|
|
9309
|
+
if (lastSession) {
|
|
9310
|
+
type Session = { summary?: string; ts?: string; focus?: string };
|
|
9311
|
+
const sess: Session = JSON.parse(lastSession);
|
|
9312
|
+
lines.push(`### 🕐 Last Session`);
|
|
9313
|
+
if (sess.focus) lines.push(`Focus: _${sess.focus}_`);
|
|
9314
|
+
if (sess.summary) lines.push(`Summary: ${sess.summary.slice(0, 300)}`);
|
|
9315
|
+
lines.push('');
|
|
9316
|
+
}
|
|
9317
|
+
|
|
9318
|
+
// 3. Session handoff
|
|
9319
|
+
const handoff = await redis.get('cachly:session:handoff');
|
|
9320
|
+
if (handoff) {
|
|
9321
|
+
type Handoff = { remaining_tasks?: string[]; instructions?: string; context_summary?: string; blocked_on?: string };
|
|
9322
|
+
const h: Handoff = JSON.parse(handoff);
|
|
9323
|
+
lines.push(`### 📋 Handoff (from last window)`);
|
|
9324
|
+
if (h.context_summary) lines.push(`Context: ${h.context_summary.slice(0, 200)}`);
|
|
9325
|
+
if (h.remaining_tasks?.length) {
|
|
9326
|
+
lines.push(`Remaining tasks:`);
|
|
9327
|
+
for (const t of h.remaining_tasks.slice(0, 5)) lines.push(` • ${t}`);
|
|
9328
|
+
}
|
|
9329
|
+
if (h.instructions) lines.push(`⚠️ Instructions: ${h.instructions.slice(0, 200)}`);
|
|
9330
|
+
if (h.blocked_on) lines.push(`🚧 Blocked on: ${h.blocked_on}`);
|
|
9331
|
+
lines.push('');
|
|
9332
|
+
}
|
|
9333
|
+
|
|
9334
|
+
// 4. WIP registry
|
|
9335
|
+
const wipRaw = await redis.get('cachly:ctx:wip-registry');
|
|
9336
|
+
if (wipRaw) {
|
|
9337
|
+
type Ctx = { content?: string };
|
|
9338
|
+
const wip: Ctx = JSON.parse(wipRaw);
|
|
9339
|
+
if (wip.content) {
|
|
9340
|
+
lines.push(`### 🔧 WIP Registry`);
|
|
9341
|
+
lines.push(wip.content.slice(0, 400));
|
|
9342
|
+
lines.push('');
|
|
9343
|
+
}
|
|
9344
|
+
}
|
|
9345
|
+
|
|
9346
|
+
// 5. Open failures (roadmap with status=blocked/in_progress)
|
|
9347
|
+
const roadmapKeys: string[] = [];
|
|
9348
|
+
const rStream = redis.scanStream({ match: 'cachly:roadmap:*', count: 100 });
|
|
9349
|
+
await new Promise<void>((res, rej) => { rStream.on('data', (b: string[]) => roadmapKeys.push(...b)); rStream.on('end', res); rStream.on('error', rej); });
|
|
9350
|
+
const openItems: Array<{ title: string; status: string; priority?: string }> = [];
|
|
9351
|
+
for (const k of roadmapKeys.slice(0, 30)) {
|
|
9352
|
+
const r = await redis.get(k);
|
|
9353
|
+
if (!r) continue;
|
|
9354
|
+
try {
|
|
9355
|
+
const item = JSON.parse(r) as { title?: string; status?: string; priority?: string };
|
|
9356
|
+
if (item.status === 'in_progress' || item.status === 'blocked') openItems.push({ title: item.title ?? k, status: item.status, priority: item.priority });
|
|
9357
|
+
} catch { /* skip */ }
|
|
9358
|
+
}
|
|
9359
|
+
if (openItems.length > 0) {
|
|
9360
|
+
lines.push(`### 🚧 Open Items`);
|
|
9361
|
+
for (const i of openItems.slice(0, 5)) lines.push(` • [${i.status}] ${i.title}`);
|
|
9362
|
+
lines.push('');
|
|
9363
|
+
}
|
|
9364
|
+
|
|
9365
|
+
// 6. Focus-relevant lessons
|
|
9366
|
+
if (focus) {
|
|
9367
|
+
const lessonKeys: string[] = [];
|
|
9368
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 200 });
|
|
9369
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
9370
|
+
const relevant: Array<{ topic: string; what_worked: string }> = [];
|
|
9371
|
+
for (const k of lessonKeys) {
|
|
9372
|
+
const r = await redis.get(k);
|
|
9373
|
+
if (!r) continue;
|
|
9374
|
+
try {
|
|
9375
|
+
const l = JSON.parse(r) as { topic: string; what_worked?: string };
|
|
9376
|
+
if (l.topic.toLowerCase().includes(focus.toLowerCase()) && l.what_worked) {
|
|
9377
|
+
relevant.push({ topic: l.topic, what_worked: l.what_worked });
|
|
9378
|
+
}
|
|
9379
|
+
} catch { /* skip */ }
|
|
9380
|
+
}
|
|
9381
|
+
if (relevant.length > 0) {
|
|
9382
|
+
lines.push(`### 💡 Relevant Lessons for "${focus}"`);
|
|
9383
|
+
for (const l of relevant.slice(0, 4)) lines.push(` • **${l.topic}**: ${l.what_worked.slice(0, 100)}`);
|
|
9384
|
+
lines.push('');
|
|
9385
|
+
}
|
|
9386
|
+
}
|
|
9387
|
+
|
|
9388
|
+
if (lines.length <= 3) {
|
|
9389
|
+
lines.push(`_No brain data found. Start accumulating knowledge with \`learn_from_attempts\` and \`session_start\`._`);
|
|
9390
|
+
}
|
|
9391
|
+
lines.push(`---`, `🧠 Brain is ready. Continue your work — full context restored.`);
|
|
9392
|
+
return lines.join('\n');
|
|
9393
|
+
}
|
|
9394
|
+
|
|
9395
|
+
// ── brain_from_git ────────────────────────────────────────────────────────
|
|
9396
|
+
case 'brain_from_git': {
|
|
9397
|
+
const { instance_id, repo_path = '.', limit = 100, branch = 'HEAD', since = '' } = args as {
|
|
9398
|
+
instance_id: string; repo_path?: string; limit?: number; branch?: string; since?: string;
|
|
9399
|
+
};
|
|
9400
|
+
const redis = await getConnection(instance_id);
|
|
9401
|
+
const { execSync } = await import('node:child_process');
|
|
9402
|
+
const { resolve } = await import('node:path');
|
|
9403
|
+
|
|
9404
|
+
const repoDir = resolve(repo_path);
|
|
9405
|
+
const maxCommits = Math.min(Number(limit) || 100, 500);
|
|
9406
|
+
|
|
9407
|
+
// Verify it's a git repo
|
|
9408
|
+
try {
|
|
9409
|
+
execSync('git rev-parse --git-dir', { cwd: repoDir, stdio: 'pipe' });
|
|
9410
|
+
} catch {
|
|
9411
|
+
return `❌ Not a git repository: \`${repoDir}\`. Pass \`repo_path\` pointing to a git checkout.`;
|
|
9412
|
+
}
|
|
9413
|
+
|
|
9414
|
+
// Build git log command
|
|
9415
|
+
const sinceFlag = since ? `--since="${since}"` : '';
|
|
9416
|
+
const logCmd = `git log ${branch} ${sinceFlag} --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n ${maxCommits}`;
|
|
9417
|
+
|
|
9418
|
+
let logOutput = '';
|
|
9419
|
+
try {
|
|
9420
|
+
logOutput = execSync(logCmd, { cwd: repoDir, encoding: 'utf-8', stdio: 'pipe' });
|
|
9421
|
+
} catch (e) {
|
|
9422
|
+
return `❌ git log failed: ${(e as Error).message}. Check \`repo_path\` and \`branch\`.`;
|
|
9423
|
+
}
|
|
9424
|
+
|
|
9425
|
+
const commits = logOutput.trim().split('\n').filter(Boolean).map(line => {
|
|
9426
|
+
const [sha, subject, date, author] = line.split('|||');
|
|
9427
|
+
return { sha: (sha ?? '').trim(), subject: (subject ?? '').trim(), date: (date ?? '').trim(), author: (author ?? '').trim() };
|
|
9428
|
+
});
|
|
9429
|
+
|
|
9430
|
+
if (commits.length === 0) {
|
|
9431
|
+
return `⚠️ No commits found in \`${repoDir}\` on branch \`${branch}\`${since ? ` since ${since}` : ''}.`;
|
|
9432
|
+
}
|
|
9433
|
+
|
|
9434
|
+
// Pattern classifiers
|
|
9435
|
+
const classifyCommit = (subject: string): { category: string; outcome: 'success' | 'failure' | 'partial'; severity: 'critical' | 'major' | 'minor' } => {
|
|
9436
|
+
const s = subject.toLowerCase();
|
|
9437
|
+
if (/\b(fix|fixed|fixes|bug|hotfix|patch|revert|resolve|closes? #\d+)\b/.test(s)) {
|
|
9438
|
+
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';
|
|
9439
|
+
return { category: 'fix', outcome: 'success', severity: sev };
|
|
9440
|
+
}
|
|
9441
|
+
if (/\b(feat|feature|add|added|implement|new|introduce)\b/.test(s)) return { category: 'feat', outcome: 'success', severity: 'minor' };
|
|
9442
|
+
if (/\b(refactor|clean|cleanup|improve|simplify|extract|rename)\b/.test(s)) return { category: 'refactor', outcome: 'success', severity: 'minor' };
|
|
9443
|
+
if (/\b(perf|optimize|speed|cache|latency|memory|performance)\b/.test(s)) return { category: 'perf', outcome: 'success', severity: 'major' };
|
|
9444
|
+
if (/\b(security|cve|auth|csrf|xss|sql|injection|sanitize|escape|encrypt)\b/.test(s)) return { category: 'security', outcome: 'success', severity: 'critical' };
|
|
9445
|
+
if (/\b(deploy|ci|cd|build|docker|k8s|helm|infra|devops)\b/.test(s)) return { category: 'deploy', outcome: 'success', severity: 'major' };
|
|
9446
|
+
if (/\b(test|spec|coverage|assert|mock|unit|integration)\b/.test(s)) return { category: 'test', outcome: 'success', severity: 'minor' };
|
|
9447
|
+
return { category: 'chore', outcome: 'success', severity: 'minor' };
|
|
9448
|
+
};
|
|
9449
|
+
|
|
9450
|
+
// Extract domain keywords from commit subject
|
|
9451
|
+
const extractDomain = (subject: string): string => {
|
|
9452
|
+
const s = subject.toLowerCase();
|
|
9453
|
+
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));
|
|
9454
|
+
return tokens.slice(0, 3).join('-') || 'general';
|
|
9455
|
+
};
|
|
9456
|
+
|
|
9457
|
+
const ts = new Date().toISOString();
|
|
9458
|
+
let ingested = 0;
|
|
9459
|
+
let skipped = 0;
|
|
9460
|
+
const categoryCount = new Map<string, number>();
|
|
9461
|
+
|
|
9462
|
+
for (const commit of commits) {
|
|
9463
|
+
if (!commit.subject) { skipped++; continue; }
|
|
9464
|
+
const { category, outcome, severity } = classifyCommit(commit.subject);
|
|
9465
|
+
const domain = extractDomain(commit.subject);
|
|
9466
|
+
const topic = `${category}:${domain}`;
|
|
9467
|
+
categoryCount.set(category, (categoryCount.get(category) ?? 0) + 1);
|
|
9468
|
+
|
|
9469
|
+
const lessonObj = {
|
|
9470
|
+
topic, outcome, severity,
|
|
9471
|
+
what_worked: commit.subject.slice(0, 200),
|
|
9472
|
+
what_failed: '',
|
|
9473
|
+
context: `git:${commit.sha.slice(0, 8)} by ${commit.author} on ${commit.date}`,
|
|
9474
|
+
file_paths: [], commands: [`git show ${commit.sha.slice(0, 8)}`],
|
|
9475
|
+
tags: ['brain_from_git', category, 'git-history'],
|
|
9476
|
+
depends_on: [], recall_count: 0, ts, verified_at: ts,
|
|
9477
|
+
confidence: 0.55, // lower confidence for auto-inferred lessons
|
|
9478
|
+
audit_trail: [{ ts, action: 'brain_from_git', sha: commit.sha.slice(0, 8) }],
|
|
9479
|
+
version: 3,
|
|
9480
|
+
};
|
|
9481
|
+
|
|
9482
|
+
// Only store if no existing lesson for this topic (avoid overwriting higher-confidence lessons)
|
|
9483
|
+
const existing = await redis.get(`cachly:lesson:best:${topic}`);
|
|
9484
|
+
if (!existing) {
|
|
9485
|
+
await redis.set(`cachly:lesson:best:${topic}`, JSON.stringify(lessonObj));
|
|
9486
|
+
await redis.rpush(`cachly:lessons:${topic}`, JSON.stringify(lessonObj));
|
|
9487
|
+
}
|
|
9488
|
+
await redis.rpush('cachly:lessons:brain_from_git:all', JSON.stringify({ topic, sha: commit.sha.slice(0, 8), subject: commit.subject.slice(0, 60) }));
|
|
9489
|
+
await redis.ltrim('cachly:lessons:brain_from_git:all', -500, -1);
|
|
9490
|
+
|
|
9491
|
+
// Update CKG
|
|
9492
|
+
const conceptId = ckgSlug(topic);
|
|
9493
|
+
await ckgUpsertNode(redis, conceptId, category, 'git-derived');
|
|
9494
|
+
ingested++;
|
|
9495
|
+
}
|
|
9496
|
+
|
|
9497
|
+
const categoryBreakdown = [...categoryCount.entries()].sort((a, b) => b[1] - a[1]).map(([k, v]) => ` • **${k}** (${v})`).join('\n');
|
|
9498
|
+
|
|
9499
|
+
return [
|
|
9500
|
+
`🔁 **brain_from_git: ${repoDir}**`, '',
|
|
9501
|
+
`📂 Branch: \`${branch}\` | Processed: **${commits.length}** commits | Ingested: **${ingested}** lessons | Skipped: ${skipped}`,
|
|
9502
|
+
``,
|
|
9503
|
+
`**Breakdown by category:**`,
|
|
9504
|
+
categoryBreakdown,
|
|
9505
|
+
``,
|
|
9506
|
+
`💡 New lessons are stored with confidence 0.55 (auto-inferred).`,
|
|
9507
|
+
`💡 As you confirm them via \`learn_from_attempts\`, confidence rises automatically.`,
|
|
9508
|
+
`🔍 Explore: \`brain_search(query="fix")\` | \`ckg_inspect(concept="deploy")\``,
|
|
9509
|
+
].join('\n');
|
|
9510
|
+
}
|
|
9511
|
+
|
|
9512
|
+
// ── brain_predict_failures ─────────────────────────────────────────────────
|
|
9513
|
+
case 'brain_predict_failures': {
|
|
9514
|
+
const { instance_id, context: ctx, top_k = 5, format = 'detailed' } = args as {
|
|
9515
|
+
instance_id: string; context: string; top_k?: number; format?: 'brief' | 'detailed';
|
|
9516
|
+
};
|
|
9517
|
+
const redis = await getConnection(instance_id);
|
|
9518
|
+
|
|
9519
|
+
const ctxTokens = ctx.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g, ' ').split(/\s+/).filter(t => t.length > 2);
|
|
9520
|
+
|
|
9521
|
+
type FailurePred = { concept: string; failure: string; probability: number; fix?: string; topic?: string; source: 'ckg' | 'lesson' };
|
|
9522
|
+
const failures: FailurePred[] = [];
|
|
9523
|
+
|
|
9524
|
+
// Step 1: CKG — find 'causes' and 'degrades_under' edges from context tokens
|
|
9525
|
+
for (const token of ctxTokens.slice(0, 8)) {
|
|
9526
|
+
const nodeKeys: string[] = [];
|
|
9527
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
|
|
9528
|
+
await new Promise<void>((res, rej) => { nStream.on('data', (b: string[]) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
9529
|
+
|
|
9530
|
+
for (const nk of nodeKeys.slice(0, 5)) {
|
|
9531
|
+
const nodeRaw = await redis.get(nk);
|
|
9532
|
+
if (!nodeRaw) continue;
|
|
9533
|
+
const node: CKGNode = JSON.parse(nodeRaw);
|
|
9534
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
9535
|
+
for (const ek of edgeKeys.slice(0, 20)) {
|
|
9536
|
+
const edgeRaw = await redis.get(ek);
|
|
9537
|
+
if (!edgeRaw) continue;
|
|
9538
|
+
const edge: CKGEdge = JSON.parse(edgeRaw);
|
|
9539
|
+
if (edge.edgeType !== 'causes' && edge.edgeType !== 'degrades_under') continue;
|
|
9540
|
+
|
|
9541
|
+
// Look up fix for this failure from CKG 'fixes' edges
|
|
9542
|
+
const fixEdgeKeys = await redis.smembers(`cachly:ckg:idx:from:${edge.to}`);
|
|
9543
|
+
let fix: string | undefined;
|
|
9544
|
+
for (const fek of fixEdgeKeys.slice(0, 10)) {
|
|
9545
|
+
const feRaw = await redis.get(fek);
|
|
9546
|
+
if (!feRaw) continue;
|
|
9547
|
+
const fe: CKGEdge = JSON.parse(feRaw);
|
|
9548
|
+
if (fe.edgeType === 'fixes') {
|
|
9549
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${fe.from}`);
|
|
9550
|
+
if (lessonRaw) {
|
|
9551
|
+
const lesson = JSON.parse(lessonRaw) as { what_worked?: string };
|
|
9552
|
+
fix = lesson.what_worked?.slice(0, 120);
|
|
9553
|
+
break;
|
|
9554
|
+
}
|
|
9555
|
+
}
|
|
9556
|
+
}
|
|
9557
|
+
|
|
9558
|
+
failures.push({
|
|
9559
|
+
concept: node.id,
|
|
9560
|
+
failure: edge.to.replace(/-/g, ' '),
|
|
9561
|
+
probability: edge.confidence,
|
|
9562
|
+
fix,
|
|
9563
|
+
source: 'ckg',
|
|
9564
|
+
});
|
|
9565
|
+
}
|
|
9566
|
+
}
|
|
9567
|
+
}
|
|
9568
|
+
|
|
9569
|
+
// Step 2: Lesson history — find failure-outcome lessons matching context
|
|
9570
|
+
const lessonKeys: string[] = [];
|
|
9571
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 300 });
|
|
9572
|
+
await new Promise<void>((res, rej) => { lStream.on('data', (b: string[]) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
9573
|
+
|
|
9574
|
+
for (const k of lessonKeys.slice(0, 100)) {
|
|
9575
|
+
const r = await redis.get(k);
|
|
9576
|
+
if (!r) continue;
|
|
9577
|
+
try {
|
|
9578
|
+
const l = JSON.parse(r) as { topic: string; outcome: string; what_failed?: string; what_worked?: string; confidence?: number; severity?: string };
|
|
9579
|
+
if (l.outcome !== 'failure' && l.outcome !== 'partial') continue;
|
|
9580
|
+
if (!l.what_failed) continue;
|
|
9581
|
+
const haystack = `${l.topic} ${l.what_failed}`.toLowerCase();
|
|
9582
|
+
const matchScore = ctxTokens.filter(t => haystack.includes(t)).length / Math.max(1, ctxTokens.length);
|
|
9583
|
+
if (matchScore < 0.15) continue;
|
|
9584
|
+
const sevBoost = l.severity === 'critical' ? 0.15 : l.severity === 'major' ? 0.05 : 0;
|
|
9585
|
+
failures.push({
|
|
9586
|
+
concept: l.topic,
|
|
9587
|
+
failure: l.what_failed.slice(0, 80),
|
|
9588
|
+
probability: Math.min(0.97, (l.confidence ?? 0.5) * matchScore * 1.5 + sevBoost),
|
|
9589
|
+
fix: l.what_worked?.slice(0, 120),
|
|
9590
|
+
topic: l.topic,
|
|
9591
|
+
source: 'lesson',
|
|
9592
|
+
});
|
|
9593
|
+
} catch { /* skip */ }
|
|
9594
|
+
}
|
|
9595
|
+
|
|
9596
|
+
if (failures.length === 0) {
|
|
9597
|
+
return [
|
|
9598
|
+
`🔮 **Failure Prediction: "${ctx}"**`, '',
|
|
9599
|
+
`No known failure patterns found for this context.`,
|
|
9600
|
+
`💡 The brain learns from every \`learn_from_attempts(outcome="failure")\` call.`,
|
|
9601
|
+
`🔍 Try: \`brain_predict(context="${ctx}")\` for broader predictions.`,
|
|
9602
|
+
].join('\n');
|
|
9603
|
+
}
|
|
9604
|
+
|
|
9605
|
+
// Deduplicate and rank by probability
|
|
9606
|
+
const seen = new Set<string>();
|
|
9607
|
+
const ranked = failures.filter(f => {
|
|
9608
|
+
const k = f.failure.slice(0, 40);
|
|
9609
|
+
if (seen.has(k)) return false;
|
|
9610
|
+
seen.add(k);
|
|
9611
|
+
return true;
|
|
9612
|
+
}).sort((a, b) => b.probability - a.probability).slice(0, Number(top_k));
|
|
9613
|
+
|
|
9614
|
+
const lines = [`🔮 **Failure Prediction for: "${ctx}"**\n`];
|
|
9615
|
+
lines.push(`> Pre-deploy failure analysis based on ${failures.length} patterns. Ranked by probability.\n`);
|
|
9616
|
+
|
|
9617
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
9618
|
+
const f = ranked[i];
|
|
9619
|
+
const pct = Math.round(f.probability * 100);
|
|
9620
|
+
const bar = '█'.repeat(Math.round(pct / 10)) + '░'.repeat(10 - Math.round(pct / 10));
|
|
9621
|
+
const icon = pct >= 70 ? '🔴' : pct >= 40 ? '🟡' : '🟢';
|
|
9622
|
+
lines.push(`${icon} **${i + 1}. ${f.failure}**`);
|
|
9623
|
+
lines.push(` Probability: ${bar} **${pct}%** (${f.source === 'ckg' ? 'CKG causal edge' : 'lesson history'})`);
|
|
9624
|
+
if (format === 'detailed' && f.fix) {
|
|
9625
|
+
lines.push(` ✅ Pre-loaded fix: _${f.fix}_`);
|
|
9626
|
+
}
|
|
9627
|
+
if (format === 'detailed' && f.topic) {
|
|
9628
|
+
lines.push(` 📚 Lesson: \`${f.topic}\``);
|
|
9629
|
+
}
|
|
9630
|
+
lines.push('');
|
|
9631
|
+
}
|
|
9632
|
+
|
|
9633
|
+
const highRisk = ranked.filter(f => f.probability >= 0.6);
|
|
9634
|
+
if (highRisk.length > 0) {
|
|
9635
|
+
lines.push(`⚠️ **${highRisk.length} high-risk failure${highRisk.length > 1 ? 's' : ''} detected** (≥60% probability). Review fixes before proceeding.`);
|
|
9636
|
+
} else {
|
|
9637
|
+
lines.push(`✅ No high-risk failures detected. Proceed with caution and monitor closely.`);
|
|
9638
|
+
}
|
|
9639
|
+
lines.push('', `💡 After deploy: \`learn_from_attempts(topic="deploy:...", outcome="success|failure")\` to improve future predictions.`);
|
|
9640
|
+
return lines.join('\n');
|
|
9641
|
+
}
|
|
9642
|
+
|
|
9179
9643
|
default:
|
|
9180
9644
|
return null;
|
|
9181
9645
|
}
|