@cachly-dev/mcp-server 0.10.205 → 0.10.206

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.
@@ -1,8 +1,5 @@
1
- import{existsSync as _}from"node:fs";import{readFile as p,writeFile as o,chmod as c,mkdir as m}from"node:fs/promises";import{resolve as s}from"node:path";import{instanzIdFuerSkript as f,schluesselFuerSkript as $}from"./git-ohne-shell.js";const u="v1",h=/(?:#!\/bin\/sh\n)?# cachly brain_watch[\s\S]*?\nexit 0\n?/;async function H(r,e,d){if(!_(s(r,".git")))return{result:"skipped-no-git",hookPath:""};const l=s(r,".git","hooks"),t=s(l,"post-commit");await m(l,{recursive:!0});const i=w(e,d);let n="";try{n=await p(t,"utf-8")}catch{}if(!n)return await o(t,i+`
2
- `,"utf-8"),await c(t,493).catch(()=>{}),{result:"written",hookPath:t};if(n.includes(`cachly brain_watch \u2014 Auto-Learn ${u}`))return{result:"unchanged",hookPath:t};if(h.test(n)){const a=n.replace(h,i);return await o(t,a.endsWith(`
3
- `)?a:a+`
4
- `,"utf-8"),await c(t,493).catch(()=>{}),{result:"upgraded",hookPath:t}}return await o(t,n.trimEnd()+`
1
+ import{existsSync as c}from"node:fs";import{readFile as u,writeFile as f}from"node:fs/promises";import{resolve as a}from"node:path";import{installClsPostCommitHook as h}from"./cls-hook.js";import{instanzIdFuerSkript as m}from"./git-ohne-shell.js";const s=/(?:#!\/bin\/sh\n)?# cachly brain_watch[\s\S]*?\nexit 0\n?/;function p(r){if(!s.test(r))return null;let t=r;for(let n=s.exec(t);n;n=s.exec(t)){const o=t.slice(0,n.index).replace(/\s+$/,""),i=t.slice(n.index+n[0].length).replace(/^\s*\n/,"");t=o+(o&&i.trim()?`
5
2
 
6
- `+i+`
7
- `,"utf-8"),await c(t,493).catch(()=>{}),{result:"appended",hookPath:t}}function w(r,e){return r=f(r),e&&(e=$(e)),["#!/bin/sh",`# cachly brain_watch \u2014 Auto-Learn ${u}`,"# Silently teaches your Brain after every commit \u2014 no manual brain_from_git needed.",...e?[`CACHLY_JWT="${e}"`]:[],'_BW_SHA=$(git rev-parse HEAD 2>/dev/null || echo "")',"_BW_MSG=$(git log -1 --pretty=%B 2>/dev/null | head -1 | cut -c1-200)","_BW_FILES=$(git diff-tree --no-commit-id -r --name-only HEAD 2>/dev/null | tr '\\n' '\\t' | sed 's/\\t$//')","(curl -s -o /dev/null -m 8 \\",` -X POST "https://api.cachly.dev/api/v1/instances/${r}/learn" \\`,' -H "Authorization: Bearer ${CACHLY_JWT}" \\',' -H "Content-Type: application/json" \\',` --data-raw "{\\"message\\":\\"$(echo "$_BW_MSG" | sed 's/"/\\\\"/g')\\",\\"sha\\":\\"$_BW_SHA\\",\\"files\\":[$(echo "$_BW_FILES" | tr '\\t' '\\n' | grep -v '^$' | sed 's/.*/\\"&\\"/' | tr '\\n' ',' | sed 's/,$//')],\\"source\\":\\"brain_watch\\"}" \\`,") 2>/dev/null &","exit 0"].join(`
8
- `)}export{h as BRAIN_WATCH_BLOCK_RE,u as BRAIN_WATCH_HOOK_VERSION,w as buildBrainWatchHook,H as installBrainWatchHook};
3
+ `:"")+i}const e=t.trim();return e===""||e.startsWith("#!")&&!e.includes(`
4
+ `)?"":t.replace(/\s+$/,"")+`
5
+ `}async function w(r,t){if(m(t),!c(a(r,".git")))return{result:"skipped-no-git",hookPath:"",alterBlockEntfernt:!1};const e=a(r,".git","hooks","post-commit");let n="";try{n=await u(e,"utf-8")}catch{}const o=p(n);o!==null&&await f(e,o,"utf-8");const i=await h(r,t),l=o!==null;return{result:l&&i==="unchanged"?"upgraded":i,hookPath:e,alterBlockEntfernt:l}}export{s as BRAIN_WATCH_BLOCK_RE,w as installBrainWatchHook,p as ohneBrainWatchBlock};
@@ -1,40 +1,40 @@
1
- import{createHmac as he}from"node:crypto";import{ckgSlug as b,extractProblemConcept as me,ckgUpsertNode as T,ckgUpdateEdge as M,ckgUpsertPersonNode as pe,ckgUpsertFileNode as ge,ckgRecordCollaboration as _e}from"../ckg.js";import{safeJsonParse as R}from"../utils.js";import{buildClsPostCommitHook as we}from"../cls-hook.js";import{alsShellWort as ye,beginntMitBindestrich as $e,gitLesen as ie,instanzIdFuerSkript as be,istCommitHash as ke,pruefeOrdner as Se}from"../git-ohne-shell.js";import{installBrainWatchHook as Ce}from"../brain-watch-hook.js";import{keywordSearch as xe,wortindexEntwerten as ve}from"../search.js";import{buildFirstContactReport as ae,suggestRecallQueries as Oe}from"../first-contact.js";import{commitAlsLektion as Ne,gitLogArgumente as je,leseCommits as Ie}from"../git-lektionen.js";import{VEKTOR_NACHTRAG as Ae}from"../bedeutung.js";import{VERDACHT_TAG as Le,fuerEigenenSpeicher as G,fuerWeitergabe as re,hinweise as W,istMarkiert as Re,markiert as K,weitergabeHinweis as ce,zaehlHinweise as F}from"../schreibtor.js";let De=null,Te=null,Y=0;const Me=10,le=[];function Je(){return Y<Me?(Y++,Promise.resolve()):new Promise(B=>le.push(B))}function Pe(){const B=le.shift();B?B():Y--}const Qe=new Set(["madc_deliberate","cls_ingest","cls_install_hooks","fedbrain_contribute","fedbrain_search","fedbrain_confirm","fedbrain_status","brain_federate","crystal_view","compact_recover","brain_from_git","brain_from_ci","brain_predict_failures","brain_contribute_signal","brain_import_meta","brain_watch"]);async function Xe(B,j,A,z){switch(B){case"madc_deliberate":{const{instance_id:w,topic:c}=j,d=await A(w),e=(await d.lrange(`cachly:lessons:${c}`,0,-1)).map(_=>{try{return JSON.parse(_)}catch{return null}}).filter(Boolean);if(e.length<2)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`Not enough history for deliberation (need \u2265 2 entries, found ${e.length}).`,"","Call `learn_from_attempts` with conflicting outcomes to trigger deliberation."].join(`
2
- `);const i=[{name:"InfraAgent",domains:["infra","k8s","docker","server","wireguard","helm"]},{name:"AuthAgent",domains:["auth","jwt","keycloak","oauth","oidc","token"]},{name:"DeployAgent",domains:["deploy","ci","pipeline","rsync","release"]},{name:"DatabaseAgent",domains:["db","gorm","migration","postgres","clickhouse","redis"]},{name:"DebugAgent",domains:["debug","panic","race","nil","fix","error"]},{name:"APIAgent",domains:["api","http","grpc","rest","fiber","web"]}],u=c.split(":")[0]??"",r=i.filter(_=>_.domains.some($=>u===$||c.includes($))),f=r.length>0?r:i,l=new Map;for(const _ of f){let $=0;for(const v of _.domains){const O=[],S=d.scanStream({match:`cachly:ckg:node:${v}*`,count:50});await new Promise((k,N)=>{S.on("data",J=>O.push(...J)),S.on("end",k),S.on("error",N)}),$+=O.length}l.set(_.name,$)}const a=e.filter(_=>_.outcome==="success"||_.outcome==="partial"),t=e.filter(_=>_.outcome==="failure");if(t.length===0)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`No contradictions found \u2014 all ${a.length} entries have non-failure outcomes.`,"",`Use \`ckg_inspect(concept="${b(c)}")\` to explore the confidence graph.`].join(`
3
- `);const o=[];for(const _ of f){const $=l.get(_.name)??0;let v,O;$<2?(v="abstain",O="insufficient domain coverage"):a.length>=t.length*2?(v="success",O=`${a.length}/${e.length} entries confirm success`):t.length>=a.length*2?(v="failure",O=`${t.length}/${e.length} entries confirm failure`):(v="abstain",O=`contested (${a.length} success vs ${t.length} failure)`),o.push({agent:_.name,vote:v,coverage:$,reason:O})}const n=o.filter(_=>_.vote==="success").length,h=o.filter(_=>_.vote==="failure").length,m=o.filter(_=>_.vote==="abstain").length;let p,y;n>0&&h===0?(p="unanimous_success",y=`\u2705 **Unanimous: SUCCESS** \u2014 ${n} agent(s) confirm, ${m} abstain`):h>0&&n===0?(p="unanimous_failure",y=`\u274C **Unanimous: FAILURE** \u2014 ${h} agent(s) confirm, ${m} abstain`):(p="contested",y=`\u26A0\uFE0F **CONTESTED** \u2014 ${n} success votes, ${h} failure votes, ${m} abstain`);const g=b(`resolution:${c}`),x={id:g,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:p,topic:c,votes:{success:n,failure:h,abstain:m}};if(await d.set(`cachly:ckg:node:${g}`,JSON.stringify(x)),p==="contested")await M(d,b(c),"contradicts",g,!1);else{if(((p==="unanimous_success"?"failure":"success")==="failure"?t:a).length>0){const v=await d.smembers(`cachly:ckg:idx:from:${b(c)}`);for(const O of v){const S=await d.get(O);if(S)try{const k=JSON.parse(S);k.edgeType==="fixes"&&k.confidence>.15&&p==="unanimous_failure"&&(k.confidence=.1,k.last_updated=new Date().toISOString(),await d.set(O,JSON.stringify(k)))}catch{}}}await d.del(`cachly:ckg:conflict:${b(c)}`)}const C=[`\u{1F5F3}\uFE0F **MADC Deliberation: "${c}"**`,"",`\u{1F4CA} Evidence: ${a.length} success/partial vs ${t.length} failure entries (${e.length} total)`,"",`**Voting agents (${f.length}):**`,...o.map(_=>{const $=_.vote==="success"?"\u2705":_.vote==="failure"?"\u274C":"\u2B1C",v="\u2593".repeat(Math.min(_.coverage,5))+"\u2591".repeat(Math.max(0,5-_.coverage));return` ${$} **${_.agent}** [${v}] ${_.coverage} CKG edges \u2014 ${_.reason}`}),"",y,""];return p==="unanimous_success"?C.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${c}", outcome="success", ...)\``):p==="unanimous_failure"?C.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${c}")\``):C.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${b(c)}")\``),C.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${g}\``),C.join(`
4
- `)}case"cls_ingest":{const{instance_id:w,source:c,payload:d}=j,s=G(d),e=s.felder,i=await A(w),u=new Date().toISOString(),r="cachly:cls:events";if(c==="git_commit"){const f=String(e.message??""),l=String(e.sha??""),a=Array.isArray(e.files)?e.files:[],t=/^fix/i.test(f)?"fix":/^feat/i.test(f)?"feat":/^refactor/i.test(f)?"refactor":/^test/i.test(f)?"test":"commit",o=`${t}:${b(f.slice(0,60))}`,n=b(o);await T(i,n,t,"commit");for(const p of a.slice(0,10)){const y=p.includes("auth")?"auth":p.includes("api")?"api":p.includes("infra")?"infra":p.includes("web")?"web":"code",g=b(`file:${y}`);await T(i,g,"file",y),await M(i,n,"co-occurs",g,!0)}const h={topic:o,outcome:"success",what_worked:f,what_failed:"",context:`CLS/git: sha=${l}`,severity:"minor",file_paths:a.slice(0,10),commands:l?[`git show ${l}`]:[],tags:K(["cls","git"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.6,audit_trail:[{ts:u,action:"cls_git_commit"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(h)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(h)),await i.rpush(r,JSON.stringify({source:c,payload:{message:f,sha:l},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${l.slice(0,8)||"?"}\`: ${f.slice(0,80)}`,`Concept: \`${n}\` (${t}) \xB7 Files: ${a.length}`,"",`\u{1F578}\uFE0F CKG: \`${n}\` + ${a.length} file edges \xB7 Lesson: \`${o}\``,`\u{1F4A1} Inspect: \`ckg_inspect(concept="${t}")\``,...W(s)].join(`
5
- `)}if(c==="ci_outcome"){const f=String(e.status??""),l=String(e.prev_status??""),a=String(e.job??"unknown"),t=String(e.context??""),o=["failure","red","error"].includes(l)&&["success","green","passed"].includes(f),n=["success","green","passed"].includes(l)&&["failure","red","error"].includes(f),h=`ci:${b(a)}`,m=b(h);if(await T(i,m,"ci","job"),o){const y=b(`problem:${b(a)}`);await T(i,y,"problem","ci-failure"),await M(i,m,"fixes",y,!0);const g={topic:h,outcome:"success",what_worked:`CI job "${a}" went ${l} \u2192 ${f}`,what_failed:`Job "${a}" was failing`,context:`CLS/ci: ${t}`,severity:"major",file_paths:[],commands:[],tags:K(["cls","ci"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.75,audit_trail:[{ts:u,action:"cls_ci_fixed"}],version:3};await i.rpush(`cachly:lessons:${h}`,JSON.stringify(g)),await i.set(`cachly:lesson:best:${h}`,JSON.stringify(g))}else if(n){const y=b(`cause:${b(a)}`);await T(i,y,"cause","ci-break"),await M(i,m,"causes",y,!1)}return await i.rpush(r,JSON.stringify({source:c,payload:{status:f,prev_status:l,job:a},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ci_outcome**","",`${o?"\u2705 Fixed":n?"\u{1F534} Broken":"\u{1F4CA} Recorded"}: \`${a}\` \u2014 ${l||"?"} \u2192 ${f}`,o?"\u{1F527} CKG `fixes` edge added (75% confidence)":n?"\u26A1 CKG `causes` edge added":"\u{1F4CA} State recorded",`\u{1F4A1} Lesson: \`${h}\` | Predict: \`brain_predict(context="${a}")\``,...W(o?s:{geschwaerzt:s.geschwaerzt,verdacht:[]})].join(`
6
- `)}if(c==="ide_diagnostic"){const f=String(e.error??""),l=String(e.fix??""),a=String(e.file??""),t=me(f)??"unknown-error",o=`debug:${b(t)}`,n=b(o),h=b(`problem:${t}`);await T(i,n,"debug","diagnostic"),await T(i,h,"problem","compiler-error"),await M(i,n,"fixes",h,!0);const m={topic:o,outcome:"success",what_worked:l,what_failed:f,context:`CLS/ide: ${a}`,severity:"minor",file_paths:a?[a]:[],commands:[],tags:K(["cls","ide-diagnostic"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.65,audit_trail:[{ts:u,action:"cls_ide_diagnostic"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(m)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(m)),await i.rpush(r,JSON.stringify({source:c,payload:{error:f.slice(0,60),fix:l.slice(0,60),file:a},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ide_diagnostic**","",`Error: \`${f.slice(0,80)}\``,`Fix: ${l.slice(0,100)}`,a?`File: \`${a}\``:"","",`\u{1F578}\uFE0F CKG: \`${n}\` \u2192 fixes \u2192 \`${h}\` | Lesson: \`${o}\``,...W(s)].filter(y=>y!=="").join(`
7
- `)}return`\u274C Unknown CLS source: "${c}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:w,repo_path:c=".",hooks:d=["git","ci"]}=j,s=Array.isArray(d)?d:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
8
- `];if(be(w),s.includes("git")){const i=we(w),u=ye(`${c}/.git/hooks/post-commit`);e.push("### Git post-commit hook"),e.push("**Quick install (run once per repo):**"),e.push("```sh"),e.push(`touch ${u}`),e.push(`grep -q 'cachly CLS' ${u} || cat >> ${u} << 'HOOK'`),e.push(i),e.push("HOOK"),e.push(`chmod +x ${u}`),e.push("```"),e.push("After install: every `git commit` automatically updates your brain's CKG."),e.push("")}return s.includes("ci")&&(e.push("### GitHub Actions CI outcome hook"),e.push("**Add at the end of each job** (after build/test steps):"),e.push("```yaml"),e.push("- name: cachly CLS \u2014 record CI outcome"),e.push(" if: always()"),e.push(" run: |"),e.push(' node -e "'),e.push(" const r=require('https');"),e.push(` const d=JSON.stringify({instance_id:'${w}',source:'ci_outcome',payload:{`),e.push(" status:'${{ job.status }}',prev_status:'unknown',job:'${{ github.job }}',"),e.push(" context:'github-actions run ${{ github.run_number }}'}});"),e.push(" r.request({hostname:'api.cachly.dev',path:'/api/v1/cls/ingest',method:'POST',"),e.push(" headers:{'Content-Type':'application/json','Authorization':'Bearer $CACHLY_JWT',"),e.push(" 'Content-Length':d.length}},()=>{}).end(d);"),e.push(' " 2>/dev/null || true'),e.push(" env:"),e.push(" CACHLY_JWT: ${{ secrets.CACHLY_JWT }}"),e.push("```"),e.push("")),e.push('\u{1F4A1} Once installed: `brain_search(query="cls")` to verify events are arriving.'),e.push('\u{1F4CA} Monitor CKG growth: `ckg_inspect(concept="ci")` or `ckg_inspect(concept="fix")`'),e.join(`
9
- `)}case"fedbrain_contribute":{const{instance_id:w,lesson_key:c,visibility:d="public"}=j,s=await A(w),e=await s.get(`cachly:lesson:best:${c}`);if(!e)return`\u274C Lesson \`${c}\` not found. Store it first with \`learn_from_attempts\`.`;const i=R(e,null);if(!i)return`\u274C Lesson \`${c}\` data is corrupted. Re-store with \`learn_from_attempts\`.`;const u=re({topic:i.topic,what_worked:i.what_worked,what_failed:i.what_failed??"",tags:i.tags??[]},"die Commons");if(!u.ok)return u.meldung;if(Re(i))return`\u26D4 Tuersteher: Die Lektion \`${c}\` ist beim Speichern als verdaechtig markiert worden \u2014 NICHT an die Commons weitergegeben. Nichts wurde gesendet. Inhalt pruefen, dann mit \`learn_from_attempts\` ohne die Anweisung neu speichern.`;const r={...i,...u.felder},f=[r.topic.split(":")[0],...r.tags??[]].filter(Boolean),l=[...new Set(f)].sort().join(","),a=`${r.topic}:${r.outcome}:${r.what_worked}`,t=he("sha256",`cachly-fedbrain:${w}`).update(a).digest("hex").slice(0,16),o={cert_id:t,lesson_key:c,visibility:d,domain_fingerprint:l,contributed_at:new Date().toISOString(),confirm_count:0,trust_score:r.outcome==="success"?.85:.5};await s.set(`cachly:fedbrain:cert:${t}`,JSON.stringify(o)),await s.sadd("cachly:fedbrain:contributed",t);let n;try{await z("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify({topic:r.topic,outcome:r.outcome,what_worked:r.what_worked,what_failed:r.what_failed??"",severity:r.severity??"major",cert_id:t,domain_fingerprint:l,visibility:d})}),n="\u2705 Contributed to global commons"}catch{n="\u{1F4E6} Stored locally (commons API unavailable \u2014 will sync when online)"}return[`\u{1F310} **FedBrain Contribute: "${c}"**`,"",`\u{1F4DC} Certificate: \`${t}\``,`\u{1F3F7}\uFE0F Domain fingerprint: ${f.slice(0,6).map(h=>`\`${h}\``).join(", ")}`,`\u{1F512} Visibility: ${d}`,"",n,...u.geschwaerzt.length?[ce(u.geschwaerzt)]:[],"","\u{1F4A1} At 10 independent confirms \u2192 \u{1F3C6} Gold Standard",`\u{1F50D} Search: \`fedbrain_search(query="${r.topic.split(":").slice(-1)[0]}")\``].join(`
10
- `)}case"fedbrain_search":{const{instance_id:w,query:c,context_hints:d=[],limit:s=10}=j,e=await A(w),i=await e.smembers("cachly:fedbrain:contributed"),u=new Map;for(const o of i.slice(0,30)){const n=await e.get(`cachly:fedbrain:cert:${o}`);if(n)try{const h=JSON.parse(n);for(const m of(h.domain_fingerprint??"").split(",").filter(Boolean))u.set(m,(u.get(m)??0)+1)}catch{}}for(const o of Array.isArray(d)?d:[])u.set(o.toLowerCase(),(u.get(o.toLowerCase())??0)+2);let r=[],f=!1;try{const o=new URLSearchParams({q:c,limit:String(Math.min(s*2,50))});r=(await z(`/api/v1/syndication/search?${o}`)).results??[]}catch{f=!0;const o=[],n=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{n.on("data",p=>o.push(...p)),n.on("end",h),n.on("error",m)});for(const h of o.slice(0,60)){const m=await e.get(h);if(m)try{const p=JSON.parse(m),y=`${p.topic} ${p.what_worked??""} ${p.what_failed??""}`.toLowerCase();c.toLowerCase().split(/\s+/).some(g=>g.length>2&&y.includes(g))&&r.push({id:h.split(":").pop()??h,topic:p.topic,category:p.topic.split(":")[0],outcome:p.outcome,what_worked:p.what_worked??"",severity:p.severity??"major",confirm_count:0,created_at:p.ts??new Date().toISOString()})}catch{}}}const l=f?" \u2014 \u26A0\uFE0F Commons unreachable, local fallback (this machine only, not confirmed by the network)":"";if(r.length===0)return[`\u{1F310} **FedBrain Search: "${c}"**${l}`,"",'No results. Contribute: `fedbrain_contribute(lesson_key="fix:...")`'].join(`
11
- `);const a=r.map(o=>{const n=(o.domain_fingerprint??o.category??"").split(",").filter(Boolean),h=n.reduce((g,x)=>g+(u.get(x)??0),0),m=u.size>0?h/Math.max(1,u.size+n.length):0,p=Math.min(1,o.confirm_count/10),y=m*.4+p*.4+(o.outcome==="success"?.2:0);return{...o,weightedScore:y,isGoldStandard:!f&&o.confirm_count>=10}}).sort((o,n)=>n.weightedScore-o.weightedScore).slice(0,s),t=[`\u{1F310} **FedBrain Search: "${c}"** \u2014 ${a.length} result${a.length!==1?"s":""} (context-weighted)${l}
12
- `];for(const o of a){const n=o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F",h=o.isGoldStandard?" \u{1F3C6} _Gold Standard_":!f&&o.confirm_count>=3?` \u2713${o.confirm_count}`:"",m=Math.round(o.weightedScore*100);t.push(`${n}${h} **\`${o.topic}\`** [ctx: ${m}%]`),o.what_worked&&t.push(` \u2705 ${o.what_worked.slice(0,150)}`),o.what_failed&&t.push(` \u274C ${o.what_failed.slice(0,80)}`),t.push(` _${o.confirm_count} confirm${o.confirm_count!==1?"s":""} | id: \`${o.id}\`_`,"")}if(u.size>0){const o=[...u.entries()].sort((n,h)=>h[1]-n[1]).slice(0,5).map(([n,h])=>`\`${n}\`(${h})`).join(", ");t.push(`\u{1F3AF} Your context: ${o}`)}return t.push('\u{1F4A1} Confirm a result: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`'),t.join(`
13
- `)}case"fedbrain_confirm":{const{instance_id:w,id:c,topic:d,outcome:s}=j;if(!c)return["\u274C **FedBrain Confirm** needs the lesson `id` from `fedbrain_search` results.",'Run `fedbrain_search(query="...")`, copy the id shown next to a result,','then: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`.'].join(`
14
- `);const e=await A(w),i=new Date().toISOString(),u=JSON.stringify({id:c,topic:d,outcome:s,ts:i});await e.rpush("cachly:fedbrain:confirmations",u),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const r=s==="worked",f=s==="partially_worked";d&&await M(e,b(d),"fixes",b(`syndicated:${d}`),r,f);let l;try{await z(`/api/v1/syndication/${encodeURIComponent(c)}/confirm`,{method:"POST"}),l="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",u),await e.ltrim("cachly:fedbrain:pending_confirms",-50,-1),l="\u{1F4E6} Queued locally (API unavailable \u2014 will propagate on next online session)"}return[`${r?"\u2705":f?"\u26A0\uFE0F":"\u274C"} **FedBrain Confirm: "${d??c}"** \u2192 ${s}`,"",l,"",d?`\u{1F578}\uFE0F CKG confidence ${r||f?"boosted":"reduced"} for \`${b(d)}\``:"\u{1F578}\uFE0F Local CKG unchanged (pass `topic` to also update your own confidence graph)","\u{1F4A1} Your confirmation helps other brains worldwide.",'\u{1F4CA} Status: `fedbrain_status(instance_id="...")`'].join(`
15
- `)}case"fedbrain_status":{const{instance_id:w}=j,c=await A(w),d=await c.smembers("cachly:fedbrain:contributed"),s=await c.lrange("cachly:fedbrain:confirmations",-10,-1),e=await c.llen("cachly:fedbrain:pending_confirms"),i=s.map(f=>{try{return JSON.parse(f)}catch{return null}}).filter(Boolean),u=[];for(const f of d.slice(0,15)){const l=await c.get(`cachly:fedbrain:cert:${f}`);if(l)try{const a=JSON.parse(l);u.push({cert_id:a.cert_id,lesson_key:a.lesson_key,confirm_count:a.confirm_count??0,trust_score:a.trust_score??.5,isGold:(a.confirm_count??0)>=10})}catch{}}const r=[`\u{1F310} **FedBrain Status**
16
- `,`### \u{1F4E4} Contributed Lessons: ${d.length}`];if(u.length>0)for(const f of u){const l=f.isGold?" \u{1F3C6} Gold Standard":"",a="\u2588".repeat(Math.min(10,f.confirm_count))+"\u2591".repeat(Math.max(0,10-f.confirm_count));r.push(` \`${f.lesson_key}\` [${a}] \xD7${f.confirm_count}${l}`)}else r.push(' _None yet. Contribute with `fedbrain_contribute(lesson_key="fix:...")`_');if(r.push("",`### \u{1F4E5} Recent Confirmations: ${i.length}`),i.length>0)for(const f of i.slice(-5)){const l=f.outcome==="worked"?"\u2705":f.outcome==="partially_worked"?"\u26A0\uFE0F":"\u274C";r.push(` ${l} \`${f.topic}\` \u2014 ${f.outcome} (${new Date(f.ts).toLocaleDateString("de-DE")})`)}else r.push(" _None yet. Confirm syndicated lessons with `fedbrain_confirm`_");return e>0&&r.push("",`\u26A0\uFE0F ${e} confirmation${e!==1?"s":""} pending propagation`),r.push("","---",'**Contribute:** `fedbrain_contribute(lesson_key="fix:...")`','**Search:** `fedbrain_search(query="...")`','**Confirm:** `fedbrain_confirm(id="...", topic="...", outcome="worked")`'),r.join(`
17
- `)}case"brain_federate":{const{instance_id:w,source:c,domain:d,min_confidence:s=.6,dry_run:e=!1}=j;if(w===c)return"\u274C Source and destination cannot be the same brain.";const i=await A(w),u=await A(c),r=d==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${d}*`,f=[],l=u.scanStream({match:r,count:100});if(await new Promise((x,C)=>{l.on("data",_=>f.push(..._)),l.on("end",x),l.on("error",C)}),f.length===0)return[`\u{1F9E0} **brain_federate: "${d}"**`,"",`No CKG nodes found in source brain for domain \`${d}\`.`,"The source brain may not have knowledge in this area yet.",`Try: \`fedbrain_search(query="${d}")\` to find global commons knowledge instead.`].join(`
18
- `);let a=0,t=0,o=0,n=0,h=0,m=0;const p=[];for(const x of f){const C=await u.get(x);if(!C)continue;let _;try{_=JSON.parse(C)}catch{continue}e||await i.set(x,C),a++;const $=await u.smembers(`cachly:ckg:idx:from:${_.id}`);for(const S of $){const k=await u.get(S);if(!k)continue;let N;try{N=JSON.parse(k)}catch{continue}if(N.confidence<s){n++;continue}e||(await i.set(S,k),await i.sadd(`cachly:ckg:idx:from:${N.from}`,S),await i.sadd(`cachly:ckg:idx:to:${N.to}`,S)),t++}const v=`cachly:lesson:best:${_.id}`,O=await u.get(v);if(O){const S=R(O,null);if(!S||typeof S!="object")continue;const k=G(S);k.geschwaerzt.length&&h++,k.verdacht.length&&m++;const N=k.verdacht.length?{...k.felder,tags:K(k.felder.tags,k.verdacht)}:k.felder;if(e||await i.set(v,JSON.stringify(N)),o++,p.length<8){const J=N.outcome==="success"?"\u2705":N.outcome==="failure"?"\u274C":"\u26A0\uFE0F";p.push(` ${J} \`${N.topic}\` \u2014 ${(N.what_worked??"").slice(0,80)}`)}}}if(!e){const x=JSON.stringify({source:c,domain:d,transferred_at:new Date().toISOString(),nodes:a,edges:t,lessons:o});await i.rpush("cachly:fedbrain:federations",x),await i.ltrim("cachly:fedbrain:federations",-50,-1)}const g=[`\u{1F9E0} **brain_federate: "${d}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${c}\``,`\u{1F4E5} Destination: \`${w}\``,`\u{1F50D} Domain filter: \`${d}\` | min_confidence: ${s}`,"","### Transfer Summary",` \u{1F578}\uFE0F CKG nodes: ${a}`,` \u{1F517} CKG edges: ${t} (${n} skipped, confidence < ${s})`,` \u{1F4DA} Lessons: ${o}`,...F(h,m,`${o} kopierten Lektionen`),""];return p.length>0&&(g.push("### Sample lessons transferred:",...p),o>p.length&&g.push(` _... and ${o-p.length} more_`),g.push("")),e?g.push("\u{1F4A1} Run without `dry_run: true` to apply the transfer."):(g.push(`\u2705 Transfer complete. Your brain now has the \`${d}\` knowledge from \`${c}\`.`),g.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${d}")\` | \`recall_best_solution(topic="${d}:...")\``)),g.join(`
19
- `)}case"crystal_view":{const{instance_id:w,show_raw:c=!1}=j,d=await A(w),s=await d.get("cachly:crystal:latest");if(!s)return["\u{1F48E} **Memory Crystal: not yet created**","","No crystal found. Create one with `memory_crystalize()` to compress your accumulated wisdom.","","\u{1F4A1} Tip: run `memory_crystalize` monthly for best results."].join(`
20
- `);const e=R(s,null);if(!e)return"\u274C Memory Crystal data is corrupted. Re-create with `memory_crystalize()`.";const i=Math.floor((Date.now()-new Date(e.ts).getTime())/864e5),u=i<=7?"\u{1F7E2}":i<=30?"\u{1F7E1}":"\u{1F534}",r=[`\u{1F48E} **Memory Crystal: ${e.label}**`,"",`\u{1F4C5} Created: ${new Date(e.ts).toLocaleDateString("de-DE")} (${i}d ago ${u})`,`\u{1F4CA} Compressed from: ${e.created_from}`,`\u{1F5C2}\uFE0F Categories: ${e.categories.slice(0,10).map(l=>`\`${l}\``).join(", ")}${e.categories.length>10?` +${e.categories.length-10} more`:""}`,"",`**\u{1F511} Top patterns (${e.top_patterns.length}):**`];for(const l of e.top_patterns)r.push(` \u2022 **${l.category}** (${l.count}\xD7): ${l.insight.slice(0,110)}`);i>30&&r.push("",`\u26A0\uFE0F Crystal is ${i}d old \u2014 run \`memory_crystalize()\` to refresh it.`),c&&r.push("","```json",JSON.stringify(e,null,2),"```");const f=await d.get("cachly:crystal:team:latest").catch(()=>null);if(f){const l=R(f,null);if(l&&l.patterns?.length){const a=Math.floor((Date.now()-new Date(l.ts).getTime())/864e5);r.push("","---",`\u{1F4A0} **Team Crystal: ${l.label}** _(${a}d ago \xB7 ${l.contributors} contributors)_`,"_Fixes multiple teammates independently converged on \u2014 the team-wide layer:_");for(const t of l.patterns.slice(0,5))r.push(` \u2022 \u{1F9E9} **${t.concept}** \u2014 ${t.author_count} people (${t.authors.map(o=>`@${o}`).join(", ")}): ${t.convergent_fix.slice(0,90)}`)}}return r.push("",'\u{1F4A1} Refresh: `memory_crystalize()` \xB7 `team_crystallize()` | Recover: `compact_recover(instance_id="...")`'),r.join(`
21
- `)}case"compact_recover":{const{instance_id:w,focus:c=""}=j,d=await A(w),s=[`\u{1F501} **Compact Recovery Briefing**
1
+ import{createHmac as he}from"node:crypto";import{ckgSlug as b,extractProblemConcept as me,ckgUpsertNode as T,ckgUpdateEdge as J,ckgUpsertPersonNode as pe,ckgUpsertFileNode as ge,ckgRecordCollaboration as _e}from"../ckg.js";import{safeJsonParse as R}from"../utils.js";import{buildClsPostCommitHook as we}from"../cls-hook.js";import{alsShellWort as ye,beginntMitBindestrich as $e,gitLesen as ie,instanzIdFuerSkript as be,istCommitHash as ke,pruefeOrdner as Se}from"../git-ohne-shell.js";import{installBrainWatchHook as Ce}from"../brain-watch-hook.js";import{keywordSearch as xe,wortindexEntwerten as ve}from"../search.js";import{buildFirstContactReport as ae,suggestRecallQueries as je}from"../first-contact.js";import{commitAlsLektion as Oe,gitLogArgumente as Ne,leseCommits as Ie}from"../git-lektionen.js";import{VEKTOR_NACHTRAG as Ae}from"../bedeutung.js";import{VERDACHT_TAG as Le,fuerEigenenSpeicher as G,fuerWeitergabe as re,hinweise as V,istMarkiert as Re,markiert as K,weitergabeHinweis as ce,zaehlHinweise as H}from"../schreibtor.js";let De=null,Te=null,Y=0;const Je=10,le=[];function Me(){return Y<Je?(Y++,Promise.resolve()):new Promise(B=>le.push(B))}function Pe(){const B=le.shift();B?B():Y--}const Qe=new Set(["madc_deliberate","cls_ingest","cls_install_hooks","fedbrain_contribute","fedbrain_search","fedbrain_confirm","fedbrain_status","brain_federate","crystal_view","compact_recover","brain_from_git","brain_from_ci","brain_predict_failures","brain_contribute_signal","brain_import_meta","brain_watch"]);async function Xe(B,N,A,E){switch(B){case"madc_deliberate":{const{instance_id:w,topic:c}=N,d=await A(w),e=(await d.lrange(`cachly:lessons:${c}`,0,-1)).map(_=>{try{return JSON.parse(_)}catch{return null}}).filter(Boolean);if(e.length<2)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`Not enough history for deliberation (need \u2265 2 entries, found ${e.length}).`,"","Call `learn_from_attempts` with conflicting outcomes to trigger deliberation."].join(`
2
+ `);const i=[{name:"InfraAgent",domains:["infra","k8s","docker","server","wireguard","helm"]},{name:"AuthAgent",domains:["auth","jwt","keycloak","oauth","oidc","token"]},{name:"DeployAgent",domains:["deploy","ci","pipeline","rsync","release"]},{name:"DatabaseAgent",domains:["db","gorm","migration","postgres","clickhouse","redis"]},{name:"DebugAgent",domains:["debug","panic","race","nil","fix","error"]},{name:"APIAgent",domains:["api","http","grpc","rest","fiber","web"]}],f=c.split(":")[0]??"",r=i.filter(_=>_.domains.some($=>f===$||c.includes($))),u=r.length>0?r:i,l=new Map;for(const _ of u){let $=0;for(const v of _.domains){const j=[],S=d.scanStream({match:`cachly:ckg:node:${v}*`,count:50});await new Promise((k,O)=>{S.on("data",M=>j.push(...M)),S.on("end",k),S.on("error",O)}),$+=j.length}l.set(_.name,$)}const a=e.filter(_=>_.outcome==="success"||_.outcome==="partial"),t=e.filter(_=>_.outcome==="failure");if(t.length===0)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`No contradictions found \u2014 all ${a.length} entries have non-failure outcomes.`,"",`Use \`ckg_inspect(concept="${b(c)}")\` to explore the confidence graph.`].join(`
3
+ `);const o=[];for(const _ of u){const $=l.get(_.name)??0;let v,j;$<2?(v="abstain",j="insufficient domain coverage"):a.length>=t.length*2?(v="success",j=`${a.length}/${e.length} entries confirm success`):t.length>=a.length*2?(v="failure",j=`${t.length}/${e.length} entries confirm failure`):(v="abstain",j=`contested (${a.length} success vs ${t.length} failure)`),o.push({agent:_.name,vote:v,coverage:$,reason:j})}const n=o.filter(_=>_.vote==="success").length,h=o.filter(_=>_.vote==="failure").length,m=o.filter(_=>_.vote==="abstain").length;let p,y;n>0&&h===0?(p="unanimous_success",y=`\u2705 **Unanimous: SUCCESS** \u2014 ${n} agent(s) confirm, ${m} abstain`):h>0&&n===0?(p="unanimous_failure",y=`\u274C **Unanimous: FAILURE** \u2014 ${h} agent(s) confirm, ${m} abstain`):(p="contested",y=`\u26A0\uFE0F **CONTESTED** \u2014 ${n} success votes, ${h} failure votes, ${m} abstain`);const g=b(`resolution:${c}`),x={id:g,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:p,topic:c,votes:{success:n,failure:h,abstain:m}};if(await d.set(`cachly:ckg:node:${g}`,JSON.stringify(x)),p==="contested")await J(d,b(c),"contradicts",g,!1);else{if(((p==="unanimous_success"?"failure":"success")==="failure"?t:a).length>0){const v=await d.smembers(`cachly:ckg:idx:from:${b(c)}`);for(const j of v){const S=await d.get(j);if(S)try{const k=JSON.parse(S);k.edgeType==="fixes"&&k.confidence>.15&&p==="unanimous_failure"&&(k.confidence=.1,k.last_updated=new Date().toISOString(),await d.set(j,JSON.stringify(k)))}catch{}}}await d.del(`cachly:ckg:conflict:${b(c)}`)}const C=[`\u{1F5F3}\uFE0F **MADC Deliberation: "${c}"**`,"",`\u{1F4CA} Evidence: ${a.length} success/partial vs ${t.length} failure entries (${e.length} total)`,"",`**Voting agents (${u.length}):**`,...o.map(_=>{const $=_.vote==="success"?"\u2705":_.vote==="failure"?"\u274C":"\u2B1C",v="\u2593".repeat(Math.min(_.coverage,5))+"\u2591".repeat(Math.max(0,5-_.coverage));return` ${$} **${_.agent}** [${v}] ${_.coverage} CKG edges \u2014 ${_.reason}`}),"",y,""];return p==="unanimous_success"?C.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${c}", outcome="success", ...)\``):p==="unanimous_failure"?C.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${c}")\``):C.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${b(c)}")\``),C.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${g}\``),C.join(`
4
+ `)}case"cls_ingest":{const{instance_id:w,source:c,payload:d}=N,s=G(d),e=s.felder,i=await A(w),f=new Date().toISOString(),r="cachly:cls:events";if(c==="git_commit"){const u=String(e.message??""),l=String(e.sha??""),a=Array.isArray(e.files)?e.files:[],t=/^fix/i.test(u)?"fix":/^feat/i.test(u)?"feat":/^refactor/i.test(u)?"refactor":/^test/i.test(u)?"test":"commit",o=`${t}:${b(u.slice(0,60))}`,n=b(o);await T(i,n,t,"commit");for(const p of a.slice(0,10)){const y=p.includes("auth")?"auth":p.includes("api")?"api":p.includes("infra")?"infra":p.includes("web")?"web":"code",g=b(`file:${y}`);await T(i,g,"file",y),await J(i,n,"co-occurs",g,!0)}const h={topic:o,outcome:"success",what_worked:u,what_failed:"",context:`CLS/git: sha=${l}`,severity:"minor",file_paths:a.slice(0,10),commands:l?[`git show ${l}`]:[],tags:K(["cls","git"],s.verdacht),depends_on:[],recall_count:0,ts:f,verified_at:f,confidence:.6,audit_trail:[{ts:f,action:"cls_git_commit"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(h)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(h)),await i.rpush(r,JSON.stringify({source:c,payload:{message:u,sha:l},ts:f})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${l.slice(0,8)||"?"}\`: ${u.slice(0,80)}`,`Concept: \`${n}\` (${t}) \xB7 Files: ${a.length}`,"",`\u{1F578}\uFE0F CKG: \`${n}\` + ${a.length} file edges \xB7 Lesson: \`${o}\``,`\u{1F4A1} Inspect: \`ckg_inspect(concept="${t}")\``,...V(s)].join(`
5
+ `)}if(c==="ci_outcome"){const u=String(e.status??""),l=String(e.prev_status??""),a=String(e.job??"unknown"),t=String(e.context??""),o=["failure","red","error"].includes(l)&&["success","green","passed"].includes(u),n=["success","green","passed"].includes(l)&&["failure","red","error"].includes(u),h=`ci:${b(a)}`,m=b(h);if(await T(i,m,"ci","job"),o){const y=b(`problem:${b(a)}`);await T(i,y,"problem","ci-failure"),await J(i,m,"fixes",y,!0);const g={topic:h,outcome:"success",what_worked:`CI job "${a}" went ${l} \u2192 ${u}`,what_failed:`Job "${a}" was failing`,context:`CLS/ci: ${t}`,severity:"major",file_paths:[],commands:[],tags:K(["cls","ci"],s.verdacht),depends_on:[],recall_count:0,ts:f,verified_at:f,confidence:.75,audit_trail:[{ts:f,action:"cls_ci_fixed"}],version:3};await i.rpush(`cachly:lessons:${h}`,JSON.stringify(g)),await i.set(`cachly:lesson:best:${h}`,JSON.stringify(g))}else if(n){const y=b(`cause:${b(a)}`);await T(i,y,"cause","ci-break"),await J(i,m,"causes",y,!1)}return await i.rpush(r,JSON.stringify({source:c,payload:{status:u,prev_status:l,job:a},ts:f})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ci_outcome**","",`${o?"\u2705 Fixed":n?"\u{1F534} Broken":"\u{1F4CA} Recorded"}: \`${a}\` \u2014 ${l||"?"} \u2192 ${u}`,o?"\u{1F527} CKG `fixes` edge added (75% confidence)":n?"\u26A1 CKG `causes` edge added":"\u{1F4CA} State recorded",`\u{1F4A1} Lesson: \`${h}\` | Predict: \`brain_predict(context="${a}")\``,...V(o?s:{geschwaerzt:s.geschwaerzt,verdacht:[]})].join(`
6
+ `)}if(c==="ide_diagnostic"){const u=String(e.error??""),l=String(e.fix??""),a=String(e.file??""),t=me(u)??"unknown-error",o=`debug:${b(t)}`,n=b(o),h=b(`problem:${t}`);await T(i,n,"debug","diagnostic"),await T(i,h,"problem","compiler-error"),await J(i,n,"fixes",h,!0);const m={topic:o,outcome:"success",what_worked:l,what_failed:u,context:`CLS/ide: ${a}`,severity:"minor",file_paths:a?[a]:[],commands:[],tags:K(["cls","ide-diagnostic"],s.verdacht),depends_on:[],recall_count:0,ts:f,verified_at:f,confidence:.65,audit_trail:[{ts:f,action:"cls_ide_diagnostic"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(m)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(m)),await i.rpush(r,JSON.stringify({source:c,payload:{error:u.slice(0,60),fix:l.slice(0,60),file:a},ts:f})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ide_diagnostic**","",`Error: \`${u.slice(0,80)}\``,`Fix: ${l.slice(0,100)}`,a?`File: \`${a}\``:"","",`\u{1F578}\uFE0F CKG: \`${n}\` \u2192 fixes \u2192 \`${h}\` | Lesson: \`${o}\``,...V(s)].filter(y=>y!=="").join(`
7
+ `)}return`\u274C Unknown CLS source: "${c}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:w,repo_path:c=".",hooks:d=["git","ci"]}=N,s=Array.isArray(d)?d:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
8
+ `];if(be(w),s.includes("git")){const i=we(w),f=ye(`${c}/.git/hooks/post-commit`);e.push("### Git post-commit hook"),e.push("**Quick install (run once per repo):**"),e.push("```sh"),e.push(`touch ${f}`),e.push(`grep -q 'cachly CLS' ${f} || cat >> ${f} << 'HOOK'`),e.push(i),e.push("HOOK"),e.push(`chmod +x ${f}`),e.push("```"),e.push("After install: every `git commit` automatically updates your brain's CKG."),e.push("")}return s.includes("ci")&&(e.push("### GitHub Actions CI outcome hook"),e.push("**Add at the end of each job** (after build/test steps):"),e.push("```yaml"),e.push("- name: cachly CLS \u2014 record CI outcome"),e.push(" if: always()"),e.push(" run: |"),e.push(' node -e "'),e.push(" const r=require('https');"),e.push(` const d=JSON.stringify({instance_id:'${w}',source:'ci_outcome',payload:{`),e.push(" status:'${{ job.status }}',prev_status:'unknown',job:'${{ github.job }}',"),e.push(" context:'github-actions run ${{ github.run_number }}'}});"),e.push(" r.request({hostname:'api.cachly.dev',path:'/api/v1/cls/ingest',method:'POST',"),e.push(" headers:{'Content-Type':'application/json','Authorization':'Bearer $CACHLY_JWT',"),e.push(" 'Content-Length':d.length}},()=>{}).end(d);"),e.push(' " 2>/dev/null || true'),e.push(" env:"),e.push(" CACHLY_JWT: ${{ secrets.CACHLY_JWT }}"),e.push("```"),e.push("")),e.push('\u{1F4A1} Once installed: `brain_search(query="cls")` to verify events are arriving.'),e.push('\u{1F4CA} Monitor CKG growth: `ckg_inspect(concept="ci")` or `ckg_inspect(concept="fix")`'),e.join(`
9
+ `)}case"fedbrain_contribute":{const{instance_id:w,lesson_key:c,visibility:d="public"}=N,s=await A(w),e=await s.get(`cachly:lesson:best:${c}`);if(!e)return`\u274C Lesson \`${c}\` not found. Store it first with \`learn_from_attempts\`.`;const i=R(e,null);if(!i)return`\u274C Lesson \`${c}\` data is corrupted. Re-store with \`learn_from_attempts\`.`;const f=re({topic:i.topic,what_worked:i.what_worked,what_failed:i.what_failed??"",tags:i.tags??[]},"die Commons");if(!f.ok)return f.meldung;if(Re(i))return`\u26D4 Tuersteher: Die Lektion \`${c}\` ist beim Speichern als verdaechtig markiert worden \u2014 NICHT an die Commons weitergegeben. Nichts wurde gesendet. Inhalt pruefen, dann mit \`learn_from_attempts\` ohne die Anweisung neu speichern.`;const r={...i,...f.felder},u=[r.topic.split(":")[0],...r.tags??[]].filter(Boolean),l=[...new Set(u)].sort().join(","),a=`${r.topic}:${r.outcome}:${r.what_worked}`,t=he("sha256",`cachly-fedbrain:${w}`).update(a).digest("hex").slice(0,16),o={cert_id:t,lesson_key:c,visibility:d,domain_fingerprint:l,contributed_at:new Date().toISOString(),confirm_count:0,trust_score:r.outcome==="success"?.85:.5};await s.set(`cachly:fedbrain:cert:${t}`,JSON.stringify(o)),await s.sadd("cachly:fedbrain:contributed",t);let n;try{await E("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify({topic:r.topic,outcome:r.outcome,what_worked:r.what_worked,what_failed:r.what_failed??"",severity:r.severity??"major",cert_id:t,domain_fingerprint:l,visibility:d})}),n="\u2705 Contributed to global commons"}catch{n="\u{1F4E6} Stored locally (commons API unavailable \u2014 will sync when online)"}return[`\u{1F310} **FedBrain Contribute: "${c}"**`,"",`\u{1F4DC} Certificate: \`${t}\``,`\u{1F3F7}\uFE0F Domain fingerprint: ${u.slice(0,6).map(h=>`\`${h}\``).join(", ")}`,`\u{1F512} Visibility: ${d}`,"",n,...f.geschwaerzt.length?[ce(f.geschwaerzt)]:[],"","\u{1F4A1} At 10 independent confirms \u2192 \u{1F3C6} Gold Standard",`\u{1F50D} Search: \`fedbrain_search(query="${r.topic.split(":").slice(-1)[0]}")\``].join(`
10
+ `)}case"fedbrain_search":{const{instance_id:w,query:c,context_hints:d=[],limit:s=10}=N,e=await A(w),i=await e.smembers("cachly:fedbrain:contributed"),f=new Map;for(const o of i.slice(0,30)){const n=await e.get(`cachly:fedbrain:cert:${o}`);if(n)try{const h=JSON.parse(n);for(const m of(h.domain_fingerprint??"").split(",").filter(Boolean))f.set(m,(f.get(m)??0)+1)}catch{}}for(const o of Array.isArray(d)?d:[])f.set(o.toLowerCase(),(f.get(o.toLowerCase())??0)+2);let r=[],u=!1;try{const o=new URLSearchParams({q:c,limit:String(Math.min(s*2,50))});r=(await E(`/api/v1/syndication/search?${o}`)).results??[]}catch{u=!0;const o=[],n=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{n.on("data",p=>o.push(...p)),n.on("end",h),n.on("error",m)});for(const h of o.slice(0,60)){const m=await e.get(h);if(m)try{const p=JSON.parse(m),y=`${p.topic} ${p.what_worked??""} ${p.what_failed??""}`.toLowerCase();c.toLowerCase().split(/\s+/).some(g=>g.length>2&&y.includes(g))&&r.push({id:h.split(":").pop()??h,topic:p.topic,category:p.topic.split(":")[0],outcome:p.outcome,what_worked:p.what_worked??"",severity:p.severity??"major",confirm_count:0,created_at:p.ts??new Date().toISOString()})}catch{}}}const l=u?" \u2014 \u26A0\uFE0F Commons unreachable, local fallback (this machine only, not confirmed by the network)":"";if(r.length===0)return[`\u{1F310} **FedBrain Search: "${c}"**${l}`,"",'No results. Contribute: `fedbrain_contribute(lesson_key="fix:...")`'].join(`
11
+ `);const a=r.map(o=>{const n=(o.domain_fingerprint??o.category??"").split(",").filter(Boolean),h=n.reduce((g,x)=>g+(f.get(x)??0),0),m=f.size>0?h/Math.max(1,f.size+n.length):0,p=Math.min(1,o.confirm_count/10),y=m*.4+p*.4+(o.outcome==="success"?.2:0);return{...o,weightedScore:y,isGoldStandard:!u&&o.confirm_count>=10}}).sort((o,n)=>n.weightedScore-o.weightedScore).slice(0,s),t=[`\u{1F310} **FedBrain Search: "${c}"** \u2014 ${a.length} result${a.length!==1?"s":""} (context-weighted)${l}
12
+ `];for(const o of a){const n=o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F",h=o.isGoldStandard?" \u{1F3C6} _Gold Standard_":!u&&o.confirm_count>=3?` \u2713${o.confirm_count}`:"",m=Math.round(o.weightedScore*100);t.push(`${n}${h} **\`${o.topic}\`** [ctx: ${m}%]`),o.what_worked&&t.push(` \u2705 ${o.what_worked.slice(0,150)}`),o.what_failed&&t.push(` \u274C ${o.what_failed.slice(0,80)}`),t.push(` _${o.confirm_count} confirm${o.confirm_count!==1?"s":""} | id: \`${o.id}\`_`,"")}if(f.size>0){const o=[...f.entries()].sort((n,h)=>h[1]-n[1]).slice(0,5).map(([n,h])=>`\`${n}\`(${h})`).join(", ");t.push(`\u{1F3AF} Your context: ${o}`)}return t.push('\u{1F4A1} Confirm a result: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`'),t.join(`
13
+ `)}case"fedbrain_confirm":{const{instance_id:w,id:c,topic:d,outcome:s}=N;if(!c)return["\u274C **FedBrain Confirm** needs the lesson `id` from `fedbrain_search` results.",'Run `fedbrain_search(query="...")`, copy the id shown next to a result,','then: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`.'].join(`
14
+ `);const e=await A(w),i=new Date().toISOString(),f=JSON.stringify({id:c,topic:d,outcome:s,ts:i});await e.rpush("cachly:fedbrain:confirmations",f),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const r=s==="worked",u=s==="partially_worked";d&&await J(e,b(d),"fixes",b(`syndicated:${d}`),r,u);let l;try{await E(`/api/v1/syndication/${encodeURIComponent(c)}/confirm`,{method:"POST"}),l="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",f),await e.ltrim("cachly:fedbrain:pending_confirms",-50,-1),l="\u{1F4E6} Queued locally (API unavailable \u2014 will propagate on next online session)"}return[`${r?"\u2705":u?"\u26A0\uFE0F":"\u274C"} **FedBrain Confirm: "${d??c}"** \u2192 ${s}`,"",l,"",d?`\u{1F578}\uFE0F CKG confidence ${r||u?"boosted":"reduced"} for \`${b(d)}\``:"\u{1F578}\uFE0F Local CKG unchanged (pass `topic` to also update your own confidence graph)","\u{1F4A1} Your confirmation helps other brains worldwide.",'\u{1F4CA} Status: `fedbrain_status(instance_id="...")`'].join(`
15
+ `)}case"fedbrain_status":{const{instance_id:w}=N,c=await A(w),d=await c.smembers("cachly:fedbrain:contributed"),s=await c.lrange("cachly:fedbrain:confirmations",-10,-1),e=await c.llen("cachly:fedbrain:pending_confirms"),i=s.map(u=>{try{return JSON.parse(u)}catch{return null}}).filter(Boolean),f=[];for(const u of d.slice(0,15)){const l=await c.get(`cachly:fedbrain:cert:${u}`);if(l)try{const a=JSON.parse(l);f.push({cert_id:a.cert_id,lesson_key:a.lesson_key,confirm_count:a.confirm_count??0,trust_score:a.trust_score??.5,isGold:(a.confirm_count??0)>=10})}catch{}}const r=[`\u{1F310} **FedBrain Status**
16
+ `,`### \u{1F4E4} Contributed Lessons: ${d.length}`];if(f.length>0)for(const u of f){const l=u.isGold?" \u{1F3C6} Gold Standard":"",a="\u2588".repeat(Math.min(10,u.confirm_count))+"\u2591".repeat(Math.max(0,10-u.confirm_count));r.push(` \`${u.lesson_key}\` [${a}] \xD7${u.confirm_count}${l}`)}else r.push(' _None yet. Contribute with `fedbrain_contribute(lesson_key="fix:...")`_');if(r.push("",`### \u{1F4E5} Recent Confirmations: ${i.length}`),i.length>0)for(const u of i.slice(-5)){const l=u.outcome==="worked"?"\u2705":u.outcome==="partially_worked"?"\u26A0\uFE0F":"\u274C";r.push(` ${l} \`${u.topic}\` \u2014 ${u.outcome} (${new Date(u.ts).toLocaleDateString("de-DE")})`)}else r.push(" _None yet. Confirm syndicated lessons with `fedbrain_confirm`_");return e>0&&r.push("",`\u26A0\uFE0F ${e} confirmation${e!==1?"s":""} pending propagation`),r.push("","---",'**Contribute:** `fedbrain_contribute(lesson_key="fix:...")`','**Search:** `fedbrain_search(query="...")`','**Confirm:** `fedbrain_confirm(id="...", topic="...", outcome="worked")`'),r.join(`
17
+ `)}case"brain_federate":{const{instance_id:w,source:c,domain:d,min_confidence:s=.6,dry_run:e=!1}=N;if(w===c)return"\u274C Source and destination cannot be the same brain.";const i=await A(w),f=await A(c),r=d==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${d}*`,u=[],l=f.scanStream({match:r,count:100});if(await new Promise((x,C)=>{l.on("data",_=>u.push(..._)),l.on("end",x),l.on("error",C)}),u.length===0)return[`\u{1F9E0} **brain_federate: "${d}"**`,"",`No CKG nodes found in source brain for domain \`${d}\`.`,"The source brain may not have knowledge in this area yet.",`Try: \`fedbrain_search(query="${d}")\` to find global commons knowledge instead.`].join(`
18
+ `);let a=0,t=0,o=0,n=0,h=0,m=0;const p=[];for(const x of u){const C=await f.get(x);if(!C)continue;let _;try{_=JSON.parse(C)}catch{continue}e||await i.set(x,C),a++;const $=await f.smembers(`cachly:ckg:idx:from:${_.id}`);for(const S of $){const k=await f.get(S);if(!k)continue;let O;try{O=JSON.parse(k)}catch{continue}if(O.confidence<s){n++;continue}e||(await i.set(S,k),await i.sadd(`cachly:ckg:idx:from:${O.from}`,S),await i.sadd(`cachly:ckg:idx:to:${O.to}`,S)),t++}const v=`cachly:lesson:best:${_.id}`,j=await f.get(v);if(j){const S=R(j,null);if(!S||typeof S!="object")continue;const k=G(S);k.geschwaerzt.length&&h++,k.verdacht.length&&m++;const O=k.verdacht.length?{...k.felder,tags:K(k.felder.tags,k.verdacht)}:k.felder;if(e||await i.set(v,JSON.stringify(O)),o++,p.length<8){const M=O.outcome==="success"?"\u2705":O.outcome==="failure"?"\u274C":"\u26A0\uFE0F";p.push(` ${M} \`${O.topic}\` \u2014 ${(O.what_worked??"").slice(0,80)}`)}}}if(!e){const x=JSON.stringify({source:c,domain:d,transferred_at:new Date().toISOString(),nodes:a,edges:t,lessons:o});await i.rpush("cachly:fedbrain:federations",x),await i.ltrim("cachly:fedbrain:federations",-50,-1)}const g=[`\u{1F9E0} **brain_federate: "${d}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${c}\``,`\u{1F4E5} Destination: \`${w}\``,`\u{1F50D} Domain filter: \`${d}\` | min_confidence: ${s}`,"","### Transfer Summary",` \u{1F578}\uFE0F CKG nodes: ${a}`,` \u{1F517} CKG edges: ${t} (${n} skipped, confidence < ${s})`,` \u{1F4DA} Lessons: ${o}`,...H(h,m,`${o} kopierten Lektionen`),""];return p.length>0&&(g.push("### Sample lessons transferred:",...p),o>p.length&&g.push(` _... and ${o-p.length} more_`),g.push("")),e?g.push("\u{1F4A1} Run without `dry_run: true` to apply the transfer."):(g.push(`\u2705 Transfer complete. Your brain now has the \`${d}\` knowledge from \`${c}\`.`),g.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${d}")\` | \`recall_best_solution(topic="${d}:...")\``)),g.join(`
19
+ `)}case"crystal_view":{const{instance_id:w,show_raw:c=!1}=N,d=await A(w),s=await d.get("cachly:crystal:latest");if(!s)return["\u{1F48E} **Memory Crystal: not yet created**","","No crystal found. Create one with `memory_crystalize()` to compress your accumulated wisdom.","","\u{1F4A1} Tip: run `memory_crystalize` monthly for best results."].join(`
20
+ `);const e=R(s,null);if(!e)return"\u274C Memory Crystal data is corrupted. Re-create with `memory_crystalize()`.";const i=Math.floor((Date.now()-new Date(e.ts).getTime())/864e5),f=i<=7?"\u{1F7E2}":i<=30?"\u{1F7E1}":"\u{1F534}",r=[`\u{1F48E} **Memory Crystal: ${e.label}**`,"",`\u{1F4C5} Created: ${new Date(e.ts).toLocaleDateString("de-DE")} (${i}d ago ${f})`,`\u{1F4CA} Compressed from: ${e.created_from}`,`\u{1F5C2}\uFE0F Categories: ${e.categories.slice(0,10).map(l=>`\`${l}\``).join(", ")}${e.categories.length>10?` +${e.categories.length-10} more`:""}`,"",`**\u{1F511} Top patterns (${e.top_patterns.length}):**`];for(const l of e.top_patterns)r.push(` \u2022 **${l.category}** (${l.count}\xD7): ${l.insight.slice(0,110)}`);i>30&&r.push("",`\u26A0\uFE0F Crystal is ${i}d old \u2014 run \`memory_crystalize()\` to refresh it.`),c&&r.push("","```json",JSON.stringify(e,null,2),"```");const u=await d.get("cachly:crystal:team:latest").catch(()=>null);if(u){const l=R(u,null);if(l&&l.patterns?.length){const a=Math.floor((Date.now()-new Date(l.ts).getTime())/864e5);r.push("","---",`\u{1F4A0} **Team Crystal: ${l.label}** _(${a}d ago \xB7 ${l.contributors} contributors)_`,"_Fixes multiple teammates independently converged on \u2014 the team-wide layer:_");for(const t of l.patterns.slice(0,5))r.push(` \u2022 \u{1F9E9} **${t.concept}** \u2014 ${t.author_count} people (${t.authors.map(o=>`@${o}`).join(", ")}): ${t.convergent_fix.slice(0,90)}`)}}return r.push("",'\u{1F4A1} Refresh: `memory_crystalize()` \xB7 `team_crystallize()` | Recover: `compact_recover(instance_id="...")`'),r.join(`
21
+ `)}case"compact_recover":{const{instance_id:w,focus:c=""}=N,d=await A(w),s=[`\u{1F501} **Compact Recovery Briefing**
22
22
  `];s.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*
23
- `);const e=await d.get("cachly:crystal:latest");if(e){const t=R(e,null);if(t){s.push(`### \u{1F48E} Memory Crystal: ${t.label}`),s.push(`Compressed from ${t.session_count} sessions, ${t.lesson_count} lessons.`);const o=c?t.top_patterns.filter(n=>n.category.toLowerCase().includes(c.toLowerCase())||n.insight.toLowerCase().includes(c.toLowerCase())).slice(0,4):t.top_patterns.slice(0,4);for(const n of o)s.push(` \u2022 **${n.category}**: ${n.insight.slice(0,100)}`);s.push("")}}const i=await d.get("cachly:session:last");if(i){const t=R(i,null);t&&(s.push("### \u{1F550} Last Session"),t.focus&&s.push(`Focus: _${t.focus}_`),t.summary&&s.push(`Summary: ${t.summary.slice(0,300)}`),s.push(""))}const u=await d.get("cachly:session:handoff");if(u){const t=R(u,null);if(t){if(s.push("### \u{1F4CB} Handoff (from last window)"),t.context_summary&&s.push(`Context: ${t.context_summary.slice(0,200)}`),t.remaining_tasks?.length){s.push("Remaining tasks:");for(const o of t.remaining_tasks.slice(0,5))s.push(` \u2022 ${o}`)}t.instructions&&s.push(`\u26A0\uFE0F Instructions: ${t.instructions.slice(0,200)}`),t.blocked_on&&s.push(`\u{1F6A7} Blocked on: ${t.blocked_on}`),s.push("")}}const r=await d.get("cachly:ctx:wip-registry");if(r){const t=R(r,null);t?.content&&(s.push("### \u{1F527} WIP Registry"),s.push(t.content.slice(0,400)),s.push(""))}const f=[],l=d.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((t,o)=>{l.on("data",n=>f.push(...n)),l.on("end",t),l.on("error",o)});const a=[];for(const t of f.slice(0,30)){const o=await d.get(t);if(o)try{const n=JSON.parse(o);(n.status==="in_progress"||n.status==="blocked")&&a.push({title:n.title??t,status:n.status,priority:n.priority})}catch{}}if(a.length>0){s.push("### \u{1F6A7} Open Items");for(const t of a.slice(0,5))s.push(` \u2022 [${t.status}] ${t.title}`);s.push("")}if(c){const t=[],o=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{o.on("data",p=>t.push(...p)),o.on("end",h),o.on("error",m)});const n=[];for(const h of t){const m=await d.get(h);if(m)try{const p=JSON.parse(m);p.topic.toLowerCase().includes(c.toLowerCase())&&p.what_worked&&n.push({topic:p.topic,what_worked:p.what_worked})}catch{}}if(n.length>0){s.push(`### \u{1F4A1} Relevant Lessons for "${c}"`);for(const h of n.slice(0,4))s.push(` \u2022 **${h.topic}**: ${h.what_worked.slice(0,100)}`);s.push("")}}return s.length<=3&&s.push("_No brain data found. Start accumulating knowledge with `learn_from_attempts` and `session_start`._"),s.push("---","\u{1F9E0} Brain is ready. Continue your work \u2014 full context restored."),s.join(`
24
- `)}case"brain_from_git":{const w=Date.now(),{instance_id:c,repo_path:d=".",limit:s=100,branch:e="HEAD",since:i="",incremental:u=!0}=j,r=await A(c),{resolve:f}=await import("node:path"),l=f(d),a=Math.max(1,Math.floor(Math.min(Number(s)||100,500)));if(typeof e!="string"||$e(e))return'\u274C Ungueltiger `branch`: darf nicht mit "-" beginnen.';await Je();try{try{if(!Se(l))throw new Error("kein Ordner");ie(l,["rev-parse","--git-dir"],{stderr:"pipe"})}catch{return`\u274C Not a git repository: \`${l}\`. Pass \`repo_path\` pointing to a git checkout.`}const t=`cachly:brain_from_git:last_sha:${Buffer.from(l).toString("base64").slice(0,32)}`;let o="",n=!1;u!==!1&&!i&&(o=await r.get(t)??"",ke(o)||(o=""),n=!!o);const m=(n?`${o}..HEAD`:"")||e||"HEAD",p=je(m,a,i);let y="";try{y=ie(l,p,{stderr:"pipe",timeoutMs:6e4})}catch(I){return`\u274C git log failed: ${I.message}. Check \`repo_path\` and \`branch\`.`}const g=Ie(y);if(g.length===0)return n?`\u2705 brain_from_git: Brain is up to date \u2014 no new commits since last run (last SHA: \`${o.slice(0,8)}\`).`:ae({repoDir:l,revRange:m,processed:0,ingested:0,skipped:0,durationMs:Date.now()-w,isIncremental:!1,instanceId:c,categories:[],suggestedQueries:[],emptyReason:`No commits found in \`${l}\` on branch \`${e}\`${i?` since ${i}`:""}.`});const x=new Date().toISOString();let C=0,_=0;const $=new Map,v=new Map,O=[];let S=null;const k=g.length,N=Math.max(1,Math.floor(k/10));let J=0;process.stderr.write(`
23
+ `);const e=await d.get("cachly:crystal:latest");if(e){const t=R(e,null);if(t){s.push(`### \u{1F48E} Memory Crystal: ${t.label}`),s.push(`Compressed from ${t.session_count} sessions, ${t.lesson_count} lessons.`);const o=c?t.top_patterns.filter(n=>n.category.toLowerCase().includes(c.toLowerCase())||n.insight.toLowerCase().includes(c.toLowerCase())).slice(0,4):t.top_patterns.slice(0,4);for(const n of o)s.push(` \u2022 **${n.category}**: ${n.insight.slice(0,100)}`);s.push("")}}const i=await d.get("cachly:session:last");if(i){const t=R(i,null);t&&(s.push("### \u{1F550} Last Session"),t.focus&&s.push(`Focus: _${t.focus}_`),t.summary&&s.push(`Summary: ${t.summary.slice(0,300)}`),s.push(""))}const f=await d.get("cachly:session:handoff");if(f){const t=R(f,null);if(t){if(s.push("### \u{1F4CB} Handoff (from last window)"),t.context_summary&&s.push(`Context: ${t.context_summary.slice(0,200)}`),t.remaining_tasks?.length){s.push("Remaining tasks:");for(const o of t.remaining_tasks.slice(0,5))s.push(` \u2022 ${o}`)}t.instructions&&s.push(`\u26A0\uFE0F Instructions: ${t.instructions.slice(0,200)}`),t.blocked_on&&s.push(`\u{1F6A7} Blocked on: ${t.blocked_on}`),s.push("")}}const r=await d.get("cachly:ctx:wip-registry");if(r){const t=R(r,null);t?.content&&(s.push("### \u{1F527} WIP Registry"),s.push(t.content.slice(0,400)),s.push(""))}const u=[],l=d.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((t,o)=>{l.on("data",n=>u.push(...n)),l.on("end",t),l.on("error",o)});const a=[];for(const t of u.slice(0,30)){const o=await d.get(t);if(o)try{const n=JSON.parse(o);(n.status==="in_progress"||n.status==="blocked")&&a.push({title:n.title??t,status:n.status,priority:n.priority})}catch{}}if(a.length>0){s.push("### \u{1F6A7} Open Items");for(const t of a.slice(0,5))s.push(` \u2022 [${t.status}] ${t.title}`);s.push("")}if(c){const t=[],o=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{o.on("data",p=>t.push(...p)),o.on("end",h),o.on("error",m)});const n=[];for(const h of t){const m=await d.get(h);if(m)try{const p=JSON.parse(m);p.topic.toLowerCase().includes(c.toLowerCase())&&p.what_worked&&n.push({topic:p.topic,what_worked:p.what_worked})}catch{}}if(n.length>0){s.push(`### \u{1F4A1} Relevant Lessons for "${c}"`);for(const h of n.slice(0,4))s.push(` \u2022 **${h.topic}**: ${h.what_worked.slice(0,100)}`);s.push("")}}return s.length<=3&&s.push("_No brain data found. Start accumulating knowledge with `learn_from_attempts` and `session_start`._"),s.push("---","\u{1F9E0} Brain is ready. Continue your work \u2014 full context restored."),s.join(`
24
+ `)}case"brain_from_git":{const w=Date.now(),{instance_id:c,repo_path:d=".",limit:s=100,branch:e="HEAD",since:i="",incremental:f=!0}=N,r=await A(c),{resolve:u}=await import("node:path"),l=u(d),a=Math.max(1,Math.floor(Math.min(Number(s)||100,500)));if(typeof e!="string"||$e(e))return'\u274C Ungueltiger `branch`: darf nicht mit "-" beginnen.';await Me();try{try{if(!Se(l))throw new Error("kein Ordner");ie(l,["rev-parse","--git-dir"],{stderr:"pipe"})}catch{return`\u274C Not a git repository: \`${l}\`. Pass \`repo_path\` pointing to a git checkout.`}const t=`cachly:brain_from_git:last_sha:${Buffer.from(l).toString("base64").slice(0,32)}`;let o="",n=!1;f!==!1&&!i&&(o=await r.get(t)??"",ke(o)||(o=""),n=!!o);const m=(n?`${o}..HEAD`:"")||e||"HEAD",p=Ne(m,a,i);let y="";try{y=ie(l,p,{stderr:"pipe",timeoutMs:6e4})}catch(I){return`\u274C git log failed: ${I.message}. Check \`repo_path\` and \`branch\`.`}const g=Ie(y);if(g.length===0)return n?`\u2705 brain_from_git: Brain is up to date \u2014 no new commits since last run (last SHA: \`${o.slice(0,8)}\`).`:ae({repoDir:l,revRange:m,processed:0,ingested:0,skipped:0,durationMs:Date.now()-w,isIncremental:!1,instanceId:c,categories:[],suggestedQueries:[],emptyReason:`No commits found in \`${l}\` on branch \`${e}\`${i?` since ${i}`:""}.`});const x=new Date().toISOString();let C=0,_=0;const $=new Map,v=new Map,j=[];let S=null;const k=g.length,O=Math.max(1,Math.floor(k/10));let M=0;process.stderr.write(`
25
25
  \u{1F9E0} brain_from_git: processing ${k} commits from ${l}...
26
- `);let H=0,Q=0;for(let I=0;I<g.length;I++){const{commit:L,geschwaerzt:de,verdacht:ue,lektion:P}=Ne(g[I]);if(de&&H++,ue&&Q++,I-J>=N&&(process.stderr.write(` \u23F3 Processing ${I}/${k} commits (${C} lessons so far)...
27
- `),J=I),!P){_++;continue}const{topic:D,category:E,outcome:q,severity:U}=P;$.set(E,($.get(E)??0)+1),v.set(U,(v.get(U)??0)+1),O.push(D),(!S||E==="fix"&&!S.topic.startsWith("fix:"))&&(S={topic:D,subject:L.subject});const te=P.file_paths,oe={topic:D,outcome:q,severity:U,what_worked:P.what_worked,what_failed:P.what_failed,context:P.context,author:P.author,file_paths:te,commands:P.commands,tags:P.tags,visibility:"team",depends_on:[],recall_count:0,ts:x,verified_at:x,confidence:.55,audit_trail:[{ts:x,action:"brain_from_git",sha:L.sha.slice(0,8)}],version:3};await r.get(`cachly:lesson:best:${D}`)||(await r.set(`cachly:lesson:best:${D}`,JSON.stringify(oe),"EX",90*86400),await r.rpush(`cachly:lessons:${D}`,JSON.stringify(oe)),await r.ltrim(`cachly:lessons:${D}`,-100,-1),await r.expire(`cachly:lessons:${D}`,90*86400),await r.sadd(Ae,D).catch(()=>{})),await r.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:D,sha:L.sha.slice(0,8),subject:L.subject.slice(0,60)})),await r.ltrim("cachly:lessons:brain_from_git:all",-500,-1),await r.expire("cachly:lessons:brain_from_git:all",90*86400);const se=b(D);if(await T(r,se,E,"git-derived"),L.author)try{const V=await pe(r,L.author,E);await M(r,V,"authored",se,q==="success",q==="partial");for(const fe of te.slice(0,8)){const ne=await ge(r,fe);await M(r,V,"touched",ne,!0),await _e(r,ne,V)}}catch{}C++}process.stderr.write(` \u2705 brain_from_git complete: ${C}/${k} commits ingested
26
+ `);let F=0,Q=0;for(let I=0;I<g.length;I++){const{commit:L,geschwaerzt:de,verdacht:ue,lektion:P}=Oe(g[I]);if(de&&F++,ue&&Q++,I-M>=O&&(process.stderr.write(` \u23F3 Processing ${I}/${k} commits (${C} lessons so far)...
27
+ `),M=I),!P){_++;continue}const{topic:D,category:z,outcome:q,severity:U}=P;$.set(z,($.get(z)??0)+1),v.set(U,(v.get(U)??0)+1),j.push(D),(!S||z==="fix"&&!S.topic.startsWith("fix:"))&&(S={topic:D,subject:L.subject});const te=P.file_paths,oe={topic:D,outcome:q,severity:U,what_worked:P.what_worked,what_failed:P.what_failed,context:P.context,author:P.author,file_paths:te,commands:P.commands,tags:P.tags,visibility:"team",depends_on:[],recall_count:0,ts:x,verified_at:x,confidence:.55,audit_trail:[{ts:x,action:"brain_from_git",sha:L.sha.slice(0,8)}],version:3};await r.get(`cachly:lesson:best:${D}`)||(await r.set(`cachly:lesson:best:${D}`,JSON.stringify(oe),"EX",90*86400),await r.rpush(`cachly:lessons:${D}`,JSON.stringify(oe)),await r.ltrim(`cachly:lessons:${D}`,-100,-1),await r.expire(`cachly:lessons:${D}`,90*86400),await r.sadd(Ae,D).catch(()=>{})),await r.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:D,sha:L.sha.slice(0,8),subject:L.subject.slice(0,60)})),await r.ltrim("cachly:lessons:brain_from_git:all",-500,-1),await r.expire("cachly:lessons:brain_from_git:all",90*86400);const se=b(D);if(await T(r,se,z,"git-derived"),L.author)try{const W=await pe(r,L.author,z);await J(r,W,"authored",se,q==="success",q==="partial");for(const fe of te.slice(0,8)){const ne=await ge(r,fe);await J(r,W,"touched",ne,!0),await _e(r,ne,W)}}catch{}C++}process.stderr.write(` \u2705 brain_from_git complete: ${C}/${k} commits ingested
28
28
 
29
- `),C>0&&ve(),g.length>0&&g[0]?.sha&&await r.set(t,g[0].sha,"EX",2160*3600),De={fixes:$.get("fix")??0,features:$.get("feat")??0,refactors:$.get("refactor")??0,total:C};let X=null;if(S&&C>0)try{const I=await xe(r,["cachly:lesson:best:*"],S.subject,1);if(I.length>0){const L=R(I[0].content,{});X={query:S.subject.slice(0,80),topic:L.topic??I[0].key.replace("cachly:lesson:best:",""),snippet:(L.what_worked??"").slice(0,120)||S.subject.slice(0,120)}}}catch{}const Z=ae({repoDir:l,revRange:m,processed:g.length,ingested:C,skipped:_,durationMs:Date.now()-w,isIncremental:n,lastSha:o,instanceId:c,categories:[...$.entries()].sort((I,L)=>L[1]-I[1]),severities:[...v.entries()].sort((I,L)=>L[1]-I[1]),proof:X,suggestedQueries:Oe(O,c)}),ee=F(H,Q,`${g.length} Commits`);return ee.length?[Z,"",...ee].join(`
30
- `):Z}finally{Pe()}}case"brain_from_ci":{const{instance_id:w,outcomes:c}=j,d=await A(w),s=Date.now();let e=0,i=0,u=0,r=0,f=0;const l=c.length;for(const a of c){const t=G({job:String(a.job??"unknown"),context:String(a.context??"")});t.geschwaerzt.length&&r++;const o=String(a.status??""),n=String(a.prev_status??""),h=t.felder.job,m=t.felder.context,p=["failure","red","error"].includes(n)&&["success","green","passed"].includes(o),y=["success","green","passed"].includes(n)&&["failure","red","error"].includes(o),g=`ci:${b(h)}`,x=b(g);if(await T(d,x,"ci","job"),p){const _=b(`problem:${b(h)}`);await T(d,_,"problem","ci-failure"),await M(d,x,"fixes",_,!0);const $={topic:g,outcome:"success",what_worked:`CI job "${h}" went ${n} \u2192 ${o}`,what_failed:`Job "${h}" was failing`,context:`brain_from_ci: ${m}`,severity:"major",file_paths:[],commands:[],tags:K(["brain_from_ci","ci"],t.verdacht),depends_on:[],recall_count:0,ts:s,verified_at:s,confidence:.65,audit_trail:[{ts:s,action:"brain_from_ci_fixed"}],version:3};await d.rpush(`cachly:lessons:${g}`,JSON.stringify($)),await d.ltrim(`cachly:lessons:${g}`,-100,-1),await d.set(`cachly:lesson:best:${g}`,JSON.stringify($)),t.verdacht.length&&f++,e++}else if(y){const _=b(`cause:${b(h)}`);await T(d,_,"cause","ci-break"),await M(d,x,"causes",_,!1),i++}else u++;const C=`cachly:cls:${w}`;await d.rpush(C,JSON.stringify({source:"ci_outcome",payload:{status:o,prev_status:n,job:h},ts:s})),await d.ltrim(C,-200,-1)}return Te={fixes:e,breaks:i,stable:u,total:l},[`\u{1F4E5} **brain_from_ci**: Ingested ${l} outcomes \u2014 ${e} fixes learned, ${i} breaks noted, ${u} stable`,"",e>0?`\u2705 ${e} fix lesson${e!==1?"s":""} written (confidence 0.65) \u2014 CKG \`fixes\` edges added`:"",i>0?`\u{1F534} ${i} break${i!==1?"s":""} noted \u2014 CKG \`causes\` edges added`:"",u>0?`\u{1F4CA} ${u} stable outcome${u!==1?"s":""} recorded`:"","",'\u{1F4A1} Explore: `brain_search(query="ci")` | `brain_predict(context="<job-name>")`',...F(r,f,`${l} CI-Ergebnissen`)].filter(Boolean).join(`
31
- `)}case"brain_predict_failures":{const{instance_id:w,context:c,top_k:d=5,format:s="detailed"}=j,e=await A(w),i=c.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g," ").split(/\s+/).filter(n=>n.length>2),u=[];for(const n of i.slice(0,8)){const h=[],m=e.scanStream({match:`cachly:ckg:node:*${n}*`,count:50});await new Promise((p,y)=>{m.on("data",g=>h.push(...g)),m.on("end",p),m.on("error",y)});for(const p of h.slice(0,5)){const y=await e.get(p);if(!y)continue;const g=R(y,null);if(!g)continue;const x=await e.smembers(`cachly:ckg:idx:from:${g.id}`);for(const C of x.slice(0,20)){const _=await e.get(C);if(!_)continue;const $=R(_,null);if(!$||$.edgeType!=="causes"&&$.edgeType!=="degrades_under")continue;const v=await e.smembers(`cachly:ckg:idx:from:${$.to}`);let O;for(const S of v.slice(0,10)){const k=await e.get(S);if(!k)continue;const N=R(k,null);if(N&&N.edgeType==="fixes"){const J=await e.get(`cachly:lesson:best:${N.from}`);if(J){O=R(J,null)?.what_worked?.slice(0,120);break}}}u.push({concept:g.id,failure:$.to.replace(/-/g," "),probability:$.confidence,fix:O,source:"ckg"})}}}const r=[],f=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((n,h)=>{f.on("data",m=>r.push(...m)),f.on("end",n),f.on("error",h)});for(const n of r.slice(0,100)){const h=await e.get(n);if(h)try{const m=JSON.parse(h);if(m.outcome!=="failure"&&m.outcome!=="partial"||!m.what_failed)continue;const p=`${m.topic} ${m.what_failed}`.toLowerCase(),y=i.filter(x=>p.includes(x)).length/Math.max(1,i.length);if(y<.15)continue;const g=m.severity==="critical"?.15:m.severity==="major"?.05:0;u.push({concept:m.topic,failure:m.what_failed.slice(0,80),probability:Math.min(.97,(m.confidence??.5)*y*1.5+g),fix:m.what_worked?.slice(0,120),topic:m.topic,source:"lesson"})}catch{}}if(u.length===0)return[`\u{1F52E} **Failure Prediction: "${c}"**`,"","No known failure patterns found for this context.",'\u{1F4A1} The brain learns from every `learn_from_attempts(outcome="failure")` call.',`\u{1F50D} Try: \`brain_predict(context="${c}")\` for broader predictions.`].join(`
32
- `);const l=new Set,a=u.filter(n=>{const h=n.failure.slice(0,40);return l.has(h)?!1:(l.add(h),!0)}).sort((n,h)=>h.probability-n.probability).slice(0,Number(d)),t=[`\u{1F52E} **Failure Prediction for: "${c}"**
33
- `];t.push(`> Pre-deploy failure analysis based on ${u.length} patterns. Ranked by probability.
29
+ `),C>0&&ve(),g.length>0&&g[0]?.sha&&await r.set(t,g[0].sha,"EX",2160*3600),De={fixes:$.get("fix")??0,features:$.get("feat")??0,refactors:$.get("refactor")??0,total:C};let X=null;if(S&&C>0)try{const I=await xe(r,["cachly:lesson:best:*"],S.subject,1);if(I.length>0){const L=R(I[0].content,{});X={query:S.subject.slice(0,80),topic:L.topic??I[0].key.replace("cachly:lesson:best:",""),snippet:(L.what_worked??"").slice(0,120)||S.subject.slice(0,120)}}}catch{}const Z=ae({repoDir:l,revRange:m,processed:g.length,ingested:C,skipped:_,durationMs:Date.now()-w,isIncremental:n,lastSha:o,instanceId:c,categories:[...$.entries()].sort((I,L)=>L[1]-I[1]),severities:[...v.entries()].sort((I,L)=>L[1]-I[1]),proof:X,suggestedQueries:je(j,c)}),ee=H(F,Q,`${g.length} Commits`);return ee.length?[Z,"",...ee].join(`
30
+ `):Z}finally{Pe()}}case"brain_from_ci":{const{instance_id:w,outcomes:c}=N,d=await A(w),s=Date.now();let e=0,i=0,f=0,r=0,u=0;const l=c.length;for(const a of c){const t=G({job:String(a.job??"unknown"),context:String(a.context??"")});t.geschwaerzt.length&&r++;const o=String(a.status??""),n=String(a.prev_status??""),h=t.felder.job,m=t.felder.context,p=["failure","red","error"].includes(n)&&["success","green","passed"].includes(o),y=["success","green","passed"].includes(n)&&["failure","red","error"].includes(o),g=`ci:${b(h)}`,x=b(g);if(await T(d,x,"ci","job"),p){const _=b(`problem:${b(h)}`);await T(d,_,"problem","ci-failure"),await J(d,x,"fixes",_,!0);const $={topic:g,outcome:"success",what_worked:`CI job "${h}" went ${n} \u2192 ${o}`,what_failed:`Job "${h}" was failing`,context:`brain_from_ci: ${m}`,severity:"major",file_paths:[],commands:[],tags:K(["brain_from_ci","ci"],t.verdacht),depends_on:[],recall_count:0,ts:s,verified_at:s,confidence:.65,audit_trail:[{ts:s,action:"brain_from_ci_fixed"}],version:3};await d.rpush(`cachly:lessons:${g}`,JSON.stringify($)),await d.ltrim(`cachly:lessons:${g}`,-100,-1),await d.set(`cachly:lesson:best:${g}`,JSON.stringify($)),t.verdacht.length&&u++,e++}else if(y){const _=b(`cause:${b(h)}`);await T(d,_,"cause","ci-break"),await J(d,x,"causes",_,!1),i++}else f++;const C=`cachly:cls:${w}`;await d.rpush(C,JSON.stringify({source:"ci_outcome",payload:{status:o,prev_status:n,job:h},ts:s})),await d.ltrim(C,-200,-1)}return Te={fixes:e,breaks:i,stable:f,total:l},[`\u{1F4E5} **brain_from_ci**: Ingested ${l} outcomes \u2014 ${e} fixes learned, ${i} breaks noted, ${f} stable`,"",e>0?`\u2705 ${e} fix lesson${e!==1?"s":""} written (confidence 0.65) \u2014 CKG \`fixes\` edges added`:"",i>0?`\u{1F534} ${i} break${i!==1?"s":""} noted \u2014 CKG \`causes\` edges added`:"",f>0?`\u{1F4CA} ${f} stable outcome${f!==1?"s":""} recorded`:"","",'\u{1F4A1} Explore: `brain_search(query="ci")` | `brain_predict(context="<job-name>")`',...H(r,u,`${l} CI-Ergebnissen`)].filter(Boolean).join(`
31
+ `)}case"brain_predict_failures":{const{instance_id:w,context:c,top_k:d=5,format:s="detailed"}=N,e=await A(w),i=c.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g," ").split(/\s+/).filter(n=>n.length>2),f=[];for(const n of i.slice(0,8)){const h=[],m=e.scanStream({match:`cachly:ckg:node:*${n}*`,count:50});await new Promise((p,y)=>{m.on("data",g=>h.push(...g)),m.on("end",p),m.on("error",y)});for(const p of h.slice(0,5)){const y=await e.get(p);if(!y)continue;const g=R(y,null);if(!g)continue;const x=await e.smembers(`cachly:ckg:idx:from:${g.id}`);for(const C of x.slice(0,20)){const _=await e.get(C);if(!_)continue;const $=R(_,null);if(!$||$.edgeType!=="causes"&&$.edgeType!=="degrades_under")continue;const v=await e.smembers(`cachly:ckg:idx:from:${$.to}`);let j;for(const S of v.slice(0,10)){const k=await e.get(S);if(!k)continue;const O=R(k,null);if(O&&O.edgeType==="fixes"){const M=await e.get(`cachly:lesson:best:${O.from}`);if(M){j=R(M,null)?.what_worked?.slice(0,120);break}}}f.push({concept:g.id,failure:$.to.replace(/-/g," "),probability:$.confidence,fix:j,source:"ckg"})}}}const r=[],u=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((n,h)=>{u.on("data",m=>r.push(...m)),u.on("end",n),u.on("error",h)});for(const n of r.slice(0,100)){const h=await e.get(n);if(h)try{const m=JSON.parse(h);if(m.outcome!=="failure"&&m.outcome!=="partial"||!m.what_failed)continue;const p=`${m.topic} ${m.what_failed}`.toLowerCase(),y=i.filter(x=>p.includes(x)).length/Math.max(1,i.length);if(y<.15)continue;const g=m.severity==="critical"?.15:m.severity==="major"?.05:0;f.push({concept:m.topic,failure:m.what_failed.slice(0,80),probability:Math.min(.97,(m.confidence??.5)*y*1.5+g),fix:m.what_worked?.slice(0,120),topic:m.topic,source:"lesson"})}catch{}}if(f.length===0)return[`\u{1F52E} **Failure Prediction: "${c}"**`,"","No known failure patterns found for this context.",'\u{1F4A1} The brain learns from every `learn_from_attempts(outcome="failure")` call.',`\u{1F50D} Try: \`brain_predict(context="${c}")\` for broader predictions.`].join(`
32
+ `);const l=new Set,a=f.filter(n=>{const h=n.failure.slice(0,40);return l.has(h)?!1:(l.add(h),!0)}).sort((n,h)=>h.probability-n.probability).slice(0,Number(d)),t=[`\u{1F52E} **Failure Prediction for: "${c}"**
33
+ `];t.push(`> Pre-deploy failure analysis based on ${f.length} patterns. Ranked by probability.
34
34
  `);for(let n=0;n<a.length;n++){const h=a[n],m=Math.round(h.probability*100),p="\u2588".repeat(Math.round(m/10))+"\u2591".repeat(10-Math.round(m/10)),y=m>=70?"\u{1F534}":m>=40?"\u{1F7E1}":"\u{1F7E2}";t.push(`${y} **${n+1}. ${h.failure}**`),t.push(` Probability: ${p} **${m}%** (${h.source==="ckg"?"CKG causal edge":"lesson history"})`),s==="detailed"&&h.fix&&t.push(` \u2705 Pre-loaded fix: _${h.fix}_`),s==="detailed"&&h.topic&&t.push(` \u{1F4DA} Lesson: \`${h.topic}\``),t.push("")}const o=a.filter(n=>n.probability>=.6);return o.length>0?t.push(`\u26A0\uFE0F **${o.length} high-risk failure${o.length>1?"s":""} detected** (\u226560% probability). Review fixes before proceeding.`):t.push("\u2705 No high-risk failures detected. Proceed with caution and monitor closely."),t.push("",'\u{1F4A1} After deploy: `learn_from_attempts(topic="deploy:...", outcome="success|failure")` to improve future predictions.'),t.join(`
35
- `)}case"brain_contribute_signal":{const{instance_id:w,topic_category:c,outcome:d,confidence:s=.5}=j;if(!c?.trim())throw new Error("topic_category is required");if(!["success","failure","partial"].includes(d))throw new Error("outcome must be success, failure, or partial");const e=re({topic_category:c.trim()},"die Commons");if(!e.ok)return e.meldung;const i=e.felder.topic_category,u=s>=.75?"high":s>=.5?"medium":"low";let r="\u{1F4E6} Signal stored locally (commons API unavailable)";try{await z("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:i.toLowerCase(),outcome:d,confidence:s})}),r="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const f=await A(w),l=`cachly:fed:outbox:${Date.now()}`;await f.set(l,JSON.stringify({topic_category:i,outcome:d,bucket:u,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${i}\`**`,"",`\u{1F4CA} Outcome: **${d}** \xB7 Confidence bucket: **${u}**`,"\u{1F6E1}\uFE0F Privacy: topic category only \u2014 no lesson text, no org identity","",r,...e.geschwaerzt.length?[ce(e.geschwaerzt)]:[],"","\u{1F4A1} When \u2265 k orgs contribute the same pattern, a meta-lesson appears in `brain_import_meta`."].join(`
36
- `)}case"brain_import_meta":{const{instance_id:w,category:c,limit:d=20}=j;let s=[],e=3;try{const a=new URLSearchParams;c&&a.set("category",c),a.set("limit",String(Math.min(d,200)));const t=await z(`/api/v1/federation/meta?${a.toString()}`);s=t.meta_lessons??[],e=t.k_threshold??3}catch{return"\u274C Could not reach the global commons API. Try again later."}if(s.length===0)return["\u{1F310} **Brain Import Meta-Lessons**","",`No meta-lessons available yet (k-threshold: ${e} signals required).`,"","\u{1F4A1} Contribute signals with `brain_contribute_signal` to help build the commons."].join(`
37
- `);let i=0;const u=new Set;s=s.map(a=>{const t=G({topic_category:a.topic_category,dominant_outcome:a.dominant_outcome});return t.geschwaerzt.length&&i++,t.verdacht.length&&u.add(t.felder.topic_category),{...a,...t.felder}});const r=await A(w);let f=0;for(const a of s){const t=`cachly:lesson:best:meta:${a.topic_category}`;await r.get(t)||(await r.set(t,JSON.stringify({topic:`meta:${a.topic_category}`,outcome:a.dominant_outcome,what_worked:a.contributor_count!=null?`Meta-pattern from ${a.contributor_count} independent orgs`:`Meta-pattern from ${a.signal_count} signals`,what_failed:"",recall_count:0,ts:a.derived_at,state:"meta",...u.has(a.topic_category)?{tags:[Le]}:{},avg_confidence:a.avg_confidence,signal_count:a.signal_count,audit_trail:[{ts:new Date().toISOString(),action:"imported_meta"}]})),f++)}const l=[`\u{1F310} **Brain Import Meta-Lessons** (k \u2265 ${e})`,"","| Topic Category | Outcome | Confidence | Signals |","|---|---|---|---|"];for(const a of s.slice(0,15)){const t=(a.avg_confidence*100).toFixed(0)+"%";l.push(`| \`${a.topic_category}\` | ${a.dominant_outcome} | ${t} | ${a.signal_count} |`)}return s.length>15&&l.push(`| _\u2026${s.length-15} more_ | | | |`),l.push("",`\u2705 **${f}** new meta-lessons imported into local Brain.`),f<s.length&&l.push(`_(${s.length-f} already present \u2014 not overwritten)_`),l.push(...F(i,u.size,`${s.length} Kategorienamen`)),l.join(`
38
- `)}case"brain_watch":{const{instance_id:w="",project_dir:c=".",api_key:d}=j,{resolve:s}=await import("node:path"),e=s(c),{result:i,hookPath:u}=await Ce(e,w,d);return i==="skipped-no-git"?["\u26A0\uFE0F **brain_watch: no git repository found**","",`No \`.git\` directory in \`${e}\`.`,"Pass `project_dir` pointing to a git checkout."].join(`
39
- `):[`\u{1F9E0} **brain_watch ${{written:"\u2705 Hook installed (new)",upgraded:"\u{1F504} Hook upgraded to latest version",appended:"\u{1F4CE} Hook appended to existing post-commit script",unchanged:"\u2713 Hook already up to date \u2014 nothing changed"}[i]??i}**`,"",`Hook path: \`${u}\``,`Instance: \`${w||"(none \u2014 set CACHLY_BRAIN_INSTANCE_ID or pass instance_id)"}\``,"","Every future commit will automatically teach your Brain.","No manual `brain_from_git` needed \u2014 the hook runs silently in the background.","",'\u{1F4A1} Verify: `git commit --allow-empty -m "test brain_watch"` then `smart_recall(query="test")`'].join(`
35
+ `)}case"brain_contribute_signal":{const{instance_id:w,topic_category:c,outcome:d,confidence:s=.5}=N;if(!c?.trim())throw new Error("topic_category is required");if(!["success","failure","partial"].includes(d))throw new Error("outcome must be success, failure, or partial");const e=re({topic_category:c.trim()},"die Commons");if(!e.ok)return e.meldung;const i=e.felder.topic_category,f=s>=.75?"high":s>=.5?"medium":"low";let r="\u{1F4E6} Signal stored locally (commons API unavailable)";try{await E("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:i.toLowerCase(),outcome:d,confidence:s})}),r="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const u=await A(w),l=`cachly:fed:outbox:${Date.now()}`;await u.set(l,JSON.stringify({topic_category:i,outcome:d,bucket:f,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${i}\`**`,"",`\u{1F4CA} Outcome: **${d}** \xB7 Confidence bucket: **${f}**`,"\u{1F6E1}\uFE0F Privacy: topic category only \u2014 no lesson text, no org identity","",r,...e.geschwaerzt.length?[ce(e.geschwaerzt)]:[],"","\u{1F4A1} When \u2265 k orgs contribute the same pattern, a meta-lesson appears in `brain_import_meta`."].join(`
36
+ `)}case"brain_import_meta":{const{instance_id:w,category:c,limit:d=20}=N;let s=[],e=3;try{const a=new URLSearchParams;c&&a.set("category",c),a.set("limit",String(Math.min(d,200)));const t=await E(`/api/v1/federation/meta?${a.toString()}`);s=t.meta_lessons??[],e=t.k_threshold??3}catch{return"\u274C Could not reach the global commons API. Try again later."}if(s.length===0)return["\u{1F310} **Brain Import Meta-Lessons**","",`No meta-lessons available yet (k-threshold: ${e} signals required).`,"","\u{1F4A1} Contribute signals with `brain_contribute_signal` to help build the commons."].join(`
37
+ `);let i=0;const f=new Set;s=s.map(a=>{const t=G({topic_category:a.topic_category,dominant_outcome:a.dominant_outcome});return t.geschwaerzt.length&&i++,t.verdacht.length&&f.add(t.felder.topic_category),{...a,...t.felder}});const r=await A(w);let u=0;for(const a of s){const t=`cachly:lesson:best:meta:${a.topic_category}`;await r.get(t)||(await r.set(t,JSON.stringify({topic:`meta:${a.topic_category}`,outcome:a.dominant_outcome,what_worked:a.contributor_count!=null?`Meta-pattern from ${a.contributor_count} independent orgs`:`Meta-pattern from ${a.signal_count} signals`,what_failed:"",recall_count:0,ts:a.derived_at,state:"meta",...f.has(a.topic_category)?{tags:[Le]}:{},avg_confidence:a.avg_confidence,signal_count:a.signal_count,audit_trail:[{ts:new Date().toISOString(),action:"imported_meta"}]})),u++)}const l=[`\u{1F310} **Brain Import Meta-Lessons** (k \u2265 ${e})`,"","| Topic Category | Outcome | Confidence | Signals |","|---|---|---|---|"];for(const a of s.slice(0,15)){const t=(a.avg_confidence*100).toFixed(0)+"%";l.push(`| \`${a.topic_category}\` | ${a.dominant_outcome} | ${t} | ${a.signal_count} |`)}return s.length>15&&l.push(`| _\u2026${s.length-15} more_ | | | |`),l.push("",`\u2705 **${u}** new meta-lessons imported into local Brain.`),u<s.length&&l.push(`_(${s.length-u} already present \u2014 not overwritten)_`),l.push(...H(i,f.size,`${s.length} Kategorienamen`)),l.join(`
38
+ `)}case"brain_watch":{const{instance_id:w="",project_dir:c=".",api_key:d}=N,{resolve:s}=await import("node:path"),e=s(c),{result:i,hookPath:f,alterBlockEntfernt:r}=await Ce(e,w);return i==="skipped-no-git"?["\u26A0\uFE0F **brain_watch: no git repository found**","",`No \`.git\` directory in \`${e}\`.`,"Pass `project_dir` pointing to a git checkout."].join(`
39
+ `):[`\u{1F9E0} **brain_watch ${{written:"\u2705 Hook installed (new)",upgraded:"\u{1F504} Hook upgraded to latest version",appended:"\u{1F4CE} Hook appended to existing post-commit script",unchanged:"\u2713 Hook already up to date \u2014 nothing changed"}[i]??i}**`,"",`Hook path: \`${f}\``,`Instance: \`${w||"(none \u2014 set CACHLY_BRAIN_INSTANCE_ID or pass instance_id)"}\``,...r?["\u{1F9F9} Removed the old brain_watch block from this file (it could hold your key in plain text)."]:[],...d?["\u2139\uFE0F The api_key you passed was not written into the hook."]:[],"","Every future commit will automatically teach your Brain \u2014 the same hook `init` installs.","It reads your key when it runs: `$CACHLY_JWT` or `~/.cachly/credentials.json`. No key is stored in the project.","",'\u{1F4A1} Verify: `git commit --allow-empty -m "test brain_watch"` then `smart_recall(query="test")`'].join(`
40
40
  `)}default:return null}}export{Qe as FEDBRAIN_TOOL_NAMES,Te as _lastBrainFromCiCounts,De as _lastBrainFromGitCounts,Xe as handleFedbrainTool};
package/dist/src/tools.js CHANGED
@@ -7,4 +7,4 @@ Layer 3 \u2014 Autopilot: generates a copilot-instructions.md / .github/copilot-
7
7
  and save lessons AFTER \u2014 fully automatic, zero manual effort.
8
8
 
9
9
  Returns the copilot-instructions.md content + provider-specific .mcp.json snippet.
10
- Optionally writes copilot-instructions.md directly to the project directory.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cachly instance to use as the AI brain"},project_dir:{type:"string",description:"Absolute path to the project root. If provided, puts the cachly block into .github/copilot-instructions.md (and CLAUDE.md, .cursor/rules/cachly.mdc, .windsurfrules when that editor is in use). Text outside the cachly markers is kept."},embed_provider:{type:"string",enum:["openai","mistral","cohere","ollama","gemini"],description:"Embedding provider to use for smart_recall / semantic search. Default: openai. Use ollama for fully local/free setup."},project_description:{type:"string",description:"Short description of the project (used in the generated instructions)"}},required:[]}},{name:"cache_stream_set",description:"Cache a list of string chunks (e.g. LLM token stream) via Redis RPUSH. Each chunk is stored as a separate list element under cachly:stream:{key}. Replay with cache_stream_get.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Cache key"},chunks:{type:"array",items:{type:"string"},description:"Ordered list of string chunks"},ttl:{type:"number",description:"TTL in seconds for the stored list (optional)"}},required:["key","chunks"]}},{name:"cache_stream_get",description:"Retrieve a previously cached stream as an ordered list of string chunks. Returns null on cache miss (key absent or empty list). Stored under cachly:stream:{key}.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Cache key"}},required:["key"]}},{name:"cache_org_stats",description:"Show shared cache statistics for an org namespace. Scans all keys under org:{org_id}:sem:* and reports how many entries are shared. Use this to verify org-sharing is working and to monitor cross-instance cache utilization. Also aggregates org-wide ROI via the Cachly API: total cache hits, hits in the last 24h, estimated total and projected monthly USD savings across all org instances, plus a per-instance breakdown. Zero-config: no API changes required \u2014 any cache_set call with org_id writes to this namespace.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},org_id:{type:"string",description:'Org ID to inspect (e.g. "acme", "my-company")'}},required:["org_id"]}},{name:"set_cost_per_call",description:"Set the assumed cost per avoided LLM API call (USD) for this instance. This is used to compute accurate ROI savings estimates in cache_stats. The default ($0.002) is calibrated for a small model (gpt-5.5-mini class). Set your actual model cost for accurate numbers: claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001. After updating, cache_stats will show savings computed from your real cost. Use list_instances to find your instance_id.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},cost_per_call_usd:{type:"number",description:"Cost per LLM API call in USD. Common values: 0.02 (claude-opus-4.8), 0.015 (gpt-5.5), 0.009 (claude-sonnet-4.6), 0.002 (gpt-5.5-mini), 0.001 (claude-haiku-4.5)."}},required:["cost_per_call_usd"]}},{name:"memory_consolidate",description:"Cognitive memory consolidation \u2014 the weekly garbage collector for your AI Brain. Scans all lessons, detects contradictions (same topic with conflicting outcomes), names possible duplicates by meaning (same content under a different topic, cosine \u2265 0.80), flags stale entries (not recalled in 90+ days), and computes a health score. Never merges or deletes a lesson; link two with `ersetzt` on learn_from_attempts. Run weekly or when brain_doctor reports > 20 lessons. Like git gc for knowledge.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dry_run:{type:"boolean",description:"If true, report what would change without writing (default: false)"},stale_days:{type:"number",description:"Lessons not recalled in this many days are flagged stale (default: 90)"}},required:[]}},{name:"brain_diff",description:'git log for your AI Brain \u2014 see exactly what changed since a point in time. Returns a structured changelog: new lessons added, lessons updated (outcome changed), lessons recalled (hit count increased), and lessons that decayed. Perfect for weekly reviews: "What did my AI learn this week?" Example: brain_diff(instance_id="...", since="7d") \u2192 "12 new \xB7 4 updated \xB7 2 stale"',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},since:{type:"string",description:'Time window: "1d", "7d", "30d", or ISO-8601 date (default: "7d")'},format:{type:"string",enum:["summary","detailed"],description:"Output format (default: summary)"}},required:[]}},{name:"causal_trace",description:'Root Cause Analysis through memory: given a problem description, traces the causal chain from root cause through intermediate failures to the current symptom, then surfaces the exact solution that worked before. Read-only \u2014 does not modify any stored data. Requires prior learning: brain must have lessons stored via learn_from_attempts or brain_from_git. Returns an ordered chain of concepts with confidence scores plus the matching solution; returns an empty chain with a message if no causal path is found. Example: causal_trace(problem="auth breaks after restart") \u2192 "Root: k8s:namespace-terminating \u2192 keycloak:jwks-race \u2192 Solution: PollUntilContextTimeout 3min". Use recall_best_solution for direct topic lookup, syndicate_search for community patterns, and causal_trace when you have a symptom and need the full root-cause chain.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},problem:{type:"string",description:"Describe the problem or error you are seeing right now"},max_depth:{type:"number",description:"Max causal chain depth to trace (default: 5)"},tags:{type:"array",items:{type:"string"},description:"Optional: narrow search to these tags"}},required:["problem"]}},{name:"knowledge_decay",description:'Confidence scoring for every lesson in your Brain \u2014 because old knowledge rots. Computes a decay score (0\u2013100%) per lesson based on age, recall frequency, and outcome. Lessons recalled recently score high. Lessons from 90 days ago never recalled score low. Returns a ranked list with visual confidence bars: "\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591 40%". Use this before a big refactor to know which lessons to trust and which to re-validate.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_age_days:{type:"number",description:"Only include lessons older than N days (default: 0 = all)"},show_top:{type:"number",description:"Number of entries to return, sorted by lowest confidence first (default: 20)"}},required:[]}},{name:"autopilot",description:'Generate a CLAUDE.md / copilot-instructions.md that makes any AI self-managing forever. Writes a configuration file to disk \u2014 will overwrite an existing file at the target path. No auth required beyond a valid instance_id. The generated file instructs Claude, Cursor, Copilot, Windsurf, or Gemini to automatically call session_start at window open, learn_from_attempts after every fix, and session_end before closing \u2014 without being asked. Returns the generated file content as a string and the path where it was written. Use style="minimal" for just the three hooks; style="full" for the complete ruleset with examples. One command. Every AI. Always on. Use setup_ai_memory instead if you want an interactive one-shot setup that also creates an instance.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},editor:{type:"string",enum:["claude","cursor","copilot","windsurf","gemini","continue","all"],description:"Target editor (default: claude)"},project_name:{type:"string",description:"Your project name (used in generated instructions)"},style:{type:"string",enum:["minimal","full"],description:"minimal = just the hooks, full = full ruleset with examples (default: full)"}},required:[]}},{name:"syndicate",description:'Contribute a verified lesson to the GLOBAL Cachly Knowledge Commons \u2014 a privacy-preserving shared brain where every AI instance can learn from the discoveries of every other. Your contributor identity is a one-way HMAC hash: completely anonymous. The lesson is immediately searchable by any other AI using syndicate_search. This is how individual knowledge becomes collective intelligence. Call this AFTER every learn_from_attempts that is worth sharing universally (critical bugs, deployment gotchas, architecture discoveries). If a lesson with the same topic already exists in the commons, it is updated in place (idempotent). Returns { key, confirm_count, scope } confirming the stored lesson. Use scope="org" to keep the lesson private to your organisation. Do NOT use for secrets or PII \u2014 content is stored in a shared knowledge base.',inputSchema:{type:"object",properties:{topic:{type:"string",description:'Topic key in category:keyword format (e.g. "fix:clickhouse-ipv6", "deploy:docker-compose")'},outcome:{type:"string",enum:["success","failure","partial"],description:"Result of the attempt (default: success)"},what_worked:{type:"string",description:"Exact approach, command, or fix that worked. File paths are stripped automatically."},what_failed:{type:"string",description:"What failed or was wrong \u2014 helps others avoid the same trap."},severity:{type:"string",enum:["critical","major","minor"],description:"How severe the issue was (default: minor)"},tags:{type:"array",items:{type:"string"},description:"Up to 10 keywords for better discoverability"},scope:{type:"string",enum:["public","org"],description:'Visibility: "public" = global commons (default), "org" = private to your org only'}},required:["topic","what_worked"]}},{name:"syndicate_search",description:'Search the GLOBAL Cachly Knowledge Commons for solutions contributed by the entire community. Returns lessons ranked by confirm_count (trust score) then recency. Use this BEFORE debugging any unknown issue \u2014 someone in the global brain likely solved it already. Example: syndicate_search(q="clickhouse localhost connection refused") \u2192 "fix: use 127.0.0.1 not localhost when IPv6 is disabled \xB7 confirmed by 47 instances"',inputSchema:{type:"object",properties:{q:{type:"string",description:"Free-text search query (leave empty for most recent lessons)"},category:{type:"string",description:'Filter by category prefix: "fix", "deploy", "debug", "infra", "api", "web"'},scope:{type:"string",enum:["public","org"],description:'"public" = global commons (default), "org" = public + your org-private lessons'},limit:{type:"number",description:"Max results to return (default: 20, max: 50)"}},required:[]}},{name:"syndicate_stats",description:"Show the health of the global Knowledge Commons: total lessons, total confirms, top categories, most-trusted lessons, growth in the last 7 days, and top contributors (anonymous scores). Use for weekly reviews or to explore what the community knows.",inputSchema:{type:"object",properties:{},required:[]}},{name:"syndicate_trending",description:"Show the TRENDING lessons in the global Knowledge Commons \u2014 those with the fastest confirmation velocity in the last 7 days (confirm_count / age_in_days). Use this at the start of a session or weekly review to see what the community is actively validating. Lessons need at least 2 independent confirms to appear here.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max results (default: 10, max: 50)"}},required:[]}},{name:"brain_marketplace",description:'Browse the Domain Brain marketplace \u2014 curated, installable packs of high-trust community lessons, grouped by domain (Kubernetes, Auth, Database, React, Payments, \u2026). Each brain is built from verified, community-confirmed lessons in the global Knowledge Commons. Use at onboarding or when starting work in an unfamiliar domain to bootstrap your Brain instantly. Install one with brain_install(slug="..."). Example: brain_marketplace() \u2192 "\u2638\uFE0F Kubernetes Incident Brain \xB7 42 lessons \xB7 install: brain_install(slug=\\"k8s\\")".',inputSchema:{type:"object",properties:{min_confirms:{type:"number",description:"Only count lessons with at least this many community confirmations (default: 1)"}},required:[]}},{name:"brain_install",description:'Install a Domain Brain into your local Brain \u2014 pulls its curated, high-trust lessons so they surface in smart_recall immediately, even offline. Idempotent and non-destructive: it NEVER overrides your own lessons (only prior installs of the same brain). Re-run anytime to pull updates. Browse available brains first with brain_marketplace(). Example: brain_install(slug="k8s") \u2192 "\u{1F4E6} Installed: Kubernetes Incident Brain \xB7 42 lessons merged".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},slug:{type:"string",description:'Domain brain slug from brain_marketplace (e.g. "k8s", "auth", "db")'},min_confirms:{type:"number",description:"Only install lessons with at least this many community confirmations (default: 1)"},limit:{type:"number",description:"Max lessons to install (default: 200, max: 500)"},dry_run:{type:"boolean",description:"Preview what would be installed without writing anything (default: false)"}},required:["slug"]}},{name:"brain_search",description:"BM25+ full-text search over ALL brain data: lessons, context entries, session history, CKG nodes, roadmap items. Unlike smart_recall (which focuses on lessons + context), brain_search casts a wider net. Use when smart_recall returns nothing or when you want to find anything the brain knows about a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},query:{type:"string",description:"What to search for"},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"ckg_inspect",description:"Inspect the Causal Knowledge Graph (CKG) for a concept. Shows all typed edges (fixes, requires, co-occurs, causes) with Bayesian confidence scores. Use to understand what the brain knows about a topic and which fixes have the highest confidence. Also shows related concepts via graph traversal.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},concept:{type:"string",description:'Concept to inspect, e.g. "fix:clickhouse-ipv6" or "docker"'},max_hops:{type:"number",description:"Traversal depth (default: 2)"}},required:["concept"]}},{name:"brain_predict",description:'READ-ONLY \u2014 no side effects, no writes, no external network calls. Predictive Pre-fetch Engine (PPE): given your current context, reads the CKG in your Redis instance to predict likely failures and return the highest-confidence fixes. "Pre-load" means results are returned inline \u2014 nothing is cached or persisted. Requires a valid instance_id (your Redis brain). No rate limits. Call at session start when working on a specific feature or debugging area. Set scope="org" to widen prediction across your whole organisation \u2014 surfaces cross-team risks ("failed 3\xD7 across 2 other teams") from the Org Knowledge Graph, so an incident in one team becomes a vaccine for yours.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},context:{type:"string",description:`What you're working on, e.g. "upgrading Keycloak from 21 to 24"`},top_k:{type:"number",description:"Max predictions to return (default: 5)"},scope:{type:"string",enum:["instance","org","org+commons"],description:'Scope: "instance" (default) = this brain, "org" = warnings from failures in other teams of your organisation, "org+commons" = plus public lessons. Falls back to "instance" without an org.'}},required:["context"]}},{name:"brain_plan",description:'READ-ONLY \u2014 no side effects, no writes, no external network calls. Generative planning layer on top of the CKG: given a task you are ABOUT to do (e.g. "upgrade Postgres 14\u219216", "add Stripe webhooks"), returns an ordered action plan grounded in your own proven lessons \u2014 the failure modes most likely to bite (ranked by confidence), the concrete steps that fixed them before (with commands), and a pre-flight checklist. Where brain_predict answers "what might fail?", brain_plan answers "what should I do, in what order?". Requires a valid instance_id (your Redis brain). Call before starting non-trivial work.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},task:{type:"string",description:'The change you are about to make, e.g. "migrate auth from sessions to JWT"'},top_k:{type:"number",description:"Max items per section (default: 5)"}},required:["task"]}},{name:"brain_conflicts",description:"READ-ONLY \u2014 list every unresolved belief_conflict (a previously confirmed fix now contradicted by a failure) plus the agents currently writing to this Brain (last 1h). This is the arbitration inbox for multi-agent teams: when several AI sessions share one Brain, contradictory writes surface here instead of silently overwriting each other. Resolve any listed conflict with brain_resolve_conflict.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"}},required:[]}},{name:"brain_resolve_conflict",description:'Arbitrate a contested topic by picking the winning side. winner="success" reaffirms the fix (the contradicting failure stops blocking recall); winner="failure" retires the fix (its CKG fixes-edges decay to ~0 and the losing lesson is archived). Human-in-the-loop resolution is the strongest possible confidence signal. List open conflicts first with brain_conflicts.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic:{type:"string",description:'The contested topic, e.g. "fix:jwks-rotation"'},winner:{type:"string",enum:["success","failure"],description:"Which side wins the arbitration"},resolved_by:{type:"string",description:'Who resolved it (agent name or "human"); default "human"'}},required:["topic","winner"]}},{name:"brain_confirm_ci",description:"Close the CI feedback loop: tell the Brain whether a CI job passed or failed and which topics it covered. The Brain adjusts lesson confidence automatically \u2014 confirmed failures get +15%, false positives (brain predicted failure but CI passed) get \u221210%. Called automatically by cachly-action at the end of every pipeline. Also use manually after a deploy to confirm or refute the brain's last prediction.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},job_status:{type:"string",enum:["success","failure","cancelled"],description:"Outcome of the CI job"},topics:{type:"array",items:{type:"string"},description:'Topics touched by this CI run (e.g. ["auth:jwt", "deploy:k8s"])'},scan_topics:{type:"array",items:{type:"string"},description:"Topics the brain predicted would fail (from the scan response). Used to detect false positives."},source:{type:"string",description:'Optional: "github_actions", "gitlab_ci", etc.'}},required:["job_status","topics"]}},{name:"brain_briefing",description:"Push-based Brain warning: instead of waiting for you to ask, the Brain proactively checks whether the file you just opened, the PR you are about to raise, or the deploy you are about to run matches any known failure pattern \u2014 and surfaces warnings BEFORE something breaks. Call this on file_open (with the file path as context), pr_open (with the PR title/body), or deploy (with a short description of what is being deployed). Returns a risk_level (low/medium/high) plus up to 5 ranked warnings with confidence and a known fix.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},event_type:{type:"string",enum:["file_open","pr_open","deploy","manual"],description:"What triggered this briefing \u2014 determines how the context is interpreted"},context:{type:"string",description:"The event context: file path for file_open, title+body for pr_open, short description for deploy/manual"},threshold:{type:"number",description:"Minimum confidence (0\u20131) for a warning to be surfaced. Default 0.6 \u2014 raise it to reduce noise."}},required:["event_type","context"]}},{name:"brain_contribute_signal",description:"Contribute a privacy-safe signal to the global Brain commons. Only the topic category, outcome, and confidence bucket (high/medium/low) are shared \u2014 no lesson text, no org identity. When \u2265 k independent orgs contribute the same pattern, a meta-lesson is derived in the commons. Use this instead of fedbrain_contribute when privacy is required (enterprise, GDPR).",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic_category:{type:"string",description:'Normalised topic, e.g. "auth:jwt" or "deploy:k8s"'},outcome:{type:"string",enum:["success","failure","partial"],description:"Outcome of the pattern"},confidence:{type:"number",description:"Confidence 0\u20131 (bucketed before sending; default 0.5)"}},required:["topic_category","outcome"]}},{name:"brain_import_meta",description:'Import k-anonymous meta-lessons from the global Brain commons into your local Brain. Meta-lessons are derived from \u2265 k independent org signals \u2014 no individual org data is revealed. Imported lessons get state="meta" and never overwrite your own lessons. Filter by category to target relevant patterns.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},category:{type:"string",description:'Optional filter, e.g. "auth" or "deploy"'},limit:{type:"number",description:"Max meta-lessons to import (default 20, max 200)"}},required:[]}},{name:"madc_deliberate",description:"Multi-Agent Deliberation Chamber (MADC \u2014 Layer 3): When conflicting lessons exist for a topic, run deliberation between 6 specialist expert agents (InfraAgent, AuthAgent, DeployAgent, DatabaseAgent, DebugAgent, APIAgent). Each agent votes based on its domain CKG coverage. Unanimous vote \u2192 loser superseded. Split vote \u2192 contested flag, causal_trace required before acting. Resolution stored as permanent CKG node. Called automatically when learn_from_attempts detects a contradiction.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic:{type:"string",description:'Topic to deliberate, e.g. "fix:jwks-rotation"'},context:{type:"string",description:"Optional context for the deliberation"}},required:["topic"]}},{name:"cls_ingest",description:"Continuous Learning Stream (CLS \u2014 Layer 5): Ingest learning signals WITHOUT explicit session_end calls. Sources: git_commit (commit message + files \u2192 CKG edges), ci_outcome (green/red build \u2192 confirms fix), ide_diagnostic (compiler error + fix pair \u2192 instant lesson). Install automatic ingestion with cls_install_hooks \u2014 brain learns from every commit and CI run.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},source:{type:"string",enum:["git_commit","ci_outcome","ide_diagnostic"],description:"Event source type"},payload:{type:"object",description:"Event data. git_commit: {message, sha?, files?, diff?}. ci_outcome: {status, prev_status, job, context?}. ide_diagnostic: {error, fix, file?}"}},required:["source","payload"]}},{name:"cls_install_hooks",description:"READ-ONLY \u2014 outputs text only, writes no files, makes no network calls, has no side effects. Generates ready-to-paste shell scripts: a git post-commit hook and/or a GitHub Actions step. You must manually copy and install the output. Once the generated scripts are installed, each git commit or CI run will make outbound HTTPS calls to api.cachly.dev to feed learning signals to your brain. No auth required to call this tool \u2014 only an instance_id. Run once per repository.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},repo_path:{type:"string",description:"Path to repo root (default: current dir)"},hooks:{type:"array",items:{type:"string",enum:["git","ci"]},description:'Which hooks to output (default: ["git", "ci"])'}},required:[]}},{name:"fedbrain_contribute",description:"FedBrain (Layer 6): Contribute a lesson to the global Knowledge Commons with a cryptographic knowledge certificate. Certificate includes: domain fingerprint, confidence, outcome chain hash. Lessons with 10+ independent confirmations become Gold Standard. Context-weighted: other brains with similar tech stacks see your lesson ranked higher in fedbrain_search.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},lesson_key:{type:"string",description:'Topic key to contribute, e.g. "fix:clickhouse-ipv6"'},visibility:{type:"string",enum:["public","org_private"],description:"Visibility (default: public)"}},required:["lesson_key"]}},{name:"fedbrain_search",description:"FedBrain context-weighted search: Search the global commons, weighting results by tech-stack similarity. Brains with matching domain context (Go/Kubernetes/Postgres) rank higher than unrelated stacks. Shows certificate provenance, confirm_count, and Gold Standard badges.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},query:{type:"string",description:"What to search for"},context_hints:{type:"array",items:{type:"string"},description:'Your tech stack, e.g. ["go", "kubernetes", "postgres"]'},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}},{name:"fedbrain_confirm",description:"Confirm that a syndicated lesson from the global commons worked for you. Propagates confirmation back \u2014 increments confirm_count on the knowledge certificate. Also updates your local CKG confidence. At 10 independent confirmations \u2192 Gold Standard.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},id:{type:"string",description:"Syndicated lesson id to confirm (shown next to each fedbrain_search result)"},topic:{type:"string",description:"Optional topic of the lesson \u2014 also updates your local CKG confidence for it"},outcome:{type:"string",enum:["worked","partially_worked","did_not_work"],description:"Did the lesson work for you?"}},required:["id","outcome"]}},{name:"fedbrain_status",description:"Show your FedBrain federation status: lessons contributed to global commons, recent confirmations, Gold Standard lessons, pending propagations. Use to track your brain's global knowledge contribution.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"}},required:[]}},{name:"brain_federate",description:`FedBrain Layer 6 \u2014 Private org knowledge transfer: copy CKG edges + lessons from a source brain into your brain for a specific domain (e.g. "billing", "auth", "deploy"). The new hire use case: one command gives you the senior engineer's 5 years of typed, confidence-weighted knowledge in your domain. Unlike syndicate_search (global, anonymous), brain_federate is org-private \u2014 both brains must be in the same Cachly org, or the source instance_id must be explicitly shared. Example: brain_federate(source="prod-brain-id", domain="billing", min_confidence=0.6)`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Your brain instance ID (destination)"},source:{type:"string",description:"Source brain instance ID to federate from"},domain:{type:"string",description:'Domain to transfer, e.g. "billing", "auth", "deploy", "infra". Use "*" for all domains.'},min_confidence:{type:"number",description:"Minimum edge confidence to transfer (default: 0.6)"},dry_run:{type:"boolean",description:"Preview what would be transferred without writing (default: false)"}},required:["source","domain"]}},{name:"crystal_view",description:"Inspect the current Memory Crystal \u2014 the compressed wisdom distilled from all past sessions. Shows top patterns per category, lesson count, and when the crystal was last refreshed. Call after session_start when you want to quickly see accumulated wisdom across all past work.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},show_raw:{type:"boolean",description:"Include raw JSON crystal data (default: false)"}},required:[]}},{name:"compact_recover",description:"Call FIRST after any context limit hit / compaction. Reconstructs full context from Memory Crystal + recent sessions + WIP registry + open failures. Returns a condensed briefing so the new context window starts exactly where the previous one left off \u2014 no lost progress.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},focus:{type:"string",description:"What you were working on (helps filter relevant context)"}},required:[]}},{name:"brain_from_git",description:"Bootstrap brain lessons from git history. Parses commit messages and infers fix/feature/refactor lessons automatically. Great for onboarding an existing codebase \u2014 run once and the brain instantly knows your team's accumulated patterns. Incremental by default: only processes new commits since the last run, so repeated calls are fast. Emits progress updates to stderr during long scans.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},repo_path:{type:"string",description:"Path to git repository (default: current directory)"},limit:{type:"number",description:"Max commits to process (default: 100, max: 500)"},branch:{type:"string",description:"Git branch to parse (default: current branch / HEAD)"},since:{type:"string",description:'Only commits after this date, e.g. "2024-01-01" (optional)'},incremental:{type:"boolean",description:"Only process commits since last run (default: true). Set false to reprocess all."}},required:[]}},{name:"brain_from_ci",description:"Bulk-ingest CI run outcomes into the Brain \u2014 the brain_from_git equivalent for CI history. Feed it an array of {job, status, prev_status} objects from your CI system and it will learn which jobs have been fixed, broken, or are stable. Use it to bootstrap the Brain from historical CI logs.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},outcomes:{type:"array",description:"List of CI run outcomes to ingest",items:{type:"object",properties:{job:{type:"string",description:'Job name (e.g. "test", "build", "lint")'},status:{type:"string",description:"Current status: success|failure|error"},prev_status:{type:"string",description:"Previous run status (optional, needed to detect transitions)"},context:{type:"string",description:"Optional: error message, branch, commit hash, etc."}},required:["job","status"]}}},required:["outcomes"]}},{name:"brain_watch",description:"Install an ambient git post-commit hook that automatically learns from every commit \u2014 no manual brain_from_git needed. After installation every `git commit` silently POSTs the commit message, SHA, and changed files to the cachly Brain API in the background. Idempotent: running brain_watch twice installs the hook only once. Uses curl (not Node/npx) so it works in any environment. The hook always exits 0 and runs asynchronously \u2014 it never blocks a commit. Returns the hook path and installation status (written/upgraded/appended/unchanged/skipped-no-git).",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID to learn into"},project_dir:{type:"string",description:'Path to the git repository (default: current directory ".")'},api_key:{type:"string",description:"Optional cachly API key (cky_\u2026) to embed in the hook for authentication"}},required:[]}},{name:"brain_predict_failures",description:'Pre-deploy failure prediction with probability percentages. Given a change context (e.g. "upgrading Keycloak 21\u219224" or "deploying Redis 7 to prod"), returns the top likely failure modes ranked by probability, with pre-loaded fixes. Uses CKG causal edges + lesson history. Call before any significant deploy, migration, or infrastructure change.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},context:{type:"string",description:'What you are about to do, e.g. "upgrading Keycloak 21 to 24"'},top_k:{type:"number",description:"Number of failure predictions to return (default: 5)"},format:{type:"string",enum:["brief","detailed"],description:"Output format (default: detailed)"}},required:["context"]}},{name:"brain_share",description:'Export a Brain snapshot and create a publicly shareable link that anyone can import. Optionally filter by topic prefix (e.g. only "auth:" or "deploy:" lessons). Visibility can be "public" (discoverable) or "unlisted" (link-only). Returns a share URL and the import command to give to teammates or the community. Example: brain_share(instance_id="...", title="My Auth Patterns", topic_filter=["auth"])',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to export from."},title:{type:"string",description:'Human-readable title for the shared Brain snapshot. Default: "My Brain Snapshot".'},description:{type:"string",description:"Short description of what knowledge this Brain contains."},topic_filter:{type:"array",items:{type:"string"},description:"Only export lessons whose topic contains one of these strings. Omit to export all lessons."},visibility:{type:"string",enum:["public","unlisted"],description:'"public" = discoverable in the Brain marketplace. "unlisted" = only accessible by direct link. Default: unlisted.'},max_lessons:{type:"number",description:"Maximum number of lessons to include (default 100, max 500)."},dry_run:{type:"boolean",description:"If true, preview what would be shared without creating the public link."}},required:[]}},{name:"brain_import",description:'Import lessons from a publicly shared Brain snapshot into your own Brain instance. Accepts a share ID (UUID) or the full share URL from brain_share. Optionally prefix all imported topics to avoid naming collisions (e.g. topic_prefix="team"). Existing lessons are NOT overwritten by default \u2014 pass overwrite=true to replace them. Example: brain_import(instance_id="...", share_id="abc123", topic_prefix="imported")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to import lessons into."},share_id:{type:"string",description:"Share ID (UUID) or full share URL from brain_share."},topic_prefix:{type:"string",description:'Optional prefix to prepend to all imported topic names (e.g. "team" \u2192 "team:auth:jwt-expiry"). Prevents collisions with your own lessons.'},min_confidence:{type:"number",description:"Skip lessons below this confidence threshold (0.0\u20131.0). Default: 0 (import all)."},overwrite:{type:"boolean",description:"Replace existing lessons with the same topic. Default false."},dry_run:{type:"boolean",description:"Preview what would be imported without writing to the Brain."}},required:["share_id"]}},{name:"brain_share_list",description:'List all Brain snapshots you have previously shared with brain_share. Shows share ID, title, lesson count, visibility, and creation date for each share. Checks the local provenance log and the cachly API. Example: brain_share_list(instance_id="...")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance that created the shares."}},required:[]}},{name:"brain_unshare",description:'Revoke and permanently delete a public Brain share by its share ID. After calling this, the share URL becomes invalid and no one can import it. Note: users who already imported the Brain keep their local copy. Example: brain_unshare(instance_id="...", share_id="abc123")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance that owns the share."},share_id:{type:"string",description:"Share ID to revoke (from brain_share or brain_share_list)."}},required:["share_id"]}},{name:"brain_discover",description:'Search and browse publicly shared Brain snapshots in the cachly marketplace. Find ready-made knowledge bases on specific topics (TypeScript, Docker, auth, CI/CD, etc.) created and shared by the community. Returns a ranked list with lesson counts, topics, and import commands. Example: brain_discover(query="kubernetes deployment") \xB7 brain_discover(topic="auth")',inputSchema:{type:"object",properties:{query:{type:"string",description:"Full-text search query across Brain titles and descriptions."},topic:{type:"string",description:'Filter by topic prefix (e.g. "auth", "docker", "nextjs").'},limit:{type:"number",description:"Max number of results to return (default 10, max 50)."}},required:[]}},{name:"brain_seed_starter",description:`Seed a fresh Brain with a curated set of universal, high-value engineering lessons (Docker layer cache, JWT clock skew, Postgres migration locks, K8s OOM limits, N+1 queries, cache stampede, CORS preflight, and more). Makes the very first smart_recall return a useful hit instead of nothing \u2014 ideal right after setup or in a fresh repo with no git history to learn from. Starter lessons are tagged source:"starter", never override your own lessons, and are idempotent (won't double-seed). Example: brain_seed_starter(instance_id="...") \xB7 brain_seed_starter(instance_id="...", topic_filter=["docker","redis"])`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to seed."},topic_filter:{type:"array",items:{type:"string"},description:'Only seed lessons whose topic or tags match one of these strings (e.g. ["docker", "auth"]). Omit to seed all.'},force:{type:"boolean",description:"Re-seed even if already seeded; also overwrites same-topic lessons. Default false."},dry_run:{type:"boolean",description:"Preview which starter lessons would be seeded without writing."}},required:[]}},{name:"brain_graph",description:'Export the Causal Knowledge Graph as a 3D-render-ready node/link payload (schema cachly.brain_graph/v1) \u2014 the data layer behind the brain viz: the visual, explorable 3D map of every concept, person, file and service the brain knows, and how they causally relate. Node kinds (concept/person/file/service) carry stable color groups and a size (val) scaled by reference count; links carry edgeType (fixes/causes/co-occurs/authored/collaborates) and confidence (value). Consumed verbatim by react-force-graph-3d / three.js frontends. Example: brain_graph(instance_id="...") \xB7 brain_graph(instance_id="...", domain="auth", min_confidence=0.5, format="summary")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to export."},max_nodes:{type:"number",description:"Cap on nodes returned (default 400, max 2000). Edges to dropped nodes are pruned."},domain:{type:"string",description:'Only include nodes whose domain or id contains this string (e.g. "auth", "docker"). Omit for the whole graph.'},min_confidence:{type:"number",description:"Drop edges below this confidence 0..1 (default 0 = keep all)."},format:{type:"string",enum:["json","summary"],description:'"json" (default) emits the full renderable payload; "summary" emits a human-readable overview.'}},required:[]}},{name:"brain_set_pref",description:'Persist a user preference for this Brain instance. Preferences are stored in Redis and survive restarts. Known keys: `auto_changelog` (set to "false" to disable the automatic changelog shown at session_start).',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (Brain ID)."},key:{type:"string",description:'Preference key (e.g. "auto_changelog").'},value:{type:"string",description:'Value to set (e.g. "false" to disable, "true" to re-enable).'}},required:["key","value"]}},{name:"brain_get_pref",description:"Read back one or all preferences stored for this Brain instance. Call with a `key` to get a single value, or omit `key` to list every preference that has been set. Returns a default note when a key has never been set. Complement to `brain_set_pref`.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance."},key:{type:"string",description:"Preference key to read. Omit to list all preferences."}},required:[]}}];export{e as TOOLS};
10
+ Optionally writes copilot-instructions.md directly to the project directory.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cachly instance to use as the AI brain"},project_dir:{type:"string",description:"Absolute path to the project root. If provided, puts the cachly block into .github/copilot-instructions.md (and CLAUDE.md, .cursor/rules/cachly.mdc, .windsurfrules when that editor is in use). Text outside the cachly markers is kept."},embed_provider:{type:"string",enum:["openai","mistral","cohere","ollama","gemini"],description:"Embedding provider to use for smart_recall / semantic search. Default: openai. Use ollama for fully local/free setup."},project_description:{type:"string",description:"Short description of the project (used in the generated instructions)"}},required:[]}},{name:"cache_stream_set",description:"Cache a list of string chunks (e.g. LLM token stream) via Redis RPUSH. Each chunk is stored as a separate list element under cachly:stream:{key}. Replay with cache_stream_get.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Cache key"},chunks:{type:"array",items:{type:"string"},description:"Ordered list of string chunks"},ttl:{type:"number",description:"TTL in seconds for the stored list (optional)"}},required:["key","chunks"]}},{name:"cache_stream_get",description:"Retrieve a previously cached stream as an ordered list of string chunks. Returns null on cache miss (key absent or empty list). Stored under cachly:stream:{key}.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Cache key"}},required:["key"]}},{name:"cache_org_stats",description:"Show shared cache statistics for an org namespace. Scans all keys under org:{org_id}:sem:* and reports how many entries are shared. Use this to verify org-sharing is working and to monitor cross-instance cache utilization. Also aggregates org-wide ROI via the Cachly API: total cache hits, hits in the last 24h, estimated total and projected monthly USD savings across all org instances, plus a per-instance breakdown. Zero-config: no API changes required \u2014 any cache_set call with org_id writes to this namespace.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},org_id:{type:"string",description:'Org ID to inspect (e.g. "acme", "my-company")'}},required:["org_id"]}},{name:"set_cost_per_call",description:"Set the assumed cost per avoided LLM API call (USD) for this instance. This is used to compute accurate ROI savings estimates in cache_stats. The default ($0.002) is calibrated for a small model (gpt-5.5-mini class). Set your actual model cost for accurate numbers: claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001. After updating, cache_stats will show savings computed from your real cost. Use list_instances to find your instance_id.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},cost_per_call_usd:{type:"number",description:"Cost per LLM API call in USD. Common values: 0.02 (claude-opus-4.8), 0.015 (gpt-5.5), 0.009 (claude-sonnet-4.6), 0.002 (gpt-5.5-mini), 0.001 (claude-haiku-4.5)."}},required:["cost_per_call_usd"]}},{name:"memory_consolidate",description:"Cognitive memory consolidation \u2014 the weekly garbage collector for your AI Brain. Scans all lessons, detects contradictions (same topic with conflicting outcomes), names possible duplicates by meaning (same content under a different topic, cosine \u2265 0.80), flags stale entries (not recalled in 90+ days), and computes a health score. Never merges or deletes a lesson; link two with `ersetzt` on learn_from_attempts. Run weekly or when brain_doctor reports > 20 lessons. Like git gc for knowledge.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dry_run:{type:"boolean",description:"If true, report what would change without writing (default: false)"},stale_days:{type:"number",description:"Lessons not recalled in this many days are flagged stale (default: 90)"}},required:[]}},{name:"brain_diff",description:'git log for your AI Brain \u2014 see exactly what changed since a point in time. Returns a structured changelog: new lessons added, lessons updated (outcome changed), lessons recalled (hit count increased), and lessons that decayed. Perfect for weekly reviews: "What did my AI learn this week?" Example: brain_diff(instance_id="...", since="7d") \u2192 "12 new \xB7 4 updated \xB7 2 stale"',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},since:{type:"string",description:'Time window: "1d", "7d", "30d", or ISO-8601 date (default: "7d")'},format:{type:"string",enum:["summary","detailed"],description:"Output format (default: summary)"}},required:[]}},{name:"causal_trace",description:'Root Cause Analysis through memory: given a problem description, traces the causal chain from root cause through intermediate failures to the current symptom, then surfaces the exact solution that worked before. Read-only \u2014 does not modify any stored data. Requires prior learning: brain must have lessons stored via learn_from_attempts or brain_from_git. Returns an ordered chain of concepts with confidence scores plus the matching solution; returns an empty chain with a message if no causal path is found. Example: causal_trace(problem="auth breaks after restart") \u2192 "Root: k8s:namespace-terminating \u2192 keycloak:jwks-race \u2192 Solution: PollUntilContextTimeout 3min". Use recall_best_solution for direct topic lookup, syndicate_search for community patterns, and causal_trace when you have a symptom and need the full root-cause chain.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},problem:{type:"string",description:"Describe the problem or error you are seeing right now"},max_depth:{type:"number",description:"Max causal chain depth to trace (default: 5)"},tags:{type:"array",items:{type:"string"},description:"Optional: narrow search to these tags"}},required:["problem"]}},{name:"knowledge_decay",description:'Confidence scoring for every lesson in your Brain \u2014 because old knowledge rots. Computes a decay score (0\u2013100%) per lesson based on age, recall frequency, and outcome. Lessons recalled recently score high. Lessons from 90 days ago never recalled score low. Returns a ranked list with visual confidence bars: "\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591 40%". Use this before a big refactor to know which lessons to trust and which to re-validate.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_age_days:{type:"number",description:"Only include lessons older than N days (default: 0 = all)"},show_top:{type:"number",description:"Number of entries to return, sorted by lowest confidence first (default: 20)"}},required:[]}},{name:"autopilot",description:'Generate a CLAUDE.md / copilot-instructions.md that makes any AI self-managing forever. Writes a configuration file to disk \u2014 will overwrite an existing file at the target path. No auth required beyond a valid instance_id. The generated file instructs Claude, Cursor, Copilot, Windsurf, or Gemini to automatically call session_start at window open, learn_from_attempts after every fix, and session_end before closing \u2014 without being asked. Returns the generated file content as a string and the path where it was written. Use style="minimal" for just the three hooks; style="full" for the complete ruleset with examples. One command. Every AI. Always on. Use setup_ai_memory instead if you want an interactive one-shot setup that also creates an instance.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},editor:{type:"string",enum:["claude","cursor","copilot","windsurf","gemini","continue","all"],description:"Target editor (default: claude)"},project_name:{type:"string",description:"Your project name (used in generated instructions)"},style:{type:"string",enum:["minimal","full"],description:"minimal = just the hooks, full = full ruleset with examples (default: full)"}},required:[]}},{name:"syndicate",description:'Contribute a verified lesson to the GLOBAL Cachly Knowledge Commons \u2014 a privacy-preserving shared brain where every AI instance can learn from the discoveries of every other. Your contributor identity is a one-way HMAC hash: completely anonymous. The lesson is immediately searchable by any other AI using syndicate_search. This is how individual knowledge becomes collective intelligence. Call this AFTER every learn_from_attempts that is worth sharing universally (critical bugs, deployment gotchas, architecture discoveries). If a lesson with the same topic already exists in the commons, it is updated in place (idempotent). Returns { key, confirm_count, scope } confirming the stored lesson. Use scope="org" to keep the lesson private to your organisation. Do NOT use for secrets or PII \u2014 content is stored in a shared knowledge base.',inputSchema:{type:"object",properties:{topic:{type:"string",description:'Topic key in category:keyword format (e.g. "fix:clickhouse-ipv6", "deploy:docker-compose")'},outcome:{type:"string",enum:["success","failure","partial"],description:"Result of the attempt (default: success)"},what_worked:{type:"string",description:"Exact approach, command, or fix that worked. File paths are stripped automatically."},what_failed:{type:"string",description:"What failed or was wrong \u2014 helps others avoid the same trap."},severity:{type:"string",enum:["critical","major","minor"],description:"How severe the issue was (default: minor)"},tags:{type:"array",items:{type:"string"},description:"Up to 10 keywords for better discoverability"},scope:{type:"string",enum:["public","org"],description:'Visibility: "public" = global commons (default), "org" = private to your org only'}},required:["topic","what_worked"]}},{name:"syndicate_search",description:'Search the GLOBAL Cachly Knowledge Commons for solutions contributed by the entire community. Returns lessons ranked by confirm_count (trust score) then recency. Use this BEFORE debugging any unknown issue \u2014 someone in the global brain likely solved it already. Example: syndicate_search(q="clickhouse localhost connection refused") \u2192 "fix: use 127.0.0.1 not localhost when IPv6 is disabled \xB7 confirmed by 47 instances"',inputSchema:{type:"object",properties:{q:{type:"string",description:"Free-text search query (leave empty for most recent lessons)"},category:{type:"string",description:'Filter by category prefix: "fix", "deploy", "debug", "infra", "api", "web"'},scope:{type:"string",enum:["public","org"],description:'"public" = global commons (default), "org" = public + your org-private lessons'},limit:{type:"number",description:"Max results to return (default: 20, max: 50)"}},required:[]}},{name:"syndicate_stats",description:"Show the health of the global Knowledge Commons: total lessons, total confirms, top categories, most-trusted lessons, growth in the last 7 days, and top contributors (anonymous scores). Use for weekly reviews or to explore what the community knows.",inputSchema:{type:"object",properties:{},required:[]}},{name:"syndicate_trending",description:"Show the TRENDING lessons in the global Knowledge Commons \u2014 those with the fastest confirmation velocity in the last 7 days (confirm_count / age_in_days). Use this at the start of a session or weekly review to see what the community is actively validating. Lessons need at least 2 independent confirms to appear here.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max results (default: 10, max: 50)"}},required:[]}},{name:"brain_marketplace",description:'Browse the Domain Brain marketplace \u2014 curated, installable packs of high-trust community lessons, grouped by domain (Kubernetes, Auth, Database, React, Payments, \u2026). Each brain is built from verified, community-confirmed lessons in the global Knowledge Commons. Use at onboarding or when starting work in an unfamiliar domain to bootstrap your Brain instantly. Install one with brain_install(slug="..."). Example: brain_marketplace() \u2192 "\u2638\uFE0F Kubernetes Incident Brain \xB7 42 lessons \xB7 install: brain_install(slug=\\"k8s\\")".',inputSchema:{type:"object",properties:{min_confirms:{type:"number",description:"Only count lessons with at least this many community confirmations (default: 1)"}},required:[]}},{name:"brain_install",description:'Install a Domain Brain into your local Brain \u2014 pulls its curated, high-trust lessons so they surface in smart_recall immediately, even offline. Idempotent and non-destructive: it NEVER overrides your own lessons (only prior installs of the same brain). Re-run anytime to pull updates. Browse available brains first with brain_marketplace(). Example: brain_install(slug="k8s") \u2192 "\u{1F4E6} Installed: Kubernetes Incident Brain \xB7 42 lessons merged".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},slug:{type:"string",description:'Domain brain slug from brain_marketplace (e.g. "k8s", "auth", "db")'},min_confirms:{type:"number",description:"Only install lessons with at least this many community confirmations (default: 1)"},limit:{type:"number",description:"Max lessons to install (default: 200, max: 500)"},dry_run:{type:"boolean",description:"Preview what would be installed without writing anything (default: false)"}},required:["slug"]}},{name:"brain_search",description:"BM25+ full-text search over ALL brain data: lessons, context entries, session history, CKG nodes, roadmap items. Unlike smart_recall (which focuses on lessons + context), brain_search casts a wider net. Use when smart_recall returns nothing or when you want to find anything the brain knows about a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},query:{type:"string",description:"What to search for"},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"ckg_inspect",description:"Inspect the Causal Knowledge Graph (CKG) for a concept. Shows all typed edges (fixes, requires, co-occurs, causes) with Bayesian confidence scores. Use to understand what the brain knows about a topic and which fixes have the highest confidence. Also shows related concepts via graph traversal.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},concept:{type:"string",description:'Concept to inspect, e.g. "fix:clickhouse-ipv6" or "docker"'},max_hops:{type:"number",description:"Traversal depth (default: 2)"}},required:["concept"]}},{name:"brain_predict",description:'READ-ONLY \u2014 no side effects, no writes, no external network calls. Predictive Pre-fetch Engine (PPE): given your current context, reads the CKG in your Redis instance to predict likely failures and return the highest-confidence fixes. "Pre-load" means results are returned inline \u2014 nothing is cached or persisted. Requires a valid instance_id (your Redis brain). No rate limits. Call at session start when working on a specific feature or debugging area. Set scope="org" to widen prediction across your whole organisation \u2014 surfaces cross-team risks ("failed 3\xD7 across 2 other teams") from the Org Knowledge Graph, so an incident in one team becomes a vaccine for yours.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},context:{type:"string",description:`What you're working on, e.g. "upgrading Keycloak from 21 to 24"`},top_k:{type:"number",description:"Max predictions to return (default: 5)"},scope:{type:"string",enum:["instance","org","org+commons"],description:'Scope: "instance" (default) = this brain, "org" = warnings from failures in other teams of your organisation, "org+commons" = plus public lessons. Falls back to "instance" without an org.'}},required:["context"]}},{name:"brain_plan",description:'READ-ONLY \u2014 no side effects, no writes, no external network calls. Generative planning layer on top of the CKG: given a task you are ABOUT to do (e.g. "upgrade Postgres 14\u219216", "add Stripe webhooks"), returns an ordered action plan grounded in your own proven lessons \u2014 the failure modes most likely to bite (ranked by confidence), the concrete steps that fixed them before (with commands), and a pre-flight checklist. Where brain_predict answers "what might fail?", brain_plan answers "what should I do, in what order?". Requires a valid instance_id (your Redis brain). Call before starting non-trivial work.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},task:{type:"string",description:'The change you are about to make, e.g. "migrate auth from sessions to JWT"'},top_k:{type:"number",description:"Max items per section (default: 5)"}},required:["task"]}},{name:"brain_conflicts",description:"READ-ONLY \u2014 list every unresolved belief_conflict (a previously confirmed fix now contradicted by a failure) plus the agents currently writing to this Brain (last 1h). This is the arbitration inbox for multi-agent teams: when several AI sessions share one Brain, contradictory writes surface here instead of silently overwriting each other. Resolve any listed conflict with brain_resolve_conflict.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"}},required:[]}},{name:"brain_resolve_conflict",description:'Arbitrate a contested topic by picking the winning side. winner="success" reaffirms the fix (the contradicting failure stops blocking recall); winner="failure" retires the fix (its CKG fixes-edges decay to ~0 and the losing lesson is archived). Human-in-the-loop resolution is the strongest possible confidence signal. List open conflicts first with brain_conflicts.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic:{type:"string",description:'The contested topic, e.g. "fix:jwks-rotation"'},winner:{type:"string",enum:["success","failure"],description:"Which side wins the arbitration"},resolved_by:{type:"string",description:'Who resolved it (agent name or "human"); default "human"'}},required:["topic","winner"]}},{name:"brain_confirm_ci",description:"Close the CI feedback loop: tell the Brain whether a CI job passed or failed and which topics it covered. The Brain adjusts lesson confidence automatically \u2014 confirmed failures get +15%, false positives (brain predicted failure but CI passed) get \u221210%. Called automatically by cachly-action at the end of every pipeline. Also use manually after a deploy to confirm or refute the brain's last prediction.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},job_status:{type:"string",enum:["success","failure","cancelled"],description:"Outcome of the CI job"},topics:{type:"array",items:{type:"string"},description:'Topics touched by this CI run (e.g. ["auth:jwt", "deploy:k8s"])'},scan_topics:{type:"array",items:{type:"string"},description:"Topics the brain predicted would fail (from the scan response). Used to detect false positives."},source:{type:"string",description:'Optional: "github_actions", "gitlab_ci", etc.'}},required:["job_status","topics"]}},{name:"brain_briefing",description:"Push-based Brain warning: instead of waiting for you to ask, the Brain proactively checks whether the file you just opened, the PR you are about to raise, or the deploy you are about to run matches any known failure pattern \u2014 and surfaces warnings BEFORE something breaks. Call this on file_open (with the file path as context), pr_open (with the PR title/body), or deploy (with a short description of what is being deployed). Returns a risk_level (low/medium/high) plus up to 5 ranked warnings with confidence and a known fix.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},event_type:{type:"string",enum:["file_open","pr_open","deploy","manual"],description:"What triggered this briefing \u2014 determines how the context is interpreted"},context:{type:"string",description:"The event context: file path for file_open, title+body for pr_open, short description for deploy/manual"},threshold:{type:"number",description:"Minimum confidence (0\u20131) for a warning to be surfaced. Default 0.6 \u2014 raise it to reduce noise."}},required:["event_type","context"]}},{name:"brain_contribute_signal",description:"Contribute a privacy-safe signal to the global Brain commons. Only the topic category, outcome, and confidence bucket (high/medium/low) are shared \u2014 no lesson text, no org identity. When \u2265 k independent orgs contribute the same pattern, a meta-lesson is derived in the commons. Use this instead of fedbrain_contribute when privacy is required (enterprise, GDPR).",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic_category:{type:"string",description:'Normalised topic, e.g. "auth:jwt" or "deploy:k8s"'},outcome:{type:"string",enum:["success","failure","partial"],description:"Outcome of the pattern"},confidence:{type:"number",description:"Confidence 0\u20131 (bucketed before sending; default 0.5)"}},required:["topic_category","outcome"]}},{name:"brain_import_meta",description:'Import k-anonymous meta-lessons from the global Brain commons into your local Brain. Meta-lessons are derived from \u2265 k independent org signals \u2014 no individual org data is revealed. Imported lessons get state="meta" and never overwrite your own lessons. Filter by category to target relevant patterns.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},category:{type:"string",description:'Optional filter, e.g. "auth" or "deploy"'},limit:{type:"number",description:"Max meta-lessons to import (default 20, max 200)"}},required:[]}},{name:"madc_deliberate",description:"Multi-Agent Deliberation Chamber (MADC \u2014 Layer 3): When conflicting lessons exist for a topic, run deliberation between 6 specialist expert agents (InfraAgent, AuthAgent, DeployAgent, DatabaseAgent, DebugAgent, APIAgent). Each agent votes based on its domain CKG coverage. Unanimous vote \u2192 loser superseded. Split vote \u2192 contested flag, causal_trace required before acting. Resolution stored as permanent CKG node. Called automatically when learn_from_attempts detects a contradiction.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},topic:{type:"string",description:'Topic to deliberate, e.g. "fix:jwks-rotation"'},context:{type:"string",description:"Optional context for the deliberation"}},required:["topic"]}},{name:"cls_ingest",description:"Continuous Learning Stream (CLS \u2014 Layer 5): Ingest learning signals WITHOUT explicit session_end calls. Sources: git_commit (commit message + files \u2192 CKG edges), ci_outcome (green/red build \u2192 confirms fix), ide_diagnostic (compiler error + fix pair \u2192 instant lesson). Install automatic ingestion with cls_install_hooks \u2014 brain learns from every commit and CI run.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},source:{type:"string",enum:["git_commit","ci_outcome","ide_diagnostic"],description:"Event source type"},payload:{type:"object",description:"Event data. git_commit: {message, sha?, files?, diff?}. ci_outcome: {status, prev_status, job, context?}. ide_diagnostic: {error, fix, file?}"}},required:["source","payload"]}},{name:"cls_install_hooks",description:"READ-ONLY \u2014 outputs text only, writes no files, makes no network calls, has no side effects. Generates ready-to-paste shell scripts: a git post-commit hook and/or a GitHub Actions step. You must manually copy and install the output. Once the generated scripts are installed, each git commit or CI run will make outbound HTTPS calls to api.cachly.dev to feed learning signals to your brain. No auth required to call this tool \u2014 only an instance_id. Run once per repository.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},repo_path:{type:"string",description:"Path to repo root (default: current dir)"},hooks:{type:"array",items:{type:"string",enum:["git","ci"]},description:'Which hooks to output (default: ["git", "ci"])'}},required:[]}},{name:"fedbrain_contribute",description:"FedBrain (Layer 6): Contribute a lesson to the global Knowledge Commons with a cryptographic knowledge certificate. Certificate includes: domain fingerprint, confidence, outcome chain hash. Lessons with 10+ independent confirmations become Gold Standard. Context-weighted: other brains with similar tech stacks see your lesson ranked higher in fedbrain_search.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},lesson_key:{type:"string",description:'Topic key to contribute, e.g. "fix:clickhouse-ipv6"'},visibility:{type:"string",enum:["public","org_private"],description:"Visibility (default: public)"}},required:["lesson_key"]}},{name:"fedbrain_search",description:"FedBrain context-weighted search: Search the global commons, weighting results by tech-stack similarity. Brains with matching domain context (Go/Kubernetes/Postgres) rank higher than unrelated stacks. Shows certificate provenance, confirm_count, and Gold Standard badges.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},query:{type:"string",description:"What to search for"},context_hints:{type:"array",items:{type:"string"},description:'Your tech stack, e.g. ["go", "kubernetes", "postgres"]'},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}},{name:"fedbrain_confirm",description:"Confirm that a syndicated lesson from the global commons worked for you. Propagates confirmation back \u2014 increments confirm_count on the knowledge certificate. Also updates your local CKG confidence. At 10 independent confirmations \u2192 Gold Standard.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},id:{type:"string",description:"Syndicated lesson id to confirm (shown next to each fedbrain_search result)"},topic:{type:"string",description:"Optional topic of the lesson \u2014 also updates your local CKG confidence for it"},outcome:{type:"string",enum:["worked","partially_worked","did_not_work"],description:"Did the lesson work for you?"}},required:["id","outcome"]}},{name:"fedbrain_status",description:"Show your FedBrain federation status: lessons contributed to global commons, recent confirmations, Gold Standard lessons, pending propagations. Use to track your brain's global knowledge contribution.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"}},required:[]}},{name:"brain_federate",description:`FedBrain Layer 6 \u2014 Private org knowledge transfer: copy CKG edges + lessons from a source brain into your brain for a specific domain (e.g. "billing", "auth", "deploy"). The new hire use case: one command gives you the senior engineer's 5 years of typed, confidence-weighted knowledge in your domain. Unlike syndicate_search (global, anonymous), brain_federate is org-private \u2014 both brains must be in the same Cachly org, or the source instance_id must be explicitly shared. Example: brain_federate(source="prod-brain-id", domain="billing", min_confidence=0.6)`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Your brain instance ID (destination)"},source:{type:"string",description:"Source brain instance ID to federate from"},domain:{type:"string",description:'Domain to transfer, e.g. "billing", "auth", "deploy", "infra". Use "*" for all domains.'},min_confidence:{type:"number",description:"Minimum edge confidence to transfer (default: 0.6)"},dry_run:{type:"boolean",description:"Preview what would be transferred without writing (default: false)"}},required:["source","domain"]}},{name:"crystal_view",description:"Inspect the current Memory Crystal \u2014 the compressed wisdom distilled from all past sessions. Shows top patterns per category, lesson count, and when the crystal was last refreshed. Call after session_start when you want to quickly see accumulated wisdom across all past work.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},show_raw:{type:"boolean",description:"Include raw JSON crystal data (default: false)"}},required:[]}},{name:"compact_recover",description:"Call FIRST after any context limit hit / compaction. Reconstructs full context from Memory Crystal + recent sessions + WIP registry + open failures. Returns a condensed briefing so the new context window starts exactly where the previous one left off \u2014 no lost progress.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},focus:{type:"string",description:"What you were working on (helps filter relevant context)"}},required:[]}},{name:"brain_from_git",description:"Bootstrap brain lessons from git history. Parses commit messages and infers fix/feature/refactor lessons automatically. Great for onboarding an existing codebase \u2014 run once and the brain instantly knows your team's accumulated patterns. Incremental by default: only processes new commits since the last run, so repeated calls are fast. Emits progress updates to stderr during long scans.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},repo_path:{type:"string",description:"Path to git repository (default: current directory)"},limit:{type:"number",description:"Max commits to process (default: 100, max: 500)"},branch:{type:"string",description:"Git branch to parse (default: current branch / HEAD)"},since:{type:"string",description:'Only commits after this date, e.g. "2024-01-01" (optional)'},incremental:{type:"boolean",description:"Only process commits since last run (default: true). Set false to reprocess all."}},required:[]}},{name:"brain_from_ci",description:"Bulk-ingest CI run outcomes into the Brain \u2014 the brain_from_git equivalent for CI history. Feed it an array of {job, status, prev_status} objects from your CI system and it will learn which jobs have been fixed, broken, or are stable. Use it to bootstrap the Brain from historical CI logs.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},outcomes:{type:"array",description:"List of CI run outcomes to ingest",items:{type:"object",properties:{job:{type:"string",description:'Job name (e.g. "test", "build", "lint")'},status:{type:"string",description:"Current status: success|failure|error"},prev_status:{type:"string",description:"Previous run status (optional, needed to detect transitions)"},context:{type:"string",description:"Optional: error message, branch, commit hash, etc."}},required:["job","status"]}}},required:["outcomes"]}},{name:"brain_watch",description:"Install an ambient git post-commit hook that automatically learns from every commit \u2014 no manual brain_from_git needed. After installation every `git commit` sends the commit message, SHA, and changed files to the cachly Brain in the background. It is the same hook `init` installs; no key is written into the project (the hook reads $CACHLY_JWT or ~/.cachly/credentials.json when it runs). Removes an older brain_watch block. Idempotent: running brain_watch twice installs the hook only once. The hook always exits 0 and runs asynchronously \u2014 it never blocks a commit. Returns the hook path and installation status (written/upgraded/appended/unchanged/skipped-no-git).",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID to learn into"},project_dir:{type:"string",description:'Path to the git repository (default: current directory ".")'}},required:[]}},{name:"brain_predict_failures",description:'Pre-deploy failure prediction with probability percentages. Given a change context (e.g. "upgrading Keycloak 21\u219224" or "deploying Redis 7 to prod"), returns the top likely failure modes ranked by probability, with pre-loaded fixes. Uses CKG causal edges + lesson history. Call before any significant deploy, migration, or infrastructure change.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"Brain instance ID"},context:{type:"string",description:'What you are about to do, e.g. "upgrading Keycloak 21 to 24"'},top_k:{type:"number",description:"Number of failure predictions to return (default: 5)"},format:{type:"string",enum:["brief","detailed"],description:"Output format (default: detailed)"}},required:["context"]}},{name:"brain_share",description:'Export a Brain snapshot and create a publicly shareable link that anyone can import. Optionally filter by topic prefix (e.g. only "auth:" or "deploy:" lessons). Visibility can be "public" (discoverable) or "unlisted" (link-only). Returns a share URL and the import command to give to teammates or the community. Example: brain_share(instance_id="...", title="My Auth Patterns", topic_filter=["auth"])',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to export from."},title:{type:"string",description:'Human-readable title for the shared Brain snapshot. Default: "My Brain Snapshot".'},description:{type:"string",description:"Short description of what knowledge this Brain contains."},topic_filter:{type:"array",items:{type:"string"},description:"Only export lessons whose topic contains one of these strings. Omit to export all lessons."},visibility:{type:"string",enum:["public","unlisted"],description:'"public" = discoverable in the Brain marketplace. "unlisted" = only accessible by direct link. Default: unlisted.'},max_lessons:{type:"number",description:"Maximum number of lessons to include (default 100, max 500)."},dry_run:{type:"boolean",description:"If true, preview what would be shared without creating the public link."}},required:[]}},{name:"brain_import",description:'Import lessons from a publicly shared Brain snapshot into your own Brain instance. Accepts a share ID (UUID) or the full share URL from brain_share. Optionally prefix all imported topics to avoid naming collisions (e.g. topic_prefix="team"). Existing lessons are NOT overwritten by default \u2014 pass overwrite=true to replace them. Example: brain_import(instance_id="...", share_id="abc123", topic_prefix="imported")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to import lessons into."},share_id:{type:"string",description:"Share ID (UUID) or full share URL from brain_share."},topic_prefix:{type:"string",description:'Optional prefix to prepend to all imported topic names (e.g. "team" \u2192 "team:auth:jwt-expiry"). Prevents collisions with your own lessons.'},min_confidence:{type:"number",description:"Skip lessons below this confidence threshold (0.0\u20131.0). Default: 0 (import all)."},overwrite:{type:"boolean",description:"Replace existing lessons with the same topic. Default false."},dry_run:{type:"boolean",description:"Preview what would be imported without writing to the Brain."}},required:["share_id"]}},{name:"brain_share_list",description:'List all Brain snapshots you have previously shared with brain_share. Shows share ID, title, lesson count, visibility, and creation date for each share. Checks the local provenance log and the cachly API. Example: brain_share_list(instance_id="...")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance that created the shares."}},required:[]}},{name:"brain_unshare",description:'Revoke and permanently delete a public Brain share by its share ID. After calling this, the share URL becomes invalid and no one can import it. Note: users who already imported the Brain keep their local copy. Example: brain_unshare(instance_id="...", share_id="abc123")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance that owns the share."},share_id:{type:"string",description:"Share ID to revoke (from brain_share or brain_share_list)."}},required:["share_id"]}},{name:"brain_discover",description:'Search and browse publicly shared Brain snapshots in the cachly marketplace. Find ready-made knowledge bases on specific topics (TypeScript, Docker, auth, CI/CD, etc.) created and shared by the community. Returns a ranked list with lesson counts, topics, and import commands. Example: brain_discover(query="kubernetes deployment") \xB7 brain_discover(topic="auth")',inputSchema:{type:"object",properties:{query:{type:"string",description:"Full-text search query across Brain titles and descriptions."},topic:{type:"string",description:'Filter by topic prefix (e.g. "auth", "docker", "nextjs").'},limit:{type:"number",description:"Max number of results to return (default 10, max 50)."}},required:[]}},{name:"brain_seed_starter",description:`Seed a fresh Brain with a curated set of universal, high-value engineering lessons (Docker layer cache, JWT clock skew, Postgres migration locks, K8s OOM limits, N+1 queries, cache stampede, CORS preflight, and more). Makes the very first smart_recall return a useful hit instead of nothing \u2014 ideal right after setup or in a fresh repo with no git history to learn from. Starter lessons are tagged source:"starter", never override your own lessons, and are idempotent (won't double-seed). Example: brain_seed_starter(instance_id="...") \xB7 brain_seed_starter(instance_id="...", topic_filter=["docker","redis"])`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to seed."},topic_filter:{type:"array",items:{type:"string"},description:'Only seed lessons whose topic or tags match one of these strings (e.g. ["docker", "auth"]). Omit to seed all.'},force:{type:"boolean",description:"Re-seed even if already seeded; also overwrites same-topic lessons. Default false."},dry_run:{type:"boolean",description:"Preview which starter lessons would be seeded without writing."}},required:[]}},{name:"brain_graph",description:'Export the Causal Knowledge Graph as a 3D-render-ready node/link payload (schema cachly.brain_graph/v1) \u2014 the data layer behind the brain viz: the visual, explorable 3D map of every concept, person, file and service the brain knows, and how they causally relate. Node kinds (concept/person/file/service) carry stable color groups and a size (val) scaled by reference count; links carry edgeType (fixes/causes/co-occurs/authored/collaborates) and confidence (value). Consumed verbatim by react-force-graph-3d / three.js frontends. Example: brain_graph(instance_id="...") \xB7 brain_graph(instance_id="...", domain="auth", min_confidence=0.5, format="summary")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance to export."},max_nodes:{type:"number",description:"Cap on nodes returned (default 400, max 2000). Edges to dropped nodes are pruned."},domain:{type:"string",description:'Only include nodes whose domain or id contains this string (e.g. "auth", "docker"). Omit for the whole graph.'},min_confidence:{type:"number",description:"Drop edges below this confidence 0..1 (default 0 = keep all)."},format:{type:"string",enum:["json","summary"],description:'"json" (default) emits the full renderable payload; "summary" emits a human-readable overview.'}},required:[]}},{name:"brain_set_pref",description:'Persist a user preference for this Brain instance. Preferences are stored in Redis and survive restarts. Known keys: `auto_changelog` (set to "false" to disable the automatic changelog shown at session_start).',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (Brain ID)."},key:{type:"string",description:'Preference key (e.g. "auto_changelog").'},value:{type:"string",description:'Value to set (e.g. "false" to disable, "true" to re-enable).'}},required:["key","value"]}},{name:"brain_get_pref",description:"Read back one or all preferences stored for this Brain instance. Call with a `key` to get a single value, or omit `key` to list every preference that has been set. Returns a default note when a key has never been set. Complement to `brain_set_pref`.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the Brain instance."},key:{type:"string",description:"Preference key to read. Omit to list all preferences."}},required:[]}}];export{e as TOOLS};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.205",
3
+ "version": "0.10.206",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.205",
3
+ "version": "0.10.206",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Solve it once. From then on, your AI knows. Experience for coding agents, EU-hosted: an MCP server for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -6,13 +6,13 @@
6
6
  "url": "https://github.com/cachly-dev/cachly-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.10.205",
9
+ "version": "0.10.206",
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.10.205",
15
+ "version": "0.10.206",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }