@cachly-dev/mcp-server 0.10.249 → 0.10.250
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 +4 -4
- package/dist/src/handlers/advanced.js +24 -24
- package/dist/src/handlers/brain.js +67 -67
- package/dist/src/handlers/fedbrain.js +39 -39
- package/dist/src/handlers/syndicate.js +38 -38
- package/dist/src/handlers/team.js +42 -42
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +27 -27
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Seltenheit as f,inhaltsWoerter as c,grobStamm as p,spreizeImTopf as
|
|
1
|
+
import{Seltenheit as f,inhaltsWoerter as c,grobStamm as p,spreizeImTopf as m}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{istTeamweit as x}from"./utils.js";import{rahmeEin as B,entschaerfe as P,RAHMEN_ETIKETT as C,RAHMEN_HINWEIS as F}from"./einblendung-rahmen.js";import{stopAntwort as K}from"./schreibbeleg.js";const _=E,T=["topic","outcome","what_worked","what_failed","severity","confidence","recall_count","ts","endorsements"],d=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+/)),z=["ierungen","ierung","ieren","iert","ungen","ung","heit","keit","lich","isch","ing","ed","en","er","es","e","n","s"];function y(s){for(const e of z)if(s.length-e.length>=4&&s.endsWith(e))return s.slice(0,-e.length);return s}function I(s){return[...new Set(String(s).toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>3&&!d.has(e)).map(y).filter(e=>!d.has(e)))]}function D(s,e){let r=0;for(const o of s)e.includes(o)&&r++;return r}class L{texte;wortmengen;heuhaufen;statistik;wortbestand;platzVonSchluessel=new Map;topf;lektionen;constructor(e,{topf:r=_}={}){const o=e.filter(t=>!S(t)&&x(t));this.lektionen=o,this.topf=r,this.texte=o.map(t=>w(t)),this.wortmengen=this.texte.map(t=>new Set([...c(t)].map(p))),this.heuhaufen=this.texte.map(t=>t.toLowerCase()),this.statistik=new f(this.texte);const h=o.map((t,a)=>{const u=`cachly:lesson:best:${String(t.topic??a)}`;this.platzVonSchluessel.set(u,a);const l={};for(const n of T)t[n]!==void 0&&(l[n]=t[n]);return{key:u,content:JSON.stringify(l)}});this.wortbestand=g(h)}get groesse(){return this.lektionen.length}sortiere(e){if(!this.wortbestand)return[];const r=k(this.wortbestand,e,this.topf),o=[],h=[];for(const n of r){const i=this.platzVonSchluessel.get(n.key);i!==void 0&&(o.push(i),h.push(n.score))}if(o.length===0)return[];const t=c(e),a=I(e),u=m(h),l=m(o.map(n=>this.statistik.besterZeuge(t,this.wortmengen[n])));return o.map((n,i)=>({lektion:this.lektionen[n],punkte:u[i]+b*this.statistik.deckung(t,this.wortmengen[n])+N*l[i],belege:D(a,this.heuhaufen[n])})).sort((n,i)=>i.punkte-n.punkte||Number(i.lektion.recall_count??0)-Number(n.lektion.recall_count??0))}}export{L as Einblendbestand,T as INDEX_FELDER,C as RAHMEN_ETIKETT,F as RAHMEN_HINWEIS,_ as WORT_TOPF,P as entschaerfe,B as rahmeEin,y as stammKuerzen,K as stopAntwort,I as torWoerter,D as zaehleBelege};
|
package/dist/src/einblendung.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{readFileSync as T,existsSync as C,writeFileSync as j,mkdirSync as F,statSync as W,appendFileSync as V}from"node:fs";import{dirname as R,join as _}from"node:path";import{tmpdir as b}from"node:os";import{createHash as X}from"node:crypto";import{spawn as Q}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U,RAHMEN_HINWEIS as z}from"./einblendung-rahmen.js";import{istMarkiert as ee}from"./verdacht-marke.js";import{
|
|
1
|
+
import{readFileSync as T,existsSync as C,writeFileSync as j,mkdirSync as F,statSync as W,appendFileSync as V}from"node:fs";import{dirname as R,join as _}from"node:path";import{tmpdir as b}from"node:os";import{createHash as X}from"node:crypto";import{spawn as Q}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U,RAHMEN_HINWEIS as z}from"./einblendung-rahmen.js";import{istMarkiert as ee}from"./verdacht-marke.js";import{istTeamweit as te}from"./utils.js";import{istBlossesThema as re}from"./blosses-thema.js";import{leserText as ne}from"./seltenheitsbestand.js";import{mischeMitLeser as H}from"./leser.js";import{LeserSicherung as se,dateiSpeicher as oe,frageLeser as ie}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as le,LESER_ZEITLIMIT_MS as ae}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as ce}from"./gueltigkeit-version.js";import{ARME as O,BASIS_MIN_BELEGE as ue,MERKMAL_KANDIDATEN as pe,OHNE_LERNEN as fe,entscheide as he,leseArmZaehlung as me,lernEinstellungen as de,lernenAuffrischen as ge,merkeEntscheidung as Ee,neuerSatz as _e,sitzungsKennung as be,zugKennung as Se}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as ht,lernenAuffrischen as mt,lernEinstellungen as dt,ARME as gt}from"./lernen.js";const ye=600*1e3,P=300*1e3,Ae=10*1e3,Ne=2e3,Ie=50,ve=60*1e3;function ke(e,t){return t<P?{ttlMs:Ae,sofort:!0}:e<Ie?{ttlMs:ve,sofort:!1}:{ttlMs:ye,sofort:!1}}const D=8e3,we=60*1e3,J=120,K=le,Me=1500,I=ae,Le=_(b(),"cachly-ambient-netlog.jsonl");function rt(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 r=e;for(let n=0;n<8;n++){const s=_(r,".mcp.json");if(C(s))try{const i=JSON.parse(T(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 o=R(r);if(o===r)break;r=o}return t}function v(e){return X("sha1").update(e).digest("hex").slice(0,12)}function q(e){return _(b(),`cachly-ambient-bestand-${v(e)}.json`)}function xe(e){return _(b(),`cachly-leser-sicherung-${v(e)}.json`)}function Te(e,t="ambient-auffrischen"){return _(b(),`cachly-${t}-${v(e)}.lock`)}async function k(e,{fetchFn:t=fetch,zeitlimitMs:r=D}={}){try{const n=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(r)});if(!n.ok)return null;const s=await n.json();return!Array.isArray(s?.lessons)||s.lessons.length===0&&typeof s.note=="string"&&s.note?null:s.lessons.map(o=>typeof o=="string"?Ce(o):o).filter(o=>!!o&&typeof o=="object")}catch{return null}}function Ce(e){try{return JSON.parse(e)}catch{return null}}function S(e,t,r="server"){const n=Date.now(),s=y(e),o=s?.seit??n;let i;r==="vorab"?i=t:r==="server"&&s?.vorab&&n-o<P&&(i=s.vorab);const a=r==="server"&&i?je(t,i):t;try{F(R(e),{recursive:!0}),j(e,JSON.stringify({at:n,seit:o,lessons:a,...i?{vorab:i}:{}}),{mode:384})}catch{}return a}function je(e,t){const r=new Set(e.map(n=>n.topic));return[...e,...t.filter(n=>!r.has(n.topic))]}function nt(e,t){if(!e||t.length===0)return!1;const r=q(e);return(y(r)?.lessons.length??0)>0?!1:(S(r,t,"vorab"),!0)}function y(e){try{const t=JSON.parse(T(e,"utf8"));if(Array.isArray(t?.lessons)){const r=Number(t.at)||0;return{at:r,seit:Number(t.seit)||r,lessons:t.lessons,...Array.isArray(t.vorab)?{vorab:t.vorab}:{}}}}catch{}return null}function Re(e,t,{zweck:r,ordner:n}={}){const s=Te(e.instanceId,r);try{if(C(s)&&Date.now()-W(s).mtimeMs<we)return!1;j(s,String(Date.now()),{mode:384})}catch{return!1}try{return Q(process.execPath,t,{detached:!0,stdio:"ignore",...n?{cwd:n}:{},env:{...process.env,CACHLY_API_URL:e.apiUrl,CACHLY_JWT:e.jwt,CACHLY_BRAIN_INSTANCE_ID:e.instanceId}}).unref(),!0}catch{return!1}}async function $e(e,{force:t=!1,nebenlauf:r,abrufMs:n=D,lernen:s=!1,vorabSchliessen:o=!1,fetchFn:i}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const a=q(e.instanceId);if(t){const[m]=await Promise.all([k(e,{fetchFn:i,zeitlimitMs:n}),s?ge(e,{fetchFn:i}):void 0]);if(m)return{lessons:S(a,m,o?"abschluss":"server"),quelle:"server"};const u=y(a);return u?{lessons:u.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const l=y(a);if(l){const m=Date.now(),u=ke(l.lessons.length,m-l.seit);if(m-l.at<u.ttlMs)return{lessons:l.lessons,quelle:"platte"};if(u.sofort){const h=await k(e,{fetchFn:i,zeitlimitMs:Math.min(n,Ne)});return h?{lessons:S(a,h),quelle:"server"}:{lessons:l.lessons,quelle:"platte-alt"}}return r&&Re(e,r),{lessons:l.lessons,quelle:"platte-alt"}}const c=await k(e,{fetchFn:i,zeitlimitMs:n});return c?{lessons:S(a,c),quelle:"server"}:{lessons:[],quelle:"server-nicht-erreichbar"}}function w(e){return Math.ceil(String(e).length/4)}function M(e){const t=e.severity?`[${e.severity}] `:"",r=String(e.what_worked??"").replace(/\s+/g," ").trim(),n=r.length>J?`${r.slice(0,J)}\u2026`:r,s=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${s}: ${n}`}const A={lessons:[],tokens:0,topScore:0,belege:0};function L(e,t,r){if(e.length===0)return{...A};const n=[];let s=0;e=ce(e);for(const{lektion:o}of e.slice(0,t)){const i=w(M(o));if(s+i>r)break;n.push(o),s+=i}return{lessons:n,tokens:s,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function st(e,t,{minBelege:r=2,topK:n=3,tokenBudget:s=600}={}){if(!Array.isArray(t)||t.length===0)return{...A};if(B(e).length===0)return{...A};const o=new $(t).sortiere(e).filter(i=>i.belege>=r);return o.length===0?{...A}:L(o,n,s)}function Be(e){return ne(e,Me)}async function G(e,t,r,{zeitlimitMs:n=I,fetchFn:s}={}){if(!e?.jwt||!e?.instanceId||r.length===0)return{art:"ohne"};if(["0","off","aus","false"].includes(String(process.env.CACHLY_LESER||"").toLowerCase()))return{art:"ohne"};const o=new se(oe(xe(e.instanceId)));return ie({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:r,instanceId:e.instanceId,zeitlimitMs:n,fetchFn:s},o)}async function ot(e,t,r,n={}){const s=await G(e,t,r,n);return s.art==="punkte"?{scores:s.scores,provider:s.provider,ms:s.ms}:null}async function Y(e,t,r,{minBelege:n,tiefe:s,zeitlimitMs:o,fetchFn:i}){const a={sortiert:[],leser:"aus",leserMs:0};if(!Array.isArray(t)||t.length===0||B(e).length===0)return a;let l=new $(t).sortiere(e).filter(u=>u.belege>=n);if(l.length===0)return a;let c="aus",m=0;if(l.length>1&&s>0){const u=l.slice(0,s),d=l.slice(s),h=await G(r,e,u.map(E=>Be(E.lektion)),{zeitlimitMs:o,fetchFn:i});h.art==="punkte"?(l=[...H(u.map(f=>f.punkte),h.scores,1).map(f=>({...u[f],leser:h.scores[f]})),...d],c=h.provider,m=h.ms):h.art==="uebersprungen"&&(c="uebersprungen")}return{sortiert:l,leser:c,leserMs:m}}async function it(e,t,r,{minBelege:n=2,topK:s=3,tokenBudget:o=600,tiefe:i=K,zeitlimitMs:a=I,fetchFn:l}={}){const c=await Y(e,t,r,{minBelege:n,tiefe:i,zeitlimitMs:a,fetchFn:l});return{...L(c.sortiert,s,o),leser:c.leser,leserMs:c.leserMs}}function Ue(e){if(!e.lessons.length)return"";const t=e.lessons.map(M).join(`
|
|
2
2
|
`);return`\u{1F9E0} Cachly Brain \u2014 relevant lessons for this task (auto-recall, ${e.lessons.length}):
|
|
3
3
|
${U(t)}
|
|
4
|
-
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const
|
|
4
|
+
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const ze=5;function lt(e){const t=e.filter(l=>!ee(l)&&te(l));if(!t.length)return"";const r=t.filter(l=>{const c=String(l.topic??"");return!(/^auto:/.test(c)||re(c))}),n=[...r.length?r:t].sort((l,c)=>(Number(c.recall_count)||0)-(Number(l.recall_count)||0)).slice(0,ze),s=n.map(M).join(`
|
|
5
5
|
`),o=n.some(l=>(Number(l.recall_count)||0)>0),i=o?"Top by proven reuse":"Starter tips (not yet from your project)",a=o?z:z.replace("Stored notes from earlier sessions.","General starter notes, not yet from your project.");return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${t.length} lessons). ${i}:
|
|
6
6
|
${U(s,a)}
|
|
7
|
-
(Relevant lessons for each task are auto-injected per prompt. ~${w(s)} tokens.)`}function
|
|
8
|
-
`)}catch{}return{kontext:N,auswahl:p,quelle:d,bestand:u.length,entscheidung:f}}export{D as ABRUF_TIMEOUT_MS,J as ANZEIGE_ZEICHEN,
|
|
7
|
+
(Relevant lessons for each task are auto-injected per prompt. ~${w(s)} tokens.)`}function at(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}function He(e,t){return e.map((r,n)=>({x:r,rang:n,gezeigt:t.includes(r.lektion)})).filter(({rang:r,gezeigt:n})=>r<pe||n).map(({x:r,rang:n,gezeigt:s})=>({thema:String(r.lektion.topic??""),rang:n,punkte:Math.round(r.punkte*1e3)/1e3,belege:r.belege,leser:typeof r.leser=="number"&&Number.isFinite(r.leser)?Math.round(r.leser*1e3)/1e3:null,gezeigt:s}))}async function ct(e,t,{nebenlauf:r,abrufMs:n,leser:s=!0,session:o=null,protokoll:i=!0,ereignis:a="UserPromptSubmit",editor:l="",lernen:c=!0,fetchFn:m}={}){const{lessons:u,quelle:d}=await $e(t,{nebenlauf:r,abrufMs:n,fetchFn:m}),h=de(),E=c&&h.aktiv&&a==="UserPromptSubmit"&&!!t.instanceId,f=E?he({instanceId:t.instanceId,sitzung:o,prompt:e,zaehlung:me(t.instanceId),einstellungen:h}):fe,x=O[f.arm]??O[0],g=await Y(e,u,t,{minBelege:ue,tiefe:s?K:0,zeitlimitMs:I,fetchFn:m}),p={...L(g.sortiert.filter(Z=>Z.belege>=x.minBelege),x.topK,600),leser:g.leser,leserMs:g.leserMs},N=f.kontrolle?"":Ue(p);if(E&&g.sortiert.length>0&&Ee(t.instanceId,o,_e({sitzung:be(o),zug:Se(e),ereignis:a,editor:l,arm:f.arm,kontrolle:f.kontrolle,erkundet:f.erkundet,ausgewaehlt:p.lessons.length,kandidatenZahl:g.sortiert.length,belege:p.belege,topScore:p.topScore,leser:p.leser,leserMs:p.leserMs,quelle:d,bestand:u.length,kandidaten:He(g.sortiert,p.lessons)})),i)try{V(Le,JSON.stringify({at:Date.now(),session:o,prompt_tokens:w(e),injected_tokens:N?p.tokens:0,matches:N?p.lessons.length:0,arm:f.arm,kontrolle:f.kontrolle,ausgewaehlt:p.lessons.length,top_score:p.topScore,belege:p.belege,leser:p.leser,leser_ms:p.leserMs,quelle:d,bestand:u.length})+`
|
|
8
|
+
`)}catch{}return{kontext:N,auswahl:p,quelle:d,bestand:u.length,entscheidung:f}}export{D as ABRUF_TIMEOUT_MS,J as ANZEIGE_ZEICHEN,gt as ARME,Ae as BESTAND_TTL_JUNG_MS,ve as BESTAND_TTL_KLEIN_MS,ye as BESTAND_TTL_MS,Ne as JUNG_ABRUF_MS,P as JUNG_FENSTER_MS,Ie as KLEIN_LEKTIONEN,I as LESER_HOOK_ZEITLIMIT_MS,Me as LESER_MAX_ZEICHEN,K as LESER_TIEFE,Le as NETZ_PROTOKOLL,ze as SITZUNG_TOP_N,ht as belohnungMelden,ke as bestandFrist,q as bestandPfad,je as ergaenzeUmVorab,w as estimateTokens,$e as holeBestand,at as hookAusgabe,dt as lernEinstellungen,mt as lernenAuffrischen,G as leserAnfrageApi,ot as leserPunkteApi,Be as leserText,H as mischeMitLeser,ct as promptEinblendung,Ue as promptKontext,M as renderLesson,rt as resolveConfig,nt as schreibeVorabBestand,st as selectRelevant,it as selectRelevantMitLeser,xe as sicherungsPfad,lt as sitzungsKontext,Re as starteNebenlauf};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{ckgSlug as L}from"../ckg.js";import{safeJsonParse as
|
|
2
|
-
`)}case"brain_diff":{const{instance_id:
|
|
3
|
-
`)}case"causal_trace":{const{instance_id:
|
|
1
|
+
import{ckgSlug as L}from"../ckg.js";import{safeJsonParse as D,darfHeraus as O,istTeamweit as j}from"../utils.js";import{ersparteMinuten as F,zaehltAlsErsparnis as K}from"../wertbeitrag.js";import{findePaare as z}from"../zulassung-und-urteil.js";import{Vektorbestand as H}from"../bedeutung.js";import{doppelPaare as U}from"../doppel-kandidat.js";import{DOPPEL_SCHWELLE as W}from"../rangfolge-stellschrauben.js";import{sofortAntwortNeuesBrain as G}from"../leeres-brain.js";import{fuerWeitergabe as V}from"../schreibtor.js";import{kappeAnfrage as q,trefferIstStark as J}from"../pflichtfelder.js";import{namensPruefer as Y}from"./team.js";function N(B){return O(B)&&!B.group}const re=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function le(B,E,I,P){switch(B){case"memory_consolidate":{const{instance_id:u,dry_run:v=!1,stale_days:b=90}=E,g=await I(u),m=Date.now(),x=b*86400*1e3;let r=0;const p=[];do{const[t,f]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(t),p.push(...f)}while(r!==0);if(p.length===0)return"\u{1F9E0} **Brain is empty** \u2014 no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.";const l=new Map,$=new Set;for(const t of p){const f=await g.get(t);if(!f)continue;const S=D(f,null);if(S){l.set(t,S);const M=S.topic;j(S)||$.add(M)}}const _=(...t)=>t.every(f=>!$.has(f)),k=new H(0);await k.aktualisiere(g).catch(()=>{});const T=U([...l.values()].flatMap(t=>{const f=k.rohvektor(t.topic);return f?[{lektion:t,vektor:f}]:[]})),y=[...l.values()],C=z(y),a=C.filter(t=>t.beziehung==="widerspruch"),n=C.filter(t=>t.beziehung==="ersetzung"),o=[],c=new Map;for(const[t,f]of l){const S=c.get(f.topic)??[];S.push(t),c.set(f.topic,S)}for(const[t,f]of c)new Set(f.map(M=>l.get(M)?.outcome)).size>1&&o.push({topic:t,keys:f});const d=[];for(const[t,f]of l){const S=m-new Date(f.ts).getTime(),M=f.recall_count??0;S>x&&M===0&&d.push(t)}const w=0;if(!v)for(const t of d)await g.expire(t,86400*30);const h=a.filter(t=>_(t.a.topic,t.b.topic)),e=n.filter(t=>_(t.a.topic,t.b.topic)),i=o.filter(t=>_(t.topic)),s=T.filter(t=>_(t.neu,t.alt)),A=a.length-h.length+(n.length-e.length)+(o.length-i.length)+(T.length-s.length);return[`\u{1F52C} **Memory Consolidation Report** ${v?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${p.length} lessons`,"",`\u{1F501} **Contradictions \u2014 exact topic match (old rule):** ${o.length}`,`\u{1F50E} **Same subject, admitted for judgement:** ${C.length} \u2192 contradiction ${a.length} \xB7 supersession ${n.length}`,...h.slice(0,5).map(t=>` \u2192 \`${t.a.topic}\` vs \`${t.b.topic}\` (${t.naehe.toFixed(2)}): ${t.grund}`),h.length>5?` \u2026 and ${h.length-5} more`:"",...e.slice(0,3).map(t=>` \u21BB \`${t.a.topic}\` \u2192 \`${t.b.topic}\`: ${t.grund}`),...i.slice(0,5).map(t=>` \u2192 \`${t.topic}\`: ${t.keys.length} conflicting entries (kept: success)`),i.length>5?` \u2026 and ${i.length-5} more`:"","",`\u267B\uFE0F **Possible duplicates \u2014 same meaning, different topic (cosine \u2265 ${W.toFixed(2)}, never merged):** ${T.length}`+(k.groesse===0?" (no vectors in this Brain, so nothing could be compared)":""),...s.slice(0,5).map(t=>` \u2192 \`${t.neu}\` \u2248 \`${t.alt}\` (${t.naehe.toFixed(2)})`),s.length>5?` \u2026 and ${s.length-5} more`:"",s.length>0?' If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`.':"",A>0?`\u{1F512} ${A} of the pairs above involve a private or group-only lesson and are counted, not named.`:"","",`\u{1F570}\uFE0F **Stale entries (${b}d, 0 recalls):** ${d.length}`+(d.length>0&&!v?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${p.length-w} lessons`,"",v?"\u{1F4A1} Re-run without dry_run=true to apply changes.":'\u2728 Brain consolidated. Run `brain_diff(since="1h")` to see the delta.'].filter(t=>t!=="").join(`
|
|
2
|
+
`)}case"brain_diff":{const{instance_id:u,since:v="7d",format:b="summary"}=E,g=await I(u);let m;const x=v.match(/^(\d+)([dhm])$/);if(x){const e=parseInt(x[1]),i=x[2],s=i==="d"?864e5:i==="h"?36e5:6e4;m=Date.now()-e*s}else m=new Date(v).getTime()||Date.now()-7*864e5;let r=0;const p=[];do{const[e,i]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(e),p.push(...i)}while(r!==0);const l=[],$=[],_=[],k=p.length;for(const e of p){const i=await g.get(e);if(i){const s=D(i,null);if(!j(s))continue;if(new Date(s.ts).getTime()>=m){const R=`cachly:lesson:history:${s.topic}`;await g.llen(R)<=1?l.push(s):$.push(s)}(s.recall_count??0)>0&&_.push(s)}}const y=[`\u{1F4CA} **Brain Diff** \u2014 ${x?`last ${v}`:new Date(m).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${k}**`,"",`\u2705 **New** (${l.length}):`,...l.slice(0,b==="detailed"?20:5).map(e=>` + \`${e.topic}\` \u2014 ${e.outcome} ${e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u{1F7E0}":"\u{1F7E2}"}`),l.length>5&&b==="summary"?` \u2026 and ${l.length-5} more`:"","",`\u{1F504} **Updated** (${$.length}):`,...$.slice(0,b==="detailed"?20:5).map(e=>` ~ \`${e.topic}\` \u2014 now: ${e.outcome}`),$.length>5&&b==="summary"?` \u2026 and ${$.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${_.length}`,""].filter(e=>e!==""),C=[],a=g.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((e,i)=>{a.on("data",s=>C.push(...s)),a.on("end",e),a.on("error",i)});const n=[],o=Y(g);for(const e of C){const i=await g.get(e);if(i){const s=D(i,null);s?.ts&&new Date(s.ts).getTime()>=m&&(!s.topic||await o(s.topic))&&n.push({topic:s.topic??e,resolution:s.resolution??"unknown",ts:s.ts})}}if(n.length>0){y.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${n.length} contested beliefs resolved):`);for(const e of n.slice(0,5)){const i=e.resolution==="unanimous_success"?"\u2705":e.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";y.push(` ${i} \`${e.topic}\` \u2192 ${e.resolution}`)}y.push("")}const c=new Set($.concat(_).map(e=>e.topic.split(":")[0])),d=[...new Set(l.map(e=>e.topic.split(":")[0]))].filter(e=>!c.has(e));d.length>0&&y.push(`\u{1F331} **New domains bootstrapped:** ${d.map(e=>`\`${e}\``).join(", ")}`,"");const h=(await g.lrange("cachly:fedbrain:federations",-20,-1)).map(e=>D(e,null)).filter(e=>e!==null&&new Date(e.transferred_at).getTime()>=m);if(h.length>0){y.push(`\u{1F9E0} **FedBrain transfers received (${h.length}):**`);for(const e of h.slice(0,3))y.push(` \u{1F4E5} domain \`${e.domain}\` from \`${e.source.slice(0,16)}\u2026\` \u2014 ${e.nodes} nodes, ${e.edges} edges`);y.push("")}return y.push("\u{1F4A1} Run `memory_consolidate` to merge duplicates \xB7 `knowledge_decay` to see confidence scores."),y.join(`
|
|
3
|
+
`)}case"causal_trace":{const{instance_id:u,problem:v,max_depth:b=5,tags:g=[]}=E,m=q(v),x=await G(u,P,`\u{1F50D} **Causal Trace: "${m}"**
|
|
4
4
|
|
|
5
|
-
No matching lessons found in brain.`);if(
|
|
6
|
-
`);const n=[`\u{1F50D} **Causal Trace: "${
|
|
7
|
-
`)}case"knowledge_decay":{let
|
|
8
|
-
${
|
|
9
|
-
`)}case"autopilot":{const{instance_id:
|
|
5
|
+
No matching lessons found in brain.`);if(x)return x;const r=await I(u),p=m.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(o=>o.length>2),l={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},$=[];try{for(const o of p.slice(0,4)){const c=await r.smembers(`cachly:ckg:idx:from:${L(o)}`),d=await r.smembers(`cachly:ckg:idx:to:${L(o)}`),w=[],h=r.scanStream({match:`cachly:ckg:node:*${o}*`,count:50});await new Promise((e,i)=>{h.on("data",s=>w.push(...s)),h.on("end",e),h.on("error",i)});for(const e of w.slice(0,10)){const i=await r.get(e);if(!i)continue;const s=D(i,null);if(!s)continue;const A=await r.smembers(`cachly:ckg:idx:from:${s.id}`);for(const R of A.slice(0,20)){const t=await r.get(R);if(!t)continue;const f=D(t,null);if(!f||f.edgeType!=="fixes"&&f.edgeType!=="requires")continue;const S=await r.get(`cachly:lesson:best:${f.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),M=S?D(S,null)??void 0:void 0;$.push({conceptId:s.id,edge:f,lesson:M&&N(M)?M:void 0})}}for(const e of[...c,...d].slice(0,20)){const i=await r.get(e);if(!i)continue;const s=D(i,null);if(!s)continue;const A=await r.get(`cachly:lesson:best:${s.from}`),R=A?D(A,null)??void 0:void 0;$.push({conceptId:s.from,edge:s,lesson:R&&N(R)?R:void 0})}}}catch{}const _=new Set,k=$.filter(o=>{const c=`${o.edge.from}:${o.edge.edgeType}:${o.edge.to}`;return _.has(c)?!1:(_.add(c),!0)}).sort((o,c)=>c.edge.confidence-o.edge.confidence).slice(0,b);let T=0;const y=[];do{const[o,c]=await r.scan(T,"MATCH","cachly:lesson:best:*","COUNT",200);T=parseInt(o),y.push(...c)}while(T!==0);const C=[];for(const o of y){const c=await r.get(o);if(c){const d=D(c,null);if(!d||!N(d)||g.length>0&&!(d.tags??[]).some(e=>g.includes(e)))continue;const w=[d.topic,d.what_failed??"",d.what_worked??"",d.context??""].join(" ").toLowerCase(),h=p.reduce((e,i)=>e+(w.includes(i)?1:0),0);h>0&&C.push({score:h,lesson:d,key:o})}}C.sort((o,c)=>c.score-o.score);const a=C.slice(0,b);if(a.length===0&&k.length===0)return[`\u{1F50D} **Causal Trace: "${m}"**`,"","No matching lessons found in brain.","","\u{1F4A1} After you solve this, call:","```","learn_from_attempts(",` instance_id = "${u}",`,` topic = "fix:${p[0]??"issue"}",`,' outcome = "success",',' what_worked = "...",',` what_failed = "${m}",`,")","```"].join(`
|
|
6
|
+
`);const n=[`\u{1F50D} **Causal Trace: "${m}"**`,""];if(k.length>0){n.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const o of k){const c=Math.round(o.edge.confidence*100),d="\u2593".repeat(Math.round(c/10))+"\u2591".repeat(10-Math.round(c/10));n.push(` ${o.edge.from} **\u2192[${o.edge.edgeType}]\u2192** ${o.edge.to}`),n.push(` ${d} ${c}% confidence (${o.edge.successes}/${o.edge.trials} confirmed)`),o.lesson?.what_worked&&n.push(` \u2705 Fix: ${o.lesson.what_worked.slice(0,150)}`),n.push("")}}if(a.length>0){n.push(k.length>0?`### \u{1F4DA} Text Search (${a.length} related lessons)`:`Found **${a.length}** related lessons. Reconstructed causal chain:`,"");const o=a.filter(w=>w.lesson.outcome!=="success"),c=a.filter(w=>w.lesson.outcome==="success");o.length>0&&(n.push("**Root causes & failure chain:**"),o.forEach((w,h)=>{const e=w.lesson,i=l[e.severity??"minor"]??"\u{1F7E1}";n.push(`${h===0?" Root:":" \u2192 :"} ${i} \`${e.topic}\``),e.what_failed&&n.push(` \u21B3 ${e.what_failed.slice(0,120)}`)}),n.push("")),c.length>0&&(n.push("**Solutions that worked before:**"),c.forEach((w,h)=>{const e=w.lesson,i=new Date(e.ts).toLocaleDateString("de-DE");n.push(` ${h+1}. \u2705 \`${e.topic}\` \u2014 ${i} \xB7 in ${e.recall_count??0} answers`),e.what_worked&&n.push(` ${e.what_worked.slice(0,200)}`)}),n.push(""));const d=c[0]?.lesson;if(d?.what_worked){const w=J(c[0].score,p);n.push(w?"**\u26A1 Most likely fix:**":`**Closest solution (weak match: ${c[0].score} of ${new Set(p).size} words \u2014 check that it fits before using it):**`),n.push("```"),n.push(d.what_worked.slice(0,500)),n.push("```"),n.push("");const h=K(d)?F(d,"trace"):0;h>0&&r.incrbyfloat(`cachly:stats:time_saved_mins:${u}`,h).catch(()=>{})}}return n.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${p[0]??"issue"}", outcome="success", ...)\``),k.length>0&&n.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${p[0]??"fix"}")\``),n.join(`
|
|
7
|
+
`)}case"knowledge_decay":{let _=function(a){const n=Math.round(a/10);return"\u2588".repeat(n)+"\u2591".repeat(10-n)+` ${a}%`};const{instance_id:u,min_age_days:v=0,show_top:b=20}=E,g=await I(u),m=Date.now(),x=v*864e5;let r=0;const p=[];do{const[a,n]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(a),p.push(...n)}while(r!==0);const l=[];for(const a of p){const n=await g.get(a);if(n){const o=D(n,null);if(!j(o))continue;const c=m-new Date(o.ts).getTime();if(c<x)continue;const d=Math.floor(c/864e5),w=o.recall_count??0,h=Math.max(0,d-7),e=Math.max(5,100-h),i=Math.min(50,w*5),s=o.outcome==="failure"?-20:0,A=Math.min(100,Math.max(0,e+i+s));l.push({topic:o.topic,confidence:A,age_days:d,recalls:w,outcome:o.outcome})}}l.sort((a,n)=>a.confidence-n.confidence);const $=l.slice(0,b),k=l.length>0?Math.round(l.reduce((a,n)=>a+n.confidence,0)/l.length):0,T=l.filter(a=>a.confidence<30).length,y=l.filter(a=>a.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${l.length} lessons`,"",`Average confidence: **${_(k)}**`,`\u{1F534} Critical (<30%): ${T} \u{1F7E2} Healthy (\u226570%): ${y}`,"","Lowest confidence lessons (fix these first):","",...$.map((a,n)=>`${(n+1).toString().padStart(2)}. \`${a.topic}\`
|
|
8
|
+
${_(a.confidence)} \xB7 ${a.age_days}d old \xB7 ${a.recalls} recalls \xB7 ${a.outcome}`),"",l.length>b?`\u2026 and ${l.length-b} more lessons`:"","",T>0?`\u26A0\uFE0F ${T} 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(a=>a!=="").join(`
|
|
9
|
+
`)}case"autopilot":{const{instance_id:u,editor:v="claude",project_name:b="this project",style:g="full"}=E,m=V({editor:String(v),project_name:String(b)},"the instruction file (CLAUDE.md)");if(!m.ok)return m.meldung;const x=(T,y)=>T.replace(/[\p{C}\s]+/gu," ").trim().slice(0,y),r=x(m.felder.editor,30)||"claude",p=x(m.felder.project_name,80)||"this project",l=`## Cachly AI Brain \u2014 Autopilot
|
|
10
10
|
|
|
11
|
-
**Instance:** \`${
|
|
11
|
+
**Instance:** \`${u}\`
|
|
12
12
|
|
|
13
13
|
> **Where your data goes:** these calls read/write *your own* Brain instance
|
|
14
14
|
> (the ID above) \u2014 your infrastructure, EU-hosted, under your control. Nothing
|
|
@@ -19,12 +19,12 @@ No matching lessons found in brain.`);if(k)return k;const c=await R(d),u=f.toLow
|
|
|
19
19
|
> Sessions are fully automatic. The Brain starts when you call any tool and saves a summary when you close.
|
|
20
20
|
|
|
21
21
|
### Brain hooks \u2014 run these automatically (safe to skip if a step doesn't apply):
|
|
22
|
-
- **Window opens** \u2192 call \`session_start(instance_id="${
|
|
23
|
-
- **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${
|
|
24
|
-
- **Window closes** \u2192 call \`session_end(instance_id="${
|
|
25
|
-
|
|
22
|
+
- **Window opens** \u2192 call \`session_start(instance_id="${u}", focus="<today's goal>")\`
|
|
23
|
+
- **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${u}", topic="fix:<area>", outcome="success", what_worked="...")\`
|
|
24
|
+
- **Window closes** \u2192 call \`session_end(instance_id="${u}", summary="...", files_changed=[...])\`
|
|
25
|
+
`,$=`## Cachly AI Brain \u2014 Autopilot for ${p}
|
|
26
26
|
|
|
27
|
-
**Instance:** \`${
|
|
27
|
+
**Instance:** \`${u}\`
|
|
28
28
|
|
|
29
29
|
> **What this is & where your data goes:** the calls below read and write to
|
|
30
30
|
> *your own* Cachly Brain instance (the ID above) \u2014 your infrastructure,
|
|
@@ -42,7 +42,7 @@ No matching lessons found in brain.`);if(k)return k;const c=await R(d),u=f.toLow
|
|
|
42
42
|
### Rule 1 \u2014 Session Start (FIRST thing in every window)
|
|
43
43
|
\`\`\`
|
|
44
44
|
session_start(
|
|
45
|
-
instance_id = "${
|
|
45
|
+
instance_id = "${u}",
|
|
46
46
|
focus = "<what you plan to work on today>",
|
|
47
47
|
)
|
|
48
48
|
\`\`\`
|
|
@@ -52,7 +52,7 @@ Returns: last session summary, handoff tasks, recent lessons, open failures.
|
|
|
52
52
|
**After EVERY** bug fix, deployment, or technical discovery \u2014 call immediately:
|
|
53
53
|
\`\`\`
|
|
54
54
|
learn_from_attempts(
|
|
55
|
-
instance_id = "${
|
|
55
|
+
instance_id = "${u}",
|
|
56
56
|
topic = "category:keyword",
|
|
57
57
|
outcome = "success" | "failure" | "partial",
|
|
58
58
|
what_worked = "exact command or approach",
|
|
@@ -72,7 +72,7 @@ learn_from_attempts(
|
|
|
72
72
|
### Rule 3 \u2014 Session End (LAST thing before closing)
|
|
73
73
|
\`\`\`
|
|
74
74
|
session_end(
|
|
75
|
-
instance_id = "${
|
|
75
|
+
instance_id = "${u}",
|
|
76
76
|
summary = "What was accomplished (2-3 sentences)",
|
|
77
77
|
files_changed = ["list", "of", "changed", "files"],
|
|
78
78
|
lessons_learned = <number of learn_from_attempts calls>,
|
|
@@ -82,7 +82,7 @@ session_end(
|
|
|
82
82
|
### Rule 4 \u2014 Before any non-trivial task
|
|
83
83
|
\`\`\`
|
|
84
84
|
smart_recall(
|
|
85
|
-
instance_id = "${
|
|
85
|
+
instance_id = "${u}",
|
|
86
86
|
query = "<describe what you are about to do>",
|
|
87
87
|
)
|
|
88
88
|
\`\`\`
|
|
@@ -93,13 +93,13 @@ smart_recall(
|
|
|
93
93
|
|
|
94
94
|
| When | Call |
|
|
95
95
|
|---|---|
|
|
96
|
-
| Brain feeling cluttered | \`memory_consolidate(instance_id="${
|
|
97
|
-
| Weekly review | \`brain_diff(instance_id="${
|
|
98
|
-
| Weird bug, no idea why | \`causal_trace(instance_id="${
|
|
99
|
-
| Before big refactor | \`knowledge_decay(instance_id="${
|
|
96
|
+
| Brain feeling cluttered | \`memory_consolidate(instance_id="${u}")\` |
|
|
97
|
+
| Weekly review | \`brain_diff(instance_id="${u}", since="7d")\` |
|
|
98
|
+
| Weird bug, no idea why | \`causal_trace(instance_id="${u}", problem="<symptom>")\` |
|
|
99
|
+
| Before big refactor | \`knowledge_decay(instance_id="${u}")\` |
|
|
100
100
|
|
|
101
101
|
---
|
|
102
102
|
|
|
103
103
|
*Cachly v0.6 \xB7 Generated ${new Date().toISOString().slice(0,10)}*
|
|
104
|
-
`,
|
|
105
|
-
`)}default:return null}}export{
|
|
104
|
+
`,_=g==="minimal"?l:$,k=r==="copilot"?".github/copilot-instructions.md":r==="continue"?".continue/cachly-autopilot.md":"CLAUDE.md";return[`\u{1F916} **Autopilot instructions generated** for **${r==="all"?"all editors":r}**`,"",`**File:** \`${k}\` \u2014 create it, or APPEND to your existing one`,"","```markdown",_,"```","",`**How to apply** (\`>>\` appends \u2014 an existing ${k} keeps every line you wrote):`,"```bash",`cat >> ${k} << 'EOF'`,_,"EOF","```","",`\u2728 Once this file is in place, **${r==="copilot"?"GitHub Copilot":r==="continue"?"Continue.dev":"Claude/Cursor/Windsurf"}** will manage the Brain automatically \u2014 no manual calls needed, ever.`].join(`
|
|
105
|
+
`)}default:return null}}export{re as ADVANCED_TOOL_NAMES,le as handleAdvancedTool};
|