@cachly-dev/mcp-server 0.10.174 → 0.10.176
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 +5 -3
- package/dist/src/ambient-cli.js +2 -2
- package/dist/src/ambient-hook-start.js +1 -0
- package/dist/src/ambient-hook.js +2 -0
- package/dist/src/ambient-hooks.js +6 -5
- package/dist/src/ambient-ledger.js +5 -5
- package/dist/src/ausgabe-ordnung.js +1 -0
- package/dist/src/commit-art.js +1 -0
- package/dist/src/credentials.js +1 -1
- package/dist/src/einblendung.js +6 -6
- package/dist/src/embeddings.js +4 -4
- package/dist/src/handlers/brain.js +67 -67
- package/dist/src/handlers/fedbrain.js +31 -31
- package/dist/src/hook-zugang.js +1 -0
- package/dist/src/index.js +153 -154
- package/dist/src/leser-sicherung.js +1 -0
- package/dist/src/leser.js +1 -1
- package/dist/src/zugang.js +6 -0
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +27 -0
- package/package.json +5 -2
- package/server.json +2 -2
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import{createHmac as
|
|
2
|
-
`);const l=[{name:"InfraAgent",domains:["infra","k8s","docker","server","wireguard","helm"]},{name:"AuthAgent",domains:["auth","jwt","keycloak","oauth","oidc","token"]},{name:"DeployAgent",domains:["deploy","ci","pipeline","rsync","release"]},{name:"DatabaseAgent",domains:["db","gorm","migration","postgres","clickhouse","redis"]},{name:"DebugAgent",domains:["debug","panic","race","nil","fix","error"]},{name:"APIAgent",domains:["api","http","grpc","rest","fiber","web"]}],u=i.split(":")[0]??"",c=l.filter(g=>g.domains.some(S=>u===S||i.includes(S))),o=c.length>0?c:l,d=new Map;for(const g of o){let S=0;for(const
|
|
3
|
-
`);const a=[];for(const g of o){const S=d.get(g.name)??0;let
|
|
4
|
-
`)}case"cls_ingest":{const{instance_id:
|
|
5
|
-
`)}if(i==="ci_outcome"){const u=String(n.status??""),c=String(n.prev_status??""),o=String(n.job??"unknown"),d=String(n.context??""),h=["failure","red","error"].includes(c)&&["success","green","passed"].includes(u),s=["success","green","passed"].includes(c)&&["failure","red","error"].includes(u),a=`ci:${
|
|
6
|
-
`)}if(i==="ide_diagnostic"){const u=String(n.error??""),c=String(n.fix??""),o=String(n.file??""),d=
|
|
7
|
-
`)}return`\u274C Unknown CLS source: "${i}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:
|
|
8
|
-
`];if(t.includes("git")){const l=
|
|
9
|
-
`)}case"fedbrain_contribute":{const{instance_id:
|
|
10
|
-
`)}case"fedbrain_search":{const{instance_id:
|
|
11
|
-
`);const h=c.map(a=>{const r=(a.domain_fingerprint??a.category??"").split(",").filter(Boolean),f=r.reduce((
|
|
1
|
+
import{createHmac as oe}from"node:crypto";import{ckgSlug as k,extractProblemConcept as ne,ckgUpsertNode as J,ckgUpdateEdge as T,ckgUpsertPersonNode as ie,ckgUpsertFileNode as ae,ckgRecordCollaboration as ce}from"../ckg.js";import{safeJsonParse as A,normalizeGitPath as re}from"../utils.js";import{buildClsPostCommitHook as le}from"../cls-hook.js";import{installBrainWatchHook as ue}from"../brain-watch-hook.js";import{keywordSearch as de}from"../search.js";import{buildFirstContactReport as Z,suggestRecallQueries as fe}from"../first-contact.js";import{classifyCommit as he,extractDomain as me}from"../commit-art.js";let pe=null,ge=null,U=0;const _e=10,ee=[];function we(){return U<_e?(U++,Promise.resolve()):new Promise(B=>ee.push(B))}function ye(){const B=ee.shift();B?B():U--}const Ne=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 Ie(B,N,I,K){switch(B){case"madc_deliberate":{const{instance_id:_,topic:i}=N,n=await I(_),e=(await n.lrange(`cachly:lessons:${i}`,0,-1)).map(g=>{try{return JSON.parse(g)}catch{return null}}).filter(Boolean);if(e.length<2)return[`\u{1F5F3}\uFE0F **MADC: "${i}"**`,"",`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 l=[{name:"InfraAgent",domains:["infra","k8s","docker","server","wireguard","helm"]},{name:"AuthAgent",domains:["auth","jwt","keycloak","oauth","oidc","token"]},{name:"DeployAgent",domains:["deploy","ci","pipeline","rsync","release"]},{name:"DatabaseAgent",domains:["db","gorm","migration","postgres","clickhouse","redis"]},{name:"DebugAgent",domains:["debug","panic","race","nil","fix","error"]},{name:"APIAgent",domains:["api","http","grpc","rest","fiber","web"]}],u=i.split(":")[0]??"",c=l.filter(g=>g.domains.some(S=>u===S||i.includes(S))),o=c.length>0?c:l,d=new Map;for(const g of o){let S=0;for(const $ of g.domains){const x=[],v=n.scanStream({match:`cachly:ckg:node:${$}*`,count:50});await new Promise((L,P)=>{v.on("data",R=>x.push(...R)),v.on("end",L),v.on("error",P)}),S+=x.length}d.set(g.name,S)}const h=e.filter(g=>g.outcome==="success"||g.outcome==="partial"),s=e.filter(g=>g.outcome==="failure");if(s.length===0)return[`\u{1F5F3}\uFE0F **MADC: "${i}"**`,"",`No contradictions found \u2014 all ${h.length} entries have non-failure outcomes.`,"",`Use \`ckg_inspect(concept="${k(i)}")\` to explore the confidence graph.`].join(`
|
|
3
|
+
`);const a=[];for(const g of o){const S=d.get(g.name)??0;let $,x;S<2?($="abstain",x="insufficient domain coverage"):h.length>=s.length*2?($="success",x=`${h.length}/${e.length} entries confirm success`):s.length>=h.length*2?($="failure",x=`${s.length}/${e.length} entries confirm failure`):($="abstain",x=`contested (${h.length} success vs ${s.length} failure)`),a.push({agent:g.name,vote:$,coverage:S,reason:x})}const r=a.filter(g=>g.vote==="success").length,f=a.filter(g=>g.vote==="failure").length,m=a.filter(g=>g.vote==="abstain").length;let p,w;r>0&&f===0?(p="unanimous_success",w=`\u2705 **Unanimous: SUCCESS** \u2014 ${r} agent(s) confirm, ${m} abstain`):f>0&&r===0?(p="unanimous_failure",w=`\u274C **Unanimous: FAILURE** \u2014 ${f} agent(s) confirm, ${m} abstain`):(p="contested",w=`\u26A0\uFE0F **CONTESTED** \u2014 ${r} success votes, ${f} failure votes, ${m} abstain`);const y=k(`resolution:${i}`),j={id:y,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:p,topic:i,votes:{success:r,failure:f,abstain:m}};if(await n.set(`cachly:ckg:node:${y}`,JSON.stringify(j)),p==="contested")await T(n,k(i),"contradicts",y,!1);else{if(((p==="unanimous_success"?"failure":"success")==="failure"?s:h).length>0){const $=await n.smembers(`cachly:ckg:idx:from:${k(i)}`);for(const x of $){const v=await n.get(x);if(v)try{const L=JSON.parse(v);L.edgeType==="fixes"&&L.confidence>.15&&p==="unanimous_failure"&&(L.confidence=.1,L.last_updated=new Date().toISOString(),await n.set(x,JSON.stringify(L)))}catch{}}}await n.del(`cachly:ckg:conflict:${k(i)}`)}const C=[`\u{1F5F3}\uFE0F **MADC Deliberation: "${i}"**`,"",`\u{1F4CA} Evidence: ${h.length} success/partial vs ${s.length} failure entries (${e.length} total)`,"",`**Voting agents (${o.length}):**`,...a.map(g=>{const S=g.vote==="success"?"\u2705":g.vote==="failure"?"\u274C":"\u2B1C",$="\u2593".repeat(Math.min(g.coverage,5))+"\u2591".repeat(Math.max(0,5-g.coverage));return` ${S} **${g.agent}** [${$}] ${g.coverage} CKG edges \u2014 ${g.reason}`}),"",w,""];return p==="unanimous_success"?C.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${i}", outcome="success", ...)\``):p==="unanimous_failure"?C.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${i}")\``):C.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${k(i)}")\``),C.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${y}\``),C.join(`
|
|
4
|
+
`)}case"cls_ingest":{const{instance_id:_,source:i,payload:n}=N,t=await I(_),e=new Date().toISOString(),l="cachly:cls:events";if(i==="git_commit"){const u=String(n.message??""),c=String(n.sha??""),o=Array.isArray(n.files)?n.files:[],d=/^fix/i.test(u)?"fix":/^feat/i.test(u)?"feat":/^refactor/i.test(u)?"refactor":/^test/i.test(u)?"test":"commit",h=`${d}:${k(u.slice(0,60))}`,s=k(h);await J(t,s,d,"commit");for(const f of o.slice(0,10)){const m=f.includes("auth")?"auth":f.includes("api")?"api":f.includes("infra")?"infra":f.includes("web")?"web":"code",p=k(`file:${m}`);await J(t,p,"file",m),await T(t,s,"co-occurs",p,!0)}const a={topic:h,outcome:"success",what_worked:u,what_failed:"",context:`CLS/git: sha=${c}`,severity:"minor",file_paths:o.slice(0,10),commands:c?[`git show ${c}`]:[],tags:["cls","git"],depends_on:[],recall_count:0,ts:e,verified_at:e,confidence:.6,audit_trail:[{ts:e,action:"cls_git_commit"}],version:3};return await t.rpush(`cachly:lessons:${h}`,JSON.stringify(a)),await t.get(`cachly:lesson:best:${h}`)||await t.set(`cachly:lesson:best:${h}`,JSON.stringify(a)),await t.rpush(l,JSON.stringify({source:i,payload:{message:u,sha:c},ts:e})),await t.ltrim(l,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${c.slice(0,8)||"?"}\`: ${u.slice(0,80)}`,`Concept: \`${s}\` (${d}) \xB7 Files: ${o.length}`,"",`\u{1F578}\uFE0F CKG: \`${s}\` + ${o.length} file edges \xB7 Lesson: \`${h}\``,`\u{1F4A1} Inspect: \`ckg_inspect(concept="${d}")\``].join(`
|
|
5
|
+
`)}if(i==="ci_outcome"){const u=String(n.status??""),c=String(n.prev_status??""),o=String(n.job??"unknown"),d=String(n.context??""),h=["failure","red","error"].includes(c)&&["success","green","passed"].includes(u),s=["success","green","passed"].includes(c)&&["failure","red","error"].includes(u),a=`ci:${k(o)}`,r=k(a);if(await J(t,r,"ci","job"),h){const m=k(`problem:${k(o)}`);await J(t,m,"problem","ci-failure"),await T(t,r,"fixes",m,!0);const p={topic:a,outcome:"success",what_worked:`CI job "${o}" went ${c} \u2192 ${u}`,what_failed:`Job "${o}" was failing`,context:`CLS/ci: ${d}`,severity:"major",file_paths:[],commands:[],tags:["cls","ci"],depends_on:[],recall_count:0,ts:e,verified_at:e,confidence:.75,audit_trail:[{ts:e,action:"cls_ci_fixed"}],version:3};await t.rpush(`cachly:lessons:${a}`,JSON.stringify(p)),await t.set(`cachly:lesson:best:${a}`,JSON.stringify(p))}else if(s){const m=k(`cause:${k(o)}`);await J(t,m,"cause","ci-break"),await T(t,r,"causes",m,!1)}return await t.rpush(l,JSON.stringify({source:i,payload:{status:u,prev_status:c,job:o},ts:e})),await t.ltrim(l,-200,-1),["\u{1F4E8} **CLS Ingested: ci_outcome**","",`${h?"\u2705 Fixed":s?"\u{1F534} Broken":"\u{1F4CA} Recorded"}: \`${o}\` \u2014 ${c||"?"} \u2192 ${u}`,h?"\u{1F527} CKG `fixes` edge added (75% confidence)":s?"\u26A1 CKG `causes` edge added":"\u{1F4CA} State recorded",`\u{1F4A1} Lesson: \`${a}\` | Predict: \`brain_predict(context="${o}")\``].join(`
|
|
6
|
+
`)}if(i==="ide_diagnostic"){const u=String(n.error??""),c=String(n.fix??""),o=String(n.file??""),d=ne(u)??"unknown-error",h=`debug:${k(d)}`,s=k(h),a=k(`problem:${d}`);await J(t,s,"debug","diagnostic"),await J(t,a,"problem","compiler-error"),await T(t,s,"fixes",a,!0);const r={topic:h,outcome:"success",what_worked:c,what_failed:u,context:`CLS/ide: ${o}`,severity:"minor",file_paths:o?[o]:[],commands:[],tags:["cls","ide-diagnostic"],depends_on:[],recall_count:0,ts:e,verified_at:e,confidence:.65,audit_trail:[{ts:e,action:"cls_ide_diagnostic"}],version:3};return await t.rpush(`cachly:lessons:${h}`,JSON.stringify(r)),await t.get(`cachly:lesson:best:${h}`)||await t.set(`cachly:lesson:best:${h}`,JSON.stringify(r)),await t.rpush(l,JSON.stringify({source:i,payload:{error:u.slice(0,60),fix:c.slice(0,60),file:o},ts:e})),await t.ltrim(l,-200,-1),["\u{1F4E8} **CLS Ingested: ide_diagnostic**","",`Error: \`${u.slice(0,80)}\``,`Fix: ${c.slice(0,100)}`,o?`File: \`${o}\``:"","",`\u{1F578}\uFE0F CKG: \`${s}\` \u2192 fixes \u2192 \`${a}\` | Lesson: \`${h}\``].filter(m=>m!=="").join(`
|
|
7
|
+
`)}return`\u274C Unknown CLS source: "${i}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:_,repo_path:i=".",hooks:n=["git","ci"]}=N,t=Array.isArray(n)?n:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
|
|
8
|
+
`];if(t.includes("git")){const l=le(_);e.push("### Git post-commit hook"),e.push("**Quick install (run once per repo):**"),e.push("```sh"),e.push(`touch ${i}/.git/hooks/post-commit`),e.push(`grep -q 'cachly CLS' ${i}/.git/hooks/post-commit || cat >> ${i}/.git/hooks/post-commit << 'HOOK'`),e.push(l),e.push("HOOK"),e.push(`chmod +x ${i}/.git/hooks/post-commit`),e.push("```"),e.push("After install: every `git commit` automatically updates your brain's CKG."),e.push("")}return t.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:i,visibility:n="public"}=N,t=await I(_),e=await t.get(`cachly:lesson:best:${i}`);if(!e)return`\u274C Lesson \`${i}\` not found. Store it first with \`learn_from_attempts\`.`;const l=A(e,null);if(!l)return`\u274C Lesson \`${i}\` data is corrupted. Re-store with \`learn_from_attempts\`.`;const u=[l.topic.split(":")[0],...l.tags??[]].filter(Boolean),c=[...new Set(u)].sort().join(","),o=`${l.topic}:${l.outcome}:${l.what_worked}`,d=oe("sha256",`cachly-fedbrain:${_}`).update(o).digest("hex").slice(0,16),h={cert_id:d,lesson_key:i,visibility:n,domain_fingerprint:c,contributed_at:new Date().toISOString(),confirm_count:0,trust_score:l.outcome==="success"?.85:.5};await t.set(`cachly:fedbrain:cert:${d}`,JSON.stringify(h)),await t.sadd("cachly:fedbrain:contributed",d);let s;try{await K("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify({topic:l.topic,outcome:l.outcome,what_worked:l.what_worked,what_failed:l.what_failed??"",severity:l.severity??"major",cert_id:d,domain_fingerprint:c,visibility:n})}),s="\u2705 Contributed to global commons"}catch{s="\u{1F4E6} Stored locally (commons API unavailable \u2014 will sync when online)"}return[`\u{1F310} **FedBrain Contribute: "${i}"**`,"",`\u{1F4DC} Certificate: \`${d}\``,`\u{1F3F7}\uFE0F Domain fingerprint: ${u.slice(0,6).map(a=>`\`${a}\``).join(", ")}`,`\u{1F512} Visibility: ${n}`,"",s,"","\u{1F4A1} At 10 independent confirms \u2192 \u{1F3C6} Gold Standard",`\u{1F50D} Search: \`fedbrain_search(query="${l.topic.split(":").slice(-1)[0]}")\``].join(`
|
|
10
|
+
`)}case"fedbrain_search":{const{instance_id:_,query:i,context_hints:n=[],limit:t=10}=N,e=await I(_),l=await e.smembers("cachly:fedbrain:contributed"),u=new Map;for(const a of l.slice(0,30)){const r=await e.get(`cachly:fedbrain:cert:${a}`);if(r)try{const f=JSON.parse(r);for(const m of(f.domain_fingerprint??"").split(",").filter(Boolean))u.set(m,(u.get(m)??0)+1)}catch{}}for(const a of Array.isArray(n)?n:[])u.set(a.toLowerCase(),(u.get(a.toLowerCase())??0)+2);let c=[],o=!1;try{const a=new URLSearchParams({q:i,limit:String(Math.min(t*2,50))});c=(await K(`/api/v1/syndication/search?${a}`)).results??[]}catch{o=!0;const a=[],r=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,m)=>{r.on("data",p=>a.push(...p)),r.on("end",f),r.on("error",m)});for(const f of a.slice(0,60)){const m=await e.get(f);if(m)try{const p=JSON.parse(m),w=`${p.topic} ${p.what_worked??""} ${p.what_failed??""}`.toLowerCase();i.toLowerCase().split(/\s+/).some(y=>y.length>2&&w.includes(y))&&c.push({id:f.split(":").pop()??f,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 d=o?" \u2014 \u26A0\uFE0F Commons unreachable, local fallback (this machine only, not confirmed by the network)":"";if(c.length===0)return[`\u{1F310} **FedBrain Search: "${i}"**${d}`,"",'No results. Contribute: `fedbrain_contribute(lesson_key="fix:...")`'].join(`
|
|
11
|
+
`);const h=c.map(a=>{const r=(a.domain_fingerprint??a.category??"").split(",").filter(Boolean),f=r.reduce((y,j)=>y+(u.get(j)??0),0),m=u.size>0?f/Math.max(1,u.size+r.length):0,p=Math.min(1,a.confirm_count/10),w=m*.4+p*.4+(a.outcome==="success"?.2:0);return{...a,weightedScore:w,isGoldStandard:!o&&a.confirm_count>=10}}).sort((a,r)=>r.weightedScore-a.weightedScore).slice(0,t),s=[`\u{1F310} **FedBrain Search: "${i}"** \u2014 ${h.length} result${h.length!==1?"s":""} (context-weighted)${d}
|
|
12
12
|
`];for(const a of h){const r=a.outcome==="success"?"\u2705":a.outcome==="failure"?"\u274C":"\u26A0\uFE0F",f=a.isGoldStandard?" \u{1F3C6} _Gold Standard_":!o&&a.confirm_count>=3?` \u2713${a.confirm_count}`:"",m=Math.round(a.weightedScore*100);s.push(`${r}${f} **\`${a.topic}\`** [ctx: ${m}%]`),a.what_worked&&s.push(` \u2705 ${a.what_worked.slice(0,150)}`),a.what_failed&&s.push(` \u274C ${a.what_failed.slice(0,80)}`),s.push(` _${a.confirm_count} confirm${a.confirm_count!==1?"s":""} | id: \`${a.id}\`_`,"")}if(u.size>0){const a=[...u.entries()].sort((r,f)=>f[1]-r[1]).slice(0,5).map(([r,f])=>`\`${r}\`(${f})`).join(", ");s.push(`\u{1F3AF} Your context: ${a}`)}return s.push('\u{1F4A1} Confirm a result: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`'),s.join(`
|
|
13
|
-
`)}case"fedbrain_confirm":{const{instance_id:
|
|
14
|
-
`);const e=await I(
|
|
15
|
-
`)}case"fedbrain_status":{const{instance_id:
|
|
13
|
+
`)}case"fedbrain_confirm":{const{instance_id:_,id:i,topic:n,outcome:t}=N;if(!i)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 I(_),l=new Date().toISOString(),u=JSON.stringify({id:i,topic:n,outcome:t,ts:l});await e.rpush("cachly:fedbrain:confirmations",u),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const c=t==="worked",o=t==="partially_worked";n&&await T(e,k(n),"fixes",k(`syndicated:${n}`),c,o);let d;try{await K(`/api/v1/syndication/${encodeURIComponent(i)}/confirm`,{method:"POST"}),d="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",u),await e.ltrim("cachly:fedbrain:pending_confirms",-50,-1),d="\u{1F4E6} Queued locally (API unavailable \u2014 will propagate on next online session)"}return[`${c?"\u2705":o?"\u26A0\uFE0F":"\u274C"} **FedBrain Confirm: "${n??i}"** \u2192 ${t}`,"",d,"",n?`\u{1F578}\uFE0F CKG confidence ${c||o?"boosted":"reduced"} for \`${k(n)}\``:"\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,i=await I(_),n=await i.smembers("cachly:fedbrain:contributed"),t=await i.lrange("cachly:fedbrain:confirmations",-10,-1),e=await i.llen("cachly:fedbrain:pending_confirms"),l=t.map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(Boolean),u=[];for(const o of n.slice(0,15)){const d=await i.get(`cachly:fedbrain:cert:${o}`);if(d)try{const h=JSON.parse(d);u.push({cert_id:h.cert_id,lesson_key:h.lesson_key,confirm_count:h.confirm_count??0,trust_score:h.trust_score??.5,isGold:(h.confirm_count??0)>=10})}catch{}}const c=[`\u{1F310} **FedBrain Status**
|
|
16
16
|
`,`### \u{1F4E4} Contributed Lessons: ${n.length}`];if(u.length>0)for(const o of u){const d=o.isGold?" \u{1F3C6} Gold Standard":"",h="\u2588".repeat(Math.min(10,o.confirm_count))+"\u2591".repeat(Math.max(0,10-o.confirm_count));c.push(` \`${o.lesson_key}\` [${h}] \xD7${o.confirm_count}${d}`)}else c.push(' _None yet. Contribute with `fedbrain_contribute(lesson_key="fix:...")`_');if(c.push("",`### \u{1F4E5} Recent Confirmations: ${l.length}`),l.length>0)for(const o of l.slice(-5)){const d=o.outcome==="worked"?"\u2705":o.outcome==="partially_worked"?"\u26A0\uFE0F":"\u274C";c.push(` ${d} \`${o.topic}\` \u2014 ${o.outcome} (${new Date(o.ts).toLocaleDateString("de-DE")})`)}else c.push(" _None yet. Confirm syndicated lessons with `fedbrain_confirm`_");return e>0&&c.push("",`\u26A0\uFE0F ${e} confirmation${e!==1?"s":""} pending propagation`),c.push("","---",'**Contribute:** `fedbrain_contribute(lesson_key="fix:...")`','**Search:** `fedbrain_search(query="...")`','**Confirm:** `fedbrain_confirm(id="...", topic="...", outcome="worked")`'),c.join(`
|
|
17
|
-
`)}case"brain_federate":{const{instance_id:
|
|
18
|
-
`);let h=0,s=0,a=0,r=0;const f=[];for(const w of o){const
|
|
19
|
-
`)}case"crystal_view":{const{instance_id:
|
|
17
|
+
`)}case"brain_federate":{const{instance_id:_,source:i,domain:n,min_confidence:t=.6,dry_run:e=!1}=N;if(_===i)return"\u274C Source and destination cannot be the same brain.";const l=await I(_),u=await I(i),c=n==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${n}*`,o=[],d=u.scanStream({match:c,count:100});if(await new Promise((w,y)=>{d.on("data",j=>o.push(...j)),d.on("end",w),d.on("error",y)}),o.length===0)return[`\u{1F9E0} **brain_federate: "${n}"**`,"",`No CKG nodes found in source brain for domain \`${n}\`.`,"The source brain may not have knowledge in this area yet.",`Try: \`fedbrain_search(query="${n}")\` to find global commons knowledge instead.`].join(`
|
|
18
|
+
`);let h=0,s=0,a=0,r=0;const f=[];for(const w of o){const y=await u.get(w);if(!y)continue;let j;try{j=JSON.parse(y)}catch{continue}e||await l.set(w,y),h++;const C=await u.smembers(`cachly:ckg:idx:from:${j.id}`);for(const $ of C){const x=await u.get($);if(!x)continue;let v;try{v=JSON.parse(x)}catch{continue}if(v.confidence<t){r++;continue}e||(await l.set($,x),await l.sadd(`cachly:ckg:idx:from:${v.from}`,$),await l.sadd(`cachly:ckg:idx:to:${v.to}`,$)),s++}const g=`cachly:lesson:best:${j.id}`,S=await u.get(g);if(S&&(e||await l.set(g,S),a++,f.length<8))try{const $=JSON.parse(S),x=$.outcome==="success"?"\u2705":$.outcome==="failure"?"\u274C":"\u26A0\uFE0F";f.push(` ${x} \`${$.topic}\` \u2014 ${($.what_worked??"").slice(0,80)}`)}catch{}}if(!e){const w=JSON.stringify({source:i,domain:n,transferred_at:new Date().toISOString(),nodes:h,edges:s,lessons:a});await l.rpush("cachly:fedbrain:federations",w),await l.ltrim("cachly:fedbrain:federations",-50,-1)}const p=[`\u{1F9E0} **brain_federate: "${n}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${i}\``,`\u{1F4E5} Destination: \`${_}\``,`\u{1F50D} Domain filter: \`${n}\` | min_confidence: ${t}`,"","### Transfer Summary",` \u{1F578}\uFE0F CKG nodes: ${h}`,` \u{1F517} CKG edges: ${s} (${r} skipped, confidence < ${t})`,` \u{1F4DA} Lessons: ${a}`,""];return f.length>0&&(p.push("### Sample lessons transferred:",...f),a>f.length&&p.push(` _... and ${a-f.length} more_`),p.push("")),e?p.push("\u{1F4A1} Run without `dry_run: true` to apply the transfer."):(p.push(`\u2705 Transfer complete. Your brain now has the \`${n}\` knowledge from \`${i}\`.`),p.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${n}")\` | \`recall_best_solution(topic="${n}:...")\``)),p.join(`
|
|
19
|
+
`)}case"crystal_view":{const{instance_id:_,show_raw:i=!1}=N,n=await I(_),t=await n.get("cachly:crystal:latest");if(!t)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
20
|
`);const e=A(t,null);if(!e)return"\u274C Memory Crystal data is corrupted. Re-create with `memory_crystalize()`.";const l=Math.floor((Date.now()-new Date(e.ts).getTime())/864e5),u=l<=7?"\u{1F7E2}":l<=30?"\u{1F7E1}":"\u{1F534}",c=[`\u{1F48E} **Memory Crystal: ${e.label}**`,"",`\u{1F4C5} Created: ${new Date(e.ts).toLocaleDateString("de-DE")} (${l}d ago ${u})`,`\u{1F4CA} Compressed from: ${e.created_from}`,`\u{1F5C2}\uFE0F Categories: ${e.categories.slice(0,10).map(d=>`\`${d}\``).join(", ")}${e.categories.length>10?` +${e.categories.length-10} more`:""}`,"",`**\u{1F511} Top patterns (${e.top_patterns.length}):**`];for(const d of e.top_patterns)c.push(` \u2022 **${d.category}** (${d.count}\xD7): ${d.insight.slice(0,110)}`);l>30&&c.push("",`\u26A0\uFE0F Crystal is ${l}d old \u2014 run \`memory_crystalize()\` to refresh it.`),i&&c.push("","```json",JSON.stringify(e,null,2),"```");const o=await n.get("cachly:crystal:team:latest").catch(()=>null);if(o){const d=A(o,null);if(d&&d.patterns?.length){const h=Math.floor((Date.now()-new Date(d.ts).getTime())/864e5);c.push("","---",`\u{1F4A0} **Team Crystal: ${d.label}** _(${h}d ago \xB7 ${d.contributors} contributors)_`,"_Fixes multiple teammates independently converged on \u2014 the team-wide layer:_");for(const s of d.patterns.slice(0,5))c.push(` \u2022 \u{1F9E9} **${s.concept}** \u2014 ${s.author_count} people (${s.authors.map(a=>`@${a}`).join(", ")}): ${s.convergent_fix.slice(0,90)}`)}}return c.push("",'\u{1F4A1} Refresh: `memory_crystalize()` \xB7 `team_crystallize()` | Recover: `compact_recover(instance_id="...")`'),c.join(`
|
|
21
|
-
`)}case"compact_recover":{const{instance_id:
|
|
21
|
+
`)}case"compact_recover":{const{instance_id:_,focus:i=""}=N,n=await I(_),t=[`\u{1F501} **Compact Recovery Briefing**
|
|
22
22
|
`];t.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*
|
|
23
23
|
`);const e=await n.get("cachly:crystal:latest");if(e){const s=A(e,null);if(s){t.push(`### \u{1F48E} Memory Crystal: ${s.label}`),t.push(`Compressed from ${s.session_count} sessions, ${s.lesson_count} lessons.`);const a=i?s.top_patterns.filter(r=>r.category.toLowerCase().includes(i.toLowerCase())||r.insight.toLowerCase().includes(i.toLowerCase())).slice(0,4):s.top_patterns.slice(0,4);for(const r of a)t.push(` \u2022 **${r.category}**: ${r.insight.slice(0,100)}`);t.push("")}}const l=await n.get("cachly:session:last");if(l){const s=A(l,null);s&&(t.push("### \u{1F550} Last Session"),s.focus&&t.push(`Focus: _${s.focus}_`),s.summary&&t.push(`Summary: ${s.summary.slice(0,300)}`),t.push(""))}const u=await n.get("cachly:session:handoff");if(u){const s=A(u,null);if(s){if(t.push("### \u{1F4CB} Handoff (from last window)"),s.context_summary&&t.push(`Context: ${s.context_summary.slice(0,200)}`),s.remaining_tasks?.length){t.push("Remaining tasks:");for(const a of s.remaining_tasks.slice(0,5))t.push(` \u2022 ${a}`)}s.instructions&&t.push(`\u26A0\uFE0F Instructions: ${s.instructions.slice(0,200)}`),s.blocked_on&&t.push(`\u{1F6A7} Blocked on: ${s.blocked_on}`),t.push("")}}const c=await n.get("cachly:ctx:wip-registry");if(c){const s=A(c,null);s?.content&&(t.push("### \u{1F527} WIP Registry"),t.push(s.content.slice(0,400)),t.push(""))}const o=[],d=n.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((s,a)=>{d.on("data",r=>o.push(...r)),d.on("end",s),d.on("error",a)});const h=[];for(const s of o.slice(0,30)){const a=await n.get(s);if(a)try{const r=JSON.parse(a);(r.status==="in_progress"||r.status==="blocked")&&h.push({title:r.title??s,status:r.status,priority:r.priority})}catch{}}if(h.length>0){t.push("### \u{1F6A7} Open Items");for(const s of h.slice(0,5))t.push(` \u2022 [${s.status}] ${s.title}`);t.push("")}if(i){const s=[],a=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,m)=>{a.on("data",p=>s.push(...p)),a.on("end",f),a.on("error",m)});const r=[];for(const f of s){const m=await n.get(f);if(m)try{const p=JSON.parse(m);p.topic.toLowerCase().includes(i.toLowerCase())&&p.what_worked&&r.push({topic:p.topic,what_worked:p.what_worked})}catch{}}if(r.length>0){t.push(`### \u{1F4A1} Relevant Lessons for "${i}"`);for(const f of r.slice(0,4))t.push(` \u2022 **${f.topic}**: ${f.what_worked.slice(0,100)}`);t.push("")}}return t.length<=3&&t.push("_No brain data found. Start accumulating knowledge with `learn_from_attempts` and `session_start`._"),t.push("---","\u{1F9E0} Brain is ready. Continue your work \u2014 full context restored."),t.join(`
|
|
24
|
-
`)}case"brain_from_git":{const
|
|
25
|
-
`)){const
|
|
26
|
-
\u{1F9E0} brain_from_git: processing ${
|
|
27
|
-
`);for(let
|
|
28
|
-
`),
|
|
24
|
+
`)}case"brain_from_git":{const _=Date.now(),{instance_id:i,repo_path:n=".",limit:t=100,branch:e="HEAD",since:l="",incremental:u=!0}=N,c=await I(i),{execSync:o}=await import("node:child_process"),{resolve:d}=await import("node:path"),h=d(n),s=Math.min(Number(t)||100,500);await we();try{try{o("git rev-parse --git-dir",{cwd:h,stdio:"pipe"})}catch{return`\u274C Not a git repository: \`${h}\`. Pass \`repo_path\` pointing to a git checkout.`}const a=`cachly:brain_from_git:last_sha:${Buffer.from(h).toString("base64").slice(0,32)}`;let r="",f=!1;u!==!1&&!l&&(r=await c.get(a)??"",f=!!r);const m=l?`--since="${l}"`:"",w=(f?`${r}..HEAD`:"")||e,y=`git log ${w} ${m} --pretty=format:"COMMIT|||%H|||%s|||%ad|||%an" --date=short --no-merges --name-only -n ${s}`;let j="";try{j=o(y,{cwd:h,encoding:"utf-8",stdio:"pipe"})}catch(O){return`\u274C git log failed: ${O.message}. Check \`repo_path\` and \`branch\`.`}const C=[];let g=null;for(const O of j.split(`
|
|
25
|
+
`)){const b=O.trim();if(b.startsWith("COMMIT|||")){g&&C.push(g);const[,D,G,F,q]=b.split("|||");g={sha:(D??"").trim(),subject:(G??"").trim(),date:(F??"").trim(),author:(q??"").trim(),files:[]}}else if(b&&g){const D=re(b);D&&g.files.push(D)}}if(g&&C.push(g),C.length===0)return f?`\u2705 brain_from_git: Brain is up to date \u2014 no new commits since last run (last SHA: \`${r.slice(0,8)}\`).`:Z({repoDir:h,revRange:w,processed:0,ingested:0,skipped:0,durationMs:Date.now()-_,isIncremental:!1,instanceId:i,categories:[],suggestedQueries:[],emptyReason:`No commits found in \`${h}\` on branch \`${e}\`${l?` since ${l}`:""}.`});const S=new Date().toISOString();let $=0,x=0;const v=new Map,L=new Map,P=[];let R=null;const E=C.length,te=Math.max(1,Math.floor(E/10));let z=0;process.stderr.write(`
|
|
26
|
+
\u{1F9E0} brain_from_git: processing ${E} commits from ${h}...
|
|
27
|
+
`);for(let O=0;O<C.length;O++){const b=C[O];if(O-z>=te&&(process.stderr.write(` \u23F3 Processing ${O}/${E} commits (${$} lessons so far)...
|
|
28
|
+
`),z=O),!b.subject){x++;continue}const{category:D,outcome:G,severity:F}=he(b.subject),q=me(b.subject),M=`${D}:${q}`;v.set(D,(v.get(D)??0)+1),L.set(F,(L.get(F)??0)+1),P.push(M),(!R||D==="fix"&&!R.topic.startsWith("fix:"))&&(R={topic:M,subject:b.subject});const Y=b.files.filter(H=>H.length>0).slice(0,12),V={topic:M,outcome:G,severity:F,what_worked:b.subject.slice(0,200),what_failed:"",context:`git:${b.sha.slice(0,8)} by ${b.author} on ${b.date}`,author:b.author||void 0,file_paths:Y,commands:[`git show ${b.sha.slice(0,8)}`],tags:["brain_from_git",D,"git-history"],visibility:"team",depends_on:[],recall_count:0,ts:S,verified_at:S,confidence:.55,audit_trail:[{ts:S,action:"brain_from_git",sha:b.sha.slice(0,8)}],version:3};await c.get(`cachly:lesson:best:${M}`)||(await c.set(`cachly:lesson:best:${M}`,JSON.stringify(V),"EX",90*86400),await c.rpush(`cachly:lessons:${M}`,JSON.stringify(V)),await c.ltrim(`cachly:lessons:${M}`,-100,-1),await c.expire(`cachly:lessons:${M}`,90*86400)),await c.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:M,sha:b.sha.slice(0,8),subject:b.subject.slice(0,60)})),await c.ltrim("cachly:lessons:brain_from_git:all",-500,-1),await c.expire("cachly:lessons:brain_from_git:all",90*86400);const Q=k(M);if(await J(c,Q,D,"git-derived"),b.author)try{const H=await ie(c,b.author,D);await T(c,H,"authored",Q,G==="success",G==="partial");for(const se of Y.slice(0,8)){const X=await ae(c,se);await T(c,H,"touched",X,!0),await ce(c,X,H)}}catch{}$++}process.stderr.write(` \u2705 brain_from_git complete: ${$}/${E} commits ingested
|
|
29
29
|
|
|
30
|
-
`),C.length>0&&C[0]?.sha&&await c.set(a,C[0].sha,"EX",2160*3600),pe={fixes:
|
|
31
|
-
`)}case"brain_predict_failures":{const{instance_id:
|
|
30
|
+
`),C.length>0&&C[0]?.sha&&await c.set(a,C[0].sha,"EX",2160*3600),pe={fixes:v.get("fix")??0,features:v.get("feat")??0,refactors:v.get("refactor")??0,total:$};let W=null;if(R&&$>0)try{const O=await de(c,["cachly:lesson:best:*"],R.subject,1);if(O.length>0){const b=A(O[0].content,{});W={query:R.subject.slice(0,80),topic:b.topic??O[0].key.replace("cachly:lesson:best:",""),snippet:(b.what_worked??"").slice(0,120)||R.subject.slice(0,120)}}}catch{}return Z({repoDir:h,revRange:w,processed:C.length,ingested:$,skipped:x,durationMs:Date.now()-_,isIncremental:f,lastSha:r,instanceId:i,categories:[...v.entries()].sort((O,b)=>b[1]-O[1]),severities:[...L.entries()].sort((O,b)=>b[1]-O[1]),proof:W,suggestedQueries:fe(P,i)})}finally{ye()}}case"brain_from_ci":{const{instance_id:_,outcomes:i}=N,n=await I(_),t=Date.now();let e=0,l=0,u=0;const c=i.length;for(const o of i){const d=String(o.status??""),h=String(o.prev_status??""),s=String(o.job??"unknown"),a=String(o.context??""),r=["failure","red","error"].includes(h)&&["success","green","passed"].includes(d),f=["success","green","passed"].includes(h)&&["failure","red","error"].includes(d),m=`ci:${k(s)}`,p=k(m);if(await J(n,p,"ci","job"),r){const y=k(`problem:${k(s)}`);await J(n,y,"problem","ci-failure"),await T(n,p,"fixes",y,!0);const j={topic:m,outcome:"success",what_worked:`CI job "${s}" went ${h} \u2192 ${d}`,what_failed:`Job "${s}" was failing`,context:`brain_from_ci: ${a}`,severity:"major",file_paths:[],commands:[],tags:["brain_from_ci","ci"],depends_on:[],recall_count:0,ts:t,verified_at:t,confidence:.65,audit_trail:[{ts:t,action:"brain_from_ci_fixed"}],version:3};await n.rpush(`cachly:lessons:${m}`,JSON.stringify(j)),await n.ltrim(`cachly:lessons:${m}`,-100,-1),await n.set(`cachly:lesson:best:${m}`,JSON.stringify(j)),e++}else if(f){const y=k(`cause:${k(s)}`);await J(n,y,"cause","ci-break"),await T(n,p,"causes",y,!1),l++}else u++;const w=`cachly:cls:${_}`;await n.rpush(w,JSON.stringify({source:"ci_outcome",payload:{status:d,prev_status:h,job:s},ts:t})),await n.ltrim(w,-200,-1)}return ge={fixes:e,breaks:l,stable:u,total:c},[`\u{1F4E5} **brain_from_ci**: Ingested ${c} outcomes \u2014 ${e} fixes learned, ${l} breaks noted, ${u} stable`,"",e>0?`\u2705 ${e} fix lesson${e!==1?"s":""} written (confidence 0.65) \u2014 CKG \`fixes\` edges added`:"",l>0?`\u{1F534} ${l} break${l!==1?"s":""} noted \u2014 CKG \`causes\` edges added`:"",u>0?`\u{1F4CA} ${u} stable outcome${u!==1?"s":""} recorded`:"","",'\u{1F4A1} Explore: `brain_search(query="ci")` | `brain_predict(context="<job-name>")`'].filter(Boolean).join(`
|
|
31
|
+
`)}case"brain_predict_failures":{const{instance_id:_,context:i,top_k:n=5,format:t="detailed"}=N,e=await I(_),l=i.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g," ").split(/\s+/).filter(r=>r.length>2),u=[];for(const r of l.slice(0,8)){const f=[],m=e.scanStream({match:`cachly:ckg:node:*${r}*`,count:50});await new Promise((p,w)=>{m.on("data",y=>f.push(...y)),m.on("end",p),m.on("error",w)});for(const p of f.slice(0,5)){const w=await e.get(p);if(!w)continue;const y=A(w,null);if(!y)continue;const j=await e.smembers(`cachly:ckg:idx:from:${y.id}`);for(const C of j.slice(0,20)){const g=await e.get(C);if(!g)continue;const S=A(g,null);if(!S||S.edgeType!=="causes"&&S.edgeType!=="degrades_under")continue;const $=await e.smembers(`cachly:ckg:idx:from:${S.to}`);let x;for(const v of $.slice(0,10)){const L=await e.get(v);if(!L)continue;const P=A(L,null);if(P&&P.edgeType==="fixes"){const R=await e.get(`cachly:lesson:best:${P.from}`);if(R){x=A(R,null)?.what_worked?.slice(0,120);break}}}u.push({concept:y.id,failure:S.to.replace(/-/g," "),probability:S.confidence,fix:x,source:"ckg"})}}}const c=[],o=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((r,f)=>{o.on("data",m=>c.push(...m)),o.on("end",r),o.on("error",f)});for(const r of c.slice(0,100)){const f=await e.get(r);if(f)try{const m=JSON.parse(f);if(m.outcome!=="failure"&&m.outcome!=="partial"||!m.what_failed)continue;const p=`${m.topic} ${m.what_failed}`.toLowerCase(),w=l.filter(j=>p.includes(j)).length/Math.max(1,l.length);if(w<.15)continue;const y=m.severity==="critical"?.15:m.severity==="major"?.05:0;u.push({concept:m.topic,failure:m.what_failed.slice(0,80),probability:Math.min(.97,(m.confidence??.5)*w*1.5+y),fix:m.what_worked?.slice(0,120),topic:m.topic,source:"lesson"})}catch{}}if(u.length===0)return[`\u{1F52E} **Failure Prediction: "${i}"**`,"","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="${i}")\` for broader predictions.`].join(`
|
|
32
32
|
`);const d=new Set,h=u.filter(r=>{const f=r.failure.slice(0,40);return d.has(f)?!1:(d.add(f),!0)}).sort((r,f)=>f.probability-r.probability).slice(0,Number(n)),s=[`\u{1F52E} **Failure Prediction for: "${i}"**
|
|
33
33
|
`];s.push(`> Pre-deploy failure analysis based on ${u.length} patterns. Ranked by probability.
|
|
34
34
|
`);for(let r=0;r<h.length;r++){const f=h[r],m=Math.round(f.probability*100),p="\u2588".repeat(Math.round(m/10))+"\u2591".repeat(10-Math.round(m/10)),w=m>=70?"\u{1F534}":m>=40?"\u{1F7E1}":"\u{1F7E2}";s.push(`${w} **${r+1}. ${f.failure}**`),s.push(` Probability: ${p} **${m}%** (${f.source==="ckg"?"CKG causal edge":"lesson history"})`),t==="detailed"&&f.fix&&s.push(` \u2705 Pre-loaded fix: _${f.fix}_`),t==="detailed"&&f.topic&&s.push(` \u{1F4DA} Lesson: \`${f.topic}\``),s.push("")}const a=h.filter(r=>r.probability>=.6);return a.length>0?s.push(`\u26A0\uFE0F **${a.length} high-risk failure${a.length>1?"s":""} detected** (\u226560% probability). Review fixes before proceeding.`):s.push("\u2705 No high-risk failures detected. Proceed with caution and monitor closely."),s.push("",'\u{1F4A1} After deploy: `learn_from_attempts(topic="deploy:...", outcome="success|failure")` to improve future predictions.'),s.join(`
|
|
35
|
-
`)}case"brain_contribute_signal":{const{instance_id:
|
|
36
|
-
`)}case"brain_import_meta":{const{instance_id:
|
|
37
|
-
`);const l=await I(
|
|
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"}[l]??l}**`,"",`Hook path: \`${u}\``,`Instance: \`${
|
|
40
|
-
`)}default:return null}}export{
|
|
35
|
+
`)}case"brain_contribute_signal":{const{instance_id:_,topic_category:i,outcome:n,confidence:t=.5}=N;if(!i?.trim())throw new Error("topic_category is required");if(!["success","failure","partial"].includes(n))throw new Error("outcome must be success, failure, or partial");const e=t>=.75?"high":t>=.5?"medium":"low";let l="\u{1F4E6} Signal stored locally (commons API unavailable)";try{await K("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:i.trim().toLowerCase(),outcome:n,confidence:t})}),l="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const u=await I(_),c=`cachly:fed:outbox:${Date.now()}`;await u.set(c,JSON.stringify({topic_category:i,outcome:n,bucket:e,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${i}\`**`,"",`\u{1F4CA} Outcome: **${n}** \xB7 Confidence bucket: **${e}**`,"\u{1F6E1}\uFE0F Privacy: topic category only \u2014 no lesson text, no org identity","",l,"","\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:i,limit:n=20}=N;let t=[],e=3;try{const o=new URLSearchParams;i&&o.set("category",i),o.set("limit",String(Math.min(n,200)));const d=await K(`/api/v1/federation/meta?${o.toString()}`);t=d.meta_lessons??[],e=d.k_threshold??3}catch{return"\u274C Could not reach the global commons API. Try again later."}if(t.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
|
+
`);const l=await I(_);let u=0;for(const o of t){const d=`cachly:lesson:best:meta:${o.topic_category}`;await l.get(d)||(await l.set(d,JSON.stringify({topic:`meta:${o.topic_category}`,outcome:o.dominant_outcome,what_worked:o.contributor_count!=null?`Meta-pattern from ${o.contributor_count} independent orgs`:`Meta-pattern from ${o.signal_count} signals`,what_failed:"",recall_count:0,ts:o.derived_at,state:"meta",avg_confidence:o.avg_confidence,signal_count:o.signal_count,audit_trail:[{ts:new Date().toISOString(),action:"imported_meta"}]})),u++)}const c=[`\u{1F310} **Brain Import Meta-Lessons** (k \u2265 ${e})`,"","| Topic Category | Outcome | Confidence | Signals |","|---|---|---|---|"];for(const o of t.slice(0,15)){const d=(o.avg_confidence*100).toFixed(0)+"%";c.push(`| \`${o.topic_category}\` | ${o.dominant_outcome} | ${d} | ${o.signal_count} |`)}return t.length>15&&c.push(`| _\u2026${t.length-15} more_ | | | |`),c.push("",`\u2705 **${u}** new meta-lessons imported into local Brain.`),u<t.length&&c.push(`_(${t.length-u} already present \u2014 not overwritten)_`),c.join(`
|
|
38
|
+
`)}case"brain_watch":{const{instance_id:_="",project_dir:i=".",api_key:n}=N,{resolve:t}=await import("node:path"),e=t(i),{result:l,hookPath:u}=await ue(e,_,n);return l==="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"}[l]??l}**`,"",`Hook path: \`${u}\``,`Instance: \`${_||"(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(`
|
|
40
|
+
`)}default:return null}}export{Ne as FEDBRAIN_TOOL_NAMES,ge as _lastBrainFromCiCounts,pe as _lastBrainFromGitCounts,Ie as handleFedbrainTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as a}from"node:fs";import{homedir as f}from"node:os";import{join as n}from"node:path";import{readInstanceId as _,resolveApiKey as h}from"./credentials.js";import{echterWert as u}from"./zugang.js";function E(e=process.env){return{env:e,heim:e.HOME||e.USERPROFILE||f(),projekt:e.CLAUDE_PROJECT_DIR||process.cwd()}}function s(e){try{return JSON.parse(a(e,"utf8"))}catch{return null}}function i(e){return[n(e.heim,".claude","mcp.json"),n(e.projekt,".mcp.json"),n(e.heim,".cursor","mcp.json"),n(e.heim,".codeium","windsurf","mcp_config.json")].map(r=>{const o=s(r)?.mcpServers?.cachly?.env;return o&&typeof o=="object"?o:{}})}function m(...e){for(const r of e){const o=u(r);if(o)return o}return""}function N(e){return m(e.env.CLAUDE_PLUGIN_OPTION_API_KEY,h({env:e.env,home:e.heim,cwd:e.projekt}),...i(e).map(r=>r.CACHLY_JWT))}function k(e){return m(e.env.CLAUDE_PLUGIN_OPTION_INSTANCE_ID,e.env.CACHLY_BRAIN_INSTANCE_ID,_({home:e.heim}),...i(e).map(r=>r.CACHLY_BRAIN_INSTANCE_ID))}const A="cachly-ambient-";function O(e,r){return[n(r.projekt,".claude","settings.json"),n(r.projekt,".claude","settings.local.json"),n(r.heim,".claude","settings.json")].some(o=>{const t=s(o)?.hooks?.[e];return Array.isArray(t)&&t.some(c=>Array.isArray(c?.hooks)&&c.hooks.some(p=>String(p?.command??"").includes(A)))})}export{A as PROJEKT_HOOK_MARKE,k as findeInstanz,N as findeSchluessel,E as hookUmfeld,O as projektHatHook};
|