@cachly-dev/mcp-server 0.10.143 → 0.10.145
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/abstention.js +2 -2
- package/dist/src/bedeutung.js +2 -2
- package/dist/src/embeddings.js +4 -4
- package/dist/src/handlers/brain.js +57 -57
- package/dist/src/rangfolge-stellschrauben.js +1 -1
- package/glama.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/src/abstention.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CKG_BELEG_SCHWELLE as
|
|
2
|
-
`)}export{m as abstentionSatz,E as beurteileTreffer};
|
|
1
|
+
import{CKG_BELEG_SCHWELLE as f,SINN_BELEG_SCHWELLE as u,WORT_BELEG_SCHWELLE as c}from"./rangfolge-stellschrauben.js";const s=e=>typeof e=="number"&&Number.isFinite(e)?e:0;function h(e,t={}){return s(e.wortBelege)>=(t.woerter??c)||s(e.semScore)>=(t.naehe??u)||s(e.ckgScore)>=(t.kante??f)}function E(e,t={}){let r=0,n=0,i=!1,g=0;for(const o of e){const a=s(o.wortBelege),l=s(o.semScore);a>r&&(r=a),l>n&&(n=l),h(o,t)&&(i=!0,g++)}return{schweigen:e.length===0||!i,besteWortBelege:r,besteNaehe:n,geprueft:e.length,belegte:g}}function m(e,t={}){if(e.geprueft===0)return"\u{1F50D} **Nichts Passendes im Bestand** \u2014 zu dieser Frage gibt es noch keine Lektion.";const r=t.woerter??c,n=t.naehe??u;return["\u{1F50D} **Nichts Passendes im Bestand.**","",`${e.geprueft} Treffer betrachtet, keiner belegt \u2014 der beste enthielt ${e.besteWortBelege} der gesuchten W\xF6rter (n\xF6tig: ${r}), h\xF6chste Bedeutungsn\xE4he ${e.besteNaehe.toFixed(2)} (n\xF6tig: ${n.toFixed(2)}).`,"Sie werden bewusst NICHT gezeigt: ein schwacher Treffer sieht wie ein starker aus, und der Unterschied entscheidet.","",'_Wenn die Antwort trotzdem im Bestand liegen sollte, hilft eine Frage mit anderen Worten \u2014 oder `recall_best_solution(topic="\u2026")`, wenn das Thema bekannt ist._'].join(`
|
|
2
|
+
`)}const b=5;function B(e){const t=e.filter(i=>Number.isFinite(i)&&i>=0);if(t.length===0)return null;const r=Math.min(...t),n=Math.max(...t);return r<b?null:t.length===1?`Der belegte Treffer ist ${n} Tage unbest\xE4tigt.`:r===n?`Die belegten Treffer sind ${n} Tage unbest\xE4tigt.`:`Die belegten Treffer sind seit ${r}\u2013${n} Tagen unbest\xE4tigt.`}export{b as ALTER_NENNEN_AB_TAGEN,m as abstentionSatz,B as alterssatzFuerBelegte,E as beurteileTreffer,h as istBelegt};
|
package/dist/src/bedeutung.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const x="cachly:lesson:vec:",
|
|
2
|
-
`).slice(0,2e3)}class
|
|
1
|
+
const x="cachly:lesson:vec:",E="cachly:lesson:vecname:",w="cachly:lesson:vec2:";function b(o){return o.replace(/[:_-]+/g," ").replace(/\s+/g," ").trim()}const f=1,a=7;function d(o){let e=0;for(const t of o){const n=Math.abs(t);n>e&&(e=n)}const i=e>0?e/127:1;let r=a+o.length;for(;r%4!==1;)r++;const s=Buffer.alloc(r);s.writeUInt8(f,0),s.writeUInt16LE(o.length,1),s.writeFloatLE(i,3);for(let t=0;t<o.length;t++){const n=Math.round(o[t]/i);s.writeInt8(n>127?127:n<-127?-127:n,a+t)}return s.toString("base64")}function k(o){try{const e=Buffer.from(o,"base64");if(e.byteLength===0)return null;if(e[0]===f&&e.byteLength%4===1&&e.byteLength>a){const r=e.readUInt16LE(1);if(r===0||a+r>e.byteLength)return null;const s=e.readFloatLE(3);if(!Number.isFinite(s))return null;const t=new Array(r);for(let n=0;n<r;n++)t[n]=e.readInt8(a+n)*s;return t}if(e.byteLength%4!==0)return null;const i=new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return Array.from(i)}catch{return null}}function u(o,e){if(o.length!==e.length)return-1;let i=0,r=0,s=0;for(let t=0;t<o.length;t++)i+=o[t]*e[t],r+=o[t]*o[t],s+=e[t]*e[t];return r&&s?i/Math.sqrt(r*s):0}function v(o){const e=i=>typeof i=="string"?i:"";return[e(o.topic),e(o.what_worked),e(o.what_failed)].filter(Boolean).join(`
|
|
2
|
+
`).slice(0,2e3)}class _{frischeMs;praefix;vektoren=new Map;geladen=0;constructor(e=6e4,i=x){this.frischeMs=e,this.praefix=i}naehe(e,i){const r=this.vektoren.get(`${this.praefix}${i}`);return r?u(e,r):-2}rohvektor(e){return this.vektoren.get(`${this.praefix}${e}`)??null}get groesse(){return this.vektoren.size}async aktualisiere(e,i=Date.now()){if(this.vektoren.size>0&&i-this.geladen<this.frischeMs)return;const r=[];let s="0";do{const[n,c]=await e.scan(s,"MATCH",`${this.praefix}*`,"COUNT",500);s=n,r.push(...c)}while(s!=="0");const t=r.filter(n=>!this.vektoren.has(n));for(let n=0;n<t.length;n+=100){const c=t.slice(n,n+100),g=await e.mget(...c);for(const[p,l]of g.entries()){if(!l)continue;const h=k(l);h&&this.vektoren.set(c[p],h)}}if(r.length<this.vektoren.size){const n=new Set(r);for(const c of[...this.vektoren.keys()])n.has(c)||this.vektoren.delete(c)}this.geladen=i}aehnlichste(e,i){const r=[];for(const[s,t]of this.vektoren)r.push({topic:s.slice(this.praefix.length),naehe:u(e,t)});return r.sort((s,t)=>t.naehe-s.naehe),r.slice(0,i)}}const y=.1;function I(o,e,i=y,r=60){const s=new Map;return o.forEach((t,n)=>s.set(t,(s.get(t)??0)+i/(r+n+1))),e.forEach((t,n)=>s.set(t,(s.get(t)??0)+(1-i)/(r+n+1))),[...s.entries()].sort((t,n)=>n[1]-t[1]).map(([t])=>t)}export{E as NAME_VEKTOR_PRAEFIX,x as VEKTOR_PRAEFIX,_ as Vektorbestand,y as WORT_GEWICHT,w as ZWEIT_VEKTOR_PRAEFIX,k as entpacke,u as kosinus,I as mischeRangfolgen,d as packe,b as textFuerNamensVektor,v as textFuerVektor};
|
package/dist/src/embeddings.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
const s={apiUrl:process.env.CACHLY_API_URL??"https://api.cachly.dev",jwt:process.env.CACHLY_JWT??"",model:process.env.CACHLY_EMBED_MODEL??""};function
|
|
1
|
+
const s={apiUrl:process.env.CACHLY_API_URL??"https://api.cachly.dev",jwt:process.env.CACHLY_JWT??"",model:process.env.CACHLY_EMBED_MODEL??""};function C(r){s.jwt=r}const u=Number(process.env.CACHLY_EMBED_TIMEOUT_MS??8e3),p=Number(process.env.CACHLY_EMBED_TIMEOUT_MAX_MS??45e3),A=12;function h(r,n){return n==="kurz"?u:Math.min(p,u+r.length*A)}function f(){return process.env.CACHLY_JWT?"cachly":process.env.OLLAMA_BASE_URL?"ollama":"none"}const c=(process.env.CACHLY_EMBED_PROVIDER??f()).toLowerCase();async function g(r,n,i){const a=h(r,n);switch(c){case"cachly":{if(!s.jwt)throw new Error(`CACHLY_JWT not set.
|
|
2
2
|
|
|
3
3
|
The "cachly" provider uses server-side embeddings via the Cachly API.
|
|
4
4
|
Set CACHLY_JWT, or use another provider via CACHLY_EMBED_PROVIDER:
|
|
5
5
|
openai \u2192 OPENAI_API_KEY
|
|
6
6
|
gemini \u2192 GEMINI_API_KEY
|
|
7
|
-
ollama \u2192 OLLAMA_BASE_URL (local, no key needed)`);const
|
|
7
|
+
ollama \u2192 OLLAMA_BASE_URL (local, no key needed)`);const t=`${s.apiUrl}/api/v1/embed`,o={text:r};(i??s.model)&&(o.model=i??s.model);const e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.jwt}`},body:JSON.stringify(o),signal:AbortSignal.timeout(a)});if(!e.ok){const _=await e.text();let l=null;const m=Number(e.headers.get("retry-after"));if(Number.isFinite(m)&&m>=0)l=m;else try{const E=JSON.parse(_);typeof E.retry_after=="number"&&E.retry_after>=0&&(l=E.retry_after)}catch{}throw Object.assign(new Error(`Cachly embed API error ${e.status}: ${_.slice(0,200)}`),{status:e.status,retryAfterSek:l})}return(await e.json()).embedding}case"mistral":{const t=process.env.MISTRAL_API_KEY;if(!t)throw new Error("MISTRAL_API_KEY not set");const o=s.model!=="text-embedding-3-small"?s.model:"mistral-embed",e=await fetch("https://api.mistral.ai/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:o,input:[r]}),signal:AbortSignal.timeout(a)});if(!e.ok)throw new Error(`Mistral embedding error: ${e.statusText}`);const d=await e.json();if(!d.data?.[0]?.embedding)throw new Error("Mistral returned empty embedding response");return d.data[0].embedding}case"cohere":{const t=process.env.COHERE_API_KEY;if(!t)throw new Error("COHERE_API_KEY not set");const o=s.model!=="text-embedding-3-small"?s.model:"embed-english-v3.0",e=await fetch("https://api.cohere.com/v2/embed",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:o,texts:[r],input_type:"search_query",embedding_types:["float"]}),signal:AbortSignal.timeout(a)});if(!e.ok)throw new Error(`Cohere embedding error: ${e.statusText}`);return(await e.json()).embeddings.float[0]}case"ollama":{const t=process.env.OLLAMA_BASE_URL??"http://localhost:11434",o=i??(s.model!=="text-embedding-3-small"?s.model:"nomic-embed-text"),e=await fetch(`${t}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o,prompt:r}),signal:AbortSignal.timeout(a)});if(!e.ok)throw new Error(`Ollama embedding error: ${e.statusText}`);return(await e.json()).embedding}case"gemini":{const t=process.env.GEMINI_API_KEY;if(!t)throw new Error("GEMINI_API_KEY not set");const o=s.model!=="text-embedding-3-small"?s.model:"text-embedding-004",e=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${o}:embedContent?key=${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`models/${o}`,content:{parts:[{text:r}]}}),signal:AbortSignal.timeout(a)});if(!e.ok)throw new Error(`Gemini embedding error: ${e.statusText}`);return(await e.json()).embedding.values}case"openai":{const t=process.env.OPENAI_API_KEY;if(!t)throw new Error(`OPENAI_API_KEY not set.
|
|
8
8
|
|
|
9
9
|
Set OPENAI_API_KEY in your .env, or switch provider:
|
|
10
10
|
CACHLY_EMBED_PROVIDER=gemini (+ GEMINI_API_KEY)
|
|
11
11
|
CACHLY_EMBED_PROVIDER=ollama (local, free)
|
|
12
|
-
CACHLY_EMBED_PROVIDER=cachly (server-side, no key needed)`);const
|
|
13
|
-
Supported: cachly (default), openai, mistral, cohere, ollama, gemini`)}}const
|
|
12
|
+
CACHLY_EMBED_PROVIDER=cachly (server-side, no key needed)`);const o=s.model||"text-embedding-3-small",e=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:o,input:r}),signal:AbortSignal.timeout(a)});if(!e.ok)throw new Error(`OpenAI embedding error: ${e.statusText}`);const d=await e.json();if(!d.data?.[0]?.embedding)throw new Error("OpenAI returned empty embedding response");return d.data[0].embedding}default:throw new Error(`Unknown CACHLY_EMBED_PROVIDER="${c}".
|
|
13
|
+
Supported: cachly (default), openai, mistral, cohere, ollama, gemini`)}}const b=3,I=4;function w(r){const n=r;if(typeof n?.status=="number")return n.status===429||n.status>=500;if(n?.name==="TimeoutError"||n?.name==="AbortError")return!1;if(/fetch failed/i.test(String(n?.message??"")))return!0;const i=n?.cause?.code??"";return["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","EPIPE","UND_ERR_SOCKET"].includes(i)}function y(r,n,i){if(n>=(i==="lang"?I:b)||!w(r))return null;const t=r?.retryAfterSek;if(typeof t=="number"&&Number.isFinite(t)&&t>=0){const o=t*1e3;return i==="kurz"?o<=2e3?o:null:Math.min(o,61e3)}return i==="lang"?Math.min(1e3*2**(n-1),8e3):250*2**(n-1)}async function P(r,n){const i=n?.geduld??"kurz";if(n?.modell&&c!=="cachly"&&c!=="ollama")throw new Error(`Anbieter "${c}" kann kein abweichendes Modell anfragen (verlangt: ${n.modell}).`);let a=0;for(;;){a++;try{return await g(r,i,n?.modell)}catch(t){const o=y(t,a,i);if(o===null)throw t;await new Promise(e=>setTimeout(e,o))}}}function M(){switch(c){case"cachly":return!!s.jwt;case"mistral":return!!process.env.MISTRAL_API_KEY;case"cohere":return!!process.env.COHERE_API_KEY;case"ollama":return!0;case"gemini":return!!process.env.GEMINI_API_KEY;case"openai":return!!process.env.OPENAI_API_KEY;case"none":return!1;default:return!1}}function O(){const r={cachly:"CACHLY_JWT (server-side, no extra key needed)",openai:"OPENAI_API_KEY",mistral:"MISTRAL_API_KEY",cohere:"COHERE_API_KEY",ollama:"OLLAMA_BASE_URL (optional, default: http://localhost:11434)",gemini:"GEMINI_API_KEY"};if(c==="none")return"No embedding provider configured. Set OPENAI_API_KEY, GEMINI_API_KEY, or another provider key in .env. Brain works without embedding.";const n=r[c]??"CACHLY_JWT";return`CACHLY_EMBED_PROVIDER=${c} \u2192 requires ${n}`}export{c as EMBED_PROVIDER,P as computeEmbedding,s as embedConfig,O as embedProviderHint,M as hasEmbedProvider,w as istVoruebergehend,C as setEmbedJwt,y as wiederholungMs,h as zeitlimitMs};
|
|
@@ -1,73 +1,73 @@
|
|
|
1
|
-
import{execSync as qe}from"node:child_process";import{createRequire as Ue}from"node:module";import{calculateConfidence as Te,confidenceBadge as bt,STRUCTURED_TEMPLATES as $t,CONFIDENCE_WARN_VALUE as Ve,CONFIDENCE_STALE_VALUE as vt,CONFIDENCE_WARN_DAYS as kt}from"../confidence.js";import{ckgSlug as le,extractProblemConcept as De,ckgUpsertNode as ke,ckgUpdateEdge as ue,ckgUpsertPersonNode as St,ckgUpsertFileNode as Ye,ckgRecordCollaboration as Ct,ckgUpsertServiceNode as xt}from"../ckg.js";import{safeJsonParse as j,scanKeys as pe,leseOderNull as _e,darfHeraus as Se}from"../utils.js";import{ersparteMinuten as Ze,istStarterLektion as Ne,zaehltAlsErsparnis as Xe}from"../wertbeitrag.js";import{lessonPreviewLines as Ce,trimTo as Tt}from"../lesson-preview.js";import{normalisiereZeit as Be,zaehleZeitangaben as Le}from"../zeit-normalisieren.js";import{abstentionSatz as Nt,beurteileTreffer as At}from"../abstention.js";import{meldeEinmal as Oe,meldeUndVermerke as Ae,fehlerText as Pe,OHNE_VEKTOREN as Et,OHNE_DIENST as Mt,OHNE_FRAGEVEKTOR as It,SINNPFAD_ABBRUCH as Rt,OHNE_SCHREIBVEKTOR as je}from"../aussetzer.js";import{versuchStart as Dt,neueKennung as Bt,wendeZuteilungAn as Lt,schliesseVersuchAb as Ot}from"../versuch.js";function Qe(ce,Z,Q){if(ce.includes("lesson:best:")){const f=j(Z,{});if(f&&typeof f=="object"&&(f.what_worked||f.what_failed||f.commands?.length))return Ce(f,{maxChars:Q,indent:" "})}const de=Tt(Z,Q);return de?[de]:[]}import{getRole as ze,ROLE_BADGE as Pt,getScopes as et,lessonVisibleToScope as tt,reviewModeEnabled as jt,storeLessonProposal as zt}from"./team.js";import{keywordSearch as Ee,wortindexEntwerten as Ft,tokenize as Fe,splitMultiQuery as Wt,levenshtein as Kt,indexVocab as st}from"../search.js";import{rerankByQuality as Gt,qualityMultiplier as Ht,extractLessonQuality as Jt}from"../rerank.js";import{computeEmbedding as be,hasEmbedProvider as Me,EMBED_PROVIDER as We}from"../embeddings.js";import{repariereFelder as qt}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as nt,NAME_VEKTOR_PRAEFIX as ot,packe as Ke,textFuerVektor as at,textFuerNamensVektor as Ut,Vektorbestand as it}from"../bedeutung.js";import{schreibeEingaenge as Vt,Eingangsbestand as Yt}from"../eingaenge.js";import{Seltenheitsbestand as Zt}from"../seltenheitsbestand.js";import{spurLegen as Xt}from"../spuren.js";import{schlageErsetzungVor as Qt}from"../ersetzung-vorschlag.js";const xe="cachly:vek:nachtrag",es=365;import{etikettenFuer as ts,lieferJournalSchluessel as rt,JOURNAL_DECKEL as ss}from"../etiketten.js";import{klassifiziereFehlschlag as ns,suchProtokollSchluessel as ct,trichterSchluessel as lt,SUCH_DECKEL as os}from"../recall-trichter.js";import{leiteEntscheidungAb as as,entscheidungsZeile as ut}from"../entscheidung-ableiten.js";import{bewerteTopf as is,spreizeImTopf as rs,reichereAn as cs,inhaltsWoerter as ht,grobStamm as ls,GEWICHTE as us,knapperSiegSatz as hs}from"../rangfolge.js";import{pruefeWirkung as ds,werteAus as fs,lehrwert as ps,leiteAb as ms}from"../wirkungsspur.js";import{SINN_TOPF as gs,EINGANG_SCHWELLE as ys,EINGANG_SORTIER_GEWICHT as ws}from"../rangfolge-stellschrauben.js";const $e=new it,Ge=new it(6e4,ot),He=new Yt,Ie=new Zt,_s=gs,bs=ys,$s=ws;import{upgradeNudge as vs}from"../upgrade-nudge.js";import{recallTiefe as dt,TIEFE_VOLL as ks,TIEFE_VOLL_MEHRTHEMIG as Ss}from"../recall-tiefe.js";import{nutzungInWorten as Cs,nutzungsSchluessel as xs,verdichte as Ts}from"../werkzeug-nutzung.js";import{inWorten as Ns,lieferBild as As,lieferSchluessel as Es,trefferSchluessel as Ms}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Is,autorHinweis as Rs,coautorAus as Ds,echterGitLeser as Bs,ermittleAutor as Ls,mitCoautor as Os,nurMensch as ft}from"../autor.js";import{TOOLS as Ps}from"../tools.js";import{vorspannHinweis as js}from"../vorspann.js";import{autorAbzeichen as zs,fremdanteil as Fs}from"../autor-abzeichen.js";import{cachlyUrl as Ws}from"../cachly-url.js";const Re=(()=>{try{const ce=Ue(import.meta.url);for(const Z of["../../../package.json","../../package.json"])try{const Q=ce(Z);if(Q.name==="@cachly-dev/mcp-server"&&Q.version)return Q.version}catch{}}catch{}return"0.10.100"})(),Ks=()=>{try{return Ue(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Gs={"0.10.119":["\u{1F50D} **Explainable briefings \u2014 provenance in every warning**"," \u{1F4CE} `/briefing` warnings now carry `outcome`, `author`, `learned_at` and `matched_on` (the context tokens that triggered the warning) \u2014 editors can show WHY a fix hint fired, not just what it claims.",' \u{1F9F0} VS Code 0.12.0 uses this: severity + confidence in the toast, full lesson card with provenance, "Not helpful" per-file suppression, reviewable CLS auto-learns.'," \u{1F9F9} CI docs now describe exactly what ships: scan mode uses the REST `/scan` endpoint, the GitLab template covers learn/scan/confirm."],"0.10.115":["\u{1F527} **`brain_get_pref` + `brain_set_pref` \u2014 persistent Brain preferences**"," \u{1F4D6} `brain_get_pref` reads back any stored preference (omit key to list all)."," \u270F\uFE0F `brain_set_pref` saves a preference to Redis \u2014 survives restarts, scoped per Brain instance.",' \u{1F4A1} Known key: `auto_changelog` \u2014 set to "false" to silence the new-lessons digest at session_start.'," \u{1F4CA} 140 MCP tools"],"0.10.114":["\u{1F4CB} **`brain_changelog` \u2014 weekly knowledge digest in one call**"," \u{1F4C5} Generates a grouped Markdown changelog of lessons learned in the last N days."," \u{1F465} Grouped by topic category, annotated with author, recall count, and confidence \u2014 paste directly into standup or Slack."," \u2699\uFE0F Params: `days` (default 7), `max_lessons` (default 30), `include_failures` (default true)."," \u{1F4CA} 138 MCP tools"],"0.10.113":["\u{1F4C8} **Week-over-week savings trend in `cache_stats`**"," \u{1F4C5} `cache_stats` now shows **7-day hits** + **WoW trend %** (e.g. `+23.0% vs prev week`) so ROI momentum is visible, not just the cumulative total."," \u2B07\uFE0F Goes red (\u{1F4C9}) on drops, green (\u{1F4C8}) on growth \u2014 first week always shows +100% (new)."," \u{1F527} Backed by new `CountHitsInWindow` repo method + `hits_last_7d`, `hits_prev_7d`, `week_over_week_pct` fields in `SavingsEstimate`."," \u{1F4CA} 137 MCP tools"],"0.10.112":["\u2699\uFE0F **Configurable cost_per_call_usd \u2014 accurate ROI for any LLM**"," \u{1F4A1} New `set_cost_per_call` tool: set your real per-call cost (claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001) so savings estimates in `cache_stats` reflect your actual bill."," \u{1F527} New API: `PUT /api/v1/instances/:id/cost-per-call` \u2014 persisted per instance, used by `cache_stats`, org savings, and SSE analytics stream."," \u{1F4CA} 137 MCP tools"],"0.10.111":["\u{1F3E2} **Org-wide ROI + GitLab CI \u2014 the CFO number, aggregated**"," \u{1F4B0} `cache_org_stats` now shows **org-wide Tokenmaxxing ROI**: total savings summed across every instance in your org, monthly projection, top-5 instances by savings. One number for the whole team."," \u{1F50C} Backed by new API endpoint `GET /api/v1/orgs/:id/savings` (org members only)"," \u{1F98A} GitLab CI integration: `brain-from-ci-gitlab.yml` \u2014 two `.post` jobs (on_success/on_failure), same helper script, pipeline never fails because of Brain push"," \u{1F6E0}\uFE0F GitHub Action template fixed: `secrets.*` in job-level `if` is invalid \u2014 guard removed (helper script skips cleanly on missing secrets)"," \u{1F4CA} 136 MCP tools"],"0.10.110":["\u{1F3E2} **Zero friction: ROI-Projektor, Org-Shared-Cache, CI ready-to-paste**"," \u{1F4C8} `cache_stats` \u2014 zero-hit projection calculator: shows expected monthly savings for 5/10/20-dev teams before a single cache hit lands. ROI visible from day 1."," \u{1F3E2} New `cache_org_stats` \u2014 shared org-level cache stats across multiple instances. Convention-based (`org:{id}:sem`), zero API changes needed."," \u{1F517} `cache_set`/`cache_get` now accept optional `org_id` \u2014 write to personal + org namespace, fall back to org on miss. Fully backwards-compatible."," \u{1F4CB} Copy-paste CI integration: `brain-from-ci-action.yml` \u2192 Brain self-calibrates confidence on every GitHub Actions run. No config beyond two repo secrets."," \u{1F4CA} 136 MCP tools"],"0.10.109":["\u{1F4B0} **Tokenmaxxing ROI + Closed-loop CI learning**"," \u{1F4CA} `cache_stats` now shows a **Tokenmaxxing ROI** section \u2014 total tokens saved, monthly cost projection, and top 3 most-cached prompts. Finally a number you can show the CFO."," \u{1F504} New `brain_from_ci` \u2014 bulk-ingest CI history into the Brain (red\u2192green = learned fix, green\u2192red = CKG causal edge). The brain_from_git equivalent for CI. Bootstrap the Brain from your CI logs in one call."," \u{1F4CA} 134 MCP tools"],"0.10.108":["\u{1F9E0} **Focused briefing + trustworthy autopilot**"," \u{1F3AF} New `session_start_summary` \u2014 top-N focused briefing by topic. Scores lessons by relevance \xD7 confidence + recall_count + severity + recency. Use it for a quick pre-brief without loading the full Brain.",' \u{1F91D} Autopilot template now explains the data flow upfront ("your own Brain, EU-hosted, no third parties") \u2014 no more friction with cautious AI assistants during onboarding'," \u{1F4CA} 132 MCP tools"],"0.10.107":["\u{1F3AF} **Recall@3 gap closed \u2014 the moat proof got sharper (the head-to-head that matters)**"," \u{1F50D} External-corpus Recall@3 **82.1% \u2192 98.2%** \xB7 Precision@1 **80.4%** \xB7 MRR **89.0%** \u2014 now ahead of flat-file memory on every metric"," \u{1F9EC} Root-cause fix: documents are no longer indexed with cross-lingual synonyms (the symmetric-expansion bug inflated any doc containing a common word ~28\xD7, burying topic-specific lessons). Queries still expand \u2014 a \u65E5\u672C\u8A9E query still finds English lessons."," \u2696\uFE0F Reranker now compresses BM25 with score^0.3 before applying lesson quality, so a proven success can overtake a text-similar failed attempt even when the distractor scores 5\u20136\xD7 higher in raw BM25"," \u{1F6E1}\uFE0F CI bench gate widened to both home + external corpora with committed floors (`npm run bench:gate`) \u2014 recall quality can never silently regress again"," \u{1F4CA} 121 MCP tools"],"0.10.98":['\u{1F310} **Model-Neutrality as Feature (W9) \u2014 "Bring your own model, keep your brain."**'," \u{1F50C} New `brain_portability()` \u2014 shows your Brain ID, all compatible MCP clients, and ready-to-paste config snippets for each; proves the same Brain works in Claude, Cursor, Copilot, Windsurf, Cline, Zed and more"," \u{1F9E0} Your lessons, crystals, and predictions are model-agnostic \u2014 no vendor lock-in at the memory layer",' \u{1F4D6} New docs: cachly.dev/docs/model-neutral \u2014 "Same Brain, Any Model" guide with live config examples'," \u{1F4CA} 121 MCP tools (new: `brain_portability`)"],"0.10.97":['\u{1F4A0} **Team Crystallize (W8) \u2014 the team-wide, causal counter to per-user "Dreaming"**'," \u{1F9EC} New `team_crystallize()` \u2014 surfaces fixes that 2+ teammates *independently converged on*, the one thing a single-user memory structurally can't build",' \u{1F9E9} Cross-person clustering: groups structurally similar problems across people & namespaces (e.g. "pool exhaustion" solved the same way in payments, auth & db)',' \u{1F465} Each pattern names who converged \u2014 instant "ask @alice and @bob, they both hit this"'," \u{1F48E} Shows up in `crystal_view` alongside your per-brain crystal"," \u{1F4CA} 120 MCP tools (new: `team_crystallize`)"],"0.10.96":["\u{1F510} **Roles & Team-Scopes now ENFORCED (W6) \u2014 the enterprise governance layer**"," \u{1F6E1}\uFE0F `team_confirm` is now reviewer-gated, `team_learn` blocks viewers (recall-only) \u2014 roles stop being cosmetic the moment an admin is assigned"," \u{1F4DC} New `team_audit` tool \u2014 immutable, admin-only trail of every role change & lesson confirmation, for compliance & security reviews"," \u{1F513} Zero impact on open teams: governance activates only once you bootstrap an admin; before that everything works exactly as before"," \u{1F4CA} 119 MCP tools (new: `team_audit`)"],"0.10.95":["\u{1F9E0} **Domain Brain Marketplace (W10) \u2014 bootstrap your Brain with curated community knowledge**"," \u{1F6D2} `brain_marketplace()` \u2014 browse installable packs of high-trust lessons by domain: \u2638\uFE0F Kubernetes, \u{1F510} Auth, \u{1F5C4}\uFE0F Database, \u269B\uFE0F React, \u{1F4B3} Payments & more",' \u{1F4E6} `brain_install(slug="k8s")` \u2014 merges a domain\'s verified lessons into your Brain; live in `smart_recall` instantly, even offline',' \u{1F6E1}\uFE0F Idempotent + non-destructive: installed lessons are tagged `source:"marketplace:<slug>"` and NEVER override your own'," \u{1F50C} New gRPC `Subscribe` RPC \u2014 agents get new lessons streamed live the moment they're learned (completes the M2M loop with `Learn`)"," \u{1F4CA} 118 MCP tools (new: `brain_marketplace`, `brain_install`)"],"0.10.94":['\u{1F91D} **Person\u2194Person Collaboration Graph (W5) \u2014 "Frag X und Y, die haben das zusammen gel\xF6st"**'," \u{1F578}\uFE0F New `brain_collab_pairs()` tool: shows every contributor pair who've touched the same files or recalled each other's lessons \u2014 ideal for onboarding and bus-factor analysis"," \u{1F4E1} `smart_recall` now wires CKG `collaborates` edges live when cross-author reuse fires \u2014 collaboration graph grows with every team recall"," \u26A0\uFE0F Bus-factor section: flags solo contributors whose knowledge no teammate has yet recalled"," \u{1F4CA} 116 MCP tools (new: `brain_collab_pairs`)"],"0.10.93":['\u{1F5FA}\uFE0F **`brain_plan` \u2014 your Brain goes from "what did we learn?" to "what should I do?"**',` \u{1F9ED} Give it a task you're about to start ("upgrade Postgres 14\u219216") and it returns an ordered, grounded action plan: ranked failure modes to avoid, proven fix steps (dependency-aware, with commands), and a pre-flight checklist \u2014 all from your own lessons`,' \u{1F52C} Generative layer on the CKG: where `brain_predict` answers "what might fail?", `brain_plan` answers "what, in what order?"'," \u{1F4CA} 115 MCP tools (new: `brain_plan`)"],"0.10.92":["\u{1F44B} **Welcome-back digest \u2014 re-entry after a week away now leads with what changed**"," \u{1F331} `session_start` detects a gap \u2265 7 days and surfaces how many lessons your Brain gained while you were gone (git, CI & teammates kept it learning), with the freshest topics"," \u{1F9E0} Zero extra latency \u2014 the digest is computed from data session_start already loads"," \u{1F50C} New gRPC `Learn` RPC (M2M write path) \u2014 agents & CI can now teach the Brain directly, byte-compatible with the MCP lesson format"," \u{1F4CA} 115 MCP tools"],"0.10.91":["\u{1F550} **Lesson-anchored time attribution \u2014 every recall shows when it was learned and how much it saves**",` \u{1F4A1} "Brain saved you" banner now includes: when the lesson was learned (e.g. "12 May"), estimated original debug cost by severity (critical=2h, major=1h, minor=20min), and team attribution when a teammate's lesson fires`,' \u{1F4C5} Origin date formatted as "12 May" (same year) or "12 May 2024" (different year) \u2014 no clutter',' \u{1F465} Cross-author recalls now show "@author" on the same banner line \u2014 the "team knowledge reuse" value is front-and-center'," \u{1F4CA} 115 MCP tools"],"0.10.90":["\u{1F4CA} **External benchmark corpus v2 \u2014 the proof is now statistically solid**"," \u{1F9EA} Expanded from 8 queries \u2192 61 lessons / 56 queries across 10 real-world engineering domains (k8s, DB, auth, CI, frontend, API, payments, observability, network, Node.js, security, infra)"," \u2694\uFE0F 10 adversarial distractors added \u2014 failure lessons that share the exact same vocabulary as the query, forcing the quality reranker to earn its lift"," \u{1F4C8} Results on the larger corpus: cachly +2.9% Precision@1 vs flat-file, +12.5% vs raw BM25 baseline \u2014 on a harder dataset, not an easy one"," \u{1F4CA} 115 MCP tools"],"0.10.89":["\u26A1 **One-command onboarding \u2014 `autopilot` is now the single canonical setup**"," \u{1F680} Every surface (README, docs, emails, dashboard, blog) now leads with `npx @cachly-dev/mcp-server@latest autopilot` \u2014 one command signs you in, configures every editor, and bootstraps from git",' \u{1F9F9} Retired the split-brain instructions (legacy `@cachly-dev/init` wrapper + the old "three steps") so there\'s exactly one thing to copy-paste'," \u{1F527} Fixed a build-breaking duplicate `export` on buildClaudeMdBlock that failed CI on v0.10.88"," \u{1F522} Version hygiene \u2014 package.json, server.json, lockfile and MCP_VERSION resynced (server.json/lockfile were stuck at 0.10.85)"," \u{1F4CA} 115 MCP tools"],"0.10.88":["\u2705 **Honest setup + tested config writer (v0.10.88)**",' \u{1F512} setup/autopilot now report the truth: if no editor config could be written it exits non-zero with the exact failures instead of falsely claiming "Brain is ready"'," \u{1F4CA} New setup_config_write_failed telemetry \u2014 permission/path failures that block activation are now visible in reporting"," \u{1F9EA} 24 new unit tests for the config writer (buildServerEnv, buildMcpConfig, mergeMcpConfig, buildClaudeMdBlock) \u2014 the merge logic that must never clobber your other MCP servers is now regression-guarded"," \u{1F4CA} 115 MCP tools"],"0.10.87":["\u{1F310} **Multi-editor auth persistence + full activation telemetry (v0.10.87)**"," \u2705 JWT + instance_id now persisted to Cursor (`~/.cursor/mcp.json`) and Windsurf configs on auth \u2014 no more infinite re-auth for non-Claude-Code users",' \u{1F4E1} `device_flow_failed(reason="timeout")` now fires when sign-in window expires \u2014 blind spot in the funnel is gone'," \u{1F4E1} `auto_provision_failed` now fires on network errors too (was only HTTP non-2xx)"," \u{1F4E1} `brain_from_git_failed` fires with error reason when auto-bootstrap throws \u2014 no more empty brain with no explanation",' \u2728 Git bootstrap shows lesson count in session_start: "Brain bootstrapped \u2014 23 lessons loaded" \u2014 the WOW moment'," \u{1F527} API: McpEvent stores brain quality metrics (fixes/features/refactors/total) \u2014 git learning quality now measurable"," \u{1F4CA} 115 MCP tools"],"0.10.86":["\u{1F6E1}\uFE0F **Zero-friction activation \u2014 your Brain self-heals into existence**"," \u{1F527} Auto-provision now runs on *any* tool call, not just at sign-in \u2014 if instance creation ever fails once, the next call recovers it automatically"," \u{1F91D} Parallel tool calls on startup are coalesced into one resolve (no more duplicate-instance races)",' \u{1F4AC} Clearer "instance still starting" message \u2014 leads with "just retry", no manual config needed'," \u{1F4C8} New activation-funnel telemetry: install \u2192 sign-in \u2192 provision, so silent churn is visible"," \u{1F4CA} 115 MCP tools"],"0.10.85":["\u{1F680} **One-command onboarding \u2014 `npx @cachly-dev/mcp-server@latest autopilot`**"," \u26A1 Single command does it all: auth \u2192 instance \u2192 every editor config \u2192 CLAUDE.md \u2192 Brain bootstrap \u2192 health"," \u{1F331} Seeds the 16-lesson starter corpus when git history is empty \u2014 your first smart_recall hits instantly"," \u{1F916} Fully automatic (zero prompts); `setup` remains for interactive, pick-your-editors onboarding"],"0.10.84":["\u{1F916} **M2M & agent-ecosystem reach \u2014 cachly for every caller, human or machine**"," \u{1F511} OAuth2 `client_credentials` grant \u2014 set CACHLY_CLIENT_ID + CACHLY_CLIENT_SECRET for fully headless auth (CI, agents, AI-to-AI)"," \u{1F5C2}\uFE0F `npx ... tool-specs --format=openai|anthropic|langchain` \u2014 export all 121 tools in any framework's dialect"," \u{1F310} `npx ... openapi` \u2014 OpenAPI 3.1 doc (1 POST path per tool) for Assistants / codegen / Postman"," \u{1F9EA} 14 new tests: client_credentials helpers, all four spec dialects, OpenAPI required-body inference"],"0.10.83":["\u{1F9E0} **Brain Viz \u2014 3D graph export**"," \u{1F310} `brain_graph(instance_id)` \u2014 exports the Causal Knowledge Graph as a render-ready {nodes, links} payload"," \u{1F3A8} Schema `cachly.brain_graph/v1`: node kinds (concept/person/file/service) with color groups + size, edges with confidence"," \u{1F5A5}\uFE0F Consumed verbatim by the 3D frontend (react-force-graph-3d / three.js) \u2014 the visual brain map",' \u{1F50E} Filters: `domain`, `min_confidence`, `max_nodes` (with truncation flag), `format="summary"`'," \u{1F9EA} 10 tests: kind detection, dangling-edge pruning, confidence/domain filters, schema contract"," \u{1F4CA} 115 MCP tools"],"0.10.82":["\u{1F4E1} **Telemetry API contracts \u2014 dashboard ingest pipeline prepared**"," \u{1F5C2}\uFE0F `src/telemetry-types.ts` \u2014 canonical event types + resolved event format (TelemetryEventRaw / TelemetryEventResolved)"," \u{1F510} `user_fingerprint` \u2014 non-reversible JWT sub hash, PII-free user clustering for dashboard"," \u{1F4CA} `metrics` block on key events: smart_recall (hit/topic), brain_from_git (fixes/features/total), brain_seed_starter (seeded_count)"," \u{1F6A6} Internal API contract documented: GET /internal/telemetry/stream \u2192 TelemetryEventResolved[]"],"0.10.81":["\u23F1\uFE0F **Onboarding-Bench \u2014 time-to-first-recall, now measured**"," \u{1F4D0} `npm run bench:onboarding` \u2014 cold (empty) vs seeded (starter) first-query hit rate via the real search engine"," \u{1F4CA} Result: first-query hit@1 **0% \u2192 87.5%**, hit@3 **0% \u2192 100%**, MRR **0% \u2192 93.8%**"," \u{1F6E1}\uFE0F CI-defended in `onboarding-bench.test.ts` (cold must answer 0%, seeded thresholds enforced)"," \u{1F4CB} `PLAN-DASHBOARD.md` \u2014 full build spec for the external Team-Knowledge-Reuse dashboard (separate repo)"],"0.10.80":["\u{1F331} **Starter corpus \u2014 first recall in seconds, not sessions**"," \u{1F4DA} `brain_seed_starter(instance_id)` \u2014 seed 16 curated universal lessons (Docker cache, JWT skew, K8s OOM, N+1, cache stampede\u2026)"," \u{1F680} Auto-seeds on first session when git history is empty/shallow \u2014 your first `smart_recall` returns a real hit",' \u{1F6E1}\uFE0F Tagged `source:"starter"`, idempotent, never overrides your own lessons'," \u23F1\uFE0F Directly attacks time-to-first-recall (<2 min goal); stamps `born_at` on seed"," \u{1F9EA} 18 new tests: seeding, idempotency, topic_filter, force, user-lesson protection"," \u{1F4CA} 113 MCP tools"],"0.10.79":["\u{1F310} **Brain Marketplace \u2014 full shareable Brain lifecycle**"," \u{1F4CB} `brain_share_list(instance_id)` \u2014 see all your public shares with lesson counts + share IDs"," \u{1F5D1}\uFE0F `brain_unshare(share_id)` \u2014 revoke a share; link goes dead immediately"," \u{1F50D} `brain_discover(query, topic)` \u2014 search public Brains in the cachly marketplace"," \u{1F4E4} `publish` CLI \u2014 fancy card + share URL; `--public` for discoverable; `--title` custom name"," \u{1F9EA} stress tests: team_expertise_map with 50 contributors, chain import/unshare, discover fallback"," \u{1F4CA} 112 MCP tools"],"0.10.78":["\u{1F310} **Phase 3: Shareable / Public Brains**",' \u{1F4E4} `brain_share(instance_id="...")` \u2014 export a Brain snapshot as a shareable link (public or unlisted)',' \u{1F4E5} `brain_import(instance_id="...", share_id="...")` \u2014 import any public Brain into yours (1-line)'," \u{1F50D} Optional topic_filter, min_confidence, topic_prefix \u2014 precise control over what gets shared/imported"," \u{1F512} dry_run mode on both tools \u2014 preview before committing"," \u{1F9EA} Regression suite added: share handler, buildServerEnv, stdout cleanness"," \u{1F4CA} 109 MCP tools"],"0.10.77":["\u{1FA79} **Frictionless onboarding + first-class self-hosting/BYOK**"," \u{1F680} Editor-launched server now serves all tools even before sign-in \u2014 zero-credential device flow finally triggers on first tool call"," \u{1F512} No more stdout pollution: stdio JSON-RPC stream stays clean when no JWT is set"," \u{1F3E0} `setup --api-url` / `init --api-url` point at a self-hosted backend; URL baked into config only when non-default",' \u{1F9EC} `health` now shows your BYOK embedding provider + accepts cky_ long-lived keys (was a false "invalid token" failure)'],"0.10.76":["\u{1F4CA} **Agent-trace benchmark + editor matrix + setup timer**"," \u{1F4C2} New `agent-traces-corpus.json` \u2014 22 lessons, 15 queries, realistic AI-agent debug patterns"," \u{1F3C6} Benchmark result: **P@1 +66.7%, MRR +9.5% vs flat-file** (adversarial failure-distractors per category)"," \u{1F4CB} README: first-class editor support matrix (Claude Code, Cursor, Windsurf, VSCode, Cline, Continue.dev, Zed)",' \u23F1\uFE0F setup now shows elapsed time + "Brain is ready" banner at the end'],"0.10.75":["\u{1FA79} **Setup hardened \u2014 works from the VSCode plugin & any non-TTY terminal**"," \u{1F50C} `setup` no longer hangs on a non-interactive stdin (VSCode tasks, CI) \u2014 auto-detects + runs in automatic mode"," \u{1F510} Device-flow now uses the API proxy first (the old direct-Keycloak call returned 403) \u2014 sign-in actually completes"," \u{1F310} When auto sign-in is unavailable, the browser opens with a step-by-step API-key guide instead of a silent paste prompt"," \u{1F4CA} Funnel fix: `device_flow_completed` / `device_flow_failed(reason)` now emitted from setup too"],"0.10.73":["\u{1F510} **Team visibility scopes + one-command init + external bench**",' \u{1F195} `team_grant_scope` / `team_scopes` \u2014 scope lessons to a sub-team (group="security"); only members + admins recall them',' \u{1F3F7}\uFE0F `learn_from_attempts(group="...")` \u2014 orthogonal to private; smart_recall enforces it per requester'," \u26A1 `init` is now zero-arg + idempotent (reuses saved creds, only writes what changed, <60s)"," \u{1F4E6} `npm run bench:external` \u2014 prove recall-lift on a third-party-labeled corpus (portable JSON format)"," \u{1F4CA} 107 MCP tools"],"0.10.72":["\u{1F451} **Role model \u2014 admin \xB7 reviewer \xB7 contributor \xB7 viewer (Phase 3)**"," \u{1F195} `team_assign_role` \u2014 establish governance; first call bootstraps, admins manage the rest"," \u{1F195} `team_whoami` \u2014 see your own role and capabilities"," \u{1F195} `team_roster` \u2014 full team role table (\u{1F451}\u{1F6E1}\uFE0F\u270F\uFE0F\u{1F441}\uFE0F)"," \u{1F6E1}\uFE0F `team_confirm` is now role-aware \u2014 admin/reviewer auto-get senior weight; contributor gets peer; no self-promotion"," \u{1F451} Setup CLI now prompts for governance bootstrap (idempotent). 105 MCP tools"],"0.10.71":['\u{1F6E1}\uFE0F **Self-healing auth** \u2014 no more silent "0 recalls because the token quietly died"'," \u267B\uFE0F Near-expiry tokens auto-refresh into a long-lived key while still valid (zero interaction)"," \u{1F501} A rejected (401) call self-heals once and retries before surfacing an error"," \u{1F4E3} If the credential is truly dead, session_start + get_api_status say so plainly + how to fix"],"0.10.70":["\u{1F6F0}\uFE0F **Service/System nodes in the graph (Phase 3)** \u2014 the brain now models running systems",' \u{1F195} `brain_service_map(service="prometheus")` \u2014 who owns it + every failure/fix known',' \u{1F3F7}\uFE0F Tag lessons with `service="..."` (`service_kind="system"` for infra) \u2014 person\u2192operates, file\u2192runs_in edges',` \u{1F6A8} Incident triage: a restarting pod \u2192 instant "who knows this and what's broken before"`," \u{1F4CA} 102 MCP tools"],"0.10.69":["\u{1F4C1} **Personalized context-aware recall (Phase 3)** \u2014 pass `context_files` to `smart_recall`"," \u{1F3AF} Lessons learned on your current files bubble up \u2014 even when the query doesn't name the file"," \u{1F3F7}\uFE0F `\u{1F4C1} context match` badge on every file-boosted result so you know WHY it ranked up"," \u2705 Works alongside keyword, semantic, CKG, and governance signals \u2014 a 6th ranking dimension"],"0.10.68":["\u{1F91D} **Collaboration graph (Phase 3)** \u2014 person\u2194person edges from shared files"," \u{1F465} `brain_who_knows` now shows who the top expert frequently works with",' \u{1F68C} Bus-factor insight: "ask X and Y together \u2014 they solved this on shared files"'," \u{1F6E1}\uFE0F Stability: every network call in the agent hot path is now timeout-bounded"],"0.10.64":["\u{1F4C8} **The three decisive metrics, now measurable**"," \u23F1\uFE0F `brain_metrics()` \u2014 time-to-first-recall, recall-lift, team-knowledge-reuse in one view"," \u{1F465} Cross-author reuse tracked: recall a teammate's lesson \u2192 counted + surfaced inline"," \u{1F6E1}\uFE0F Stability: scans now capped + timed out (a huge keyspace can't hang the agent)"],"0.10.61":["\u{1F3AF} **Phase 3C: 100 MCP tools milestone \u2014 zero-setup knowledge graph**"," \u{1F504} `brain_from_git` now auto-builds Person+File nodes from git history (zero setup!)"," \u{1F50D} `skill_gaps()` \u2014 find domains with unresolved failures, missing attribution"," \u{1F4CA} `brain_coverage()` \u2014 scored 0-100 health report: lessons \xB7 attribution \xB7 file coverage"],"0.10.60":["\u{1F195} **Phase 3B: File map + team overview + visibility**"," \u{1F4C1} `brain_file_map(file_paths=[...])` \u2014 experts + lessons per file before you touch it"," \u{1F5FA}\uFE0F `team_expertise_map()` \u2014 full team skills matrix in one table",' \u{1F512} `visibility: "private"` on `learn_from_attempts` \u2014 private notes never leak to smart_recall'," \u{1F4CA} 98 MCP tools"],"0.10.59":["\u{1F195} **Phase 3A: Org-wide knowledge graph**",' \u{1F465} `brain_who_knows(topic="...")` \u2014 find your team\'s experts on any topic instantly',' \u{1F578}\uFE0F Person + File nodes auto-built from `learn_from_attempts(author="...", file_paths=[...])`'," \u{1F464} Author attribution now shown inline in `smart_recall` results"," \u{1F4CA} 96 MCP tools \xB7 386 tests green"],"0.10.58":["\u{1F9F9} Zero lint warnings \u2014 all unused imports cleaned across every handler","\u2705 Build: 0 errors, 0 warnings \xB7 379 tests green"],"0.10.57":[`\u{1F195} **What's new in v${Re}:**`," \u{1F527} **Critical fix** \u2014 corrected the npm bin/main entry path (`dist/src/index.js`); 0.10.50\u20130.10.52 shipped a broken entry point"," \u{1F527} Version hygiene \u2014 synced package.json, server.json, lockfile, MCP_VERSION; `latest` now points forward again"," \u2705 Accurate tool count (95) across README, server.json, CLI banners"," \u2705 Includes all Phase 2/3 work: quality reranking, Cachly-Bench, hybrid + CKG recall, team_confirm governance"],"0.10.52":[" \u2705 `smart_recall` \u2014 CKG traversal as Layer 3: finds lessons that FIXED causal-graph-similar problems (\u{1F578}\uFE0F causal graph badge)"," \u2705 Bench corpus expanded: governance adversarial pair proves review-boost end-to-end (+22% P@1 headline)"," \u{1F527} Import cleanup: unused symbols removed from brain.ts (no functional change)"," \u{1F4A1} `smart_recall` now shows keyword / semantic / CKG / hybrid match type for every result"],"0.10.51":[" \u2705 `team_confirm` \u2014 human review raises lesson recall ranking (\u{1F6E1}\uFE0F senior / \u2714\uFE0F peer)"," \u2705 Governance-aware recall \u2014 confirmed lessons outrank unreviewed auto-learned entries"],"0.10.50":[" \u2705 `smart_recall` \u2014 unified keyword + semantic hybrid list (one ranked result, not two sections)",' \u2705 `smart_recall` \u2014 "Brain saved you here" banner surfaces time saved inline per proven lesson'," \u2705 Quality reranking \u2014 proven successes outrank symptom-dense failures (+11% Precision@1)"," \u2705 Cachly-Bench \u2014 IR benchmark with CI regression guard (see BENCH.md for the proof)"," \u{1F527} Contradiction resolution now persisted to Redis (90-day TTL)"," \u{1F4A1} Run `smart_recall` to see your Brain's recall quality in action"],"0.10.49":[" \u2705 `brain_from_git` \u2014 auto-seed your Brain from git history in seconds"," \u2705 `brain_predict_failures` \u2014 predict CI/build failures before they happen"," \u2705 VS Code extension \u2014 Brain status bar, ambient learning, CodeLens hints"," \u2705 Team Brain \u2014 share lessons across your whole engineering team"," \u{1F527} Stability \u2014 auto-expiring memory keys, longer provisioning wait, robust recall"]},Mn=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","session_start","session_start_summary","session_end","session_ping","session_handoff","auto_learn_session","brain_who_knows","brain_file_map","team_expertise_map","skill_gaps","brain_coverage","brain_metrics","brain_service_map","brain_collab_pairs","brain_portability","brain_changelog","brain_set_pref","brain_get_pref"]),Hs=Ws("/billing","upgrade"),pt=new Map,mt=new Set,Js=1680*60*60;function qs(ce=new Date){return`cachly:quota:recalls:${ce.toISOString().slice(0,7)}`}async function gt(ce){try{const Z=qs();await ce.incr(Z)===1&&await ce.expire(Z,Js)}catch{}}function yt(ce){return`cachly:stats:drei-ausgaenge:${ce}`}async function wt(ce,Z,Q){try{await ce.hincrby(yt(Z),Q,1)}catch{}}async function _t(ce,Z){const Q=pt.get(ce);if(Q&&Q.expiresAt>Date.now())return Q.gate;try{const de=await Z(`/api/v1/instances/${ce}/memory`),f=de?.recall_limit??-1,t=de?.total_recall_count??0,o={reached:f>0&&t>=f,limit:f,used:t,goodwillMessage:de?.goodwill_message,notice:de?.notice};return pt.set(ce,{gate:o,expiresAt:Date.now()+6e4}),o}catch{return{reached:!1,limit:-1,used:0}}}async function In(ce,Z,Q,de){switch(ce){case"learn_from_attempts":{const{instance_id:f,topic:t,outcome:o,what_worked:w,what_failed:E="",context:d="",severity:a="major",file_paths:$=[],commands:l=[],tags:u=[],depends_on:h=[],author:k="",visibility:T="team",service:i="",service_kind:c="service",group:x="",grund:g="",ersetzt:v="",gilt_ab:M=""}=Z,{what_worked:I,what_failed:e="",context:G=""}=qt({what_worked:w,what_failed:E,context:d}),_=await Q(f),ne=new Date,oe=ne.toISOString(),U=Be(I,ne),A=Be(e,ne),O=Be(G,ne),ee=Le(I,ne)+Le(e,ne)+Le(G,ne),V=Ls({uebergeben:k,umgebung:process.env.CACHLY_AUTHOR,git:Bs(process.env.CACHLY_WORKSPACE??process.cwd())});let Y="";try{Y=Ds(await _.get(`cachly:prefs:${Is}:${f}`))}catch{}const s=Os(V.autor,Y),p=Rs(V);if(T!=="private"&&await jt(_,f))return zt(_,t,{topic:t,outcome:o,what_worked:U,what_failed:A,context:O,severity:a,file_paths:$,commands:l,tags:u,depends_on:h,...s?{author:s}:{},...i?{service:i}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:0,ts:oe,confidence:1,version:3});const m=t.split(":")[0],r=$t[m],n=[];if(r)for(const P of r.required)P==="commands"&&l.length===0&&n.push(`\u{1F4CB} ${r.hint}`);let N=!1,R=0,L,D=[];const B=await _.get(`cachly:lesson:best:${t}`),ie=String(g??"").trim();if(B&&!ie)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
-
`);if(B)try{const P=JSON.parse(B);R=P.recall_count??0,L=P.last_recalled_at,D=P.audit_trail??[],D.push({ts:oe,action:"updated",prev_outcome:P.outcome,grund:ie}),D.length>20&&(D=D.slice(-20)),N=!0;const C=[];if(P.outcome==="success"&&o==="failure"?C.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):P.outcome==="failure"&&o==="success"&&C.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),C.length>0){D[D.length-1].action="contradiction-resolved";try{const J=le(t),F=le(`resolution:${t}`);await ue(_,J,"contradicts",F,!1)}catch{}try{const J=`cachly:contradictions:${t}`,F=P.outcome==="success"&&o==="failure"?"kept-success":"overwrote-failure";await _.rpush(J,JSON.stringify({ts:oe,prev_outcome:P.outcome,new_outcome:o,direction:F})),await _.ltrim(J,-50,-1),await _.expire(J,180*86400)}catch{}C.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else D=[{ts:oe,action:"created"}];const y=[];if(o==="failure"){const P=[],C=_.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((F,W)=>{C.on("data",se=>P.push(...se)),C.on("end",F),C.on("error",W)});const J=t.split(/[:\-_]/).filter(F=>F.length>2);for(const F of P.slice(0,50)){const W=await _.get(F);if(W)try{const se=JSON.parse(W);if(se.outcome!=="success")continue;const re=(se.topic??"").split(/[:\-_]/).filter(ve=>ve.length>2);if(J.filter(ve=>re.includes(ve)).length>=1&&se.topic!==t){y.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${se.topic}\` (success, ${se.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${se.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${se.topic}", ..., severity="critical")\``);break}}catch{}}}for(const P of h){const C=`cachly:dep:${P}`,J=await _.get(C),F=j(J,[]);F.includes(t)||F.push(t),await _.set(C,JSON.stringify(F),"EX",90*86400)}const S={topic:t,outcome:o,what_worked:U,what_failed:A,context:O,severity:a,file_paths:$,commands:l,tags:u,depends_on:h,...s?{author:s}:{},...i?{service:i}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:R,...L?{last_recalled_at:L}:{},...M&&!Number.isNaN(Date.parse(String(M)))?{gilt_ab:new Date(String(M)).toISOString()}:{},ts:oe,verified_at:o==="success"||o==="partial"?oe:void 0,confidence:1,audit_trail:D,version:3},b=String(v??"").trim();let q="",H=null;b===t&&b?q="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":b&&(H=await _.get(`cachly:lesson:best:${b}`),H?S.ersetzt=b:q=`\u26A0\uFE0F Die zu ersetzende Lektion \`${b}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let K="";if(!b)try{const P=(await Ee(_,["cachly:lesson:best:*"],`${t} ${U}`.slice(0,300),5)).filter(C=>C.key.startsWith("cachly:lesson:best:")).map(C=>{const J=j(C.content,{});return{topic:J.topic??C.key.slice(19),what_worked:J.what_worked}});K=Qt(t,U,P)??""}catch{}if(o==="failure")try{const C=(await _.lrange(ct(f),0,199)).map(W=>j(W,{ts:"",frage:"",geliefert:[]})).filter(W=>W.ts!==""),J=(await Ee(_,["cachly:lesson:best:*"],`${t} ${A||U}`.slice(0,300),5)).filter(W=>W.key.startsWith("cachly:lesson:best:")).map(W=>{const se=j(W.content,{});return{topic:se.topic??W.key.slice(19),what_worked:se.what_worked}}),F=ns(t,String(A||""),C,J);await _.hincrby(lt(f),F,1)}catch{}const te=as([U,A,d].filter(Boolean).join(" ").slice(0,2e3));te&&(S.entscheidung=te);const X=JSON.stringify(S);_.set(`cachly:stats:born_at:${f}`,oe,"EX",365*86400,"NX").catch(()=>{});const z=`cachly:lessons:${t}`;await _.rpush(z,X),await _.ltrim(z,-100,-1),await _.expire(z,es*86400);let ae=!1;if(o==="success"||o==="partial"?(await _.set(`cachly:lesson:best:${t}`,X),ae=!0):B||(await _.set(`cachly:lesson:best:${t}`,X),ae=!0),H&&ae)try{const P=JSON.parse(H);P.ersetzt_durch=t,P.gilt_bis=oe,P.ersetzt_am=oe,await _.set(`cachly:lesson:best:${b}`,JSON.stringify(P))}catch{}ae&&Ft(),ae&&Me()&&(async()=>{const P=j(X,{});try{const C=await be(at(P),{geduld:"lang"});C?.length&&await _.set(`${nt}${t}`,Ke(C))}catch(C){await _.sadd(xe,t).catch(()=>{}),await Ae(_,je,`Volltext-Vektor nicht geschrieben (${We}): ${Pe(C)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const C=await be(Ut(t),{geduld:"lang"});C?.length&&await _.set(`${ot}${t}`,Ke(C))}catch(C){await Ae(_,je,`Namens-Vektor nicht geschrieben (${We}): ${Pe(C)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await Vt(_,t,P,C=>be(C,{geduld:"lang"}))}catch(C){await Ae(_,je,`Eingaenge nicht geschrieben (${We}): ${Pe(C)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{const C=await _.spop(xe,3),J=Array.isArray(C)?C:C?[C]:[];for(const F of J){if(F===t){await _.sadd(xe,F);continue}const W=await _.get(`cachly:lesson:best:${F}`);if(!W)continue;const se=j(W,{});try{const re=await be(at(se),{geduld:"lang"});re?.length?await _.set(`${nt}${F}`,Ke(re)):await _.sadd(xe,F)}catch{await _.sadd(xe,F)}}}catch{}})();try{const P="cachly:session:decision-log",C=JSON.stringify({ts:oe,topic:t,outcome:o,what_worked:U.slice(0,120)});await _.rpush(P,C),await _.ltrim(P,-50,-1)}catch{}let me=null;try{const P=le(t),C=t.split(":")[0]??"unknown";await ke(_,P,C,C);for(const F of u){const W=le(`tag:${F}`);await ke(_,W,"tag","tag"),await ue(_,P,"co-occurs",W,o==="success",o==="partial")}for(const F of h){const W=le(F);await ue(_,P,"requires",W,!0)}if((C==="fix"||C==="debug")&&(o==="success"||o==="partial")){const F=A||O||"",W=F?De(F):null;if(W){const se=le(`problem:${W}`);await ke(_,se,"problem","problem"),await ue(_,P,"fixes",se,o==="success",o==="partial")}}if(o==="failure"&&(A||U)){const W=De(A||U);if(W){const se=le(`cause:${W}`);await ke(_,se,"cause","cause"),await ue(_,P,"causes",se,!1)}}if(o==="failure"){const F=await _.smembers(`cachly:ckg:idx:from:${P}`);for(const W of F){const se=await _.get(W);if(!se)continue;const re=j(se,null);if(re&&re.edgeType==="fixes"&&re.confidence>.7&&re.trials>=3){me=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${re.confidence.toFixed(2)}, n=${re.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${P}")\` to review.`;const he=`cachly:ckg:conflict:${P}`;await _.set(he,JSON.stringify({topic:t,concept_id:P,detected_at:new Date().toISOString(),fix_confidence:re.confidence,fix_trials:re.trials,failure_outcome:o,reported_by:s||"unknown",what_failed:A||"",resolved:!1}),"EX",3600*24*90)}}}if(o==="success"&&(C==="fix"||C==="debug")){const F=await _.smembers(`cachly:ckg:idx:from:${P}`);for(const W of F.slice(0,10)){const se=await _.get(W);if(!se)continue;const re=j(se,null);if(!re||re.edgeType!=="fixes")continue;const he=await _.smembers(`cachly:ckg:idx:from:${re.to}`);for(const ve of he.slice(0,5)){const Je=await _.get(ve);if(!Je)continue;const fe=j(Je,null);fe&&fe.edgeType==="co-occurs"&&(fe.successes=(fe.successes||0)+.1,fe.trials=(fe.trials||0)+.1,fe.confidence=(fe.successes+1)/(fe.trials+2),fe.last_updated=new Date().toISOString(),await _.set(ve,JSON.stringify(fe)))}}}if(Math.random()<.01){const F=Date.now()-7776e6,W=await _.smembers(`cachly:ckg:idx:from:${P}`);for(const se of W){const re=await _.get(se);if(!re)continue;const he=j(re,null);he&&he.trials<3&&he.last_updated&&new Date(he.last_updated).getTime()<F&&(he.confidence=he.confidence*.9,he.last_updated=new Date().toISOString(),await _.set(se,JSON.stringify(he)))}}}catch{}if(s){_.set(`cachly:agents:active:${s}`,JSON.stringify({author:s,last_topic:t,last_outcome:o,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const P=t.split(":")[0]??"unknown",C=await St(_,ft(s),P),J=le(t);await ue(_,C,"authored",J,o==="success",o==="partial");for(const F of $.slice(0,8)){const W=await Ye(_,F);await ue(_,C,"touched",W,!0),await Ct(_,W,C)}}catch{}}if(i&&typeof i=="string"&&i.trim())try{const P=t.split(":")[0]??"unknown",C=c==="system"?"system":"service",J=await xt(_,i.trim(),P,C),F=le(t);if(await ue(_,F,"affects",J,o==="success",o==="partial"),s){const W=`person:${le(ft(s))}`;await ue(_,W,"operates",J,!0)}for(const W of $.slice(0,8)){const se=`file:${le(W)}`;await ue(_,se,"runs_in",J,!0)}}catch{}if(s&&(o==="success"||o==="partial")){const P={topic:t,outcome:o,what_worked:U,what_failed:A??"",severity:a,author:s,file_paths:$,commands:l,tags:[...new Set([...u,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},C=`cachly:lessons:${t}`;_.rpush(C,JSON.stringify(P)).catch(()=>{})}return[`${o==="success"?"\u2705":o==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${N?"updated":"stored"}:** \`${t}\` (${o}) ${a==="critical"?"\u{1F534}":a==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${a}`,me??"","",`**What worked:** ${U}`,A?`**What failed:** ${A}`:"",O?`**Context:** ${O}`:"",$.length>0?`**Files:** ${$.map(P=>`\`${P}\``).join(", ")}`:"",l.length>0?`**Commands:** ${l.map(P=>`\`${P}\``).join(", ")}`:"",u.length>0?`**Tags:** ${u.map(P=>`#${P}`).join(" ")}`:"","",N?`\u267B\uFE0F Updated (recall count: ${R} \xB7 audit entries: ${D.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,s&&(o==="success"||o==="partial")?`\u{1F465} Auto-shared with team (by _${s}_${V.quelle!=="uebergeben"?` \xB7 aus ${V.quelle}`:""}) \u2014 visible in \`team_recall\``:"",p??"",h.length>0?`\u{1F517} Depends on: ${h.map(P=>`\`${P}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",K,H&&ae?`\u21B7 Ersetzt \`${b}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin.`:q,...n,...y,ee>0?`\u{1F5D3}\uFE0F ${ee} relative Zeitangabe${ee===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(ne.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",js(U)??""].filter(P=>P!=="").join(`
|
|
3
|
-
`)}case"recall_feedback":{const{instance_id:f}=
|
|
4
|
-
`);const
|
|
5
|
-
`)}case"recall_best_solution":{const{instance_id:f,topic:t,author:o}=
|
|
6
|
-
`):"",
|
|
7
|
-
`)}const d=[],a=
|
|
1
|
+
import{execSync as Ye}from"node:child_process";import{createRequire as Ze}from"node:module";import{calculateConfidence as Ne,confidenceBadge as St,STRUCTURED_TEMPLATES as Ct,CONFIDENCE_WARN_VALUE as Xe,CONFIDENCE_STALE_VALUE as xt,CONFIDENCE_WARN_DAYS as Tt}from"../confidence.js";import{ckgSlug as le,extractProblemConcept as Le,ckgUpsertNode as ke,ckgUpdateEdge as ue,ckgUpsertPersonNode as Nt,ckgUpsertFileNode as Qe,ckgRecordCollaboration as Et,ckgUpsertServiceNode as At}from"../ckg.js";import{safeJsonParse as F,scanKeys as ge,leseOderNull as $e,darfHeraus as Se}from"../utils.js";import{ersparteMinuten as et,istStarterLektion as Ee,zaehltAlsErsparnis as tt}from"../wertbeitrag.js";import{lessonPreviewLines as Ce,trimTo as It}from"../lesson-preview.js";import{normalisiereZeit as Oe,zaehleZeitangaben as Pe}from"../zeit-normalisieren.js";import{abstentionSatz as Mt,alterssatzFuerBelegte as Rt,beurteileTreffer as Dt,istBelegt as Bt}from"../abstention.js";import{meldeEinmal as je,meldeUndVermerke as Ae,fehlerText as ze,OHNE_VEKTOREN as Lt,OHNE_DIENST as Ot,OHNE_FRAGEVEKTOR as Pt,SINNPFAD_ABBRUCH as jt,OHNE_SCHREIBVEKTOR as Fe}from"../aussetzer.js";import{versuchStart as zt,neueKennung as Ft,wendeZuteilungAn as Wt,schliesseVersuchAb as Kt}from"../versuch.js";function st(ce,X,Q){if(ce.includes("lesson:best:")){const f=F(X,{});if(f&&typeof f=="object"&&(f.what_worked||f.what_failed||f.commands?.length))return Ce(f,{maxChars:Q,indent:" "})}const de=It(X,Q);return de?[de]:[]}import{getRole as We,ROLE_BADGE as Gt,getScopes as nt,lessonVisibleToScope as ot,reviewModeEnabled as Ht,storeLessonProposal as Jt}from"./team.js";import{keywordSearch as Ie,wortindexEntwerten as qt,tokenize as Ke,splitMultiQuery as Ut,levenshtein as Vt,indexVocab as at}from"../search.js";import{rerankByQuality as Yt,qualityMultiplier as Zt,extractLessonQuality as Xt}from"../rerank.js";import{computeEmbedding as ye,hasEmbedProvider as Me,EMBED_PROVIDER as xe}from"../embeddings.js";import{repariereFelder as Qt}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as it,NAME_VEKTOR_PRAEFIX as rt,ZWEIT_VEKTOR_PRAEFIX as ct,packe as Re,textFuerVektor as Ge,textFuerNamensVektor as es,Vektorbestand as He}from"../bedeutung.js";import{schreibeEingaenge as ts,Eingangsbestand as ss}from"../eingaenge.js";import{Seltenheitsbestand as ns}from"../seltenheitsbestand.js";import{spurLegen as os}from"../spuren.js";import{schlageErsetzungVor as as}from"../ersetzung-vorschlag.js";const Te="cachly:vek:nachtrag",is=365;import{etikettenFuer as rs,lieferJournalSchluessel as lt,JOURNAL_DECKEL as cs}from"../etiketten.js";import{klassifiziereFehlschlag as ls,suchProtokollSchluessel as ut,trichterSchluessel as ht,SUCH_DECKEL as us}from"../recall-trichter.js";import{leiteEntscheidungAb as hs,entscheidungsZeile as dt}from"../entscheidung-ableiten.js";import{bewerteTopf as ds,spreizeImTopf as ft,reichereAn as fs,inhaltsWoerter as pt,grobStamm as ps,GEWICHTE as ms,knapperSiegSatz as gs}from"../rangfolge.js";import{pruefeWirkung as ys,werteAus as ws,lehrwert as _s,leiteAb as bs}from"../wirkungsspur.js";import{SINN_TOPF as $s,EINGANG_SCHWELLE as vs,EINGANG_SORTIER_GEWICHT as ks,ZWEIT_MODELL as mt,ZWEIT_GEWICHT as Ss,ZWEIT_MINDESTDECKUNG as Cs}from"../rangfolge-stellschrauben.js";const we=new He,Je=new He(6e4,rt),qe=new He(6e4,ct),Ue=new ss,De=new ns,xs=$s,Ts=vs,Ns=ks;import{upgradeNudge as Es}from"../upgrade-nudge.js";import{recallTiefe as gt,TIEFE_VOLL as As,TIEFE_VOLL_MEHRTHEMIG as Is}from"../recall-tiefe.js";import{nutzungInWorten as Ms,nutzungsSchluessel as Rs,verdichte as Ds}from"../werkzeug-nutzung.js";import{inWorten as Bs,lieferBild as Ls,lieferSchluessel as Os,trefferSchluessel as Ps}from"../geliefert.js";import{COAUTHOR_PREF_KEY as js,autorHinweis as zs,coautorAus as Fs,echterGitLeser as Ws,ermittleAutor as Ks,mitCoautor as Gs,nurMensch as yt}from"../autor.js";import{TOOLS as Hs}from"../tools.js";import{vorspannHinweis as Js}from"../vorspann.js";import{autorAbzeichen as qs,fremdanteil as Us}from"../autor-abzeichen.js";import{cachlyUrl as Vs}from"../cachly-url.js";const Be=(()=>{try{const ce=Ze(import.meta.url);for(const X of["../../../package.json","../../package.json"])try{const Q=ce(X);if(Q.name==="@cachly-dev/mcp-server"&&Q.version)return Q.version}catch{}}catch{}return"0.10.100"})(),Ys=()=>{try{return Ze(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Zs={"0.10.119":["\u{1F50D} **Explainable briefings \u2014 provenance in every warning**"," \u{1F4CE} `/briefing` warnings now carry `outcome`, `author`, `learned_at` and `matched_on` (the context tokens that triggered the warning) \u2014 editors can show WHY a fix hint fired, not just what it claims.",' \u{1F9F0} VS Code 0.12.0 uses this: severity + confidence in the toast, full lesson card with provenance, "Not helpful" per-file suppression, reviewable CLS auto-learns.'," \u{1F9F9} CI docs now describe exactly what ships: scan mode uses the REST `/scan` endpoint, the GitLab template covers learn/scan/confirm."],"0.10.115":["\u{1F527} **`brain_get_pref` + `brain_set_pref` \u2014 persistent Brain preferences**"," \u{1F4D6} `brain_get_pref` reads back any stored preference (omit key to list all)."," \u270F\uFE0F `brain_set_pref` saves a preference to Redis \u2014 survives restarts, scoped per Brain instance.",' \u{1F4A1} Known key: `auto_changelog` \u2014 set to "false" to silence the new-lessons digest at session_start.'," \u{1F4CA} 140 MCP tools"],"0.10.114":["\u{1F4CB} **`brain_changelog` \u2014 weekly knowledge digest in one call**"," \u{1F4C5} Generates a grouped Markdown changelog of lessons learned in the last N days."," \u{1F465} Grouped by topic category, annotated with author, recall count, and confidence \u2014 paste directly into standup or Slack."," \u2699\uFE0F Params: `days` (default 7), `max_lessons` (default 30), `include_failures` (default true)."," \u{1F4CA} 138 MCP tools"],"0.10.113":["\u{1F4C8} **Week-over-week savings trend in `cache_stats`**"," \u{1F4C5} `cache_stats` now shows **7-day hits** + **WoW trend %** (e.g. `+23.0% vs prev week`) so ROI momentum is visible, not just the cumulative total."," \u2B07\uFE0F Goes red (\u{1F4C9}) on drops, green (\u{1F4C8}) on growth \u2014 first week always shows +100% (new)."," \u{1F527} Backed by new `CountHitsInWindow` repo method + `hits_last_7d`, `hits_prev_7d`, `week_over_week_pct` fields in `SavingsEstimate`."," \u{1F4CA} 137 MCP tools"],"0.10.112":["\u2699\uFE0F **Configurable cost_per_call_usd \u2014 accurate ROI for any LLM**"," \u{1F4A1} New `set_cost_per_call` tool: set your real per-call cost (claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001) so savings estimates in `cache_stats` reflect your actual bill."," \u{1F527} New API: `PUT /api/v1/instances/:id/cost-per-call` \u2014 persisted per instance, used by `cache_stats`, org savings, and SSE analytics stream."," \u{1F4CA} 137 MCP tools"],"0.10.111":["\u{1F3E2} **Org-wide ROI + GitLab CI \u2014 the CFO number, aggregated**"," \u{1F4B0} `cache_org_stats` now shows **org-wide Tokenmaxxing ROI**: total savings summed across every instance in your org, monthly projection, top-5 instances by savings. One number for the whole team."," \u{1F50C} Backed by new API endpoint `GET /api/v1/orgs/:id/savings` (org members only)"," \u{1F98A} GitLab CI integration: `brain-from-ci-gitlab.yml` \u2014 two `.post` jobs (on_success/on_failure), same helper script, pipeline never fails because of Brain push"," \u{1F6E0}\uFE0F GitHub Action template fixed: `secrets.*` in job-level `if` is invalid \u2014 guard removed (helper script skips cleanly on missing secrets)"," \u{1F4CA} 136 MCP tools"],"0.10.110":["\u{1F3E2} **Zero friction: ROI-Projektor, Org-Shared-Cache, CI ready-to-paste**"," \u{1F4C8} `cache_stats` \u2014 zero-hit projection calculator: shows expected monthly savings for 5/10/20-dev teams before a single cache hit lands. ROI visible from day 1."," \u{1F3E2} New `cache_org_stats` \u2014 shared org-level cache stats across multiple instances. Convention-based (`org:{id}:sem`), zero API changes needed."," \u{1F517} `cache_set`/`cache_get` now accept optional `org_id` \u2014 write to personal + org namespace, fall back to org on miss. Fully backwards-compatible."," \u{1F4CB} Copy-paste CI integration: `brain-from-ci-action.yml` \u2192 Brain self-calibrates confidence on every GitHub Actions run. No config beyond two repo secrets."," \u{1F4CA} 136 MCP tools"],"0.10.109":["\u{1F4B0} **Tokenmaxxing ROI + Closed-loop CI learning**"," \u{1F4CA} `cache_stats` now shows a **Tokenmaxxing ROI** section \u2014 total tokens saved, monthly cost projection, and top 3 most-cached prompts. Finally a number you can show the CFO."," \u{1F504} New `brain_from_ci` \u2014 bulk-ingest CI history into the Brain (red\u2192green = learned fix, green\u2192red = CKG causal edge). The brain_from_git equivalent for CI. Bootstrap the Brain from your CI logs in one call."," \u{1F4CA} 134 MCP tools"],"0.10.108":["\u{1F9E0} **Focused briefing + trustworthy autopilot**"," \u{1F3AF} New `session_start_summary` \u2014 top-N focused briefing by topic. Scores lessons by relevance \xD7 confidence + recall_count + severity + recency. Use it for a quick pre-brief without loading the full Brain.",' \u{1F91D} Autopilot template now explains the data flow upfront ("your own Brain, EU-hosted, no third parties") \u2014 no more friction with cautious AI assistants during onboarding'," \u{1F4CA} 132 MCP tools"],"0.10.107":["\u{1F3AF} **Recall@3 gap closed \u2014 the moat proof got sharper (the head-to-head that matters)**"," \u{1F50D} External-corpus Recall@3 **82.1% \u2192 98.2%** \xB7 Precision@1 **80.4%** \xB7 MRR **89.0%** \u2014 now ahead of flat-file memory on every metric"," \u{1F9EC} Root-cause fix: documents are no longer indexed with cross-lingual synonyms (the symmetric-expansion bug inflated any doc containing a common word ~28\xD7, burying topic-specific lessons). Queries still expand \u2014 a \u65E5\u672C\u8A9E query still finds English lessons."," \u2696\uFE0F Reranker now compresses BM25 with score^0.3 before applying lesson quality, so a proven success can overtake a text-similar failed attempt even when the distractor scores 5\u20136\xD7 higher in raw BM25"," \u{1F6E1}\uFE0F CI bench gate widened to both home + external corpora with committed floors (`npm run bench:gate`) \u2014 recall quality can never silently regress again"," \u{1F4CA} 121 MCP tools"],"0.10.98":['\u{1F310} **Model-Neutrality as Feature (W9) \u2014 "Bring your own model, keep your brain."**'," \u{1F50C} New `brain_portability()` \u2014 shows your Brain ID, all compatible MCP clients, and ready-to-paste config snippets for each; proves the same Brain works in Claude, Cursor, Copilot, Windsurf, Cline, Zed and more"," \u{1F9E0} Your lessons, crystals, and predictions are model-agnostic \u2014 no vendor lock-in at the memory layer",' \u{1F4D6} New docs: cachly.dev/docs/model-neutral \u2014 "Same Brain, Any Model" guide with live config examples'," \u{1F4CA} 121 MCP tools (new: `brain_portability`)"],"0.10.97":['\u{1F4A0} **Team Crystallize (W8) \u2014 the team-wide, causal counter to per-user "Dreaming"**'," \u{1F9EC} New `team_crystallize()` \u2014 surfaces fixes that 2+ teammates *independently converged on*, the one thing a single-user memory structurally can't build",' \u{1F9E9} Cross-person clustering: groups structurally similar problems across people & namespaces (e.g. "pool exhaustion" solved the same way in payments, auth & db)',' \u{1F465} Each pattern names who converged \u2014 instant "ask @alice and @bob, they both hit this"'," \u{1F48E} Shows up in `crystal_view` alongside your per-brain crystal"," \u{1F4CA} 120 MCP tools (new: `team_crystallize`)"],"0.10.96":["\u{1F510} **Roles & Team-Scopes now ENFORCED (W6) \u2014 the enterprise governance layer**"," \u{1F6E1}\uFE0F `team_confirm` is now reviewer-gated, `team_learn` blocks viewers (recall-only) \u2014 roles stop being cosmetic the moment an admin is assigned"," \u{1F4DC} New `team_audit` tool \u2014 immutable, admin-only trail of every role change & lesson confirmation, for compliance & security reviews"," \u{1F513} Zero impact on open teams: governance activates only once you bootstrap an admin; before that everything works exactly as before"," \u{1F4CA} 119 MCP tools (new: `team_audit`)"],"0.10.95":["\u{1F9E0} **Domain Brain Marketplace (W10) \u2014 bootstrap your Brain with curated community knowledge**"," \u{1F6D2} `brain_marketplace()` \u2014 browse installable packs of high-trust lessons by domain: \u2638\uFE0F Kubernetes, \u{1F510} Auth, \u{1F5C4}\uFE0F Database, \u269B\uFE0F React, \u{1F4B3} Payments & more",' \u{1F4E6} `brain_install(slug="k8s")` \u2014 merges a domain\'s verified lessons into your Brain; live in `smart_recall` instantly, even offline',' \u{1F6E1}\uFE0F Idempotent + non-destructive: installed lessons are tagged `source:"marketplace:<slug>"` and NEVER override your own'," \u{1F50C} New gRPC `Subscribe` RPC \u2014 agents get new lessons streamed live the moment they're learned (completes the M2M loop with `Learn`)"," \u{1F4CA} 118 MCP tools (new: `brain_marketplace`, `brain_install`)"],"0.10.94":['\u{1F91D} **Person\u2194Person Collaboration Graph (W5) \u2014 "Frag X und Y, die haben das zusammen gel\xF6st"**'," \u{1F578}\uFE0F New `brain_collab_pairs()` tool: shows every contributor pair who've touched the same files or recalled each other's lessons \u2014 ideal for onboarding and bus-factor analysis"," \u{1F4E1} `smart_recall` now wires CKG `collaborates` edges live when cross-author reuse fires \u2014 collaboration graph grows with every team recall"," \u26A0\uFE0F Bus-factor section: flags solo contributors whose knowledge no teammate has yet recalled"," \u{1F4CA} 116 MCP tools (new: `brain_collab_pairs`)"],"0.10.93":['\u{1F5FA}\uFE0F **`brain_plan` \u2014 your Brain goes from "what did we learn?" to "what should I do?"**',` \u{1F9ED} Give it a task you're about to start ("upgrade Postgres 14\u219216") and it returns an ordered, grounded action plan: ranked failure modes to avoid, proven fix steps (dependency-aware, with commands), and a pre-flight checklist \u2014 all from your own lessons`,' \u{1F52C} Generative layer on the CKG: where `brain_predict` answers "what might fail?", `brain_plan` answers "what, in what order?"'," \u{1F4CA} 115 MCP tools (new: `brain_plan`)"],"0.10.92":["\u{1F44B} **Welcome-back digest \u2014 re-entry after a week away now leads with what changed**"," \u{1F331} `session_start` detects a gap \u2265 7 days and surfaces how many lessons your Brain gained while you were gone (git, CI & teammates kept it learning), with the freshest topics"," \u{1F9E0} Zero extra latency \u2014 the digest is computed from data session_start already loads"," \u{1F50C} New gRPC `Learn` RPC (M2M write path) \u2014 agents & CI can now teach the Brain directly, byte-compatible with the MCP lesson format"," \u{1F4CA} 115 MCP tools"],"0.10.91":["\u{1F550} **Lesson-anchored time attribution \u2014 every recall shows when it was learned and how much it saves**",` \u{1F4A1} "Brain saved you" banner now includes: when the lesson was learned (e.g. "12 May"), estimated original debug cost by severity (critical=2h, major=1h, minor=20min), and team attribution when a teammate's lesson fires`,' \u{1F4C5} Origin date formatted as "12 May" (same year) or "12 May 2024" (different year) \u2014 no clutter',' \u{1F465} Cross-author recalls now show "@author" on the same banner line \u2014 the "team knowledge reuse" value is front-and-center'," \u{1F4CA} 115 MCP tools"],"0.10.90":["\u{1F4CA} **External benchmark corpus v2 \u2014 the proof is now statistically solid**"," \u{1F9EA} Expanded from 8 queries \u2192 61 lessons / 56 queries across 10 real-world engineering domains (k8s, DB, auth, CI, frontend, API, payments, observability, network, Node.js, security, infra)"," \u2694\uFE0F 10 adversarial distractors added \u2014 failure lessons that share the exact same vocabulary as the query, forcing the quality reranker to earn its lift"," \u{1F4C8} Results on the larger corpus: cachly +2.9% Precision@1 vs flat-file, +12.5% vs raw BM25 baseline \u2014 on a harder dataset, not an easy one"," \u{1F4CA} 115 MCP tools"],"0.10.89":["\u26A1 **One-command onboarding \u2014 `autopilot` is now the single canonical setup**"," \u{1F680} Every surface (README, docs, emails, dashboard, blog) now leads with `npx @cachly-dev/mcp-server@latest autopilot` \u2014 one command signs you in, configures every editor, and bootstraps from git",' \u{1F9F9} Retired the split-brain instructions (legacy `@cachly-dev/init` wrapper + the old "three steps") so there\'s exactly one thing to copy-paste'," \u{1F527} Fixed a build-breaking duplicate `export` on buildClaudeMdBlock that failed CI on v0.10.88"," \u{1F522} Version hygiene \u2014 package.json, server.json, lockfile and MCP_VERSION resynced (server.json/lockfile were stuck at 0.10.85)"," \u{1F4CA} 115 MCP tools"],"0.10.88":["\u2705 **Honest setup + tested config writer (v0.10.88)**",' \u{1F512} setup/autopilot now report the truth: if no editor config could be written it exits non-zero with the exact failures instead of falsely claiming "Brain is ready"'," \u{1F4CA} New setup_config_write_failed telemetry \u2014 permission/path failures that block activation are now visible in reporting"," \u{1F9EA} 24 new unit tests for the config writer (buildServerEnv, buildMcpConfig, mergeMcpConfig, buildClaudeMdBlock) \u2014 the merge logic that must never clobber your other MCP servers is now regression-guarded"," \u{1F4CA} 115 MCP tools"],"0.10.87":["\u{1F310} **Multi-editor auth persistence + full activation telemetry (v0.10.87)**"," \u2705 JWT + instance_id now persisted to Cursor (`~/.cursor/mcp.json`) and Windsurf configs on auth \u2014 no more infinite re-auth for non-Claude-Code users",' \u{1F4E1} `device_flow_failed(reason="timeout")` now fires when sign-in window expires \u2014 blind spot in the funnel is gone'," \u{1F4E1} `auto_provision_failed` now fires on network errors too (was only HTTP non-2xx)"," \u{1F4E1} `brain_from_git_failed` fires with error reason when auto-bootstrap throws \u2014 no more empty brain with no explanation",' \u2728 Git bootstrap shows lesson count in session_start: "Brain bootstrapped \u2014 23 lessons loaded" \u2014 the WOW moment'," \u{1F527} API: McpEvent stores brain quality metrics (fixes/features/refactors/total) \u2014 git learning quality now measurable"," \u{1F4CA} 115 MCP tools"],"0.10.86":["\u{1F6E1}\uFE0F **Zero-friction activation \u2014 your Brain self-heals into existence**"," \u{1F527} Auto-provision now runs on *any* tool call, not just at sign-in \u2014 if instance creation ever fails once, the next call recovers it automatically"," \u{1F91D} Parallel tool calls on startup are coalesced into one resolve (no more duplicate-instance races)",' \u{1F4AC} Clearer "instance still starting" message \u2014 leads with "just retry", no manual config needed'," \u{1F4C8} New activation-funnel telemetry: install \u2192 sign-in \u2192 provision, so silent churn is visible"," \u{1F4CA} 115 MCP tools"],"0.10.85":["\u{1F680} **One-command onboarding \u2014 `npx @cachly-dev/mcp-server@latest autopilot`**"," \u26A1 Single command does it all: auth \u2192 instance \u2192 every editor config \u2192 CLAUDE.md \u2192 Brain bootstrap \u2192 health"," \u{1F331} Seeds the 16-lesson starter corpus when git history is empty \u2014 your first smart_recall hits instantly"," \u{1F916} Fully automatic (zero prompts); `setup` remains for interactive, pick-your-editors onboarding"],"0.10.84":["\u{1F916} **M2M & agent-ecosystem reach \u2014 cachly for every caller, human or machine**"," \u{1F511} OAuth2 `client_credentials` grant \u2014 set CACHLY_CLIENT_ID + CACHLY_CLIENT_SECRET for fully headless auth (CI, agents, AI-to-AI)"," \u{1F5C2}\uFE0F `npx ... tool-specs --format=openai|anthropic|langchain` \u2014 export all 121 tools in any framework's dialect"," \u{1F310} `npx ... openapi` \u2014 OpenAPI 3.1 doc (1 POST path per tool) for Assistants / codegen / Postman"," \u{1F9EA} 14 new tests: client_credentials helpers, all four spec dialects, OpenAPI required-body inference"],"0.10.83":["\u{1F9E0} **Brain Viz \u2014 3D graph export**"," \u{1F310} `brain_graph(instance_id)` \u2014 exports the Causal Knowledge Graph as a render-ready {nodes, links} payload"," \u{1F3A8} Schema `cachly.brain_graph/v1`: node kinds (concept/person/file/service) with color groups + size, edges with confidence"," \u{1F5A5}\uFE0F Consumed verbatim by the 3D frontend (react-force-graph-3d / three.js) \u2014 the visual brain map",' \u{1F50E} Filters: `domain`, `min_confidence`, `max_nodes` (with truncation flag), `format="summary"`'," \u{1F9EA} 10 tests: kind detection, dangling-edge pruning, confidence/domain filters, schema contract"," \u{1F4CA} 115 MCP tools"],"0.10.82":["\u{1F4E1} **Telemetry API contracts \u2014 dashboard ingest pipeline prepared**"," \u{1F5C2}\uFE0F `src/telemetry-types.ts` \u2014 canonical event types + resolved event format (TelemetryEventRaw / TelemetryEventResolved)"," \u{1F510} `user_fingerprint` \u2014 non-reversible JWT sub hash, PII-free user clustering for dashboard"," \u{1F4CA} `metrics` block on key events: smart_recall (hit/topic), brain_from_git (fixes/features/total), brain_seed_starter (seeded_count)"," \u{1F6A6} Internal API contract documented: GET /internal/telemetry/stream \u2192 TelemetryEventResolved[]"],"0.10.81":["\u23F1\uFE0F **Onboarding-Bench \u2014 time-to-first-recall, now measured**"," \u{1F4D0} `npm run bench:onboarding` \u2014 cold (empty) vs seeded (starter) first-query hit rate via the real search engine"," \u{1F4CA} Result: first-query hit@1 **0% \u2192 87.5%**, hit@3 **0% \u2192 100%**, MRR **0% \u2192 93.8%**"," \u{1F6E1}\uFE0F CI-defended in `onboarding-bench.test.ts` (cold must answer 0%, seeded thresholds enforced)"," \u{1F4CB} `PLAN-DASHBOARD.md` \u2014 full build spec for the external Team-Knowledge-Reuse dashboard (separate repo)"],"0.10.80":["\u{1F331} **Starter corpus \u2014 first recall in seconds, not sessions**"," \u{1F4DA} `brain_seed_starter(instance_id)` \u2014 seed 16 curated universal lessons (Docker cache, JWT skew, K8s OOM, N+1, cache stampede\u2026)"," \u{1F680} Auto-seeds on first session when git history is empty/shallow \u2014 your first `smart_recall` returns a real hit",' \u{1F6E1}\uFE0F Tagged `source:"starter"`, idempotent, never overrides your own lessons'," \u23F1\uFE0F Directly attacks time-to-first-recall (<2 min goal); stamps `born_at` on seed"," \u{1F9EA} 18 new tests: seeding, idempotency, topic_filter, force, user-lesson protection"," \u{1F4CA} 113 MCP tools"],"0.10.79":["\u{1F310} **Brain Marketplace \u2014 full shareable Brain lifecycle**"," \u{1F4CB} `brain_share_list(instance_id)` \u2014 see all your public shares with lesson counts + share IDs"," \u{1F5D1}\uFE0F `brain_unshare(share_id)` \u2014 revoke a share; link goes dead immediately"," \u{1F50D} `brain_discover(query, topic)` \u2014 search public Brains in the cachly marketplace"," \u{1F4E4} `publish` CLI \u2014 fancy card + share URL; `--public` for discoverable; `--title` custom name"," \u{1F9EA} stress tests: team_expertise_map with 50 contributors, chain import/unshare, discover fallback"," \u{1F4CA} 112 MCP tools"],"0.10.78":["\u{1F310} **Phase 3: Shareable / Public Brains**",' \u{1F4E4} `brain_share(instance_id="...")` \u2014 export a Brain snapshot as a shareable link (public or unlisted)',' \u{1F4E5} `brain_import(instance_id="...", share_id="...")` \u2014 import any public Brain into yours (1-line)'," \u{1F50D} Optional topic_filter, min_confidence, topic_prefix \u2014 precise control over what gets shared/imported"," \u{1F512} dry_run mode on both tools \u2014 preview before committing"," \u{1F9EA} Regression suite added: share handler, buildServerEnv, stdout cleanness"," \u{1F4CA} 109 MCP tools"],"0.10.77":["\u{1FA79} **Frictionless onboarding + first-class self-hosting/BYOK**"," \u{1F680} Editor-launched server now serves all tools even before sign-in \u2014 zero-credential device flow finally triggers on first tool call"," \u{1F512} No more stdout pollution: stdio JSON-RPC stream stays clean when no JWT is set"," \u{1F3E0} `setup --api-url` / `init --api-url` point at a self-hosted backend; URL baked into config only when non-default",' \u{1F9EC} `health` now shows your BYOK embedding provider + accepts cky_ long-lived keys (was a false "invalid token" failure)'],"0.10.76":["\u{1F4CA} **Agent-trace benchmark + editor matrix + setup timer**"," \u{1F4C2} New `agent-traces-corpus.json` \u2014 22 lessons, 15 queries, realistic AI-agent debug patterns"," \u{1F3C6} Benchmark result: **P@1 +66.7%, MRR +9.5% vs flat-file** (adversarial failure-distractors per category)"," \u{1F4CB} README: first-class editor support matrix (Claude Code, Cursor, Windsurf, VSCode, Cline, Continue.dev, Zed)",' \u23F1\uFE0F setup now shows elapsed time + "Brain is ready" banner at the end'],"0.10.75":["\u{1FA79} **Setup hardened \u2014 works from the VSCode plugin & any non-TTY terminal**"," \u{1F50C} `setup` no longer hangs on a non-interactive stdin (VSCode tasks, CI) \u2014 auto-detects + runs in automatic mode"," \u{1F510} Device-flow now uses the API proxy first (the old direct-Keycloak call returned 403) \u2014 sign-in actually completes"," \u{1F310} When auto sign-in is unavailable, the browser opens with a step-by-step API-key guide instead of a silent paste prompt"," \u{1F4CA} Funnel fix: `device_flow_completed` / `device_flow_failed(reason)` now emitted from setup too"],"0.10.73":["\u{1F510} **Team visibility scopes + one-command init + external bench**",' \u{1F195} `team_grant_scope` / `team_scopes` \u2014 scope lessons to a sub-team (group="security"); only members + admins recall them',' \u{1F3F7}\uFE0F `learn_from_attempts(group="...")` \u2014 orthogonal to private; smart_recall enforces it per requester'," \u26A1 `init` is now zero-arg + idempotent (reuses saved creds, only writes what changed, <60s)"," \u{1F4E6} `npm run bench:external` \u2014 prove recall-lift on a third-party-labeled corpus (portable JSON format)"," \u{1F4CA} 107 MCP tools"],"0.10.72":["\u{1F451} **Role model \u2014 admin \xB7 reviewer \xB7 contributor \xB7 viewer (Phase 3)**"," \u{1F195} `team_assign_role` \u2014 establish governance; first call bootstraps, admins manage the rest"," \u{1F195} `team_whoami` \u2014 see your own role and capabilities"," \u{1F195} `team_roster` \u2014 full team role table (\u{1F451}\u{1F6E1}\uFE0F\u270F\uFE0F\u{1F441}\uFE0F)"," \u{1F6E1}\uFE0F `team_confirm` is now role-aware \u2014 admin/reviewer auto-get senior weight; contributor gets peer; no self-promotion"," \u{1F451} Setup CLI now prompts for governance bootstrap (idempotent). 105 MCP tools"],"0.10.71":['\u{1F6E1}\uFE0F **Self-healing auth** \u2014 no more silent "0 recalls because the token quietly died"'," \u267B\uFE0F Near-expiry tokens auto-refresh into a long-lived key while still valid (zero interaction)"," \u{1F501} A rejected (401) call self-heals once and retries before surfacing an error"," \u{1F4E3} If the credential is truly dead, session_start + get_api_status say so plainly + how to fix"],"0.10.70":["\u{1F6F0}\uFE0F **Service/System nodes in the graph (Phase 3)** \u2014 the brain now models running systems",' \u{1F195} `brain_service_map(service="prometheus")` \u2014 who owns it + every failure/fix known',' \u{1F3F7}\uFE0F Tag lessons with `service="..."` (`service_kind="system"` for infra) \u2014 person\u2192operates, file\u2192runs_in edges',` \u{1F6A8} Incident triage: a restarting pod \u2192 instant "who knows this and what's broken before"`," \u{1F4CA} 102 MCP tools"],"0.10.69":["\u{1F4C1} **Personalized context-aware recall (Phase 3)** \u2014 pass `context_files` to `smart_recall`"," \u{1F3AF} Lessons learned on your current files bubble up \u2014 even when the query doesn't name the file"," \u{1F3F7}\uFE0F `\u{1F4C1} context match` badge on every file-boosted result so you know WHY it ranked up"," \u2705 Works alongside keyword, semantic, CKG, and governance signals \u2014 a 6th ranking dimension"],"0.10.68":["\u{1F91D} **Collaboration graph (Phase 3)** \u2014 person\u2194person edges from shared files"," \u{1F465} `brain_who_knows` now shows who the top expert frequently works with",' \u{1F68C} Bus-factor insight: "ask X and Y together \u2014 they solved this on shared files"'," \u{1F6E1}\uFE0F Stability: every network call in the agent hot path is now timeout-bounded"],"0.10.64":["\u{1F4C8} **The three decisive metrics, now measurable**"," \u23F1\uFE0F `brain_metrics()` \u2014 time-to-first-recall, recall-lift, team-knowledge-reuse in one view"," \u{1F465} Cross-author reuse tracked: recall a teammate's lesson \u2192 counted + surfaced inline"," \u{1F6E1}\uFE0F Stability: scans now capped + timed out (a huge keyspace can't hang the agent)"],"0.10.61":["\u{1F3AF} **Phase 3C: 100 MCP tools milestone \u2014 zero-setup knowledge graph**"," \u{1F504} `brain_from_git` now auto-builds Person+File nodes from git history (zero setup!)"," \u{1F50D} `skill_gaps()` \u2014 find domains with unresolved failures, missing attribution"," \u{1F4CA} `brain_coverage()` \u2014 scored 0-100 health report: lessons \xB7 attribution \xB7 file coverage"],"0.10.60":["\u{1F195} **Phase 3B: File map + team overview + visibility**"," \u{1F4C1} `brain_file_map(file_paths=[...])` \u2014 experts + lessons per file before you touch it"," \u{1F5FA}\uFE0F `team_expertise_map()` \u2014 full team skills matrix in one table",' \u{1F512} `visibility: "private"` on `learn_from_attempts` \u2014 private notes never leak to smart_recall'," \u{1F4CA} 98 MCP tools"],"0.10.59":["\u{1F195} **Phase 3A: Org-wide knowledge graph**",' \u{1F465} `brain_who_knows(topic="...")` \u2014 find your team\'s experts on any topic instantly',' \u{1F578}\uFE0F Person + File nodes auto-built from `learn_from_attempts(author="...", file_paths=[...])`'," \u{1F464} Author attribution now shown inline in `smart_recall` results"," \u{1F4CA} 96 MCP tools \xB7 386 tests green"],"0.10.58":["\u{1F9F9} Zero lint warnings \u2014 all unused imports cleaned across every handler","\u2705 Build: 0 errors, 0 warnings \xB7 379 tests green"],"0.10.57":[`\u{1F195} **What's new in v${Be}:**`," \u{1F527} **Critical fix** \u2014 corrected the npm bin/main entry path (`dist/src/index.js`); 0.10.50\u20130.10.52 shipped a broken entry point"," \u{1F527} Version hygiene \u2014 synced package.json, server.json, lockfile, MCP_VERSION; `latest` now points forward again"," \u2705 Accurate tool count (95) across README, server.json, CLI banners"," \u2705 Includes all Phase 2/3 work: quality reranking, Cachly-Bench, hybrid + CKG recall, team_confirm governance"],"0.10.52":[" \u2705 `smart_recall` \u2014 CKG traversal as Layer 3: finds lessons that FIXED causal-graph-similar problems (\u{1F578}\uFE0F causal graph badge)"," \u2705 Bench corpus expanded: governance adversarial pair proves review-boost end-to-end (+22% P@1 headline)"," \u{1F527} Import cleanup: unused symbols removed from brain.ts (no functional change)"," \u{1F4A1} `smart_recall` now shows keyword / semantic / CKG / hybrid match type for every result"],"0.10.51":[" \u2705 `team_confirm` \u2014 human review raises lesson recall ranking (\u{1F6E1}\uFE0F senior / \u2714\uFE0F peer)"," \u2705 Governance-aware recall \u2014 confirmed lessons outrank unreviewed auto-learned entries"],"0.10.50":[" \u2705 `smart_recall` \u2014 unified keyword + semantic hybrid list (one ranked result, not two sections)",' \u2705 `smart_recall` \u2014 "Brain saved you here" banner surfaces time saved inline per proven lesson'," \u2705 Quality reranking \u2014 proven successes outrank symptom-dense failures (+11% Precision@1)"," \u2705 Cachly-Bench \u2014 IR benchmark with CI regression guard (see BENCH.md for the proof)"," \u{1F527} Contradiction resolution now persisted to Redis (90-day TTL)"," \u{1F4A1} Run `smart_recall` to see your Brain's recall quality in action"],"0.10.49":[" \u2705 `brain_from_git` \u2014 auto-seed your Brain from git history in seconds"," \u2705 `brain_predict_failures` \u2014 predict CI/build failures before they happen"," \u2705 VS Code extension \u2014 Brain status bar, ambient learning, CodeLens hints"," \u2705 Team Brain \u2014 share lessons across your whole engineering team"," \u{1F527} Stability \u2014 auto-expiring memory keys, longer provisioning wait, robust recall"]},Pn=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","session_start","session_start_summary","session_end","session_ping","session_handoff","auto_learn_session","brain_who_knows","brain_file_map","team_expertise_map","skill_gaps","brain_coverage","brain_metrics","brain_service_map","brain_collab_pairs","brain_portability","brain_changelog","brain_set_pref","brain_get_pref"]),Xs=Vs("/billing","upgrade"),wt=new Map,_t=new Set,Qs=1680*60*60;function en(ce=new Date){return`cachly:quota:recalls:${ce.toISOString().slice(0,7)}`}async function bt(ce){try{const X=en();await ce.incr(X)===1&&await ce.expire(X,Qs)}catch{}}function $t(ce){return`cachly:stats:drei-ausgaenge:${ce}`}async function vt(ce,X,Q){try{await ce.hincrby($t(X),Q,1)}catch{}}async function kt(ce,X){const Q=wt.get(ce);if(Q&&Q.expiresAt>Date.now())return Q.gate;try{const de=await X(`/api/v1/instances/${ce}/memory`),f=de?.recall_limit??-1,t=de?.total_recall_count??0,o={reached:f>0&&t>=f,limit:f,used:t,goodwillMessage:de?.goodwill_message,notice:de?.notice};return wt.set(ce,{gate:o,expiresAt:Date.now()+6e4}),o}catch{return{reached:!1,limit:-1,used:0}}}async function jn(ce,X,Q,de){switch(ce){case"learn_from_attempts":{const{instance_id:f,topic:t,outcome:o,what_worked:_,what_failed:A="",context:d="",severity:a="major",file_paths:$=[],commands:l=[],tags:u=[],depends_on:h=[],author:k="",visibility:x="team",service:i="",service_kind:c="service",group:S="",grund:g="",ersetzt:v="",gilt_ab:I=""}=X,{what_worked:M,what_failed:e="",context:H=""}=Qt({what_worked:_,what_failed:A,context:d}),b=await Q(f),ne=new Date,ae=ne.toISOString(),U=Oe(M,ne),N=Oe(e,ne),O=Oe(H,ne),te=Pe(M,ne)+Pe(e,ne)+Pe(H,ne),V=Ks({uebergeben:k,umgebung:process.env.CACHLY_AUTHOR,git:Ws(process.env.CACHLY_WORKSPACE??process.cwd())});let Z="";try{Z=Fs(await b.get(`cachly:prefs:${js}:${f}`))}catch{}const s=Gs(V.autor,Z),p=zs(V);if(x!=="private"&&await Ht(b,f))return Jt(b,t,{topic:t,outcome:o,what_worked:U,what_failed:N,context:O,severity:a,file_paths:$,commands:l,tags:u,depends_on:h,...s?{author:s}:{},...i?{service:i}:{},...S?{group:String(S).toLowerCase().trim()}:{},visibility:x,recall_count:0,ts:ae,confidence:1,version:3});const m=t.split(":")[0],r=Ct[m],n=[];if(r)for(const P of r.required)P==="commands"&&l.length===0&&n.push(`\u{1F4CB} ${r.hint}`);let T=!1,R=0,L,D=[];const B=await b.get(`cachly:lesson:best:${t}`),re=String(g??"").trim();if(B&&!re)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
+
`);if(B)try{const P=JSON.parse(B);R=P.recall_count??0,L=P.last_recalled_at,D=P.audit_trail??[],D.push({ts:ae,action:"updated",prev_outcome:P.outcome,grund:re}),D.length>20&&(D=D.slice(-20)),T=!0;const z=[];if(P.outcome==="success"&&o==="failure"?z.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):P.outcome==="failure"&&o==="success"&&z.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),z.length>0){D[D.length-1].action="contradiction-resolved";try{const se=le(t),E=le(`resolution:${t}`);await ue(b,se,"contradicts",E,!1)}catch{}try{const se=`cachly:contradictions:${t}`,E=P.outcome==="success"&&o==="failure"?"kept-success":"overwrote-failure";await b.rpush(se,JSON.stringify({ts:ae,prev_outcome:P.outcome,new_outcome:o,direction:E})),await b.ltrim(se,-50,-1),await b.expire(se,180*86400)}catch{}z.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else D=[{ts:ae,action:"created"}];const y=[];if(o==="failure"){const P=[],z=b.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((E,j)=>{z.on("data",J=>P.push(...J)),z.on("end",E),z.on("error",j)});const se=t.split(/[:\-_]/).filter(E=>E.length>2);for(const E of P.slice(0,50)){const j=await b.get(E);if(j)try{const J=JSON.parse(j);if(J.outcome!=="success")continue;const oe=(J.topic??"").split(/[:\-_]/).filter(ve=>ve.length>2);if(se.filter(ve=>oe.includes(ve)).length>=1&&J.topic!==t){y.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${J.topic}\` (success, ${J.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${J.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${J.topic}", ..., severity="critical")\``);break}}catch{}}}for(const P of h){const z=`cachly:dep:${P}`,se=await b.get(z),E=F(se,[]);E.includes(t)||E.push(t),await b.set(z,JSON.stringify(E),"EX",90*86400)}const C={topic:t,outcome:o,what_worked:U,what_failed:N,context:O,severity:a,file_paths:$,commands:l,tags:u,depends_on:h,...s?{author:s}:{},...i?{service:i}:{},...S?{group:String(S).toLowerCase().trim()}:{},visibility:x,recall_count:R,...L?{last_recalled_at:L}:{},...I&&!Number.isNaN(Date.parse(String(I)))?{gilt_ab:new Date(String(I)).toISOString()}:{},ts:ae,verified_at:o==="success"||o==="partial"?ae:void 0,confidence:1,audit_trail:D,version:3},w=String(v??"").trim();let q="",K=null;w===t&&w?q="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":w&&(K=await b.get(`cachly:lesson:best:${w}`),K?C.ersetzt=w:q=`\u26A0\uFE0F Die zu ersetzende Lektion \`${w}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let G="";if(!w)try{const P=(await Ie(b,["cachly:lesson:best:*"],`${t} ${U}`.slice(0,300),5)).filter(z=>z.key.startsWith("cachly:lesson:best:")).map(z=>{const se=F(z.content,{});return{topic:se.topic??z.key.slice(19),what_worked:se.what_worked}});G=as(t,U,P)??""}catch{}if(o==="failure")try{const z=(await b.lrange(ut(f),0,199)).map(j=>F(j,{ts:"",frage:"",geliefert:[]})).filter(j=>j.ts!==""),se=(await Ie(b,["cachly:lesson:best:*"],`${t} ${N||U}`.slice(0,300),5)).filter(j=>j.key.startsWith("cachly:lesson:best:")).map(j=>{const J=F(j.content,{});return{topic:J.topic??j.key.slice(19),what_worked:J.what_worked}}),E=ls(t,String(N||""),z,se);await b.hincrby(ht(f),E,1)}catch{}const ee=hs([U,N,d].filter(Boolean).join(" ").slice(0,2e3));ee&&(C.entscheidung=ee);const Y=JSON.stringify(C);b.set(`cachly:stats:born_at:${f}`,ae,"EX",365*86400,"NX").catch(()=>{});const W=`cachly:lessons:${t}`;await b.rpush(W,Y),await b.ltrim(W,-100,-1),await b.expire(W,is*86400);let ie=!1;if(o==="success"||o==="partial"?(await b.set(`cachly:lesson:best:${t}`,Y),ie=!0):B||(await b.set(`cachly:lesson:best:${t}`,Y),ie=!0),K&&ie)try{const P=JSON.parse(K);P.ersetzt_durch=t,P.gilt_bis=ae,P.ersetzt_am=ae,await b.set(`cachly:lesson:best:${w}`,JSON.stringify(P))}catch{}ie&&qt(),ie&&Me()&&(async()=>{const P=F(Y,{});try{const z=await ye(Ge(P),{geduld:"lang"});if(z?.length&&await b.set(`${it}${t}`,Re(z)),xe==="cachly"||xe==="ollama")try{const se=await ye(Ge(P),{geduld:"lang",modell:mt});se?.length&&await b.set(`${ct}${t}`,Re(se))}catch{}}catch(z){await b.sadd(Te,t).catch(()=>{}),await Ae(b,Fe,`Volltext-Vektor nicht geschrieben (${xe}): ${ze(z)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const z=await ye(es(t),{geduld:"lang"});z?.length&&await b.set(`${rt}${t}`,Re(z))}catch(z){await Ae(b,Fe,`Namens-Vektor nicht geschrieben (${xe}): ${ze(z)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await ts(b,t,P,z=>ye(z,{geduld:"lang"}))}catch(z){await Ae(b,Fe,`Eingaenge nicht geschrieben (${xe}): ${ze(z)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{const z=await b.spop(Te,3),se=Array.isArray(z)?z:z?[z]:[];for(const E of se){if(E===t){await b.sadd(Te,E);continue}const j=await b.get(`cachly:lesson:best:${E}`);if(!j)continue;const J=F(j,{});try{const oe=await ye(Ge(J),{geduld:"lang"});oe?.length?await b.set(`${it}${E}`,Re(oe)):await b.sadd(Te,E)}catch{await b.sadd(Te,E)}}}catch{}})();try{const P="cachly:session:decision-log",z=JSON.stringify({ts:ae,topic:t,outcome:o,what_worked:U.slice(0,120)});await b.rpush(P,z),await b.ltrim(P,-50,-1)}catch{}let me=null;try{const P=le(t),z=t.split(":")[0]??"unknown";await ke(b,P,z,z);for(const E of u){const j=le(`tag:${E}`);await ke(b,j,"tag","tag"),await ue(b,P,"co-occurs",j,o==="success",o==="partial")}for(const E of h){const j=le(E);await ue(b,P,"requires",j,!0)}if((z==="fix"||z==="debug")&&(o==="success"||o==="partial")){const E=N||O||"",j=E?Le(E):null;if(j){const J=le(`problem:${j}`);await ke(b,J,"problem","problem"),await ue(b,P,"fixes",J,o==="success",o==="partial")}}if(o==="failure"&&(N||U)){const j=Le(N||U);if(j){const J=le(`cause:${j}`);await ke(b,J,"cause","cause"),await ue(b,P,"causes",J,!1)}}if(o==="failure"){const E=await b.smembers(`cachly:ckg:idx:from:${P}`);for(const j of E){const J=await b.get(j);if(!J)continue;const oe=F(J,null);if(oe&&oe.edgeType==="fixes"&&oe.confidence>.7&&oe.trials>=3){me=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${oe.confidence.toFixed(2)}, n=${oe.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${P}")\` to review.`;const he=`cachly:ckg:conflict:${P}`;await b.set(he,JSON.stringify({topic:t,concept_id:P,detected_at:new Date().toISOString(),fix_confidence:oe.confidence,fix_trials:oe.trials,failure_outcome:o,reported_by:s||"unknown",what_failed:N||"",resolved:!1}),"EX",3600*24*90)}}}if(o==="success"&&(z==="fix"||z==="debug")){const E=await b.smembers(`cachly:ckg:idx:from:${P}`);for(const j of E.slice(0,10)){const J=await b.get(j);if(!J)continue;const oe=F(J,null);if(!oe||oe.edgeType!=="fixes")continue;const he=await b.smembers(`cachly:ckg:idx:from:${oe.to}`);for(const ve of he.slice(0,5)){const Ve=await b.get(ve);if(!Ve)continue;const pe=F(Ve,null);pe&&pe.edgeType==="co-occurs"&&(pe.successes=(pe.successes||0)+.1,pe.trials=(pe.trials||0)+.1,pe.confidence=(pe.successes+1)/(pe.trials+2),pe.last_updated=new Date().toISOString(),await b.set(ve,JSON.stringify(pe)))}}}if(Math.random()<.01){const E=Date.now()-7776e6,j=await b.smembers(`cachly:ckg:idx:from:${P}`);for(const J of j){const oe=await b.get(J);if(!oe)continue;const he=F(oe,null);he&&he.trials<3&&he.last_updated&&new Date(he.last_updated).getTime()<E&&(he.confidence=he.confidence*.9,he.last_updated=new Date().toISOString(),await b.set(J,JSON.stringify(he)))}}}catch{}if(s){b.set(`cachly:agents:active:${s}`,JSON.stringify({author:s,last_topic:t,last_outcome:o,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const P=t.split(":")[0]??"unknown",z=await Nt(b,yt(s),P),se=le(t);await ue(b,z,"authored",se,o==="success",o==="partial");for(const E of $.slice(0,8)){const j=await Qe(b,E);await ue(b,z,"touched",j,!0),await Et(b,j,z)}}catch{}}if(i&&typeof i=="string"&&i.trim())try{const P=t.split(":")[0]??"unknown",z=c==="system"?"system":"service",se=await At(b,i.trim(),P,z),E=le(t);if(await ue(b,E,"affects",se,o==="success",o==="partial"),s){const j=`person:${le(yt(s))}`;await ue(b,j,"operates",se,!0)}for(const j of $.slice(0,8)){const J=`file:${le(j)}`;await ue(b,J,"runs_in",se,!0)}}catch{}if(s&&(o==="success"||o==="partial")){const P={topic:t,outcome:o,what_worked:U,what_failed:N??"",severity:a,author:s,file_paths:$,commands:l,tags:[...new Set([...u,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},z=`cachly:lessons:${t}`;b.rpush(z,JSON.stringify(P)).catch(()=>{})}return[`${o==="success"?"\u2705":o==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${T?"updated":"stored"}:** \`${t}\` (${o}) ${a==="critical"?"\u{1F534}":a==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${a}`,me??"","",`**What worked:** ${U}`,N?`**What failed:** ${N}`:"",O?`**Context:** ${O}`:"",$.length>0?`**Files:** ${$.map(P=>`\`${P}\``).join(", ")}`:"",l.length>0?`**Commands:** ${l.map(P=>`\`${P}\``).join(", ")}`:"",u.length>0?`**Tags:** ${u.map(P=>`#${P}`).join(" ")}`:"","",T?`\u267B\uFE0F Updated (recall count: ${R} \xB7 audit entries: ${D.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,s&&(o==="success"||o==="partial")?`\u{1F465} Auto-shared with team (by _${s}_${V.quelle!=="uebergeben"?` \xB7 aus ${V.quelle}`:""}) \u2014 visible in \`team_recall\``:"",p??"",h.length>0?`\u{1F517} Depends on: ${h.map(P=>`\`${P}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",G,K&&ie?`\u21B7 Ersetzt \`${w}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin.`:q,...n,...y,te>0?`\u{1F5D3}\uFE0F ${te} relative Zeitangabe${te===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(ne.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",Js(U)??""].filter(P=>P!=="").join(`
|
|
3
|
+
`)}case"recall_feedback":{const{instance_id:f}=X,t=await Q(f),o=ys(X,new Date().toISOString());if(!o.ok)return[`\u26A0\uFE0F ${o.grund}`,"","Beispiel:","```",'recall_feedback(instance_id="\u2026", query="warum bricht der Deploy ab",',' topic="ci:zeitgrenze-meldet-cancelled", helped=true, rank=0)',"```","rank=0 heisst: die Lektion stand GAR NICHT in der Antwort.","Das ist die wertvollste Rueckmeldung von allen."].join(`
|
|
4
|
+
`);const _=o.eintrag,A=`cachly:wirkung:${f}`;await t.rpush(A,JSON.stringify(_));const a=(await t.lrange(A,0,-1).catch(()=>[])).map(k=>F(k,null)).filter(Boolean),$=ws(a),l=_s(_),u={"fehlender-treffer":"Sie half, stand aber gar nicht in der Antwort \u2014 der Topf hat sie nicht aufgenommen. Das ist der wertvollste Fall.","zu-weit-hinten":`Sie half, stand aber auf Platz ${_.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${_.platz} und half nicht \u2014 die Sortierung war sich sicher und lag falsch.`,bestaetigung:"Sie stand vorn und half. Bestaetigung.",unauffaellig:"Half nicht und stand hinten. Sagt wenig."},h=$.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${($.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${_.thema}** \u2014 ${_.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${_.platz===0?"\u2014 (stand nicht drin)":_.platz}`,"",u[l],"",`Spur: ${$.gesamt} Rueckmeldungen, ${h}.`,`Davon: ${$.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${$.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${$.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
|
|
5
|
+
`)}case"recall_best_solution":{const{instance_id:f,topic:t,author:o}=X,_=await Q(f);try{const u=await _.get(`cachly:letzter-recall:${f}`),h=u?F(u,null):null,k=bs(h,t,new Date().toISOString());k&&(await _.rpush(`cachly:wirkung:${f}`,JSON.stringify(k)),await _.del(`cachly:letzter-recall:${f}`))}catch{}const A=await _.get(`cachly:lesson:best:${t}`);if(A){const u=F(A,null);if(!u)return`\u26A0\uFE0F Lesson data for \`${t}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const h=u.group;if(h){const B=o?await nt(_,f,o).catch(()=>new Set):new Set,re=o?await We(_,f,o).catch(()=>null)==="admin":!1;if(!ot(h,B,re))return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const k=Ne(u),x=u.verified_at??u.ts,i=(Date.now()-new Date(x).getTime())/864e5,c=St(k,i),S=new Date().toISOString(),g={...u,recall_count:(u.recall_count??0)+1,verified_at:S,last_recalled_at:S,confidence:1};await _.set(`cachly:lesson:best:${t}`,JSON.stringify(g)),bt(_);const v=tt(u)?et(u):0;v>0&&_.incrbyfloat(`cachly:stats:time_saved_mins:${f}`,v).catch(()=>{});const I=u.severity==="critical"?"\u{1F534}":u.severity==="major"?"\u{1F7E1}":u.severity?"\u{1F7E2}":"",M=u.audit_trail??[],e=M.filter(B=>B&&typeof B.grund=="string"&&B.grund.trim().length>0).slice(-3).map(B=>` \xB7 ${B.ts?new Date(B.ts).toLocaleDateString("de-DE"):"?"}: ${B.grund.trim()}`),H=M.length>1?[`_Audit: ${M.length} changes \xB7 stored ${new Date(u.ts).toLocaleDateString("de-DE")}_`,...e.length>0?["**Warum zuletzt geaendert:**",...e]:[]].join(`
|
|
6
|
+
`):"",b=(Date.now()-new Date(u.ts).getTime())/864e5,ne=b>60?`\u{1F4AD} _Remember when you solved this ${Math.round(b/30)} months ago? Still works._`:"",ae=g.recall_count===3&&!u.pinned?"\u{1F4CC} **You've looked this up 3 times.** Consider pinning it for instant access: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",U=u.authors??(u.author?[u.author]:[]),N=[...new Set(U.filter(Boolean))],O=g.recall_count;let te="";N.length>=2&&O>=5?te=`\u{1F3C6} **Battle-tested** \u2014 recalled ${O}\xD7 \xB7 verified by ${N.length} developers. Trust this.`:O>=10?te=`\u{1F3C6} **Battle-tested** \u2014 recalled ${O}\xD7. This is one of your most-proven solutions.`:N.length>=2?te=`\u2705 **Team-verified** \u2014 confirmed by ${N.length} developers.`:O>=5&&(te=`\u2705 **Proven** \u2014 recalled ${O}\xD7 without contradiction.`);const V=u.ersetzt_durch,Z=u.ersetzt_am?` (am ${u.ersetzt_am.slice(0,10)})`:"",s=V?await _.get(`cachly:lesson:best:${V}`):null,p=s?!Se($e(s)):!1,m=V?s?p?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${Z} \u2014 die Nachfolge-Lektion ist nicht team-sichtbar (privat). Der Text unten bleibt als Vorgeschichte lesbar; die gueltige Fassung kennt ihr Autor.`:`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${Z} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${V}")\`. Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${Z} \u2014 der Nachfolger \`${V}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",r=u.gilt_ab,n=u.gilt_bis,T=r?`\u{1F4C5} Gilt seit ${String(r).slice(0,10)}.`:"",R=u.entscheidung,L=R?.gegen?dt({gegen:R.gegen,grund:R.grund??null}):"",D=n&&Date.parse(String(n))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(n).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[m,D,T,L,ne,te,`${c} **Best solution for \`${t}\`** ${I}${u.severity?` (${u.severity})`:""} \xB7 recalled ${g.recall_count}\xD7`,"",u.what_worked?`**What worked:** ${u.what_worked}`:"",u.what_failed?`**What failed (avoid this):** ${u.what_failed}`:"",u.context?`**Context:** ${u.context}`:"",(u.file_paths??[]).length>0?`**Files:** ${(u.file_paths??[]).map(B=>`\`${B}\``).join(", ")}`:"",(u.commands??[]).length>0?`**Commands:** ${(u.commands??[]).map(B=>`\`${B}\``).join(", ")}`:"",(u.tags??[]).length>0?`**Tags:** ${(u.tags??[]).map(B=>`#${B}`).join(" ")}`:"",H,ae].filter(B=>B!=="").join(`
|
|
7
|
+
`)}const d=[],a=_.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((u,h)=>{a.on("data",k=>d.push(...k)),a.on("end",u),a.on("error",h)});const $=d.filter(u=>u.toLowerCase().includes(t.toLowerCase()));if($.length===0){const u=`cachly:lessons:${t}`,h=await _.lrange(u,-3,-1);if(h.length>0){const x=h.map(i=>F(i,null)).filter(Boolean).map(i=>`- ${i.outcome==="success"?"\u2705":"\u274C"} ${i.what_worked.slice(0,120)} (${new Date(i.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${t}\` yet. Last attempts:
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
`)}`}return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const l=[];for(const u of $.slice(0,5)){const h=await
|
|
9
|
+
${x.join(`
|
|
10
|
+
`)}`}return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const l=[];for(const u of $.slice(0,5)){const h=await _.get(u);if(!h)continue;const k=F(h,null);k&&l.push(`**\`${k.topic}\`** \u2014 ${k.what_worked.slice(0,200)}`)}return`\u{1F50D} **Partial matches for \`${t}\`:**
|
|
11
11
|
|
|
12
12
|
${l.join(`
|
|
13
13
|
|
|
14
|
-
`)}`}case"smart_recall":{const{instance_id:f,query:t,threshold:o=.78,author:
|
|
14
|
+
`)}`}case"smart_recall":{const{instance_id:f,query:t,threshold:o=.78,author:_="",context_files:A=[]}=X,d=Array.isArray(A)?A.filter(y=>typeof y=="string"):[],a=await Q(f);let $=new Set,l=!1;_&&($=await nt(a,f,_).catch(()=>new Set),l=await We(a,f,_).catch(()=>null)==="admin");const u=await Ie(a,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],t,25),h=Yt(u);let k=!1,x=null;const i=await(async()=>{if(!Me())return je(Ot,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),h;try{if(await we.aktualisiere(a),we.groesse===0)return je(Lt,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),h;const y=await ye(t);if(!y?.length)return je(Pt,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),h;await Je.aktualisiere(a),await Ue.aktualisiere(a),await De.aktualisiere(a),await qe.aktualisiere(a);const w=(we.groesse>0?qe.groesse/we.groesse:0)>=Cs?ye(t,{modell:mt}).catch(()=>null):null,q=h.filter(E=>E.key.startsWith("cachly:lesson:best:")).map(E=>E.key.slice(19)),K=E=>Math.max(we.naehe(y,E),Je.naehe(y,E)),G=[...De.themen()],ee=(G.length>0?G:we.aehnlichste(y,500).map(E=>E.topic)).map(E=>({t:E,n:K(E)})).sort((E,j)=>j.n-E.n).slice(0,xs).map(E=>E.t),Y=[...new Set([...q,...ee])],W=ee.slice(0,3).map(E=>we.rohvektor(E)).filter(Boolean),ie=W.length?fs(y,W):y,me=pt(t),_e=De.statistik,be=Y.map(E=>{const j=new Set([...pt(De.textVon(E))].map(ps));return{naeheText:we.naehe(y,E),naeheThema:Je.naehe(y,E),naeheRueckkopplung:we.naehe(ie,E),seltenheitsDeckung:_e?_e.deckung(me,j):0,besterZeuge:_e?_e.besterZeuge(me,j):0}});let fe=ds(be,ms);{const E=[...fe].sort((j,J)=>J-j);x=E.length>1?E[0]-E[1]:null}if(Ue.groesse>0){const E=Y.map(J=>{const oe=Ue.besteNaehe(y,J);return oe>=Ts?oe:-2}),j=ft(E);fe=fe.map((J,oe)=>J+Ns*j[oe])}if(w){const E=await w;if(E?.length){const j=ft(Y.map(J=>qe.naehe(E,J)));fe=fe.map((J,oe)=>J+Ss*j[oe])}}const P=Y.map((E,j)=>({t:E,p:fe[j]})).sort((E,j)=>j.p-E.p).map(E=>E.t),z=new Map(h.map(E=>[E.key,E])),se=[];for(const E of P){const j=`cachly:lesson:best:${E}`,J=z.get(j);if(J){se.push(J),z.delete(j);continue}const oe=await a.get(j).catch(()=>null);oe&&se.push({key:j,content:oe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return se.push(...z.values()),k=!0,se}catch(y){return await Ae(a,jt,`der Bedeutungspfad brach ab (${y instanceof Error?y.message:String(y)}) \u2014 diese Suche lief nur ueber Woerter`),h}})();bt(a);{const y=i.filter(C=>C.key.startsWith("cachly:lesson:best:")).slice(0,3).map(C=>C.key.slice(19));if(y.length>0){const C={ts:new Date().toISOString(),themen:y};(async()=>{const w=lt(f);await a.lpush(w,JSON.stringify(C)),await a.ltrim(w,0,cs-1)})().catch(()=>{})}{const C={ts:new Date().toISOString(),frage:t.slice(0,200),geliefert:y};(async()=>{const w=ut(f);await a.lpush(w,JSON.stringify(C)),await a.ltrim(w,0,us-1)})().catch(()=>{})}}if(Me()){const y=i.filter(C=>C.key.startsWith("cachly:lesson:best:")).slice(0,3).map(C=>C.key.slice(19));os(a,t,y,ye).catch(()=>{})}const c=[],S=i.filter(y=>y.key.startsWith("cachly:lesson:best:"));let g=0,v=0;for(const y of S.slice(0,5)){const C=await a.get(y.key).catch(()=>null);if(C){const w=F(C,null);if(w?.state==="archived")continue;if(w){const q=new Date().toISOString(),K={...w,recall_count:(w.recall_count??0)+1,verified_at:q,last_recalled_at:q};a.set(y.key,JSON.stringify(K)).catch(()=>{});const G=tt(w)?et(w):0;if(G>0&&a.incrbyfloat(`cachly:stats:time_saved_mins:${f}`,G).catch(()=>{}),a.incr(`cachly:stats:recalls_total:${f}`).catch(()=>{}),w.author&&_&&w.author!==_){g++,a.incr(`cachly:stats:cross_author_recalls:${f}`).catch(()=>{}),a.sadd(`cachly:stats:reuse_pairs:${f}`,`${_}<-${w.author}`).catch(()=>{});const ee=`person:${le(_)}`,Y=`person:${le(w.author)}`;ue(a,ee,"collaborates",Y,!0).catch(()=>{}),ue(a,Y,"collaborates",ee,!0).catch(()=>{})}w.outcome==="success"&&v++,w.outcome==="success"&&(w.recall_count??0)>=1&&!Ee(w)&&c.push({topic:y.key.replace("cachly:lesson:best:",""),severity:w.severity??"major",recall_count:(w.recall_count??0)+1,savedMins:G,ts:w.ts,author:w.author})}}}v>0&&a.set(`cachly:stats:first_recall_at:${f}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{});const I=await de(`/api/v1/instances/${f}`).catch(()=>null),M=!I?.tier||I.tier.toLowerCase()==="free",e=[];if(!M&&I?.vector_token&&Me())try{const y=await ye(t),C=`https://api.cachly.dev/v1/sem/${I.vector_token}`,w=await fetch(`${C}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:y,namespace:"cachly:ctx",threshold:o,top_k:5}),signal:AbortSignal.timeout(8e3)});if(w.ok){const q=await w.json();for(const K of q.filter(G=>G.found&&G.id)){const G=K.id.replace("ctx:","").split(":"),ee=G[0],Y=G.slice(1).join(":"),W=`cachly:ctx:${ee}:${Y}`,ie=await a.get(W).catch(()=>null);e.push({key:W,similarity:K.similarity??0,content:ie??"(evicted)"})}}}catch{}const H=i.map(y=>y.score),b=H.length?Math.min(...H):0,ne=H.length&&Math.max(...H)-b||1,ae=y=>(y-b)/ne,U=new Map;for(const y of i){const C=ae(y.score);U.set(y.key,{key:y.key,content:y.content,bm25Score:C,hybridScore:C*(e.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const y of e){const C=U.get(y.key);C?(C.semScore=y.similarity,C.hybridScore=(C.bm25Score??0)*.6+y.similarity*.4,C.matchType="hybrid"):U.set(y.key,{key:y.key,content:y.content,semScore:y.similarity,hybridScore:y.similarity*.5,matchType:"semantic"})}try{const y=Ke(t).filter(q=>q.length>=4).slice(0,4),C=new Set;for(const q of y){const K=a.scanStream({match:`cachly:ckg:node:*${q}*`,count:20});await new Promise((G,ee)=>{K.on("data",Y=>{for(const W of Y.slice(0,5))C.add(W.replace("cachly:ckg:node:",""))}),K.on("end",G),K.on("error",ee)})}const w=new Set;for(const q of[...C].slice(0,12)){const K=await a.smembers(`cachly:ckg:idx:to:${q}`);for(const G of K.slice(0,6)){const ee=await a.get(G);if(!ee)continue;const Y=F(ee,null);if(!Y||Y.edgeType!=="fixes"||Y.confidence<.35||w.has(Y.from))continue;w.add(Y.from);const W=`cachly:lesson:best:${Y.from}`,ie=U.get(W);if(ie)ie.ckgScore=Math.max(ie.ckgScore??0,Y.confidence),ie.hybridScore=ie.hybridScore*.88+Y.confidence*.12,ie.matchType==="keyword"&&(ie.matchType="hybrid");else{const me=await a.get(W).catch(()=>null);if(!me)continue;U.set(W,{key:W,content:me,ckgScore:Y.confidence,hybridScore:Y.confidence*.3,matchType:"ckg"})}}}}catch{}if(d.length>0){const y=new Set(d.map(C=>C.replace(/\\/g,"/")));for(const C of U.values()){if(!C.key.startsWith("cachly:lesson:best:"))continue;const w=F(C.content,{});(Array.isArray(w.file_paths)?w.file_paths.filter(K=>typeof K=="string").map(K=>K.replace(/\\/g,"/")):[]).some(K=>y.has(K))&&(C.hybridScore*=1.15,C.contextBoost=!0)}}for(const y of U.values()){if(y.matchType!=="semantic"&&y.matchType!=="ckg")continue;const C=Xt({key:y.key,content:y.content});C&&(y.hybridScore*=Zt(C))}const N=[...U.values()].filter(y=>{if(!y.key.startsWith("cachly:lesson:best:"))return!0;const C=$e(y.content);return!(!Se(C)||!ot(C?.group,$,l))}).sort((y,C)=>C.hybridScore-y.hybridScore),O=[];for(const y of N){if(!y.key.startsWith("cachly:lesson:best:"))continue;const C=F(y.content,{});C.gilt_bis&&Date.parse(String(C.gilt_bis))<Date.now()&&O.push(`\u23F3 \`${y.key.replace("cachly:lesson:best:","")}\` galt bis ${String(C.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`)}{const y=new Set(N.map(C=>C.key));for(let C=N.length-1;C>=0;C--){const w=N[C];if(!w.key.startsWith("cachly:lesson:best:"))continue;const q=F(w.content,{});if(!q.ersetzt_durch)continue;const K=w.key.replace("cachly:lesson:best:","");if(y.has(`cachly:lesson:best:${q.ersetzt_durch}`))N.splice(C,1),O.push(`\u21B7 \`${K}\` verdraengt \u2014 ersetzt durch \`${q.ersetzt_durch}\`${q.ersetzt_am?` am ${q.ersetzt_am.slice(0,10)}`:""}`);else if(await a.get(`cachly:lesson:best:${q.ersetzt_durch}`)){const G=$e(await a.get(`cachly:lesson:best:${q.ersetzt_durch}`));Se(G)?O.push(`\u26A0\uFE0F \`${K}\` ist ersetzt durch \`${q.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${q.ersetzt_durch}")\``):O.push(`\u21B7 \`${K}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else O.push(`\u21A9\uFE0F \`${K}\` war ersetzt durch \`${q.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const te=zt();let V="",Z=null;if(te!==null){V=Ft();const y=N[0]?.hybridScore??0,C=Wt(N.map(w=>({key:w.key,content:w.content,punktzahl:w.hybridScore})),V,te,y);C.weggelassenesThema!==void 0?N.splice(0,1):C.markierungGesetzt&&N[0]&&C.treffer[0]&&(N[0]={...N[0],content:C.treffer[0].content}),Z={frage:t,hoechstePunktzahl:y,themen:[],zulassungsfaehig:C.zulassungsfaehig,zulassungsGrund:C.zulassungsGrund,zuteilung:C.zuteilung,weggelassenesThema:C.weggelassenesThema,markierungGesetzt:C.markierungGesetzt}}const s=await kt(f,de),p=s.reached,m=gt({ueberLimit:p,gesamt:N.length,volleTiefe:As}),r=m.sichtbar,n=[`\u{1F9E0} **Smart Recall** for: _"${t}"_
|
|
15
15
|
`];s.goodwillMessage&&n.push(`${s.goodwillMessage}
|
|
16
|
-
`);const
|
|
16
|
+
`);const T={critical:0,major:1,minor:2},R=c.sort((y,C)=>(T[y.severity]??1)-(T[C.severity]??1))[0];if(R){const y=G=>G>=60?`${G/60}h`:`${G}min`,C=(()=>{if(!R.ts)return null;const G=new Date(R.ts);if(isNaN(G.getTime()))return null;const ee=new Date,Y=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return G.getFullYear()===ee.getFullYear()?`${G.getDate()} ${Y[G.getMonth()]}`:`${G.getDate()} ${Y[G.getMonth()]} ${G.getFullYear()}`})(),w=R.severity==="critical"?120:R.severity==="major"?60:20,q=R.author&&R.author!==_?` \xB7 by @${R.author}`:"",K=C?` \xB7 learned ${C} (was a ${y(w)} debug)`:"";n.push(`> \u{1F4A1} **Brain saved you ~${y(R.savedMins)} here** \u2014 \`${R.topic}\`${K} \xB7 recalled ${R.recall_count}\xD7${q}
|
|
17
17
|
`)}g>0&&n.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${g} of these lesson${g!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
|
|
18
|
-
`);const L=
|
|
19
|
-
`);const D=
|
|
20
|
-
`);const B=
|
|
21
|
-
`);const
|
|
22
|
-
`),B.belegte<
|
|
23
|
-
`)
|
|
24
|
-
`);for(const
|
|
25
|
-
\u26A0\uFE0F **No results for:** ${
|
|
26
|
-
`)}}else{n.push(`\u26A0\uFE0F No matches found for: "${t}"`),O.length>0&&n.push("",...O.map(
|
|
27
|
-
\u{1F4A1} Tips:`),n.push(" \u2022 Try different keywords"),n.push(" \u2022 Use `list_remembered` to see available context"),n.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(
|
|
18
|
+
`);const L=N.filter(y=>y.contextBoost).length;L>0&&n.push(`> \u{1F4C1} **Personalized** \u2014 ${L} lesson${L!==1?"s":""} boosted because ${L!==1?"they match":"it matches"} your current file context (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})
|
|
19
|
+
`);const D=Ut(t);D.length>1&&n.push(`_Detected ${D.length} sub-topics:_ ${D.map((y,C)=>`${C+1}. "${y}"`).join(", ")}
|
|
20
|
+
`);const B=Dt(N.map(y=>({wortBelege:y.wortBelege,semScore:y.semScore,ckgScore:y.ckgScore})));if(B.schweigen)return vt(a,f,"schweigen"),n.push(Mt(B)),n.join(`
|
|
21
|
+
`);const re=gs(x);if(re&&n.push(re,""),vt(a,f,re?"knapp":"beantwortet"),N.length>0){const y=N.some(w=>w.ckgScore!==void 0),C=e.length>0&&y?"keyword + semantic + CKG hybrid":e.length>0?"keyword + semantic hybrid":y?"keyword + CKG hybrid":"keyword";if(n.push(`### \u{1F50D} Results (${N.length} \u2014 ${C})
|
|
22
|
+
`),B.belegte<N.length){const w=[];for(const K of N){if(!K.key.startsWith("cachly:lesson:best:")||!Bt({wortBelege:K.wortBelege,semScore:K.semScore,ckgScore:K.ckgScore}))continue;const G=F(K.content,{}),ee=Date.parse(G.verified_at??G.ts??"");Number.isFinite(ee)&&w.push(Math.floor((Date.now()-ee)/864e5))}const q=Rt(w);n.push(`> \u{1F4CA} ${B.belegte} von ${N.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(q?` \u23F3 ${q}`:"")+`
|
|
23
|
+
`)}if(O.length>0&&n.push(...O.map(w=>`> ${w}`),""),D.length>1){const w=new Map,q=gt({ueberLimit:p,gesamt:N.length,volleTiefe:Is});for(const ee of N.slice(0,q.sichtbar)){const Y=ee.subQuery??t;w.has(Y)||w.set(Y,[]),w.get(Y).push(ee)}for(const[ee,Y]of w){n.push(`**Topic: "${ee}"** (${Y.length} results)
|
|
24
|
+
`);for(const W of Y.slice(0,4)){const ie=W.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),me=W.matchType==="ckg"?`CKG: ${(W.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:W.ckgScore!==void 0&&W.bm25Score!==void 0?`BM25: ${W.bm25Score.toFixed(2)}, CKG: ${W.ckgScore.toFixed(2)}, \u{1F500} hybrid`:W.matchType==="hybrid"?`BM25: ${(W.bm25Score??0).toFixed(2)}, sem: ${((W.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:W.matchType==="semantic"?`sem: ${((W.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(W.bm25Score??0).toFixed(2)}, matched: ${W.matchedWords?.join(", ")}`,_e=st(W.key,W.content,300);if(n.push(` **${ie}** _(${me})_`),W.key.startsWith("cachly:lesson:best:")){const be=await a.get(W.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(W.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),fe=be?F(be,{}):{};fe.title&&n.push(` \u{1F4D6} **${fe.title}** \u2014 ${fe.summary??""}`)}for(const be of _e)n.push(` > ${be}`);n.push("")}}const K=[...w.keys()],G=D.filter(ee=>!K.includes(ee));G.length>0&&n.push(`
|
|
25
|
+
\u26A0\uFE0F **No results for:** ${G.map(ee=>`"${ee}"`).join(", ")}`)}else for(const w of N.slice(0,r)){const q=w.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let K="";if(w.key.startsWith("cachly:lesson:best:")){const W=F(w.content,{});W.author&&(K=` \xB7 \u{1F464} ${W.author}`)}const G=w.contextBoost?" \xB7 \u{1F4C1} context match":"",ee=w.matchType==="hybrid"?`BM25: ${(w.bm25Score??0).toFixed(2)}, sem: ${((w.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:w.matchType==="semantic"?`sem: ${((w.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(w.bm25Score??0).toFixed(2)}, matched: ${w.matchedWords?.join(", ")}`,Y=st(w.key,w.content,400);n.push(`**${q}**${K}${G} _(${ee})_`);{const W=F(w.content??"",{});W.entscheidung?.gegen&&n.push(dt({gegen:W.entscheidung.gegen,grund:W.entscheidung.grund??null}))}if(w.key.startsWith("cachly:lesson:best:")){const W=await a.get(w.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(w.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ie=W?F(W,{}):{};ie.title&&n.push(`\u{1F4D6} **${ie.title}** \u2014 ${ie.summary??""}`)}for(const W of Y)n.push(`> ${W}`);n.push("")}if(p&&m.zurueckgehalten>0){const w=m.zurueckgehalten;n.push(`\u{1F512} **Free recall limit reached** (${s.used}/${s.limit} this month). Showing your top match; ${w} further relevant lesson${w!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${Xs}
|
|
26
|
+
`)}}else{n.push(`\u26A0\uFE0F No matches found for: "${t}"`),O.length>0&&n.push("",...O.map(w=>`> ${w}`));const y=Ke(t),C=[];if(at.size>0&&y.length>0)for(const w of y.slice(0,3)){if(w.length<4)continue;let q=3,K="";for(const G of at){if(G.length<3||Math.abs(G.length-w.length)>4)continue;const ee=Vt(w,G);ee>0&&ee<q&&(q=ee,K=G)}K&&C.push(`"${K}" (instead of "${w}")`)}C.length>0?n.push(`\u{1F4A1} **Did you mean:** ${C.join(", ")}?`):(n.push(`
|
|
27
|
+
\u{1F4A1} Tips:`),n.push(" \u2022 Try different keywords"),n.push(" \u2022 Use `list_remembered` to see available context"),n.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(N.length>0){n.push(""),n.push("\u21A9\uFE0E Hat eine davon geholfen? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` \u2014 und wenn die richtige Lektion **nicht** dabei war: dieselbe Meldung mit `rank=0`. Das ist die einzige Zahl, die die Sortierung besser macht.");const y=N.filter(C=>C.key.startsWith("cachly:lesson:best:")).map(C=>C.key.slice(19));if(y.length>0)try{await a.setex(`cachly:letzter-recall:${f}`,7200,JSON.stringify({frage:t,themen:y}))}catch{}}if(te!==null&&Z){const y=N.slice(0,r).filter(C=>C.key.startsWith("cachly:lesson:best:")).map(C=>C.key.slice(19));return Kt(a,V,{...Z,themen:y},n.join(`
|
|
28
28
|
`))}return n.join(`
|
|
29
|
-
`)}case"session_start":{const{instance_id:f,focus:t="",author:o="",provider:
|
|
29
|
+
`)}case"session_start":{const{instance_id:f,focus:t="",author:o="",provider:_="",workspace_path:A=""}=X,d=await Q(f),a=[],$=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((s,p)=>{$.on("data",m=>a.push(...m)),$.on("end",s),$.on("error",p)});const l=[];if(a.length>0){const s=await d.mget(...a);for(const p of s){const m=F(p??null,null);m&&l.push(m)}}l.sort((s,p)=>new Date(p.ts).getTime()-new Date(s.ts).getTime());let u=0;const h=d.scanStream({match:"cachly:ctx:*",count:200});await new Promise((s,p)=>{h.on("data",m=>{u+=m.filter(r=>!r.endsWith(":meta")).length}),h.on("end",s),h.on("error",p)});const k=await d.get("cachly:session:last"),x=F(k,null),i=t.toLowerCase().split(/\s+/).filter(Boolean),c=i.length>0?l.filter(s=>i.some(p=>s.topic.toLowerCase().includes(p)||(s.tags??[]).some(m=>m.toLowerCase().includes(p)))):[];let S=0,g=0,v="";try{const s=await d.get("cachly:streak:current"),p=F(s,null),m=new Date().toISOString().slice(0,10);if(p){const r=p.last_date,n=new Date(Date.now()-864e5).toISOString().slice(0,10);r===m?(S=p.days,g=p.record):r===n?(S=p.days+1,g=Math.max(S,p.record),await d.set("cachly:streak:current",JSON.stringify({days:S,last_date:m,record:g}))):(S=1,g=p.record,await d.set("cachly:streak:current",JSON.stringify({days:1,last_date:m,record:g})))}else S=1,g=1,await d.set("cachly:streak:current",JSON.stringify({days:1,last_date:m,record:1}));S>=7?v=`\u{1F525} **${S}-day streak!** ${S===g?" New record!":`Best: ${g}d`}`:S>1&&(v=`\u{1F525} ${S}-day streak`)}catch{}await d.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:t,provider:_}),"EX",86400);let I=0;try{const s=await d.get(`cachly:stats:time_saved_mins:${f}`);I=parseFloat(s??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${_?` \xB7 ${_}`:""}`,""];if(v&&e.push(v,""),I>=30){const s=Math.floor(I/60),p=Math.round(I%60),m=s>0?`${s}h${p>0?` ${p}m`:""}`:`${p}m`,r=l.filter(T=>!Ee(T)&&(T.recall_count??0)>0).length,n=r>0?` \u2014 ${r} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${m} total**${n}`,"")}const H=await kt(f,de),b=Es({used:H.used,limit:H.limit,savedMins:I});if(b&&e.push(b,""),H.notice&&!_t.has(f)&&(_t.add(f),e.push(H.notice,"")),x?.ts){const s=new Date(x.ts).getTime(),p=Math.floor((Date.now()-s)/864e5);if(p>=7&&!Number.isNaN(s)){const m=l.filter(r=>{const n=new Date(r.ts).getTime();return!Number.isNaN(n)&&n>s});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${p} days since your last session.`),m.length>0){const r=m.slice(0,3).map(n=>`\`${n.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${m.length} lesson${m.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${r}${m.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${l.length} lesson${l.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);e.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await d.get("cachly:mcp:version:last_seen")!==Be){await d.set("cachly:mcp:version:last_seen",Be,"EX",365*86400);const p=Zs[Be];if(p){e.push(...p,"");const m=Ys();m&&e.push(`\u{1F4CA} ${m} MCP tools`,"")}}}catch{}const ne=!x&&l.length===0&&u===0;if(ne&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),A?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${f}")\``),e.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),e.push(""),e.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),e.push("")),o&&!ne)try{const s=`cachly:team:first_briefing:${o}`;if(!await d.get(s)){const m=l.filter(r=>r.author&&r.author!==o);if(m.length>0){await d.set(s,"1","EX",365*86400);const r=new Map;for(const n of m){const T=n.author;r.has(T)||r.set(T,[]),r.get(T).push(n)}e.push(""),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),e.push(""),e.push("Your teammates have already solved problems you're about to hit:"),e.push("");for(const[n,T]of r){e.push(` \u{1F464} **${n}** fixed ${T.length} thing${T.length>1?"s":""}:`);for(const R of T.slice(0,2)){const L=R.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${L} \`${R.topic}\` \u2014 ${R.what_worked.slice(0,90)}`)}T.length>2&&e.push(` \u2026 and ${T.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const ae=await d.get("cachly:session:handoff");if(ae)try{const s=JSON.parse(ae),p=Math.round((Date.now()-new Date(s.ts).getTime())/6e4),m=p<60?`${p}m ago`:p<1440?`${Math.round(p/60)}h ago`:`${Math.round(p/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${m}):`),s.context_summary&&e.push(` ${s.context_summary}`),s.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const n of s.remaining_tasks)e.push(` - ${n}`)}s.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${s.completed_tasks.join(", ")}`);const r=(s.files_changed??[]).filter(n=>n.status==="broken"||n.status==="partial");r.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${r.map(n=>`\`${n.path}\` (${n.status}${n.description?": "+n.description:""})`).join(", ")}`),s.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${s.blocked_on}`),s.instructions&&e.push(` \u{1F4DD} **Instructions:** ${s.instructions}`),e.push("")}catch{}const U=await d.get("cachly:session:checkpoint");if(U)try{const s=JSON.parse(U),p=new Date(s.ts).getTime(),m=x?new Date(x.ts).getTime():0;if(p>m){const r=Math.round((Date.now()-p)/6e4),n=r<60?`${r}m ago`:r<1440?`${Math.round(r/60)}h ago`:`${Math.round(r/1440)}d ago`,T=s.provider?` [${s.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${T} (${n}): ${s.task}`),s.files_touched.length>0&&e.push(` Files: ${s.files_touched.slice(0,5).map(R=>`\`${R}\``).join(", ")}`),s.next_step&&e.push(` \u{1F4CD} Next step was: ${s.next_step}`),(!x||p-m>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(A&&!x)try{const{execSync:s}=await import("node:child_process"),p=s(`git -C "${A}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),m=s(`git -C "${A}" diff --stat HEAD~3 2>/dev/null || git -C "${A}" diff --stat 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim();if(p){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const r of p.split(`
|
|
30
30
|
`).slice(0,8))e.push(` ${r}`);if(m){const r=m.split(`
|
|
31
|
-
`).filter(n=>n.includes("|")||n.includes("changed"));if(r.length>0){e.push(" **Recent changes:**");for(const n of r.slice(0,5))e.push(` ${n.trim()}`)}}e.push("")}}catch{}if(T){const s=Math.round((Date.now()-new Date(T.ts).getTime())/6e4),p=s<60?`${s}m ago`:s<1440?`${Math.round(s/60)}h ago`:`${Math.round(s/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${p}): ${T.summary}`),T.duration_min&&e.push(` Duration: ${T.duration_min} min`),(T.files_changed??[]).length>0&&e.push(` Files: ${(T.files_changed??[]).slice(0,5).map(m=>`\`${m}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${l.length} lessons \xB7 ${u} context entries`,"");{const p=l.filter(m=>!Ne(m)).filter(m=>m.outcome==="success"&&(m.pinned===!0||(m.recall_count??0)>=5)).sort((m,r)=>(r.recall_count??0)-(m.recall_count??0)).slice(0,5);if(p.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const m of p){const r=m.severity==="critical"?"\u{1F534}":m.severity==="major"?"\u{1F7E1}":"",n=m.recall_count??0,N=m.pinned===!0?"pinned":`recalled ${n}\xD7`,R=Ce(m);e.push(` \u{1F3C6}${r} \`${m.topic}\` _(${N})_ \u2014 ${R[0]??""}`,...R.slice(1))}e.push("")}}if(l.length>=3){const s=new Map;for(const r of l){const n=r.topic.split(":")[0]??"other";s.has(n)||s.set(n,{total:0,success:0,critical:0});const N=s.get(n);N.total++,r.outcome==="success"&&N.success++,r.severity==="critical"&&N.critical++}const p=[...s.entries()].sort((r,n)=>n[1].total-r[1].total).slice(0,6),m=p.some(([,r])=>r.success<r.total*.4&&r.total>=2);if(p.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[r,n]of p){const N=Math.round(n.success/n.total*100),R=Math.round(N/10),L="\u2588".repeat(R)+"\u2591".repeat(10-R),D=n.critical>0?" \u{1F534}":N<40&&n.total>=2?" \u26A0\uFE0F":"";e.push(` ${L} ${r.padEnd(18)} ${String(N).padStart(3)}% (${n.success}/${n.total} confirmed)${D}`)}m&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}try{const s=[],p=d.scanStream({match:"cachly:ckg:conflict:*",count:50});if(await new Promise((m,r)=>{p.on("data",n=>s.push(...n)),p.on("end",m),p.on("error",r)}),s.length>0){e.push(`\u26A1 **Active belief conflicts (${s.length}):**`);for(const m of s.slice(0,3)){const r=await d.get(m);if(!r)continue;const n=j(r,null);n&&e.push(` \u26A0\uFE0F \`${n.topic}\` \u2014 previously confirmed fix (${(n.fix_confidence*100).toFixed(0)}%, n=${n.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${le(n.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(m=>m.length>3),p=[];for(const m of s.slice(0,6))if(!await d.exists(`cachly:ckg:node:${m}`)){const n=[],N=d.scanStream({match:`cachly:ckg:node:${m}*`,count:10});await new Promise((R,L)=>{N.on("data",D=>n.push(...D)),N.on("end",R),N.on("error",L)}),n.length===0&&p.push(m)}if(p.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const m of p.slice(0,3))e.push(` \u2B1C \`${m}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${m}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${m}")\` \u2014 search global commons`);e.push("")}}catch{}if(c.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const s of c.slice(0,4)){const p=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":"",r=Ce(s);e.push(` ${p}${m} \`${s.topic}\` \u2014 ${r[0]??""}`,...r.slice(1))}e.push("")}if(l.length>0){const p=[...l].filter(r=>!Ne(r)).sort((r,n)=>(n.recall_count??0)-(r.recall_count??0)).filter(r=>(r.recall_count??0)>0).slice(0,3),m=(c.length>0?l.filter(r=>!c.includes(r)):l).filter(r=>!p.includes(r)).slice(0,c.length>0?3:4);if(p.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${p[0].recall_count}\xD7 before):`);for(const r of p){const n=r.outcome==="success"?"\u2705":r.outcome==="partial"?"\u26A0\uFE0F":"\u274C",N=r.severity==="critical"?"\u{1F534}":r.severity==="major"?"\u{1F7E1}":"",R=r.recall_count??0,L=r.authors??(r.author?[r.author]:[]),D=new Set(L.filter(Boolean)).size,B=D>=2&&R>=5||R>=10?" \u{1F3C6}":D>=2||R>=5?" \u2705":"",ie=R>1?` _(${R}\xD7 recalled)_`:"",y=Ce(r);e.push(` ${n}${N}${B} \`${r.topic}\`${ie} \u2014 ${y[0]??""}`,...y.slice(1))}e.push("")}if(m.length>0){const r=p.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(r);for(const n of m){const N=n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C",R=n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":"",L=Ce(n);e.push(` ${N}${R} \`${n.topic}\` \u2014 ${L[0]??""}`,...L.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");l.length>=10&&(l.some(p=>p.author)||(e.push(`\u{1F91D} **Your Brain has ${l.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const A=l.filter(s=>s.outcome==="failure"||s.outcome==="partial");if(A.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${A.length} topic${A.length>1?"s":""} with no success yet):`);for(const s of A.slice(0,3))e.push(` \u274C \`${s.topic}\` \u2014 ${(s.what_failed??s.what_worked).slice(0,80)}`);e.push("")}const O=l.filter(s=>s.outcome!=="success"&&s.outcome!=="partial"?!1:Te(s)<Ve);if(O.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${kt}d \u2014 verify before applying):`);for(const s of O.slice(0,4)){const p=Te(s),m=Math.round((Date.now()-new Date(s.verified_at??s.ts).getTime())/864e5),r=p<vt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${r} \`${s.topic}\` \u2014 ${m}d stale, ${(p*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const ee=T;if(ee?.decision_log?.length){const s=ee.decision_log,p=s.filter(r=>r.outcome==="success"),m=s.filter(r=>r.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${s.length} lessons stored):`),p.length>0&&e.push(` \u2705 Worked: ${p.slice(0,3).map(r=>`\`${r.topic}\``).join(", ")}`),m.length>0&&e.push(` \u274C Failed: ${m.slice(0,3).map(r=>`\`${r.topic}\``).join(", ")}`),e.push("")}{const s=new Set(["src","lib","test","tests","dist","index","main","app","internal","pkg","cmd","node_modules","components","utils","ts","tsx","js","jsx","go","py","rs","java","json","yaml","yml"]),p=N=>{const R=new Set;for(const L of N)for(const D of L.toLowerCase().split(/[/\\._-]/))D.length>3&&!s.has(D)&&R.add(D);return[...R]};let m=i,r=t,n=!1;if(m.length===0&&T){const N=p(T.files_changed??[]),R=(T.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(L=>L.length>3&&!s.has(L));m=[...new Set([...N,...R])],r="where you left off last session",n=!0}if(m.length>0){const N=l.filter(R=>{if(R.outcome==="success")return!1;const L=R.topic.split(":")[0];return m.some(D=>R.topic.toLowerCase().includes(D)||L===D||(R.tags??[]).some(B=>B.toLowerCase()===D))});if(N.length>=1){const L=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",n?` You're likely to continue **${r}** \u2014 ${N.length} known pitfall${N.length>1?"s":""} there:`:` Known pitfalls for **"${r}"** (${N.length} past failure${N.length>1?"s":""}):`,...N.slice(0,3).map(D=>` \u274C \`${D.topic}\` \u2014 ${(D.what_failed??D.what_worked).slice(0,80)}`),""];e.splice(2,0,...L)}}}if(o){const s=Date.now()-6048e5,p=l.filter(m=>m.author&&m.author!==o&&new Date(m.ts).getTime()>s);if(p.length>0){const m=new Map;for(const r of p){const n=r.author;m.has(n)||m.set(n,[]),m.get(n).push(r)}e.push(`\u{1F465} **Team this week** (${p.length} lesson${p.length>1?"s":""} from teammates):`);for(const[r,n]of m){e.push(` \u{1F464} **${r}**:`);for(const N of n.slice(0,3)){const R=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${R} \`${N.topic}\` \u2014 ${N.what_worked.slice(0,80)}`)}n.length>3&&e.push(` \u2026 and ${n.length-3} more`)}e.push("")}}try{const s=await d.get("cachly:crystal:latest");if(s){const p=j(s,null);if(p&&Math.round((Date.now()-new Date(p.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${p.label} \xB7 ${p.session_count} sessions compressed):`);for(const r of p.top_patterns.slice(0,3))e.push(` \u2022 **${r.category}** (${r.count}\xD7): ${r.insight.slice(0,90)}`);e.push("")}}}catch{}try{const s=await d.hgetall(`cachly:roadmap:${f}`);if(s&&Object.keys(s).length>0){const p={critical:0,high:1,medium:2,low:3},m={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},r=new Set(["planned","in-progress","blocked"]),n=Object.values(s).flatMap(L=>{const D=j(L,null);return D?[D]:[]}),N=n.filter(L=>r.has(L.status)).sort((L,D)=>L.status==="in-progress"&&D.status!=="in-progress"?-1:D.status==="in-progress"&&L.status!=="in-progress"?1:(p[L.priority]??99)-(p[D.priority]??99)),R=n.filter(L=>L.status==="done").length;if(N.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${N.length} open \xB7 ${R} done):`);for(const L of N.slice(0,5)){const D=L.status==="in-progress"?"\u26A1":L.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${D} ${m[L.priority]??"\u26AA"} \`${L.id}\` **${L.title}**`)}N.length>5&&e.push(` \u2026 and ${N.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(n=>n.length>2).slice(0,5),p=[];for(const n of s){const N=[],R=d.scanStream({match:`cachly:ckg:node:*${n}*`,count:20});await new Promise((L,D)=>{R.on("data",B=>N.push(...B)),R.on("end",L),R.on("error",D)});for(const L of N.slice(0,3)){const D=await d.get(L);if(!D)continue;const B=j(D,null);if(!B)continue;const ie=await d.smembers(`cachly:ckg:idx:from:${B.id}`);for(const y of ie.slice(0,15)){const S=await d.get(y);if(!S)continue;const b=j(S,null);if(!b||b.edgeType!=="causes"&&b.edgeType!=="co-occurs"&&b.edgeType!=="fixes"||b.confidence<.35)continue;const q=b.edgeType==="fixes"?`cachly:lesson:best:${b.from}`:`cachly:lesson:best:${b.to}`,H=await d.get(q),K=j(H,null);p.push({concept:B.id,edgeType:b.edgeType,target:b.to,confidence:b.confidence,lesson:K??void 0})}}}const m=new Set,r=p.filter(n=>{const N=`${n.concept}:${n.target}`;return m.has(N)?!1:(m.add(N),!0)}).sort((n,N)=>N.confidence-n.confidence).slice(0,4);if(r.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const n of r){const N=Math.round(n.confidence*100),R=n.edgeType==="causes"?"\u26A1":n.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${R} **${N}%** \`${n.concept}\` ${n.edgeType} \`${n.target}\``),n.lesson?.what_worked&&e.push(` \u2705 ${n.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const s=await d.get("cachly:mcm:calibration:last"),p=j(s,null)?.ts??0;if((Date.now()-p)/864e5>=30&&l.length>=5){const r=l.filter(N=>N.outcome==="success"&&(N.recall_count??0)>0),n=l.filter(N=>(N.recall_count??0)>0);if(n.length>=3){const N=n.length>0?r.length/n.length:1,R=[],L=new Map;for(const D of n){const B=D.topic.split(":")[0]??"other";L.has(B)||L.set(B,{success:0,total:0});const ie=L.get(B);ie.total++,D.outcome==="success"&&ie.success++}for(const[D,B]of L)B.total>=2&&B.success/B.total<.6&&R.push(D);await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:N,recalled:n.length,low_precision_domains:R})),(R.length>0||N<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${n.length} recalled lessons):`),e.push(` Overall precision: **${(N*100).toFixed(0)}%** recalled lessons actually worked`),R.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${R.map(D=>`\`${D}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const s=await de("/api/v1/syndication/stats");s.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${s.total_lessons.toLocaleString()} lessons \xB7 ${s.total_confirms.toLocaleString()} confirms \xB7 +${s.added_last_7_days} this week`),e.push(""))}catch{}const V=l.filter(s=>s.outcome==="failure"||s.outcome==="partial").length>0,Y=l.some(s=>s.outcome==="success"&&Te(s)<Ve);if(l.length===0||V||Y){const s=[];l.length===0&&s.push("brain is empty"),V&&s.push("open failures"),Y&&s.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${s.join(", ")}._`)}try{if(await d.get(`cachly:prefs:auto_changelog:${f}`).catch(()=>null)!=="false"&&T?.ts&&!ne){const m=new Date(T.ts).getTime();if(!Number.isNaN(m)){const r=l.filter(n=>{const N=new Date(n.ts).getTime();return!Number.isNaN(N)&&N>m});if(r.length>0){const n=Math.round((Date.now()-m)/6e4),N=n<60?`${n}m`:n<1440?`${Math.round(n/60)}h`:`${Math.round(n/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${r.length} new lesson${r.length!==1?"s":""} since your last session** (${N} ago):`);const R=new Map;for(const L of r.slice(0,20)){const D=L.topic.includes(":")?L.topic.split(":")[0]:"general",B=R.get(D)??[];B.push(L),R.set(D,B)}for(const[L,D]of R){e.push(` **${L}**`);for(const B of D){const ie=B.outcome==="failure"?"\u274C":B.severity==="critical"?"\u{1F6A8}":B.severity==="major"?"\u26A0\uFE0F":"\u2705",y=(B.outcome==="failure"?B.what_failed:B.what_worked)??"";e.push(` ${ie} \`${B.topic}\`${y?` \u2014 ${y.slice(0,80)}`:""}`)}}r.length>20&&e.push(` \u2026 and ${r.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${f}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
|
|
32
|
-
`)}case"session_start_summary":{const{instance_id:f,focus:t,top_n:o=10,author:
|
|
33
|
-
`);const u=l.length>
|
|
34
|
-
`)}case"session_end":{const{instance_id:f,summary:t,files_changed:o=[],lessons_learned:
|
|
35
|
-
`).map(B=>B.trim()).filter(Boolean).slice(0,12):[],D=[];for(const B of L)D.push(await
|
|
31
|
+
`).filter(n=>n.includes("|")||n.includes("changed"));if(r.length>0){e.push(" **Recent changes:**");for(const n of r.slice(0,5))e.push(` ${n.trim()}`)}}e.push("")}}catch{}if(x){const s=Math.round((Date.now()-new Date(x.ts).getTime())/6e4),p=s<60?`${s}m ago`:s<1440?`${Math.round(s/60)}h ago`:`${Math.round(s/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${p}): ${x.summary}`),x.duration_min&&e.push(` Duration: ${x.duration_min} min`),(x.files_changed??[]).length>0&&e.push(` Files: ${(x.files_changed??[]).slice(0,5).map(m=>`\`${m}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${l.length} lessons \xB7 ${u} context entries`,"");{const p=l.filter(m=>!Ee(m)).filter(m=>m.outcome==="success"&&(m.pinned===!0||(m.recall_count??0)>=5)).sort((m,r)=>(r.recall_count??0)-(m.recall_count??0)).slice(0,5);if(p.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const m of p){const r=m.severity==="critical"?"\u{1F534}":m.severity==="major"?"\u{1F7E1}":"",n=m.recall_count??0,T=m.pinned===!0?"pinned":`recalled ${n}\xD7`,R=Ce(m);e.push(` \u{1F3C6}${r} \`${m.topic}\` _(${T})_ \u2014 ${R[0]??""}`,...R.slice(1))}e.push("")}}if(l.length>=3){const s=new Map;for(const r of l){const n=r.topic.split(":")[0]??"other";s.has(n)||s.set(n,{total:0,success:0,critical:0});const T=s.get(n);T.total++,r.outcome==="success"&&T.success++,r.severity==="critical"&&T.critical++}const p=[...s.entries()].sort((r,n)=>n[1].total-r[1].total).slice(0,6),m=p.some(([,r])=>r.success<r.total*.4&&r.total>=2);if(p.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[r,n]of p){const T=Math.round(n.success/n.total*100),R=Math.round(T/10),L="\u2588".repeat(R)+"\u2591".repeat(10-R),D=n.critical>0?" \u{1F534}":T<40&&n.total>=2?" \u26A0\uFE0F":"";e.push(` ${L} ${r.padEnd(18)} ${String(T).padStart(3)}% (${n.success}/${n.total} confirmed)${D}`)}m&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}try{const s=[],p=d.scanStream({match:"cachly:ckg:conflict:*",count:50});if(await new Promise((m,r)=>{p.on("data",n=>s.push(...n)),p.on("end",m),p.on("error",r)}),s.length>0){e.push(`\u26A1 **Active belief conflicts (${s.length}):**`);for(const m of s.slice(0,3)){const r=await d.get(m);if(!r)continue;const n=F(r,null);n&&e.push(` \u26A0\uFE0F \`${n.topic}\` \u2014 previously confirmed fix (${(n.fix_confidence*100).toFixed(0)}%, n=${n.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${le(n.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(m=>m.length>3),p=[];for(const m of s.slice(0,6))if(!await d.exists(`cachly:ckg:node:${m}`)){const n=[],T=d.scanStream({match:`cachly:ckg:node:${m}*`,count:10});await new Promise((R,L)=>{T.on("data",D=>n.push(...D)),T.on("end",R),T.on("error",L)}),n.length===0&&p.push(m)}if(p.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const m of p.slice(0,3))e.push(` \u2B1C \`${m}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${m}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${m}")\` \u2014 search global commons`);e.push("")}}catch{}if(c.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const s of c.slice(0,4)){const p=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":"",r=Ce(s);e.push(` ${p}${m} \`${s.topic}\` \u2014 ${r[0]??""}`,...r.slice(1))}e.push("")}if(l.length>0){const p=[...l].filter(r=>!Ee(r)).sort((r,n)=>(n.recall_count??0)-(r.recall_count??0)).filter(r=>(r.recall_count??0)>0).slice(0,3),m=(c.length>0?l.filter(r=>!c.includes(r)):l).filter(r=>!p.includes(r)).slice(0,c.length>0?3:4);if(p.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${p[0].recall_count}\xD7 before):`);for(const r of p){const n=r.outcome==="success"?"\u2705":r.outcome==="partial"?"\u26A0\uFE0F":"\u274C",T=r.severity==="critical"?"\u{1F534}":r.severity==="major"?"\u{1F7E1}":"",R=r.recall_count??0,L=r.authors??(r.author?[r.author]:[]),D=new Set(L.filter(Boolean)).size,B=D>=2&&R>=5||R>=10?" \u{1F3C6}":D>=2||R>=5?" \u2705":"",re=R>1?` _(${R}\xD7 recalled)_`:"",y=Ce(r);e.push(` ${n}${T}${B} \`${r.topic}\`${re} \u2014 ${y[0]??""}`,...y.slice(1))}e.push("")}if(m.length>0){const r=p.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(r);for(const n of m){const T=n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C",R=n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":"",L=Ce(n);e.push(` ${T}${R} \`${n.topic}\` \u2014 ${L[0]??""}`,...L.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");l.length>=10&&(l.some(p=>p.author)||(e.push(`\u{1F91D} **Your Brain has ${l.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const N=l.filter(s=>s.outcome==="failure"||s.outcome==="partial");if(N.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${N.length} topic${N.length>1?"s":""} with no success yet):`);for(const s of N.slice(0,3))e.push(` \u274C \`${s.topic}\` \u2014 ${(s.what_failed??s.what_worked).slice(0,80)}`);e.push("")}const O=l.filter(s=>s.outcome!=="success"&&s.outcome!=="partial"?!1:Ne(s)<Xe);if(O.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Tt}d \u2014 verify before applying):`);for(const s of O.slice(0,4)){const p=Ne(s),m=Math.round((Date.now()-new Date(s.verified_at??s.ts).getTime())/864e5),r=p<xt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${r} \`${s.topic}\` \u2014 ${m}d stale, ${(p*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const te=x;if(te?.decision_log?.length){const s=te.decision_log,p=s.filter(r=>r.outcome==="success"),m=s.filter(r=>r.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${s.length} lessons stored):`),p.length>0&&e.push(` \u2705 Worked: ${p.slice(0,3).map(r=>`\`${r.topic}\``).join(", ")}`),m.length>0&&e.push(` \u274C Failed: ${m.slice(0,3).map(r=>`\`${r.topic}\``).join(", ")}`),e.push("")}{const s=new Set(["src","lib","test","tests","dist","index","main","app","internal","pkg","cmd","node_modules","components","utils","ts","tsx","js","jsx","go","py","rs","java","json","yaml","yml"]),p=T=>{const R=new Set;for(const L of T)for(const D of L.toLowerCase().split(/[/\\._-]/))D.length>3&&!s.has(D)&&R.add(D);return[...R]};let m=i,r=t,n=!1;if(m.length===0&&x){const T=p(x.files_changed??[]),R=(x.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(L=>L.length>3&&!s.has(L));m=[...new Set([...T,...R])],r="where you left off last session",n=!0}if(m.length>0){const T=l.filter(R=>{if(R.outcome==="success")return!1;const L=R.topic.split(":")[0];return m.some(D=>R.topic.toLowerCase().includes(D)||L===D||(R.tags??[]).some(B=>B.toLowerCase()===D))});if(T.length>=1){const L=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",n?` You're likely to continue **${r}** \u2014 ${T.length} known pitfall${T.length>1?"s":""} there:`:` Known pitfalls for **"${r}"** (${T.length} past failure${T.length>1?"s":""}):`,...T.slice(0,3).map(D=>` \u274C \`${D.topic}\` \u2014 ${(D.what_failed??D.what_worked).slice(0,80)}`),""];e.splice(2,0,...L)}}}if(o){const s=Date.now()-6048e5,p=l.filter(m=>m.author&&m.author!==o&&new Date(m.ts).getTime()>s);if(p.length>0){const m=new Map;for(const r of p){const n=r.author;m.has(n)||m.set(n,[]),m.get(n).push(r)}e.push(`\u{1F465} **Team this week** (${p.length} lesson${p.length>1?"s":""} from teammates):`);for(const[r,n]of m){e.push(` \u{1F464} **${r}**:`);for(const T of n.slice(0,3)){const R=T.outcome==="success"?"\u2705":T.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${R} \`${T.topic}\` \u2014 ${T.what_worked.slice(0,80)}`)}n.length>3&&e.push(` \u2026 and ${n.length-3} more`)}e.push("")}}try{const s=await d.get("cachly:crystal:latest");if(s){const p=F(s,null);if(p&&Math.round((Date.now()-new Date(p.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${p.label} \xB7 ${p.session_count} sessions compressed):`);for(const r of p.top_patterns.slice(0,3))e.push(` \u2022 **${r.category}** (${r.count}\xD7): ${r.insight.slice(0,90)}`);e.push("")}}}catch{}try{const s=await d.hgetall(`cachly:roadmap:${f}`);if(s&&Object.keys(s).length>0){const p={critical:0,high:1,medium:2,low:3},m={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},r=new Set(["planned","in-progress","blocked"]),n=Object.values(s).flatMap(L=>{const D=F(L,null);return D?[D]:[]}),T=n.filter(L=>r.has(L.status)).sort((L,D)=>L.status==="in-progress"&&D.status!=="in-progress"?-1:D.status==="in-progress"&&L.status!=="in-progress"?1:(p[L.priority]??99)-(p[D.priority]??99)),R=n.filter(L=>L.status==="done").length;if(T.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${T.length} open \xB7 ${R} done):`);for(const L of T.slice(0,5)){const D=L.status==="in-progress"?"\u26A1":L.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${D} ${m[L.priority]??"\u26AA"} \`${L.id}\` **${L.title}**`)}T.length>5&&e.push(` \u2026 and ${T.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(n=>n.length>2).slice(0,5),p=[];for(const n of s){const T=[],R=d.scanStream({match:`cachly:ckg:node:*${n}*`,count:20});await new Promise((L,D)=>{R.on("data",B=>T.push(...B)),R.on("end",L),R.on("error",D)});for(const L of T.slice(0,3)){const D=await d.get(L);if(!D)continue;const B=F(D,null);if(!B)continue;const re=await d.smembers(`cachly:ckg:idx:from:${B.id}`);for(const y of re.slice(0,15)){const C=await d.get(y);if(!C)continue;const w=F(C,null);if(!w||w.edgeType!=="causes"&&w.edgeType!=="co-occurs"&&w.edgeType!=="fixes"||w.confidence<.35)continue;const q=w.edgeType==="fixes"?`cachly:lesson:best:${w.from}`:`cachly:lesson:best:${w.to}`,K=await d.get(q),G=F(K,null);p.push({concept:B.id,edgeType:w.edgeType,target:w.to,confidence:w.confidence,lesson:G??void 0})}}}const m=new Set,r=p.filter(n=>{const T=`${n.concept}:${n.target}`;return m.has(T)?!1:(m.add(T),!0)}).sort((n,T)=>T.confidence-n.confidence).slice(0,4);if(r.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const n of r){const T=Math.round(n.confidence*100),R=n.edgeType==="causes"?"\u26A1":n.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${R} **${T}%** \`${n.concept}\` ${n.edgeType} \`${n.target}\``),n.lesson?.what_worked&&e.push(` \u2705 ${n.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const s=await d.get("cachly:mcm:calibration:last"),p=F(s,null)?.ts??0;if((Date.now()-p)/864e5>=30&&l.length>=5){const r=l.filter(T=>T.outcome==="success"&&(T.recall_count??0)>0),n=l.filter(T=>(T.recall_count??0)>0);if(n.length>=3){const T=n.length>0?r.length/n.length:1,R=[],L=new Map;for(const D of n){const B=D.topic.split(":")[0]??"other";L.has(B)||L.set(B,{success:0,total:0});const re=L.get(B);re.total++,D.outcome==="success"&&re.success++}for(const[D,B]of L)B.total>=2&&B.success/B.total<.6&&R.push(D);await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:T,recalled:n.length,low_precision_domains:R})),(R.length>0||T<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${n.length} recalled lessons):`),e.push(` Overall precision: **${(T*100).toFixed(0)}%** recalled lessons actually worked`),R.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${R.map(D=>`\`${D}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const s=await de("/api/v1/syndication/stats");s.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${s.total_lessons.toLocaleString()} lessons \xB7 ${s.total_confirms.toLocaleString()} confirms \xB7 +${s.added_last_7_days} this week`),e.push(""))}catch{}const V=l.filter(s=>s.outcome==="failure"||s.outcome==="partial").length>0,Z=l.some(s=>s.outcome==="success"&&Ne(s)<Xe);if(l.length===0||V||Z){const s=[];l.length===0&&s.push("brain is empty"),V&&s.push("open failures"),Z&&s.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${s.join(", ")}._`)}try{if(await d.get(`cachly:prefs:auto_changelog:${f}`).catch(()=>null)!=="false"&&x?.ts&&!ne){const m=new Date(x.ts).getTime();if(!Number.isNaN(m)){const r=l.filter(n=>{const T=new Date(n.ts).getTime();return!Number.isNaN(T)&&T>m});if(r.length>0){const n=Math.round((Date.now()-m)/6e4),T=n<60?`${n}m`:n<1440?`${Math.round(n/60)}h`:`${Math.round(n/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${r.length} new lesson${r.length!==1?"s":""} since your last session** (${T} ago):`);const R=new Map;for(const L of r.slice(0,20)){const D=L.topic.includes(":")?L.topic.split(":")[0]:"general",B=R.get(D)??[];B.push(L),R.set(D,B)}for(const[L,D]of R){e.push(` **${L}**`);for(const B of D){const re=B.outcome==="failure"?"\u274C":B.severity==="critical"?"\u{1F6A8}":B.severity==="major"?"\u26A0\uFE0F":"\u2705",y=(B.outcome==="failure"?B.what_failed:B.what_worked)??"";e.push(` ${re} \`${B.topic}\`${y?` \u2014 ${y.slice(0,80)}`:""}`)}}r.length>20&&e.push(` \u2026 and ${r.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${f}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
|
|
32
|
+
`)}case"session_start_summary":{const{instance_id:f,focus:t,top_n:o=10,author:_=""}=X;if(!t||!t.trim())throw new Error("focus is required for session_start_summary");const A=Math.min(Math.max(1,Math.floor(Number(o)||10)),25),d=await Q(f),a=[],$=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,H)=>{$.on("data",b=>a.push(...b)),$.on("end",e),$.on("error",H)});const l=[];if(a.length>0){const e=await d.mget(...a);for(const H of e){const b=F(H??null,null);b&&l.push(b)}}if(l.length===0)return["\u{1F9E0} Brain Summary \u2014 no lessons yet","","Your brain is empty. Use `learn_from_attempts` after solving tasks to build it up.",`\u{1F4A1} Tip: \`brain_seed_starter(instance_id="${f}")\` to bootstrap with 16 universal lessons.`].join(`
|
|
33
|
+
`);const u=l.length>A,h=t.toLowerCase().split(/\s+/).filter(Boolean),k=Date.now(),x=l.map(e=>{const H=h.filter(s=>e.topic.toLowerCase().includes(s)).length,b=h.filter(s=>(e.tags??[]).some(p=>p.toLowerCase().includes(s))).length,ne=H*2+b,ae=Math.max(0,e.recall_count??0),U=Math.min(1.5,Math.log1p(ae)/10),N=e.severity==="critical"?1:e.severity==="major"?.5:0,O=(k-new Date(e.verified_at??e.ts).getTime())/864e5,te=O<30?.5*(1-O/30):0,V=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,Z=ne+U+N+te+V;return{lesson:e,score:Z}});x.sort((e,H)=>H.score!==e.score?H.score-e.score:new Date(H.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const i=(u?x.slice(0,A):x).map(e=>e.lesson),c=l.length,S=i.length,I=[u?`\u{1F9E0} Brain Summary \u2014 top ${S} of ${c} lessons for "${t}"`:`\u{1F9E0} Brain Summary \u2014 all ${S} lesson${S!==1?"s":""} for "${t}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(const e of i){const H=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",b=e.severity?`[${e.severity}] `:"[minor] ",ne=e.recall_count??0,ae=ne>0?` (\u2713 recalled ${ne}\xD7)`:"",U=e.what_worked.slice(0,110),N=qs(e.author,_);I.push(`${H} ${b}\`${e.topic}\` \u2014 ${U}${ae}${N}`)}I.push("");const M=Us(i,_);return M>0&&I.push(`\u{1F465} ${M} of these ${M===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),u?I.push(`\u{1F4A1} Showing top ${S} of ${c} lessons \xB7 \`session_start\` for full briefing`):I.push(`\u{1F4A1} All ${S} lesson${S!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),I.join(`
|
|
34
|
+
`)}case"session_end":{const{instance_id:f,summary:t,files_changed:o=[],lessons_learned:_,workspace_path:A=""}=X,d=await Q(f),a=new Date;let $;const l=await d.get("cachly:session:current");if(!l)return"\u26A0\uFE0F No active session found.\n\nRun `session_start` first to begin tracking a session, then call `session_end` when you're done.";const u=F(l,null);u?.started&&($=Math.round((a.getTime()-new Date(u.started).getTime())/6e4));let h=[];try{h=(await d.lrange("cachly:session:decision-log",0,-1)).flatMap(H=>{const b=F(H,null);return b?[b]:[]}),await d.del("cachly:session:decision-log")}catch{}const k={ts:a.toISOString(),summary:t,files_changed:o,..._!==void 0?{lessons_learned:_}:{},...$!==void 0?{duration_min:$}:{},...h.length>0?{decision_log:h}:{}};await d.set("cachly:session:last",JSON.stringify(k)),await d.lpush("cachly:session:history",JSON.stringify(k)),await d.ltrim("cachly:session:history",0,49),await d.expire("cachly:session:history",90*86400),await d.del("cachly:session:current");const x=[];try{const e=/\b(fixed|deployed|added|removed|refactored|migrated|updated|resolved|implemented|improved|optimized|configured|created|deleted|disabled|enabled|discovered|found|learned|debugged|patched|upgraded|installed|tested|built|rewrote|moved|renamed|split|merged|extracted)\b/i,H=t.split(/[.!\n]+/).map(b=>b.trim()).filter(b=>b.length>20&&e.test(b));for(const b of H.slice(0,6)){const ae=b.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(V=>V.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(V)).slice(0,4).join("-");if(!ae)continue;const U=`auto:${ae}`,N=`cachly:lesson:best:${U}`,O=await d.get(N);if(O)try{if(JSON.parse(O).outcome==="success")continue}catch{}const te={topic:U,outcome:"success",what_worked:b,context:`Auto-learned from session summary. Full summary: ${t.slice(0,300)}`,severity:"minor",ts:a.toISOString(),recall_count:0,auto_learned:!0,session_ts:a.toISOString(),version:2};await d.set(N,JSON.stringify(te)),await d.expire(N,90*86400),x.push(U)}}catch{}const i=[];if(A)try{const e=l?(()=>{try{return JSON.parse(l).started??""}catch{return""}})():"",H=e?`--since="${e}"`:'--since="1 hour ago"',b=Ye(`git -C "${A}" log ${H} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(b){const ne=/\b(fix|add|remove|refactor|migrate|update|resolve|implement|improve|optimize|configure|create|delete|disable|enable|debug|patch|upgrade|build|rewrite|deploy|feat|chore|docs|test|perf|ci)\b/i,ae=b.split("|||ENDE").map(U=>U.trim()).filter(Boolean);for(const U of ae.slice(0,10)){const[N,O,te,V]=U.split("|||");if(N)try{const T=Ye(`git -C "${A}" diff-tree --no-commit-id --name-only -r --root "${N}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),L=T?T.split(`
|
|
35
|
+
`).map(B=>B.trim()).filter(Boolean).slice(0,12):[],D=[];for(const B of L)D.push(await Qe(d,B));for(let B=0;B<D.length;B++)for(let re=B+1;re<D.length;re++)await ue(d,D[B],"co-occurs",D[re],!0),await ue(d,D[re],"co-occurs",D[B],!0)}catch{}if(!O||!ne.test(O))continue;const Z=(te??"").trim();if(Z.length<120)continue;const s=O.toLowerCase().replace(/^(fix|feat|chore|docs|test|ci|perf|refactor|build|revert)[:(\s]/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);if(!s)continue;const p=`git:${s}`,m=`cachly:lesson:best:${p}`;if(await d.get(m))continue;const n={topic:p,outcome:"success",what_worked:`${O}
|
|
36
36
|
|
|
37
|
-
${
|
|
37
|
+
${Z.slice(0,1200)}`,context:`Auto-learned from git commit ${(N??"").slice(0,7)} at ${V??""} in ${A}`,severity:"minor",ts:a.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3};await d.set(m,JSON.stringify(n)),await d.expire(m,60*86400),i.push(p)}}}catch{}const c=$!==void 0?` \xB7 ${$} min`:"",S=x.length+i.length,g=[];$!==void 0&&$>0&&g.push(`\u23F1 ${$} min session`),S>0&&g.push(`\u{1F9E0} ${S} lessons saved to Brain`),o.length>0&&g.push(`\u{1F4C1} ${o.length} file${o.length>1?"s":""} changed`);const v=g.length>0?`${g.join(" \xB7 ")}
|
|
38
38
|
|
|
39
39
|
My AI Brain remembers this so I never repeat it. @cachlydev
|
|
40
40
|
cachly.dev`:`Session saved to my AI Brain. No more re-explaining this tomorrow. @cachlydev
|
|
41
|
-
cachly.dev`,
|
|
42
|
-
`);return[`\u2705 **Session saved**${c}`,"",`\u{1F4CB} **Summary:** ${t}`,o.length>0?`\u{1F4C1} **Files changed:** ${o.map(e=>`\`${e}\``).join(", ")}`:"",
|
|
43
|
-
`)}case"session_ping":{const{instance_id:f,task:t,files_touched:o=[],next_step:
|
|
44
|
-
\u{1F4CD} **Next step:** ${
|
|
45
|
-
`)}case"session_handoff":{const{instance_id:f,completed_tasks:t=[],remaining_tasks:o=[],files_changed:
|
|
41
|
+
cachly.dev`,I=`https://twitter.com/intent/tweet?text=${encodeURIComponent(v)}`,M=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",$!==void 0?`\u2502 \u23F1 Duration : ${($+" min").padEnd(26)}\u2502`:"",S>0?`\u2502 \u{1F4DA} Learned : ${(S+" lessons").padEnd(26)}\u2502`:"",o.length>0?`\u2502 \u{1F4C1} Changed : ${(o.length+" file"+(o.length>1?"s":"")).padEnd(26)}\u2502`:"","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",`\u2502 \u{1F4E3} Share: ${I.slice(0,34).padEnd(34)}\u2502`,"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"].filter(e=>e!=="").join(`
|
|
42
|
+
`);return[`\u2705 **Session saved**${c}`,"",`\u{1F4CB} **Summary:** ${t}`,o.length>0?`\u{1F4C1} **Files changed:** ${o.map(e=>`\`${e}\``).join(", ")}`:"",_!==void 0?`\u{1F9E0} **Lessons stored:** ${_}`:"",x.length>0?`\u{1F916} **Auto-learned:** ${x.length} lessons extracted from summary (${x.slice(0,3).map(e=>`\`${e}\``).join(", ")}${x.length>3?"\u2026":""})`:"",i.length>0?`\u{1F33F} **Ambient git learning:** ${i.length} commit${i.length>1?"s":""} auto-learned (${i.slice(0,3).map(e=>`\`${e}\``).join(", ")}${i.length>3?"\u2026":""})`:"",M,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(e=>e!=="").join(`
|
|
43
|
+
`)}case"session_ping":{const{instance_id:f,task:t,files_touched:o=[],next_step:_="",provider:A=""}=X,d=await Q(f),a={ts:new Date().toISOString(),task:t,files_touched:o,next_step:_,provider:A};await d.set("cachly:session:checkpoint",JSON.stringify(a),"EX",86400*3),await d.lpush("cachly:session:checkpoint:log",JSON.stringify(a)),await d.ltrim("cachly:session:checkpoint:log",0,19);const $=A?` [${A}]`:"",l=o.length>0?` \xB7 ${o.length} file${o.length>1?"s":""} touched`:"",u=_?`
|
|
44
|
+
\u{1F4CD} **Next step:** ${_}`:"";return[`\u{1F4CC} **Checkpoint saved**${$} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${t}${l}`,u,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically."].filter(h=>h!=="").join(`
|
|
45
|
+
`)}case"session_handoff":{const{instance_id:f,completed_tasks:t=[],remaining_tasks:o=[],files_changed:_=[],instructions:A="",context_summary:d="",blocked_on:a=""}=X,$=await Q(f),u={ts:new Date().toISOString(),completed_tasks:t,remaining_tasks:o,files_changed:_,instructions:A,context_summary:d,blocked_on:a};await $.set("cachly:session:handoff",JSON.stringify(u)),await $.lpush("cachly:session:handoff:history",JSON.stringify(u)),await $.ltrim("cachly:session:handoff:history",0,19);const h=t.length+o.length,k=h>0?Math.round(t.length/h*100):0,x=_.filter(i=>i.status==="broken"||i.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${t.length}/${h} tasks done (${k}%)`,"",t.length>0?`\u2705 **Completed:**
|
|
46
46
|
${t.map(i=>` - ${i}`).join(`
|
|
47
47
|
`)}`:"",o.length>0?`
|
|
48
48
|
\u23F3 **Remaining for next window:**
|
|
49
49
|
${o.map(i=>` - ${i}`).join(`
|
|
50
|
-
`)}`:"",
|
|
51
|
-
\u26A0\uFE0F **Needs attention:** ${
|
|
52
|
-
\u{1F6AB} **Blocked on:** ${a}`:"",
|
|
53
|
-
\u{1F4DD} **Instructions:** ${
|
|
54
|
-
`)}case"auto_learn_session":{const{instance_id:f,observations:t}=
|
|
55
|
-
`)}case"brain_who_knows":{const{instance_id:f,topic:t,limit:o=10}=
|
|
56
|
-
`);const u=[...l.entries()].map(([i,c])=>({id:i,handle:c.handle,lessonCount:c.lessonCount,avgConfidence:c.totalConfidence/c.lessonCount,domains:[...c.domains].slice(0,3).join(", "),lastActive:c.lastActive})).sort((i,c)=>c.lessonCount*c.avgConfidence-i.lessonCount*i.avgConfidence).slice(0,
|
|
57
|
-
`)}case"brain_file_map":{const{instance_id:f,file_paths:t=[]}=
|
|
58
|
-
`)}case"team_expertise_map":{const{instance_id:f,top_n:t=20}=
|
|
59
|
-
`);const
|
|
60
|
-
`)}case"skill_gaps":{const{instance_id:f,min_failures:t=1}=
|
|
61
|
-
`)}case"brain_coverage":{const{instance_id:f,repo_path:t="."}=
|
|
62
|
-
`).filter(Boolean).length,$=String(a)}catch{}let l=0,u=0,h=0;const k=new Set;for(const g of
|
|
63
|
-
`)}case"brain_metrics":{const{instance_id:f}=
|
|
64
|
-
`),
|
|
65
|
-
`)}case"brain_service_map":{const{instance_id:f,service:t}=
|
|
66
|
-
`);const i=d?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${d?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${t}\``,"",d?`_${i} \xB7 ${d.count} lesson${d.count!==1?"s":""} referenced \xB7 domain: ${d.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if($.length>0){const v=$.slice(0,5).map((M
|
|
67
|
-
`)}case"brain_collab_pairs":{const{instance_id:f,min_weight:t=1}=
|
|
68
|
-
`);const a=new Map;for(const[k,
|
|
69
|
-
`)}case"brain_portability":{const{instance_id:f}=
|
|
70
|
-
`)}case"brain_changelog":{const{instance_id:f,days:t=7,max_lessons:o=30,include_failures:
|
|
71
|
-
`);const u=new Map;for(const c of l){const
|
|
72
|
-
`)}case"brain_set_pref":{const{instance_id:f,key:t,value:o}=
|
|
73
|
-
`)}default:return null}}export{
|
|
50
|
+
`)}`:"",x.length>0?`
|
|
51
|
+
\u26A0\uFE0F **Needs attention:** ${x.map(i=>`\`${i.path}\` (${i.status})`).join(", ")}`:"",a?`
|
|
52
|
+
\u{1F6AB} **Blocked on:** ${a}`:"",A?`
|
|
53
|
+
\u{1F4DD} **Instructions:** ${A}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically."].filter(i=>i!=="").join(`
|
|
54
|
+
`)}case"auto_learn_session":{const{instance_id:f,observations:t}=X,o=await Q(f),_=[],A=[];for(const a of t){const $=a.topic??a.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),l=$.includes(":")?$:`auto:${$}`,u=`cachly:lesson:best:${l}`,h=await o.get(u);if(h&&JSON.parse(h).outcome==="success"&&a.outcome!=="success"){A.push(l);continue}const k={topic:l,outcome:a.outcome,what_worked:a.outcome==="success"?a.action:a.details??a.action,what_failed:a.outcome==="failure"?a.action:void 0,context:a.details,severity:a.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2},x=JSON.stringify(k);await o.set(u,x);const i=`cachly:lessons:${l}`;await o.rpush(i,x),await o.ltrim(i,-100,-1),await o.expire(i,90*86400);try{const c=l.split(":")[0]??"auto",S=le(l);if(await ke(o,S,c,c),a.outcome==="success"||a.outcome==="partial"){const g=a.details?Le(a.details):null;if(g){const v=le(`problem:${g}`);await ke(o,v,"problem","problem"),await ue(o,S,"fixes",v,a.outcome==="success",a.outcome==="partial")}}}catch{}_.push(`${a.outcome==="success"?"\u2705":a.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${l}\``)}const d=[`\u{1F916} **Auto-learn complete**: ${_.length} stored, ${A.length} skipped`,""];return _.length>0&&d.push("**Stored:**",..._.map(a=>" "+a),""),A.length>0&&d.push(`**Skipped** (better lesson already exists): ${A.map(a=>`\`${a}\``).join(", ")}`),d.join(`
|
|
55
|
+
`)}case"brain_who_knows":{const{instance_id:f,topic:t,limit:o=10}=X;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const _=Math.max(1,Math.min(Number(o)||10,50)),A=await Q(f),d=le(t),a=Ke(t).filter(i=>i.length>=3).slice(0,5),$=new Set([d]);for(const i of a.slice(0,3)){const c=A.scanStream({match:`cachly:ckg:node:*${i}*`,count:30});await new Promise((S,g)=>{c.on("data",v=>{for(const I of v.slice(0,10)){const M=I.replace("cachly:ckg:node:","");!M.startsWith("person:")&&!M.startsWith("file:")&&$.add(M)}}),c.on("end",S),c.on("error",g)})}const l=new Map;for(const i of[...$].slice(0,25)){const c=await A.smembers(`cachly:ckg:idx:to:${i}`);for(const S of c){const g=await A.get(S);if(!g)continue;const v=F(g,null);if(!v||v.edgeType!=="authored")continue;const I=await A.get(`cachly:ckg:node:${v.from}`);if(!I)continue;const M=F(I,null);if(!M||M.type!=="person")continue;const e=l.get(v.from);e?(e.lessonCount++,e.totalConfidence+=v.confidence,e.domains.add(M.domain),v.last_updated>e.lastActive&&(e.lastActive=v.last_updated)):l.set(v.from,{handle:M.handle,lessonCount:1,totalConfidence:v.confidence,domains:new Set([M.domain]),lastActive:M.last_active??v.last_updated})}}if(l.size===0)return[`## \u{1F465} Who Knows About \`${t}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${t}", author="your-handle", ...)\``].join(`
|
|
56
|
+
`);const u=[...l.entries()].map(([i,c])=>({id:i,handle:c.handle,lessonCount:c.lessonCount,avgConfidence:c.totalConfidence/c.lessonCount,domains:[...c.domains].slice(0,3).join(", "),lastActive:c.lastActive})).sort((i,c)=>c.lessonCount*c.avgConfidence-i.lessonCount*i.avgConfidence).slice(0,_),h=[],k=u[0];if(k)try{const i=await A.smembers(`cachly:ckg:idx:from:${k.id}`),c=[];for(const S of i){const g=await A.get(S);if(!g)continue;const v=F(g,null);if(!v||v.edgeType!=="collaborates")continue;const I=await A.get(`cachly:ckg:node:${v.to}`),M=I?F(I,null):null;M?.handle&&c.push({handle:M.handle,trials:v.trials})}c.sort((S,g)=>g.trials-S.trials);for(const S of c.slice(0,3))h.push(S.handle)}catch{}const x=[`## \u{1F465} Who Knows About \`${t}\`?`,"",`**${u.length}** contributor${u.length!==1?"s":""} with relevant lessons:`,""];for(const[i,c]of u.entries()){const S=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}.`,g=(c.avgConfidence*100).toFixed(0),v=Math.floor((Date.now()-new Date(c.lastActive).getTime())/864e5),I=v<1?"today":v<7?`${v}d ago`:v<30?`${Math.floor(v/7)}w ago`:`${Math.floor(v/30)}mo ago`,M=await We(A,f,c.handle).catch(()=>null),e=M?` ${Gt[M]}`:"";x.push(`${S} **${c.handle}**${e} \u2014 ${c.lessonCount} lesson${c.lessonCount!==1?"s":""} \xB7 ${g}% confidence \xB7 last active ${I}`,` _domains: ${c.domains}_`,"")}return h.length>0&&k&&x.push(`\u{1F91D} **${k.handle}** frequently works with: ${h.map(i=>`**${i}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),x.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),x.join(`
|
|
57
|
+
`)}case"brain_file_map":{const{instance_id:f,file_paths:t=[]}=X,o=(Array.isArray(t)?t:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim());if(!o.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const _=await Q(f),A=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const d of o.slice(0,10)){A.push(`### \`${d}\``);const a=`file:${le(d)}`,$=await _.smembers(`cachly:ckg:idx:to:${a}`),l=[];for(const x of $){const i=await _.get(x);if(!i)continue;const c=F(i,null);if(!c||c.edgeType!=="touched")continue;const S=await _.get(`cachly:ckg:node:${c.from}`);if(!S)continue;const g=F(S,null);!g||g.type!=="person"||l.push({handle:g.handle,touches:c.trials,lastSeen:c.last_updated})}if(l.sort((x,i)=>i.touches-x.touches),l.length>0){const x=l.slice(0,5).map((i,c)=>{const S=c===0?"\u{1F947}":c===1?"\u{1F948}":c===2?"\u{1F949}":`${c+1}.`,g=Math.floor((Date.now()-new Date(i.lastSeen).getTime())/864e5),v=g<1?"today":g<7?`${g}d ago`:`${Math.floor(g/7)}w ago`;return`${S} **${i.handle}** (${i.touches}\xD7 \xB7 ${v})`}).join(" \xB7 ");A.push(`**Experts:** ${x}`)}else A.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const h=d.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(x=>x.length>=4).slice(0,3).join(" "),k=[];if(h)try{const x=await Ie(_,["cachly:lesson:best:*"],h,4);for(const i of x){const c=$e(i.content);if(!Se(c))continue;const S=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",g=c.severity==="critical"?" \u{1F534}":c.severity==="major"?" \u{1F7E1}":"",v=c.author?` \xB7 \u{1F464} ${c.author}`:"",I=i.key.replace("cachly:lesson:best:","");k.push(` - ${S} \`${I}\`${g}${v} \u2014 ${(c.what_worked??"").slice(0,100)}`)}}catch{}if(k.length<2){const x=await ge(_,"cachly:lesson:best:*",{max:1500});for(const i of x.slice(0,300)){const c=await _.get(i);if(!c)continue;const S=$e(c);if(!Se(S)||!(S.file_paths??[]).includes(d))continue;const g=i.replace("cachly:lesson:best:","");if(k.some(e=>e.includes(`\`${g}\``)))continue;const v=S.outcome==="success"?"\u2705":S.outcome==="partial"?"\u26A0\uFE0F":"\u274C",I=S.severity==="critical"?" \u{1F534}":S.severity==="major"?" \u{1F7E1}":"",M=S.author?` \xB7 \u{1F464} ${S.author}`:"";k.push(` - ${v} \`${g}\`${I}${M} \u2014 ${(S.what_worked??"").slice(0,100)}`)}}k.length>0?(A.push("**Related lessons:**"),A.push(...k.slice(0,5))):A.push("**Related lessons:** _None yet_"),A.push("")}return A.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),A.join(`
|
|
58
|
+
`)}case"team_expertise_map":{const{instance_id:f,top_n:t=20}=X,o=await Q(f),_=await ge(o,"cachly:ckg:node:person:*",{max:2e3});if(_.length===0)return["## \u{1F5FA}\uFE0F Team Expertise Map","","No contributors yet.","",'Add `author="handle"` to any `learn_from_attempts` call to start building the map.'].join(`
|
|
59
|
+
`);const A=[];for(const $ of _){const l=await o.get($);if(!l)continue;const u=F(l,null);if(!u||u.type!=="person")continue;const h=await o.smembers(`cachly:ckg:idx:from:${u.id}`),k=new Map;let x=0;for(const i of h){const c=await o.get(i);if(!c)continue;const S=F(c,null);if(!S||S.edgeType!=="authored")continue;x++;const g=S.to.split(":")[0]??"unknown";k.set(g,(k.get(g)??0)+1)}A.push({handle:u.handle,lessonCount:x,domains:k,lastActive:u.last_active})}A.sort(($,l)=>l.lessonCount-$.lessonCount);const d=A.slice(0,t),a=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${d.length}** contributor${d.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[$,l]of d.entries()){const u=$===0?"\u{1F947}":$===1?"\u{1F948}":$===2?"\u{1F949}":`${$+1}`,h=Math.floor((Date.now()-new Date(l.lastActive).getTime())/864e5),k=h<1?"today":h<7?`${h}d ago`:h<30?`${Math.floor(h/7)}w ago`:`${Math.floor(h/30)}mo ago`,x=[...l.domains.entries()].sort((i,c)=>c[1]-i[1]).slice(0,3).map(([i,c])=>`${i}(${c})`).join(", ")||"\u2014";a.push(`| ${u} | **${l.handle}** | ${l.lessonCount} | ${x} | ${k} |`)}return a.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),a.join(`
|
|
60
|
+
`)}case"skill_gaps":{const{instance_id:f,min_failures:t=1}=X,o=await Q(f),_=await ge(o,"cachly:lesson:best:*",{max:3e3}),A=new Map;let d=0,a=0;for(const u of _){const h=await o.get(u);if(!h)continue;const k=$e(h);if(k===null)continue;const x=(k.topic??"").split(":")[0]??"unknown",i=A.get(x)??{successes:0,failures:0,attributed:0,topics:[]};k.outcome==="success"||k.outcome==="partial"?i.successes++:i.failures++,k.author&&(i.attributed++,d++),k.visibility==="private"&&a++,i.topics.push(k.topic??""),A.set(x,i)}const $=[];for(const[u,h]of A)h.failures>=t&&h.successes===0&&$.push({domain:u,type:"unresolved failures",severity:h.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${h.failures} failure${h.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),h.successes+h.failures>=3&&h.attributed===0&&$.push({domain:u,type:"no attribution",severity:"\u{1F535} info",detail:`${h.successes+h.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const l=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${_.length}** lessons scanned \xB7 **${d}** attributed \xB7 **${$.length}** gap${$.length!==1?"s":""} found`,a>0?`_(${a} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if($.length===0)l.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const u=[...$.filter(h=>h.severity.includes("critical")),...$.filter(h=>h.severity.includes("warn")),...$.filter(h=>h.severity.includes("info"))];for(const h of u.slice(0,15))l.push(`${h.severity} **\`${h.domain}\`** \u2014 ${h.type}`),l.push(` ${h.detail}`),l.push("");$.length>15&&l.push(`_\u2026and ${$.length-15} more gaps. Fix critical ones first._`)}return l.push("---",`_Fix gaps with \`learn_from_attempts(topic="${$[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),l.join(`
|
|
61
|
+
`)}case"brain_coverage":{const{instance_id:f,repo_path:t="."}=X,o=await Q(f),[_,A,d]=await Promise.all([ge(o,"cachly:lesson:best:*",{max:5e3}),ge(o,"cachly:ckg:node:person:*",{max:2e3}),ge(o,"cachly:ckg:node:file:*",{max:5e3})]);let a=0,$="n/a";try{const{execSync:g}=await import("node:child_process"),{resolve:v}=await import("node:path"),I=v(t);a=g("git ls-files",{cwd:I,encoding:"utf-8",stdio:"pipe"}).trim().split(`
|
|
62
|
+
`).filter(Boolean).length,$=String(a)}catch{}let l=0,u=0,h=0;const k=new Set;for(const g of _){const v=await o.get(g);if(!v)continue;const I=F(v,{});I.outcome==="success"||I.outcome==="partial"?l++:u++,I.author&&h++,k.add((I.topic??"").split(":")[0]??"unknown")}const x=a>0?`${Math.round(d.length/a*100)}% (${d.length}/${a} files)`:`${d.length} files tracked`,i=_.length>0?Math.round(h/_.length*100):0,c=Math.round(Math.min(1,_.length/50)*25+Math.min(1,l/Math.max(1,_.length))*25+Math.min(1,i/100)*25+Math.min(1,A.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${c>=80?"\u{1F7E2}":c>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${c}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${_.length}** (${l} success \xB7 ${u} failure) |`,`| Problem domains | **${k.size}** |`,`| Attribution | **${h}/${_.length}** (${i}%) |`,`| Contributors | **${A.length}** tracked in knowledge graph |`,`| File coverage | **${x}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,_.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,l/Math.max(1,_.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,i/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,A.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
|
|
63
|
+
`)}case"brain_metrics":{const{instance_id:f}=X,t=await Q(f),[o,_,A,d,a,$]=await Promise.all([t.get(`cachly:stats:born_at:${f}`).catch(()=>null),t.get(`cachly:stats:first_recall_at:${f}`).catch(()=>null),t.get(`cachly:stats:recalls_total:${f}`).catch(()=>null),t.get(`cachly:stats:cross_author_recalls:${f}`).catch(()=>null),t.get(`cachly:stats:time_saved_mins:${f}`).catch(()=>null),t.smembers(`cachly:stats:reuse_pairs:${f}`).catch(()=>[])]);let l={};try{l=await t.hgetall($t(f))??{}}catch{l={}}let u={};try{u=await t.hgetall(ht(f))??{}}catch{u={}}const h={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const N=await t.lrange(lt(f),0,499),O=new Map;for(const te of N){const V=F(te,{ts:"",themen:[]});if(!(!V.ts||!Array.isArray(V.themen)))for(const Z of V.themen){if(h.lieferungen++,!O.has(Z)){const p=await t.get(`cachly:lesson:best:${Z}`).catch(()=>null);O.set(Z,p?F(p,{}):null)}const s=rs(V.ts,O.get(Z)??null);if(s.length===0){h.ohneEreignis++;continue}for(const p of s)h[p]++}}}catch{}let k=0,x=0;try{const N=await t.lrange(`cachly:wirkung:${f}`,0,-1);for(const O of N){const te=F(O,{});x++,te.geholfen===!0&&k++}}catch{}let i={};try{i=await t.hgetall(Rs(f))??{}}catch{i={}}const c=Ds(i,10);let S={token:0,abrufe:0,treffer:0};try{const N=await t.get(Os(f)),O=await t.hgetall(Ps(f))??{};S={token:N??0,abrufe:O.abrufe??0,treffer:O.treffer??0}}catch{}const g=Ls(S);let v;if(o&&_){const N=new Date(_).getTime()-new Date(o).getTime(),O=Math.max(0,Math.round(N/6e4)),te=O<1?"<1 min":O<60?`${O} min`:`${(O/60).toFixed(1)} h`,V=N<=2*6e4?"\u{1F7E2} under 2 min target":N<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";v=`**${te}** from first lesson \u2192 first proven recall \xB7 ${V}`}else o&&!_?v="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":v="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const I=["\u26AA **Nicht gemessen** \u2014 diese Zahl erhebt der Server nicht selbst."," Selbst messen: `npm run bench` in `sdk/mcp`."," Achtung, der Pruefstand hat 17 Lektionen und 13 Fragen \u2014 ein Beispielsatz, kein Bestand."," Auf 498 ECHTEN Lektionen gemessen am 19.08.2026: Precision@1 **30 %** (vorher 15 %)."].join(`
|
|
64
|
+
`),M=Number(A??0),e=Number(d??0),H=M>0?Math.round(e/M*100):0,b=H>=30?"\u{1F7E2} above 30 % target":M===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",ne=Math.round(Number(a??0)),ae=ne<60?`${ne} min`:`${(ne/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",v,"","### 2. Recall-lift _(the moat proof)_",I,"_Reproduce: `npm run bench` \xB7 CI-defended in `rerank.test.ts` \xB7 details in BENCH.md_","","### 3. Team-knowledge-reuse _(the value only a shared brain delivers)_",`**${H}%** of proven recalls used a teammate's lesson (${e}/${M}) \xB7 ${b}`,$.length>0?`**${$.length}** distinct reuse relationship${$.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",Bs(g),"",g.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ae} nicht neu recherchiert \u2014 gerechnet mit 30\u2013240 Min. je Lektion nach Schwere, nicht gemessen. Die Zahl dar\xFCber braucht diese Annahme nicht._`:`_Eine **Sch\xE4tzung** von ${ae} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,M===0?'_Tip: pass `author="your-handle"` to `smart_recall` so cross-author reuse can be tracked._':"_These numbers compound: every learned lesson and every teammate raises all three._","","### \u2696\uFE0F Die drei Ausgaenge der Suche _(gezaehlt, nicht behauptet)_",(()=>{const N=Number(l.beantwortet??0),O=Number(l.knapp??0),te=Number(l.schweigen??0),V=N+O+te;if(V===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const Z=s=>`${Math.round(100*s/V)} %`;return`**${V}** Suchen: ${Z(N)} beantwortet \xB7 ${Z(O)} als knapper Sieg markiert \xB7 ${Z(te)} ehrliches Nein. (Ob ein Nein stimmt, zeigt nur die Stichprobe \u2014 die Rate hier zaehlt, sie urteilt nicht.)`})(),"","### \u{1F53D} Recall-Trichter _(je Fehlschlag: WORAN scheiterte der Abruf)_",(()=>{const N=Z=>Number(u[Z]??0),O=[["nicht-gesucht","nicht gesucht"],["nominierung","Nominierung (gesucht, nichts geliefert)"],["ranking","Ranking (geliefert, das Richtige fehlte)"],["anwendung","Anwendung (das Richtige lag vor)"],["ohne-vorwissen","ohne Vorwissen (es gab nichts zu finden)"]],te=O.reduce((Z,[s])=>Z+N(s),0);if(te===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const V=O.filter(([Z])=>Z!=="ohne-vorwissen").sort((Z,s)=>N(s[0])-N(Z[0]))[0];return`**${te}** klassifizierte Fehlschlaege: `+O.map(([Z,s])=>`${N(Z)} ${s}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${V[1]}** (${N(V[0])}) \u2014 dorthin gehoert das naechste Investment. (Heuristik je Einzelfall; erst die Verteilung ueber viele Sessions traegt.)`})(),"","### \u{1F3F7}\uFE0F Drei Etiketten ohne Selbstauskunft _(widersprochen \xB7 korrigiert \xB7 veraltet)_",h.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${h.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${h.widersprochen} widersprochen \xB7 ${h.korrigiert} korrigiert \xB7 ${h.veraltet} veraltet \xB7 ${h.ohneEreignis} ohne spaeteres Ereignis. (Kein Etikett heisst: nichts ist passiert \u2014 nicht "benutzt". Das vierte Etikett haette nur eine geschmeichelte Fassung.)`,"","### \u2696\uFE0F Netto-verhinderter-Schaden _(kann negativ werden \u2014 sonst misst es nichts)_",(()=>{const N=Number(h.widersprochen)+Number(h.veraltet);if(x===0&&N===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const O=k-N;return`**${O>=0?"+":""}${O}** = ${k} bestaetigt geholfen (Wirkungsspur, ${x} Eintraege) \u2212 ${N} Schadenslieferungen (${h.widersprochen} spaeter widerlegt + ${h.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",Ms(c,Hs.length),...c.spitze.length>0?c.spitze.map((N,O)=>` ${String(O+1).padStart(2)}. \`${N.name}\` \u2014 ${N.aufrufe}\xD7 (${Math.round(N.anteil*100)} %)`):[]].filter(Boolean).join(`
|
|
65
|
+
`)}case"brain_service_map":{const{instance_id:f,service:t}=X;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const o=await Q(f),_=`service:${le(t.trim())}`,A=await o.get(`cachly:ckg:node:${_}`).catch(()=>null),d=A?F(A,null):null,a=await o.smembers(`cachly:ckg:idx:to:${_}`).catch(()=>[]),$=[],l=[],u=[];for(const v of a){const I=await o.get(v).catch(()=>null);if(!I)continue;const M=F(I,null);if(M)if(M.edgeType==="operates"){const e=await o.get(`cachly:ckg:node:${M.from}`).catch(()=>null),H=e?F(e,null):null;H?.handle&&$.push({handle:H.handle,trials:M.trials})}else if(M.edgeType==="runs_in"){const e=await o.get(`cachly:ckg:node:${M.from}`).catch(()=>null),H=e?F(e,null):null;H?.path&&l.push({path:H.path,trials:M.trials})}else M.edgeType==="affects"&&u.push({id:M.from,confidence:M.confidence})}$.sort((v,I)=>I.trials-v.trials),l.sort((v,I)=>I.trials-v.trials),u.sort((v,I)=>I.confidence-v.confidence);const h=[],k=await ge(o,"cachly:lesson:best:*",{max:1500}),x=t.trim().toLowerCase();for(const v of k.slice(0,400)){const I=await o.get(v).catch(()=>null);if(!I)continue;const M=$e(I);Se(M)&&(M.service??"").toLowerCase()===x&&h.push({...M,topic:v.replace("cachly:lesson:best:","")})}if(!d&&h.length===0&&$.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${t}\``,"","Nothing known about this service yet.","","Tag lessons with the service they concern so the brain can build this map:",`\`learn_from_attempts(topic="...", service="${t}", author="you", file_paths=[...])\``].join(`
|
|
66
|
+
`);const i=d?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${d?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${t}\``,"",d?`_${i} \xB7 ${d.count} lesson${d.count!==1?"s":""} referenced \xB7 domain: ${d.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if($.length>0){const v=$.slice(0,5).map((I,M)=>`${M===0?"\u{1F947}":M===1?"\u{1F948}":M===2?"\u{1F949}":`${M+1}.`} **${I.handle}** (${I.trials}\xD7)`).join(" \xB7 ");c.push(`**Operators:** ${v}`,"")}else c.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const S=h.filter(v=>v.outcome==="failure"),g=h.filter(v=>v.outcome!=="failure");if(S.length>0){c.push(`**\u26A0\uFE0F Known failures (${S.length}):**`);for(const v of S.slice(0,6)){const I=v.severity==="critical"?" \u{1F534}":v.severity==="major"?" \u{1F7E1}":"",M=v.author?` \xB7 \u{1F464} ${v.author}`:"";c.push(` - \u274C \`${v.topic}\`${I}${M} \u2014 ${(v.what_worked??"").slice(0,100)}`)}c.push("")}if(g.length>0){c.push(`**\u2705 Proven fixes (${g.length}):**`);for(const v of g.slice(0,6)){const I=v.outcome==="partial"?"\u26A0\uFE0F":"\u2705",M=v.author?` \xB7 \u{1F464} ${v.author}`:"";c.push(` - ${I} \`${v.topic}\`${M} \u2014 ${(v.what_worked??"").slice(0,100)}`)}c.push("")}return l.length>0&&c.push(`**Files in this service:** ${l.slice(0,8).map(v=>`\`${v.path}\``).join(", ")}`,""),c.push("---",`_Tag lessons with \`service="${t}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),c.join(`
|
|
67
|
+
`)}case"brain_collab_pairs":{const{instance_id:f,min_weight:t=1}=X,o=await Q(f),_=typeof t=="number"&&t>=1?Math.floor(t):1,A=await ge(o,"cachly:ckg:node:person:*",{max:500}),d=new Map;for(const k of A){const x=await o.get(k);if(!x)continue;const i=F(x,null);!i||i.type!=="person"||d.set(i.id,{id:i.id,handle:i.handle,domain:i.domain,count:i.count})}if(d.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
|
|
68
|
+
`);const a=new Map;for(const[k,x]of d){const i=await o.smembers(`cachly:ckg:idx:from:${k}`);for(const c of i){const S=await o.get(c);if(!S)continue;const g=F(S,null);if(!g||g.edgeType!=="collaborates")continue;const v=d.get(g.to);if(!v)continue;const[I,M]=k<g.to?[k,g.to]:[g.to,k],e=`${I}||${M}`,H=a.get(e);if(H)H.trials+=g.trials;else{const[b,ne]=k<g.to?[x,v]:[v,x];a.set(e,{a:b,b:ne,trials:g.trials,confidence:g.confidence})}}}const $=[...a.values()].filter(k=>k.trials>=_).sort((k,x)=>x.trials-k.trials),l=new Set;for(const k of $)l.add(k.a.id),l.add(k.b.id);const u=[...d.values()].filter(k=>!l.has(k.id)),h=["## \u{1F91D} Team Collaboration Graph",""];if($.length===0)h.push(`No collaboration pairs yet (min weight: ${_}).`,"","Pairs appear when two contributors touch the same file in `learn_from_attempts`",'or when someone recalls a teammate\'s lesson via `smart_recall(requester="...")`.');else{h.push(`**${$.length} collaboration pair${$.length!==1?"s":""}** across ${l.size} contributor${l.size!==1?"s":""}:`,"");for(const k of $.slice(0,20)){const x=(k.confidence*100).toFixed(0),i=[k.a.domain,k.b.domain].filter((c,S,g)=>c&&g.indexOf(c)===S).map(c=>`\`${c}\``).join(", ");h.push(`### @${k.a.handle} \u2194 @${k.b.handle}`,`- **${k.trials} collaboration event${k.trials!==1?"s":""}** \xB7 ${x}% confidence`,`- Domains: ${i||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${k.a.handle}** und **@${k.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}$.length>20&&h.push(`_...and ${$.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return u.length>0&&h.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${u.length} contributor${u.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...u.slice(0,10).map(k=>`- **@${k.handle}** \u2014 ${k.count} lesson${k.count!==1?"s":""} \xB7 domain: \`${k.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),h.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),h.join(`
|
|
69
|
+
`)}case"brain_portability":{const{instance_id:f}=X,t=[{name:"Claude Code",slug:"claude-code",icon:"\u{1F916}",configPath:"~/.claude/settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"Cursor",slug:"cursor",icon:"\u{1F5B1}\uFE0F",configPath:"~/.cursor/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"Windsurf",slug:"windsurf",icon:"\u{1F3C4}",configPath:"~/.windsurf/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"GitHub Copilot (VS Code)",slug:"copilot",icon:"\u{1F419}",configPath:".vscode/mcp.json (workspace)",configBlock:JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"Cline",slug:"cline",icon:"\u26A1",configPath:"~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"Zed",slug:"zed",icon:"\u26A1",configPath:"~/.config/zed/settings.json",configBlock:JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["@cachly-dev/mcp-server@latest"]},env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}}},null,2)},{name:"Continue",slug:"continue",icon:"\u25B6\uFE0F",configPath:"~/.continue/config.json",configBlock:JSON.stringify({mcpServers:[{name:"cachly",command:"npx @cachly-dev/mcp-server@latest",env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:f}}]},null,2)}],o=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${f}\``,"","Replace `<cky_live_...>` below with your own API key (get one at https://cachly.dev/setup-ai) \u2014 the Brain ID alone does not authenticate you.","","This Brain ID is model-agnostic. Every lesson you've learned, every Memory Crystal you've distilled,","and every prediction from your Causal Knowledge Graph is accessible from **any MCP-compatible AI client**.","","---","",`### Compatible Clients (${t.length} supported)`,""];for(const _ of t)o.push(`#### ${_.icon} ${_.name}`,`Config: \`${_.configPath}\``,"","```json",_.configBlock,"```","");return o.push("---","","### What travels with you","","| Data | Model-neutral? |","|------|---------------|","| Lessons (learn_from_attempts) | \u2705 Full access in all clients |","| Memory Crystals (memory_crystalize) | \u2705 Included in every session_start |","| Causal Knowledge Graph (brain_predict) | \u2705 Same graph, same predictions |","| Team lessons (team_learn, team_confirm) | \u2705 Team is per-Brain, not per-model |","| Domain Brain Marketplace installs | \u2705 Installed once, available everywhere |","| Session handoffs (session_handoff) | \u2705 Cross-client continuity |","","---","","### One-command setup for any new client","","```bash","npx @cachly-dev/mcp-server@latest autopilot","```","",`Autopilot detects all installed editors and writes the config for each \u2014 with your \`${f}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),o.join(`
|
|
70
|
+
`)}case"brain_changelog":{const{instance_id:f,days:t=7,max_lessons:o=30,include_failures:_=!0}=X,A=await Q(f),d=Date.now()-Number(t)*864e5,a=await ge(A,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),$=[];for(const c of a){const S=await A.get(c).catch(()=>null);if(!S)continue;const g=F(S,{});if((g.ts?new Date(g.ts).getTime():0)<d||!_&&g.outcome==="failure")continue;const I=c.replace("cachly:lesson:best:","");$.push({...g,topic:I})}$.sort((c,S)=>{const g=c.ts?new Date(c.ts).getTime():0;return(S.ts?new Date(S.ts).getTime():0)-g});const l=$.slice(0,Number(o));if(l.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${t} day${Number(t)!==1?"s":""}`,"","_No new lessons learned in this window. Your Brain already knows everything it knows \u2014 add new lessons with `learn_from_attempts`._"].join(`
|
|
71
|
+
`);const u=new Map;for(const c of l){const S=c.topic.includes(":")?c.topic.split(":")[0]:"general",g=u.get(S)??[];g.push(c),u.set(S,g)}const h=c=>c==="critical"?"\u{1F6A8}":c==="major"?"\u26A0\uFE0F":c==="minor"?"\u{1F4A1}":"\u2728",k=c=>c==="failure"?"\u274C":c==="partial"?"\u{1F536}":"\u2705",i=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${t} day${Number(t)!==1?"s":""})`,"",`_${l.length} lesson${l.length!==1?"s":""} learned across ${u.size} topic area${u.size!==1?"s":""}_`,""];for(const[c,S]of Array.from(u.entries()).sort((g,v)=>v[1].length-g[1].length)){i.push(`### ${c}`),i.push("");for(const g of S){const v=g.outcome==="failure"?k(g.outcome):h(g.severity),I=g.outcome==="failure"?g.what_failed:g.what_worked,M=[];g.author&&M.push(`by **${g.author}**`),g.recall_count&&M.push(`${g.recall_count} recall${g.recall_count!==1?"s":""}`),g.confidence!==void 0&&M.push(`${Math.round(g.confidence*100)}% confidence`),i.push(`- ${v} **${g.topic}**${I?` \u2014 ${I}`:""}`),M.length&&i.push(` _${M.join(" \xB7 ")}_`)}i.push("")}return i.push("---",`_Generated from Brain \`${f}\` \xB7 Share this in your standup or Slack_`),i.join(`
|
|
72
|
+
`)}case"brain_set_pref":{const{instance_id:f,key:t,value:o}=X;if(!t||!t.trim())throw new Error("key is required");const _=await Q(f),A=`cachly:prefs:${t.trim()}:${f}`;return await _.set(A,String(o)),`\u2705 Preference \`${t}\` set to \`${o}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:f,key:t}=X,o=await Q(f);if(t&&t.trim()){const a=await o.get(`cachly:prefs:${t.trim()}:${f}`).catch(()=>null);return a===null?`\u2139\uFE0F Preference \`${t}\` is not set (using default).`:`\u{1F527} Preference \`${t}\` = \`${a}\``}const _=await ge(o,`cachly:prefs:*:${f}`,{max:200,timeoutMs:2e3});if(_.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const A=await o.mget(..._),d=["\u{1F527} **Brain preferences:**",""];for(let a=0;a<_.length;a++){const $=_[a].replace("cachly:prefs:","").replace(`:${f}`,"");d.push(`- \`${$}\` = \`${A[a]??"(null)"}\``)}return d.join(`
|
|
73
|
+
`)}default:return null}}export{Pn as BRAIN_TOOL_NAMES,jn as handleBrainTool,st as recallVorschau};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const E=75,o=.5,t=.7,L=1,
|
|
1
|
+
const E=75,o=.5,t=.7,L="qwen3-embedding:0.6b",_=1,e=.8,N=1,n=.35,G=.35,I=.05,T=1;export{I as ABLEHN_ABSTAND,G as CKG_BELEG_SCHWELLE,o as EINGANG_SCHWELLE,t as EINGANG_SORTIER_GEWICHT,T as SELTENHEIT_LAENGE_B,n as SINN_BELEG_SCHWELLE,E as SINN_TOPF,N as WORT_BELEG_SCHWELLE,_ as ZWEIT_GEWICHT,e as ZWEIT_MINDESTDECKUNG,L as ZWEIT_MODELL};
|
package/glama.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cachly-dev/mcp-server",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.145",
|
|
4
4
|
"mcpName": "io.github.cachly-dev/mcp-server",
|
|
5
5
|
"description": "Your AI forgets everything between sessions. cachly fixes that permanently: 123 MCP tools for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run. Arrives pre-briefed. Free tier forever, EU servers, GDPR.",
|
|
6
6
|
"type": "module",
|
package/server.json
CHANGED
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
"url": "https://github.com/cachly-dev/cachly-mcp",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.10.
|
|
9
|
+
"version": "0.10.145",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"name": "@cachly-dev/mcp-server",
|
|
14
14
|
"identifier": "@cachly-dev/mcp-server",
|
|
15
|
-
"version": "0.10.
|
|
15
|
+
"version": "0.10.145",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|