@cachly-dev/mcp-server 0.10.196 → 0.10.198
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/doppel-kandidat.js +1 -0
- package/dist/src/einblendung.js +4 -4
- package/dist/src/handlers/advanced.js +11 -11
- package/dist/src/handlers/brain.js +66 -66
- package/dist/src/rangfolge-stellschrauben.js +1 -1
- package/dist/src/startwissen-hook.js +1 -1
- package/dist/src/tools.js +1 -1
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +24 -24
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{kosinus as P}from"./bedeutung.js";import{DOPPEL_SCHWELLE as _}from"./rangfolge-stellschrauben.js";const f="cachly:doppel:kandidaten",w=40,x=14,T=30,d=90*86400,y=6,E=864e5,D=t=>typeof t.what_worked=="string"?t.what_worked.trim().length:0;function k(t,e,o,n=_){return t.topic===e.topic||!(o>=n)||D(t)<w||D(e)<w?!1:!(t.ersetzt===e.topic||t.ersetzt_durch===e.topic||e.ersetzt===t.topic||e.ersetzt_durch===t.topic)}function O(t,e){let o=null;for(const n of e)k(t,n.lektion,n.naehe)&&(!o||n.naehe>o.naehe)&&(o={topic:n.lektion.topic,naehe:n.naehe});return o}function g(t){if(!t)return null;try{const e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}const S=t=>Math.round(t*1e3)/1e3;async function v(t,e,o,n,c=new Date){try{await n.aktualisiere(t);const i=n.aehnlichste(o,y+1).filter(l=>l.topic!==e.topic&&l.naehe>=_);let a=null;if(i.length>0){const l=await t.mget(...i.map(u=>`cachly:lesson:best:${u.topic}`)),h=i.flatMap((u,L)=>{const m=g(l[L]);return m?[{lektion:{...m,topic:u.topic},naehe:u.naehe}]:[]});a=O(e,h)}const p=await t.hgetall(f),r=Object.entries(p).filter(([l,h])=>l===e.topic||c.getTime()-Date.parse(String(g(h)?.am??""))>T*E||!g(h)).map(([l])=>l);if(r.length>0&&await t.hdel(f,...r),!a)return null;const s={neu:e.topic,alt:a.topic,naehe:S(a.naehe),am:c.toISOString()};return await t.hset(f,e.topic,JSON.stringify({alt:s.alt,naehe:s.naehe,am:s.am})),await t.expire(f,d),s}catch{return null}}async function M(t,e,o=new Date){try{const n=await t.hgetall(f),c=new Map(e.map(a=>[a.topic,a])),i=[];for(const[a,p]of Object.entries(n)){const r=g(p);if(!r||typeof r.alt!="string")continue;const s=String(r.am??"");if(!(o.getTime()-Date.parse(s)<=x*E))continue;const l=c.get(a),h=c.get(r.alt),u=Number(r.naehe);!l||!h||!k(l,h,u)||i.push({neu:a,alt:r.alt,naehe:u,am:s})}return i.sort((a,p)=>p.naehe-a.naehe)}catch{return[]}}function z(t){const e=[];for(let o=0;o<t.length;o++)for(let n=o+1;n<t.length;n++){const c=t[o],i=t[n],a=P(c.vektor,i.vektor);if(!k(c.lektion,i.lektion,a))continue;const p=String(c.lektion.ts??"")>=String(i.lektion.ts??""),[r,s]=p?[c.lektion,i.lektion]:[i.lektion,c.lektion];e.push({neu:r.topic,alt:s.topic,naehe:S(a)})}return e.sort((o,n)=>n.naehe-o.naehe)}export{x as DOPPEL_BRIEFING_TAGE,T as DOPPEL_HALTEN_TAGE,w as DOPPEL_MINDEST_TEXT,f as DOPPEL_SCHLUESSEL,d as DOPPEL_TTL_S,z as doppelPaare,M as leseDoppelKandidaten,v as pruefeDoppelung,O as waehleDoppelKandidat,k as zaehltAlsDoppelung};
|
package/dist/src/einblendung.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{readFileSync as T,existsSync as C,writeFileSync as R,mkdirSync as
|
|
1
|
+
import{readFileSync as T,existsSync as C,writeFileSync as R,mkdirSync as G,statSync as F,appendFileSync as V}from"node:fs";import{dirname as j,join as _}from"node:path";import{tmpdir as b}from"node:os";import{createHash as W}from"node:crypto";import{spawn as X}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U}from"./einblendung-rahmen.js";import{istMarkiert as Q}from"./verdacht-marke.js";import{leserText as ee}from"./seltenheitsbestand.js";import{mischeMitLeser as z}from"./leser.js";import{LeserSicherung as te,dateiSpeicher as ne,frageLeser as re}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as se,LESER_ZEITLIMIT_MS as oe}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as ie}from"./gueltigkeit-version.js";import{ARME as H,BASIS_MIN_BELEGE as le,MERKMAL_KANDIDATEN as ae,OHNE_LERNEN as ce,entscheide as ue,leseArmZaehlung as pe,lernEinstellungen as fe,lernenAuffrischen as he,merkeEntscheidung as me,neuerSatz as de,sitzungsKennung as ge,zugKennung as Ee}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as at,lernenAuffrischen as ct,lernEinstellungen as ut,ARME as pt}from"./lernen.js";const _e=600*1e3,O=300*1e3,be=10*1e3,Se=2e3,Ae=50,ye=60*1e3;function Ne(e,t){return t<O?{ttlMs:be,sofort:!0}:e<Ae?{ttlMs:ye,sofort:!1}:{ttlMs:_e,sofort:!1}}const P=8e3,ve=60*1e3,D=120,J=se,Ie=1500,v=oe,ke=_(b(),"cachly-ambient-netlog.jsonl");function We(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 s=0;s<8;s++){const r=_(n,".mcp.json");if(C(r))try{const i=JSON.parse(T(r,"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=j(n);if(o===n)break;n=o}return t}function I(e){return W("sha1").update(e).digest("hex").slice(0,12)}function K(e){return _(b(),`cachly-ambient-bestand-${I(e)}.json`)}function we(e){return _(b(),`cachly-leser-sicherung-${I(e)}.json`)}function Me(e,t="ambient-auffrischen"){return _(b(),`cachly-${t}-${I(e)}.lock`)}async function k(e,{fetchFn:t=fetch,zeitlimitMs:n=P}={}){try{const s=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(n)});if(!s.ok)return null;const r=await s.json();return!Array.isArray(r?.lessons)||r.lessons.length===0&&typeof r.note=="string"&&r.note?null:r.lessons.map(o=>typeof o=="string"?Le(o):o).filter(o=>!!o&&typeof o=="object")}catch{return null}}function Le(e){try{return JSON.parse(e)}catch{return null}}function S(e,t,n="server"){const s=Date.now(),r=A(e),o=r?.seit??s;let i;n==="vorab"?i=t:n==="server"&&r?.vorab&&s-o<O&&(i=r.vorab);const a=n==="server"&&i?xe(t,i):t;try{G(j(e),{recursive:!0}),R(e,JSON.stringify({at:s,seit:o,lessons:a,...i?{vorab:i}:{}}),{mode:384})}catch{}return a}function xe(e,t){const n=new Set(e.map(s=>s.topic));return[...e,...t.filter(s=>!n.has(s.topic))]}function Xe(e,t){if(!e||t.length===0)return!1;const n=K(e);return(A(n)?.lessons.length??0)>0?!1:(S(n,t,"vorab"),!0)}function A(e){try{const t=JSON.parse(T(e,"utf8"));if(Array.isArray(t?.lessons)){const n=Number(t.at)||0;return{at:n,seit:Number(t.seit)||n,lessons:t.lessons,...Array.isArray(t.vorab)?{vorab:t.vorab}:{}}}}catch{}return null}function Te(e,t,{zweck:n,ordner:s}={}){const r=Me(e.instanceId,n);try{if(C(r)&&Date.now()-F(r).mtimeMs<ve)return!1;R(r,String(Date.now()),{mode:384})}catch{return!1}try{return X(process.execPath,t,{detached:!0,stdio:"ignore",...s?{cwd:s}:{},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 Ce(e,{force:t=!1,nebenlauf:n,abrufMs:s=P,lernen:r=!1,vorabSchliessen:o=!1,fetchFn:i}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const a=K(e.instanceId);if(t){const[m]=await Promise.all([k(e,{fetchFn:i,zeitlimitMs:s}),r?he(e,{fetchFn:i}):void 0]);if(m)return{lessons:S(a,m,o?"abschluss":"server"),quelle:"server"};const c=A(a);return c?{lessons:c.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const l=A(a);if(l){const m=Date.now(),c=Ne(l.lessons.length,m-l.seit);if(m-l.at<c.ttlMs)return{lessons:l.lessons,quelle:"platte"};if(c.sofort){const h=await k(e,{fetchFn:i,zeitlimitMs:Math.min(s,Se)});return h?{lessons:S(a,h),quelle:"server"}:{lessons:l.lessons,quelle:"platte-alt"}}return n&&Te(e,n),{lessons:l.lessons,quelle:"platte-alt"}}const f=await k(e,{fetchFn:i,zeitlimitMs:s});return f?{lessons:S(a,f),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}] `:"",n=String(e.what_worked??"").replace(/\s+/g," ").trim(),s=n.length>D?`${n.slice(0,D)}\u2026`:n,r=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${r}: ${s}`}const y={lessons:[],tokens:0,topScore:0,belege:0};function L(e,t,n){if(e.length===0)return{...y};const s=[];let r=0;e=ie(e);for(const{lektion:o}of e.slice(0,t)){const i=w(M(o));if(r+i>n)break;s.push(o),r+=i}return{lessons:s,tokens:r,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function Qe(e,t,{minBelege:n=2,topK:s=3,tokenBudget:r=600}={}){if(!Array.isArray(t)||t.length===0)return{...y};if(B(e).length===0)return{...y};const o=new $(t).sortiere(e).filter(i=>i.belege>=n);return o.length===0?{...y}:L(o,s,r)}function Re(e){return ee(e,Ie)}async function q(e,t,n,{zeitlimitMs:s=v,fetchFn:r}={}){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 o=new te(ne(we(e.instanceId)));return re({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:n,instanceId:e.instanceId,zeitlimitMs:s,fetchFn:r},o)}async function et(e,t,n,s={}){const r=await q(e,t,n,s);return r.art==="punkte"?{scores:r.scores,provider:r.provider,ms:r.ms}:null}async function Y(e,t,n,{minBelege:s,tiefe:r,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(c=>c.belege>=s);if(l.length===0)return a;let f="aus",m=0;if(l.length>1&&r>0){const c=l.slice(0,r),d=l.slice(r),h=await q(n,e,c.map(E=>Re(E.lektion)),{zeitlimitMs:o,fetchFn:i});h.art==="punkte"?(l=[...z(c.map(p=>p.punkte),h.scores,1).map(p=>({...c[p],leser:h.scores[p]})),...d],f=h.provider,m=h.ms):h.art==="uebersprungen"&&(f="uebersprungen")}return{sortiert:l,leser:f,leserMs:m}}async function tt(e,t,n,{minBelege:s=2,topK:r=3,tokenBudget:o=600,tiefe:i=J,zeitlimitMs:a=v,fetchFn:l}={}){const f=await Y(e,t,n,{minBelege:s,tiefe:i,zeitlimitMs:a,fetchFn:l});return{...L(f.sortiert,r,o),leser:f.leser,leserMs:f.leserMs}}function je(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 $e=5;function nt(e){const t=e.filter(o=>!Q(o));if(!t.length)return"";const n=t.filter(o=>{const i=String(o.topic??"");return!(/^auto:/.test(i)||/^[a-z]+:?$/.test(i))}),r=[...n.length?n:t].sort((o,i)=>(Number(i.recall_count)||0)-(Number(o.recall_count)||0)).slice(0,$e).map(M).join(`
|
|
5
5
|
`);return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${t.length} lessons). Top by proven reuse:
|
|
6
6
|
${U(r)}
|
|
7
|
-
(Relevant lessons for each task are auto-injected per prompt. ~${
|
|
8
|
-
`)}catch{}return{kontext:
|
|
7
|
+
(Relevant lessons for each task are auto-injected per prompt. ~${w(r)} tokens.)`}function rt(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}function Be(e,t){return e.map((n,s)=>({x:n,rang:s,gezeigt:t.includes(n.lektion)})).filter(({rang:n,gezeigt:s})=>n<ae||s).map(({x:n,rang:s,gezeigt:r})=>({thema:String(n.lektion.topic??""),rang:s,punkte:Math.round(n.punkte*1e3)/1e3,belege:n.belege,leser:typeof n.leser=="number"&&Number.isFinite(n.leser)?Math.round(n.leser*1e3)/1e3:null,gezeigt:r}))}async function st(e,t,{nebenlauf:n,abrufMs:s,leser:r=!0,session:o=null,protokoll:i=!0,ereignis:a="UserPromptSubmit",editor:l="",lernen:f=!0,fetchFn:m}={}){const{lessons:c,quelle:d}=await Ce(t,{nebenlauf:n,abrufMs:s,fetchFn:m}),h=fe(),E=f&&h.aktiv&&a==="UserPromptSubmit"&&!!t.instanceId,p=E?ue({instanceId:t.instanceId,sitzung:o,prompt:e,zaehlung:pe(t.instanceId),einstellungen:h}):ce,x=H[p.arm]??H[0],g=await Y(e,c,t,{minBelege:le,tiefe:r?J:0,zeitlimitMs:v,fetchFn:m}),u={...L(g.sortiert.filter(Z=>Z.belege>=x.minBelege),x.topK,600),leser:g.leser,leserMs:g.leserMs},N=p.kontrolle?"":je(u);if(E&&g.sortiert.length>0&&me(t.instanceId,o,de({sitzung:ge(o),zug:Ee(e),ereignis:a,editor:l,arm:p.arm,kontrolle:p.kontrolle,erkundet:p.erkundet,ausgewaehlt:u.lessons.length,kandidatenZahl:g.sortiert.length,belege:u.belege,topScore:u.topScore,leser:u.leser,leserMs:u.leserMs,quelle:d,bestand:c.length,kandidaten:Be(g.sortiert,u.lessons)})),i)try{V(ke,JSON.stringify({at:Date.now(),session:o,prompt_tokens:w(e),injected_tokens:N?u.tokens:0,matches:N?u.lessons.length:0,arm:p.arm,kontrolle:p.kontrolle,ausgewaehlt:u.lessons.length,top_score:u.topScore,belege:u.belege,leser:u.leser,leser_ms:u.leserMs,quelle:d,bestand:c.length})+`
|
|
8
|
+
`)}catch{}return{kontext:N,auswahl:u,quelle:d,bestand:c.length,entscheidung:p}}export{P as ABRUF_TIMEOUT_MS,D as ANZEIGE_ZEICHEN,pt as ARME,be as BESTAND_TTL_JUNG_MS,ye as BESTAND_TTL_KLEIN_MS,_e as BESTAND_TTL_MS,Se as JUNG_ABRUF_MS,O as JUNG_FENSTER_MS,Ae as KLEIN_LEKTIONEN,v as LESER_HOOK_ZEITLIMIT_MS,Ie as LESER_MAX_ZEICHEN,J as LESER_TIEFE,ke as NETZ_PROTOKOLL,$e as SITZUNG_TOP_N,at as belohnungMelden,Ne as bestandFrist,K as bestandPfad,xe as ergaenzeUmVorab,w as estimateTokens,Ce as holeBestand,rt as hookAusgabe,ut as lernEinstellungen,ct as lernenAuffrischen,q as leserAnfrageApi,et as leserPunkteApi,Re as leserText,z as mischeMitLeser,st as promptEinblendung,je as promptKontext,M as renderLesson,We as resolveConfig,Xe as schreibeVorabBestand,Qe as selectRelevant,tt as selectRelevantMitLeser,we as sicherungsPfad,nt as sitzungsKontext,Te as starteNebenlauf};
|
|
@@ -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 j}from"../ckg.js";import{safeJsonParse as x,darfHeraus as N}from"../utils.js";import{ersparteMinuten as P,zaehltAlsErsparnis as F}from"../wertbeitrag.js";import{findePaare as K}from"../zulassung-und-urteil.js";import{Vektorbestand as O}from"../bedeutung.js";import{doppelPaare as H}from"../doppel-kandidat.js";import{DOPPEL_SCHWELLE as U}from"../rangfolge-stellschrauben.js";import{sofortAntwortNeuesBrain as W}from"../leeres-brain.js";import{fuerWeitergabe as z}from"../schreibtor.js";function B(A){return N(A)&&!A.group}const te=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function ne(A,S,M,L){switch(A){case"memory_consolidate":{const{instance_id:l,dry_run:g=!1,stale_days:$=90}=S,m=await M(l),w=Date.now(),d=$*86400*1e3;let u=0;const _=[];do{const[n,e]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(n),_.push(...e)}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 e=await m.get(n);if(!e)continue;const s=x(e,null);s&&c.set(n,s)}const y=new O(0);await y.aktualisiere(m).catch(()=>{});const f=H([...c.values()].flatMap(n=>{const e=y.rohvektor(n.topic);return e?[{lektion:n,vektor:e}]:[]})),k=[...c.values()],b=K(k),h=b.filter(n=>n.beziehung==="widerspruch"),v=b.filter(n=>n.beziehung==="ersetzung"),t=[],o=new Map;for(const[n,e]of c){const s=o.get(e.topic)??[];s.push(n),o.set(e.topic,s)}for(const[n,e]of o)new Set(e.map(i=>c.get(i)?.outcome)).size>1&&t.push({topic:n,keys:e});const a=[];for(const[n,e]of c){const s=w-new Date(e.ts).getTime(),i=e.recall_count??0;s>d&&i===0&&a.push(n)}const r=0;if(!g)for(const n of a)await m.expire(n,86400*30);return[`\u{1F52C} **Memory Consolidation Report** ${g?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${_.length} lessons`,"",`\u{1F501} **Contradictions \u2014 exact topic match (old rule):** ${t.length}`,`\u{1F50E} **Same subject, admitted for judgement:** ${b.length} \u2192 contradiction ${h.length} \xB7 supersession ${v.length}`,...h.slice(0,5).map(n=>` \u2192 \`${n.a.topic}\` vs \`${n.b.topic}\` (${n.naehe.toFixed(2)}): ${n.grund}`),h.length>5?` \u2026 and ${h.length-5} more`:"",...v.slice(0,3).map(n=>` \u21BB \`${n.a.topic}\` \u2192 \`${n.b.topic}\`: ${n.grund}`),...t.slice(0,5).map(n=>` \u2192 \`${n.topic}\`: ${n.keys.length} conflicting entries (kept: success)`),t.length>5?` \u2026 and ${t.length-5} more`:"","",`\u267B\uFE0F **Possible duplicates \u2014 same meaning, different topic (cosine \u2265 ${U.toFixed(2)}, never merged):** ${f.length}`+(y.groesse===0?" (no vectors in this Brain, so nothing could be compared)":""),...f.slice(0,5).map(n=>` \u2192 \`${n.neu}\` \u2248 \`${n.alt}\` (${n.naehe.toFixed(2)})`),f.length>5?` \u2026 and ${f.length-5} more`:"",f.length>0?' If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`.':"","",`\u{1F570}\uFE0F **Stale entries (${$}d, 0 recalls):** ${a.length}`+(a.length>0&&!g?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${_.length-r} lessons`,"",g?"\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:g="7d",format:$="summary"}=S,m=await M(l);let w;const d=g.match(/^(\d+)([dhm])$/);if(d){const e=parseInt(d[1]),s=d[2],i=s==="d"?864e5:s==="h"?36e5:6e4;w=Date.now()-e*i}else w=new Date(g).getTime()||Date.now()-7*864e5;let u=0;const _=[];do{const[e,s]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(e),_.push(...s)}while(u!==0);const c=[],y=[],f=[],k=_.length;for(const e of _){const s=await m.get(e);if(s){const i=x(s,null);if(!i)continue;if(new Date(i.ts).getTime()>=w){const T=`cachly:lesson:history:${i.topic}`;await m.llen(T)<=1?c.push(i):y.push(i)}(i.recall_count??0)>0&&f.push(i)}}const h=[`\u{1F4CA} **Brain Diff** \u2014 ${d?`last ${g}`:new Date(w).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${k}**`,"",`\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** (${y.length}):`,...y.slice(0,$==="detailed"?20:5).map(e=>` ~ \`${e.topic}\` \u2014 now: ${e.outcome}`),y.length>5&&$==="summary"?` \u2026 and ${y.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${f.length}`,""].filter(e=>e!==""),v=[],t=m.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((e,s)=>{t.on("data",i=>v.push(...i)),t.on("end",e),t.on("error",s)});const o=[];for(const e of v){const s=await m.get(e);if(s){const i=x(s,null);i?.ts&&new Date(i.ts).getTime()>=w&&o.push({topic:i.topic??e,resolution:i.resolution??"unknown",ts:i.ts})}}if(o.length>0){h.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${o.length} contested beliefs resolved):`);for(const e of o.slice(0,5)){const s=e.resolution==="unanimous_success"?"\u2705":e.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";h.push(` ${s} \`${e.topic}\` \u2192 ${e.resolution}`)}h.push("")}const a=new Set(y.concat(f).map(e=>e.topic.split(":")[0])),r=[...new Set(c.map(e=>e.topic.split(":")[0]))].filter(e=>!a.has(e));r.length>0&&h.push(`\u{1F331} **New domains bootstrapped:** ${r.map(e=>`\`${e}\``).join(", ")}`,"");const n=(await m.lrange("cachly:fedbrain:federations",-20,-1)).map(e=>x(e,null)).filter(e=>e!==null&&new Date(e.transferred_at).getTime()>=w);if(n.length>0){h.push(`\u{1F9E0} **FedBrain transfers received (${n.length}):**`);for(const e of n.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:g,max_depth:$=5,tags:m=[]}=S,w=await W(l,L,`\u{1F50D} **Causal Trace: "${g}"**
|
|
4
4
|
|
|
5
|
-
No matching lessons found in brain.`);if(
|
|
6
|
-
`);const
|
|
7
|
-
`)}case"knowledge_decay":{let
|
|
8
|
-
${
|
|
9
|
-
`)}case"autopilot":{const{instance_id:l,editor:
|
|
5
|
+
No matching lessons found in brain.`);if(w)return w;const d=await M(l),u=g.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(o=>o.length>2),_={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},c=[];try{for(const o of u.slice(0,4)){const a=await d.smembers(`cachly:ckg:idx:from:${j(o)}`),r=await d.smembers(`cachly:ckg:idx:to:${j(o)}`),p=[],n=d.scanStream({match:`cachly:ckg:node:*${o}*`,count:50});await new Promise((e,s)=>{n.on("data",i=>p.push(...i)),n.on("end",e),n.on("error",s)});for(const e of p.slice(0,10)){const s=await d.get(e);if(!s)continue;const i=x(s,null);if(!i)continue;const D=await d.smembers(`cachly:ckg:idx:from:${i.id}`);for(const T of D.slice(0,20)){const R=await d.get(T);if(!R)continue;const C=x(R,null);if(!C||C.edgeType!=="fixes"&&C.edgeType!=="requires")continue;const I=await d.get(`cachly:lesson:best:${C.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),E=I?x(I,null)??void 0:void 0;c.push({conceptId:i.id,edge:C,lesson:E&&B(E)?E:void 0})}}for(const e of[...a,...r].slice(0,20)){const s=await d.get(e);if(!s)continue;const i=x(s,null);if(!i)continue;const D=await d.get(`cachly:lesson:best:${i.from}`),T=D?x(D,null)??void 0:void 0;c.push({conceptId:i.from,edge:i,lesson:T&&B(T)?T:void 0})}}}catch{}const y=new Set,f=c.filter(o=>{const a=`${o.edge.from}:${o.edge.edgeType}:${o.edge.to}`;return y.has(a)?!1:(y.add(a),!0)}).sort((o,a)=>a.edge.confidence-o.edge.confidence).slice(0,$);let k=0;const b=[];do{const[o,a]=await d.scan(k,"MATCH","cachly:lesson:*","COUNT",200);k=parseInt(o),b.push(...a)}while(k!==0);const h=[];for(const o of b){const a=await d.get(o);if(a){const r=x(a,null);if(!r||!B(r)||m.length>0&&!(r.tags??[]).some(e=>m.includes(e)))continue;const p=[r.topic,r.what_failed??"",r.what_worked??"",r.context??""].join(" ").toLowerCase(),n=u.reduce((e,s)=>e+(p.includes(s)?1:0),0);n>0&&h.push({score:n,lesson:r,key:o})}}h.sort((o,a)=>a.score-o.score);const v=h.slice(0,$);if(v.length===0&&f.length===0)return[`\u{1F50D} **Causal Trace: "${g}"**`,"","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 = "${g}",`,")","```"].join(`
|
|
6
|
+
`);const t=[`\u{1F50D} **Causal Trace: "${g}"**`,""];if(f.length>0){t.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const o of f){const a=Math.round(o.edge.confidence*100),r="\u2593".repeat(Math.round(a/10))+"\u2591".repeat(10-Math.round(a/10));t.push(` ${o.edge.from} **\u2192[${o.edge.edgeType}]\u2192** ${o.edge.to}`),t.push(` ${r} ${a}% confidence (${o.edge.successes}/${o.edge.trials} confirmed)`),o.lesson?.what_worked&&t.push(` \u2705 Fix: ${o.lesson.what_worked.slice(0,150)}`),t.push("")}}if(v.length>0){t.push(f.length>0?`### \u{1F4DA} Text Search (${v.length} related lessons)`:`Found **${v.length}** related lessons. Reconstructed causal chain:`,"");const o=v.filter(p=>p.lesson.outcome!=="success"),a=v.filter(p=>p.lesson.outcome==="success");o.length>0&&(t.push("**Root causes & failure chain:**"),o.forEach((p,n)=>{const e=p.lesson,s=_[e.severity??"minor"]??"\u{1F7E1}";t.push(`${n===0?" Root:":" \u2192 :"} ${s} \`${e.topic}\``),e.what_failed&&t.push(` \u21B3 ${e.what_failed.slice(0,120)}`)}),t.push("")),a.length>0&&(t.push("**Solutions that worked before:**"),a.forEach((p,n)=>{const e=p.lesson,s=new Date(e.ts).toLocaleDateString("de-DE");t.push(` ${n+1}. \u2705 \`${e.topic}\` \u2014 ${s} \xB7 recalled ${e.recall_count??0}\xD7`),e.what_worked&&t.push(` ${e.what_worked.slice(0,200)}`)}),t.push(""));const r=a[0]?.lesson;if(r?.what_worked){t.push("**\u26A1 Most likely fix:**"),t.push("```"),t.push(r.what_worked.slice(0,500)),t.push("```"),t.push("");const p=F(r)?P(r,"trace"):0;p>0&&d.incrbyfloat(`cachly:stats:time_saved_mins:${l}`,p).catch(()=>{})}}return t.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${u[0]??"issue"}", outcome="success", ...)\``),f.length>0&&t.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${u[0]??"fix"}")\``),t.join(`
|
|
7
|
+
`)}case"knowledge_decay":{let f=function(t){const o=Math.round(t/10);return"\u2588".repeat(o)+"\u2591".repeat(10-o)+` ${t}%`};const{instance_id:l,min_age_days:g=0,show_top:$=20}=S,m=await M(l),w=Date.now(),d=g*864e5;let u=0;const _=[];do{const[t,o]=await m.scan(u,"MATCH","cachly:lesson:best:*","COUNT",200);u=parseInt(t),_.push(...o)}while(u!==0);const c=[];for(const t of _){const o=await m.get(t);if(o){const a=x(o,null);if(!a)continue;const r=w-new Date(a.ts).getTime();if(r<d)continue;const p=Math.floor(r/864e5),n=a.recall_count??0,e=Math.max(0,p-7),s=Math.max(5,100-e),i=Math.min(50,n*5),D=a.outcome==="failure"?-20:0,T=Math.min(100,Math.max(0,s+i+D));c.push({topic:a.topic,confidence:T,age_days:p,recalls:n,outcome:a.outcome})}}c.sort((t,o)=>t.confidence-o.confidence);const y=c.slice(0,$),k=c.length>0?Math.round(c.reduce((t,o)=>t+o.confidence,0)/c.length):0,b=c.filter(t=>t.confidence<30).length,h=c.filter(t=>t.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${c.length} lessons`,"",`Average confidence: **${f(k)}**`,`\u{1F534} Critical (<30%): ${b} \u{1F7E2} Healthy (\u226570%): ${h}`,"","Lowest confidence lessons (fix these first):","",...y.map((t,o)=>`${(o+1).toString().padStart(2)}. \`${t.topic}\`
|
|
8
|
+
${f(t.confidence)} \xB7 ${t.age_days}d old \xB7 ${t.recalls} recalls \xB7 ${t.outcome}`),"",c.length>$?`\u2026 and ${c.length-$} more lessons`:"","",b>0?`\u26A0\uFE0F ${b} 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(t=>t!=="").join(`
|
|
9
|
+
`)}case"autopilot":{const{instance_id:l,editor:g="claude",project_name:$="this project",style:m="full"}=S,w=z({editor:String(g),project_name:String($)},"die Anweisungsdatei (CLAUDE.md)");if(!w.ok)return w.meldung;const d=(b,h)=>b.replace(/[\p{C}\s]+/gu," ").trim().slice(0,h),u=d(w.felder.editor,30)||"claude",_=d(w.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(g)return g;const d=await M(l),u=p.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
|
+
`,y=`## 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
|
+
`,f=m==="minimal"?c:y,k=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:** \`${k}\` \u2014 create it, or APPEND to your existing one`,"","```markdown",f,"```","",`**How to apply** (\`>>\` appends \u2014 an existing ${k} keeps every line you wrote):`,"```bash",`cat >> ${k} << 'EOF'`,f,"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{te as ADVANCED_TOOL_NAMES,ne as handleAdvancedTool};
|