@cachly-dev/mcp-server 0.10.187 → 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/geheimnis-filter.js +1 -1
- package/dist/src/handlers/advanced.js +11 -11
- package/dist/src/handlers/brain.js +70 -68
- package/dist/src/handlers/context.js +13 -13
- 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 +51 -48
- package/dist/src/schreibtor.js +1 -0
- package/dist/src/tuersteher.js +1 -0
- package/dist/src/verdacht-marke.js +1 -0
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +21 -21
- package/package.json +3 -2
- package/server.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Seltenheit as
|
|
1
|
+
import{Seltenheit as f,inhaltsWoerter as c,grobStamm as p,spreizeImTopf as d}from"./rangfolge.js";import{lektionsText as w}from"./seltenheitsbestand.js";import{bestandAusDokumenten as g,keywordSearchMitBestand as k}from"./search.js";import{SINN_TOPF as E,EINBLENDUNG_DECKUNG as b,EINBLENDUNG_ZEUGE as N}from"./rangfolge-stellschrauben.js";import{istMarkiert as S}from"./verdacht-marke.js";import{rahmeEin as U,entschaerfe as j,RAHMEN_ETIKETT as B,RAHMEN_HINWEIS as P}from"./einblendung-rahmen.js";import{stopAntwort as F}from"./schreibbeleg.js";const x=E,_=["topic","outcome","what_worked","what_failed","severity","confidence","recall_count","ts","endorsements"],m=new Set("the a an and or but for to of in on at is are be do does did we you i it this that with without how what why when where can could would should please just get set use using make made need bitte und oder der die das ein eine f\xFCr mit ohne wie was warum kann soll noch mal auch von den dem ist weil wenn dann doch aber alle jede jeder jedes immer wieder wird werden wurde muss beim sehr nicht".split(/\s+/)),T=["ierungen","ierung","ieren","iert","ungen","ung","heit","keit","lich","isch","ing","ed","en","er","es","e","n","s"];function z(s){for(const e of T)if(s.length-e.length>=4&&s.endsWith(e))return s.slice(0,-e.length);return s}function y(s){return[...new Set(String(s).toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>3&&!m.has(e)).map(z).filter(e=>!m.has(e)))]}function I(s,e){let i=0;for(const o of s)e.includes(o)&&i++;return i}class A{texte;wortmengen;heuhaufen;statistik;wortbestand;platzVonSchluessel=new Map;topf;lektionen;constructor(e,{topf:i=x}={}){const o=e.filter(n=>!S(n));this.lektionen=o,this.topf=i,this.texte=o.map(n=>w(n)),this.wortmengen=this.texte.map(n=>new Set([...c(n)].map(p))),this.heuhaufen=this.texte.map(n=>n.toLowerCase()),this.statistik=new f(this.texte);const h=o.map((n,a)=>{const l=`cachly:lesson:best:${String(n.topic??a)}`;this.platzVonSchluessel.set(l,a);const u={};for(const t of _)n[t]!==void 0&&(u[t]=n[t]);return{key:l,content:JSON.stringify(u)}});this.wortbestand=g(h)}get groesse(){return this.lektionen.length}sortiere(e){if(!this.wortbestand)return[];const i=k(this.wortbestand,e,this.topf),o=[],h=[];for(const t of i){const r=this.platzVonSchluessel.get(t.key);r!==void 0&&(o.push(r),h.push(t.score))}if(o.length===0)return[];const n=c(e),a=y(e),l=d(h),u=d(o.map(t=>this.statistik.besterZeuge(n,this.wortmengen[t])));return o.map((t,r)=>({lektion:this.lektionen[t],punkte:l[r]+b*this.statistik.deckung(n,this.wortmengen[t])+N*u[r],belege:I(a,this.heuhaufen[t])})).sort((t,r)=>r.punkte-t.punkte||Number(r.lektion.recall_count??0)-Number(t.lektion.recall_count??0))}}export{A as Einblendbestand,_ as INDEX_FELDER,B as RAHMEN_ETIKETT,P as RAHMEN_HINWEIS,x as WORT_TOPF,j as entschaerfe,U as rahmeEin,z as stammKuerzen,F as stopAntwort,y as torWoerter,I as zaehleBelege};
|
package/dist/src/einblendung.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{readFileSync as I,existsSync as v,writeFileSync as b,mkdirSync as D,statSync as Y,appendFileSync as J}from"node:fs";import{dirname as k,join as h}from"node:path";import{tmpdir as m}from"node:os";import{createHash as q}from"node:crypto";import{spawn as Z}from"node:child_process";import{Einblendbestand as x,torWoerter as L}from"./einblendung-kern.js";import{rahmeEin as N}from"./einblendung-rahmen.js";import{
|
|
1
|
+
import{readFileSync as I,existsSync as v,writeFileSync as b,mkdirSync as D,statSync as Y,appendFileSync as J}from"node:fs";import{dirname as k,join as h}from"node:path";import{tmpdir as m}from"node:os";import{createHash as q}from"node:crypto";import{spawn as Z}from"node:child_process";import{Einblendbestand as x,torWoerter as L}from"./einblendung-kern.js";import{rahmeEin as N}from"./einblendung-rahmen.js";import{istMarkiert as z}from"./verdacht-marke.js";import{leserText as F}from"./seltenheitsbestand.js";import{mischeMitLeser as C}from"./leser.js";import{LeserSicherung as G,dateiSpeicher as K,frageLeser as W}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as V,LESER_ZEITLIMIT_MS as X}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as Q}from"./gueltigkeit-version.js";export*from"./einblendung-kern.js";const ee=600*1e3,T=8e3,te=60*1e3,j=120,$=V,ne=1500,R=X,re=h(m(),"cachly-ambient-netlog.jsonl");function xe(e=process.cwd()){const t={apiUrl:process.env.CACHLY_API_URL||"https://api.cachly.dev",jwt:process.env.CACHLY_JWT||"",instanceId:process.env.CACHLY_BRAIN_INSTANCE_ID||""};if(t.jwt&&t.instanceId)return t;let n=e;for(let o=0;o<8;o++){const s=h(n,".mcp.json");if(v(s))try{const i=JSON.parse(I(s,"utf8"))?.mcpServers?.cachly?.env??{};if(t.apiUrl=t.apiUrl||i.CACHLY_API_URL||"https://api.cachly.dev",t.jwt=t.jwt||i.CACHLY_JWT||"",t.instanceId=t.instanceId||i.CACHLY_BRAIN_INSTANCE_ID||"",t.jwt&&t.instanceId)return t}catch{}const r=k(n);if(r===n)break;n=r}return t}function S(e){return q("sha1").update(e).digest("hex").slice(0,12)}function se(e){return h(m(),`cachly-ambient-bestand-${S(e)}.json`)}function oe(e){return h(m(),`cachly-leser-sicherung-${S(e)}.json`)}function ie(e){return h(m(),`cachly-ambient-auffrischen-${S(e)}.lock`)}async function M(e,{fetchFn:t=fetch,zeitlimitMs:n=T}={}){try{const o=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(n)});if(!o.ok)return null;const s=await o.json();return Array.isArray(s?.lessons)?s.lessons.map(r=>typeof r=="string"?ae(r):r).filter(r=>!!r&&typeof r=="object"):null}catch{return null}}function ae(e){try{return JSON.parse(e)}catch{return null}}function H(e,t){try{D(k(e),{recursive:!0}),b(e,JSON.stringify({at:Date.now(),lessons:t}),{mode:384})}catch{}}function O(e){try{const t=JSON.parse(I(e,"utf8"));if(Array.isArray(t?.lessons))return{at:Number(t.at)||0,lessons:t.lessons}}catch{}return null}function ce(e,t){const n=ie(e.instanceId);try{if(v(n)&&Date.now()-Y(n).mtimeMs<te)return;b(n,String(Date.now()),{mode:384})}catch{return}try{Z(process.execPath,t,{detached:!0,stdio:"ignore",env:{...process.env,CACHLY_API_URL:e.apiUrl,CACHLY_JWT:e.jwt,CACHLY_BRAIN_INSTANCE_ID:e.instanceId}}).unref()}catch{}}async function le(e,{force:t=!1,nebenlauf:n,abrufMs:o=T,fetchFn:s}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const r=se(e.instanceId);if(t){const c=await M(e,{fetchFn:s,zeitlimitMs:o});if(c)return H(r,c),{lessons:c,quelle:"server"};const l=O(r);return l?{lessons:l.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const i=O(r);if(i){const c=Date.now()-i.at<ee;return!c&&n&&ce(e,n),{lessons:i.lessons,quelle:c?"platte":"platte-alt"}}const u=await M(e,{fetchFn:s,zeitlimitMs:o});return u?(H(r,u),{lessons:u,quelle:"server"}):{lessons:[],quelle:"server-nicht-erreichbar"}}function g(e){return Math.ceil(String(e).length/4)}function E(e){const t=e.severity?`[${e.severity}] `:"",n=String(e.what_worked??"").replace(/\s+/g," ").trim(),o=n.length>j?`${n.slice(0,j)}\u2026`:n,s=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${s}: ${o}`}const d={lessons:[],tokens:0,topScore:0,belege:0};function U(e,t,n){const o=[];let s=0;e=Q(e);for(const{lektion:r}of e.slice(0,t)){const i=g(E(r));if(s+i>n)break;o.push(r),s+=i}return{lessons:o,tokens:s,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function Le(e,t,{minBelege:n=2,topK:o=3,tokenBudget:s=600}={}){if(!Array.isArray(t)||t.length===0)return{...d};if(L(e).length===0)return{...d};const r=new x(t).sortiere(e).filter(i=>i.belege>=n);return r.length===0?{...d}:U(r,o,s)}function ue(e){return F(e,ne)}async function B(e,t,n,{zeitlimitMs:o=R,fetchFn:s}={}){if(!e?.jwt||!e?.instanceId||n.length===0)return{art:"ohne"};if(["0","off","aus","false"].includes(String(process.env.CACHLY_LESER||"").toLowerCase()))return{art:"ohne"};const r=new G(K(oe(e.instanceId)));return W({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:n,instanceId:e.instanceId,zeitlimitMs:o,fetchFn:s},r)}async function Ne(e,t,n,o={}){const s=await B(e,t,n,o);return s.art==="punkte"?{scores:s.scores,provider:s.provider,ms:s.ms}:null}async function pe(e,t,n,{minBelege:o=2,topK:s=3,tokenBudget:r=600,tiefe:i=$,zeitlimitMs:u=R,fetchFn:c}={}){const l={...d,leser:"aus",leserMs:0};if(!Array.isArray(t)||t.length===0||L(e).length===0)return l;let a=new x(t).sortiere(e).filter(p=>p.belege>=o);if(a.length===0)return l;let y="aus",w=0;if(a.length>1&&i>0){const p=a.slice(0,i),P=a.slice(i),f=await B(n,e,p.map(A=>ue(A.lektion)),{zeitlimitMs:u,fetchFn:c});f.art==="punkte"?(a=[...C(p.map(_=>_.punkte),f.scores,1).map(_=>p[_]),...P],y=f.provider,w=f.ms):f.art==="uebersprungen"&&(y="uebersprungen")}return{...U(a,s,r),leser:y,leserMs:w}}function fe(e){if(!e.lessons.length)return"";const t=e.lessons.map(E).join(`
|
|
2
2
|
`);return`\u{1F9E0} Cachly Brain \u2014 relevant lessons for this task (auto-recall, ${e.lessons.length}):
|
|
3
3
|
${N(t)}
|
|
4
|
-
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const
|
|
5
|
-
`);return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${
|
|
6
|
-
${N(
|
|
7
|
-
(Relevant lessons for each task are auto-injected per prompt. ~${g(
|
|
8
|
-
`)}catch{}return{kontext:
|
|
4
|
+
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const he=5;function Ce(e){const t=e.filter(r=>!z(r));if(!t.length)return"";const n=t.filter(r=>{const i=String(r.topic??"");return!(/^auto:/.test(i)||/^[a-z]+:?$/.test(i))}),s=[...n.length?n:t].sort((r,i)=>(Number(i.recall_count)||0)-(Number(r.recall_count)||0)).slice(0,he).map(E).join(`
|
|
5
|
+
`);return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${t.length} lessons). Top by proven reuse:
|
|
6
|
+
${N(s)}
|
|
7
|
+
(Relevant lessons for each task are auto-injected per prompt. ~${g(s)} tokens.)`}function Te(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}async function je(e,t,{nebenlauf:n,abrufMs:o,leser:s=!0,session:r=null,protokoll:i=!0,fetchFn:u}={}){const{lessons:c,quelle:l}=await le(t,{nebenlauf:n,abrufMs:o,fetchFn:u}),a=await pe(e,c,t,{tiefe:s?$:0,fetchFn:u});if(i)try{J(re,JSON.stringify({at:Date.now(),session:r,prompt_tokens:g(e),injected_tokens:a.tokens,matches:a.lessons.length,top_score:a.topScore,belege:a.belege,leser:a.leser,leser_ms:a.leserMs,quelle:l,bestand:c.length})+`
|
|
8
|
+
`)}catch{}return{kontext:fe(a),auswahl:a,quelle:l,bestand:c.length}}export{T as ABRUF_TIMEOUT_MS,j as ANZEIGE_ZEICHEN,ee as BESTAND_TTL_MS,R as LESER_HOOK_ZEITLIMIT_MS,ne as LESER_MAX_ZEICHEN,$ as LESER_TIEFE,re as NETZ_PROTOKOLL,he as SITZUNG_TOP_N,se as bestandPfad,g as estimateTokens,le as holeBestand,Te as hookAusgabe,B as leserAnfrageApi,Ne as leserPunkteApi,ue as leserText,C as mischeMitLeser,je as promptEinblendung,fe as promptKontext,E as renderLesson,xe as resolveConfig,Le as selectRelevant,pe as selectRelevantMitLeser,oe as sicherungsPfad,Ce as sitzungsKontext,ce as starteNebenlauf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const p="[GESCHWAERZT]",i=
|
|
1
|
+
const p="[GESCHWAERZT]",c=/x{12,}/i,A=e=>/\d/.test(e)&&/[A-Za-z]/.test(e),u=e=>/^[A-Z][A-Z0-9_]{2,}$/.test(e)||/environ|process\.env|secrets\./i.test(e),b="(?!(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[::1\\])[:/\\s])",_=[{name:"privater Schluessel",re:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g},{name:"AWS-Zugangsschluessel",re:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"GitHub-Token",re:/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/g},{name:"GitLab-Token",re:/\bglpat-[A-Za-z0-9_-]{20,}\b/g},{name:"Slack-Token",re:/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g},{name:"Stripe-Schluessel",re:/\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}\b/g},{name:"KI-Anbieter-Schluessel",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}\b/g},{name:"JWT",re:/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g},{name:"Telegram-Bot-Token",re:/\b\d{8,10}:[A-Za-z0-9_-]{30,}\b/g},{name:"npm-Token",re:/\bnpm_[A-Za-z0-9]{36}\b/g},{name:"Google-API-Schluessel",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"SendGrid-Schluessel",re:/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g},{name:"Hugging-Face-Token",re:/\bhf_[A-Za-z0-9]{30,}\b/g},{name:"PyPI-Token",re:/\bpypi-[A-Za-z0-9_-]{40,}\b/g},{name:"Docker-Hub-Token",re:/\bdckr_pat_[A-Za-z0-9_-]{20,}\b/g},{name:"Resend-Schluessel",re:/\bre_[A-Za-z0-9_]{20,}\b/g,ausser:e=>!/\d/.test(e)},{name:"Bearer-Token",re:/\b(?:Bearer|Token)\s+((?![$<{])[A-Za-z0-9._~+/-]{20,}=*)/gi,gruppe:1},{name:"Basic-Auth-Kopfzeile",re:/\bauthorization\s*:\s*basic\s+((?![$<{])[A-Za-z0-9+/]{12,}={0,2})/gi,gruppe:1},{name:"Passwort in URL",re:new RegExp(`\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:/@]+:((?![$<{])[^\\s/@]{6,})@${b}`,"gi"),gruppe:1},{name:"Schluessel-Zuweisung",re:/(?:password|passwort|passwd|pwd|secret|client[_-]?secret|api[_-]?key|access[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key|secret[_-]?key|signing[_-]?key|encryption[_-]?key)["']?\s*[:=]\s*["']?((?![$<{%])[^\s"'`,;)]{8,})/gi,gruppe:1,ausser:u},{name:"Token-Zuweisung",re:/token["']?\s*[:=]\s*["']?((?![$<{%])[^\s"'`,;)]{12,})/gi,gruppe:1,ausser:e=>u(e)||!A(e)},{name:"Passwort in Anfuehrungszeichen",re:/(?:password|passwort|kennwort|passwd)\s+(?:ist\s+|is\s+|lautet\s+)?["„“'‘]((?![$<{%])[^"”“'’\s]{6,})["”“'’]/gi,gruppe:1,ausser:u},{name:"TOTP-Seed",re:/\b(?:totp|otp|mfa|2fa)[-_ ]?(?:seed|secret|key|schluessel)\s*[:=]?\s*["']?([A-Z2-7]{16,}=*)/gi,gruppe:1,ausser:e=>/^[a-z]+$/.test(e)}];function g(e){let t=String(e??"");const o=[];for(const s of _)t=t.replace(s.re,(n,...a)=>{const r=s.gruppe===void 0?n:a[s.gruppe-1];return typeof r!="string"||!r||r.includes(p)||c.test(r)||s.ausser?.(r)?n:(o.push(s.name),s.gruppe===void 0?p:n.replace(r,p))});return{text:t,funde:o}}function l(e){const t={...e},o=[];for(const[s,n]of Object.entries(e))if(typeof n=="string"){const a=g(n);t[s]=a.text,o.push(...a.funde.map(r=>`${s}: ${r}`))}else Array.isArray(n)&&(t[s]=n.map(a=>{if(typeof a!="string")return a;const r=g(a);return o.push(...r.funde.map(i=>`${s}: ${i}`)),r.text}));return{felder:t,funde:o}}export{p as GESCHWAERZT,g as schwaerze,l as schwaerzeFelder};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{ckgSlug as
|
|
2
|
-
`)}case"brain_diff":{const{instance_id:l,since:
|
|
3
|
-
`)}case"causal_trace":{const{instance_id:l,problem:
|
|
1
|
+
import{ckgSlug as I}from"../ckg.js";import{safeJsonParse as x,darfHeraus as N}from"../utils.js";import{ersparteMinuten as K,zaehltAlsErsparnis as O}from"../wertbeitrag.js";import{findePaare as F}from"../zulassung-und-urteil.js";import{sofortAntwortNeuesBrain as P}from"../leeres-brain.js";import{fuerWeitergabe as U}from"../schreibtor.js";function E(C){return N(C)&&!C.group}const J=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function Y(C,A,M,L){switch(C){case"memory_consolidate":{const{instance_id:l,dry_run:p=!1,stale_days:$=90}=A,m=await M(l),g=Date.now(),d=$*86400*1e3;let u=0;const _=[];do{const[n,a]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(n),_.push(...a)}while(u!==0);if(_.length===0)return"\u{1F9E0} **Brain is empty** \u2014 no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.";const c=new Map;for(const n of _){const a=await m.get(n);if(!a)continue;const e=x(a,null);e&&c.set(n,e)}const w=new Map;for(const[n,a]of c){const e=a.topic.split(":")[0],o=w.get(e)??[];o.push(n),w.set(e,o)}const y=[...c.values()],b=F(y),v=b.filter(n=>n.beziehung==="widerspruch"),h=b.filter(n=>n.beziehung==="ersetzung"),k=[],s=new Map;for(const[n,a]of c){const e=s.get(a.topic)??[];e.push(n),s.set(a.topic,e)}for(const[n,a]of s)new Set(a.map(o=>c.get(o)?.outcome)).size>1&&k.push({topic:n,keys:a});const t=[];for(const[n,a]of c){const e=g-new Date(a.ts).getTime(),o=a.recall_count??0;e>d&&o===0&&t.push(n)}const i=0;if(!p)for(const n of t)await m.expire(n,86400*30);return[`\u{1F52C} **Memory Consolidation Report** ${p?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${_.length} lessons`,"",`\u{1F501} **Contradictions \u2014 exact topic match (old rule):** ${k.length}`,`\u{1F50E} **Same subject, admitted for judgement:** ${b.length} \u2192 contradiction ${v.length} \xB7 supersession ${h.length}`,...v.slice(0,5).map(n=>` \u2192 \`${n.a.topic}\` vs \`${n.b.topic}\` (${n.naehe.toFixed(2)}): ${n.grund}`),v.length>5?` \u2026 and ${v.length-5} more`:"",...h.slice(0,3).map(n=>` \u21BB \`${n.a.topic}\` \u2192 \`${n.b.topic}\`: ${n.grund}`),...k.slice(0,5).map(n=>` \u2192 \`${n.topic}\`: ${n.keys.length} conflicting entries (kept: success)`),k.length>5?` \u2026 and ${k.length-5} more`:"","",`\u267B\uFE0F **Duplicate clusters (counted, never deleted):** ${Array.from(w.values()).filter(n=>n.length>1).length}`,"",`\u{1F570}\uFE0F **Stale entries (${$}d, 0 recalls):** ${t.length}`+(t.length>0&&!p?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${_.length-i} lessons`,"",p?"\u{1F4A1} Re-run without dry_run=true to apply changes.":'\u2728 Brain consolidated. Run `brain_diff(since="1h")` to see the delta.'].filter(n=>n!=="").join(`
|
|
2
|
+
`)}case"brain_diff":{const{instance_id:l,since:p="7d",format:$="summary"}=A,m=await M(l);let g;const d=p.match(/^(\d+)([dhm])$/);if(d){const e=parseInt(d[1]),o=d[2],r=o==="d"?864e5:o==="h"?36e5:6e4;g=Date.now()-e*r}else g=new Date(p).getTime()||Date.now()-7*864e5;let u=0;const _=[];do{const[e,o]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(e),_.push(...o)}while(u!==0);const c=[],w=[],y=[],b=_.length;for(const e of _){const o=await m.get(e);if(o){const r=x(o,null);if(!r)continue;if(new Date(r.ts).getTime()>=g){const T=`cachly:lesson:history:${r.topic}`;await m.llen(T)<=1?c.push(r):w.push(r)}(r.recall_count??0)>0&&y.push(r)}}const h=[`\u{1F4CA} **Brain Diff** \u2014 ${d?`last ${p}`:new Date(g).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${b}**`,"",`\u2705 **New** (${c.length}):`,...c.slice(0,$==="detailed"?20:5).map(e=>` + \`${e.topic}\` \u2014 ${e.outcome} ${e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u{1F7E0}":"\u{1F7E2}"}`),c.length>5&&$==="summary"?` \u2026 and ${c.length-5} more`:"","",`\u{1F504} **Updated** (${w.length}):`,...w.slice(0,$==="detailed"?20:5).map(e=>` ~ \`${e.topic}\` \u2014 now: ${e.outcome}`),w.length>5&&$==="summary"?` \u2026 and ${w.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${y.length}`,""].filter(e=>e!==""),k=[],s=m.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((e,o)=>{s.on("data",r=>k.push(...r)),s.on("end",e),s.on("error",o)});const t=[];for(const e of k){const o=await m.get(e);if(o){const r=x(o,null);r?.ts&&new Date(r.ts).getTime()>=g&&t.push({topic:r.topic??e,resolution:r.resolution??"unknown",ts:r.ts})}}if(t.length>0){h.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${t.length} contested beliefs resolved):`);for(const e of t.slice(0,5)){const o=e.resolution==="unanimous_success"?"\u2705":e.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";h.push(` ${o} \`${e.topic}\` \u2192 ${e.resolution}`)}h.push("")}const i=new Set(w.concat(y).map(e=>e.topic.split(":")[0])),f=[...new Set(c.map(e=>e.topic.split(":")[0]))].filter(e=>!i.has(e));f.length>0&&h.push(`\u{1F331} **New domains bootstrapped:** ${f.map(e=>`\`${e}\``).join(", ")}`,"");const a=(await m.lrange("cachly:fedbrain:federations",-20,-1)).map(e=>x(e,null)).filter(e=>e!==null&&new Date(e.transferred_at).getTime()>=g);if(a.length>0){h.push(`\u{1F9E0} **FedBrain transfers received (${a.length}):**`);for(const e of a.slice(0,3))h.push(` \u{1F4E5} domain \`${e.domain}\` from \`${e.source.slice(0,16)}\u2026\` \u2014 ${e.nodes} nodes, ${e.edges} edges`);h.push("")}return h.push("\u{1F4A1} Run `memory_consolidate` to merge duplicates \xB7 `knowledge_decay` to see confidence scores."),h.join(`
|
|
3
|
+
`)}case"causal_trace":{const{instance_id:l,problem:p,max_depth:$=5,tags:m=[]}=A,g=await P(l,L,`\u{1F50D} **Causal Trace: "${p}"**
|
|
4
4
|
|
|
5
|
-
No matching lessons found in brain.`);if(
|
|
6
|
-
`);const s=[`\u{1F50D} **Causal Trace: "${
|
|
7
|
-
`)}case"knowledge_decay":{let
|
|
8
|
-
${
|
|
9
|
-
`)}case"autopilot":{const{instance_id:l,editor:
|
|
5
|
+
No matching lessons found in brain.`);if(g)return g;const d=await M(l),u=p.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(t=>t.length>2),_={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},c=[];try{for(const t of u.slice(0,4)){const i=await d.smembers(`cachly:ckg:idx:from:${I(t)}`),f=await d.smembers(`cachly:ckg:idx:to:${I(t)}`),n=[],a=d.scanStream({match:`cachly:ckg:node:*${t}*`,count:50});await new Promise((e,o)=>{a.on("data",r=>n.push(...r)),a.on("end",e),a.on("error",o)});for(const e of n.slice(0,10)){const o=await d.get(e);if(!o)continue;const r=x(o,null);if(!r)continue;const D=await d.smembers(`cachly:ckg:idx:from:${r.id}`);for(const T of D.slice(0,20)){const R=await d.get(T);if(!R)continue;const S=x(R,null);if(!S||S.edgeType!=="fixes"&&S.edgeType!=="requires")continue;const j=await d.get(`cachly:lesson:best:${S.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),B=j?x(j,null)??void 0:void 0;c.push({conceptId:r.id,edge:S,lesson:B&&E(B)?B:void 0})}}for(const e of[...i,...f].slice(0,20)){const o=await d.get(e);if(!o)continue;const r=x(o,null);if(!r)continue;const D=await d.get(`cachly:lesson:best:${r.from}`),T=D?x(D,null)??void 0:void 0;c.push({conceptId:r.from,edge:r,lesson:T&&E(T)?T:void 0})}}}catch{}const w=new Set,y=c.filter(t=>{const i=`${t.edge.from}:${t.edge.edgeType}:${t.edge.to}`;return w.has(i)?!1:(w.add(i),!0)}).sort((t,i)=>i.edge.confidence-t.edge.confidence).slice(0,$);let b=0;const v=[];do{const[t,i]=await d.scan(b,"MATCH","cachly:lesson:*","COUNT",200);b=parseInt(t),v.push(...i)}while(b!==0);const h=[];for(const t of v){const i=await d.get(t);if(i){const f=x(i,null);if(!f||!E(f)||m.length>0&&!(f.tags??[]).some(e=>m.includes(e)))continue;const n=[f.topic,f.what_failed??"",f.what_worked??"",f.context??""].join(" ").toLowerCase(),a=u.reduce((e,o)=>e+(n.includes(o)?1:0),0);a>0&&h.push({score:a,lesson:f,key:t})}}h.sort((t,i)=>i.score-t.score);const k=h.slice(0,$);if(k.length===0&&y.length===0)return[`\u{1F50D} **Causal Trace: "${p}"**`,"","No matching lessons found in brain.","","\u{1F4A1} After you solve this, call:","```","learn_from_attempts(",` instance_id = "${l}",`,` topic = "fix:${u[0]??"issue"}",`,' outcome = "success",',' what_worked = "...",',` what_failed = "${p}",`,")","```"].join(`
|
|
6
|
+
`);const s=[`\u{1F50D} **Causal Trace: "${p}"**`,""];if(y.length>0){s.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const t of y){const i=Math.round(t.edge.confidence*100),f="\u2593".repeat(Math.round(i/10))+"\u2591".repeat(10-Math.round(i/10));s.push(` ${t.edge.from} **\u2192[${t.edge.edgeType}]\u2192** ${t.edge.to}`),s.push(` ${f} ${i}% confidence (${t.edge.successes}/${t.edge.trials} confirmed)`),t.lesson?.what_worked&&s.push(` \u2705 Fix: ${t.lesson.what_worked.slice(0,150)}`),s.push("")}}if(k.length>0){s.push(y.length>0?`### \u{1F4DA} Text Search (${k.length} related lessons)`:`Found **${k.length}** related lessons. Reconstructed causal chain:`,"");const t=k.filter(n=>n.lesson.outcome!=="success"),i=k.filter(n=>n.lesson.outcome==="success");t.length>0&&(s.push("**Root causes & failure chain:**"),t.forEach((n,a)=>{const e=n.lesson,o=_[e.severity??"minor"]??"\u{1F7E1}";s.push(`${a===0?" Root:":" \u2192 :"} ${o} \`${e.topic}\``),e.what_failed&&s.push(` \u21B3 ${e.what_failed.slice(0,120)}`)}),s.push("")),i.length>0&&(s.push("**Solutions that worked before:**"),i.forEach((n,a)=>{const e=n.lesson,o=new Date(e.ts).toLocaleDateString("de-DE");s.push(` ${a+1}. \u2705 \`${e.topic}\` \u2014 ${o} \xB7 recalled ${e.recall_count??0}\xD7`),e.what_worked&&s.push(` ${e.what_worked.slice(0,200)}`)}),s.push(""));const f=i[0]?.lesson;if(f?.what_worked){s.push("**\u26A1 Most likely fix:**"),s.push("```"),s.push(f.what_worked.slice(0,500)),s.push("```"),s.push("");const n=O(f)?K(f,"trace"):0;n>0&&d.incrbyfloat(`cachly:stats:time_saved_mins:${l}`,n).catch(()=>{})}}return s.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${u[0]??"issue"}", outcome="success", ...)\``),y.length>0&&s.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${u[0]??"fix"}")\``),s.join(`
|
|
7
|
+
`)}case"knowledge_decay":{let y=function(s){const t=Math.round(s/10);return"\u2588".repeat(t)+"\u2591".repeat(10-t)+` ${s}%`};const{instance_id:l,min_age_days:p=0,show_top:$=20}=A,m=await M(l),g=Date.now(),d=p*864e5;let u=0;const _=[];do{const[s,t]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(s),_.push(...t)}while(u!==0);const c=[];for(const s of _){const t=await m.get(s);if(t){const i=x(t,null);if(!i)continue;const f=g-new Date(i.ts).getTime();if(f<d)continue;const n=Math.floor(f/864e5),a=i.recall_count??0,e=Math.max(0,n-7),o=Math.max(5,100-e),r=Math.min(50,a*5),D=i.outcome==="failure"?-20:0,T=Math.min(100,Math.max(0,o+r+D));c.push({topic:i.topic,confidence:T,age_days:n,recalls:a,outcome:i.outcome})}}c.sort((s,t)=>s.confidence-t.confidence);const w=c.slice(0,$),b=c.length>0?Math.round(c.reduce((s,t)=>s+t.confidence,0)/c.length):0,v=c.filter(s=>s.confidence<30).length,h=c.filter(s=>s.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${c.length} lessons`,"",`Average confidence: **${y(b)}**`,`\u{1F534} Critical (<30%): ${v} \u{1F7E2} Healthy (\u226570%): ${h}`,"","Lowest confidence lessons (fix these first):","",...w.map((s,t)=>`${(t+1).toString().padStart(2)}. \`${s.topic}\`
|
|
8
|
+
${y(s.confidence)} \xB7 ${s.age_days}d old \xB7 ${s.recalls} recalls \xB7 ${s.outcome}`),"",c.length>$?`\u2026 and ${c.length-$} more lessons`:"","",v>0?`\u26A0\uFE0F ${v} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`:"\u2705 Brain confidence is healthy overall.","","\u{1F4A1} Run `memory_consolidate` to prune stale entries \xB7 `causal_trace` to find root causes."].filter(s=>s!=="").join(`
|
|
9
|
+
`)}case"autopilot":{const{instance_id:l,editor:p="claude",project_name:$="this project",style:m="full"}=A,g=U({editor:String(p),project_name:String($)},"die Anweisungsdatei (CLAUDE.md)");if(!g.ok)return g.meldung;const d=(v,h)=>v.replace(/[\p{C}\s]+/gu," ").trim().slice(0,h),u=d(g.felder.editor,30)||"claude",_=d(g.felder.project_name,80)||"this project",c=`## Cachly AI Brain \u2014 Autopilot
|
|
10
10
|
|
|
11
11
|
**Instance:** \`${l}\`
|
|
12
12
|
|
|
@@ -22,7 +22,7 @@ No matching lessons found in brain.`);if($)return $;const h=await M(l),f=u.toLow
|
|
|
22
22
|
- **Window opens** \u2192 call \`session_start(instance_id="${l}", focus="<today's goal>")\`
|
|
23
23
|
- **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${l}", topic="fix:<area>", outcome="success", what_worked="...")\`
|
|
24
24
|
- **Window closes** \u2192 call \`session_end(instance_id="${l}", summary="...", files_changed=[...])\`
|
|
25
|
-
`,
|
|
25
|
+
`,w=`## Cachly AI Brain \u2014 Autopilot for ${_}
|
|
26
26
|
|
|
27
27
|
**Instance:** \`${l}\`
|
|
28
28
|
|
|
@@ -101,5 +101,5 @@ smart_recall(
|
|
|
101
101
|
---
|
|
102
102
|
|
|
103
103
|
*Cachly v0.6 \xB7 Generated ${new Date().toISOString().slice(0,10)}*
|
|
104
|
-
`,
|
|
105
|
-
`)}default:return null}}export{
|
|
104
|
+
`,y=m==="minimal"?c:w,b=u==="copilot"?".github/copilot-instructions.md":u==="continue"?".continue/cachly-autopilot.md":"CLAUDE.md";return[`\u{1F916} **Autopilot instructions generated** for **${u==="all"?"all editors":u}**`,"",`**File:** \`${b}\` \u2014 create it, or APPEND to your existing one`,"","```markdown",y,"```","",`**How to apply** (\`>>\` appends \u2014 an existing ${b} keeps every line you wrote):`,"```bash",`cat >> ${b} << 'EOF'`,y,"EOF","```","",`\u2728 Once this file is in place, **${u==="copilot"?"GitHub Copilot":u==="continue"?"Continue.dev":"Claude/Cursor/Windsurf"}** will manage the Brain automatically \u2014 no manual calls needed, ever.`].join(`
|
|
105
|
+
`)}default:return null}}export{J as ADVANCED_TOOL_NAMES,Y as handleAdvancedTool};
|