@cachly-dev/mcp-server 0.10.188 → 0.10.190
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/einblendung-kern.js +1 -1
- package/dist/src/einblendung.js +6 -6
- package/dist/src/handlers/advanced.js +11 -11
- package/dist/src/handlers/brain.js +69 -67
- package/dist/src/handlers/fedbrain.js +40 -39
- package/dist/src/handlers/roadmap.js +10 -10
- package/dist/src/handlers/share.js +19 -19
- package/dist/src/handlers/syndicate.js +35 -35
- package/dist/src/handlers/team.js +58 -56
- package/dist/src/schreibtor.js +1 -0
- package/dist/src/tuersteher.js +1 -1
- package/dist/src/verdacht-marke.js +1 -0
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +21 -21
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,40 +1,41 @@
|
|
|
1
|
-
import{createHmac as
|
|
2
|
-
`);const
|
|
3
|
-
`);const
|
|
4
|
-
`)}case"cls_ingest":{const{instance_id:w,source:
|
|
5
|
-
`)}if(
|
|
6
|
-
`)}if(
|
|
7
|
-
`)}return`\u274C Unknown CLS source: "${
|
|
8
|
-
`];if(
|
|
9
|
-
`)}case"fedbrain_contribute":{const{instance_id:w,lesson_key:
|
|
10
|
-
`)}case"fedbrain_search":{const{instance_id:w,query:
|
|
11
|
-
`);const
|
|
12
|
-
`];for(const
|
|
13
|
-
`)}case"fedbrain_confirm":{const{instance_id:w,id:
|
|
14
|
-
`);const e=await
|
|
15
|
-
`)}case"fedbrain_status":{const{instance_id:w}=
|
|
16
|
-
`,`### \u{1F4E4} Contributed Lessons: ${
|
|
17
|
-
`)}case"brain_federate":{const{instance_id:w,source:
|
|
18
|
-
`);let
|
|
19
|
-
`)}case"crystal_view":{const{instance_id:w,show_raw:
|
|
20
|
-
`);const e=R(
|
|
21
|
-
`)}case"compact_recover":{const{instance_id:w,focus:
|
|
22
|
-
`];
|
|
23
|
-
`);const e=await
|
|
24
|
-
`)}case"brain_from_git":{const w=Date.now(),{instance_id:
|
|
25
|
-
`)){const
|
|
26
|
-
\u{1F9E0} brain_from_git: processing ${
|
|
27
|
-
`);for(let
|
|
28
|
-
`),
|
|
1
|
+
import{createHmac as me}from"node:crypto";import{ckgSlug as b,extractProblemConcept as pe,ckgUpsertNode as M,ckgUpdateEdge as J,ckgUpsertPersonNode as ge,ckgUpsertFileNode as _e,ckgRecordCollaboration as we}from"../ckg.js";import{safeJsonParse as R,normalizeGitPath as ye}from"../utils.js";import{buildClsPostCommitHook as $e}from"../cls-hook.js";import{alsShellWort as be,beginntMitBindestrich as ke,gitLesen as re,instanzIdFuerSkript as Se,istCommitHash as Ce,pruefeOrdner as xe}from"../git-ohne-shell.js";import{installBrainWatchHook as ve}from"../brain-watch-hook.js";import{keywordSearch as je,wortindexEntwerten as Oe}from"../search.js";import{buildFirstContactReport as ce,suggestRecallQueries as Ne}from"../first-contact.js";import{classifyCommit as Ie,extractDomain as Ae}from"../commit-art.js";import{VEKTOR_NACHTRAG as Le}from"../bedeutung.js";import{VERDACHT_TAG as De,fuerEigenenSpeicher as q,fuerWeitergabe as le,hinweise as Y,istMarkiert as Re,markiert as K,weitergabeHinweis as ue,zaehlHinweise as U}from"../schreibtor.js";let Te=null,Me=null,Q=0;const Je=10,de=[];function Pe(){return Q<Je?(Q++,Promise.resolve()):new Promise(E=>de.push(E))}function Be(){const E=de.shift();E?E():Q--}const Xe=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 Ze(E,A,D,G){switch(E){case"madc_deliberate":{const{instance_id:w,topic:c}=A,u=await D(w),e=(await u.lrange(`cachly:lessons:${c}`,0,-1)).map(g=>{try{return JSON.parse(g)}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 n=[{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"]}],d=c.split(":")[0]??"",r=n.filter(g=>g.domains.some(S=>d===S||c.includes(S))),f=r.length>0?r:n,l=new Map;for(const g of f){let S=0;for(const C of g.domains){const x=[],O=u.scanStream({match:`cachly:ckg:node:${C}*`,count:50});await new Promise(($,v)=>{O.on("data",z=>x.push(...z)),O.on("end",$),O.on("error",v)}),S+=x.length}l.set(g.name,S)}const a=e.filter(g=>g.outcome==="success"||g.outcome==="partial"),t=e.filter(g=>g.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 s=[];for(const g of f){const S=l.get(g.name)??0;let C,x;S<2?(C="abstain",x="insufficient domain coverage"):a.length>=t.length*2?(C="success",x=`${a.length}/${e.length} entries confirm success`):t.length>=a.length*2?(C="failure",x=`${t.length}/${e.length} entries confirm failure`):(C="abstain",x=`contested (${a.length} success vs ${t.length} failure)`),s.push({agent:g.name,vote:C,coverage:S,reason:x})}const i=s.filter(g=>g.vote==="success").length,h=s.filter(g=>g.vote==="failure").length,m=s.filter(g=>g.vote==="abstain").length;let p,y;i>0&&h===0?(p="unanimous_success",y=`\u2705 **Unanimous: SUCCESS** \u2014 ${i} agent(s) confirm, ${m} abstain`):h>0&&i===0?(p="unanimous_failure",y=`\u274C **Unanimous: FAILURE** \u2014 ${h} agent(s) confirm, ${m} abstain`):(p="contested",y=`\u26A0\uFE0F **CONTESTED** \u2014 ${i} success votes, ${h} failure votes, ${m} abstain`);const _=b(`resolution:${c}`),k={id:_,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:p,topic:c,votes:{success:i,failure:h,abstain:m}};if(await u.set(`cachly:ckg:node:${_}`,JSON.stringify(k)),p==="contested")await J(u,b(c),"contradicts",_,!1);else{if(((p==="unanimous_success"?"failure":"success")==="failure"?t:a).length>0){const C=await u.smembers(`cachly:ckg:idx:from:${b(c)}`);for(const x of C){const O=await u.get(x);if(O)try{const $=JSON.parse(O);$.edgeType==="fixes"&&$.confidence>.15&&p==="unanimous_failure"&&($.confidence=.1,$.last_updated=new Date().toISOString(),await u.set(x,JSON.stringify($)))}catch{}}}await u.del(`cachly:ckg:conflict:${b(c)}`)}const j=[`\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}):**`,...s.map(g=>{const S=g.vote==="success"?"\u2705":g.vote==="failure"?"\u274C":"\u2B1C",C="\u2593".repeat(Math.min(g.coverage,5))+"\u2591".repeat(Math.max(0,5-g.coverage));return` ${S} **${g.agent}** [${C}] ${g.coverage} CKG edges \u2014 ${g.reason}`}),"",y,""];return p==="unanimous_success"?j.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${c}", outcome="success", ...)\``):p==="unanimous_failure"?j.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${c}")\``):j.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${b(c)}")\``),j.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${_}\``),j.join(`
|
|
4
|
+
`)}case"cls_ingest":{const{instance_id:w,source:c,payload:u}=A,o=q(u),e=o.felder,n=await D(w),d=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",s=`${t}:${b(f.slice(0,60))}`,i=b(s);await M(n,i,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",_=b(`file:${y}`);await M(n,_,"file",y),await J(n,i,"co-occurs",_,!0)}const h={topic:s,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"],o.verdacht),depends_on:[],recall_count:0,ts:d,verified_at:d,confidence:.6,audit_trail:[{ts:d,action:"cls_git_commit"}],version:3};return await n.rpush(`cachly:lessons:${s}`,JSON.stringify(h)),await n.get(`cachly:lesson:best:${s}`)||await n.set(`cachly:lesson:best:${s}`,JSON.stringify(h)),await n.rpush(r,JSON.stringify({source:c,payload:{message:f,sha:l},ts:d})),await n.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${l.slice(0,8)||"?"}\`: ${f.slice(0,80)}`,`Concept: \`${i}\` (${t}) \xB7 Files: ${a.length}`,"",`\u{1F578}\uFE0F CKG: \`${i}\` + ${a.length} file edges \xB7 Lesson: \`${s}\``,`\u{1F4A1} Inspect: \`ckg_inspect(concept="${t}")\``,...Y(o)].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??""),s=["failure","red","error"].includes(l)&&["success","green","passed"].includes(f),i=["success","green","passed"].includes(l)&&["failure","red","error"].includes(f),h=`ci:${b(a)}`,m=b(h);if(await M(n,m,"ci","job"),s){const y=b(`problem:${b(a)}`);await M(n,y,"problem","ci-failure"),await J(n,m,"fixes",y,!0);const _={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"],o.verdacht),depends_on:[],recall_count:0,ts:d,verified_at:d,confidence:.75,audit_trail:[{ts:d,action:"cls_ci_fixed"}],version:3};await n.rpush(`cachly:lessons:${h}`,JSON.stringify(_)),await n.set(`cachly:lesson:best:${h}`,JSON.stringify(_))}else if(i){const y=b(`cause:${b(a)}`);await M(n,y,"cause","ci-break"),await J(n,m,"causes",y,!1)}return await n.rpush(r,JSON.stringify({source:c,payload:{status:f,prev_status:l,job:a},ts:d})),await n.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ci_outcome**","",`${s?"\u2705 Fixed":i?"\u{1F534} Broken":"\u{1F4CA} Recorded"}: \`${a}\` \u2014 ${l||"?"} \u2192 ${f}`,s?"\u{1F527} CKG `fixes` edge added (75% confidence)":i?"\u26A1 CKG `causes` edge added":"\u{1F4CA} State recorded",`\u{1F4A1} Lesson: \`${h}\` | Predict: \`brain_predict(context="${a}")\``,...Y(s?o:{geschwaerzt:o.geschwaerzt,verdacht:[]})].join(`
|
|
6
|
+
`)}if(c==="ide_diagnostic"){const f=String(e.error??""),l=String(e.fix??""),a=String(e.file??""),t=pe(f)??"unknown-error",s=`debug:${b(t)}`,i=b(s),h=b(`problem:${t}`);await M(n,i,"debug","diagnostic"),await M(n,h,"problem","compiler-error"),await J(n,i,"fixes",h,!0);const m={topic:s,outcome:"success",what_worked:l,what_failed:f,context:`CLS/ide: ${a}`,severity:"minor",file_paths:a?[a]:[],commands:[],tags:K(["cls","ide-diagnostic"],o.verdacht),depends_on:[],recall_count:0,ts:d,verified_at:d,confidence:.65,audit_trail:[{ts:d,action:"cls_ide_diagnostic"}],version:3};return await n.rpush(`cachly:lessons:${s}`,JSON.stringify(m)),await n.get(`cachly:lesson:best:${s}`)||await n.set(`cachly:lesson:best:${s}`,JSON.stringify(m)),await n.rpush(r,JSON.stringify({source:c,payload:{error:f.slice(0,60),fix:l.slice(0,60),file:a},ts:d})),await n.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: \`${i}\` \u2192 fixes \u2192 \`${h}\` | Lesson: \`${s}\``,...Y(o)].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:u=["git","ci"]}=A,o=Array.isArray(u)?u:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
|
|
8
|
+
`];if(Se(w),o.includes("git")){const n=$e(w),d=be(`${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 ${d}`),e.push(`grep -q 'cachly CLS' ${d} || cat >> ${d} << 'HOOK'`),e.push(n),e.push("HOOK"),e.push(`chmod +x ${d}`),e.push("```"),e.push("After install: every `git commit` automatically updates your brain's CKG."),e.push("")}return o.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:u="public"}=A,o=await D(w),e=await o.get(`cachly:lesson:best:${c}`);if(!e)return`\u274C Lesson \`${c}\` not found. Store it first with \`learn_from_attempts\`.`;const n=R(e,null);if(!n)return`\u274C Lesson \`${c}\` data is corrupted. Re-store with \`learn_from_attempts\`.`;const d=le({topic:n.topic,what_worked:n.what_worked,what_failed:n.what_failed??"",tags:n.tags??[]},"die Commons");if(!d.ok)return d.meldung;if(Re(n))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={...n,...d.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=me("sha256",`cachly-fedbrain:${w}`).update(a).digest("hex").slice(0,16),s={cert_id:t,lesson_key:c,visibility:u,domain_fingerprint:l,contributed_at:new Date().toISOString(),confirm_count:0,trust_score:r.outcome==="success"?.85:.5};await o.set(`cachly:fedbrain:cert:${t}`,JSON.stringify(s)),await o.sadd("cachly:fedbrain:contributed",t);let i;try{await G("/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:u})}),i="\u2705 Contributed to global commons"}catch{i="\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: ${u}`,"",i,...d.geschwaerzt.length?[ue(d.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:u=[],limit:o=10}=A,e=await D(w),n=await e.smembers("cachly:fedbrain:contributed"),d=new Map;for(const s of n.slice(0,30)){const i=await e.get(`cachly:fedbrain:cert:${s}`);if(i)try{const h=JSON.parse(i);for(const m of(h.domain_fingerprint??"").split(",").filter(Boolean))d.set(m,(d.get(m)??0)+1)}catch{}}for(const s of Array.isArray(u)?u:[])d.set(s.toLowerCase(),(d.get(s.toLowerCase())??0)+2);let r=[],f=!1;try{const s=new URLSearchParams({q:c,limit:String(Math.min(o*2,50))});r=(await G(`/api/v1/syndication/search?${s}`)).results??[]}catch{f=!0;const s=[],i=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{i.on("data",p=>s.push(...p)),i.on("end",h),i.on("error",m)});for(const h of s.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(_=>_.length>2&&y.includes(_))&&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(s=>{const i=(s.domain_fingerprint??s.category??"").split(",").filter(Boolean),h=i.reduce((_,k)=>_+(d.get(k)??0),0),m=d.size>0?h/Math.max(1,d.size+i.length):0,p=Math.min(1,s.confirm_count/10),y=m*.4+p*.4+(s.outcome==="success"?.2:0);return{...s,weightedScore:y,isGoldStandard:!f&&s.confirm_count>=10}}).sort((s,i)=>i.weightedScore-s.weightedScore).slice(0,o),t=[`\u{1F310} **FedBrain Search: "${c}"** \u2014 ${a.length} result${a.length!==1?"s":""} (context-weighted)${l}
|
|
12
|
+
`];for(const s of a){const i=s.outcome==="success"?"\u2705":s.outcome==="failure"?"\u274C":"\u26A0\uFE0F",h=s.isGoldStandard?" \u{1F3C6} _Gold Standard_":!f&&s.confirm_count>=3?` \u2713${s.confirm_count}`:"",m=Math.round(s.weightedScore*100);t.push(`${i}${h} **\`${s.topic}\`** [ctx: ${m}%]`),s.what_worked&&t.push(` \u2705 ${s.what_worked.slice(0,150)}`),s.what_failed&&t.push(` \u274C ${s.what_failed.slice(0,80)}`),t.push(` _${s.confirm_count} confirm${s.confirm_count!==1?"s":""} | id: \`${s.id}\`_`,"")}if(d.size>0){const s=[...d.entries()].sort((i,h)=>h[1]-i[1]).slice(0,5).map(([i,h])=>`\`${i}\`(${h})`).join(", ");t.push(`\u{1F3AF} Your context: ${s}`)}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:u,outcome:o}=A;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 D(w),n=new Date().toISOString(),d=JSON.stringify({id:c,topic:u,outcome:o,ts:n});await e.rpush("cachly:fedbrain:confirmations",d),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const r=o==="worked",f=o==="partially_worked";u&&await J(e,b(u),"fixes",b(`syndicated:${u}`),r,f);let l;try{await G(`/api/v1/syndication/${encodeURIComponent(c)}/confirm`,{method:"POST"}),l="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",d),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: "${u??c}"** \u2192 ${o}`,"",l,"",u?`\u{1F578}\uFE0F CKG confidence ${r||f?"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:w}=A,c=await D(w),u=await c.smembers("cachly:fedbrain:contributed"),o=await c.lrange("cachly:fedbrain:confirmations",-10,-1),e=await c.llen("cachly:fedbrain:pending_confirms"),n=o.map(f=>{try{return JSON.parse(f)}catch{return null}}).filter(Boolean),d=[];for(const f of u.slice(0,15)){const l=await c.get(`cachly:fedbrain:cert:${f}`);if(l)try{const a=JSON.parse(l);d.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(d.length>0)for(const f of d){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: ${n.length}`),n.length>0)for(const f of n.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:u,min_confidence:o=.6,dry_run:e=!1}=A;if(w===c)return"\u274C Source and destination cannot be the same brain.";const n=await D(w),d=await D(c),r=u==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${u}*`,f=[],l=d.scanStream({match:r,count:100});if(await new Promise((k,j)=>{l.on("data",g=>f.push(...g)),l.on("end",k),l.on("error",j)}),f.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,s=0,i=0,h=0,m=0;const p=[];for(const k of f){const j=await d.get(k);if(!j)continue;let g;try{g=JSON.parse(j)}catch{continue}e||await n.set(k,j),a++;const S=await d.smembers(`cachly:ckg:idx:from:${g.id}`);for(const O of S){const $=await d.get(O);if(!$)continue;let v;try{v=JSON.parse($)}catch{continue}if(v.confidence<o){i++;continue}e||(await n.set(O,$),await n.sadd(`cachly:ckg:idx:from:${v.from}`,O),await n.sadd(`cachly:ckg:idx:to:${v.to}`,O)),t++}const C=`cachly:lesson:best:${g.id}`,x=await d.get(C);if(x){const O=R(x,null);if(!O||typeof O!="object")continue;const $=q(O);$.geschwaerzt.length&&h++,$.verdacht.length&&m++;const v=$.verdacht.length?{...$.felder,tags:K($.felder.tags,$.verdacht)}:$.felder;if(e||await n.set(C,JSON.stringify(v)),s++,p.length<8){const z=v.outcome==="success"?"\u2705":v.outcome==="failure"?"\u274C":"\u26A0\uFE0F";p.push(` ${z} \`${v.topic}\` \u2014 ${(v.what_worked??"").slice(0,80)}`)}}}if(!e){const k=JSON.stringify({source:c,domain:u,transferred_at:new Date().toISOString(),nodes:a,edges:t,lessons:s});await n.rpush("cachly:fedbrain:federations",k),await n.ltrim("cachly:fedbrain:federations",-50,-1)}const _=[`\u{1F9E0} **brain_federate: "${u}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${c}\``,`\u{1F4E5} Destination: \`${w}\``,`\u{1F50D} Domain filter: \`${u}\` | min_confidence: ${o}`,"","### Transfer Summary",` \u{1F578}\uFE0F CKG nodes: ${a}`,` \u{1F517} CKG edges: ${t} (${i} skipped, confidence < ${o})`,` \u{1F4DA} Lessons: ${s}`,...U(h,m,`${s} kopierten Lektionen`),""];return p.length>0&&(_.push("### Sample lessons transferred:",...p),s>p.length&&_.push(` _... and ${s-p.length} more_`),_.push("")),e?_.push("\u{1F4A1} Run without `dry_run: true` to apply the transfer."):(_.push(`\u2705 Transfer complete. Your brain now has the \`${u}\` knowledge from \`${c}\`.`),_.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${u}")\` | \`recall_best_solution(topic="${u}:...")\``)),_.join(`
|
|
19
|
+
`)}case"crystal_view":{const{instance_id:w,show_raw:c=!1}=A,u=await D(w),o=await u.get("cachly:crystal:latest");if(!o)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(o,null);if(!e)return"\u274C Memory Crystal data is corrupted. Re-create with `memory_crystalize()`.";const n=Math.floor((Date.now()-new Date(e.ts).getTime())/864e5),d=n<=7?"\u{1F7E2}":n<=30?"\u{1F7E1}":"\u{1F534}",r=[`\u{1F48E} **Memory Crystal: ${e.label}**`,"",`\u{1F4C5} Created: ${new Date(e.ts).toLocaleDateString("de-DE")} (${n}d ago ${d})`,`\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)}`);n>30&&r.push("",`\u26A0\uFE0F Crystal is ${n}d old \u2014 run \`memory_crystalize()\` to refresh it.`),c&&r.push("","```json",JSON.stringify(e,null,2),"```");const f=await u.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(s=>`@${s}`).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=""}=A,u=await D(w),o=[`\u{1F501} **Compact Recovery Briefing**
|
|
22
|
+
`];o.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*
|
|
23
|
+
`);const e=await u.get("cachly:crystal:latest");if(e){const t=R(e,null);if(t){o.push(`### \u{1F48E} Memory Crystal: ${t.label}`),o.push(`Compressed from ${t.session_count} sessions, ${t.lesson_count} lessons.`);const s=c?t.top_patterns.filter(i=>i.category.toLowerCase().includes(c.toLowerCase())||i.insight.toLowerCase().includes(c.toLowerCase())).slice(0,4):t.top_patterns.slice(0,4);for(const i of s)o.push(` \u2022 **${i.category}**: ${i.insight.slice(0,100)}`);o.push("")}}const n=await u.get("cachly:session:last");if(n){const t=R(n,null);t&&(o.push("### \u{1F550} Last Session"),t.focus&&o.push(`Focus: _${t.focus}_`),t.summary&&o.push(`Summary: ${t.summary.slice(0,300)}`),o.push(""))}const d=await u.get("cachly:session:handoff");if(d){const t=R(d,null);if(t){if(o.push("### \u{1F4CB} Handoff (from last window)"),t.context_summary&&o.push(`Context: ${t.context_summary.slice(0,200)}`),t.remaining_tasks?.length){o.push("Remaining tasks:");for(const s of t.remaining_tasks.slice(0,5))o.push(` \u2022 ${s}`)}t.instructions&&o.push(`\u26A0\uFE0F Instructions: ${t.instructions.slice(0,200)}`),t.blocked_on&&o.push(`\u{1F6A7} Blocked on: ${t.blocked_on}`),o.push("")}}const r=await u.get("cachly:ctx:wip-registry");if(r){const t=R(r,null);t?.content&&(o.push("### \u{1F527} WIP Registry"),o.push(t.content.slice(0,400)),o.push(""))}const f=[],l=u.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((t,s)=>{l.on("data",i=>f.push(...i)),l.on("end",t),l.on("error",s)});const a=[];for(const t of f.slice(0,30)){const s=await u.get(t);if(s)try{const i=JSON.parse(s);(i.status==="in_progress"||i.status==="blocked")&&a.push({title:i.title??t,status:i.status,priority:i.priority})}catch{}}if(a.length>0){o.push("### \u{1F6A7} Open Items");for(const t of a.slice(0,5))o.push(` \u2022 [${t.status}] ${t.title}`);o.push("")}if(c){const t=[],s=u.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{s.on("data",p=>t.push(...p)),s.on("end",h),s.on("error",m)});const i=[];for(const h of t){const m=await u.get(h);if(m)try{const p=JSON.parse(m);p.topic.toLowerCase().includes(c.toLowerCase())&&p.what_worked&&i.push({topic:p.topic,what_worked:p.what_worked})}catch{}}if(i.length>0){o.push(`### \u{1F4A1} Relevant Lessons for "${c}"`);for(const h of i.slice(0,4))o.push(` \u2022 **${h.topic}**: ${h.what_worked.slice(0,100)}`);o.push("")}}return o.length<=3&&o.push("_No brain data found. Start accumulating knowledge with `learn_from_attempts` and `session_start`._"),o.push("---","\u{1F9E0} Brain is ready. Continue your work \u2014 full context restored."),o.join(`
|
|
24
|
+
`)}case"brain_from_git":{const w=Date.now(),{instance_id:c,repo_path:u=".",limit:o=100,branch:e="HEAD",since:n="",incremental:d=!0}=A,r=await D(c),{resolve:f}=await import("node:path"),l=f(u),a=Math.max(1,Math.floor(Math.min(Number(o)||100,500)));if(typeof e!="string"||ke(e))return'\u274C Ungueltiger `branch`: darf nicht mit "-" beginnen.';await Pe();try{try{if(!xe(l))throw new Error("kein Ordner");re(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 s="",i=!1;d!==!1&&!n&&(s=await r.get(t)??"",Ce(s)||(s=""),i=!!s);const m=(i?`${s}..HEAD`:"")||e||"HEAD",p=["log",m,...n?[`--since=${n}`]:[],"--pretty=format:COMMIT|||%H|||%s|||%ad|||%an","--date=short","--no-merges","--name-only","-n",String(a)];let y="";try{y=re(l,p,{stderr:"pipe",timeoutMs:6e4})}catch(N){return`\u274C git log failed: ${N.message}. Check \`repo_path\` and \`branch\`.`}const _=[];let k=null;for(const N of y.split(`
|
|
25
|
+
`)){const L=N.trim();if(L.startsWith("COMMIT|||")){k&&_.push(k);const[,P,I,B,H]=L.split("|||");k={sha:(P??"").trim(),subject:(I??"").trim(),date:(B??"").trim(),author:(H??"").trim(),files:[]}}else if(L&&k){const P=ye(L);P&&k.files.push(P)}}if(k&&_.push(k),_.length===0)return i?`\u2705 brain_from_git: Brain is up to date \u2014 no new commits since last run (last SHA: \`${s.slice(0,8)}\`).`:ce({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}\`${n?` since ${n}`:""}.`});const j=new Date().toISOString();let g=0,S=0;const C=new Map,x=new Map,O=[];let $=null;const v=_.length,z=Math.max(1,Math.floor(v/10));let W=0;process.stderr.write(`
|
|
26
|
+
\u{1F9E0} brain_from_git: processing ${v} commits from ${l}...
|
|
27
|
+
`);let X=0,Z=0;for(let N=0;N<_.length;N++){const L=_[N],P=q({subject:L.subject,author:L.author,files:L.files.slice(0,12)});P.geschwaerzt.length&&X++,P.verdacht.length&&Z++;const I={...L,...P.felder};if(N-W>=z&&(process.stderr.write(` \u23F3 Processing ${N}/${v} commits (${g} lessons so far)...
|
|
28
|
+
`),W=N),!I.subject){S++;continue}const{category:B,outcome:H,severity:V}=Ie(I.subject),fe=Ae(I.subject),T=`${B}:${fe}`;C.set(B,(C.get(B)??0)+1),x.set(V,(x.get(V)??0)+1),O.push(T),(!$||B==="fix"&&!$.topic.startsWith("fix:"))&&($={topic:T,subject:I.subject});const oe=I.files.filter(F=>F.length>0).slice(0,12),ne={topic:T,outcome:H,severity:V,what_worked:I.subject.slice(0,200),what_failed:"",context:`git:${I.sha.slice(0,8)} by ${I.author} on ${I.date}`,author:I.author||void 0,file_paths:oe,commands:[`git show ${I.sha.slice(0,8)}`],tags:K(["brain_from_git",B,"git-history"],P.verdacht),visibility:"team",depends_on:[],recall_count:0,ts:j,verified_at:j,confidence:.55,audit_trail:[{ts:j,action:"brain_from_git",sha:I.sha.slice(0,8)}],version:3};await r.get(`cachly:lesson:best:${T}`)||(await r.set(`cachly:lesson:best:${T}`,JSON.stringify(ne),"EX",90*86400),await r.rpush(`cachly:lessons:${T}`,JSON.stringify(ne)),await r.ltrim(`cachly:lessons:${T}`,-100,-1),await r.expire(`cachly:lessons:${T}`,90*86400),await r.sadd(Le,T).catch(()=>{})),await r.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:T,sha:I.sha.slice(0,8),subject:I.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 ie=b(T);if(await M(r,ie,B,"git-derived"),I.author)try{const F=await ge(r,I.author,B);await J(r,F,"authored",ie,H==="success",H==="partial");for(const he of oe.slice(0,8)){const ae=await _e(r,he);await J(r,F,"touched",ae,!0),await we(r,ae,F)}}catch{}g++}process.stderr.write(` \u2705 brain_from_git complete: ${g}/${v} commits ingested
|
|
29
29
|
|
|
30
|
-
`),g>0&&
|
|
31
|
-
`)}case"
|
|
32
|
-
`)
|
|
33
|
-
`
|
|
34
|
-
`
|
|
35
|
-
`)
|
|
36
|
-
`)}case"
|
|
37
|
-
`)
|
|
38
|
-
`)
|
|
39
|
-
`)
|
|
40
|
-
`)}
|
|
30
|
+
`),g>0&&Oe(),_.length>0&&_[0]?.sha&&await r.set(t,_[0].sha,"EX",2160*3600),Te={fixes:C.get("fix")??0,features:C.get("feat")??0,refactors:C.get("refactor")??0,total:g};let ee=null;if($&&g>0)try{const N=await je(r,["cachly:lesson:best:*"],$.subject,1);if(N.length>0){const L=R(N[0].content,{});ee={query:$.subject.slice(0,80),topic:L.topic??N[0].key.replace("cachly:lesson:best:",""),snippet:(L.what_worked??"").slice(0,120)||$.subject.slice(0,120)}}}catch{}const te=ce({repoDir:l,revRange:m,processed:_.length,ingested:g,skipped:S,durationMs:Date.now()-w,isIncremental:i,lastSha:s,instanceId:c,categories:[...C.entries()].sort((N,L)=>L[1]-N[1]),severities:[...x.entries()].sort((N,L)=>L[1]-N[1]),proof:ee,suggestedQueries:Ne(O,c)}),se=U(X,Z,`${_.length} Commits`);return se.length?[te,"",...se].join(`
|
|
31
|
+
`):te}finally{Be()}}case"brain_from_ci":{const{instance_id:w,outcomes:c}=A,u=await D(w),o=Date.now();let e=0,n=0,d=0,r=0,f=0;const l=c.length;for(const a of c){const t=q({job:String(a.job??"unknown"),context:String(a.context??"")});t.geschwaerzt.length&&r++;const s=String(a.status??""),i=String(a.prev_status??""),h=t.felder.job,m=t.felder.context,p=["failure","red","error"].includes(i)&&["success","green","passed"].includes(s),y=["success","green","passed"].includes(i)&&["failure","red","error"].includes(s),_=`ci:${b(h)}`,k=b(_);if(await M(u,k,"ci","job"),p){const g=b(`problem:${b(h)}`);await M(u,g,"problem","ci-failure"),await J(u,k,"fixes",g,!0);const S={topic:_,outcome:"success",what_worked:`CI job "${h}" went ${i} \u2192 ${s}`,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:o,verified_at:o,confidence:.65,audit_trail:[{ts:o,action:"brain_from_ci_fixed"}],version:3};await u.rpush(`cachly:lessons:${_}`,JSON.stringify(S)),await u.ltrim(`cachly:lessons:${_}`,-100,-1),await u.set(`cachly:lesson:best:${_}`,JSON.stringify(S)),t.verdacht.length&&f++,e++}else if(y){const g=b(`cause:${b(h)}`);await M(u,g,"cause","ci-break"),await J(u,k,"causes",g,!1),n++}else d++;const j=`cachly:cls:${w}`;await u.rpush(j,JSON.stringify({source:"ci_outcome",payload:{status:s,prev_status:i,job:h},ts:o})),await u.ltrim(j,-200,-1)}return Me={fixes:e,breaks:n,stable:d,total:l},[`\u{1F4E5} **brain_from_ci**: Ingested ${l} outcomes \u2014 ${e} fixes learned, ${n} breaks noted, ${d} stable`,"",e>0?`\u2705 ${e} fix lesson${e!==1?"s":""} written (confidence 0.65) \u2014 CKG \`fixes\` edges added`:"",n>0?`\u{1F534} ${n} break${n!==1?"s":""} noted \u2014 CKG \`causes\` edges added`:"",d>0?`\u{1F4CA} ${d} stable outcome${d!==1?"s":""} recorded`:"","",'\u{1F4A1} Explore: `brain_search(query="ci")` | `brain_predict(context="<job-name>")`',...U(r,f,`${l} CI-Ergebnissen`)].filter(Boolean).join(`
|
|
32
|
+
`)}case"brain_predict_failures":{const{instance_id:w,context:c,top_k:u=5,format:o="detailed"}=A,e=await D(w),n=c.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g," ").split(/\s+/).filter(i=>i.length>2),d=[];for(const i of n.slice(0,8)){const h=[],m=e.scanStream({match:`cachly:ckg:node:*${i}*`,count:50});await new Promise((p,y)=>{m.on("data",_=>h.push(..._)),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 _=R(y,null);if(!_)continue;const k=await e.smembers(`cachly:ckg:idx:from:${_.id}`);for(const j of k.slice(0,20)){const g=await e.get(j);if(!g)continue;const S=R(g,null);if(!S||S.edgeType!=="causes"&&S.edgeType!=="degrades_under")continue;const C=await e.smembers(`cachly:ckg:idx:from:${S.to}`);let x;for(const O of C.slice(0,10)){const $=await e.get(O);if(!$)continue;const v=R($,null);if(v&&v.edgeType==="fixes"){const z=await e.get(`cachly:lesson:best:${v.from}`);if(z){x=R(z,null)?.what_worked?.slice(0,120);break}}}d.push({concept:_.id,failure:S.to.replace(/-/g," "),probability:S.confidence,fix:x,source:"ckg"})}}}const r=[],f=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((i,h)=>{f.on("data",m=>r.push(...m)),f.on("end",i),f.on("error",h)});for(const i of r.slice(0,100)){const h=await e.get(i);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=n.filter(k=>p.includes(k)).length/Math.max(1,n.length);if(y<.15)continue;const _=m.severity==="critical"?.15:m.severity==="major"?.05:0;d.push({concept:m.topic,failure:m.what_failed.slice(0,80),probability:Math.min(.97,(m.confidence??.5)*y*1.5+_),fix:m.what_worked?.slice(0,120),topic:m.topic,source:"lesson"})}catch{}}if(d.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(`
|
|
33
|
+
`);const l=new Set,a=d.filter(i=>{const h=i.failure.slice(0,40);return l.has(h)?!1:(l.add(h),!0)}).sort((i,h)=>h.probability-i.probability).slice(0,Number(u)),t=[`\u{1F52E} **Failure Prediction for: "${c}"**
|
|
34
|
+
`];t.push(`> Pre-deploy failure analysis based on ${d.length} patterns. Ranked by probability.
|
|
35
|
+
`);for(let i=0;i<a.length;i++){const h=a[i],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} **${i+1}. ${h.failure}**`),t.push(` Probability: ${p} **${m}%** (${h.source==="ckg"?"CKG causal edge":"lesson history"})`),o==="detailed"&&h.fix&&t.push(` \u2705 Pre-loaded fix: _${h.fix}_`),o==="detailed"&&h.topic&&t.push(` \u{1F4DA} Lesson: \`${h.topic}\``),t.push("")}const s=a.filter(i=>i.probability>=.6);return s.length>0?t.push(`\u26A0\uFE0F **${s.length} high-risk failure${s.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(`
|
|
36
|
+
`)}case"brain_contribute_signal":{const{instance_id:w,topic_category:c,outcome:u,confidence:o=.5}=A;if(!c?.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=le({topic_category:c.trim()},"die Commons");if(!e.ok)return e.meldung;const n=e.felder.topic_category,d=o>=.75?"high":o>=.5?"medium":"low";let r="\u{1F4E6} Signal stored locally (commons API unavailable)";try{await G("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:n.toLowerCase(),outcome:u,confidence:o})}),r="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const f=await D(w),l=`cachly:fed:outbox:${Date.now()}`;await f.set(l,JSON.stringify({topic_category:n,outcome:u,bucket:d,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${n}\`**`,"",`\u{1F4CA} Outcome: **${u}** \xB7 Confidence bucket: **${d}**`,"\u{1F6E1}\uFE0F Privacy: topic category only \u2014 no lesson text, no org identity","",r,...e.geschwaerzt.length?[ue(e.geschwaerzt)]:[],"","\u{1F4A1} When \u2265 k orgs contribute the same pattern, a meta-lesson appears in `brain_import_meta`."].join(`
|
|
37
|
+
`)}case"brain_import_meta":{const{instance_id:w,category:c,limit:u=20}=A;let o=[],e=3;try{const a=new URLSearchParams;c&&a.set("category",c),a.set("limit",String(Math.min(u,200)));const t=await G(`/api/v1/federation/meta?${a.toString()}`);o=t.meta_lessons??[],e=t.k_threshold??3}catch{return"\u274C Could not reach the global commons API. Try again later."}if(o.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(`
|
|
38
|
+
`);let n=0;const d=new Set;o=o.map(a=>{const t=q({topic_category:a.topic_category,dominant_outcome:a.dominant_outcome});return t.geschwaerzt.length&&n++,t.verdacht.length&&d.add(t.felder.topic_category),{...a,...t.felder}});const r=await D(w);let f=0;for(const a of o){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",...d.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"}]})),f++)}const l=[`\u{1F310} **Brain Import Meta-Lessons** (k \u2265 ${e})`,"","| Topic Category | Outcome | Confidence | Signals |","|---|---|---|---|"];for(const a of o.slice(0,15)){const t=(a.avg_confidence*100).toFixed(0)+"%";l.push(`| \`${a.topic_category}\` | ${a.dominant_outcome} | ${t} | ${a.signal_count} |`)}return o.length>15&&l.push(`| _\u2026${o.length-15} more_ | | | |`),l.push("",`\u2705 **${f}** new meta-lessons imported into local Brain.`),f<o.length&&l.push(`_(${o.length-f} already present \u2014 not overwritten)_`),l.push(...U(n,d.size,`${o.length} Kategorienamen`)),l.join(`
|
|
39
|
+
`)}case"brain_watch":{const{instance_id:w="",project_dir:c=".",api_key:u}=A,{resolve:o}=await import("node:path"),e=o(c),{result:n,hookPath:d}=await ve(e,w,u);return n==="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(`
|
|
40
|
+
`):[`\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"}[n]??n}**`,"",`Hook path: \`${d}\``,`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(`
|
|
41
|
+
`)}default:return null}}export{Xe as FEDBRAIN_TOOL_NAMES,Me as _lastBrainFromCiCounts,Te as _lastBrainFromGitCounts,Ze as handleFedbrainTool};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{safeJsonParse as S}from"../utils.js";import{sofortAntwortNeuesBrain as I}from"../leeres-brain.js";const
|
|
2
|
-
`)}case"roadmap_update":{const{instance_id:
|
|
3
|
-
[${new Date().toISOString().slice(0,10)}] ${
|
|
4
|
-
`)}case"roadmap_list":{const{instance_id:
|
|
5
|
-
`).pop()?.slice(0,100)}`)}
|
|
6
|
-
`)}case"roadmap_next":{const{instance_id:
|
|
7
|
-
Tags: ${
|
|
8
|
-
Milestone: ${t.milestone}`:""
|
|
1
|
+
import{safeJsonParse as S}from"../utils.js";import{sofortAntwortNeuesBrain as I}from"../leeres-brain.js";import{fuerEigenenSpeicher as R,hinweise as T}from"../schreibtor.js";const v=new Set(["roadmap_add","roadmap_update","roadmap_list","roadmap_next"]);async function k(N,y,w,O){switch(N){case"roadmap_add":{const{instance_id:n,title:a,description:d="",priority:m="medium",tags:h=[],milestone:f=""}=y,g=R({title:a,description:d,tags:h,milestone:f}),{title:r,description:t,tags:p,milestone:u}=g.felder,$=await w(n),i=`rm_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,o={id:i,title:r,description:t,priority:m,tags:p,milestone:u,status:"planned",created:new Date().toISOString(),updated:new Date().toISOString(),notes:"",...g.verdacht.length?{verdacht:g.verdacht}:{}};await $.hset(`cachly:roadmap:${n}`,i,JSON.stringify(o));const s={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"};return["\u{1F4CB} **Roadmap item added**","",` ID: \`${i}\``,` Title: ${r}`,` Priority: ${s[m]??"\u26AA"} ${m}`," Status: planned",u?` Milestone: ${u}`:"",p.length?` Tags: ${p.join(", ")}`:"","",`\u{1F4A1} Use \`roadmap_update(id: "${i}", status: "in-progress")\` when you start working on it.`,...T(g,"notiz")].filter(Boolean).join(`
|
|
2
|
+
`)}case"roadmap_update":{const{instance_id:n,id:a,status:d,priority:m,notes:h,title:f,description:g}=y,r=R({notes:h,title:f,description:g}),{notes:t,title:p,description:u}=r.felder,$=await w(n),i=await $.hget(`cachly:roadmap:${n}`,a);if(!i)return`\u26A0\uFE0F **roadmap_update** \u2013 Item \`${a}\` not found. Use \`roadmap_list\` to see all items.`;const o=S(i,null);if(!o)return`\u26A0\uFE0F **roadmap_update** \u2013 Item \`${a}\` data is corrupted. Re-add with \`roadmap_add\`.`;const s=o.status;return d&&(o.status=d),m&&(o.priority=m),p&&(o.title=p),u&&(o.description=u),t&&(o.notes=o.notes?`${o.notes}
|
|
3
|
+
[${new Date().toISOString().slice(0,10)}] ${t}`:`[${new Date().toISOString().slice(0,10)}] ${t}`),o.updated=new Date().toISOString(),r.verdacht.length&&(o.verdacht=[...new Set([...Array.isArray(o.verdacht)?o.verdacht:[],...r.verdacht])]),await $.hset(`cachly:roadmap:${n}`,a,JSON.stringify(o)),[`${{planned:"\u{1F4CB}","in-progress":"\u26A1",done:"\u2705",blocked:"\u{1F6AB}",cancelled:"\u{1F5D1}\uFE0F"}[d??s]??"\u{1F4CB}"} **Roadmap updated** \`${a}\``,"",` Title: ${o.title}`,d&&s!==d?` Status: ${s} \u2192 ${d}`:` Status: ${o.status}`,t?` Notes: ${t}`:"",...T(r,"notiz")].filter(Boolean).join(`
|
|
4
|
+
`)}case"roadmap_list":{const{instance_id:n,status:a="open",tag:d,milestone:m,priority:h}=y,f=await I(n,O,"\u{1F4CB} **Roadmap is empty.**");if(f)return f;const r=await(await w(n)).hgetall(`cachly:roadmap:${n}`);if(!r||Object.keys(r).length===0)return"\u{1F4CB} **Roadmap is empty.**\n\nUse `roadmap_add` to create your first item.";const t={critical:0,high:1,medium:2,low:3},p={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},u={planned:"\u{1F4CB}","in-progress":"\u26A1",done:"\u2705",blocked:"\u{1F6AB}",cancelled:"\u{1F5D1}\uFE0F"},$=new Set(["planned","in-progress","blocked"]);let i=Object.values(r).flatMap(e=>{const c=S(e,null);return c?[c]:[]});if(a==="open"?i=i.filter(e=>$.has(e.status)):a&&(i=i.filter(e=>e.status===a)),d&&(i=i.filter(e=>e.tags.includes(d))),m&&(i=i.filter(e=>e.milestone===m)),h&&(i=i.filter(e=>(t[e.priority]??99)<=(t[h]??99))),i.sort((e,c)=>{const l=t[e.priority]??99,_=t[c.priority]??99;return l!==_?l-_:e.created.localeCompare(c.created)}),i.length===0)return`\u{1F4CB} **No roadmap items** match the current filter (status: ${a}).`;const o={};for(const e of i){const c=e.status;o[c]||(o[c]=[]),o[c].push(e)}const s=[`\u{1F4CB} **Roadmap** (${i.length} item${i.length!==1?"s":""})`,""];for(const[e,c]of Object.entries(o)){s.push(`**${u[e]??"\u2022"} ${e.toUpperCase()}** (${c.length})`);for(const l of c){const _=l.tags.length?` [${l.tags.join(", ")}]`:"",j=l.milestone?` \xB7 ${l.milestone}`:"";s.push(` ${p[l.priority]??"\u26AA"} \`${l.id}\` **${l.title}**${_}${j}`),l.description&&s.push(` ${l.description.slice(0,120)}`),l.notes&&s.push(` \u{1F4DD} ${l.notes.split(`
|
|
5
|
+
`).pop()?.slice(0,100)}`)}s.push("")}return s.push('\u{1F4A1} `roadmap_update(id, status: "in-progress")` to start \xB7 `roadmap_next` for top priority item'),s.join(`
|
|
6
|
+
`)}case"roadmap_next":{const{instance_id:n,tag:a}=y,d=await I(n,O,"\u{1F4CB} **Roadmap is empty.**");if(d)return d;const h=await(await w(n)).hgetall(`cachly:roadmap:${n}`);if(!h||Object.keys(h).length===0)return"\u{1F4CB} **Roadmap is empty.** Use `roadmap_add` to plan your first task.";const f={critical:0,high:1,medium:2,low:3},g={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},r=Object.values(h).flatMap(s=>{const e=S(s,null);return e?[e]:[]}).filter(s=>s.status==="in-progress"||s.status==="planned").filter(s=>!a||(Array.isArray(s.tags)?s.tags:[]).includes(a));if(r.length===0)return"\u{1F389} **No open roadmap items!** All tasks are done (or use `roadmap_list` to check).";r.sort((s,e)=>s.status==="in-progress"&&e.status!=="in-progress"?-1:e.status==="in-progress"&&s.status!=="in-progress"?1:(f[s.priority]??99)-(f[e.priority]??99));const t=r[0],p=r.length-1,u=Array.isArray(t.tags)?t.tags:[],$=u.length?`
|
|
7
|
+
Tags: ${u.join(", ")}`:"",i=t.milestone?`
|
|
8
|
+
Milestone: ${t.milestone}`:"",o=t.notes?`
|
|
9
9
|
Notes: ${t.notes.split(`
|
|
10
10
|
`).pop()?.slice(0,120)}`:"";return[`${t.status==="in-progress"?"\u26A1":"\u{1F4CB}"} **Next up: ${t.title}**`,"",`ID: \`${t.id}\``,`Priority: ${g[t.priority]??"\u26AA"} ${t.priority}`,`Status: ${t.status}`,t.description?`
|
|
11
11
|
What to do:
|
|
12
|
-
${t.description}`:"",
|
|
13
|
-
`)}default:return null}}export{
|
|
12
|
+
${t.description}`:"",$,i,o,"",p>0?`(+${p} more open item${p!==1?"s":""} in roadmap)`:"(last open item)","",t.status==="planned"?`\u{1F4A1} Start with: \`roadmap_update(id: "${t.id}", status: "in-progress")\``:`\u{1F4A1} Finish with: \`roadmap_update(id: "${t.id}", status: "done", notes: "...")\``].filter(s=>s!==void 0).join(`
|
|
13
|
+
`)}default:return null}}export{v as ROADMAP_TOOL_NAMES,k as handleRoadmapTool};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{safeJsonParse as
|
|
2
|
-
`);if(r){const
|
|
3
|
-
`)}let
|
|
4
|
-
... (truncated)`:""),"```","","_To import this on another Brain, use `brain_import` with the JSON payload._"].join(`
|
|
5
|
-
`)}return`\u274C brain_share failed: ${
|
|
6
|
-
`)}case"brain_import":{const{instance_id:
|
|
7
|
-
`):`\u274C brain_import failed: ${
|
|
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
|
|
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(
|
|
17
|
-
`);if(
|
|
18
|
-
`)}const
|
|
19
|
-
`)}default:return null}}export{
|
|
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 B}from"../cachly-url.js";import{VEKTOR_NACHTRAG as P}from"../bedeutung.js";import{schwaerze as z}from"../geheimnis-filter.js";import{fuerEigenenSpeicher as I,fuerWeitergabe as D,hinweise as J,istMarkiert as L,markiert as U,weitergabeHinweis as C,zaehlHinweise as H}from"../schreibtor.js";const W=new Set(["brain_share","brain_import","brain_share_list","brain_unshare","brain_discover","brain_seed_starter"]);async function K(O,g){const y=[],$=O.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((a,u)=>{$.on("data",e=>y.push(...e)),$.on("end",a),$.on("error",u)});const n=[];for(const a of y.slice(0,500)){const u=await O.get(a);if(!u)continue;const e=E(u,null);!e||!e.topic||g&&g.length>0&&!g.some(i=>e.topic.includes(i))||n.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 n}async function Q(O,g,y,$){switch(O){case"brain_share":{const{instance_id:n,title:a="My Brain Snapshot",description:u="",topic_filter:e,visibility:t="unlisted",max_lessons:i=100,dry_run:r=!1}=g;if(!n)return"\u26A0\uFE0F `brain_share` requires `instance_id`.";const c=D({title:a,description:u},"die Share");if(!c.ok)return c.meldung;const l=[...c.geschwaerzt],_=c.felder.title,f=c.felder.description,s=await y(n),p=Array.isArray(e)&&e.length>0?e:void 0,w=await K(s,p),m=[],S=[];for(const o of w){if(S.length>=i)break;const d=z(o.topic).text;if(L(o)){m.push(`${d} (beim Speichern markiert)`);continue}const b=D(o,"die 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: ${m.length} Lektion(en) NICHT in die Share aufgenommen (Anweisung oder gefaehrlicher Befehl erkannt): ${m.slice(0,10).join(", ")}${m.length>10?", \u2026":""}. Pruefen und einzeln neu speichern; die Lektionen im Brain bleiben unveraendert.`:""].filter(Boolean);if(h.length===0)return["\u{1F4E4} **brain_share** \u2014 nothing to share yet","",`No lessons found in Brain \`${n}\`${p?` matching topics: ${p.join(", ")}`:""}${m.length?" that can be shared":""}.`,"",'Store lessons first with `learn_from_attempts(topic="...", what_worked="...")`.',...T].join(`
|
|
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=B(`/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
|
+
... (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 s.rpush("cachly:brain:shares",o),await s.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:n,share_id:a,topic_prefix:u="",min_confidence:e=0,dry_run:t=!1,overwrite:i=!1}=g;if(!n)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 y(n);let f=0,s=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){s++;continue}const o=I(k);o.geschwaerzt.length&&m++,o.verdacht.length&&S++;const d=o.verdacht.length?{...o.felder,tags:U(o.felder.tags,o.verdacht)}:o.felder,b=u?`${u}:${d.topic}`:d.topic,R=`cachly:lesson:best:${b}`;if(!i&&await _.get(R)){p++;continue}const A=JSON.stringify({...d,topic:b,imported_from:r,imported_at:new Date().toISOString()});if(!t){await _.set(R,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:s,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}`,...s>0?[`**Skipped (low confidence):** ${s}`]:[],...p>0?[`**Skipped (already exist):** ${p} _(pass \`overwrite=true\` to replace)_`]:[],...H(m,S,`${l.length} Eintraegen`),...J(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:n}=g;if(!n)return"\u26A0\uFE0F `brain_share_list` requires `instance_id`.";const a=await y(n);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="${n}", title="My Patterns")\``].join(`
|
|
9
|
+
`);const i=[`\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),s=l.visibility==="public"?"\u{1F310} public":"\u{1F517} unlisted";i.push(`| ${c+1} | ${l.title??"\u2014"} | ${l.lesson_count??"?"} | ${s} | ${f} |`)}const r=t[t.length-1];return i.push("",`**Import command:** \`brain_import(instance_id="<their-id>", share_id="${r?.share_id??"..."}")\``,`**Revoke:** \`brain_unshare(instance_id="${n}", share_id="<id>")\``),i.join(`
|
|
10
|
+
`)}case"brain_unshare":{const{instance_id:n,share_id:a}=g;if(!n)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 i=await y(n);try{const c=(await i.lrange("cachly:brain:shares",0,-1)).filter(l=>{try{return JSON.parse(l).share_id!==a}catch{return!0}});await i.del("cachly:brain:shares");for(const l of c)await i.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 y(n);try{const t=(await u.lrange("cachly:brain:shares",0,-1)).filter(i=>{try{return JSON.parse(i).share_id!==a}catch{return!0}});await u.del("cachly:brain:shares");for(const i of t)await u.rpush("cachly:brain:shares",i)}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:n="",topic:a="",limit:u=10}=g;let e=[];try{const i=new URLSearchParams;n&&i.set("q",n),a&&i.set("topic",a),i.set("limit",String(u)),e=await $(`/api/v1/brains/discover?${i.toString()}`)}catch(i){const r=i.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: ${B("/brains","brain-discover")}`].join(`
|
|
13
|
+
`):`\u274C brain_discover failed: ${r}`}if(e.length===0)return[`\u{1F50D} **brain_discover** \u2014 no public Brains found ${n?`matching "${n}"`:a?`in topic "${a}"`:""}`.trim(),"",'Be the first! `brain_share(instance_id="...", visibility="public")`'].join(`
|
|
14
|
+
`);const t=[`\u{1F50D} **brain_discover**${n?` \u2014 "${n}"`:""}${a?` \xB7 topic: ${a}`:""} (${e.length} result${e.length!==1?"s":""})`,""];for(const[i,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(", ")}`:"",s=r.author?` by **${r.author}**`:"";t.push(`**${i+1}. ${r.title}**${s}`,` \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 ${B("/brains","brain-discover")}_`),t.filter(i=>i!==" ").join(`
|
|
15
|
+
`)}case"brain_seed_starter":{const{instance_id:n,topic_filter:a,dry_run:u=!1,force:e=!1}=g;if(!n)return"\u26A0\uFE0F `brain_seed_starter` requires `instance_id`.";const t=await y(n),i=await t.get(`cachly:brain:starter_seeded:${n}`);if(i&&!e&&!u)return["\u{1F331} **brain_seed_starter** \u2014 already seeded","",`This Brain was seeded with the starter corpus on ${i}.`,"","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(s=>r.some(p=>s.topic.includes(p)||s.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(s=>`\`${s.topic}\``).join(", ")}`].join(`
|
|
17
|
+
`);if(u){const s=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":""}`,"",...s,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 s of c){const p=`cachly:lesson:best:${s.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:s.topic,outcome:s.outcome,what_worked:s.what_worked,what_failed:s.what_failed,ctx:s.ctx,tags:s.tags,confidence:s.confidence,recall_count:0,source:"starter",ts:l,verified_at:l,version:3});await t.set(p,w),await t.sadd(P,s.topic).catch(()=>{});const m=`cachly:lessons:${s.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:${n}`,l,"EX",365*86400,"NX").catch(()=>{}),await t.set(`cachly:brain:starter_seeded:${n}`,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
|
+
`)}default:return null}}export{W as SHARE_TOOL_NAMES,q as STARTER_CORPUS_SIZE,Q as handleShareTool};
|