@cachly-dev/mcp-server 0.9.6 → 0.9.8
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/CHANGELOG.md +70 -30
- package/Dockerfile +4 -2
- package/LICENSE +202 -0
- package/README.md +310 -173
- package/dist/index.js +498 -11
- package/dist/index.js.map +1 -1
- package/glama.json +6 -0
- package/package.json +2 -2
- package/server.json +3 -3
- package/src/index.ts +529 -11
- package/test-features.cjs +0 -23
package/dist/index.js
CHANGED
|
@@ -47,7 +47,7 @@ import { Redis } from 'ioredis';
|
|
|
47
47
|
const API_URL = process.env.CACHLY_API_URL ?? 'https://api.cachly.dev';
|
|
48
48
|
let JWT = process.env.CACHLY_JWT ?? '';
|
|
49
49
|
const EMBED_MODEL = process.env.CACHLY_EMBED_MODEL ?? '';
|
|
50
|
-
const CURRENT_VERSION = '0.9.
|
|
50
|
+
const CURRENT_VERSION = '0.9.8';
|
|
51
51
|
// ── Default Instance Resolution (for Smithery & single-credential setups) ────
|
|
52
52
|
// When CACHLY_BRAIN_INSTANCE_ID is set, tools can omit the instance_id parameter.
|
|
53
53
|
// When neither is set, we auto-fetch the first running instance once per process.
|
|
@@ -2005,18 +2005,20 @@ function recencyBoost(timestampMs) {
|
|
|
2005
2005
|
* └─────────────────────────────────────────────────────────────────┘
|
|
2006
2006
|
*/
|
|
2007
2007
|
async function keywordSearch(redis, patterns, query, topK = 10) {
|
|
2008
|
-
// ── Step 1: Collect
|
|
2009
|
-
const
|
|
2010
|
-
|
|
2011
|
-
const stream = redis.scanStream({ match: pattern, count:
|
|
2012
|
-
|
|
2008
|
+
// ── Step 1: Collect all matching keys — patterns scanned in parallel ──
|
|
2009
|
+
const keyBatches = await Promise.all(patterns.map(pattern => {
|
|
2010
|
+
const keys = [];
|
|
2011
|
+
const stream = redis.scanStream({ match: pattern, count: 500 });
|
|
2012
|
+
return new Promise((resolve, reject) => {
|
|
2013
2013
|
stream.on('data', (batch) => {
|
|
2014
|
-
|
|
2014
|
+
keys.push(...batch.filter((k) => !k.endsWith(':meta')));
|
|
2015
2015
|
});
|
|
2016
|
-
stream.on('end', resolve);
|
|
2016
|
+
stream.on('end', () => resolve(keys));
|
|
2017
2017
|
stream.on('error', reject);
|
|
2018
2018
|
});
|
|
2019
|
-
}
|
|
2019
|
+
}));
|
|
2020
|
+
// Deduplicate across patterns (a key may match multiple globs)
|
|
2021
|
+
const allKeys = [...new Set(keyBatches.flat())];
|
|
2020
2022
|
if (allKeys.length === 0)
|
|
2021
2023
|
return [];
|
|
2022
2024
|
// Pipeline GET for speed
|
|
@@ -2269,12 +2271,32 @@ async function getConnection(instance_id) {
|
|
|
2269
2271
|
return client;
|
|
2270
2272
|
}
|
|
2271
2273
|
// ── API helper ────────────────────────────────────────────────────────────────
|
|
2274
|
+
function jwtExpiryMs(token) {
|
|
2275
|
+
try {
|
|
2276
|
+
const parts = token.split('.');
|
|
2277
|
+
if (parts.length !== 3)
|
|
2278
|
+
return null;
|
|
2279
|
+
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8'));
|
|
2280
|
+
return payload.exp ? payload.exp * 1000 : null;
|
|
2281
|
+
}
|
|
2282
|
+
catch {
|
|
2283
|
+
return null;
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2272
2286
|
async function apiFetch(path, options = {}) {
|
|
2273
2287
|
if (!JWT) {
|
|
2274
|
-
throw new McpError(ErrorCode.InvalidRequest, 'CACHLY_JWT env var not set
|
|
2288
|
+
throw new McpError(ErrorCode.InvalidRequest, 'CACHLY_JWT env var not set.\n\nGet your token at https://cachly.dev/setup-ai and add it to your MCP config:\n CACHLY_JWT=<your-token>');
|
|
2289
|
+
}
|
|
2290
|
+
// Detect token expiry before making the network call — gives a clearer error
|
|
2291
|
+
const expMs = jwtExpiryMs(JWT);
|
|
2292
|
+
if (expMs !== null && expMs < Date.now()) {
|
|
2293
|
+
const expiredAt = new Date(expMs).toISOString();
|
|
2294
|
+
throw new McpError(ErrorCode.InvalidRequest, `CACHLY_JWT expired at ${expiredAt}.\n\nGet a fresh token at https://cachly.dev/setup-ai and update CACHLY_JWT in your MCP config.`);
|
|
2275
2295
|
}
|
|
2296
|
+
const timeoutMs = Number(process.env.CACHLY_API_TIMEOUT_MS ?? 15_000);
|
|
2276
2297
|
const res = await fetch(`${API_URL}${path}`, {
|
|
2277
2298
|
...options,
|
|
2299
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
2278
2300
|
headers: {
|
|
2279
2301
|
'Content-Type': 'application/json',
|
|
2280
2302
|
Authorization: `Bearer ${JWT}`,
|
|
@@ -2283,7 +2305,14 @@ async function apiFetch(path, options = {}) {
|
|
|
2283
2305
|
});
|
|
2284
2306
|
if (!res.ok) {
|
|
2285
2307
|
const body = await res.json().catch(() => ({ error: res.statusText }));
|
|
2286
|
-
|
|
2308
|
+
const detail = body.error ?? res.statusText;
|
|
2309
|
+
if (res.status === 401) {
|
|
2310
|
+
throw new McpError(ErrorCode.InvalidRequest, `Authentication failed (401): ${detail}\n\nYour CACHLY_JWT may be expired or invalid. Get a fresh token at https://cachly.dev/setup-ai`);
|
|
2311
|
+
}
|
|
2312
|
+
if (res.status === 403) {
|
|
2313
|
+
throw new McpError(ErrorCode.InvalidRequest, `Access denied (403): ${detail}\n\nCheck that your CACHLY_JWT belongs to an account with access to this resource.`);
|
|
2314
|
+
}
|
|
2315
|
+
throw new McpError(ErrorCode.InternalError, `cachly API error ${res.status}: ${detail}`);
|
|
2287
2316
|
}
|
|
2288
2317
|
if (res.status === 204)
|
|
2289
2318
|
return undefined;
|
|
@@ -3804,6 +3833,68 @@ const TOOLS = [
|
|
|
3804
3833
|
required: ['instance_id'],
|
|
3805
3834
|
},
|
|
3806
3835
|
},
|
|
3836
|
+
{
|
|
3837
|
+
name: 'crystal_view',
|
|
3838
|
+
description: 'Inspect the current Memory Crystal — the compressed wisdom distilled from all past sessions. ' +
|
|
3839
|
+
'Shows top patterns per category, lesson count, and when the crystal was last refreshed. ' +
|
|
3840
|
+
'Call after session_start when you want to quickly see accumulated wisdom across all past work.',
|
|
3841
|
+
inputSchema: {
|
|
3842
|
+
type: 'object',
|
|
3843
|
+
properties: {
|
|
3844
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3845
|
+
show_raw: { type: 'boolean', description: 'Include raw JSON crystal data (default: false)' },
|
|
3846
|
+
},
|
|
3847
|
+
required: ['instance_id'],
|
|
3848
|
+
},
|
|
3849
|
+
},
|
|
3850
|
+
{
|
|
3851
|
+
name: 'compact_recover',
|
|
3852
|
+
description: 'Call FIRST after any context limit hit / compaction. Reconstructs full context from Memory Crystal + ' +
|
|
3853
|
+
'recent sessions + WIP registry + open failures. Returns a condensed briefing so the new context ' +
|
|
3854
|
+
'window starts exactly where the previous one left off — no lost progress.',
|
|
3855
|
+
inputSchema: {
|
|
3856
|
+
type: 'object',
|
|
3857
|
+
properties: {
|
|
3858
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3859
|
+
focus: { type: 'string', description: 'What you were working on (helps filter relevant context)' },
|
|
3860
|
+
},
|
|
3861
|
+
required: ['instance_id'],
|
|
3862
|
+
},
|
|
3863
|
+
},
|
|
3864
|
+
{
|
|
3865
|
+
name: 'brain_from_git',
|
|
3866
|
+
description: 'Bootstrap brain lessons from git history. Parses commit messages and infers fix/feature/refactor ' +
|
|
3867
|
+
'lessons automatically. Great for onboarding an existing codebase — run once and the brain instantly ' +
|
|
3868
|
+
'knows your team\'s accumulated patterns. Supports limit and branch options.',
|
|
3869
|
+
inputSchema: {
|
|
3870
|
+
type: 'object',
|
|
3871
|
+
properties: {
|
|
3872
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3873
|
+
repo_path: { type: 'string', description: 'Path to git repository (default: current directory)' },
|
|
3874
|
+
limit: { type: 'number', description: 'Max commits to process (default: 100, max: 500)' },
|
|
3875
|
+
branch: { type: 'string', description: 'Git branch to parse (default: current branch / HEAD)' },
|
|
3876
|
+
since: { type: 'string', description: 'Only commits after this date, e.g. "2024-01-01" (optional)' },
|
|
3877
|
+
},
|
|
3878
|
+
required: ['instance_id'],
|
|
3879
|
+
},
|
|
3880
|
+
},
|
|
3881
|
+
{
|
|
3882
|
+
name: 'brain_predict_failures',
|
|
3883
|
+
description: 'Pre-deploy failure prediction with probability percentages. Given a change context (e.g. ' +
|
|
3884
|
+
'"upgrading Keycloak 21→24" or "deploying Redis 7 to prod"), returns the top likely failure modes ' +
|
|
3885
|
+
'ranked by probability, with pre-loaded fixes. Uses CKG causal edges + lesson history. ' +
|
|
3886
|
+
'Call before any significant deploy, migration, or infrastructure change.',
|
|
3887
|
+
inputSchema: {
|
|
3888
|
+
type: 'object',
|
|
3889
|
+
properties: {
|
|
3890
|
+
instance_id: { type: 'string', description: 'Brain instance ID' },
|
|
3891
|
+
context: { type: 'string', description: 'What you are about to do, e.g. "upgrading Keycloak 21 to 24"' },
|
|
3892
|
+
top_k: { type: 'number', description: 'Number of failure predictions to return (default: 5)' },
|
|
3893
|
+
format: { type: 'string', enum: ['brief', 'detailed'], description: 'Output format (default: detailed)' },
|
|
3894
|
+
},
|
|
3895
|
+
required: ['instance_id', 'context'],
|
|
3896
|
+
},
|
|
3897
|
+
},
|
|
3807
3898
|
];
|
|
3808
3899
|
// ── Handlers ──────────────────────────────────────────────────────────────────
|
|
3809
3900
|
function formatInstance(inst) {
|
|
@@ -8442,6 +8533,387 @@ smart_recall(
|
|
|
8442
8533
|
lines.push('', '---', `**Contribute:** \`fedbrain_contribute(lesson_key="fix:...")\``, `**Search:** \`fedbrain_search(query="...")\``, `**Confirm:** \`fedbrain_confirm(topic="...", outcome="worked")\``);
|
|
8443
8534
|
return lines.join('\n');
|
|
8444
8535
|
}
|
|
8536
|
+
// ── crystal_view ──────────────────────────────────────────────────────────
|
|
8537
|
+
case 'crystal_view': {
|
|
8538
|
+
const { instance_id, show_raw = false } = args;
|
|
8539
|
+
const redis = await getConnection(instance_id);
|
|
8540
|
+
const raw = await redis.get('cachly:crystal:latest');
|
|
8541
|
+
if (!raw) {
|
|
8542
|
+
return [
|
|
8543
|
+
`💎 **Memory Crystal: not yet created**`, '',
|
|
8544
|
+
`No crystal found. Create one with \`memory_crystalize()\` to compress your accumulated wisdom.`,
|
|
8545
|
+
'', `💡 Tip: run \`memory_crystalize\` monthly for best results.`,
|
|
8546
|
+
].join('\n');
|
|
8547
|
+
}
|
|
8548
|
+
const crystal = JSON.parse(raw);
|
|
8549
|
+
const age = Math.floor((Date.now() - new Date(crystal.ts).getTime()) / 86400000);
|
|
8550
|
+
const freshEmoji = age <= 7 ? '🟢' : age <= 30 ? '🟡' : '🔴';
|
|
8551
|
+
const lines = [
|
|
8552
|
+
`💎 **Memory Crystal: ${crystal.label}**`, '',
|
|
8553
|
+
`📅 Created: ${new Date(crystal.ts).toLocaleDateString('de-DE')} (${age}d ago ${freshEmoji})`,
|
|
8554
|
+
`📊 Compressed from: ${crystal.created_from}`,
|
|
8555
|
+
`🗂️ Categories: ${crystal.categories.slice(0, 10).map(c => `\`${c}\``).join(', ')}${crystal.categories.length > 10 ? ` +${crystal.categories.length - 10} more` : ''}`,
|
|
8556
|
+
'',
|
|
8557
|
+
`**🔑 Top patterns (${crystal.top_patterns.length}):**`,
|
|
8558
|
+
];
|
|
8559
|
+
for (const p of crystal.top_patterns) {
|
|
8560
|
+
lines.push(` • **${p.category}** (${p.count}×): ${p.insight.slice(0, 110)}`);
|
|
8561
|
+
}
|
|
8562
|
+
if (age > 30) {
|
|
8563
|
+
lines.push('', `⚠️ Crystal is ${age}d old — run \`memory_crystalize()\` to refresh it.`);
|
|
8564
|
+
}
|
|
8565
|
+
if (show_raw) {
|
|
8566
|
+
lines.push('', '```json', JSON.stringify(crystal, null, 2), '```');
|
|
8567
|
+
}
|
|
8568
|
+
lines.push('', `💡 Refresh: \`memory_crystalize()\` | Recover: \`compact_recover(instance_id="...")\``);
|
|
8569
|
+
return lines.join('\n');
|
|
8570
|
+
}
|
|
8571
|
+
// ── compact_recover ───────────────────────────────────────────────────────
|
|
8572
|
+
case 'compact_recover': {
|
|
8573
|
+
const { instance_id, focus = '' } = args;
|
|
8574
|
+
const redis = await getConnection(instance_id);
|
|
8575
|
+
const lines = [`🔁 **Compact Recovery Briefing**\n`];
|
|
8576
|
+
lines.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*\n`);
|
|
8577
|
+
// 1. Memory Crystal
|
|
8578
|
+
const crystalRaw = await redis.get('cachly:crystal:latest');
|
|
8579
|
+
if (crystalRaw) {
|
|
8580
|
+
const crystal = JSON.parse(crystalRaw);
|
|
8581
|
+
lines.push(`### 💎 Memory Crystal: ${crystal.label}`);
|
|
8582
|
+
lines.push(`Compressed from ${crystal.session_count} sessions, ${crystal.lesson_count} lessons.`);
|
|
8583
|
+
const topN = focus
|
|
8584
|
+
? crystal.top_patterns.filter(p => p.category.toLowerCase().includes(focus.toLowerCase()) || p.insight.toLowerCase().includes(focus.toLowerCase())).slice(0, 4)
|
|
8585
|
+
: crystal.top_patterns.slice(0, 4);
|
|
8586
|
+
for (const p of topN)
|
|
8587
|
+
lines.push(` • **${p.category}**: ${p.insight.slice(0, 100)}`);
|
|
8588
|
+
lines.push('');
|
|
8589
|
+
}
|
|
8590
|
+
// 2. Last session summary
|
|
8591
|
+
const lastSession = await redis.get('cachly:session:last');
|
|
8592
|
+
if (lastSession) {
|
|
8593
|
+
const sess = JSON.parse(lastSession);
|
|
8594
|
+
lines.push(`### 🕐 Last Session`);
|
|
8595
|
+
if (sess.focus)
|
|
8596
|
+
lines.push(`Focus: _${sess.focus}_`);
|
|
8597
|
+
if (sess.summary)
|
|
8598
|
+
lines.push(`Summary: ${sess.summary.slice(0, 300)}`);
|
|
8599
|
+
lines.push('');
|
|
8600
|
+
}
|
|
8601
|
+
// 3. Session handoff
|
|
8602
|
+
const handoff = await redis.get('cachly:session:handoff');
|
|
8603
|
+
if (handoff) {
|
|
8604
|
+
const h = JSON.parse(handoff);
|
|
8605
|
+
lines.push(`### 📋 Handoff (from last window)`);
|
|
8606
|
+
if (h.context_summary)
|
|
8607
|
+
lines.push(`Context: ${h.context_summary.slice(0, 200)}`);
|
|
8608
|
+
if (h.remaining_tasks?.length) {
|
|
8609
|
+
lines.push(`Remaining tasks:`);
|
|
8610
|
+
for (const t of h.remaining_tasks.slice(0, 5))
|
|
8611
|
+
lines.push(` • ${t}`);
|
|
8612
|
+
}
|
|
8613
|
+
if (h.instructions)
|
|
8614
|
+
lines.push(`⚠️ Instructions: ${h.instructions.slice(0, 200)}`);
|
|
8615
|
+
if (h.blocked_on)
|
|
8616
|
+
lines.push(`🚧 Blocked on: ${h.blocked_on}`);
|
|
8617
|
+
lines.push('');
|
|
8618
|
+
}
|
|
8619
|
+
// 4. WIP registry
|
|
8620
|
+
const wipRaw = await redis.get('cachly:ctx:wip-registry');
|
|
8621
|
+
if (wipRaw) {
|
|
8622
|
+
const wip = JSON.parse(wipRaw);
|
|
8623
|
+
if (wip.content) {
|
|
8624
|
+
lines.push(`### 🔧 WIP Registry`);
|
|
8625
|
+
lines.push(wip.content.slice(0, 400));
|
|
8626
|
+
lines.push('');
|
|
8627
|
+
}
|
|
8628
|
+
}
|
|
8629
|
+
// 5. Open failures (roadmap with status=blocked/in_progress)
|
|
8630
|
+
const roadmapKeys = [];
|
|
8631
|
+
const rStream = redis.scanStream({ match: 'cachly:roadmap:*', count: 100 });
|
|
8632
|
+
await new Promise((res, rej) => { rStream.on('data', (b) => roadmapKeys.push(...b)); rStream.on('end', res); rStream.on('error', rej); });
|
|
8633
|
+
const openItems = [];
|
|
8634
|
+
for (const k of roadmapKeys.slice(0, 30)) {
|
|
8635
|
+
const r = await redis.get(k);
|
|
8636
|
+
if (!r)
|
|
8637
|
+
continue;
|
|
8638
|
+
try {
|
|
8639
|
+
const item = JSON.parse(r);
|
|
8640
|
+
if (item.status === 'in_progress' || item.status === 'blocked')
|
|
8641
|
+
openItems.push({ title: item.title ?? k, status: item.status, priority: item.priority });
|
|
8642
|
+
}
|
|
8643
|
+
catch { /* skip */ }
|
|
8644
|
+
}
|
|
8645
|
+
if (openItems.length > 0) {
|
|
8646
|
+
lines.push(`### 🚧 Open Items`);
|
|
8647
|
+
for (const i of openItems.slice(0, 5))
|
|
8648
|
+
lines.push(` • [${i.status}] ${i.title}`);
|
|
8649
|
+
lines.push('');
|
|
8650
|
+
}
|
|
8651
|
+
// 6. Focus-relevant lessons
|
|
8652
|
+
if (focus) {
|
|
8653
|
+
const lessonKeys = [];
|
|
8654
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 200 });
|
|
8655
|
+
await new Promise((res, rej) => { lStream.on('data', (b) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
8656
|
+
const relevant = [];
|
|
8657
|
+
for (const k of lessonKeys) {
|
|
8658
|
+
const r = await redis.get(k);
|
|
8659
|
+
if (!r)
|
|
8660
|
+
continue;
|
|
8661
|
+
try {
|
|
8662
|
+
const l = JSON.parse(r);
|
|
8663
|
+
if (l.topic.toLowerCase().includes(focus.toLowerCase()) && l.what_worked) {
|
|
8664
|
+
relevant.push({ topic: l.topic, what_worked: l.what_worked });
|
|
8665
|
+
}
|
|
8666
|
+
}
|
|
8667
|
+
catch { /* skip */ }
|
|
8668
|
+
}
|
|
8669
|
+
if (relevant.length > 0) {
|
|
8670
|
+
lines.push(`### 💡 Relevant Lessons for "${focus}"`);
|
|
8671
|
+
for (const l of relevant.slice(0, 4))
|
|
8672
|
+
lines.push(` • **${l.topic}**: ${l.what_worked.slice(0, 100)}`);
|
|
8673
|
+
lines.push('');
|
|
8674
|
+
}
|
|
8675
|
+
}
|
|
8676
|
+
if (lines.length <= 3) {
|
|
8677
|
+
lines.push(`_No brain data found. Start accumulating knowledge with \`learn_from_attempts\` and \`session_start\`._`);
|
|
8678
|
+
}
|
|
8679
|
+
lines.push(`---`, `🧠 Brain is ready. Continue your work — full context restored.`);
|
|
8680
|
+
return lines.join('\n');
|
|
8681
|
+
}
|
|
8682
|
+
// ── brain_from_git ────────────────────────────────────────────────────────
|
|
8683
|
+
case 'brain_from_git': {
|
|
8684
|
+
const { instance_id, repo_path = '.', limit = 100, branch = 'HEAD', since = '' } = args;
|
|
8685
|
+
const redis = await getConnection(instance_id);
|
|
8686
|
+
const { execSync } = await import('node:child_process');
|
|
8687
|
+
const { resolve } = await import('node:path');
|
|
8688
|
+
const repoDir = resolve(repo_path);
|
|
8689
|
+
const maxCommits = Math.min(Number(limit) || 100, 500);
|
|
8690
|
+
// Verify it's a git repo
|
|
8691
|
+
try {
|
|
8692
|
+
execSync('git rev-parse --git-dir', { cwd: repoDir, stdio: 'pipe' });
|
|
8693
|
+
}
|
|
8694
|
+
catch {
|
|
8695
|
+
return `❌ Not a git repository: \`${repoDir}\`. Pass \`repo_path\` pointing to a git checkout.`;
|
|
8696
|
+
}
|
|
8697
|
+
// Build git log command
|
|
8698
|
+
const sinceFlag = since ? `--since="${since}"` : '';
|
|
8699
|
+
const logCmd = `git log ${branch} ${sinceFlag} --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n ${maxCommits}`;
|
|
8700
|
+
let logOutput = '';
|
|
8701
|
+
try {
|
|
8702
|
+
logOutput = execSync(logCmd, { cwd: repoDir, encoding: 'utf-8', stdio: 'pipe' });
|
|
8703
|
+
}
|
|
8704
|
+
catch (e) {
|
|
8705
|
+
return `❌ git log failed: ${e.message}. Check \`repo_path\` and \`branch\`.`;
|
|
8706
|
+
}
|
|
8707
|
+
const commits = logOutput.trim().split('\n').filter(Boolean).map(line => {
|
|
8708
|
+
const [sha, subject, date, author] = line.split('|||');
|
|
8709
|
+
return { sha: (sha ?? '').trim(), subject: (subject ?? '').trim(), date: (date ?? '').trim(), author: (author ?? '').trim() };
|
|
8710
|
+
});
|
|
8711
|
+
if (commits.length === 0) {
|
|
8712
|
+
return `⚠️ No commits found in \`${repoDir}\` on branch \`${branch}\`${since ? ` since ${since}` : ''}.`;
|
|
8713
|
+
}
|
|
8714
|
+
// Pattern classifiers
|
|
8715
|
+
const classifyCommit = (subject) => {
|
|
8716
|
+
const s = subject.toLowerCase();
|
|
8717
|
+
if (/\b(fix|fixed|fixes|bug|hotfix|patch|revert|resolve|closes? #\d+)\b/.test(s)) {
|
|
8718
|
+
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';
|
|
8719
|
+
return { category: 'fix', outcome: 'success', severity: sev };
|
|
8720
|
+
}
|
|
8721
|
+
if (/\b(feat|feature|add|added|implement|new|introduce)\b/.test(s))
|
|
8722
|
+
return { category: 'feat', outcome: 'success', severity: 'minor' };
|
|
8723
|
+
if (/\b(refactor|clean|cleanup|improve|simplify|extract|rename)\b/.test(s))
|
|
8724
|
+
return { category: 'refactor', outcome: 'success', severity: 'minor' };
|
|
8725
|
+
if (/\b(perf|optimize|speed|cache|latency|memory|performance)\b/.test(s))
|
|
8726
|
+
return { category: 'perf', outcome: 'success', severity: 'major' };
|
|
8727
|
+
if (/\b(security|cve|auth|csrf|xss|sql|injection|sanitize|escape|encrypt)\b/.test(s))
|
|
8728
|
+
return { category: 'security', outcome: 'success', severity: 'critical' };
|
|
8729
|
+
if (/\b(deploy|ci|cd|build|docker|k8s|helm|infra|devops)\b/.test(s))
|
|
8730
|
+
return { category: 'deploy', outcome: 'success', severity: 'major' };
|
|
8731
|
+
if (/\b(test|spec|coverage|assert|mock|unit|integration)\b/.test(s))
|
|
8732
|
+
return { category: 'test', outcome: 'success', severity: 'minor' };
|
|
8733
|
+
return { category: 'chore', outcome: 'success', severity: 'minor' };
|
|
8734
|
+
};
|
|
8735
|
+
// Extract domain keywords from commit subject
|
|
8736
|
+
const extractDomain = (subject) => {
|
|
8737
|
+
const s = subject.toLowerCase();
|
|
8738
|
+
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));
|
|
8739
|
+
return tokens.slice(0, 3).join('-') || 'general';
|
|
8740
|
+
};
|
|
8741
|
+
const ts = new Date().toISOString();
|
|
8742
|
+
let ingested = 0;
|
|
8743
|
+
let skipped = 0;
|
|
8744
|
+
const categoryCount = new Map();
|
|
8745
|
+
for (const commit of commits) {
|
|
8746
|
+
if (!commit.subject) {
|
|
8747
|
+
skipped++;
|
|
8748
|
+
continue;
|
|
8749
|
+
}
|
|
8750
|
+
const { category, outcome, severity } = classifyCommit(commit.subject);
|
|
8751
|
+
const domain = extractDomain(commit.subject);
|
|
8752
|
+
const topic = `${category}:${domain}`;
|
|
8753
|
+
categoryCount.set(category, (categoryCount.get(category) ?? 0) + 1);
|
|
8754
|
+
const lessonObj = {
|
|
8755
|
+
topic, outcome, severity,
|
|
8756
|
+
what_worked: commit.subject.slice(0, 200),
|
|
8757
|
+
what_failed: '',
|
|
8758
|
+
context: `git:${commit.sha.slice(0, 8)} by ${commit.author} on ${commit.date}`,
|
|
8759
|
+
file_paths: [], commands: [`git show ${commit.sha.slice(0, 8)}`],
|
|
8760
|
+
tags: ['brain_from_git', category, 'git-history'],
|
|
8761
|
+
depends_on: [], recall_count: 0, ts, verified_at: ts,
|
|
8762
|
+
confidence: 0.55, // lower confidence for auto-inferred lessons
|
|
8763
|
+
audit_trail: [{ ts, action: 'brain_from_git', sha: commit.sha.slice(0, 8) }],
|
|
8764
|
+
version: 3,
|
|
8765
|
+
};
|
|
8766
|
+
// Only store if no existing lesson for this topic (avoid overwriting higher-confidence lessons)
|
|
8767
|
+
const existing = await redis.get(`cachly:lesson:best:${topic}`);
|
|
8768
|
+
if (!existing) {
|
|
8769
|
+
await redis.set(`cachly:lesson:best:${topic}`, JSON.stringify(lessonObj));
|
|
8770
|
+
await redis.rpush(`cachly:lessons:${topic}`, JSON.stringify(lessonObj));
|
|
8771
|
+
}
|
|
8772
|
+
await redis.rpush('cachly:lessons:brain_from_git:all', JSON.stringify({ topic, sha: commit.sha.slice(0, 8), subject: commit.subject.slice(0, 60) }));
|
|
8773
|
+
await redis.ltrim('cachly:lessons:brain_from_git:all', -500, -1);
|
|
8774
|
+
// Update CKG
|
|
8775
|
+
const conceptId = ckgSlug(topic);
|
|
8776
|
+
await ckgUpsertNode(redis, conceptId, category, 'git-derived');
|
|
8777
|
+
ingested++;
|
|
8778
|
+
}
|
|
8779
|
+
const categoryBreakdown = [...categoryCount.entries()].sort((a, b) => b[1] - a[1]).map(([k, v]) => ` • **${k}** (${v})`).join('\n');
|
|
8780
|
+
return [
|
|
8781
|
+
`🔁 **brain_from_git: ${repoDir}**`, '',
|
|
8782
|
+
`📂 Branch: \`${branch}\` | Processed: **${commits.length}** commits | Ingested: **${ingested}** lessons | Skipped: ${skipped}`,
|
|
8783
|
+
``,
|
|
8784
|
+
`**Breakdown by category:**`,
|
|
8785
|
+
categoryBreakdown,
|
|
8786
|
+
``,
|
|
8787
|
+
`💡 New lessons are stored with confidence 0.55 (auto-inferred).`,
|
|
8788
|
+
`💡 As you confirm them via \`learn_from_attempts\`, confidence rises automatically.`,
|
|
8789
|
+
`🔍 Explore: \`brain_search(query="fix")\` | \`ckg_inspect(concept="deploy")\``,
|
|
8790
|
+
].join('\n');
|
|
8791
|
+
}
|
|
8792
|
+
// ── brain_predict_failures ─────────────────────────────────────────────────
|
|
8793
|
+
case 'brain_predict_failures': {
|
|
8794
|
+
const { instance_id, context: ctx, top_k = 5, format = 'detailed' } = args;
|
|
8795
|
+
const redis = await getConnection(instance_id);
|
|
8796
|
+
const ctxTokens = ctx.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g, ' ').split(/\s+/).filter(t => t.length > 2);
|
|
8797
|
+
const failures = [];
|
|
8798
|
+
// Step 1: CKG — find 'causes' and 'degrades_under' edges from context tokens
|
|
8799
|
+
for (const token of ctxTokens.slice(0, 8)) {
|
|
8800
|
+
const nodeKeys = [];
|
|
8801
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
|
|
8802
|
+
await new Promise((res, rej) => { nStream.on('data', (b) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
8803
|
+
for (const nk of nodeKeys.slice(0, 5)) {
|
|
8804
|
+
const nodeRaw = await redis.get(nk);
|
|
8805
|
+
if (!nodeRaw)
|
|
8806
|
+
continue;
|
|
8807
|
+
const node = JSON.parse(nodeRaw);
|
|
8808
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
8809
|
+
for (const ek of edgeKeys.slice(0, 20)) {
|
|
8810
|
+
const edgeRaw = await redis.get(ek);
|
|
8811
|
+
if (!edgeRaw)
|
|
8812
|
+
continue;
|
|
8813
|
+
const edge = JSON.parse(edgeRaw);
|
|
8814
|
+
if (edge.edgeType !== 'causes' && edge.edgeType !== 'degrades_under')
|
|
8815
|
+
continue;
|
|
8816
|
+
// Look up fix for this failure from CKG 'fixes' edges
|
|
8817
|
+
const fixEdgeKeys = await redis.smembers(`cachly:ckg:idx:from:${edge.to}`);
|
|
8818
|
+
let fix;
|
|
8819
|
+
for (const fek of fixEdgeKeys.slice(0, 10)) {
|
|
8820
|
+
const feRaw = await redis.get(fek);
|
|
8821
|
+
if (!feRaw)
|
|
8822
|
+
continue;
|
|
8823
|
+
const fe = JSON.parse(feRaw);
|
|
8824
|
+
if (fe.edgeType === 'fixes') {
|
|
8825
|
+
const lessonRaw = await redis.get(`cachly:lesson:best:${fe.from}`);
|
|
8826
|
+
if (lessonRaw) {
|
|
8827
|
+
const lesson = JSON.parse(lessonRaw);
|
|
8828
|
+
fix = lesson.what_worked?.slice(0, 120);
|
|
8829
|
+
break;
|
|
8830
|
+
}
|
|
8831
|
+
}
|
|
8832
|
+
}
|
|
8833
|
+
failures.push({
|
|
8834
|
+
concept: node.id,
|
|
8835
|
+
failure: edge.to.replace(/-/g, ' '),
|
|
8836
|
+
probability: edge.confidence,
|
|
8837
|
+
fix,
|
|
8838
|
+
source: 'ckg',
|
|
8839
|
+
});
|
|
8840
|
+
}
|
|
8841
|
+
}
|
|
8842
|
+
}
|
|
8843
|
+
// Step 2: Lesson history — find failure-outcome lessons matching context
|
|
8844
|
+
const lessonKeys = [];
|
|
8845
|
+
const lStream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 300 });
|
|
8846
|
+
await new Promise((res, rej) => { lStream.on('data', (b) => lessonKeys.push(...b)); lStream.on('end', res); lStream.on('error', rej); });
|
|
8847
|
+
for (const k of lessonKeys.slice(0, 100)) {
|
|
8848
|
+
const r = await redis.get(k);
|
|
8849
|
+
if (!r)
|
|
8850
|
+
continue;
|
|
8851
|
+
try {
|
|
8852
|
+
const l = JSON.parse(r);
|
|
8853
|
+
if (l.outcome !== 'failure' && l.outcome !== 'partial')
|
|
8854
|
+
continue;
|
|
8855
|
+
if (!l.what_failed)
|
|
8856
|
+
continue;
|
|
8857
|
+
const haystack = `${l.topic} ${l.what_failed}`.toLowerCase();
|
|
8858
|
+
const matchScore = ctxTokens.filter(t => haystack.includes(t)).length / Math.max(1, ctxTokens.length);
|
|
8859
|
+
if (matchScore < 0.15)
|
|
8860
|
+
continue;
|
|
8861
|
+
const sevBoost = l.severity === 'critical' ? 0.15 : l.severity === 'major' ? 0.05 : 0;
|
|
8862
|
+
failures.push({
|
|
8863
|
+
concept: l.topic,
|
|
8864
|
+
failure: l.what_failed.slice(0, 80),
|
|
8865
|
+
probability: Math.min(0.97, (l.confidence ?? 0.5) * matchScore * 1.5 + sevBoost),
|
|
8866
|
+
fix: l.what_worked?.slice(0, 120),
|
|
8867
|
+
topic: l.topic,
|
|
8868
|
+
source: 'lesson',
|
|
8869
|
+
});
|
|
8870
|
+
}
|
|
8871
|
+
catch { /* skip */ }
|
|
8872
|
+
}
|
|
8873
|
+
if (failures.length === 0) {
|
|
8874
|
+
return [
|
|
8875
|
+
`🔮 **Failure Prediction: "${ctx}"**`, '',
|
|
8876
|
+
`No known failure patterns found for this context.`,
|
|
8877
|
+
`💡 The brain learns from every \`learn_from_attempts(outcome="failure")\` call.`,
|
|
8878
|
+
`🔍 Try: \`brain_predict(context="${ctx}")\` for broader predictions.`,
|
|
8879
|
+
].join('\n');
|
|
8880
|
+
}
|
|
8881
|
+
// Deduplicate and rank by probability
|
|
8882
|
+
const seen = new Set();
|
|
8883
|
+
const ranked = failures.filter(f => {
|
|
8884
|
+
const k = f.failure.slice(0, 40);
|
|
8885
|
+
if (seen.has(k))
|
|
8886
|
+
return false;
|
|
8887
|
+
seen.add(k);
|
|
8888
|
+
return true;
|
|
8889
|
+
}).sort((a, b) => b.probability - a.probability).slice(0, Number(top_k));
|
|
8890
|
+
const lines = [`🔮 **Failure Prediction for: "${ctx}"**\n`];
|
|
8891
|
+
lines.push(`> Pre-deploy failure analysis based on ${failures.length} patterns. Ranked by probability.\n`);
|
|
8892
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
8893
|
+
const f = ranked[i];
|
|
8894
|
+
const pct = Math.round(f.probability * 100);
|
|
8895
|
+
const bar = '█'.repeat(Math.round(pct / 10)) + '░'.repeat(10 - Math.round(pct / 10));
|
|
8896
|
+
const icon = pct >= 70 ? '🔴' : pct >= 40 ? '🟡' : '🟢';
|
|
8897
|
+
lines.push(`${icon} **${i + 1}. ${f.failure}**`);
|
|
8898
|
+
lines.push(` Probability: ${bar} **${pct}%** (${f.source === 'ckg' ? 'CKG causal edge' : 'lesson history'})`);
|
|
8899
|
+
if (format === 'detailed' && f.fix) {
|
|
8900
|
+
lines.push(` ✅ Pre-loaded fix: _${f.fix}_`);
|
|
8901
|
+
}
|
|
8902
|
+
if (format === 'detailed' && f.topic) {
|
|
8903
|
+
lines.push(` 📚 Lesson: \`${f.topic}\``);
|
|
8904
|
+
}
|
|
8905
|
+
lines.push('');
|
|
8906
|
+
}
|
|
8907
|
+
const highRisk = ranked.filter(f => f.probability >= 0.6);
|
|
8908
|
+
if (highRisk.length > 0) {
|
|
8909
|
+
lines.push(`⚠️ **${highRisk.length} high-risk failure${highRisk.length > 1 ? 's' : ''} detected** (≥60% probability). Review fixes before proceeding.`);
|
|
8910
|
+
}
|
|
8911
|
+
else {
|
|
8912
|
+
lines.push(`✅ No high-risk failures detected. Proceed with caution and monitor closely.`);
|
|
8913
|
+
}
|
|
8914
|
+
lines.push('', `💡 After deploy: \`learn_from_attempts(topic="deploy:...", outcome="success|failure")\` to improve future predictions.`);
|
|
8915
|
+
return lines.join('\n');
|
|
8916
|
+
}
|
|
8445
8917
|
default:
|
|
8446
8918
|
return null;
|
|
8447
8919
|
}
|
|
@@ -9080,6 +9552,21 @@ if (!JWT) {
|
|
|
9080
9552
|
'╚══════════════════════════════════════════════════════════════════╝\n' +
|
|
9081
9553
|
'\n');
|
|
9082
9554
|
}
|
|
9555
|
+
else {
|
|
9556
|
+
// Warn if the JWT is already expired or expiring within the hour.
|
|
9557
|
+
const expMs = jwtExpiryMs(JWT);
|
|
9558
|
+
if (expMs !== null) {
|
|
9559
|
+
const minsLeft = Math.floor((expMs - Date.now()) / 60_000);
|
|
9560
|
+
if (minsLeft <= 0) {
|
|
9561
|
+
process.stderr.write(`\n⚠️ cachly: CACHLY_JWT expired ${Math.abs(minsLeft)} minute(s) ago.\n` +
|
|
9562
|
+
` All tool calls will fail. Get a fresh token at https://cachly.dev/setup-ai\n\n`);
|
|
9563
|
+
}
|
|
9564
|
+
else if (minsLeft < 60) {
|
|
9565
|
+
process.stderr.write(`\n⚠️ cachly: CACHLY_JWT expires in ${minsLeft} minute(s).\n` +
|
|
9566
|
+
` Refresh it soon at https://cachly.dev/setup-ai to avoid interruptions.\n\n`);
|
|
9567
|
+
}
|
|
9568
|
+
}
|
|
9569
|
+
}
|
|
9083
9570
|
// ── Update nudge (non-blocking, fire-and-forget) ─────────────────────────────
|
|
9084
9571
|
// Check npm registry once per process start; if outdated, log to stderr so
|
|
9085
9572
|
// the editor's MCP log shows an actionable one-liner. Skipped if opted out.
|