@cachly-dev/mcp-server 0.9.14 → 0.9.16
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 +355 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +338 -2
package/dist/index.js
CHANGED
|
@@ -3904,6 +3904,26 @@ const TOOLS = [
|
|
|
3904
3904
|
required: ['instance_id'],
|
|
3905
3905
|
},
|
|
3906
3906
|
},
|
|
3907
|
+
{
|
|
3908
|
+
name: 'brain_federate',
|
|
3909
|
+
description: 'FedBrain Layer 6 — Private org knowledge transfer: copy CKG edges + lessons from a source brain ' +
|
|
3910
|
+
'into your brain for a specific domain (e.g. "billing", "auth", "deploy"). ' +
|
|
3911
|
+
'The new hire use case: one command gives you the senior engineer\'s 5 years of typed, confidence-weighted ' +
|
|
3912
|
+
'knowledge in your domain. Unlike syndicate_search (global, anonymous), brain_federate is org-private — ' +
|
|
3913
|
+
'both brains must be in the same Cachly org, or the source instance_id must be explicitly shared. ' +
|
|
3914
|
+
'Example: brain_federate(source="prod-brain-id", domain="billing", min_confidence=0.6)',
|
|
3915
|
+
inputSchema: {
|
|
3916
|
+
type: 'object',
|
|
3917
|
+
properties: {
|
|
3918
|
+
instance_id: { type: 'string', description: 'Your brain instance ID (destination)' },
|
|
3919
|
+
source: { type: 'string', description: 'Source brain instance ID to federate from' },
|
|
3920
|
+
domain: { type: 'string', description: 'Domain to transfer, e.g. "billing", "auth", "deploy", "infra". Use "*" for all domains.' },
|
|
3921
|
+
min_confidence: { type: 'number', description: 'Minimum edge confidence to transfer (default: 0.6)' },
|
|
3922
|
+
dry_run: { type: 'boolean', description: 'Preview what would be transferred without writing (default: false)' },
|
|
3923
|
+
},
|
|
3924
|
+
required: ['instance_id', 'source', 'domain'],
|
|
3925
|
+
},
|
|
3926
|
+
},
|
|
3907
3927
|
{
|
|
3908
3928
|
name: 'crystal_view',
|
|
3909
3929
|
description: 'Inspect the current Memory Crystal — the compressed wisdom distilled from all past sessions. ' +
|
|
@@ -4979,6 +4999,8 @@ async function handleTool(name, args) {
|
|
|
4979
4999
|
// Store conflict marker
|
|
4980
5000
|
const conflictKey = `cachly:ckg:conflict:${conceptId}`;
|
|
4981
5001
|
await redis.set(conflictKey, JSON.stringify({ topic, detected_at: new Date().toISOString(), fix_confidence: existEdge.confidence, fix_trials: existEdge.trials, failure_outcome: outcome }), 'EX', 60 * 60 * 24 * 90);
|
|
5002
|
+
// Auto-trigger MADC deliberation in background — never blocks learn_from_attempts
|
|
5003
|
+
handleTool('madc_deliberate', { instance_id, topic }).catch(() => undefined);
|
|
4982
5004
|
}
|
|
4983
5005
|
}
|
|
4984
5006
|
}
|
|
@@ -5556,6 +5578,35 @@ async function handleTool(name, args) {
|
|
|
5556
5578
|
}
|
|
5557
5579
|
}
|
|
5558
5580
|
catch { /* non-critical */ }
|
|
5581
|
+
// ── Layer 7 MCM: Blind Spot Detection ────────────────────────────────────
|
|
5582
|
+
// If the focus mentions a domain that has no CKG node → surface blind spot
|
|
5583
|
+
if (focus && focus.length > 3) {
|
|
5584
|
+
try {
|
|
5585
|
+
const focusTokens = focus.toLowerCase().replace(/[^a-z0-9\s:_-]/g, ' ').split(/\s+/).filter(t => t.length > 3);
|
|
5586
|
+
const blindSpots = [];
|
|
5587
|
+
for (const token of focusTokens.slice(0, 6)) {
|
|
5588
|
+
const nodeExists = await redis.exists(`cachly:ckg:node:${token}`);
|
|
5589
|
+
if (!nodeExists) {
|
|
5590
|
+
// Check if any node starts with this token (prefix match)
|
|
5591
|
+
const prefixKeys = [];
|
|
5592
|
+
const psStream = redis.scanStream({ match: `cachly:ckg:node:${token}*`, count: 10 });
|
|
5593
|
+
await new Promise((res, rej) => { psStream.on('data', (b) => prefixKeys.push(...b)); psStream.on('end', res); psStream.on('error', rej); });
|
|
5594
|
+
if (prefixKeys.length === 0)
|
|
5595
|
+
blindSpots.push(token);
|
|
5596
|
+
}
|
|
5597
|
+
}
|
|
5598
|
+
if (blindSpots.length > 0) {
|
|
5599
|
+
lines.push(`🔭 **Blind spots detected for this focus:**`);
|
|
5600
|
+
for (const bs of blindSpots.slice(0, 3)) {
|
|
5601
|
+
lines.push(` ⬜ \`${bs}\` — no CKG knowledge. Suggestions:`);
|
|
5602
|
+
lines.push(` • \`brain_from_git(instance_id="...", concept="${bs}")\` — bootstrap from commits`);
|
|
5603
|
+
lines.push(` • \`fedbrain_search(query="${bs}")\` — search global commons`);
|
|
5604
|
+
}
|
|
5605
|
+
lines.push('');
|
|
5606
|
+
}
|
|
5607
|
+
}
|
|
5608
|
+
catch { /* non-critical */ }
|
|
5609
|
+
}
|
|
5559
5610
|
if (focusLessons.length > 0) {
|
|
5560
5611
|
lines.push(`🎯 **Relevant for "${focus}":**`);
|
|
5561
5612
|
for (const l of focusLessons.slice(0, 4)) {
|
|
@@ -5714,6 +5765,115 @@ async function handleTool(name, args) {
|
|
|
5714
5765
|
}
|
|
5715
5766
|
}
|
|
5716
5767
|
catch { /* non-critical */ }
|
|
5768
|
+
// ── 🔮 PPE: Predictive Pre-fetch — CKG-powered risk detection ────────────
|
|
5769
|
+
// Layer 4: Before starting any work, scan the CKG for nodes matching focus
|
|
5770
|
+
// tokens and traverse causal edges to surface predicted failure points inline.
|
|
5771
|
+
// This is the PPE "pre-fetch" that was previously only available via brain_predict.
|
|
5772
|
+
if (focus && focus.length > 3) {
|
|
5773
|
+
try {
|
|
5774
|
+
const ppeFocusTokens = focus.toLowerCase().replace(/[^a-z0-9\s\-_:]/g, ' ').split(/\s+/).filter(t => t.length > 2).slice(0, 5);
|
|
5775
|
+
const ppePredictions = [];
|
|
5776
|
+
for (const token of ppeFocusTokens) {
|
|
5777
|
+
const nodeKeys = [];
|
|
5778
|
+
const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 20 });
|
|
5779
|
+
await new Promise((res, rej) => { nStream.on('data', (b) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
5780
|
+
for (const nk of nodeKeys.slice(0, 3)) {
|
|
5781
|
+
const nodeRaw = await redis.get(nk);
|
|
5782
|
+
if (!nodeRaw)
|
|
5783
|
+
continue;
|
|
5784
|
+
const node = JSON.parse(nodeRaw);
|
|
5785
|
+
const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
5786
|
+
for (const ek of edgeKeys.slice(0, 15)) {
|
|
5787
|
+
const edgeRaw = await redis.get(ek);
|
|
5788
|
+
if (!edgeRaw)
|
|
5789
|
+
continue;
|
|
5790
|
+
const edge = JSON.parse(edgeRaw);
|
|
5791
|
+
if (edge.edgeType !== 'causes' && edge.edgeType !== 'co-occurs' && edge.edgeType !== 'fixes')
|
|
5792
|
+
continue;
|
|
5793
|
+
if (edge.confidence < 0.35)
|
|
5794
|
+
continue;
|
|
5795
|
+
// For "fixes" edges, the lesson is on the "from" node (fix for "to")
|
|
5796
|
+
// For "causes" edges, target is the failure mode
|
|
5797
|
+
const lessonKey = edge.edgeType === 'fixes' ? `cachly:lesson:best:${edge.from}` : `cachly:lesson:best:${edge.to}`;
|
|
5798
|
+
const lessonRaw = await redis.get(lessonKey);
|
|
5799
|
+
const lesson = lessonRaw ? JSON.parse(lessonRaw) : undefined;
|
|
5800
|
+
ppePredictions.push({ concept: node.id, edgeType: edge.edgeType, target: edge.to, confidence: edge.confidence, lesson });
|
|
5801
|
+
}
|
|
5802
|
+
}
|
|
5803
|
+
}
|
|
5804
|
+
const ppeSeen = new Set();
|
|
5805
|
+
const ppeUniq = ppePredictions
|
|
5806
|
+
.filter(p => { const k = `${p.concept}:${p.target}`; if (ppeSeen.has(k))
|
|
5807
|
+
return false; ppeSeen.add(k); return true; })
|
|
5808
|
+
.sort((a, b) => b.confidence - a.confidence)
|
|
5809
|
+
.slice(0, 4);
|
|
5810
|
+
if (ppeUniq.length > 0) {
|
|
5811
|
+
lines.push(`🔮 **Predicted risks for "${focus}"** (PPE pre-fetch):`);
|
|
5812
|
+
for (const p of ppeUniq) {
|
|
5813
|
+
const confPct = Math.round(p.confidence * 100);
|
|
5814
|
+
const icon = p.edgeType === 'causes' ? '⚡' : p.edgeType === 'fixes' ? '🔧' : '🔄';
|
|
5815
|
+
lines.push(` ${icon} **${confPct}%** \`${p.concept}\` ${p.edgeType} \`${p.target}\``);
|
|
5816
|
+
if (p.lesson?.what_worked)
|
|
5817
|
+
lines.push(` ✅ ${p.lesson.what_worked.slice(0, 110)}`);
|
|
5818
|
+
}
|
|
5819
|
+
lines.push(` _Full analysis: \`brain_predict(context="${focus}")\`_`);
|
|
5820
|
+
lines.push('');
|
|
5821
|
+
}
|
|
5822
|
+
}
|
|
5823
|
+
catch { /* non-critical — never block session start */ }
|
|
5824
|
+
}
|
|
5825
|
+
// ── 📐 MCM Confidence Calibration — 30-day accuracy pass ─────────────────
|
|
5826
|
+
// Layer 7: Periodically check if high-confidence lessons are actually reliable.
|
|
5827
|
+
// If last calibration was >30 days ago (or never), run a quick pass.
|
|
5828
|
+
// Measures: of recalled lessons with confidence > 0.85, what % had outcome=success?
|
|
5829
|
+
try {
|
|
5830
|
+
const calRaw = await redis.get('cachly:mcm:calibration:last');
|
|
5831
|
+
const lastCalMs = calRaw ? JSON.parse(calRaw).ts : 0;
|
|
5832
|
+
const daysSinceCal = (Date.now() - lastCalMs) / 86_400_000;
|
|
5833
|
+
if (daysSinceCal >= 30 && lessons.length >= 5) {
|
|
5834
|
+
// Quick calibration pass on recalled lessons (recall_count > 0, outcome=success)
|
|
5835
|
+
const recalledSuccess = lessons.filter(l => l.outcome === 'success' && (l.recall_count ?? 0) > 0);
|
|
5836
|
+
const recalledAll = lessons.filter(l => (l.recall_count ?? 0) > 0);
|
|
5837
|
+
if (recalledAll.length >= 3) {
|
|
5838
|
+
const precision = recalledAll.length > 0 ? recalledSuccess.length / recalledAll.length : 1;
|
|
5839
|
+
const lowPrecisionDomains = [];
|
|
5840
|
+
// Per-domain breakdown
|
|
5841
|
+
const domCalMap = new Map();
|
|
5842
|
+
for (const l of recalledAll) {
|
|
5843
|
+
const dom = l.topic.split(':')[0] ?? 'other';
|
|
5844
|
+
if (!domCalMap.has(dom))
|
|
5845
|
+
domCalMap.set(dom, { success: 0, total: 0 });
|
|
5846
|
+
const d = domCalMap.get(dom);
|
|
5847
|
+
d.total++;
|
|
5848
|
+
if (l.outcome === 'success')
|
|
5849
|
+
d.success++;
|
|
5850
|
+
}
|
|
5851
|
+
for (const [dom, d] of domCalMap) {
|
|
5852
|
+
if (d.total >= 2 && d.success / d.total < 0.6)
|
|
5853
|
+
lowPrecisionDomains.push(dom);
|
|
5854
|
+
}
|
|
5855
|
+
// Save calibration result
|
|
5856
|
+
await redis.set('cachly:mcm:calibration:last', JSON.stringify({
|
|
5857
|
+
ts: Date.now(),
|
|
5858
|
+
precision: precision,
|
|
5859
|
+
recalled: recalledAll.length,
|
|
5860
|
+
low_precision_domains: lowPrecisionDomains,
|
|
5861
|
+
}));
|
|
5862
|
+
if (lowPrecisionDomains.length > 0 || precision < 0.7) {
|
|
5863
|
+
lines.push(`📐 **MCM Calibration** (30-day pass — ${recalledAll.length} recalled lessons):`);
|
|
5864
|
+
lines.push(` Overall precision: **${(precision * 100).toFixed(0)}%** recalled lessons actually worked`);
|
|
5865
|
+
if (lowPrecisionDomains.length > 0) {
|
|
5866
|
+
lines.push(` ⚠️ Low-precision domains: ${lowPrecisionDomains.map(d => `\`${d}\``).join(', ')} — consider revisiting these lessons`);
|
|
5867
|
+
}
|
|
5868
|
+
lines.push(` 💡 Use \`learn_from_attempts\` to update stale lessons and improve accuracy.`);
|
|
5869
|
+
lines.push('');
|
|
5870
|
+
}
|
|
5871
|
+
}
|
|
5872
|
+
// Even if no issues, stamp the date so we don't re-check for 30d
|
|
5873
|
+
await redis.set('cachly:mcm:calibration:last', JSON.stringify({ ts: Date.now(), precision: 1, recalled: 0 }), 'EX', 35 * 86400);
|
|
5874
|
+
}
|
|
5875
|
+
}
|
|
5876
|
+
catch { /* non-critical */ }
|
|
5717
5877
|
// ── 🌍 Knowledge Commons — community stats banner ───────────────────────
|
|
5718
5878
|
// Fetch syndication stats and show a 1-liner: total lessons + confirms + weekly growth.
|
|
5719
5879
|
// Non-fatal: never blocks session start if the API call fails.
|
|
@@ -7506,8 +7666,55 @@ async function handleBulkLockStream(name, args) {
|
|
|
7506
7666
|
``,
|
|
7507
7667
|
`🔍 **Active** (recalled at least once): ${recalled.length}`,
|
|
7508
7668
|
``,
|
|
7509
|
-
`💡 Run \`memory_consolidate\` to merge duplicates · \`knowledge_decay\` to see confidence scores.`,
|
|
7510
7669
|
].filter(s => s !== '');
|
|
7670
|
+
// ── 10X brain_diff extensions ──────────────────────────────────────────
|
|
7671
|
+
// 1. Contested → Established (resolution nodes created in window)
|
|
7672
|
+
const resolutionKeys = [];
|
|
7673
|
+
const rsStream = redis.scanStream({ match: 'cachly:ckg:node:resolution-*', count: 100 });
|
|
7674
|
+
await new Promise((res, rej) => { rsStream.on('data', (b) => resolutionKeys.push(...b)); rsStream.on('end', res); rsStream.on('error', rej); });
|
|
7675
|
+
const recentResolutions = [];
|
|
7676
|
+
for (const rk of resolutionKeys) {
|
|
7677
|
+
const rr = await redis.get(rk);
|
|
7678
|
+
if (!rr)
|
|
7679
|
+
continue;
|
|
7680
|
+
try {
|
|
7681
|
+
const rn = JSON.parse(rr);
|
|
7682
|
+
if (rn.ts && new Date(rn.ts).getTime() >= sinceMs)
|
|
7683
|
+
recentResolutions.push({ topic: rn.topic ?? rk, resolution: rn.resolution ?? 'unknown', ts: rn.ts });
|
|
7684
|
+
}
|
|
7685
|
+
catch { /* skip */ }
|
|
7686
|
+
}
|
|
7687
|
+
if (recentResolutions.length > 0) {
|
|
7688
|
+
lines.push(`🗳️ **MADC Resolutions** (${recentResolutions.length} contested beliefs resolved):`);
|
|
7689
|
+
for (const r of recentResolutions.slice(0, 5)) {
|
|
7690
|
+
const rIcon = r.resolution === 'unanimous_success' ? '✅' : r.resolution === 'unanimous_failure' ? '❌' : '⚠️';
|
|
7691
|
+
lines.push(` ${rIcon} \`${r.topic}\` → ${r.resolution}`);
|
|
7692
|
+
}
|
|
7693
|
+
lines.push('');
|
|
7694
|
+
}
|
|
7695
|
+
// 2. New domains bootstrapped (domains in added lessons that weren't in older lessons)
|
|
7696
|
+
const existingDomains = new Set(updated.concat(recalled).map(l => l.topic.split(':')[0]));
|
|
7697
|
+
const newDomains = [...new Set(added.map(l => l.topic.split(':')[0]))].filter(d => !existingDomains.has(d));
|
|
7698
|
+
if (newDomains.length > 0) {
|
|
7699
|
+
lines.push(`🌱 **New domains bootstrapped:** ${newDomains.map(d => `\`${d}\``).join(', ')}`, '');
|
|
7700
|
+
}
|
|
7701
|
+
// 3. FedBrain transfers received in window
|
|
7702
|
+
const fedHistRaw = await redis.lrange('cachly:fedbrain:federations', -20, -1);
|
|
7703
|
+
const recentFeds = fedHistRaw.map(r => { try {
|
|
7704
|
+
return JSON.parse(r);
|
|
7705
|
+
}
|
|
7706
|
+
catch {
|
|
7707
|
+
return null;
|
|
7708
|
+
} })
|
|
7709
|
+
.filter(f => f && new Date(f.transferred_at).getTime() >= sinceMs);
|
|
7710
|
+
if (recentFeds.length > 0) {
|
|
7711
|
+
lines.push(`🧠 **FedBrain transfers received (${recentFeds.length}):**`);
|
|
7712
|
+
for (const f of recentFeds.slice(0, 3)) {
|
|
7713
|
+
lines.push(` 📥 domain \`${f.domain}\` from \`${f.source.slice(0, 16)}…\` — ${f.nodes} nodes, ${f.edges} edges`);
|
|
7714
|
+
}
|
|
7715
|
+
lines.push('');
|
|
7716
|
+
}
|
|
7717
|
+
lines.push(`💡 Run \`memory_consolidate\` to merge duplicates · \`knowledge_decay\` to see confidence scores.`);
|
|
7511
7718
|
return lines.join('\n');
|
|
7512
7719
|
}
|
|
7513
7720
|
// ── v0.6 Cognitive Cache: causal_trace ───────────────────────────────────
|
|
@@ -8279,10 +8486,38 @@ smart_recall(
|
|
|
8279
8486
|
votes: { success: successVotes, failure: failureVotes, abstain: abstainVotes },
|
|
8280
8487
|
};
|
|
8281
8488
|
await redis.set(`cachly:ckg:node:${resNodeId}`, JSON.stringify(resNode));
|
|
8282
|
-
// Write contradicts edge if contested
|
|
8489
|
+
// Write contradicts edge if contested; decay loser confidence to 0.1 if unanimous
|
|
8283
8490
|
if (resolution === 'contested') {
|
|
8284
8491
|
await ckgUpdateEdge(redis, ckgSlug(topic), 'contradicts', resNodeId, false);
|
|
8285
8492
|
}
|
|
8493
|
+
else {
|
|
8494
|
+
// Unanimous — demote the losing side's edges to near-zero confidence
|
|
8495
|
+
const loserOutcome = resolution === 'unanimous_success' ? 'failure' : 'success';
|
|
8496
|
+
const loserLessons = (loserOutcome === 'failure' ? failureLessons : successLessons);
|
|
8497
|
+
if (loserLessons.length > 0) {
|
|
8498
|
+
// Decay all 'fixes' edges from this concept that contradict the resolution
|
|
8499
|
+
const fromKeys = await redis.smembers(`cachly:ckg:idx:from:${ckgSlug(topic)}`);
|
|
8500
|
+
for (const fk of fromKeys) {
|
|
8501
|
+
const er = await redis.get(fk);
|
|
8502
|
+
if (!er)
|
|
8503
|
+
continue;
|
|
8504
|
+
try {
|
|
8505
|
+
const edge = JSON.parse(er);
|
|
8506
|
+
if (edge.edgeType === 'fixes' && edge.confidence > 0.15) {
|
|
8507
|
+
if (resolution === 'unanimous_failure') {
|
|
8508
|
+
// Fix was wrong — decay to 0.1
|
|
8509
|
+
edge.confidence = 0.1;
|
|
8510
|
+
edge.last_updated = new Date().toISOString();
|
|
8511
|
+
await redis.set(fk, JSON.stringify(edge));
|
|
8512
|
+
}
|
|
8513
|
+
}
|
|
8514
|
+
}
|
|
8515
|
+
catch { /* skip corrupt edges */ }
|
|
8516
|
+
}
|
|
8517
|
+
}
|
|
8518
|
+
// Remove the conflict marker — deliberation resolved it
|
|
8519
|
+
await redis.del(`cachly:ckg:conflict:${ckgSlug(topic)}`);
|
|
8520
|
+
}
|
|
8286
8521
|
const lines = [
|
|
8287
8522
|
`🗳️ **MADC Deliberation: "${topic}"**`, '',
|
|
8288
8523
|
`📊 Evidence: ${successLessons.length} success/partial vs ${failureLessons.length} failure entries (${history.length} total)`,
|
|
@@ -8690,6 +8925,124 @@ smart_recall(
|
|
|
8690
8925
|
lines.push('', '---', `**Contribute:** \`fedbrain_contribute(lesson_key="fix:...")\``, `**Search:** \`fedbrain_search(query="...")\``, `**Confirm:** \`fedbrain_confirm(topic="...", outcome="worked")\``);
|
|
8691
8926
|
return lines.join('\n');
|
|
8692
8927
|
}
|
|
8928
|
+
// ── Layer 6: FedBrain — brain_federate ───────────────────────────────────
|
|
8929
|
+
case 'brain_federate': {
|
|
8930
|
+
const { instance_id, source, domain, min_confidence = 0.6, dry_run = false } = args;
|
|
8931
|
+
if (instance_id === source)
|
|
8932
|
+
return `❌ Source and destination cannot be the same brain.`;
|
|
8933
|
+
const destRedis = await getConnection(instance_id);
|
|
8934
|
+
const srcRedis = await getConnection(source);
|
|
8935
|
+
const domainPattern = domain === '*' ? 'cachly:ckg:node:*' : `cachly:ckg:node:${domain}*`;
|
|
8936
|
+
// Scan source CKG nodes matching the domain
|
|
8937
|
+
const nodeKeys = [];
|
|
8938
|
+
const nStream = srcRedis.scanStream({ match: domainPattern, count: 100 });
|
|
8939
|
+
await new Promise((res, rej) => { nStream.on('data', (b) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
|
|
8940
|
+
if (nodeKeys.length === 0) {
|
|
8941
|
+
return [
|
|
8942
|
+
`🧠 **brain_federate: "${domain}"**`, '',
|
|
8943
|
+
`No CKG nodes found in source brain for domain \`${domain}\`.`,
|
|
8944
|
+
`The source brain may not have knowledge in this area yet.`,
|
|
8945
|
+
`Try: \`fedbrain_search(query="${domain}")\` to find global commons knowledge instead.`,
|
|
8946
|
+
].join('\n');
|
|
8947
|
+
}
|
|
8948
|
+
// Transfer nodes + their outgoing edges
|
|
8949
|
+
let nodesTransferred = 0;
|
|
8950
|
+
let edgesTransferred = 0;
|
|
8951
|
+
let lessonsTransferred = 0;
|
|
8952
|
+
let skippedLowConf = 0;
|
|
8953
|
+
const transferLog = [];
|
|
8954
|
+
for (const nk of nodeKeys) {
|
|
8955
|
+
const nodeRaw = await srcRedis.get(nk);
|
|
8956
|
+
if (!nodeRaw)
|
|
8957
|
+
continue;
|
|
8958
|
+
let node;
|
|
8959
|
+
try {
|
|
8960
|
+
node = JSON.parse(nodeRaw);
|
|
8961
|
+
}
|
|
8962
|
+
catch {
|
|
8963
|
+
continue;
|
|
8964
|
+
}
|
|
8965
|
+
if (!dry_run)
|
|
8966
|
+
await destRedis.set(nk, nodeRaw);
|
|
8967
|
+
nodesTransferred++;
|
|
8968
|
+
// Transfer outgoing edges for this node
|
|
8969
|
+
const edgeKeys = await srcRedis.smembers(`cachly:ckg:idx:from:${node.id}`);
|
|
8970
|
+
for (const ek of edgeKeys) {
|
|
8971
|
+
const edgeRaw = await srcRedis.get(ek);
|
|
8972
|
+
if (!edgeRaw)
|
|
8973
|
+
continue;
|
|
8974
|
+
let edge;
|
|
8975
|
+
try {
|
|
8976
|
+
edge = JSON.parse(edgeRaw);
|
|
8977
|
+
}
|
|
8978
|
+
catch {
|
|
8979
|
+
continue;
|
|
8980
|
+
}
|
|
8981
|
+
if (edge.confidence < min_confidence) {
|
|
8982
|
+
skippedLowConf++;
|
|
8983
|
+
continue;
|
|
8984
|
+
}
|
|
8985
|
+
if (!dry_run) {
|
|
8986
|
+
await destRedis.set(ek, edgeRaw);
|
|
8987
|
+
await destRedis.sadd(`cachly:ckg:idx:from:${edge.from}`, ek);
|
|
8988
|
+
await destRedis.sadd(`cachly:ckg:idx:to:${edge.to}`, ek);
|
|
8989
|
+
}
|
|
8990
|
+
edgesTransferred++;
|
|
8991
|
+
}
|
|
8992
|
+
// Transfer best-lesson for the same topic slug
|
|
8993
|
+
const lessonKey = `cachly:lesson:best:${node.id}`;
|
|
8994
|
+
const lessonRaw = await srcRedis.get(lessonKey);
|
|
8995
|
+
if (lessonRaw) {
|
|
8996
|
+
if (!dry_run)
|
|
8997
|
+
await destRedis.set(lessonKey, lessonRaw);
|
|
8998
|
+
lessonsTransferred++;
|
|
8999
|
+
if (transferLog.length < 8) {
|
|
9000
|
+
try {
|
|
9001
|
+
const l = JSON.parse(lessonRaw);
|
|
9002
|
+
const icon = l.outcome === 'success' ? '✅' : l.outcome === 'failure' ? '❌' : '⚠️';
|
|
9003
|
+
transferLog.push(` ${icon} \`${l.topic}\` — ${(l.what_worked ?? '').slice(0, 80)}`);
|
|
9004
|
+
}
|
|
9005
|
+
catch { /* skip */ }
|
|
9006
|
+
}
|
|
9007
|
+
}
|
|
9008
|
+
}
|
|
9009
|
+
// Record federation provenance
|
|
9010
|
+
if (!dry_run) {
|
|
9011
|
+
const provEntry = JSON.stringify({
|
|
9012
|
+
source, domain, transferred_at: new Date().toISOString(),
|
|
9013
|
+
nodes: nodesTransferred, edges: edgesTransferred, lessons: lessonsTransferred,
|
|
9014
|
+
});
|
|
9015
|
+
await destRedis.rpush('cachly:fedbrain:federations', provEntry);
|
|
9016
|
+
await destRedis.ltrim('cachly:fedbrain:federations', -50, -1);
|
|
9017
|
+
}
|
|
9018
|
+
const dryTag = dry_run ? ' (DRY RUN — no writes)' : '';
|
|
9019
|
+
const lines = [
|
|
9020
|
+
`🧠 **brain_federate: "${domain}"**${dryTag}`, '',
|
|
9021
|
+
`📤 Source: \`${source}\``,
|
|
9022
|
+
`📥 Destination: \`${instance_id}\``,
|
|
9023
|
+
`🔍 Domain filter: \`${domain}\` | min_confidence: ${min_confidence}`,
|
|
9024
|
+
'',
|
|
9025
|
+
`### Transfer Summary`,
|
|
9026
|
+
` 🕸️ CKG nodes: ${nodesTransferred}`,
|
|
9027
|
+
` 🔗 CKG edges: ${edgesTransferred} (${skippedLowConf} skipped, confidence < ${min_confidence})`,
|
|
9028
|
+
` 📚 Lessons: ${lessonsTransferred}`,
|
|
9029
|
+
'',
|
|
9030
|
+
];
|
|
9031
|
+
if (transferLog.length > 0) {
|
|
9032
|
+
lines.push(`### Sample lessons transferred:`, ...transferLog);
|
|
9033
|
+
if (lessonsTransferred > transferLog.length)
|
|
9034
|
+
lines.push(` _... and ${lessonsTransferred - transferLog.length} more_`);
|
|
9035
|
+
lines.push('');
|
|
9036
|
+
}
|
|
9037
|
+
if (dry_run) {
|
|
9038
|
+
lines.push(`💡 Run without \`dry_run: true\` to apply the transfer.`);
|
|
9039
|
+
}
|
|
9040
|
+
else {
|
|
9041
|
+
lines.push(`✅ Transfer complete. Your brain now has the \`${domain}\` knowledge from \`${source}\`.`);
|
|
9042
|
+
lines.push(`🔍 Explore: \`ckg_inspect(concept="${domain}")\` | \`recall_best_solution(topic="${domain}:...")\``);
|
|
9043
|
+
}
|
|
9044
|
+
return lines.join('\n');
|
|
9045
|
+
}
|
|
8693
9046
|
// ── crystal_view ──────────────────────────────────────────────────────────
|
|
8694
9047
|
case 'crystal_view': {
|
|
8695
9048
|
const { instance_id, show_raw = false } = args;
|