@cachly-dev/mcp-server 0.10.225 → 0.10.226
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/src/aussetzer.js +1 -1
- package/dist/src/embeddings.js +4 -4
- package/dist/src/first-recall-proof.js +4 -4
- package/dist/src/git-startpunkt.js +1 -0
- package/dist/src/handlers/advanced.js +1 -1
- package/dist/src/handlers/brain.js +58 -63
- package/dist/src/handlers/fedbrain.js +37 -37
- package/dist/src/handlers/share.js +16 -16
- package/dist/src/handlers/syndicate.js +2 -2
- package/dist/src/handlers/team.js +24 -24
- package/dist/src/index.js +131 -135
- package/dist/src/pflichtfelder.js +1 -0
- package/dist/src/schreibtor.js +1 -1
- package/dist/src/tuersteher.js +1 -1
- package/dist/src/wirkungsspur.js +1 -1
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +17 -17
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import{createHmac as he}from"node:crypto";import{ckgSlug as b,extractProblemConcept as
|
|
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=
|
|
3
|
-
`);const o=[];for(const
|
|
4
|
-
`)}case"cls_ingest":{const{instance_id:
|
|
5
|
-
`)}if(
|
|
6
|
-
`)}if(
|
|
7
|
-
`)}return`\u274C Unknown CLS source: "${
|
|
8
|
-
`];if(be(
|
|
9
|
-
`)}case"fedbrain_contribute":{const{instance_id:
|
|
10
|
-
`)}case"fedbrain_search":{const{instance_id:
|
|
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),
|
|
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_":!
|
|
13
|
-
`)}case"fedbrain_confirm":{const{instance_id:
|
|
14
|
-
`);const e=await A(
|
|
15
|
-
`)}case"fedbrain_status":{const{instance_id:
|
|
16
|
-
`,`### \u{1F4E4} Contributed Lessons: ${
|
|
17
|
-
`)}case"brain_federate":{const{instance_id:
|
|
18
|
-
`);let a=0,t=0,o=0,n=0,h=0,
|
|
19
|
-
`)}case"crystal_view":{const{instance_id:
|
|
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(
|
|
21
|
-
`)}case"compact_recover":{const{instance_id:
|
|
1
|
+
import{createHmac as he}from"node:crypto";import{ckgSlug as b,extractProblemConcept as pe,ckgUpsertNode as T,ckgUpdateEdge as J,ckgUpsertPersonNode as me,ckgUpsertFileNode as ge,ckgRecordCollaboration as we}from"../ckg.js";import{safeJsonParse as R}from"../utils.js";import{buildClsPostCommitHook as _e}from"../cls-hook.js";import{alsShellWort as ye,beginntMitBindestrich as $e,gitLesen as V,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 je,gitLogArgumente as Ne,leseCommits as Ie}from"../git-lektionen.js";import{alterStartpunktSchluessel as Ae,startpunktSchluessel as Le}from"../git-startpunkt.js";import{VEKTOR_NACHTRAG as Re}from"../bedeutung.js";import{VERDACHT_TAG as De,fuerEigenenSpeicher as G,fuerWeitergabe as re,hinweise as Y,istMarkiert as Te,markiert as K,weitergabeHinweis as ce,zaehlHinweise as F}from"../schreibtor.js";let Je=null,Me=null,Q=0;const Pe=10,le=[];function Be(){return Q<Pe?(Q++,Promise.resolve()):new Promise(B=>le.push(B))}function ze(){const B=le.shift();B?B():Q--}const et=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 tt(B,N,A,z){switch(B){case"madc_deliberate":{const{instance_id:_,topic:l}=N,u=await A(_),e=(await u.lrange(`cachly:lessons:${l}`,0,-1)).map(w=>{try{return JSON.parse(w)}catch{return null}}).filter(Boolean);if(e.length<2)return[`\u{1F5F3}\uFE0F **MADC: "${l}"**`,"",`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=l.split(":")[0]??"",r=i.filter(w=>w.domains.some($=>f===$||l.includes($))),d=r.length>0?r:i,c=new Map;for(const w of d){let $=0;for(const v of w.domains){const O=[],S=u.scanStream({match:`cachly:ckg:node:${v}*`,count:50});await new Promise((k,j)=>{S.on("data",M=>O.push(...M)),S.on("end",k),S.on("error",j)}),$+=O.length}c.set(w.name,$)}const a=e.filter(w=>w.outcome==="success"||w.outcome==="partial"),t=e.filter(w=>w.outcome==="failure");if(t.length===0)return[`\u{1F5F3}\uFE0F **MADC: "${l}"**`,"",`No contradictions found \u2014 all ${a.length} entries have non-failure outcomes.`,"",`Use \`ckg_inspect(concept="${b(l)}")\` to explore the confidence graph.`].join(`
|
|
3
|
+
`);const o=[];for(const w of d){const $=c.get(w.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:w.name,vote:v,coverage:$,reason:O})}const n=o.filter(w=>w.vote==="success").length,h=o.filter(w=>w.vote==="failure").length,p=o.filter(w=>w.vote==="abstain").length;let m,y;n>0&&h===0?(m="unanimous_success",y=`\u2705 **Unanimous: SUCCESS** \u2014 ${n} agent(s) confirm, ${p} abstain`):h>0&&n===0?(m="unanimous_failure",y=`\u274C **Unanimous: FAILURE** \u2014 ${h} agent(s) confirm, ${p} abstain`):(m="contested",y=`\u26A0\uFE0F **CONTESTED** \u2014 ${n} success votes, ${h} failure votes, ${p} abstain`);const g=b(`resolution:${l}`),x={id:g,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:m,topic:l,votes:{success:n,failure:h,abstain:p}};if(await u.set(`cachly:ckg:node:${g}`,JSON.stringify(x)),m==="contested")await J(u,b(l),"contradicts",g,!1);else{if(((m==="unanimous_success"?"failure":"success")==="failure"?t:a).length>0){const v=await u.smembers(`cachly:ckg:idx:from:${b(l)}`);for(const O of v){const S=await u.get(O);if(S)try{const k=JSON.parse(S);k.edgeType==="fixes"&&k.confidence>.15&&m==="unanimous_failure"&&(k.confidence=.1,k.last_updated=new Date().toISOString(),await u.set(O,JSON.stringify(k)))}catch{}}}await u.del(`cachly:ckg:conflict:${b(l)}`)}const C=[`\u{1F5F3}\uFE0F **MADC Deliberation: "${l}"**`,"",`\u{1F4CA} Evidence: ${a.length} success/partial vs ${t.length} failure entries (${e.length} total)`,"",`**Voting agents (${d.length}):**`,...o.map(w=>{const $=w.vote==="success"?"\u2705":w.vote==="failure"?"\u274C":"\u2B1C",v="\u2593".repeat(Math.min(w.coverage,5))+"\u2591".repeat(Math.max(0,5-w.coverage));return` ${$} **${w.agent}** [${v}] ${w.coverage} CKG edges \u2014 ${w.reason}`}),"",y,""];return m==="unanimous_success"?C.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${l}", outcome="success", ...)\``):m==="unanimous_failure"?C.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${l}")\``):C.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${b(l)}")\``),C.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${g}\``),C.join(`
|
|
4
|
+
`)}case"cls_ingest":{const{instance_id:_,source:l,payload:u}=N,s=G(u),e=s.felder,i=await A(_),f=new Date().toISOString(),r="cachly:cls:events";if(l==="git_commit"){const d=String(e.message??""),c=String(e.sha??""),a=Array.isArray(e.files)?e.files:[],t=/^fix/i.test(d)?"fix":/^feat/i.test(d)?"feat":/^refactor/i.test(d)?"refactor":/^test/i.test(d)?"test":"commit",o=`${t}:${b(d.slice(0,60))}`,n=b(o);await T(i,n,t,"commit");for(const m of a.slice(0,10)){const y=m.includes("auth")?"auth":m.includes("api")?"api":m.includes("infra")?"infra":m.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:d,what_failed:"",context:`CLS/git: sha=${c}`,severity:"minor",file_paths:a.slice(0,10),commands:c?[`git show ${c}`]:[],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:l,payload:{message:d,sha:c},ts:f})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${c.slice(0,8)||"?"}\`: ${d.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}")\``,...Y(s)].join(`
|
|
5
|
+
`)}if(l==="ci_outcome"){const d=String(e.status??""),c=String(e.prev_status??""),a=String(e.job??"unknown"),t=String(e.context??""),o=["failure","red","error"].includes(c)&&["success","green","passed"].includes(d),n=["success","green","passed"].includes(c)&&["failure","red","error"].includes(d),h=`ci:${b(a)}`,p=b(h);if(await T(i,p,"ci","job"),o){const y=b(`problem:${b(a)}`);await T(i,y,"problem","ci-failure"),await J(i,p,"fixes",y,!0);const g={topic:h,outcome:"success",what_worked:`CI job "${a}" went ${c} \u2192 ${d}`,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,p,"causes",y,!1)}return await i.rpush(r,JSON.stringify({source:l,payload:{status:d,prev_status:c,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 ${c||"?"} \u2192 ${d}`,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}")\``,...Y(o?s:{geschwaerzt:s.geschwaerzt,verdacht:[]})].join(`
|
|
6
|
+
`)}if(l==="ide_diagnostic"){const d=String(e.error??""),c=String(e.fix??""),a=String(e.file??""),t=pe(d)??"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 p={topic:o,outcome:"success",what_worked:c,what_failed:d,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(p)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(p)),await i.rpush(r,JSON.stringify({source:l,payload:{error:d.slice(0,60),fix:c.slice(0,60),file:a},ts:f})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ide_diagnostic**","",`Error: \`${d.slice(0,80)}\``,`Fix: ${c.slice(0,100)}`,a?`File: \`${a}\``:"","",`\u{1F578}\uFE0F CKG: \`${n}\` \u2192 fixes \u2192 \`${h}\` | Lesson: \`${o}\``,...Y(s)].filter(y=>y!=="").join(`
|
|
7
|
+
`)}return`\u274C Unknown CLS source: "${l}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:_,repo_path:l=".",hooks:u=["git","ci"]}=N,s=Array.isArray(u)?u:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
|
|
8
|
+
`];if(be(_),s.includes("git")){const i=_e(_),f=ye(`${l}/.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:'${_}',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:_,lesson_key:l,visibility:u="public"}=N,s=await A(_),e=await s.get(`cachly:lesson:best:${l}`);if(!e)return`\u274C Lesson \`${l}\` not found. Store it first with \`learn_from_attempts\`.`;const i=R(e,null);if(!i)return`\u274C Lesson \`${l}\` 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??[]},"the Commons");if(!f.ok)return f.meldung;if(Te(i))return`\u26D4 Tuersteher (security gate): the lesson \`${l}\` was flagged as suspicious when it was saved \u2014 NOT passed on to the Commons. Nothing was sent. Check the content, then save it again with \`learn_from_attempts\` without the instruction.`;const r={...i,...f.felder},d=[r.topic.split(":")[0],...r.tags??[]].filter(Boolean),c=[...new Set(d)].sort().join(","),a=`${r.topic}:${r.outcome}:${r.what_worked}`,t=he("sha256",`cachly-fedbrain:${_}`).update(a).digest("hex").slice(0,16),o={cert_id:t,lesson_key:l,visibility:u,domain_fingerprint:c,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:c,visibility:u})}),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: "${l}"**`,"",`\u{1F4DC} Certificate: \`${t}\``,`\u{1F3F7}\uFE0F Domain fingerprint: ${d.slice(0,6).map(h=>`\`${h}\``).join(", ")}`,`\u{1F512} Visibility: ${u}`,"",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:_,query:l,context_hints:u=[],limit:s=10}=N,e=await A(_),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 p of(h.domain_fingerprint??"").split(",").filter(Boolean))f.set(p,(f.get(p)??0)+1)}catch{}}for(const o of Array.isArray(u)?u:[])f.set(o.toLowerCase(),(f.get(o.toLowerCase())??0)+2);let r=[],d=!1;try{const o=new URLSearchParams({q:l,limit:String(Math.min(s*2,50))});r=(await z(`/api/v1/syndication/search?${o}`)).results??[]}catch{d=!0;const o=[],n=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,p)=>{n.on("data",m=>o.push(...m)),n.on("end",h),n.on("error",p)});for(const h of o.slice(0,60)){const p=await e.get(h);if(p)try{const m=JSON.parse(p),y=`${m.topic} ${m.what_worked??""} ${m.what_failed??""}`.toLowerCase();l.toLowerCase().split(/\s+/).some(g=>g.length>2&&y.includes(g))&&r.push({id:h.split(":").pop()??h,topic:m.topic,category:m.topic.split(":")[0],outcome:m.outcome,what_worked:m.what_worked??"",severity:m.severity??"major",confirm_count:0,created_at:m.ts??new Date().toISOString()})}catch{}}}const c=d?" \u2014 \u26A0\uFE0F Commons unreachable, local fallback (this machine only, not confirmed by the network)":"";if(r.length===0)return[`\u{1F310} **FedBrain Search: "${l}"**${c}`,"",'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),p=f.size>0?h/Math.max(1,f.size+n.length):0,m=Math.min(1,o.confirm_count/10),y=p*.4+m*.4+(o.outcome==="success"?.2:0);return{...o,weightedScore:y,isGoldStandard:!d&&o.confirm_count>=10}}).sort((o,n)=>n.weightedScore-o.weightedScore).slice(0,s),t=[`\u{1F310} **FedBrain Search: "${l}"** \u2014 ${a.length} result${a.length!==1?"s":""} (context-weighted)${c}
|
|
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_":!d&&o.confirm_count>=3?` \u2713${o.confirm_count}`:"",p=Math.round(o.weightedScore*100);t.push(`${n}${h} **\`${o.topic}\`** [ctx: ${p}%]`),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:_,id:l,topic:u,outcome:s}=N;if(!l)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(_),i=new Date().toISOString(),f=JSON.stringify({id:l,topic:u,outcome:s,ts:i});await e.rpush("cachly:fedbrain:confirmations",f),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const r=s==="worked",d=s==="partially_worked";u&&await J(e,b(u),"fixes",b(`syndicated:${u}`),r,d);let c;try{await z(`/api/v1/syndication/${encodeURIComponent(l)}/confirm`,{method:"POST"}),c="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",f),await e.ltrim("cachly:fedbrain:pending_confirms",-50,-1),c="\u{1F4E6} Queued locally (API unavailable \u2014 will propagate on next online session)"}return[`${r?"\u2705":d?"\u26A0\uFE0F":"\u274C"} **FedBrain Confirm: "${u??l}"** \u2192 ${s}`,"",c,"",u?`\u{1F578}\uFE0F CKG confidence ${r||d?"boosted":"reduced"} for \`${b(u)}\``:"\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:_}=N,l=await A(_),u=await l.smembers("cachly:fedbrain:contributed"),s=await l.lrange("cachly:fedbrain:confirmations",-10,-1),e=await l.llen("cachly:fedbrain:pending_confirms"),i=s.map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(Boolean),f=[];for(const d of u.slice(0,15)){const c=await l.get(`cachly:fedbrain:cert:${d}`);if(c)try{const a=JSON.parse(c);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: ${u.length}`];if(f.length>0)for(const d of f){const c=d.isGold?" \u{1F3C6} Gold Standard":"",a="\u2588".repeat(Math.min(10,d.confirm_count))+"\u2591".repeat(Math.max(0,10-d.confirm_count));r.push(` \`${d.lesson_key}\` [${a}] \xD7${d.confirm_count}${c}`)}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 d of i.slice(-5)){const c=d.outcome==="worked"?"\u2705":d.outcome==="partially_worked"?"\u26A0\uFE0F":"\u274C";r.push(` ${c} \`${d.topic}\` \u2014 ${d.outcome} (${new Date(d.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:_,source:l,domain:u,min_confidence:s=.6,dry_run:e=!1}=N;if(_===l)return"\u274C Source and destination cannot be the same brain.";const i=await A(_),f=await A(l),r=u==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${u}*`,d=[],c=f.scanStream({match:r,count:100});if(await new Promise((x,C)=>{c.on("data",w=>d.push(...w)),c.on("end",x),c.on("error",C)}),d.length===0)return[`\u{1F9E0} **brain_federate: "${u}"**`,"",`No CKG nodes found in source brain for domain \`${u}\`.`,"The source brain may not have knowledge in this area yet.",`Try: \`fedbrain_search(query="${u}")\` to find global commons knowledge instead.`].join(`
|
|
18
|
+
`);let a=0,t=0,o=0,n=0,h=0,p=0;const m=[];for(const x of d){const C=await f.get(x);if(!C)continue;let w;try{w=JSON.parse(C)}catch{continue}e||await i.set(x,C),a++;const $=await f.smembers(`cachly:ckg:idx:from:${w.id}`);for(const S of $){const k=await f.get(S);if(!k)continue;let j;try{j=JSON.parse(k)}catch{continue}if(j.confidence<s){n++;continue}e||(await i.set(S,k),await i.sadd(`cachly:ckg:idx:from:${j.from}`,S),await i.sadd(`cachly:ckg:idx:to:${j.to}`,S)),t++}const v=`cachly:lesson:best:${w.id}`,O=await f.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&&p++;const j=k.verdacht.length?{...k.felder,tags:K(k.felder.tags,k.verdacht)}:k.felder;if(e||await i.set(v,JSON.stringify(j)),o++,m.length<8){const M=j.outcome==="success"?"\u2705":j.outcome==="failure"?"\u274C":"\u26A0\uFE0F";m.push(` ${M} \`${j.topic}\` \u2014 ${(j.what_worked??"").slice(0,80)}`)}}}if(!e){const x=JSON.stringify({source:l,domain:u,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: "${u}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${l}\``,`\u{1F4E5} Destination: \`${_}\``,`\u{1F50D} Domain filter: \`${u}\` | 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,p,`${o} copied lessons`),""];return m.length>0&&(g.push("### Sample lessons transferred:",...m),o>m.length&&g.push(` _... and ${o-m.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 \`${u}\` knowledge from \`${l}\`.`),g.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${u}")\` | \`recall_best_solution(topic="${u}:...")\``)),g.join(`
|
|
19
|
+
`)}case"crystal_view":{const{instance_id:_,show_raw:l=!1}=N,u=await A(_),s=await u.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(c=>`\`${c}\``).join(", ")}${e.categories.length>10?` +${e.categories.length-10} more`:""}`,"",`**\u{1F511} Top patterns (${e.top_patterns.length}):**`];for(const c of e.top_patterns)r.push(` \u2022 **${c.category}** (${c.count}\xD7): ${c.insight.slice(0,110)}`);i>30&&r.push("",`\u26A0\uFE0F Crystal is ${i}d old \u2014 run \`memory_crystalize()\` to refresh it.`),l&&r.push("","```json",JSON.stringify(e,null,2),"```");const d=await u.get("cachly:crystal:team:latest").catch(()=>null);if(d){const c=R(d,null);if(c&&c.patterns?.length){const a=Math.floor((Date.now()-new Date(c.ts).getTime())/864e5);r.push("","---",`\u{1F4A0} **Team Crystal: ${c.label}** _(${a}d ago \xB7 ${c.contributors} contributors)_`,"_Fixes multiple teammates independently converged on \u2014 the team-wide layer:_");for(const t of c.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:_,focus:l=""}=N,u=await A(_),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
|
|
24
|
-
`)}case"brain_from_git":{const
|
|
25
|
-
\u{1F9E0} brain_from_git: processing ${k} commits from ${
|
|
26
|
-
`);let
|
|
27
|
-
`),M=I),!P){
|
|
23
|
+
`);const e=await u.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=l?t.top_patterns.filter(n=>n.category.toLowerCase().includes(l.toLowerCase())||n.insight.toLowerCase().includes(l.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 u.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 u.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 u.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 d=[],c=u.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((t,o)=>{c.on("data",n=>d.push(...n)),c.on("end",t),c.on("error",o)});const a=[];for(const t of d.slice(0,30)){const o=await u.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(l){const t=[],o=u.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,p)=>{o.on("data",m=>t.push(...m)),o.on("end",h),o.on("error",p)});const n=[];for(const h of t){const p=await u.get(h);if(p)try{const m=JSON.parse(p);m.topic.toLowerCase().includes(l.toLowerCase())&&m.what_worked&&n.push({topic:m.topic,what_worked:m.what_worked})}catch{}}if(n.length>0){s.push(`### \u{1F4A1} Relevant Lessons for "${l}"`);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 _=Date.now(),{instance_id:l,repo_path:u=".",limit:s=100,branch:e="HEAD",since:i="",incremental:f=!0}=N,r=await A(l),{resolve:d}=await import("node:path"),c=d(u),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 Be();try{try{if(!Se(c))throw new Error("kein Ordner");V(c,["rev-parse","--git-dir"],{stderr:"pipe"})}catch{return`\u274C Not a git repository: \`${c}\`. Pass \`repo_path\` pointing to a git checkout.`}const t=Le(c);let o="",n=!1;if(f!==!1&&!i){if(o=await r.get(t)??await r.get(Ae(c))??"",ke(o)||(o=""),o)try{V(c,["cat-file","-e",`${o}^{commit}`])}catch{o=""}n=!!o}const p=(n?`${o}..HEAD`:"")||e||"HEAD",m=Ne(p,a,i);let y="";try{y=V(c,m,{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:c,revRange:p,processed:0,ingested:0,skipped:0,durationMs:Date.now()-_,isIncremental:!1,instanceId:l,categories:[],suggestedQueries:[],emptyReason:`No commits found in \`${c}\` on branch \`${e}\`${i?` since ${i}`:""}.`});const x=new Date().toISOString();let C=0,w=0;const $=new Map,v=new Map,O=[];let S=null;const k=g.length,j=Math.max(1,Math.floor(k/10));let M=0;process.stderr.write(`
|
|
25
|
+
\u{1F9E0} brain_from_git: processing ${k} commits from ${c}...
|
|
26
|
+
`);let H=0,X=0;for(let I=0;I<g.length;I++){const{commit:L,geschwaerzt:ue,verdacht:de,lektion:P}=je(g[I]);if(ue&&H++,de&&X++,I-M>=j&&(process.stderr.write(` \u23F3 Processing ${I}/${k} commits (${C} lessons so far)...
|
|
27
|
+
`),M=I),!P){w++;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 oe=P.file_paths,se={topic:D,outcome:q,severity:U,what_worked:P.what_worked,what_failed:P.what_failed,context:P.context,author:P.author,file_paths:oe,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(se),"EX",90*86400),await r.rpush(`cachly:lessons:${D}`,JSON.stringify(se)),await r.ltrim(`cachly:lessons:${D}`,-100,-1),await r.expire(`cachly:lessons:${D}`,90*86400),await r.sadd(Re,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 ne=b(D);if(await T(r,ne,E,"git-derived"),L.author)try{const W=await me(r,L.author,E);await J(r,W,"authored",ne,q==="success",q==="partial");for(const fe of oe.slice(0,8)){const ie=await ge(r,fe);await J(r,W,"touched",ie,!0),await we(r,ie,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),
|
|
30
|
-
`):
|
|
31
|
-
`)}case"brain_predict_failures":{const{instance_id:
|
|
32
|
-
`);const
|
|
29
|
+
`),C>0&&ve(),g.length>0&&g[0]?.sha&&await r.set(t,g[0].sha,"EX",2160*3600),Je={fixes:$.get("fix")??0,features:$.get("feat")??0,refactors:$.get("refactor")??0,total:C};let Z=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,{});Z={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 ee=ae({repoDir:c,revRange:p,processed:g.length,ingested:C,skipped:w,durationMs:Date.now()-_,isIncremental:n,lastSha:o,instanceId:l,categories:[...$.entries()].sort((I,L)=>L[1]-I[1]),severities:[...v.entries()].sort((I,L)=>L[1]-I[1]),proof:Z,suggestedQueries:Oe(O,l)}),te=F(H,X,`${g.length} commits`);return te.length?[ee,"",...te].join(`
|
|
30
|
+
`):ee}finally{ze()}}case"brain_from_ci":{const{instance_id:_,outcomes:l}=N,u=await A(_),s=Date.now();let e=0,i=0,f=0,r=0,d=0;const c=l.length;for(const a of l){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,p=t.felder.context,m=["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(u,x,"ci","job"),m){const w=b(`problem:${b(h)}`);await T(u,w,"problem","ci-failure"),await J(u,x,"fixes",w,!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: ${p}`,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 u.rpush(`cachly:lessons:${g}`,JSON.stringify($)),await u.ltrim(`cachly:lessons:${g}`,-100,-1),await u.set(`cachly:lesson:best:${g}`,JSON.stringify($)),t.verdacht.length&&d++,e++}else if(y){const w=b(`cause:${b(h)}`);await T(u,w,"cause","ci-break"),await J(u,x,"causes",w,!1),i++}else f++;const C=`cachly:cls:${_}`;await u.rpush(C,JSON.stringify({source:"ci_outcome",payload:{status:o,prev_status:n,job:h},ts:s})),await u.ltrim(C,-200,-1)}return Me={fixes:e,breaks:i,stable:f,total:c},[`\u{1F4E5} **brain_from_ci**: Ingested ${c} 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>")`',...F(r,d,`${c} CI results`)].filter(Boolean).join(`
|
|
31
|
+
`)}case"brain_predict_failures":{const{instance_id:_,context:l,top_k:u=5,format:s="detailed"}=N,e=await A(_),i=l.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=[],p=e.scanStream({match:`cachly:ckg:node:*${n}*`,count:50});await new Promise((m,y)=>{p.on("data",g=>h.push(...g)),p.on("end",m),p.on("error",y)});for(const m of h.slice(0,5)){const y=await e.get(m);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 w=await e.get(C);if(!w)continue;const $=R(w,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 j=R(k,null);if(j&&j.edgeType==="fixes"){const M=await e.get(`cachly:lesson:best:${j.from}`);if(M){O=R(M,null)?.what_worked?.slice(0,120);break}}}f.push({concept:g.id,failure:$.to.replace(/-/g," "),probability:$.confidence,fix:O,source:"ckg"})}}}const r=[],d=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((n,h)=>{d.on("data",p=>r.push(...p)),d.on("end",n),d.on("error",h)});for(const n of r.slice(0,100)){const h=await e.get(n);if(h)try{const p=JSON.parse(h);if(p.outcome!=="failure"&&p.outcome!=="partial"||!p.what_failed)continue;const m=`${p.topic} ${p.what_failed}`.toLowerCase(),y=i.filter(x=>m.includes(x)).length/Math.max(1,i.length);if(y<.15)continue;const g=p.severity==="critical"?.15:p.severity==="major"?.05:0;f.push({concept:p.topic,failure:p.what_failed.slice(0,80),probability:Math.min(.97,(p.confidence??.5)*y*1.5+g),fix:p.what_worked?.slice(0,120),topic:p.topic,source:"lesson"})}catch{}}if(f.length===0)return[`\u{1F52E} **Failure Prediction: "${l}"**`,"","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="${l}")\` for broader predictions.`].join(`
|
|
32
|
+
`);const c=new Set,a=f.filter(n=>{const h=n.failure.slice(0,40);return c.has(h)?!1:(c.add(h),!0)}).sort((n,h)=>h.probability-n.probability).slice(0,Number(u)),t=[`\u{1F52E} **Failure Prediction for: "${l}"**
|
|
33
33
|
`];t.push(`> Pre-deploy failure analysis based on ${f.length} patterns. Ranked by probability.
|
|
34
|
-
`);for(let n=0;n<a.length;n++){const h=a[n],
|
|
35
|
-
`)}case"brain_contribute_signal":{const{instance_id:
|
|
36
|
-
`)}case"brain_import_meta":{const{instance_id:
|
|
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(
|
|
38
|
-
`)}case"brain_watch":{const{instance_id:
|
|
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: \`${
|
|
40
|
-
`)}default:return null}}export{
|
|
34
|
+
`);for(let n=0;n<a.length;n++){const h=a[n],p=Math.round(h.probability*100),m="\u2588".repeat(Math.round(p/10))+"\u2591".repeat(10-Math.round(p/10)),y=p>=70?"\u{1F534}":p>=40?"\u{1F7E1}":"\u{1F7E2}";t.push(`${y} **${n+1}. ${h.failure}**`),t.push(` Probability: ${m} **${p}%** (${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:_,topic_category:l,outcome:u,confidence:s=.5}=N;if(!l?.trim())throw new Error("topic_category is required");if(!["success","failure","partial"].includes(u))throw new Error("outcome must be success, failure, or partial");const e=re({topic_category:l.trim()},"the 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 z("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:i.toLowerCase(),outcome:u,confidence:s})}),r="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const d=await A(_),c=`cachly:fed:outbox:${Date.now()}`;await d.set(c,JSON.stringify({topic_category:i,outcome:u,bucket:f,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${i}\`**`,"",`\u{1F4CA} Outcome: **${u}** \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:_,category:l,limit:u=20}=N;let s=[],e=3;try{const a=new URLSearchParams;l&&a.set("category",l),a.set("limit",String(Math.min(u,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 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(_);let d=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:[De]}:{},avg_confidence:a.avg_confidence,signal_count:a.signal_count,audit_trail:[{ts:new Date().toISOString(),action:"imported_meta"}]})),d++)}const c=[`\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)+"%";c.push(`| \`${a.topic_category}\` | ${a.dominant_outcome} | ${t} | ${a.signal_count} |`)}return s.length>15&&c.push(`| _\u2026${s.length-15} more_ | | | |`),c.push("",`\u2705 **${d}** new meta-lessons imported into local Brain.`),d<s.length&&c.push(`_(${s.length-d} already present \u2014 not overwritten)_`),c.push(...F(i,f.size,`${s.length} category names`)),c.join(`
|
|
38
|
+
`)}case"brain_watch":{const{instance_id:_="",project_dir:l=".",api_key:u}=N,{resolve:s}=await import("node:path"),e=s(l),{result:i,hookPath:f,alterBlockEntfernt:r}=await Ce(e,_);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: \`${_||"(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)."]:[],...u?["\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
|
+
`)}default:return null}}export{et as FEDBRAIN_TOOL_NAMES,Me as _lastBrainFromCiCounts,Je as _lastBrainFromGitCounts,tt as handleFedbrainTool};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{safeJsonParse as E}from"../utils.js";import{STARTER_CORPUS as x,STARTER_CORPUS_SIZE as q}from"../starter-corpus.js";import{cachlyUrl as
|
|
1
|
+
import{safeJsonParse as E}from"../utils.js";import{STARTER_CORPUS as x,STARTER_CORPUS_SIZE as q}from"../starter-corpus.js";import{cachlyUrl as R}from"../cachly-url.js";import{VEKTOR_NACHTRAG as J}from"../bedeutung.js";import{schwaerze as P}from"../geheimnis-filter.js";import{fuerEigenenSpeicher as I,fuerWeitergabe as D,hinweise as U,istMarkiert as z,markiert as L,weitergabeHinweis as C,zaehlHinweise as K}from"../schreibtor.js";const W=new Set(["brain_share","brain_import","brain_share_list","brain_unshare","brain_discover","brain_seed_starter"]);async function M(O,y){const g=[],$=O.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((a,u)=>{$.on("data",e=>g.push(...e)),$.on("end",a),$.on("error",u)});const i=[];for(const a of g.slice(0,500)){const u=await O.get(a);if(!u)continue;const e=E(u,null);!e||!e.topic||y&&y.length>0&&!y.some(s=>e.topic.includes(s))||i.push({topic:e.topic,outcome:e.outcome,...e.what_worked?{what_worked:e.what_worked}:{},...e.what_failed?{what_failed:e.what_failed}:{},...e.ctx?{ctx:e.ctx}:{},...e.tags?.length?{tags:e.tags}:{},...e.author?{author:e.author}:{},...e.service?{service:e.service}:{},confidence:e.confidence??1,ts:e.ts})}return i}async function Q(O,y,g,$){switch(O){case"brain_share":{const{instance_id:i,title:a="My Brain Snapshot",description:u="",topic_filter:e,visibility:t="unlisted",max_lessons:s=100,dry_run:r=!1}=y;if(!i)return"\u26A0\uFE0F `brain_share` requires `instance_id`.";const c=D({title:a,description:u},"the share");if(!c.ok)return c.meldung;const l=[...c.geschwaerzt],_=c.felder.title,f=c.felder.description,n=await g(i),p=Array.isArray(e)&&e.length>0?e:void 0,w=await M(n,p),m=[],S=[];for(const o of w){if(S.length>=s)break;const d=P(o.topic).text;if(z(o)){m.push(`${d} (beim Speichern markiert)`);continue}const b=D(o,"the share");if(!b.ok){m.push(`${d} (${b.verdacht.join("; ")})`);continue}l.push(...b.geschwaerzt),S.push(b.felder)}const h=S,T=[C(l),m.length?`\u26D4 Tuersteher (security gate): ${m.length} lesson(s) NOT included in the share (instruction or dangerous command detected): ${m.slice(0,10).join(", ")}${m.length>10?", \u2026":""}. Check them and save them again one by one; the lessons in the Brain stay unchanged.`:""].filter(Boolean);if(h.length===0)return["\u{1F4E4} **brain_share** \u2014 nothing to share yet","",`No lessons found in Brain \`${i}\`${p?` matching topics: ${p.join(", ")}`:""}${m.length?" that can be shared":""}.`,"",'Store lessons first with `learn_from_attempts(topic="...", what_worked="...")`.',...T].join(`
|
|
2
2
|
`);if(r){const o=h.slice(0,5).map(d=>` ${d.outcome==="success"?"\u2705":d.outcome==="failure"?"\u274C":"\u26A0\uFE0F"} \`${d.topic}\` \u2014 ${(d.what_worked??d.what_failed??"").slice(0,80)}`);return[`\u{1F4E4} **brain_share (DRY RUN)** \u2014 would share ${h.length} lesson${h.length!==1?"s":""}`,"",`**Title:** ${_}`,`**Visibility:** ${t}`,p?`**Topic filter:** ${p.join(", ")}`:"","","**Sample lessons (first 5):**",...o,h.length>5?` _...and ${h.length-5} more_`:"","",...T,"_Remove `dry_run=true` to create the public share._"].filter(d=>d!=="").join(`
|
|
3
|
-
`)}let j=null,v=null;try{j=(await $("/api/v1/brains/share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_,description:f,visibility:t,lessons:h})})).share_id??null,j&&(v=
|
|
3
|
+
`)}let j=null,v=null;try{j=(await $("/api/v1/brains/share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_,description:f,visibility:t,lessons:h})})).share_id??null,j&&(v=R(`/brain/share/${j}`,"brain-share"))}catch(o){const d=o.message??"";if(d.includes("404")||d.includes("not found")||d.includes("ECONNREFUSED")){const b=JSON.stringify({title:_,description:f,visibility:t,lessons:h,exported_at:new Date().toISOString()},null,2);return[`\u{1F4E4} **brain_share** \u2014 exported ${h.length} lesson${h.length!==1?"s":""}`,"","\u26A0\uFE0F The public share API is not yet available. Here is your portable snapshot:","","```json",b.slice(0,3e3)+(b.length>3e3?`
|
|
4
4
|
... (truncated)`:""),"```","","_To import this on another Brain, use `brain_import` with the JSON payload._",...T].join(`
|
|
5
|
-
`)}return`\u274C brain_share failed: ${o.message}`}const k=h.slice(0,5).map(o=>` ${o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F"} \`${o.topic}\``);try{const o=JSON.stringify({share_id:j,title:_,visibility:t,lesson_count:h.length,created_at:new Date().toISOString()});await
|
|
6
|
-
`)}case"brain_import":{const{instance_id:
|
|
7
|
-
`):`\u274C brain_import failed: ${k.message}`}const l=c.lessons??[];if(l.length===0)return`\u26A0\uFE0F Share \`${r}\` exists but contains no lessons.`;const _=await
|
|
8
|
-
`)}case"brain_share_list":{const{instance_id:
|
|
9
|
-
`);const
|
|
10
|
-
`)}case"brain_unshare":{const{instance_id:
|
|
11
|
-
`)}return`\u274C brain_unshare failed: ${t}`}const u=await
|
|
12
|
-
`)}case"brain_discover":{const{query:
|
|
13
|
-
`):`\u274C brain_discover failed: ${r}`}if(e.length===0)return[`\u{1F50D} **brain_discover** \u2014 no public Brains found ${
|
|
14
|
-
`);const t=[`\u{1F50D} **brain_discover**${
|
|
15
|
-
`)}case"brain_seed_starter":{const{instance_id:
|
|
16
|
-
`);const r=Array.isArray(a)&&a.length>0?a:void 0,c=r?x.filter(
|
|
17
|
-
`);if(u){const
|
|
18
|
-
`)}const l=new Date().toISOString();let _=0,f=0;for(const
|
|
5
|
+
`)}return`\u274C brain_share failed: ${o.message}`}const k=h.slice(0,5).map(o=>` ${o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F"} \`${o.topic}\``);try{const o=JSON.stringify({share_id:j,title:_,visibility:t,lesson_count:h.length,created_at:new Date().toISOString()});await n.rpush("cachly:brain:shares",o),await n.ltrim("cachly:brain:shares",-20,-1)}catch{}return[`\u{1F4E4} **brain_share** \u2014 ${h.length} lesson${h.length!==1?"s":""} shared`,"",`**Share ID:** \`${j}\``,`**URL:** ${v}`,`**Title:** ${_}`,`**Visible:** ${t}`,"","**Sample lessons:**",...k,h.length>5?` _...and ${h.length-5} more_`:"","","**Anyone can import this Brain with:**",`\`brain_import(instance_id="<their-id>", share_id="${j}")\``,"","_To list all your shares, run `brain_share_list`._",...T.length?["",...T]:[]].filter(o=>o!=="").join(`
|
|
6
|
+
`)}case"brain_import":{const{instance_id:i,share_id:a,topic_prefix:u="",min_confidence:e=0,dry_run:t=!1,overwrite:s=!1}=y;if(!i)return"\u26A0\uFE0F `brain_import` requires `instance_id`.";if(!a)return"\u26A0\uFE0F `brain_import` requires `share_id`. Get one from `brain_share`.";const r=a.replace(/^.*\/brain\/share\//,"").trim();let c;try{c=await $(`/api/v1/brains/share/${r}`)}catch(k){const o=k.message??"";return o.includes("404")||o.includes("not found")?["\u274C **brain_import** \u2014 share not found","",`Share ID \`${r}\` does not exist or has been removed.`,"","Ask the Brain owner to re-run `brain_share` and share the new ID with you."].join(`
|
|
7
|
+
`):`\u274C brain_import failed: ${k.message}`}const l=c.lessons??[];if(l.length===0)return`\u26A0\uFE0F Share \`${r}\` exists but contains no lessons.`;const _=await g(i);let f=0,n=0,p=0;const w=[];let m=0,S=0;const h=I({title:c.title??""}),T=h.felder.title||r;for(const k of l){if((k.confidence??1)<e){n++;continue}const o=I(k);o.geschwaerzt.length&&m++,o.verdacht.length&&S++;const d=o.verdacht.length?{...o.felder,tags:L(o.felder.tags,o.verdacht)}:o.felder,b=u?`${u}:${d.topic}`:d.topic,B=`cachly:lesson:best:${b}`;if(!s&&await _.get(B)){p++;continue}const A=JSON.stringify({...d,topic:b,imported_from:r,imported_at:new Date().toISOString()});if(!t){await _.set(B,A);const N=`cachly:lessons:${b}`;await _.rpush(N,A),await _.ltrim(N,-100,-1),await _.expire(N,90*86400)}if(f++,w.length<6){const N=d.outcome==="success"?"\u2705":d.outcome==="failure"?"\u274C":"\u26A0\uFE0F";w.push(` ${N} \`${b}\` \u2014 ${(d.what_worked??d.what_failed??"").slice(0,80)}`)}}if(!t&&f>0)try{const k=JSON.stringify({share_id:r,title:h.felder.title||void 0,...h.verdacht.length?{verdacht:h.verdacht}:{},imported:f,skipped:n,conflicts:p,topic_prefix:u,imported_at:new Date().toISOString()});await _.rpush("cachly:brain:imports",k),await _.ltrim("cachly:brain:imports",-20,-1)}catch{}const v=[`\u{1F4E5} **brain_import${t?" (DRY RUN \u2014 no writes)":""}** \u2014 from "${T}"`,"",`**Share ID:** \`${r}\``,`**Lessons imported:** ${f}`,...n>0?[`**Skipped (low confidence):** ${n}`]:[],...p>0?[`**Skipped (already exist):** ${p} _(pass \`overwrite=true\` to replace)_`]:[],...K(m,S,`${l.length} entries`),...U(h,"notiz"),""];return w.length>0&&(v.push("**Sample lessons imported:**",...w),f>6&&v.push(` _...and ${f-6} more_`)),f>0&&!t?v.push("",'\u2705 Brain updated \u2014 use `smart_recall(query="...")` to query the new knowledge.'):t?v.push("","_Remove `dry_run=true` to actually import these lessons._"):f===0&&p>0&&v.push("","\u2139\uFE0F All lessons already exist in your Brain. Pass `overwrite=true` to update them."),v.join(`
|
|
8
|
+
`)}case"brain_share_list":{const{instance_id:i}=y;if(!i)return"\u26A0\uFE0F `brain_share_list` requires `instance_id`.";const a=await g(i);let u=[];try{u=(await a.lrange("cachly:brain:shares",0,-1)).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean)}catch{}let e=[];try{e=(await $("/api/v1/brains/share")).shares??[]}catch{}const t=e.length>0?e:u;if(t.length===0)return["\u{1F4E4} **brain_share_list** \u2014 no shares yet","","You haven't shared any Brain snapshots from this instance.","",`Create one with: \`brain_share(instance_id="${i}", title="My Patterns")\``].join(`
|
|
9
|
+
`);const s=[`\u{1F4E4} **Your Brain Shares** (${t.length})`,"","| # | Title | Lessons | Visibility | Created |","|---|-------|---------|------------|---------|"];for(const[c,l]of t.entries()){const _=new Date(l.created_at),f=isNaN(_.getTime())?l.created_at:_.toISOString().slice(0,10),n=l.visibility==="public"?"\u{1F310} public":"\u{1F517} unlisted";s.push(`| ${c+1} | ${l.title??"\u2014"} | ${l.lesson_count??"?"} | ${n} | ${f} |`)}const r=t[t.length-1];return s.push("",`**Import command:** \`brain_import(instance_id="<their-id>", share_id="${r?.share_id??"..."}")\``,`**Revoke:** \`brain_unshare(instance_id="${i}", share_id="<id>")\``),s.join(`
|
|
10
|
+
`)}case"brain_unshare":{const{instance_id:i,share_id:a}=y;if(!i)return"\u26A0\uFE0F `brain_unshare` requires `instance_id`.";if(!a)return"\u26A0\uFE0F `brain_unshare` requires `share_id`.";try{await $(`/api/v1/brains/share/${a}`,{method:"DELETE"})}catch(e){const t=e.message??"";if(t.includes("404")||t.includes("not found"))return`\u274C Share \`${a}\` not found \u2014 it may have already been removed.`;if(t.includes("ECONNREFUSED")||t.includes("fetch failed")){const s=await g(i);try{const c=(await s.lrange("cachly:brain:shares",0,-1)).filter(l=>{try{return JSON.parse(l).share_id!==a}catch{return!0}});await s.del("cachly:brain:shares");for(const l of c)await s.rpush("cachly:brain:shares",l)}catch{}return["\u26A0\uFE0F **brain_unshare** \u2014 removed from local log","",`API unreachable \u2014 removed \`${a}\` from your local share registry.`,"The public link may still be accessible until the API confirms deletion."].join(`
|
|
11
|
+
`)}return`\u274C brain_unshare failed: ${t}`}const u=await g(i);try{const t=(await u.lrange("cachly:brain:shares",0,-1)).filter(s=>{try{return JSON.parse(s).share_id!==a}catch{return!0}});await u.del("cachly:brain:shares");for(const s of t)await u.rpush("cachly:brain:shares",s)}catch{}return["\u{1F5D1}\uFE0F **brain_unshare** \u2014 share revoked","",`Share \`${a}\` has been deleted. The public link is no longer accessible.`,"","_Anyone who already imported this Brain keeps their local copy._"].join(`
|
|
12
|
+
`)}case"brain_discover":{const{query:i="",topic:a="",limit:u=10}=y;let e=[];try{const s=new URLSearchParams;i&&s.set("q",i),a&&s.set("topic",a),s.set("limit",String(u)),e=await $(`/api/v1/brains/discover?${s.toString()}`)}catch(s){const r=s.message??"";return r.includes("404")||r.includes("ECONNREFUSED")||r.includes("fetch failed")?["\u{1F50D} **brain_discover** \u2014 marketplace not yet live","","The public Brain marketplace is coming soon.","","**In the meantime:**",' \u2022 Share your Brain: `brain_share(instance_id="...", visibility="public")`',' \u2022 Import by ID: `brain_import(instance_id="...", share_id="<id>")`',` \u2022 Community index: ${R("/brains","brain-discover")}`].join(`
|
|
13
|
+
`):`\u274C brain_discover failed: ${r}`}if(e.length===0)return[`\u{1F50D} **brain_discover** \u2014 no public Brains found ${i?`matching "${i}"`:a?`in topic "${a}"`:""}`.trim(),"",'Be the first! `brain_share(instance_id="...", visibility="public")`'].join(`
|
|
14
|
+
`);const t=[`\u{1F50D} **brain_discover**${i?` \u2014 "${i}"`:""}${a?` \xB7 topic: ${a}`:""} (${e.length} result${e.length!==1?"s":""})`,""];for(const[s,r]of e.entries()){const c=new Date(r.created_at),l=isNaN(c.getTime())?"":` \xB7 ${c.toISOString().slice(0,10)}`,_=r.imports!=null?` \xB7 ${r.imports} imports`:"",f=r.topics?.length?` \xB7 topics: ${r.topics.slice(0,4).join(", ")}`:"",n=r.author?` by **${r.author}**`:"";t.push(`**${s+1}. ${r.title}**${n}`,` \u{1F4DA} ${r.lesson_count} lessons${f}${_}${l}`,r.description?` _${r.description.slice(0,120)}_`:"",` \`brain_import(instance_id="...", share_id="${r.share_id}")\``,"")}return t.push(`_Browse more at ${R("/brains","brain-discover")}_`),t.filter(s=>s!==" ").join(`
|
|
15
|
+
`)}case"brain_seed_starter":{const{instance_id:i,topic_filter:a,dry_run:u=!1,force:e=!1}=y;if(!i)return"\u26A0\uFE0F `brain_seed_starter` requires `instance_id`.";const t=await g(i),s=await t.get(`cachly:brain:starter_seeded:${i}`);if(s&&!e&&!u)return["\u{1F331} **brain_seed_starter** \u2014 already seeded","",`This Brain was seeded with the starter corpus on ${s}.`,"","Pass `force=true` to re-seed (existing starter lessons will be refreshed)."].join(`
|
|
16
|
+
`);const r=Array.isArray(a)&&a.length>0?a:void 0,c=r?x.filter(n=>r.some(p=>n.topic.includes(p)||n.tags.some(w=>w.includes(p)))):x;if(c.length===0)return["\u{1F331} **brain_seed_starter** \u2014 no matching starter lessons","",`No starter lessons match filter: ${r?.join(", ")}.`,`Available topics: ${x.map(n=>`\`${n.topic}\``).join(", ")}`].join(`
|
|
17
|
+
`);if(u){const n=c.slice(0,8).map(p=>` \u2705 \`${p.topic}\` \u2014 ${p.what_worked.slice(0,70)}\u2026`);return[`\u{1F331} **brain_seed_starter (DRY RUN)** \u2014 would seed ${c.length} lesson${c.length!==1?"s":""}`,"",...n,c.length>8?` _...and ${c.length-8} more_`:"","","_Remove `dry_run=true` to seed these into the Brain._"].filter(p=>p!=="").join(`
|
|
18
|
+
`)}const l=new Date().toISOString();let _=0,f=0;for(const n of c){const p=`cachly:lesson:best:${n.topic}`;if(!e){const S=await t.get(p);if(S){const h=E(S,null);if(h&&h.source!=="starter"){f++;continue}}}const w=JSON.stringify({topic:n.topic,outcome:n.outcome,what_worked:n.what_worked,what_failed:n.what_failed,ctx:n.ctx,tags:n.tags,confidence:n.confidence,recall_count:0,source:"starter",ts:l,verified_at:l,version:3});await t.set(p,w),await t.sadd(J,n.topic).catch(()=>{});const m=`cachly:lessons:${n.topic}`;await t.rpush(m,w),await t.ltrim(m,-100,-1),await t.expire(m,90*86400),_++}return await t.set(`cachly:stats:born_at:${i}`,l,"EX",365*86400,"NX").catch(()=>{}),await t.set(`cachly:brain:starter_seeded:${i}`,l,"EX",365*86400),["\u{1F331} **brain_seed_starter** \u2014 Brain seeded","",`**${_}** universal engineering lesson${_!==1?"s":""} added${f>0?` (${f} skipped \u2014 your own lessons take priority)`:""}.`,"","Your Brain now answers common questions out of the box:",' \u2022 `smart_recall(query="docker build slow")`',' \u2022 `smart_recall(query="pod OOMKilled")`',' \u2022 `smart_recall(query="jwt token rejected")`',"",'_Starter lessons are tagged `source: "starter"` and never override your own._',"_They're replaced as you learn project-specific lessons on the same topics._"].join(`
|
|
19
19
|
`)}default:return null}}export{W as SHARE_TOOL_NAMES,q as STARTER_CORPUS_SIZE,Q as handleShareTool};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{McpError as I,ErrorCode as P}from"@modelcontextprotocol/sdk/types.js";import{calculateConfidence as M}from"../confidence.js";import{ckgSlug as B}from"../ckg.js";import{keywordSearch as O}from"../search.js";import{safeJsonParse as S}from"../utils.js";import{sofortAntwortNeuesBrain as K}from"../leeres-brain.js";import{fuerEigenenSpeicher as R,fuerWeitergabe as L,markiert as D,weitergabeHinweis as E,zaehlHinweise as A}from"../schreibtor.js";async function q(T,y,k,$,a){const e=(await a(`/api/v1/instances/${T}`).catch(()=>null))?.org_id;if(!e)return null;let r=null;try{r=await a(`/api/v1/orgs/${e}/brain/predict`,{method:"POST",body:JSON.stringify({context:y,top_k:k})})}catch{return null}return!r||!r.warnings||r.warnings.length===0?null:await z(y,r,$,a)}async function W(T,y,k){const $=y.warnings[0]?.problem||T;if(!$)return[];try{const a=await k(`/api/v1/syndication/search?q=${encodeURIComponent($)}&limit=3`),o=new Set(y.warnings.map(e=>e.problem));return(a.results??[]).filter(e=>!!e.topic&&!!e.what_worked&&!o.has(e.topic)).slice(0,3).map(e=>({topic:e.topic,what_worked:e.what_worked.slice(0,160)}))}catch{return[]}}async function z(T,y,k,$){const a=[`\u{1F52E} **Org Brain Predict: "${T}"**`,""];for(const o of y.warnings){const e=Math.max(0,o.team_span-1),r=o.recurrence.reduce((p,t)=>p+(t.count??0),0),c=o.severity==="critical"?"\u{1F534}":o.severity==="major"?"\u{1F7E0}":"\u{1F7E1}";o.team_span>=2?a.push(`\u26A0\uFE0F **CROSS-TEAM RISK** \u2014 this pattern failed ${r}\xD7 across ${e} other team${e===1?"":"s"}:`):a.push(`\u26A0\uFE0F **RISK** \u2014 this pattern failed ${r}\xD7 before:`),a.push(` ${c} problem: \`${o.problem}\``);for(const p of o.recurrence.slice(0,6)){const t=p.last_seen?` (last: ${p.last_seen.slice(0,10)})`:"";a.push(` \u2022 ${p.team} \xD7${p.count}${t}`)}const d=o.fixes[0];if(d){const p=Math.round((d.confidence??0)*100),t=d.source_team?` (${d.source_team})`:"";a.push(` \u2705 Proven fix \u2014 ${p}% confidence, confirmed ${d.confirm_count}\xD7${t}:`),a.push(` ${d.summary}`)}a.push("")}if(k==="org+commons"){const o=await W(T,y,$);if(o.length>0){a.push("\u{1F310} **From the public Knowledge Commons** (cross-org, lower-signal):");for(const e of o)a.push(` \u2022 \`${e.topic}\` \u2014 ${e.what_worked}`);a.push("")}}return a.push('\u{1F4A1} Heeded the warning? `learn_from_attempts(..., tags=["prevented-by-org-graph"])` \u2192 counts as a prevented cross-team mistake.'),a.join(`
|
|
2
|
-
`)}const V=new Set(["syndicate","syndicate_search","syndicate_stats","syndicate_trending","brain_search","ckg_inspect","brain_predict","brain_plan","brain_marketplace","brain_install","brain_conflicts","brain_resolve_conflict","brain_confirm_ci","brain_briefing"]);async function Q(T,y,k,$){switch(T){case"syndicate":{const{topic:a,outcome:o="success",what_worked:e,what_failed:r="",severity:c="minor",tags:d=[],scope:p="public"}=y;if(!a||!e)throw new I(P.InvalidParams,"topic and what_worked are required");const t=L({topic:a,what_worked:e,what_failed:r,tags:d},p==="org"?"
|
|
2
|
+
`)}const V=new Set(["syndicate","syndicate_search","syndicate_stats","syndicate_trending","brain_search","ckg_inspect","brain_predict","brain_plan","brain_marketplace","brain_install","brain_conflicts","brain_resolve_conflict","brain_confirm_ci","brain_briefing"]);async function Q(T,y,k,$){switch(T){case"syndicate":{const{topic:a,outcome:o="success",what_worked:e,what_failed:r="",severity:c="minor",tags:d=[],scope:p="public"}=y;if(!a||!e)throw new I(P.InvalidParams,"topic and what_worked are required");const t=L({topic:a,what_worked:e,what_failed:r,tags:d},p==="org"?"the org":"the Commons");if(!t.ok)return t.meldung;const s={...t.felder,outcome:o,severity:c,scope:p},f=await $("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify(s)}),h=p==="org"?"\u{1F3E2} org-private":"\u{1F310} global commons",u=f.deduped?`
|
|
3
3
|
> \u267B\uFE0F Duplicate detected \u2014 trust score incremented for the existing lesson.`:"";return[`${p==="org"?"\u{1F3E2}":"\u{1F310}"} **Lesson syndicated to the ${p==="org"?"org Knowledge Commons":"global Knowledge Commons"}**${u}`,"",`**ID:** \`${f.id}\``,`**Topic:** \`${f.topic}\` \xB7 **Outcome:** ${f.outcome} \xB7 **Scope:** ${h}`,"",p==="org"?'This lesson is visible only within your organisation. Use `syndicate_search(scope="org")` to find it.':"Your lesson is now searchable by every AI brain in the network.","When another instance confirms it works, its trust score rises \u2014 and so does your contributor reputation.","",`**Tip:** Use \`syndicate_search(q="${t.felder.topic}")\` to see all community lessons on this topic.`,...t.geschwaerzt.length?["",E(t.geschwaerzt)]:[]].join(`
|
|
4
4
|
`)}case"syndicate_search":{const{q:a="",limit:o=20,category:e="",scope:r=""}=y,c=new URLSearchParams;a&&c.set("q",a),e&&c.set("category",e),r&&c.set("scope",r),c.set("limit",String(Math.min(Math.max(1,o),50)));const d=await $(`/api/v1/syndication/search?${c}`);if(!d.results||d.results.length===0)return a?`No lessons found for "${a}" in the global Knowledge Commons yet.
|
|
5
5
|
|
|
@@ -31,7 +31,7 @@ No predictions yet \u2014 the brain hasn't seen this domain.`);if(c)return c;con
|
|
|
31
31
|
`)}case"brain_marketplace":{const{min_confirms:a=1}=y,o=new URLSearchParams;a&&a>1&&o.set("min_confirms",String(a));const e=await $(`/api/v1/syndication/brains${o.toString()?`?${o}`:""}`);if(!e.brains||e.brains.length===0)return["## \u{1F9E0} Domain Brain Marketplace","","No domain brains are available yet \u2014 the marketplace fills as the community","contributes verified lessons. Be an early contributor:",'`syndicate(topic="k8s:oom-kill", what_worked="raise memory limit + add probe")`'].join(`
|
|
32
32
|
`);const r=["## \u{1F9E0} Domain Brain Marketplace",`*${e.count} installable brain${e.count===1?"":"s"} \xB7 curated from the global Knowledge Commons*`,""];for(const c of e.brains){const d=c.curated?"\u2B50 curated":"community";r.push(`### ${c.icon} ${c.name} \`${c.slug}\``,`${c.description}`,`**${c.lesson_count}** lesson${c.lesson_count===1?"":"s"} \xB7 \u{1F91D} ${c.total_confirms} community confirm${c.total_confirms===1?"":"s"} \xB7 ${d}`,`Install: \`brain_install(slug="${c.slug}")\``,"")}return r.push("---","_Installed brains merge into your local Brain and surface in `smart_recall` \u2014 they never override your own lessons._"),r.join(`
|
|
33
33
|
`)}case"brain_install":{const{instance_id:a,slug:o,min_confirms:e=1,limit:r=200,dry_run:c=!1}=y,d=typeof o=="string"?o.trim():"";if(!d)throw new I(P.InvalidParams,"slug is required \u2014 run brain_marketplace() to see available domain brains");const p=new URLSearchParams;e&&e>1&&p.set("min_confirms",String(e)),r&&r!==200&&p.set("limit",String(Math.min(Math.max(1,r),500)));const t=await $(`/api/v1/syndication/brains/${encodeURIComponent(d)}${p.toString()?`?${p}`:""}`);if(!t.lessons||t.lessons.length===0)return`No installable lessons found for domain brain \`${d}\`. Run \`brain_marketplace()\` to see what's available.`;if(c)return[`## \u{1F4E6} ${t.name} (DRY RUN)`,`Would install **${t.lessons.length}** lesson${t.lessons.length===1?"":"s"} into your Brain.`,"",...t.lessons.slice(0,15).map(w=>` \u2022 \`${w.topic}\` \xB7 \u{1F91D} ${w.confirm_count}`),t.lessons.length>15?` \u2026and ${t.lessons.length-15} more`:"","",`Run without \`dry_run\` to install: \`brain_install(slug="${d}")\``].filter(Boolean).join(`
|
|
34
|
-
`);const s=await k(a),f=`marketplace:${d}`,h=new Date().toISOString();let u=0,l=0,n=0,i=0;for(const w of t.lessons){if(!w.topic||!w.what_worked){l++;continue}const g=(()=>{const C=S(w.tags,[]);return Array.isArray(C)?C.filter(N=>typeof N=="string"):[]})(),m=R({topic:w.topic,what_worked:w.what_worked,what_failed:w.what_failed??"",tags:g});m.geschwaerzt.length&&n++,m.verdacht.length&&i++;const _={...w,...m.felder},b=`cachly:lesson:best:${_.topic}`,x=await s.get(b);if(x){const C=S(x,null);if(C&&C.source!==f){l++;continue}}const v=JSON.stringify({topic:_.topic,outcome:_.outcome||"success",what_worked:_.what_worked,what_failed:_.what_failed||"",severity:_.severity||"minor",tags:D(m.felder.tags,m.verdacht),visibility:"team",confidence:M({ts:h,verified_at:h,recall_count:_.confirm_count}),recall_count:0,source:f,ts:h,verified_at:h,version:3});await s.set(b,v);const j=`cachly:lessons:${_.topic}`;await s.rpush(j,v),await s.ltrim(j,-100,-1),await s.expire(j,90*86400),u++}return await s.set(`cachly:stats:born_at:${a}`,h,"EX",365*86400,"NX").catch(()=>{}),[`## \u{1F4E6} Installed: ${t.name}`,"",`**${u}** lesson${u===1?"":"s"} merged into your Brain${l>0?` \xB7 ${l} skipped (your own lessons take priority)`:""}.`,"","They're live in `smart_recall` now \u2014 try a query in this domain:",` \u2022 \`smart_recall(query="${t.lessons[0]?.topic.split(":").pop()??"your problem"}")\``,"",`_Installed lessons are tagged \`source: "${f}"\` and never override your own. Re-run anytime to pull updates._`,...n+i>0?["",...A(n,i,`${t.lessons.length}
|
|
34
|
+
`);const s=await k(a),f=`marketplace:${d}`,h=new Date().toISOString();let u=0,l=0,n=0,i=0;for(const w of t.lessons){if(!w.topic||!w.what_worked){l++;continue}const g=(()=>{const C=S(w.tags,[]);return Array.isArray(C)?C.filter(N=>typeof N=="string"):[]})(),m=R({topic:w.topic,what_worked:w.what_worked,what_failed:w.what_failed??"",tags:g});m.geschwaerzt.length&&n++,m.verdacht.length&&i++;const _={...w,...m.felder},b=`cachly:lesson:best:${_.topic}`,x=await s.get(b);if(x){const C=S(x,null);if(C&&C.source!==f){l++;continue}}const v=JSON.stringify({topic:_.topic,outcome:_.outcome||"success",what_worked:_.what_worked,what_failed:_.what_failed||"",severity:_.severity||"minor",tags:D(m.felder.tags,m.verdacht),visibility:"team",confidence:M({ts:h,verified_at:h,recall_count:_.confirm_count}),recall_count:0,source:f,ts:h,verified_at:h,version:3});await s.set(b,v);const j=`cachly:lessons:${_.topic}`;await s.rpush(j,v),await s.ltrim(j,-100,-1),await s.expire(j,90*86400),u++}return await s.set(`cachly:stats:born_at:${a}`,h,"EX",365*86400,"NX").catch(()=>{}),[`## \u{1F4E6} Installed: ${t.name}`,"",`**${u}** lesson${u===1?"":"s"} merged into your Brain${l>0?` \xB7 ${l} skipped (your own lessons take priority)`:""}.`,"","They're live in `smart_recall` now \u2014 try a query in this domain:",` \u2022 \`smart_recall(query="${t.lessons[0]?.topic.split(":").pop()??"your problem"}")\``,"",`_Installed lessons are tagged \`source: "${f}"\` and never override your own. Re-run anytime to pull updates._`,...n+i>0?["",...A(n,i,`${t.lessons.length} lessons`)]:[]].join(`
|
|
35
35
|
`)}case"brain_conflicts":{const{instance_id:a}=y,o=await k(a),e=[],r=o.scanStream({match:"cachly:ckg:conflict:*",count:100});await new Promise((f,h)=>{r.on("data",u=>e.push(...u)),r.on("end",f),r.on("error",h)});const c=[];if(e.length>0){const f=await o.mget(...e);for(const h of f){const u=S(h??null,null);u&&!u.resolved&&c.push(u)}}const d=[],p=o.scanStream({match:"cachly:agents:active:*",count:100});await new Promise((f,h)=>{p.on("data",u=>d.push(...u)),p.on("end",f),p.on("error",h)});const t=[];if(d.length>0){const f=await o.mget(...d);for(const h of f){const u=S(h??null,null);u&&t.push(u)}}const s=["## \u2694\uFE0F Brain Conflicts & Live Agents",""];if(s.push(`**\u{1F916} Active agents (last 1h):** ${t.length}`),t.length>0)for(const f of t.sort((h,u)=>u.ts.localeCompare(h.ts)).slice(0,10)){const h=Math.round((Date.now()-new Date(f.ts).getTime())/6e4);s.push(` - **${f.author}** \u2014 last: \`${f.last_topic??"?"}\` (${f.last_outcome??"?"}, ${h}m ago)`)}if(s.push(""),c.length===0)return s.push("**\u2705 No unresolved belief conflicts.** The Brain is in consensus."),s.join(`
|
|
36
36
|
`);s.push(`**\u26A0\uFE0F Unresolved belief conflicts:** ${c.length}`),s.push(""),s.push("| Topic | Confirmed fix | Contradicted by | Detected |"),s.push("|---|---|---|---|");for(const f of c.sort((h,u)=>u.detected_at.localeCompare(h.detected_at)).slice(0,20)){const h=Math.round((Date.now()-new Date(f.detected_at).getTime())/36e5);s.push(`| \`${f.topic}\` | ${(f.fix_confidence*100).toFixed(0)}% (n=${f.fix_trials}) | ${f.reported_by??"unknown"} | ${h}h ago |`)}return s.push(""),s.push(`_Arbitrate with \`brain_resolve_conflict(instance_id="${a}", topic="<topic>", winner="success"|"failure")\`._`),s.join(`
|
|
37
37
|
`)}case"brain_resolve_conflict":{const{instance_id:a,topic:o,winner:e,resolved_by:r="human"}=y;if(!o||!o.trim())throw new I(P.InvalidParams,"topic is required");if(e!=="success"&&e!=="failure")throw new I(P.InvalidParams,'winner must be "success" or "failure"');const c=await k(a),d=B(o),p=`cachly:ckg:conflict:${d}`,t=await c.get(p);if(!t)return`\u{1F4ED} No active conflict found for \`${o}\`. Run \`brain_conflicts(instance_id="${a}")\` to list open conflicts.`;let s=0;if(e==="failure"){const n=await c.smembers(`cachly:ckg:idx:from:${d}`);for(const i of n){const w=await c.get(i);if(!w)continue;const g=S(w,null);!g||g.edgeType!=="fixes"||(g.confidence=.1,await c.set(i,JSON.stringify(g)),s++)}}let f=!1;const h=`cachly:lesson:best:${o}`,u=await c.get(h);if(u){const n=S(u,null);n&&n.outcome===e?n.state==="provisional"&&(n.state="active",n.verified_at=new Date().toISOString(),await c.set(h,JSON.stringify(n))):n&&n.outcome&&n.outcome!==e&&(n.state="archived",n.audit_trail=[...Array.isArray(n.audit_trail)?n.audit_trail:[],{ts:new Date().toISOString(),action:"conflict_loser_archived",resolved_by:r}],await c.set(h,JSON.stringify(n)),f=!0)}const l=S(t,null)??{};return l.resolved=!0,l.winner=e,l.resolved_by=r,l.resolved_at=new Date().toISOString(),await c.set(p,JSON.stringify(l),"EX",3600*24*30),[`## \u2705 Conflict resolved \u2014 \`${o}\``,"",`**Winner:** ${e==="success"?"\u2705 success (fix is valid)":"\u274C failure (fix retired)"}`,`**Resolved by:** ${r}`,"",`- CKG \`fixes\` edges decayed: **${s}**`,`- Losing lesson archived: **${f?"yes":"no"}**`,"",e==="failure"?"_The contradicted fix is retired. smart_recall will stop surfacing it; future attempts start fresh._":"_The fix is reaffirmed. The contradicting failure no longer blocks recall._"].join(`
|