@cachly-dev/mcp-server 0.10.229 → 0.10.230
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/ambient-hooks.js +10 -9
- package/dist/src/embeddings.js +4 -4
- package/dist/src/handlers/brain.js +59 -59
- package/glama.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`)}function
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`,"utf-8")),{
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`,"utf-8")}return
|
|
9
|
-
|
|
1
|
+
import{existsSync as w,readFileSync as j}from"node:fs";import{readFile as v,writeFile as E,chmod as M,mkdir as N}from"node:fs/promises";import{dirname as K,resolve as l}from"node:path";import{fileURLToPath as nt}from"node:url";import{CURSOR_FLAG as rt}from"./cursor-hook.js";import{COPILOT_FLAG as st,COPILOT_HOOK_EVENTS as it}from"./copilot-hook.js";import{CODEX_FLAG as ct,CODEX_HOOK_EVENTS as at}from"./codex-hook.js";import{GEMINI_FLAG as ut,GEMINI_HOOK_EVENTS as pt}from"./gemini-hook.js";import{istCachlyEintrag as J}from"./hook-zugang.js";const B="v5",oo="ambient-recall",S="cachly-ambient-einblendung.mjs";function C(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function I(t,o){return["#!/usr/bin/env node",`// cachly Ambient Recall \u2014 ${t} ${B}`,"// Pushes relevant memory into context automatically. Cross-platform Node hook","// (no shell script \u2014 runs identically on Windows/macOS/Linux). Never blocks","// the agent: every failure path exits 0 with no output (graceful degrade).",`// Runs the hook bundle next to this file (${S}) in this process.`,`process.env.CACHLY_BRAIN_INSTANCE_ID = '${C(o.instanceId)}';`,`process.env.CACHLY_HOOK_EVENT = '${C(t)}';`,`process.argv.splice(2, process.argv.length, '${C(t)}');`,"try {",` await import('./${S}');`,"} catch {"," process.exit(0);","}"].join(`
|
|
2
|
+
`)}const mt="__CACHLY_EREIGNIS__",lt="__CACHLY_INSTANZ__",eo="cachly-ambient-vorlage.mjs";function no(){return I(mt,{instanceId:lt})}function V(){const t=K(nt(import.meta.url));for(const o of[l(t,"..",L,S),l(t,"..","..",L,S)])if(w(o))return o;return null}function St(t){return I("SessionStart",t)}function ft(t){return I("UserPromptSubmit",t)}function ht(t){return I("PreToolUse",t)}function dt(t){return I("Stop",t)}const bt={SessionStart:30,UserPromptSubmit:10,PreToolUse:10,Stop:60},gt="Edit|Write|MultiEdit|NotebookEdit";function R(t,o){const e=(n,i,p)=>({...p?{matcher:p}:{},hooks:[{type:"command",command:`node "${i}"${o?` ${o(n)}`:""}`,timeout:bt[n]}]}),s={SessionStart:[e("SessionStart",t.sessionStart)],UserPromptSubmit:[e("UserPromptSubmit",t.userPromptSubmit)]};return t.preToolUse&&(s.PreToolUse=[e("PreToolUse",t.preToolUse,gt)]),t.stop&&(s.Stop=[e("Stop",t.stop)]),s}const $=".claude/hooks",Ot=".claude/settings.json",D={SessionStart:"cachly-ambient-session-start.mjs",UserPromptSubmit:"cachly-ambient-prompt-submit.mjs",PreToolUse:"cachly-ambient-pre-tool.mjs",Stop:"cachly-ambient-stop.mjs"},kt=".claude/hooks/cachly-ambient-",ro="cachly-ambient-settings.vorlage.json";function so(){const t=e=>`\${CLAUDE_PROJECT_DIR}/${$}/${D[e]}`,o=R({sessionStart:t("SessionStart"),userPromptSubmit:t("UserPromptSubmit"),preToolUse:t("PreToolUse"),stop:t("Stop")});return`${JSON.stringify(o,null,2)}
|
|
3
|
+
`}function _t(t,o){const e=t.hooks??[];return e.length>0&&e.every(s=>{const n=s.command??"";return n.replace(/\\/g,"/").includes(kt)||o.has(n)||[...o].some(i=>n.includes(`"${i}"`))})}function Et(t,o){const e={...t,hooks:{...t.hooks??{}}},s=e.hooks,n=R(o),i=new Set([o.sessionStart,o.userPromptSubmit,o.preToolUse,o.stop].filter(c=>!!c));for(const[c,r]of Object.entries(n)){const u=(Array.isArray(s[c])?s[c]:[]).filter(f=>!_t(f,i));s[c]=[...u,...r]}const p=JSON.stringify(e)!==JSON.stringify(t);return{settings:e,changed:p}}async function io(t,o,e,s={}){const n=l(t,$),i={instanceId:o,apiKey:e},p=["SessionStart","UserPromptSubmit","PreToolUse","Stop"],c={SessionStart:St(i),UserPromptSubmit:ft(i),PreToolUse:ht(i),Stop:dt(i)},r=a=>l(n,D[a]),u=V();if(!u)throw new Error(`cachly hook bundle ${S} missing from the package`);const f=j(u,"utf-8"),d=l(n,S),k=async a=>{try{return await v(a,"utf-8")}catch{return""}},y=l(t,Ot),T=w(y);let b={};if(T){const a=await k(y);try{const g=a.charCodeAt(0)===65279?a.slice(1):a,_=g.trim()?JSON.parse(g):{};if(!H(_))throw new O("is not a JSON object");if(_.hooks!==void 0&&!H(_.hooks))throw new O('has a "hooks" field that is not an object');b=_}catch(g){const _=g instanceof O?g.message:/^\s*\/\/|\/\*/m.test(a)?"has comments, and cachly only rewrites plain JSON":"is not valid JSON";return{sessionStartPath:r("SessionStart"),promptSubmitPath:r("UserPromptSubmit"),preToolUsePath:r("PreToolUse"),stopPath:r("Stop"),bundlePath:d,scripts:"unchanged",settings:"skipped",grund:_}}}let m=!1,h=await k(d)===f;for(const a of p){const g=await k(r(a));g&&(m=!0),g!==c[a]+`
|
|
4
|
+
`&&(h=!1)}const G=h?"unchanged":m?"upgraded":"written";if(G!=="unchanged"){await N(n,{recursive:!0}),await E(d,f,"utf-8");for(const a of p)await E(r(a),c[a]+`
|
|
5
|
+
`,"utf-8"),await M(r(a),493).catch(()=>{})}const x=a=>s.portable!==!1?`\${CLAUDE_PROJECT_DIR}/${$}/${D[a]}`:r(a),{settings:ot,changed:et}=Et(b,{sessionStart:x("SessionStart"),userPromptSubmit:x("UserPromptSubmit"),preToolUse:x("PreToolUse"),stop:x("Stop")});let P;return T?et?P="merged":P="unchanged":P="written",P!=="unchanged"&&(await N(l(t,".claude"),{recursive:!0}),await E(y,JSON.stringify(ot,null,2)+`
|
|
6
|
+
`,"utf-8")),{sessionStartPath:r("SessionStart"),promptSubmitPath:r("UserPromptSubmit"),preToolUsePath:r("PreToolUse"),stopPath:r("Stop"),bundlePath:d,scripts:G,settings:P}}const F=".cursor/hooks",Tt=".cursor/hooks.json",X="cachly-ambient-cursor.mjs",Pt={sessionStart:30,beforeSubmitPrompt:10,postToolUse:5};function U(t,o,e,s){return["#!/usr/bin/env node",`// cachly Ambient Recall \u2014 ${t} ${B}`,`// Einblendung fuer ${t}: ${e.join(", ")}.`,"// Blockiert nie: jeder Fehler endet mit Exit 0. Ruft das Buendel daneben",`// (${S}) in diesem Prozess.`,`process.env.CACHLY_BRAIN_INSTANCE_ID = '${C(s.instanceId)}';`,`process.argv.push('${o}');`,"try {",` await import('./${S}');`,"} catch {"," process.exit(0);","}"].join(`
|
|
7
|
+
`)}function It(t){return U("Cursor",rt,["sessionStart","beforeSubmitPrompt","postToolUse"],t)}function yt(){const t=o=>[{command:`node ${F}/${X} ${o}`,timeout:Pt[o]}];return{sessionStart:t("sessionStart"),beforeSubmitPrompt:t("beforeSubmitPrompt"),postToolUse:t("postToolUse")}}function xt(t){return Y(t,yt())}function Y(t,o){const e={...t.hooks??{}};for(const[n,i]of Object.entries(o)){Z(e[n],n);const p=(e[n]??[]).filter(c=>!J(c));e[n]=[...p,...i]}const s={...t,version:typeof t.version=="number"?t.version:1,hooks:e};return{datei:s,changed:JSON.stringify(s)!==JSON.stringify(t)}}function z(t,o){const e={...t.hooks??{}};for(const[n,i]of Object.entries(o)){Z(e[n],n);const p=(e[n]??[]).flatMap(c=>{const r=c?.hooks;if(!Array.isArray(r))return[c];const u=r.filter(f=>!J(f));return u.length===r.length?[c]:u.length?[{...c,hooks:u}]:[]});e[n]=[...p,...i]}const s={...t,hooks:e};return{datei:s,changed:JSON.stringify(s)!==JSON.stringify(t)}}async function A(t){const o=l(t.projectDir,t.hookDir),e=V();if(!e)throw new Error(`cachly hook bundle ${S} missing from the package`);const s=j(e,"utf-8"),n=l(o,S),i=l(o,t.skriptName),p=t.skript+`
|
|
8
|
+
`,c=async m=>{try{return await v(m,"utf-8")}catch{return""}},r=l(t.projectDir,t.configDatei),u=w(r)?await c(r):"",f=!u.trim();let d;try{const m=u.charCodeAt(0)===65279?u.slice(1):u,h=f?{}:JSON.parse(m);if(!H(h))throw new O("is not a JSON object");if(h.hooks!==void 0&&!H(h.hooks))throw new O('has a "hooks" field that is not an object');d=t.merge(h,i)}catch(m){const h=m instanceof O?m.message:/^\s*\/\/|\/\*/m.test(u)?"has comments, and cachly only rewrites plain JSON":"is not valid JSON";return{scriptPath:i,bundlePath:n,hooksPath:r,scripts:"unchanged",hooks:"skipped",grund:h}}await N(o,{recursive:!0});const k=await c(i),T=k===p&&await c(n)===s?"unchanged":k?"upgraded":"written";T!=="unchanged"&&(await E(n,s,"utf-8"),await E(i,p,"utf-8"),await M(i,493).catch(()=>{}));let b;if(f?b="written":d.changed?b="merged":b="unchanged",b!=="unchanged"){const m=/^([ \t]+)"/m.exec(u)?.[1]??2;await N(K(r),{recursive:!0}),await E(r,JSON.stringify(d.datei,null,m)+`
|
|
9
|
+
`,"utf-8")}return{scriptPath:i,bundlePath:n,hooksPath:r,scripts:T,hooks:b}}function H(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}class O extends Error{}function Z(t,o){if(t!==void 0&&!Array.isArray(t))throw new O(`has a "hooks.${o}" entry that is not a list`)}async function co(t,o){return A({projectDir:t,hookDir:F,skriptName:X,skript:It({instanceId:o}),configDatei:Tt,merge:e=>xt(e)})}const W=".github/hooks",Nt=".github/hooks/cachly-ambient.json",Q="cachly-ambient-copilot.mjs",Ct={sessionStart:30,userPromptSubmitted:10,postToolUse:5};function Ut(t){return U("VS Code / Copilot",st,it,t)}function At(){const t=o=>[{type:"command",command:`node ${W}/${Q} ${o}`,cwd:".",timeoutSec:Ct[o]}];return{sessionStart:t("sessionStart"),userPromptSubmitted:t("userPromptSubmitted"),postToolUse:t("postToolUse")}}function Ht(t){return Y(t,At())}async function ao(t,o){return A({projectDir:t,hookDir:W,skriptName:Q,skript:Ut({instanceId:o}),configDatei:Nt,merge:e=>Ht(e)})}const wt=".codex/hooks",Rt=".codex/hooks.json",$t="cachly-ambient-codex.mjs",Dt={SessionStart:30,UserPromptSubmit:10};function Lt(t){return U("Codex",ct,at,t)}function Gt(t){const o=e=>[{hooks:[{type:"command",command:`node "${t}" ${e}`,timeout:Dt[e]}]}];return{SessionStart:o("SessionStart"),UserPromptSubmit:o("UserPromptSubmit")}}function jt(t,o){return z(t,Gt(o))}async function uo(t,o){return A({projectDir:t,hookDir:wt,skriptName:$t,skript:Lt({instanceId:o}),configDatei:Rt,merge:(e,s)=>jt(e,s)})}const q=".gemini/hooks",vt=".gemini/settings.json",tt="cachly-ambient-gemini.mjs",Mt={SessionStart:3e4,BeforeAgent:1e4},Kt={SessionStart:"cachly-briefing",BeforeAgent:"cachly-recall"};function Jt(t){return U("Gemini CLI",ut,pt,t)}function Bt(){const t=o=>[{hooks:[{name:Kt[o],type:"command",command:`node ${q}/${tt} ${o}`,timeout:Mt[o]}]}];return{SessionStart:t("SessionStart"),BeforeAgent:t("BeforeAgent")}}function Vt(t){return z(t,Bt())}async function po(t,o){return A({projectDir:t,hookDir:q,skriptName:tt,skript:Jt({instanceId:o}),configDatei:vt,merge:e=>Vt(e)})}const mo=["SessionStart","UserPromptSubmit","Stop"],L="hooks";function lo(){const t=`\${CLAUDE_PLUGIN_ROOT}/${L}/${S}`,o=R({sessionStart:t,userPromptSubmit:t,stop:t},e=>`${e} --plugin`);return JSON.stringify({hooks:o},null,2)+`
|
|
10
|
+
`}export{oo as AMBIENT_CLI_SUBCOMMAND,B as AMBIENT_HOOK_VERSION,$ as CLAUDE_HOOK_DIR,Ot as CLAUDE_SETTINGS_DATEI,Rt as CODEX_HOOKS_DATEI,wt as CODEX_HOOK_DIR,$t as CODEX_SKRIPT,Dt as CODEX_TIMEOUTS,Nt as COPILOT_HOOKS_DATEI,W as COPILOT_HOOK_DIR,Q as COPILOT_SKRIPT,Ct as COPILOT_TIMEOUTS,Tt as CURSOR_HOOKS_DATEI,F as CURSOR_HOOK_DIR,X as CURSOR_SKRIPT,Pt as CURSOR_TIMEOUTS,q as GEMINI_HOOK_DIR,vt as GEMINI_SETTINGS_DATEI,tt as GEMINI_SKRIPT,Mt as GEMINI_TIMEOUTS_MS,S as HOOK_BUENDEL,eo as HOOK_VORLAGE,L as PLUGIN_HOOK_DIR,mo as PLUGIN_HOOK_EVENTS,gt as PRE_TOOL_USE_MATCHER,ro as SETTINGS_VORLAGE,mt as VORLAGE_EREIGNIS,lt as VORLAGE_INSTANZ,no as buildAmbientHookVorlage,R as buildAmbientSettingsHooks,so as buildAmbientSettingsVorlage,Lt as buildCodexHook,Gt as buildCodexHooks,Ut as buildCopilotHook,At as buildCopilotHooks,It as buildCursorHook,yt as buildCursorHooks,Jt as buildGeminiHook,Bt as buildGeminiHooks,lo as buildPluginHooksJson,ht as buildPreToolUseHook,St as buildSessionStartHook,dt as buildStopHook,ft as buildUserPromptSubmitHook,V as hookBuendelQuelle,io as installAmbientHooks,uo as installCodexHooks,ao as installCopilotHooks,co as installCursorHooks,po as installGeminiHooks,Et as mergeAmbientSettings,jt as mergeCodexHooks,Ht as mergeCopilotHooks,xt as mergeCursorHooks,Vt as mergeGeminiHooks};
|
package/dist/src/embeddings.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{zeitpunkt as
|
|
1
|
+
import{zeitpunkt as h}from"./zeitmessung.js";const i={apiUrl:process.env.CACHLY_API_URL??"https://api.cachly.dev",jwt:process.env.CACHLY_JWT??"",model:process.env.CACHLY_EMBED_MODEL??""};function R(n){i.jwt=n,n&&!I&&d==="none"&&(d="cachly")}const A=Number(process.env.CACHLY_EMBED_TIMEOUT_MS??8e3),p=Number(process.env.CACHLY_EMBED_TIMEOUT_MAX_MS??45e3),g=12;function f(n,r){return r==="kurz"?A:Math.min(p,A+n.length*g)}function b(){return process.env.CACHLY_JWT?"cachly":process.env.OLLAMA_BASE_URL?"ollama":"none"}const I=!!process.env.CACHLY_EMBED_PROVIDER;let d=(process.env.CACHLY_EMBED_PROVIDER??b()).toLowerCase();async function w(n,r,s){const c=f(n,r);switch(d){case"cachly":{if(!i.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 e=`${i.apiUrl}/api/v1/embed`,o={text:
|
|
7
|
+
ollama \u2192 OLLAMA_BASE_URL (local, no key needed)`);const e=`${i.apiUrl}/api/v1/embed`,o={text:n};(s??i.model)&&(o.model=s??i.model);const t=process.env.CACHLY_ADMIN_KEY??"",a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.jwt}`,...t?{"X-Admin-Key":t}:{}},body:JSON.stringify(o),signal:AbortSignal.timeout(c)});if(!a.ok){const _=await a.text();let m=null;const E=Number(a.headers.get("retry-after"));if(Number.isFinite(E)&&E>=0)m=E;else try{const u=JSON.parse(_);typeof u.retry_after=="number"&&u.retry_after>=0&&(m=u.retry_after)}catch{}throw Object.assign(new Error(`Cachly embed API error ${a.status}: ${_.slice(0,200)}`),{status:a.status,retryAfterSek:m})}return(await a.json()).embedding}case"mistral":{const e=process.env.MISTRAL_API_KEY;if(!e)throw new Error("MISTRAL_API_KEY not set");const o=i.model!=="text-embedding-3-small"?i.model:"mistral-embed",t=await fetch("https://api.mistral.ai/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:o,input:[n]}),signal:AbortSignal.timeout(c)});if(!t.ok)throw new Error(`Mistral embedding error: ${t.statusText}`);const a=await t.json();if(!a.data?.[0]?.embedding)throw new Error("Mistral returned empty embedding response");return a.data[0].embedding}case"cohere":{const e=process.env.COHERE_API_KEY;if(!e)throw new Error("COHERE_API_KEY not set");const o=i.model!=="text-embedding-3-small"?i.model:"embed-english-v3.0",t=await fetch("https://api.cohere.com/v2/embed",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:o,texts:[n],input_type:"search_query",embedding_types:["float"]}),signal:AbortSignal.timeout(c)});if(!t.ok)throw new Error(`Cohere embedding error: ${t.statusText}`);return(await t.json()).embeddings.float[0]}case"ollama":{const e=process.env.OLLAMA_BASE_URL??"http://localhost:11434",o=s??(i.model!=="text-embedding-3-small"?i.model:"nomic-embed-text"),t=await fetch(`${e}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o,prompt:n}),signal:AbortSignal.timeout(c)});if(!t.ok)throw new Error(`Ollama embedding error: ${t.statusText}`);return(await t.json()).embedding}case"gemini":{const e=process.env.GEMINI_API_KEY;if(!e)throw new Error("GEMINI_API_KEY not set");const o=i.model!=="text-embedding-3-small"?i.model:"text-embedding-004",t=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${o}:embedContent?key=${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`models/${o}`,content:{parts:[{text:n}]}}),signal:AbortSignal.timeout(c)});if(!t.ok)throw new Error(`Gemini embedding error: ${t.statusText}`);return(await t.json()).embedding.values}case"openai":{const e=process.env.OPENAI_API_KEY;if(!e)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 o=i.model||"text-embedding-3-small",t=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:o,input:
|
|
13
|
-
Supported: cachly (default), openai, mistral, cohere, ollama, gemini`)}}const
|
|
12
|
+
CACHLY_EMBED_PROVIDER=cachly (server-side, no key needed)`);const o=i.model||"text-embedding-3-small",t=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:o,input:n}),signal:AbortSignal.timeout(c)});if(!t.ok)throw new Error(`OpenAI embedding error: ${t.statusText}`);const a=await t.json();if(!a.data?.[0]?.embedding)throw new Error("OpenAI returned empty embedding response");return a.data[0].embedding}default:throw new Error(`Unknown CACHLY_EMBED_PROVIDER="${d}".
|
|
13
|
+
Supported: cachly (default), openai, mistral, cohere, ollama, gemini`)}}const y=3,C=4;function M(n){const r=n;if(typeof r?.status=="number")return r.status===429||r.status>=500;if(r?.name==="TimeoutError"||r?.name==="AbortError")return!1;if(/fetch failed/i.test(String(r?.message??"")))return!0;const s=r?.cause?.code??"";return["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","EPIPE","UND_ERR_SOCKET"].includes(s)}function O(n,r,s){if(r>=(s==="lang"?C:y)||!M(n))return null;const e=n?.retryAfterSek;if(typeof e=="number"&&Number.isFinite(e)&&e>=0){const o=e*1e3;return s==="kurz"?o<=2e3?o:null:Math.min(o,61e3)}return s==="lang"?Math.min(1e3*2**(r-1),8e3):250*2**(r-1)}function N(n,r){const s=`${r?.modell??""}\0${r?.geduld??"kurz"}\0${n}`,c=Date.now(),e=l.get(s);if(e&&e.bis>c)return e.vektor;const o=T(n,r);if(l.set(s,{bis:c+P,vektor:o}),l.size>v){const t=l.keys().next().value;t!==void 0&&l.delete(t)}return o.catch(()=>{l.get(s)?.vektor===o&&l.delete(s)}),o}const P=6e4,v=200,l=new Map;function Y(){l.clear()}async function T(n,r){const s=r?.geduld??"kurz";if(r?.modell&&d!=="cachly"&&d!=="ollama")throw new Error(`Anbieter "${d}" kann kein abweichendes Modell anfragen (verlangt: ${r.modell}).`);if(n.trim()==="")throw new Error("nothing to embed: empty text");let c=0;for(;;){c++;try{h(`einbettung: Anfang (${n.length} Zeichen, Versuch ${c})`);const e=await w(n,s,r?.modell);return h("einbettung: fertig"),e}catch(e){const o=O(e,c,s);if(o===null)throw e;await new Promise(t=>setTimeout(t,o))}}}function k(){switch(d){case"cachly":return!!i.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 D(){const n={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(d==="none")return"No embedding provider configured. Sign in (CACHLY_JWT) to use the EU-hosted cachly embeddings, or set OLLAMA_BASE_URL for a local model. Brain works without embedding.";const r=n[d]??"CACHLY_JWT";return`CACHLY_EMBED_PROVIDER=${d} \u2192 requires ${r}`}export{d as EMBED_PROVIDER,N as computeEmbedding,i as embedConfig,D as embedProviderHint,k as hasEmbedProvider,M as istVoruebergehend,R as setEmbedJwt,Y as vergissEinbettungen,O as wiederholungMs,f as zeitlimitMs};
|
|
@@ -1,72 +1,72 @@
|
|
|
1
|
-
import{gitLesen as We,istCommitHash as fs,pruefeOrdner as st}from"../git-ohne-shell.js";import{createRequire as kt}from"node:module";import{calculateConfidence as vt,confidenceBadge as ps,STRUCTURED_TEMPLATES as ms,CONFIDENCE_WARN_VALUE as gs}from"../confidence.js";import{kurzfassenHinweis as ws}from"../antwort-hinweis.js";import{pruefeMeldung as ys,wendeAn as _s}from"../pruefung-melden.js";import{ckgSlug as me,extractProblemConcept as nt,ckgUpsertNode as Fe,ckgUpdateEdge as _e,ckgUpsertPersonNode as bs,ckgUpsertFileNode as St,ckgRecordCollaboration as $s,ckgUpsertServiceNode as ks}from"../ckg.js";import{safeJsonParse as j,scanKeys as Ae,leseOderNull as De,darfHeraus as Ke}from"../utils.js";import{ersparteMinuten as Ct,istStarterLektion as vs,zaehltAlsErsparnis as xt}from"../wertbeitrag.js";import{lessonPreviewLines as Xe,trimTo as Ss}from"../lesson-preview.js";import{normalisiereZeit as ot,zaehleZeitangaben as at}from"../zeit-normalisieren.js";import{abstentionSatz as Cs,alterssatzFuerBelegte as xs,beurteileTreffer as Ts,istBelegt as Tt}from"../abstention.js";import{meldeEinmal as rt,meldeUndVermerke as Qe,fehlerText as it,OHNE_VEKTOREN as Ns,OHNE_DIENST as Es,OHNE_FRAGEVEKTOR as As,SINNPFAD_ABBRUCH as Is,OHNE_SCHREIBVEKTOR as ct}from"../aussetzer.js";import{versuchStart as Ms,neueKennung as Rs,wendeZuteilungAn as Bs,schliesseVersuchAb as Ls}from"../versuch.js";function lt(z,I,F,ce=F){if(z.includes("lesson:best:")){const n=j(I,{});if(n&&typeof n=="object"&&(n.what_worked||n.what_failed||n.commands?.length))return Xe(n,{maxChars:F,indent:" "})}const h=Ss(I,ce);return h?[h]:[]}const Nt=2e3,Et=400;function At(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as Os,holeKantenVorrat as Ds}from"../kanten-vorrat.js";import{getRole as ht,ROLE_BADGE as zs,getScopes as It,lessonVisibleToScope as Mt,reviewModeEnabled as Ps,storeLessonProposal as js}from"./team.js";import{keywordSearch as et,treffeUeberDateipfad as Ws,wortindexEntwerten as Rt,tokenize as ut,splitMultiQuery as Fs,levenshtein as Ks,indexVocab as Bt,bestandHolen as Gs}from"../search.js";import{startetNochLeer as Lt,leeresBrainAntwort as Ot,startLageMitCommits as dt,sofortAntwortNeuesBrain as Hs,neuesBrainBriefing as Js}from"../leeres-brain.js";import{rerankByQuality as Vs,qualityMultiplier as qs,extractLessonQuality as Us}from"../rerank.js";import{computeEmbedding as Ce,hasEmbedProvider as ze,EMBED_PROVIDER as xe}from"../embeddings.js";import{leserAktiv as Ys,leserPunkte as Zs,mischeMitLeser as Xs}from"../leser.js";import{repariereFelder as Qs}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Dt,NAME_VEKTOR_PRAEFIX as ft,ZWEIT_VEKTOR_PRAEFIX as Ge,packe as Pe,textFuerVektor as He,textFuerNamensVektor as zt,Vektorbestand as pt,VEKTOR_NACHTRAG as en,NAME_VEKTOR_NACHTRAG as mt,ZWEIT_VEKTOR_NACHTRAG as tt}from"../bedeutung.js";import{schreibeEingaenge as tn,Eingangsbestand as sn}from"../eingaenge.js";import{ordneNachHausordnung as nn,rangWerte as on}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as an}from"../seltenheitsbestand.js";import{spurLegen as rn}from"../spuren.js";import{schlageErsetzungVor as cn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as Pt,stufeSucheNachProjektversion as ln,versionsNotizen as hn,versionsBanner as un}from"../gueltigkeit-version.js";const Je=en,dn=365;import{etikettenFuer as fn,lieferJournalSchluessel as jt,JOURNAL_DECKEL as pn}from"../etiketten.js";import{klassifiziereFehlschlag as mn,suchProtokollSchluessel as gt,trichterSchluessel as Wt,SUCH_DECKEL as Ft}from"../recall-trichter.js";import{leiteEntscheidungAb as gn,entscheidungsZeile as Kt}from"../entscheidung-ableiten.js";import{bewerteTopf as wn,spreizeImTopf as Gt,reichereAn as yn,inhaltsWoerter as Ht,grobStamm as _n,GEWICHTE as bn,knapperSiegSatz as $n}from"../rangfolge.js";import{fehlendeLernfelder as kn,hatFrage as vn,kappeAnfrage as Sn,ungueltigerAusgang as Cn}from"../pflichtfelder.js";import{pruefeWirkung as xn,wirkungsEingabeAus as Tn,werteAus as Nn,lehrwert as En,leiteAb as An,belegeJeThema as In}from"../wirkungsspur.js";import{merkeSuchlauf as wt}from"../suchstatistik.js";import{schreibeTopfNotiz as Mn,topfProtokollAktiv as Rn}from"../topf-protokoll.js";import{SINN_TOPF as Bn,EINGANG_SCHWELLE as Ln,EINGANG_SORTIER_GEWICHT as On,ZWEIT_MODELL as Ue,ZWEIT_GEWICHT as Dn,ZWEIT_MINDESTDECKUNG as Jt,NAHDUPLIKAT_SCHWELLE as zn,LESER_TIEFE as Vt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as qt,quelleZeile as Pn}from"../herkunft.js";import{doppelHinweis as jn,leseDoppelKandidaten as Wn,mitFrist as Fn,pruefeDoppelung as Kn}from"../doppel-kandidat.js";import{merkeRecall as Gn,sitzungsKosten as Hn,vergissSitzungsKosten as Jn,kostenZeilen as Vn}from"../sitzungs-kosten.js";const Ut=new WeakMap;function yt(z){let I=Ut.get(z);return I||(I={vektor:new pt,namen:new pt(6e4,ft),zweit:new pt(6e4,Ge),eingang:new sn,seltenheit:new an},Ut.set(z,I)),I}const Yt=Bn,qn=Ln,Un=On;import{upgradeNudge as Yn}from"../upgrade-nudge.js";import{recallTiefe as Zt,verlangteTiefe as Zn,TIEFE_VOLL as Xn,TIEFE_VOLL_MEHRTHEMIG as Qn}from"../recall-tiefe.js";import{nutzungInWorten as eo,nutzungsSchluessel as to,verdichte as so}from"../werkzeug-nutzung.js";import{inWorten as no,lieferBild as oo,lieferSchluessel as ao,trefferSchluessel as ro}from"../geliefert.js";import{COAUTHOR_PREF_KEY as io,autorHinweis as co,coautorAus as lo,echterGitLeser as ho,ermittleAutor as uo,mitCoautor as fo,nurMensch as Xt}from"../autor.js";import{TOOLS as po}from"../tools.js";import{vorspannHinweis as mo}from"../vorspann.js";import{autorAbzeichen as go,fremdanteil as wo}from"../autor-abzeichen.js";import{cachlyUrl as yo}from"../cachly-url.js";import{belegFuer as _o}from"../schreibbeleg.js";import{schwaerzeFelder as bo}from"../geheimnis-filter.js";import{VERDACHT_TAG as _t,mitVerdachtTag as $o,pruefeFelder as ko,verdachtsWarnung as vo}from"../tuersteher.js";import{fuerEigenenSpeicher as je,hinweise as Ve,istMarkiert as Qt,markiert as So,markierungsWarnung as es,markierungsWarnungAusRohwert as ts,zaehlHinweise as ss}from"../schreibtor.js";import{istBlossesThema as ns}from"../blosses-thema.js";import{zeitpunkt as ye}from"../zeitmessung.js";const Ye=(()=>{try{const z=kt(import.meta.url);for(const I of["../../../package.json","../../package.json"])try{const F=z(I);if(F.name==="@cachly-dev/mcp-server"&&F.version)return F.version}catch{}}catch{}return"0.10.100"})(),Co=()=>{try{return kt(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},xo={"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${Ye}:**`," \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"]},Ba=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","lesson_verified","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"]),To=yo("/billing","upgrade"),os=new Map,as=new Set,No=1680*60*60;function Eo(z=new Date){return`cachly:quota:recalls:${z.toISOString().slice(0,7)}`}async function bt(z){try{const I=Eo();await z.incr(I)===1&&await z.expire(I,No)}catch{}}function rs(z){return`cachly:stats:drei-ausgaenge:${z}`}async function $t(z,I,F){try{await z.hincrby(rs(I),F,1)}catch{}}function is(z,I,F,ce){bt(z),wt(z,F,ce);const h={ts:new Date().toISOString(),frage:F.slice(0,200),geliefert:[]};(async()=>{const n=gt(I);await z.lpush(n,JSON.stringify(h)),await z.ltrim(n,0,Ft-1)})().catch(()=>{}),$t(z,I,"schweigen")}async function cs(z){const I={tage:0,rekord:0};try{const F=await z.get("cachly:streak:current"),ce=j(F,null),h=new Date().toISOString().slice(0,10);if(ce){const n=ce.last_date,m=new Date(Date.now()-864e5).toISOString().slice(0,10);n===h?(I.tage=ce.days,I.rekord=ce.record):n===m?(I.tage=ce.days+1,I.rekord=Math.max(I.tage,ce.record),await z.set("cachly:streak:current",JSON.stringify({days:I.tage,last_date:h,record:I.rekord}))):(I.tage=1,I.rekord=ce.record,await z.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:I.rekord})))}else I.tage=1,I.rekord=1,await z.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:1}))}catch{}return I}async function ls(z,I,F){await z.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:I,provider:F}),"EX",86400)}async function hs(z,I){const F=os.get(z);if(F&&F.expiresAt>Date.now())return F.gate;try{const ce=await I(`/api/v1/instances/${z}/memory`),h=ce?.recall_limit??-1,n=ce?.total_recall_count??0,m={reached:h>0&&n>=h,limit:h,used:n,goodwillMessage:ce?.goodwill_message,notice:ce?.notice};return os.set(z,{gate:m,expiresAt:Date.now()+6e4}),m}catch{return{reached:!1,limit:-1,used:0}}}const Ao={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function La(z,I,F,ce){const h=await Io(z,I,F,ce),n=Ao[z];if(n&&typeof h=="string")try{Gn(String(I.instance_id??""),String(I[n]??""),h.length)}catch{}return h}async function Io(z,I,F,ce){switch(z){case"learn_from_attempts":{{const b=kn(I);if(b.length)return`\u26A0\uFE0F learn_from_attempts needs ${b.join(" and ")}. Nothing was stored.`;const R=Cn(I);if(R)return R}const h=bo(I),n=ko(h.felder),m=n.length?{...h.felder,tags:$o(h.felder.tags)}:h.felder,{instance_id:w,topic:a,outcome:o,what_worked:N,what_failed:d="",context:r="",severity:S="major",file_paths:t=[],commands:s=[],tags:C=[],depends_on:i=[],author:c="",visibility:$="team",service:f="",service_kind:g="service",group:M="",grund:A="",ersetzt:e="",gilt_ab:J="",gilt_fuer:ie}=m,{what_worked:ae,what_failed:de="",context:U=""}=Qs({what_worked:N,what_failed:d,context:r}),p=await F(w),H=new Date,Y=H.toISOString();let X=Pt(ie,void 0);const Z=J&&!Number.isNaN(Date.parse(String(J)))?new Date(String(J)):H,V=ot(ae,Z),se=ot(de,Z),l=ot(U,Z),k=at(ae,Z)+at(de,Z)+at(U,Z),T=uo({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:ho(process.env.CACHLY_WORKSPACE??process.cwd())});let E="";try{E=lo(await p.get(`cachly:prefs:${io}:${w}`))}catch{}const _=fo(T.autor,E),v=co(T);if($!=="private"&&await Ps(p,w))return js(p,a,{topic:a,outcome:o,what_worked:V,what_failed:se,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:i,...X.angaben.length?{gilt_fuer:X.angaben}:{},..._?{author:_}:{},source:qt(),...f?{service:f}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:0,ts:Y,confidence:1,version:3});const P=a.split(":")[0],G=ms[P],x=[];if(G)for(const b of G.required)b==="commands"&&s.length===0&&x.push(`\u{1F4CB} ${G.hint}`);let ee=!1,we=0,ne,ue=[];const fe=await p.get(`cachly:lesson:best:${a}`),be=String(A||m.reason||"").trim();if(fe&&!be)return[`\u270B **Update rejected:** \`${a}\` already exists \u2014 an update needs the field \`grund\` (the reason; \`reason\` works too).`,"","One line is enough: WHY was the previous version wrong or incomplete?",'Example: grund="The deploy target moved from port 3000 to 8080"',"","The diff says WHAT changes. The grund line says why the old version was wrong \u2014","and that is the line someone reads two months from now (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
-
`);if(fe)try{const b=JSON.parse(fe);X=Pt(ie,b.gilt_fuer),we=b.recall_count??0,ne=b.last_recalled_at,ue=b.audit_trail??[],ue.push({ts:Y,action:"updated",prev_outcome:b.outcome,grund:be}),ue.length>20&&(ue=ue.slice(-20)),ee=!0;const R=[];if(b.outcome==="success"&&o==="failure"?R.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."):b.outcome==="failure"&&o==="success"&&R.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),R.length>0){ue[ue.length-1].action="contradiction-resolved";try{const oe=me(a),O=me(`resolution:${a}`);await _e(p,oe,"contradicts",O,!1)}catch{}try{const oe=`cachly:contradictions:${a}`,O=b.outcome==="success"&&o==="failure"?"kept-success":"overwrote-failure";await p.rpush(oe,JSON.stringify({ts:Y,prev_outcome:b.outcome,new_outcome:o,direction:O})),await p.ltrim(oe,-50,-1),await p.expire(oe,180*86400)}catch{}R.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${a}")\` to resolve via expert agent voting.`)}}catch{}else ue=[{ts:Y,action:"created"}];const Me=[];if(o==="failure"){const b=[],R=p.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((O,D)=>{R.on("data",K=>b.push(...K)),R.on("end",O),R.on("error",D)});const oe=a.split(/[:\-_]/).filter(O=>O.length>2);for(const O of b.slice(0,50)){const D=await p.get(O);if(D)try{const K=JSON.parse(D);if(K.outcome!=="success")continue;const le=(K.topic??"").split(/[:\-_]/).filter($e=>$e.length>2);if(oe.filter($e=>le.includes($e)).length>=1&&K.topic!==a){Me.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${K.topic}\` (success, ${K.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${K.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${K.topic}", ..., severity="critical")\``);break}}catch{}}}for(const b of i){const R=`cachly:dep:${b}`,oe=await p.get(R),O=j(oe,[]);O.includes(a)||O.push(a),await p.set(R,JSON.stringify(O),"EX",90*86400)}const Re={topic:a,outcome:o,what_worked:V,what_failed:se,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:i,..._?{author:_}:{},source:qt(),...f?{service:f}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:we,...ne?{last_recalled_at:ne}:{},...J&&!Number.isNaN(Date.parse(String(J)))?{gilt_ab:new Date(String(J)).toISOString()}:{},...X.angaben.length?{gilt_fuer:X.angaben}:{},ts:Y,verified_at:o==="success"||o==="partial"?Y:void 0,confidence:1,audit_trail:ue,version:3},ge=String(e??"").trim();let ve="",Ie=null;ge===a&&ge?ve="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":ge&&(Ie=await p.get(`cachly:lesson:best:${ge}`),Ie?j(Ie,{}).ersetzt===a?(Ie=null,ve=`\u26A0\uFE0F \`${ge}\` already replaces \`${a}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${ge}\` first, then set it here.`):Re.ersetzt=ge:ve=`\u26A0\uFE0F The lesson to replace, \`${ge}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Be="";if(!ge)try{const b=K=>{const le=j(K.content,{});return{topic:le.topic??K.key.slice(19),what_worked:le.what_worked}},[R,oe]=await Promise.all([et(p,["cachly:lesson:best:*"],`${a} ${V}`.slice(0,300),5),Ws(p,["cachly:lesson:best:*"],t??[])]),O=new Set,D=[...R,...oe].filter(K=>K.key.startsWith("cachly:lesson:best:")).filter(K=>!O.has(K.key)&&O.add(K.key)).map(b);Be=cn(a,V,D)??""}catch{}if(o==="failure")try{const R=(await p.lrange(gt(w),0,199)).map(D=>j(D,{ts:"",frage:"",geliefert:[]})).filter(D=>D.ts!==""),oe=(await et(p,["cachly:lesson:best:*"],`${a} ${se||V}`.slice(0,300),5)).filter(D=>D.key.startsWith("cachly:lesson:best:")).map(D=>{const K=j(D.content,{});return{topic:K.topic??D.key.slice(19),what_worked:K.what_worked}}),O=mn(a,String(se||""),R,oe);await p.hincrby(Wt(w),O,1)}catch{}const te=gn([V,se,r].filter(Boolean).join(" ").slice(0,2e3));te&&(Re.entscheidung=te);const Le=_o(a,Y,V);Re.beleg=Le;const Te=JSON.stringify(Re);p.set(`cachly:stats:born_at:${w}`,Y,"EX",365*86400,"NX").catch(()=>{});const Ee=`cachly:lessons:${a}`;await p.rpush(Ee,Te),await p.ltrim(Ee,-100,-1),await p.expire(Ee,dn*86400);let Ne=!1;if(o==="success"||o==="partial"?(await p.set(`cachly:lesson:best:${a}`,Te),Ne=!0):fe||(await p.set(`cachly:lesson:best:${a}`,Te),Ne=!0),Ie&&Ne)try{const b=JSON.parse(Ie);b.ersetzt_durch=a,b.gilt_bis=Y,b.ersetzt_am=Y,be&&(b.ersetzt_grund=be.slice(0,200)),await p.set(`cachly:lesson:best:${ge}`,JSON.stringify(b))}catch{}Ne&&Rt();let u=()=>{};const y=new Promise(b=>{u=b});Ne&&ze()||u(null),Ne&&ze()&&(await p.sadd(Je,a).catch(()=>{}),await p.sadd(mt,a).catch(()=>{}),(xe==="cachly"||xe==="ollama")&&await p.sadd(tt,a).catch(()=>{}),(async()=>{const b=j(Te,{});try{const R=await Ce(He(b),{geduld:"lang"});if(R?.length?(await p.set(`${Dt}${a}`,Pe(R)),await p.srem(Je,a).catch(()=>{}),u(await Kn(p,{...b,topic:a},R,yt(p).vektor))):u(null),xe==="cachly"||xe==="ollama")try{const oe=await Ce(He(b),{geduld:"lang",modell:Ue});oe?.length&&(await p.set(`${Ge}${a}`,Pe(oe)),await p.srem(tt,a).catch(()=>{}))}catch{}}catch(R){u(null),await p.sadd(Je,a).catch(()=>{}),await Qe(p,ct,`Volltext-Vektor nicht geschrieben (${xe}): ${it(R)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const R=await Ce(zt(a),{geduld:"lang"});R?.length&&(await p.set(`${ft}${a}`,Pe(R)),await p.srem(mt,a).catch(()=>{}))}catch(R){await Qe(p,ct,`Namens-Vektor nicht geschrieben (${xe}): ${it(R)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await tn(p,a,b,R=>Ce(R,{geduld:"lang"}))}catch(R){await Qe(p,ct,`Eingaenge nicht geschrieben (${xe}): ${it(R)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await us(p,a,3),u(null)})());try{const b="cachly:session:decision-log",R=JSON.stringify({ts:Y,topic:a,outcome:o,what_worked:V.slice(0,120)});await p.rpush(b,R),await p.ltrim(b,-50,-1)}catch{}let B=null;try{const b=me(a),R=a.split(":")[0]??"unknown";await Fe(p,b,R,R);for(const O of C){const D=me(`tag:${O}`);await Fe(p,D,"tag","tag"),await _e(p,b,"co-occurs",D,o==="success",o==="partial")}for(const O of i){const D=me(O);await _e(p,b,"requires",D,!0)}if((R==="fix"||R==="debug")&&(o==="success"||o==="partial")){const O=se||l||"",D=O?nt(O):null;if(D){const K=me(`problem:${D}`);await Fe(p,K,"problem","problem"),await _e(p,b,"fixes",K,o==="success",o==="partial")}}if(o==="failure"&&(se||V)){const D=nt(se||V);if(D){const K=me(`cause:${D}`);await Fe(p,K,"cause","cause"),await _e(p,b,"causes",K,!1)}}if(o==="failure"){const O=await p.smembers(`cachly:ckg:idx:from:${b}`);for(const D of O){const K=await p.get(D);if(!K)continue;const le=j(K,null);if(le&&le.edgeType==="fixes"&&le.confidence>.7&&le.trials>=3){B=`\u26A0\uFE0F **belief_conflict** on \`${a}\`: previously confirmed fix (confidence ${le.confidence.toFixed(2)}, n=${le.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${a}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${b}")\` to review.`;const he=`cachly:ckg:conflict:${b}`;await p.set(he,JSON.stringify({topic:a,concept_id:b,detected_at:new Date().toISOString(),fix_confidence:le.confidence,fix_trials:le.trials,failure_outcome:o,reported_by:_||"unknown",what_failed:se||"",resolved:!1}),"EX",3600*24*90)}}}if(o==="success"&&(R==="fix"||R==="debug")){const O=await p.smembers(`cachly:ckg:idx:from:${b}`);for(const D of O.slice(0,10)){const K=await p.get(D);if(!K)continue;const le=j(K,null);if(!le||le.edgeType!=="fixes")continue;const he=await p.smembers(`cachly:ckg:idx:from:${le.to}`);for(const $e of he.slice(0,5)){const Oe=await p.get($e);if(!Oe)continue;const W=j(Oe,null);W&&W.edgeType==="co-occurs"&&(W.successes=(W.successes||0)+.1,W.trials=(W.trials||0)+.1,W.confidence=(W.successes+1)/(W.trials+2),W.last_updated=new Date().toISOString(),await p.set($e,JSON.stringify(W)))}}}if(Math.random()<.01){const O=Date.now()-7776e6,D=await p.smembers(`cachly:ckg:idx:from:${b}`);for(const K of D){const le=await p.get(K);if(!le)continue;const he=j(le,null);he&&he.trials<3&&he.last_updated&&new Date(he.last_updated).getTime()<O&&(he.confidence=he.confidence*.9,he.last_updated=new Date().toISOString(),await p.set(K,JSON.stringify(he)))}}}catch{}if(_){p.set(`cachly:agents:active:${_}`,JSON.stringify({author:_,last_topic:a,last_outcome:o,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const b=a.split(":")[0]??"unknown",R=await bs(p,Xt(_),b),oe=me(a);await _e(p,R,"authored",oe,o==="success",o==="partial");for(const O of t.slice(0,8)){const D=await St(p,O);await _e(p,R,"touched",D,!0),await $s(p,D,R)}}catch{}}if(f&&typeof f=="string"&&f.trim())try{const b=a.split(":")[0]??"unknown",R=g==="system"?"system":"service",oe=await ks(p,f.trim(),b,R),O=me(a);if(await _e(p,O,"affects",oe,o==="success",o==="partial"),_){const D=`person:${me(Xt(_))}`;await _e(p,D,"operates",oe,!0)}for(const D of t.slice(0,8)){const K=`file:${me(D)}`;await _e(p,K,"runs_in",oe,!0)}}catch{}if(_&&(o==="success"||o==="partial")){const b={topic:a,outcome:o,what_worked:V,what_failed:se??"",severity:S,author:_,file_paths:t,commands:s,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},R=`cachly:lessons:${a}`;p.rpush(R,JSON.stringify(b)).catch(()=>{})}const re=o==="success"?"\u2705":o==="partial"?"\u26A0\uFE0F":"\u274C",L=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",q=ee?"updated":"stored",Q=await Fn(y);return[`${re} **Lesson ${q}:** \`${a}\` (${o}) ${L} ${S} \xB7 receipt: \`${Le}\``,h.funde.length?`\u{1F512} **${h.funde.length} secret(s) redacted** before saving (${h.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",vo(n),B??"","",`**What worked:** ${V}`,se?`**What failed:** ${se}`:"",l?`**Context:** ${l}`:"",t.length>0?`**Files:** ${t.map(b=>`\`${b}\``).join(", ")}`:"",s.length>0?`**Commands:** ${s.map(b=>`\`${b}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(b=>`#${b}`).join(" ")}`:"","",ee?`\u267B\uFE0F Updated (recall count: ${we} \xB7 audit entries: ${ue.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${a}")\``,_&&(o==="success"||o==="partial")?`\u{1F465} Auto-shared with team (by _${_}_${T.quelle!=="uebergeben"?` \xB7 from ${T.quelle}`:""}) \u2014 visible in \`team_recall\``:"",v??"",i.length>0?`\u{1F517} Depends on: ${i.map(b=>`\`${b}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Be,jn(Q,Be),X.angaben.length?`\u{1F4E6} Applies to ${X.angaben.map(b=>`\`${b}\``).join(", ")}${X.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...X.fehler.map(b=>`\u26A0\uFE0F gilt_fuer not stored, ${b}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),Ie&&Ne?be?`\u21B7 Replaces \`${ge}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${ge}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:ve,...x,...Me,k>0?`\u{1F5D3}\uFE0F ${k} relative time reference${k===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(H.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",mo(V)??""].filter(b=>b!=="").join(`
|
|
3
|
-
`)}case"lesson_verified":{const{instance_id:h}=
|
|
4
|
-
`);const N=
|
|
5
|
-
`):[`\u26A0\uFE0F \`${N.topic}\` ist als fraglich markiert.`,` Befund: ${N.befund}`,"","Geloescht wurde nichts \u2014 eine Pruefung kann aus Gruenden fehlschlagen,","die mit der Lektion nichts zu tun haben. Wenn du weisst, was jetzt gilt:",`\`learn_from_attempts(topic="${N.topic}", \u2026, grund="\u2026")\`.`,...Ve(
|
|
6
|
-
`)}case"recall_feedback":{const{instance_id:h}=
|
|
7
|
-
`);const w=
|
|
8
|
-
`)}case"recall_best_solution":{const h=Date.now(),{instance_id:n,topic:
|
|
9
|
-
`):"",
|
|
10
|
-
`)}const d=[],r=
|
|
1
|
+
import{gitLesen as We,istCommitHash as fs,pruefeOrdner as nt}from"../git-ohne-shell.js";import{createRequire as kt}from"node:module";import{calculateConfidence as vt,confidenceBadge as ps,STRUCTURED_TEMPLATES as ms,CONFIDENCE_WARN_VALUE as gs}from"../confidence.js";import{kurzfassenHinweis as ws}from"../antwort-hinweis.js";import{pruefeMeldung as ys,wendeAn as _s}from"../pruefung-melden.js";import{ckgSlug as me,extractProblemConcept as ot,ckgUpsertNode as Fe,ckgUpdateEdge as _e,ckgUpsertPersonNode as bs,ckgUpsertFileNode as St,ckgRecordCollaboration as $s,ckgUpsertServiceNode as ks}from"../ckg.js";import{safeJsonParse as P,scanKeys as Ae,leseOderNull as De,darfHeraus as Ke}from"../utils.js";import{ersparteMinuten as Ct,istStarterLektion as vs,zaehltAlsErsparnis as xt}from"../wertbeitrag.js";import{lessonPreviewLines as Xe,trimTo as Ss}from"../lesson-preview.js";import{normalisiereZeit as at,zaehleZeitangaben as rt}from"../zeit-normalisieren.js";import{abstentionSatz as Cs,alterssatzFuerBelegte as xs,beurteileTreffer as Ts,istBelegt as Tt}from"../abstention.js";import{meldeEinmal as it,meldeUndVermerke as Qe,fehlerText as ct,OHNE_VEKTOREN as Ns,OHNE_DIENST as Es,OHNE_FRAGEVEKTOR as As,SINNPFAD_ABBRUCH as Is,OHNE_SCHREIBVEKTOR as lt}from"../aussetzer.js";import{versuchStart as Ms,neueKennung as Rs,wendeZuteilungAn as Bs,schliesseVersuchAb as Ls}from"../versuch.js";function ht(D,A,F,ce=F){if(D.includes("lesson:best:")){const n=P(A,{});if(n&&typeof n=="object"&&(n.what_worked||n.what_failed||n.commands?.length))return Xe(n,{maxChars:F,indent:" "})}const h=Ss(A,ce);return h?[h]:[]}const Nt=2e3,Et=400;function At(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as Os,holeKantenVorrat as Ds}from"../kanten-vorrat.js";import{getRole as ut,ROLE_BADGE as zs,getScopes as It,lessonVisibleToScope as Mt,reviewModeEnabled as Ps,storeLessonProposal as js}from"./team.js";import{keywordSearch as et,treffeUeberDateipfad as Ws,wortindexEntwerten as Rt,tokenize as dt,splitMultiQuery as Fs,levenshtein as Ks,indexVocab as Bt,bestandHolen as Gs}from"../search.js";import{startetNochLeer as Lt,leeresBrainAntwort as Ot,startLageMitCommits as ft,sofortAntwortNeuesBrain as Hs,neuesBrainBriefing as Js}from"../leeres-brain.js";import{rerankByQuality as Vs,qualityMultiplier as qs,extractLessonQuality as Us}from"../rerank.js";import{computeEmbedding as Ce,hasEmbedProvider as ze,EMBED_PROVIDER as xe}from"../embeddings.js";import{leserAktiv as Ys,leserPunkte as Zs,mischeMitLeser as Xs}from"../leser.js";import{repariereFelder as Qs}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Dt,NAME_VEKTOR_PRAEFIX as pt,ZWEIT_VEKTOR_PRAEFIX as Ge,packe as Pe,textFuerVektor as He,textFuerNamensVektor as zt,Vektorbestand as mt,VEKTOR_NACHTRAG as en,NAME_VEKTOR_NACHTRAG as tt,ZWEIT_VEKTOR_NACHTRAG as st}from"../bedeutung.js";import{schreibeEingaenge as tn,Eingangsbestand as sn}from"../eingaenge.js";import{ordneNachHausordnung as nn,rangWerte as on}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as an}from"../seltenheitsbestand.js";import{spurLegen as rn}from"../spuren.js";import{schlageErsetzungVor as cn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as Pt,stufeSucheNachProjektversion as ln,versionsNotizen as hn,versionsBanner as un}from"../gueltigkeit-version.js";const Je=en,dn=365;import{etikettenFuer as fn,lieferJournalSchluessel as jt,JOURNAL_DECKEL as pn}from"../etiketten.js";import{klassifiziereFehlschlag as mn,suchProtokollSchluessel as gt,trichterSchluessel as Wt,SUCH_DECKEL as Ft}from"../recall-trichter.js";import{leiteEntscheidungAb as gn,entscheidungsZeile as Kt}from"../entscheidung-ableiten.js";import{bewerteTopf as wn,spreizeImTopf as Gt,reichereAn as yn,inhaltsWoerter as Ht,grobStamm as _n,GEWICHTE as bn,knapperSiegSatz as $n}from"../rangfolge.js";import{fehlendeLernfelder as kn,hatFrage as vn,kappeAnfrage as Sn,ungueltigerAusgang as Cn}from"../pflichtfelder.js";import{pruefeWirkung as xn,wirkungsEingabeAus as Tn,werteAus as Nn,lehrwert as En,leiteAb as An,belegeJeThema as In}from"../wirkungsspur.js";import{merkeSuchlauf as wt}from"../suchstatistik.js";import{schreibeTopfNotiz as Mn,topfProtokollAktiv as Rn}from"../topf-protokoll.js";import{SINN_TOPF as Bn,EINGANG_SCHWELLE as Ln,EINGANG_SORTIER_GEWICHT as On,ZWEIT_MODELL as Ue,ZWEIT_GEWICHT as Dn,ZWEIT_MINDESTDECKUNG as Jt,NAHDUPLIKAT_SCHWELLE as zn,LESER_TIEFE as Vt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as qt,quelleZeile as Pn}from"../herkunft.js";import{doppelHinweis as jn,leseDoppelKandidaten as Wn,mitFrist as Fn,pruefeDoppelung as Kn}from"../doppel-kandidat.js";import{merkeRecall as Gn,sitzungsKosten as Hn,vergissSitzungsKosten as Jn,kostenZeilen as Vn}from"../sitzungs-kosten.js";const Ut=new WeakMap;function yt(D){let A=Ut.get(D);return A||(A={vektor:new mt,namen:new mt(6e4,pt),zweit:new mt(6e4,Ge),eingang:new sn,seltenheit:new an},Ut.set(D,A)),A}const Yt=Bn,qn=Ln,Un=On;import{upgradeNudge as Yn}from"../upgrade-nudge.js";import{recallTiefe as Zt,verlangteTiefe as Zn,TIEFE_VOLL as Xn,TIEFE_VOLL_MEHRTHEMIG as Qn}from"../recall-tiefe.js";import{nutzungInWorten as eo,nutzungsSchluessel as to,verdichte as so}from"../werkzeug-nutzung.js";import{inWorten as no,lieferBild as oo,lieferSchluessel as ao,trefferSchluessel as ro}from"../geliefert.js";import{COAUTHOR_PREF_KEY as io,autorHinweis as co,coautorAus as lo,echterGitLeser as ho,ermittleAutor as uo,mitCoautor as fo,nurMensch as Xt}from"../autor.js";import{TOOLS as po}from"../tools.js";import{vorspannHinweis as mo}from"../vorspann.js";import{autorAbzeichen as go,fremdanteil as wo}from"../autor-abzeichen.js";import{cachlyUrl as yo}from"../cachly-url.js";import{belegFuer as _o}from"../schreibbeleg.js";import{schwaerzeFelder as bo}from"../geheimnis-filter.js";import{VERDACHT_TAG as _t,mitVerdachtTag as $o,pruefeFelder as ko,verdachtsWarnung as vo}from"../tuersteher.js";import{fuerEigenenSpeicher as je,hinweise as Ve,istMarkiert as Qt,markiert as So,markierungsWarnung as es,markierungsWarnungAusRohwert as ts,zaehlHinweise as ss}from"../schreibtor.js";import{istBlossesThema as ns}from"../blosses-thema.js";import{zeitpunkt as ye}from"../zeitmessung.js";const Ye=(()=>{try{const D=kt(import.meta.url);for(const A of["../../../package.json","../../package.json"])try{const F=D(A);if(F.name==="@cachly-dev/mcp-server"&&F.version)return F.version}catch{}}catch{}return"0.10.100"})(),Co=()=>{try{return kt(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},xo={"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${Ye}:**`," \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"]},Ba=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","lesson_verified","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"]),To=yo("/billing","upgrade"),os=new Map,as=new Set,No=1680*60*60;function Eo(D=new Date){return`cachly:quota:recalls:${D.toISOString().slice(0,7)}`}async function bt(D){try{const A=Eo();await D.incr(A)===1&&await D.expire(A,No)}catch{}}function rs(D){return`cachly:stats:drei-ausgaenge:${D}`}async function $t(D,A,F){try{await D.hincrby(rs(A),F,1)}catch{}}function is(D,A,F,ce){bt(D),wt(D,F,ce);const h={ts:new Date().toISOString(),frage:F.slice(0,200),geliefert:[]};(async()=>{const n=gt(A);await D.lpush(n,JSON.stringify(h)),await D.ltrim(n,0,Ft-1)})().catch(()=>{}),$t(D,A,"schweigen")}async function cs(D){const A={tage:0,rekord:0};try{const F=await D.get("cachly:streak:current"),ce=P(F,null),h=new Date().toISOString().slice(0,10);if(ce){const n=ce.last_date,p=new Date(Date.now()-864e5).toISOString().slice(0,10);n===h?(A.tage=ce.days,A.rekord=ce.record):n===p?(A.tage=ce.days+1,A.rekord=Math.max(A.tage,ce.record),await D.set("cachly:streak:current",JSON.stringify({days:A.tage,last_date:h,record:A.rekord}))):(A.tage=1,A.rekord=ce.record,await D.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:A.rekord})))}else A.tage=1,A.rekord=1,await D.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:1}))}catch{}return A}async function ls(D,A,F){await D.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:A,provider:F}),"EX",86400)}async function hs(D,A){const F=os.get(D);if(F&&F.expiresAt>Date.now())return F.gate;try{const ce=await A(`/api/v1/instances/${D}/memory`),h=ce?.recall_limit??-1,n=ce?.total_recall_count??0,p={reached:h>0&&n>=h,limit:h,used:n,goodwillMessage:ce?.goodwill_message,notice:ce?.notice};return os.set(D,{gate:p,expiresAt:Date.now()+6e4}),p}catch{return{reached:!1,limit:-1,used:0}}}const Ao={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function La(D,A,F,ce){const h=await Io(D,A,F,ce),n=Ao[D];if(n&&typeof h=="string")try{Gn(String(A.instance_id??""),String(A[n]??""),h.length)}catch{}return h}async function Io(D,A,F,ce){switch(D){case"learn_from_attempts":{{const b=kn(A);if(b.length)return`\u26A0\uFE0F learn_from_attempts needs ${b.join(" and ")}. Nothing was stored.`;const j=Cn(A);if(j)return j}const h=bo(A),n=ko(h.felder),p=n.length?{...h.felder,tags:$o(h.felder.tags)}:h.felder,{instance_id:w,topic:o,outcome:a,what_worked:N,what_failed:d="",context:r="",severity:S="major",file_paths:t=[],commands:s=[],tags:C=[],depends_on:i=[],author:c="",visibility:$="team",service:m="",service_kind:g="service",group:M="",grund:I="",ersetzt:e="",gilt_ab:V="",gilt_fuer:ie}=p,{what_worked:ae,what_failed:de="",context:Y=""}=Qs({what_worked:N,what_failed:d,context:r}),f=await F(w),J=new Date,Z=J.toISOString();let Q=Pt(ie,void 0);const X=V&&!Number.isNaN(Date.parse(String(V)))?new Date(String(V)):J,q=at(ae,X),ne=at(de,X),l=at(Y,X),k=rt(ae,X)+rt(de,X)+rt(Y,X),T=uo({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:ho(process.env.CACHLY_WORKSPACE??process.cwd())});let E="";try{E=lo(await f.get(`cachly:prefs:${io}:${w}`))}catch{}const _=fo(T.autor,E),v=co(T);if($!=="private"&&await Ps(f,w))return js(f,o,{topic:o,outcome:a,what_worked:q,what_failed:ne,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:i,...Q.angaben.length?{gilt_fuer:Q.angaben}:{},..._?{author:_}:{},source:qt(),...m?{service:m}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:0,ts:Z,confidence:1,version:3});const z=o.split(":")[0],G=ms[z],x=[];if(G)for(const b of G.required)b==="commands"&&s.length===0&&x.push(`\u{1F4CB} ${G.hint}`);let te=!1,we=0,oe,ue=[];const fe=await f.get(`cachly:lesson:best:${o}`),be=String(I||p.reason||"").trim();if(fe&&!be)return[`\u270B **Update rejected:** \`${o}\` already exists \u2014 an update needs the field \`grund\` (the reason; \`reason\` works too).`,"","One line is enough: WHY was the previous version wrong or incomplete?",'Example: grund="The deploy target moved from port 3000 to 8080"',"","The diff says WHAT changes. The grund line says why the old version was wrong \u2014","and that is the line someone reads two months from now (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
+
`);if(fe)try{const b=JSON.parse(fe);Q=Pt(ie,b.gilt_fuer),we=b.recall_count??0,oe=b.last_recalled_at,ue=b.audit_trail??[],ue.push({ts:Z,action:"updated",prev_outcome:b.outcome,grund:be}),ue.length>20&&(ue=ue.slice(-20)),te=!0;const j=[];if(b.outcome==="success"&&a==="failure"?j.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."):b.outcome==="failure"&&a==="success"&&j.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),j.length>0){ue[ue.length-1].action="contradiction-resolved";try{const H=me(o),B=me(`resolution:${o}`);await _e(f,H,"contradicts",B,!1)}catch{}try{const H=`cachly:contradictions:${o}`,B=b.outcome==="success"&&a==="failure"?"kept-success":"overwrote-failure";await f.rpush(H,JSON.stringify({ts:Z,prev_outcome:b.outcome,new_outcome:a,direction:B})),await f.ltrim(H,-50,-1),await f.expire(H,180*86400)}catch{}j.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${o}")\` to resolve via expert agent voting.`)}}catch{}else ue=[{ts:Z,action:"created"}];const Me=[];if(a==="failure"){const b=[],j=f.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((B,O)=>{j.on("data",K=>b.push(...K)),j.on("end",B),j.on("error",O)});const H=o.split(/[:\-_]/).filter(B=>B.length>2);for(const B of b.slice(0,50)){const O=await f.get(B);if(O)try{const K=JSON.parse(O);if(K.outcome!=="success")continue;const le=(K.topic??"").split(/[:\-_]/).filter($e=>$e.length>2);if(H.filter($e=>le.includes($e)).length>=1&&K.topic!==o){Me.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${K.topic}\` (success, ${K.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${K.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${K.topic}", ..., severity="critical")\``);break}}catch{}}}for(const b of i){const j=`cachly:dep:${b}`,H=await f.get(j),B=P(H,[]);B.includes(o)||B.push(o),await f.set(j,JSON.stringify(B),"EX",90*86400)}const Re={topic:o,outcome:a,what_worked:q,what_failed:ne,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:i,..._?{author:_}:{},source:qt(),...m?{service:m}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:we,...oe?{last_recalled_at:oe}:{},...V&&!Number.isNaN(Date.parse(String(V)))?{gilt_ab:new Date(String(V)).toISOString()}:{},...Q.angaben.length?{gilt_fuer:Q.angaben}:{},ts:Z,verified_at:a==="success"||a==="partial"?Z:void 0,confidence:1,audit_trail:ue,version:3},ge=String(e??"").trim();let ve="",Ie=null;ge===o&&ge?ve="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":ge&&(Ie=await f.get(`cachly:lesson:best:${ge}`),Ie?P(Ie,{}).ersetzt===o?(Ie=null,ve=`\u26A0\uFE0F \`${ge}\` already replaces \`${o}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${ge}\` first, then set it here.`):Re.ersetzt=ge:ve=`\u26A0\uFE0F The lesson to replace, \`${ge}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Be="";if(!ge)try{const b=K=>{const le=P(K.content,{});return{topic:le.topic??K.key.slice(19),what_worked:le.what_worked}},[j,H]=await Promise.all([et(f,["cachly:lesson:best:*"],`${o} ${q}`.slice(0,300),5),Ws(f,["cachly:lesson:best:*"],t??[])]),B=new Set,O=[...j,...H].filter(K=>K.key.startsWith("cachly:lesson:best:")).filter(K=>!B.has(K.key)&&B.add(K.key)).map(b);Be=cn(o,q,O)??""}catch{}if(a==="failure")try{const j=(await f.lrange(gt(w),0,199)).map(O=>P(O,{ts:"",frage:"",geliefert:[]})).filter(O=>O.ts!==""),H=(await et(f,["cachly:lesson:best:*"],`${o} ${ne||q}`.slice(0,300),5)).filter(O=>O.key.startsWith("cachly:lesson:best:")).map(O=>{const K=P(O.content,{});return{topic:K.topic??O.key.slice(19),what_worked:K.what_worked}}),B=mn(o,String(ne||""),j,H);await f.hincrby(Wt(w),B,1)}catch{}const se=gn([q,ne,r].filter(Boolean).join(" ").slice(0,2e3));se&&(Re.entscheidung=se);const Le=_o(o,Z,q);Re.beleg=Le;const Te=JSON.stringify(Re);f.set(`cachly:stats:born_at:${w}`,Z,"EX",365*86400,"NX").catch(()=>{});const Ee=`cachly:lessons:${o}`;await f.rpush(Ee,Te),await f.ltrim(Ee,-100,-1),await f.expire(Ee,dn*86400);let Ne=!1;if(a==="success"||a==="partial"?(await f.set(`cachly:lesson:best:${o}`,Te),Ne=!0):fe||(await f.set(`cachly:lesson:best:${o}`,Te),Ne=!0),Ie&&Ne)try{const b=JSON.parse(Ie);b.ersetzt_durch=o,b.gilt_bis=Z,b.ersetzt_am=Z,be&&(b.ersetzt_grund=be.slice(0,200)),await f.set(`cachly:lesson:best:${ge}`,JSON.stringify(b))}catch{}Ne&&Rt();let u=()=>{};const y=new Promise(b=>{u=b});Ne&&ze()||u(null),Ne&&ze()&&(await f.sadd(Je,o).catch(()=>{}),await f.sadd(tt,o).catch(()=>{}),(xe==="cachly"||xe==="ollama")&&await f.sadd(st,o).catch(()=>{}),(async()=>{const b=P(Te,{});try{const H=await Ce(He(b),{geduld:"lang"});if(H?.length?(await f.set(`${Dt}${o}`,Pe(H)),await f.srem(Je,o).catch(()=>{}),u(await Kn(f,{...b,topic:o},H,yt(f).vektor))):u(null),xe==="cachly"||xe==="ollama")try{const B=await Ce(He(b),{geduld:"lang",modell:Ue});B?.length&&(await f.set(`${Ge}${o}`,Pe(B)),await f.srem(st,o).catch(()=>{}))}catch{}}catch(H){u(null),await f.sadd(Je,o).catch(()=>{}),await Qe(f,lt,`Volltext-Vektor nicht geschrieben (${xe}): ${ct(H)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}const j=zt(o);try{if(!j)await f.srem(tt,o).catch(()=>{});else{const H=await Ce(j,{geduld:"lang"});H?.length&&(await f.set(`${pt}${o}`,Pe(H)),await f.srem(tt,o).catch(()=>{}))}}catch(H){await Qe(f,lt,`Namens-Vektor nicht geschrieben (${xe}): ${ct(H)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await tn(f,o,b,H=>Ce(H,{geduld:"lang"}))}catch(H){await Qe(f,lt,`Eingaenge nicht geschrieben (${xe}): ${ct(H)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await us(f,o,3),u(null)})());try{const b="cachly:session:decision-log",j=JSON.stringify({ts:Z,topic:o,outcome:a,what_worked:q.slice(0,120)});await f.rpush(b,j),await f.ltrim(b,-50,-1)}catch{}let R=null;try{const b=me(o),j=o.split(":")[0]??"unknown";await Fe(f,b,j,j);for(const B of C){const O=me(`tag:${B}`);await Fe(f,O,"tag","tag"),await _e(f,b,"co-occurs",O,a==="success",a==="partial")}for(const B of i){const O=me(B);await _e(f,b,"requires",O,!0)}if((j==="fix"||j==="debug")&&(a==="success"||a==="partial")){const B=ne||l||"",O=B?ot(B):null;if(O){const K=me(`problem:${O}`);await Fe(f,K,"problem","problem"),await _e(f,b,"fixes",K,a==="success",a==="partial")}}if(a==="failure"&&(ne||q)){const O=ot(ne||q);if(O){const K=me(`cause:${O}`);await Fe(f,K,"cause","cause"),await _e(f,b,"causes",K,!1)}}if(a==="failure"){const B=await f.smembers(`cachly:ckg:idx:from:${b}`);for(const O of B){const K=await f.get(O);if(!K)continue;const le=P(K,null);if(le&&le.edgeType==="fixes"&&le.confidence>.7&&le.trials>=3){R=`\u26A0\uFE0F **belief_conflict** on \`${o}\`: previously confirmed fix (confidence ${le.confidence.toFixed(2)}, n=${le.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${o}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${b}")\` to review.`;const he=`cachly:ckg:conflict:${b}`;await f.set(he,JSON.stringify({topic:o,concept_id:b,detected_at:new Date().toISOString(),fix_confidence:le.confidence,fix_trials:le.trials,failure_outcome:a,reported_by:_||"unknown",what_failed:ne||"",resolved:!1}),"EX",3600*24*90)}}}if(a==="success"&&(j==="fix"||j==="debug")){const B=await f.smembers(`cachly:ckg:idx:from:${b}`);for(const O of B.slice(0,10)){const K=await f.get(O);if(!K)continue;const le=P(K,null);if(!le||le.edgeType!=="fixes")continue;const he=await f.smembers(`cachly:ckg:idx:from:${le.to}`);for(const $e of he.slice(0,5)){const Oe=await f.get($e);if(!Oe)continue;const W=P(Oe,null);W&&W.edgeType==="co-occurs"&&(W.successes=(W.successes||0)+.1,W.trials=(W.trials||0)+.1,W.confidence=(W.successes+1)/(W.trials+2),W.last_updated=new Date().toISOString(),await f.set($e,JSON.stringify(W)))}}}if(Math.random()<.01){const B=Date.now()-7776e6,O=await f.smembers(`cachly:ckg:idx:from:${b}`);for(const K of O){const le=await f.get(K);if(!le)continue;const he=P(le,null);he&&he.trials<3&&he.last_updated&&new Date(he.last_updated).getTime()<B&&(he.confidence=he.confidence*.9,he.last_updated=new Date().toISOString(),await f.set(K,JSON.stringify(he)))}}}catch{}if(_){f.set(`cachly:agents:active:${_}`,JSON.stringify({author:_,last_topic:o,last_outcome:a,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const b=o.split(":")[0]??"unknown",j=await bs(f,Xt(_),b),H=me(o);await _e(f,j,"authored",H,a==="success",a==="partial");for(const B of t.slice(0,8)){const O=await St(f,B);await _e(f,j,"touched",O,!0),await $s(f,O,j)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const b=o.split(":")[0]??"unknown",j=g==="system"?"system":"service",H=await ks(f,m.trim(),b,j),B=me(o);if(await _e(f,B,"affects",H,a==="success",a==="partial"),_){const O=`person:${me(Xt(_))}`;await _e(f,O,"operates",H,!0)}for(const O of t.slice(0,8)){const K=`file:${me(O)}`;await _e(f,K,"runs_in",H,!0)}}catch{}if(_&&(a==="success"||a==="partial")){const b={topic:o,outcome:a,what_worked:q,what_failed:ne??"",severity:S,author:_,file_paths:t,commands:s,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},j=`cachly:lessons:${o}`;f.rpush(j,JSON.stringify(b)).catch(()=>{})}const re=a==="success"?"\u2705":a==="partial"?"\u26A0\uFE0F":"\u274C",L=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",U=te?"updated":"stored",ee=await Fn(y);return[`${re} **Lesson ${U}:** \`${o}\` (${a}) ${L} ${S} \xB7 receipt: \`${Le}\``,h.funde.length?`\u{1F512} **${h.funde.length} secret(s) redacted** before saving (${h.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",vo(n),R??"","",`**What worked:** ${q}`,ne?`**What failed:** ${ne}`:"",l?`**Context:** ${l}`:"",t.length>0?`**Files:** ${t.map(b=>`\`${b}\``).join(", ")}`:"",s.length>0?`**Commands:** ${s.map(b=>`\`${b}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(b=>`#${b}`).join(" ")}`:"","",te?`\u267B\uFE0F Updated (recall count: ${we} \xB7 audit entries: ${ue.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${o}")\``,_&&(a==="success"||a==="partial")?`\u{1F465} Auto-shared with team (by _${_}_${T.quelle!=="uebergeben"?` \xB7 from ${T.quelle}`:""}) \u2014 visible in \`team_recall\``:"",v??"",i.length>0?`\u{1F517} Depends on: ${i.map(b=>`\`${b}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Be,jn(ee,Be),Q.angaben.length?`\u{1F4E6} Applies to ${Q.angaben.map(b=>`\`${b}\``).join(", ")}${Q.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...Q.fehler.map(b=>`\u26A0\uFE0F gilt_fuer not stored, ${b}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),Ie&&Ne?be?`\u21B7 Replaces \`${ge}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${ge}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:ve,...x,...Me,k>0?`\u{1F5D3}\uFE0F ${k} relative time reference${k===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(J.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",mo(q)??""].filter(b=>b!=="").join(`
|
|
3
|
+
`)}case"lesson_verified":{const{instance_id:h}=A,n=await F(h),p=new Date().toISOString(),w=A,o=je({geprueft_mit:w.geprueft_mit,befund:w.befund}),a=ys({...w,...o.felder},p);if(!a.ok)return[`\u26A0\uFE0F ${a.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
|
|
4
|
+
`);const N=a.eintrag,d=`cachly:lesson:best:${N.topic}`,r=await n.get(d);if(!r)return`\u{1F4ED} Keine Lektion \`${N.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const S=P(r,{}),t=_s(S,N);return await n.set(d,JSON.stringify(o.verdacht.length?{...t,tags:So(t.tags,o.verdacht)}:t)),Rt(),N.haelt?[`\u2705 \`${N.topic}\` ist wieder frisch \u2014 geprueft am ${p.slice(0,10)}.`,N.geprueft_mit?` geprueft mit: \`${N.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...Ve(o)].filter(Boolean).join(`
|
|
5
|
+
`):[`\u26A0\uFE0F \`${N.topic}\` ist als fraglich markiert.`,` Befund: ${N.befund}`,"","Geloescht wurde nichts \u2014 eine Pruefung kann aus Gruenden fehlschlagen,","die mit der Lektion nichts zu tun haben. Wenn du weisst, was jetzt gilt:",`\`learn_from_attempts(topic="${N.topic}", \u2026, grund="\u2026")\`.`,...Ve(o)].join(`
|
|
6
|
+
`)}case"recall_feedback":{const{instance_id:h}=A,n=await F(h),p=xn(Tn(A),new Date().toISOString());if(!p.ok)return[`\u26A0\uFE0F ${p.grund}`,"","Example:","```",'recall_feedback(instance_id="\u2026", query="why does the deploy abort",',' topic="ci:timeout-reports-cancelled", helped=true, rank=0)',"```","rank=0 means: the lesson was NOT in the answer at all.","That is the most valuable feedback there is."].join(`
|
|
7
|
+
`);const w=p.eintrag,o=`cachly:wirkung:${h}`;await n.rpush(o,JSON.stringify(w));const N=(await n.lrange(o,0,-1).catch(()=>[])).map(s=>P(s,null)).filter(Boolean),d=Nn(N),r=En(w),S={"fehlender-treffer":"It helped but was not in the answer at all \u2014 the search never picked it up. That is the most valuable case.","zu-weit-hinten":`It helped but was only at rank ${w.platz} \u2014 the ranking was too weak.`,"falsch-und-sicher":`It was at rank ${w.platz} and did not help \u2014 the ranking was confident and wrong.`,bestaetigung:"It was near the top and helped. Confirmed.",unauffaellig:"It did not help and was far down. Says little."},t=d.trefferquote===null?"no helpful feedback yet":`${(d.trefferquote*100).toFixed(0)} % of the helpful lessons were in the top three`;return[`\u2705 Noted: **${w.thema}** \u2014 ${w.geholfen?"helped":"did not help"}, rank ${w.platz===0?"\u2014 (not in the answer)":w.platz}`,"",S[r],"",`Feedback so far: ${d.gesamt}, ${t}.`,`Of these: ${d.nachLehrwert["fehlender-treffer"]} not found \xB7 ${d.nachLehrwert["zu-weit-hinten"]} too far down \xB7 ${d.nachLehrwert["falsch-und-sicher"]} confident and wrong.`].join(`
|
|
8
|
+
`)}case"recall_best_solution":{const h=Date.now(),{instance_id:n,topic:p,author:w}=A,o=await Hs(n,ce,`\u{1F4ED} No lessons found for \`${p}\`.`);if(o)return o;const a=await F(n);try{const s=await a.get(`cachly:letzter-recall:${n}`),C=s?P(s,null):null,i=An(C,p,new Date().toISOString());i&&(await a.rpush(`cachly:wirkung:${n}`,JSON.stringify(i)),await a.del(`cachly:letzter-recall:${n}`))}catch{}const N=await a.get(`cachly:lesson:best:${p}`);if(N){const s=P(N,null);if(!s)return`\u26A0\uFE0F Lesson data for \`${p}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const C=s.group;if(C){const oe=w?await It(a,n,w).catch(()=>new Set):new Set,ue=w?await ut(a,n,w).catch(()=>null)==="admin":!1;if(!Mt(C,oe,ue))return`\u{1F4ED} No lessons found for \`${p}\`. Use \`learn_from_attempts\` after solving it.`}const i=vt(s),c=s.verified_at??s.ts,$=(Date.now()-new Date(c).getTime())/864e5,m=s.commands,g=ps(i,$,Array.isArray(m)&&typeof m[0]=="string"?m[0]:void 0,s.pruefung_gefallen_am?{am:s.pruefung_gefallen_am,befund:s.pruefung_befund}:void 0),M=new Date().toISOString(),I={...s,recall_count:(s.recall_count??0)+1,last_recalled_at:M};await a.set(`cachly:lesson:best:${p}`,JSON.stringify(I)),bt(a),wt(a,String(p??""),Date.now()-h);const e=xt(s)?Ct(s):0;e>0&&a.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,e).catch(()=>{});const V=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":s.severity?"\u{1F7E2}":"",ie=s.audit_trail??[],ae=ie.filter(oe=>oe&&typeof oe.grund=="string"&&oe.grund.trim().length>0).slice(-3).map(oe=>` \xB7 ${oe.ts?new Date(oe.ts).toLocaleDateString("de-DE"):"?"}: ${oe.grund.trim()}`),de=ie.length>1?[`_Audit: ${ie.length} changes \xB7 stored ${new Date(s.ts).toLocaleDateString("de-DE")}_`,...ae.length>0?["**Warum zuletzt geaendert:**",...ae]:[]].join(`
|
|
9
|
+
`):"",Y=(Date.now()-new Date(s.ts).getTime())/864e5,f=Y>60?`\u{1F4AD} _Remember when you solved this ${Math.round(Y/30)} months ago? Still works._`:"",J=I.recall_count===3&&!s.pinned?"\u{1F4CC} **This lesson came up in 3 answers so far.** If you need it often, pin it: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",Z=s.authors??(s.author?[s.author]:[]),Q=[...new Set(Z.filter(Boolean))];let X="";Q.length>=2&&(X=`\u2705 **Team-verified** \u2014 confirmed by ${Q.length} developers.`);const q=s.ersetzt_durch,ne=s.ersetzt_am?` (on ${s.ersetzt_am.slice(0,10)})`:"",l=q?await a.get(`cachly:lesson:best:${q}`):null,k=String(s.ersetzt_grund??"").trim(),T=k?` Reason: ${k}`:" No reason recorded.",E=l?!Ke(De(l)):!1,_=q?l?E?`\u{1F6AB} **THIS VERSION IS REPLACED**${ne} \u2014 the successor lesson is private, not visible to the team. The text below stays readable as history; its author knows the current version.`:`\u{1F6AB} **THIS VERSION IS REPLACED**${ne} \u2014 the current answer is in \`recall_best_solution(topic="${q}")\`.${T} The text below stays readable as history.`:`\u26A0\uFE0F **REPLACEMENT POINTS NOWHERE**${ne} \u2014 the successor \`${q}\` has been deleted. This version applies again as the best EXISTING answer; confirm it when you can (learn_from_attempts with grund).`:"",v=s.gilt_ab,z=s.gilt_bis,G=v?`\u{1F4C5} Valid since ${String(v).slice(0,10)}.`:"",x=s.entscheidung,te=x?.gegen?Kt({gegen:x.gegen,grund:x.grund??null}):"",we=z&&Date.parse(String(z))<Date.now()?`\u23F3 **THIS FACT WAS VALID UNTIL ${String(z).slice(0,10)}** \u2014 it is history, not current information.`:"";return[es(s),_,we,un(s.gilt_fuer),G,te,f,X,`${g} **Best solution for \`${p}\`** ${V}${s.severity?` (${s.severity})`:""} \xB7 in ${I.recall_count} answer${I.recall_count===1?"":"s"} so far`,Pn(s.author,s.source),"",s.what_worked?`**What worked:** ${s.what_worked}`:"",s.what_failed?`**What failed (avoid this):** ${s.what_failed}`:"",s.context?`**Context:** ${s.context}`:"",(s.file_paths??[]).length>0?`**Files:** ${(s.file_paths??[]).map(oe=>`\`${oe}\``).join(", ")}`:"",(s.commands??[]).length>0?`**Commands:** ${(s.commands??[]).map(oe=>`\`${oe}\``).join(", ")}`:"",(s.tags??[]).length>0?`**Tags:** ${(s.tags??[]).map(oe=>`#${oe}`).join(" ")}`:"",de,J].filter(oe=>oe!=="").join(`
|
|
10
|
+
`)}const d=[],r=a.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((s,C)=>{r.on("data",i=>d.push(...i)),r.on("end",s),r.on("error",C)});const S=d.filter(s=>s.toLowerCase().includes(p.toLowerCase()));if(S.length===0){const s=`cachly:lessons:${p}`,C=await a.lrange(s,-3,-1);if(C.length>0){const c=C.map($=>P($,null)).filter(Boolean).map($=>`- ${$.outcome==="success"?"\u2705":"\u274C"} ${$.what_worked.slice(0,120)} (${new Date($.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${p}\` yet. Last attempts:
|
|
11
11
|
|
|
12
12
|
${c.join(`
|
|
13
|
-
`)}`}return`\u{1F4ED} No lessons found for \`${
|
|
14
|
-
`:""}**\`${i.topic}\`** \u2014 ${i.what_worked.slice(0,400)}${i.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${
|
|
13
|
+
`)}`}return`\u{1F4ED} No lessons found for \`${p}\`. Use \`learn_from_attempts\` after solving it.`}const t=[];for(const s of S.slice(0,5)){const C=await a.get(s);if(!C)continue;const i=P(C,null);if(!i)continue;const c=es(i);t.push(`${c?`${c}
|
|
14
|
+
`:""}**\`${i.topic}\`** \u2014 ${i.what_worked.slice(0,400)}${i.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${p}\`:**
|
|
15
15
|
|
|
16
16
|
${t.join(`
|
|
17
17
|
|
|
18
|
-
`)}`}case"smart_recall":{const h=Date.now(),{instance_id:n,query:m,threshold:w=.78,author:a="",context_files:o=[],limit:N}=I,d=Sn(m),r=Zn(N),S=Array.isArray(o)?o.filter(u=>typeof u=="string"):[];if(ye("smart_recall: Anfang"),!vn(d))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await Lt(n,ce)){const u=Date.now()-h;return F(n).then(y=>is(y,n,String(d??""),u)).catch(()=>{}),ye("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),Ot(String(d??""),{startet:!0,...await dt(n)})}const t=await F(n);ye("smart_recall: Verbindung steht");const{vektor:s,namen:C,zweit:i,eingang:c,seltenheit:$}=yt(t);us(t,void 0,2);let f=new Set,g=!1;a&&(f=await It(t,n,a).catch(()=>new Set),g=await ht(t,n,a).catch(()=>null)==="admin");const M=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],A=await Gs(t,M);if(!A)return is(t,n,String(d??""),Date.now()-h),ye("smart_recall: Brain leer \u2014 sofort geantwortet"),Ot(String(d??""),{startet:!1,...await dt(n)});const e=A.docs.reduce((u,y)=>u+(y.key.startsWith("cachly:lesson:best:")?1:0),0),J=await et(t,M,d,25);ye(`smart_recall: Wortsuche fertig (${J.length} Treffer)`);const ie=Vs(J);let ae=!1,de=null;const U=await(async()=>{if(!ze())return rt(Es,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),ie;try{if(await s.aktualisiere(t),ye(`smart_recall: Vektorbestand geladen (${s.groesse})`),s.groesse===0)return e>0&&rt(Ns,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),ie;const u=await Ce(d);if(ye("smart_recall: Frage eingebettet"),!u?.length)return rt(As,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),ie;await C.aktualisiere(t),await c.aktualisiere(t),await $.aktualisiere(t),await i.aktualisiere(t);const y=s.groesse>0?i.groesse/s.groesse:0;y<Jt&&s.groesse>0&&Mo(t,3);const B=y>=Jt?Ce(d,{modell:Ue}).catch(()=>null):null,re=ie.filter(W=>W.key.startsWith("cachly:lesson:best:")).map(W=>W.key.slice(19)),L=W=>Math.max(s.naehe(u,W),C.naehe(u,W)),q=[...$.themen()],Q=(q.length>0?q:s.aehnlichste(u,500).map(W=>W.topic)).map(W=>({t:W,n:L(W)})).sort((W,pe)=>pe.n-W.n).slice(0,Yt).map(W=>W.t),b=[...new Set([...re,...Q])],R=Q.slice(0,3).map(W=>s.rohvektor(W)).filter(Boolean),oe=R.length?yn(u,R):u,O=Ht(d),D=$.statistik,K=b.map(W=>{const pe=new Set([...Ht($.textVon(W))].map(_n));return{naeheText:s.naehe(u,W),naeheThema:C.naehe(u,W),naeheRueckkopplung:s.naehe(oe,W),seltenheitsDeckung:D?D.deckung(O,pe):0,besterZeuge:D?D.besterZeuge(O,pe):0}});let le=wn(K,bn);{const W=[...le].sort((pe,ke)=>ke-pe);de=W.length>1?W[0]-W[1]:null}if(c.groesse>0){const W=b.map(ke=>{const Se=c.besteNaehe(u,ke);return Se>=qn?Se:-2}),pe=Gt(W);le=le.map((ke,Se)=>ke+Un*pe[Se])}if(B){const W=await B;if(W?.length){const pe=Gt(b.map(ke=>i.naehe(W,ke)));le=le.map((ke,Se)=>ke+Dn*pe[Se])}}let he=b.map((W,pe)=>({t:W,p:le[pe]})).sort((W,pe)=>pe.p-W.p).map(W=>W.t);if(Ys(n)&&he.length>1){const W=he.slice(0,Vt),pe=he.slice(Vt),ke=new Map(b.map((Ze,qe)=>[Ze,le[qe]]));ye("smart_recall: Leser Anfang");const Se=await Zs(d,W.map(Ze=>$.leserTextVon(Ze)),{instanceId:n});ye(`smart_recall: Leser ${Se?"fertig":"ohne Ergebnis"}`),Se&&(he=[...Xs(W.map(qe=>ke.get(qe)??0),Se).map(qe=>W[qe]),...pe])}const $e=new Map(ie.map(W=>[W.key,W])),Oe=[];for(const W of he){const pe=`cachly:lesson:best:${W}`,ke=$e.get(pe);if(ke){Oe.push(ke),$e.delete(pe);continue}const Se=await t.get(pe).catch(()=>null);Se&&Oe.push({key:pe,content:Se,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return Oe.push(...$e.values()),Rn&&Mn({frage:d.slice(0,200),themen:b,ausWortsuche:re.length,ausSinnsuche:Q.length,obergrenze:Yt,gezeigt:he.slice(0,10)}),ae=!0,Oe}catch(u){return await Qe(t,Is,`der Bedeutungspfad brach ab (${u instanceof Error?u.message:String(u)}) \u2014 diese Suche lief nur ueber Woerter`),ie}})();ye("smart_recall: Bedeutungspfad fertig"),bt(t),wt(t,String(d??""),Date.now()-h);{const u=U.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(u.length>0){const y={ts:new Date().toISOString(),themen:u};(async()=>{const B=jt(n);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,pn-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:d.slice(0,200),geliefert:u};(async()=>{const B=gt(n);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,Ft-1)})().catch(()=>{})}}if(ze()&&!At()){const u=U.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));rn(t,d,u,Ce).catch(()=>{})}const p=U.filter(u=>u.key.startsWith("cachly:lesson:best:"));let H=0,Y=0;for(const u of p.slice(0,5)){const y=await t.get(u.key).catch(()=>null);if(y){const B=j(y,null);if(B?.state==="archived")continue;if(B){const re=new Date().toISOString(),L={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:re};At()||t.set(u.key,JSON.stringify(L)).catch(()=>{});const q=xt(B)?Ct(B):0;if(q>0&&t.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,q).catch(()=>{}),B.author&&a&&B.author!==a){H++,t.sadd(`cachly:stats:reuse_pairs:${n}`,`${a}<-${B.author}`).catch(()=>{});const Q=`person:${me(a)}`,b=`person:${me(B.author)}`;_e(t,Q,"collaborates",b,!0).catch(()=>{}),_e(t,b,"collaborates",Q,!0).catch(()=>{})}B.outcome==="success"&&Y++}}}Y>0&&t.set(`cachly:stats:first_recall_at:${n}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),p.length>0&&(t.incr(`cachly:stats:recalls_total:${n}`).catch(()=>{}),H>0&&t.incr(`cachly:stats:cross_author_recalls:${n}`).catch(()=>{})),ye("smart_recall: Treffer gezaehlt");const X=Ds(t,ut(d).filter(u=>u.length>=4).slice(0,4)).catch(()=>null),Z=await Os(n,()=>ce(`/api/v1/instances/${n}`));ye("smart_recall: Tarif abgefragt");const V=!Z?.tier||Z.tier.toLowerCase()==="free",se=[];if(!V&&Z?.vector_token&&ze())try{const u=await Ce(d),y=`https://api.cachly.dev/v1/sem/${Z.vector_token}`,B=await fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:u,namespace:"cachly:ctx",threshold:w,top_k:5}),signal:AbortSignal.timeout(8e3)});if(B.ok){const L=(await B.json()).filter(Q=>Q.found&&Q.id).map(Q=>{const b=Q.id.replace("ctx:","").split(":");return{hit:Q,redisKey:`cachly:ctx:${b[0]}:${b.slice(1).join(":")}`}}),q=await Promise.all(L.map(Q=>t.get(Q.redisKey).catch(()=>null)));L.forEach((Q,b)=>{se.push({key:Q.redisKey,similarity:Q.hit.similarity??0,content:q[b]??"(evicted)"})})}}catch{}const l=U.map(u=>u.score),k=l.length?Math.min(...l):0,T=l.length&&Math.max(...l)-k||1,E=u=>(u-k)/T,_=new Map,v=ae?on(U.map(u=>E(u.score))):null,P=new Map;for(const[u,y]of U.entries()){const B=E(y.score),re=v?v[u]:B;v&&_.set(y.key,u),P.set(y.key,{key:y.key,content:y.content,bm25Score:B,hausWert:re,hybridScore:re*(se.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const u of se){const y=P.get(u.key);y?(y.semScore=u.similarity,y.hybridScore=(y.hausWert??0)*.6+u.similarity*.4,y.matchType="hybrid"):P.set(u.key,{key:u.key,content:u.content,semScore:u.similarity,hybridScore:u.similarity*.5,matchType:"semantic"})}try{const u=await X,y=new Set;for(const{kante:B,inhalt:re}of u??[]){if(B.edgeType!=="fixes"||B.confidence<.35||y.has(B.from))continue;y.add(B.from);const L=`cachly:lesson:best:${B.from}`,q=P.get(L);if(q)q.ckgScore=Math.max(q.ckgScore??0,B.confidence),q.hybridScore=q.hybridScore*.88+B.confidence*.12,q.matchType==="keyword"&&(q.matchType="hybrid");else{if(!re)continue;P.set(L,{key:L,content:re,ckgScore:B.confidence,hybridScore:B.confidence*.3,matchType:"ckg"})}}}catch{}if(ye("smart_recall: Sinn-Dienst und CKG fertig"),S.length>0){const u=new Set(S.map(y=>y.replace(/\\/g,"/")));for(const y of P.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const B=j(y.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(L=>typeof L=="string").map(L=>L.replace(/\\/g,"/")):[]).some(L=>u.has(L))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const u of P.values()){if(u.matchType!=="semantic"&&u.matchType!=="ckg")continue;const y=Us({key:u.key,content:u.content});y&&(u.hybridScore*=qs(y))}const G=[...P.values()].filter(u=>{if(!u.key.startsWith("cachly:lesson:best:"))return!0;const y=De(u.content);return!(!Ke(y)||!Mt(y?.group,f,g))}),x=v?nn(G,_):G.sort((u,y)=>y.hybridScore-u.hybridScore),ee=[];for(const u of x){if(!u.key.startsWith("cachly:lesson:best:"))continue;const y=j(u.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&ee.push(`\u23F3 \`${u.key.replace("cachly:lesson:best:","")}\` was valid until ${String(y.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const B=j(u.content,{});if(B.pruefung_gefallen_am){const re=u.key.replace("cachly:lesson:best:",""),L=String(B.pruefung_gefallen_am).slice(0,10),q=String(B.pruefung_befund??"").trim().slice(0,200);ee.push(`\u274C \`${re}\` \u2014 Pruefung am ${L} FEHLGESCHLAGEN`+(q?`: ${q}`:""))}}{const u=new Set(x.map(y=>y.key));for(let y=x.length-1;y>=0;y--){const B=x[y];if(!B.key.startsWith("cachly:lesson:best:"))continue;const re=j(B.content,{});if(!re.ersetzt_durch)continue;const L=String(re.ersetzt_grund??"").trim(),q=B.key.replace("cachly:lesson:best:","");if(u.has(`cachly:lesson:best:${re.ersetzt_durch}`))x.splice(y,1),ee.push(`\u21B7 \`${q}\` hidden \u2014 replaced by \`${re.ersetzt_durch}\`${re.ersetzt_am?` on ${re.ersetzt_am.slice(0,10)}`:""}${L?` \u2014 reason: ${L}`:" \u2014 no reason recorded"}`);else if(await t.get(`cachly:lesson:best:${re.ersetzt_durch}`)){const Q=De(await t.get(`cachly:lesson:best:${re.ersetzt_durch}`));Ke(Q)?ee.push(`\u26A0\uFE0F \`${q}\` is replaced by \`${re.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${re.ersetzt_durch}")\``):ee.push(`\u21B7 \`${q}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`)}else ee.push(`\u21A9\uFE0F \`${q}\` was replaced by \`${re.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const we=ln(x,S),ne=[];{await s.aktualisiere(t).catch(()=>{});const u=x.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<u.length;y++)for(let B=y+1;B<u.length;B++){const re=u[y].key.replace("cachly:lesson:best:",""),L=u[B].key.replace("cachly:lesson:best:",""),q=s.rohvektor(re),Q=s.rohvektor(L);if(!q||!Q)continue;let b=0,R=0,oe=0;for(let K=0;K<q.length;K++)b+=q[K]*Q[K],R+=q[K]*q[K],oe+=Q[K]*Q[K];if((R>0&&oe>0?b/(Math.sqrt(R)*Math.sqrt(oe)):0)<zn)continue;const D=K=>{const le=j(K??"",{});return String(le.verified_at??le.ts??"").slice(0,10)||"no date"};ne.push(`\u26A0\uFE0F \`${re}\` (${D(u[y].content)}) und \`${L}\` (${D(u[B].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}ne.length>3&&(ne.length=3)}if(ee.push(...ne),x.length>=2){const u=x[0].hybridScore,y=x[Math.min(4,x.length-1)].hybridScore,B=Math.max(0,u-y);(async()=>{try{await t.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:x.length})),await t.ltrim("cachly:recall:spread",0,199)}catch{}})()}const ue=Ms();let fe="",be=null;if(ue!==null){fe=Rs();const u=x[0]?.hybridScore??0,y=Bs(x.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),fe,ue,u);y.weggelassenesThema!==void 0?x.splice(0,1):y.markierungGesetzt&&x[0]&&y.treffer[0]&&(x[0]={...x[0],content:y.treffer[0].content}),be={frage:d,hoechstePunktzahl:u,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}ye("smart_recall: Notizen und Duplikate fertig");const Me=await hs(n,ce);ye("smart_recall: Abruf-Grenze abgefragt");const Re=Me.reached,ge=Zt({ueberLimit:Re,gesamt:x.length,volleTiefe:r??Xn}),ve=process.env.CACHLY_RECALL_COMPACT==="1",Ie=(()=>{const u=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(u)?Math.min(20,Math.max(1,u)):5})(),Be=ve?Math.min(Ie,ge.sichtbar):ge.sichtbar,te=[`\u{1F9E0} **Smart Recall** for: _"${d}"_
|
|
19
|
-
`];Me.goodwillMessage&&
|
|
20
|
-
`),
|
|
21
|
-
`);const Le=x.filter(u=>u.contextBoost).length;Le>0&&
|
|
22
|
-
`);const Te=Fs(d);Te.length>1&&
|
|
23
|
-
`);const Ee=Ts(x.map(u=>({wortBelege:u.wortBelege,semScore:u.semScore,ckgScore:u.ckgScore})));if(Ee.schweigen)return $t(t,n,"schweigen"),
|
|
24
|
-
`);const Ne=$n(de);if(Ne&&
|
|
25
|
-
`),Ee.belegte<x.length){const L=[];for(const
|
|
26
|
-
`)}if(
|
|
27
|
-
`);for(const
|
|
28
|
-
\u26A0\uFE0F **No results for:** ${b.map(
|
|
29
|
-
`)}}else{
|
|
30
|
-
\u{1F4A1} Tips:`),
|
|
31
|
-
`))}return
|
|
32
|
-
`)}case"session_start":{const{instance_id:h,focus:n="",author:
|
|
18
|
+
`)}`}case"smart_recall":{const h=Date.now(),{instance_id:n,query:p,threshold:w=.78,author:o="",context_files:a=[],limit:N}=A,d=Sn(p),r=Zn(N),S=Array.isArray(a)?a.filter(u=>typeof u=="string"):[];if(ye("smart_recall: Anfang"),!vn(d))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await Lt(n,ce)){const u=Date.now()-h;return F(n).then(y=>is(y,n,String(d??""),u)).catch(()=>{}),ye("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),Ot(String(d??""),{startet:!0,...await ft(n)})}const t=await F(n);ye("smart_recall: Verbindung steht");const{vektor:s,namen:C,zweit:i,eingang:c,seltenheit:$}=yt(t);us(t,void 0,2);let m=new Set,g=!1;o&&(m=await It(t,n,o).catch(()=>new Set),g=await ut(t,n,o).catch(()=>null)==="admin");const M=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],I=await Gs(t,M);if(!I)return is(t,n,String(d??""),Date.now()-h),ye("smart_recall: Brain leer \u2014 sofort geantwortet"),Ot(String(d??""),{startet:!1,...await ft(n)});const e=I.docs.reduce((u,y)=>u+(y.key.startsWith("cachly:lesson:best:")?1:0),0),V=await et(t,M,d,25);ye(`smart_recall: Wortsuche fertig (${V.length} Treffer)`);const ie=Vs(V);let ae=!1,de=null;const Y=await(async()=>{if(!ze())return it(Es,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),ie;try{if(await s.aktualisiere(t),ye(`smart_recall: Vektorbestand geladen (${s.groesse})`),s.groesse===0)return e>0&&it(Ns,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),ie;const u=await Ce(d);if(ye("smart_recall: Frage eingebettet"),!u?.length)return it(As,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),ie;await C.aktualisiere(t),await c.aktualisiere(t),await $.aktualisiere(t),await i.aktualisiere(t);const y=s.groesse>0?i.groesse/s.groesse:0;y<Jt&&s.groesse>0&&Mo(t,3);const R=y>=Jt?Ce(d,{modell:Ue}).catch(()=>null):null,re=ie.filter(W=>W.key.startsWith("cachly:lesson:best:")).map(W=>W.key.slice(19)),L=W=>Math.max(s.naehe(u,W),C.naehe(u,W)),U=[...$.themen()],ee=(U.length>0?U:s.aehnlichste(u,500).map(W=>W.topic)).map(W=>({t:W,n:L(W)})).sort((W,pe)=>pe.n-W.n).slice(0,Yt).map(W=>W.t),b=[...new Set([...re,...ee])],j=ee.slice(0,3).map(W=>s.rohvektor(W)).filter(Boolean),H=j.length?yn(u,j):u,B=Ht(d),O=$.statistik,K=b.map(W=>{const pe=new Set([...Ht($.textVon(W))].map(_n));return{naeheText:s.naehe(u,W),naeheThema:C.naehe(u,W),naeheRueckkopplung:s.naehe(H,W),seltenheitsDeckung:O?O.deckung(B,pe):0,besterZeuge:O?O.besterZeuge(B,pe):0}});let le=wn(K,bn);{const W=[...le].sort((pe,ke)=>ke-pe);de=W.length>1?W[0]-W[1]:null}if(c.groesse>0){const W=b.map(ke=>{const Se=c.besteNaehe(u,ke);return Se>=qn?Se:-2}),pe=Gt(W);le=le.map((ke,Se)=>ke+Un*pe[Se])}if(R){const W=await R;if(W?.length){const pe=Gt(b.map(ke=>i.naehe(W,ke)));le=le.map((ke,Se)=>ke+Dn*pe[Se])}}let he=b.map((W,pe)=>({t:W,p:le[pe]})).sort((W,pe)=>pe.p-W.p).map(W=>W.t);if(Ys(n)&&he.length>1){const W=he.slice(0,Vt),pe=he.slice(Vt),ke=new Map(b.map((Ze,qe)=>[Ze,le[qe]]));ye("smart_recall: Leser Anfang");const Se=await Zs(d,W.map(Ze=>$.leserTextVon(Ze)),{instanceId:n});ye(`smart_recall: Leser ${Se?"fertig":"ohne Ergebnis"}`),Se&&(he=[...Xs(W.map(qe=>ke.get(qe)??0),Se).map(qe=>W[qe]),...pe])}const $e=new Map(ie.map(W=>[W.key,W])),Oe=[];for(const W of he){const pe=`cachly:lesson:best:${W}`,ke=$e.get(pe);if(ke){Oe.push(ke),$e.delete(pe);continue}const Se=await t.get(pe).catch(()=>null);Se&&Oe.push({key:pe,content:Se,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return Oe.push(...$e.values()),Rn&&Mn({frage:d.slice(0,200),themen:b,ausWortsuche:re.length,ausSinnsuche:ee.length,obergrenze:Yt,gezeigt:he.slice(0,10)}),ae=!0,Oe}catch(u){return await Qe(t,Is,`der Bedeutungspfad brach ab (${u instanceof Error?u.message:String(u)}) \u2014 diese Suche lief nur ueber Woerter`),ie}})();ye("smart_recall: Bedeutungspfad fertig"),bt(t),wt(t,String(d??""),Date.now()-h);{const u=Y.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(u.length>0){const y={ts:new Date().toISOString(),themen:u};(async()=>{const R=jt(n);await t.lpush(R,JSON.stringify(y)),await t.ltrim(R,0,pn-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:d.slice(0,200),geliefert:u};(async()=>{const R=gt(n);await t.lpush(R,JSON.stringify(y)),await t.ltrim(R,0,Ft-1)})().catch(()=>{})}}if(ze()&&!At()){const u=Y.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));rn(t,d,u,Ce).catch(()=>{})}const f=Y.filter(u=>u.key.startsWith("cachly:lesson:best:"));let J=0,Z=0;for(const u of f.slice(0,5)){const y=await t.get(u.key).catch(()=>null);if(y){const R=P(y,null);if(R?.state==="archived")continue;if(R){const re=new Date().toISOString(),L={...R,recall_count:(R.recall_count??0)+1,last_recalled_at:re};At()||t.set(u.key,JSON.stringify(L)).catch(()=>{});const U=xt(R)?Ct(R):0;if(U>0&&t.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,U).catch(()=>{}),R.author&&o&&R.author!==o){J++,t.sadd(`cachly:stats:reuse_pairs:${n}`,`${o}<-${R.author}`).catch(()=>{});const ee=`person:${me(o)}`,b=`person:${me(R.author)}`;_e(t,ee,"collaborates",b,!0).catch(()=>{}),_e(t,b,"collaborates",ee,!0).catch(()=>{})}R.outcome==="success"&&Z++}}}Z>0&&t.set(`cachly:stats:first_recall_at:${n}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),f.length>0&&(t.incr(`cachly:stats:recalls_total:${n}`).catch(()=>{}),J>0&&t.incr(`cachly:stats:cross_author_recalls:${n}`).catch(()=>{})),ye("smart_recall: Treffer gezaehlt");const Q=Ds(t,dt(d).filter(u=>u.length>=4).slice(0,4)).catch(()=>null),X=await Os(n,()=>ce(`/api/v1/instances/${n}`));ye("smart_recall: Tarif abgefragt");const q=!X?.tier||X.tier.toLowerCase()==="free",ne=[];if(!q&&X?.vector_token&&ze())try{const u=await Ce(d),y=`https://api.cachly.dev/v1/sem/${X.vector_token}`,R=await fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:u,namespace:"cachly:ctx",threshold:w,top_k:5}),signal:AbortSignal.timeout(8e3)});if(R.ok){const L=(await R.json()).filter(ee=>ee.found&&ee.id).map(ee=>{const b=ee.id.replace("ctx:","").split(":");return{hit:ee,redisKey:`cachly:ctx:${b[0]}:${b.slice(1).join(":")}`}}),U=await Promise.all(L.map(ee=>t.get(ee.redisKey).catch(()=>null)));L.forEach((ee,b)=>{ne.push({key:ee.redisKey,similarity:ee.hit.similarity??0,content:U[b]??"(evicted)"})})}}catch{}const l=Y.map(u=>u.score),k=l.length?Math.min(...l):0,T=l.length&&Math.max(...l)-k||1,E=u=>(u-k)/T,_=new Map,v=ae?on(Y.map(u=>E(u.score))):null,z=new Map;for(const[u,y]of Y.entries()){const R=E(y.score),re=v?v[u]:R;v&&_.set(y.key,u),z.set(y.key,{key:y.key,content:y.content,bm25Score:R,hausWert:re,hybridScore:re*(ne.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const u of ne){const y=z.get(u.key);y?(y.semScore=u.similarity,y.hybridScore=(y.hausWert??0)*.6+u.similarity*.4,y.matchType="hybrid"):z.set(u.key,{key:u.key,content:u.content,semScore:u.similarity,hybridScore:u.similarity*.5,matchType:"semantic"})}try{const u=await Q,y=new Set;for(const{kante:R,inhalt:re}of u??[]){if(R.edgeType!=="fixes"||R.confidence<.35||y.has(R.from))continue;y.add(R.from);const L=`cachly:lesson:best:${R.from}`,U=z.get(L);if(U)U.ckgScore=Math.max(U.ckgScore??0,R.confidence),U.hybridScore=U.hybridScore*.88+R.confidence*.12,U.matchType==="keyword"&&(U.matchType="hybrid");else{if(!re)continue;z.set(L,{key:L,content:re,ckgScore:R.confidence,hybridScore:R.confidence*.3,matchType:"ckg"})}}}catch{}if(ye("smart_recall: Sinn-Dienst und CKG fertig"),S.length>0){const u=new Set(S.map(y=>y.replace(/\\/g,"/")));for(const y of z.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const R=P(y.content,{});(Array.isArray(R.file_paths)?R.file_paths.filter(L=>typeof L=="string").map(L=>L.replace(/\\/g,"/")):[]).some(L=>u.has(L))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const u of z.values()){if(u.matchType!=="semantic"&&u.matchType!=="ckg")continue;const y=Us({key:u.key,content:u.content});y&&(u.hybridScore*=qs(y))}const G=[...z.values()].filter(u=>{if(!u.key.startsWith("cachly:lesson:best:"))return!0;const y=De(u.content);return!(!Ke(y)||!Mt(y?.group,m,g))}),x=v?nn(G,_):G.sort((u,y)=>y.hybridScore-u.hybridScore),te=[];for(const u of x){if(!u.key.startsWith("cachly:lesson:best:"))continue;const y=P(u.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&te.push(`\u23F3 \`${u.key.replace("cachly:lesson:best:","")}\` was valid until ${String(y.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const R=P(u.content,{});if(R.pruefung_gefallen_am){const re=u.key.replace("cachly:lesson:best:",""),L=String(R.pruefung_gefallen_am).slice(0,10),U=String(R.pruefung_befund??"").trim().slice(0,200);te.push(`\u274C \`${re}\` \u2014 Pruefung am ${L} FEHLGESCHLAGEN`+(U?`: ${U}`:""))}}{const u=new Set(x.map(y=>y.key));for(let y=x.length-1;y>=0;y--){const R=x[y];if(!R.key.startsWith("cachly:lesson:best:"))continue;const re=P(R.content,{});if(!re.ersetzt_durch)continue;const L=String(re.ersetzt_grund??"").trim(),U=R.key.replace("cachly:lesson:best:","");if(u.has(`cachly:lesson:best:${re.ersetzt_durch}`))x.splice(y,1),te.push(`\u21B7 \`${U}\` hidden \u2014 replaced by \`${re.ersetzt_durch}\`${re.ersetzt_am?` on ${re.ersetzt_am.slice(0,10)}`:""}${L?` \u2014 reason: ${L}`:" \u2014 no reason recorded"}`);else if(await t.get(`cachly:lesson:best:${re.ersetzt_durch}`)){const ee=De(await t.get(`cachly:lesson:best:${re.ersetzt_durch}`));Ke(ee)?te.push(`\u26A0\uFE0F \`${U}\` is replaced by \`${re.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${re.ersetzt_durch}")\``):te.push(`\u21B7 \`${U}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`)}else te.push(`\u21A9\uFE0F \`${U}\` was replaced by \`${re.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const we=ln(x,S),oe=[];{await s.aktualisiere(t).catch(()=>{});const u=x.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<u.length;y++)for(let R=y+1;R<u.length;R++){const re=u[y].key.replace("cachly:lesson:best:",""),L=u[R].key.replace("cachly:lesson:best:",""),U=s.rohvektor(re),ee=s.rohvektor(L);if(!U||!ee)continue;let b=0,j=0,H=0;for(let K=0;K<U.length;K++)b+=U[K]*ee[K],j+=U[K]*U[K],H+=ee[K]*ee[K];if((j>0&&H>0?b/(Math.sqrt(j)*Math.sqrt(H)):0)<zn)continue;const O=K=>{const le=P(K??"",{});return String(le.verified_at??le.ts??"").slice(0,10)||"no date"};oe.push(`\u26A0\uFE0F \`${re}\` (${O(u[y].content)}) und \`${L}\` (${O(u[R].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}oe.length>3&&(oe.length=3)}if(te.push(...oe),x.length>=2){const u=x[0].hybridScore,y=x[Math.min(4,x.length-1)].hybridScore,R=Math.max(0,u-y);(async()=>{try{await t.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(R.toFixed(4)),n:x.length})),await t.ltrim("cachly:recall:spread",0,199)}catch{}})()}const ue=Ms();let fe="",be=null;if(ue!==null){fe=Rs();const u=x[0]?.hybridScore??0,y=Bs(x.map(R=>({key:R.key,content:R.content,punktzahl:R.hybridScore})),fe,ue,u);y.weggelassenesThema!==void 0?x.splice(0,1):y.markierungGesetzt&&x[0]&&y.treffer[0]&&(x[0]={...x[0],content:y.treffer[0].content}),be={frage:d,hoechstePunktzahl:u,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}ye("smart_recall: Notizen und Duplikate fertig");const Me=await hs(n,ce);ye("smart_recall: Abruf-Grenze abgefragt");const Re=Me.reached,ge=Zt({ueberLimit:Re,gesamt:x.length,volleTiefe:r??Xn}),ve=process.env.CACHLY_RECALL_COMPACT==="1",Ie=(()=>{const u=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(u)?Math.min(20,Math.max(1,u)):5})(),Be=ve?Math.min(Ie,ge.sichtbar):ge.sichtbar,se=[`\u{1F9E0} **Smart Recall** for: _"${d}"_
|
|
19
|
+
`];Me.goodwillMessage&&se.push(`${Me.goodwillMessage}
|
|
20
|
+
`),J>0&&se.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${J} of these lesson${J!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
|
|
21
|
+
`);const Le=x.filter(u=>u.contextBoost).length;Le>0&&se.push(`> \u{1F4C1} **Personalized** \u2014 ${Le} lesson${Le!==1?"s":""} boosted because ${Le!==1?"they match":"it matches"} your current file context (${S.slice(0,3).join(", ")}${S.length>3?", \u2026":""})
|
|
22
|
+
`);const Te=Fs(d);Te.length>1&&se.push(`_Detected ${Te.length} sub-topics:_ ${Te.map((u,y)=>`${y+1}. "${u}"`).join(", ")}
|
|
23
|
+
`);const Ee=Ts(x.map(u=>({wortBelege:u.wortBelege,semScore:u.semScore,ckgScore:u.ckgScore})));if(Ee.schweigen)return $t(t,n,"schweigen"),se.push(Cs(Ee)),se.join(`
|
|
24
|
+
`);const Ne=$n(de);if(Ne&&se.push(Ne,""),$t(t,n,Ne?"knapp":"beantwortet"),x.length>0){const u=x.some(L=>L.ckgScore!==void 0),y=ae||ne.length>0,R=y&&u?"keyword + semantic + CKG hybrid":y?"keyword + semantic hybrid":u?"keyword + CKG hybrid":"keyword",re=Math.min(Be,x.length);if(se.push(`### \u{1F50D} Results (${re<x.length&&Te.length<=1?`showing ${re} of ${x.length}`:x.length} \u2014 ${R})
|
|
25
|
+
`),Ee.belegte<x.length){const L=[];for(const ee of x){if(!ee.key.startsWith("cachly:lesson:best:")||!Tt({wortBelege:ee.wortBelege,semScore:ee.semScore,ckgScore:ee.ckgScore}))continue;const b=P(ee.content,{}),j=Date.parse(b.verified_at??b.ts??"");Number.isFinite(j)&&L.push(Math.floor((Date.now()-j)/864e5))}const U=xs(L);se.push(`> \u{1F4CA} ${Ee.belegte} of ${x.length} backed by evidence (at least one matching word, close meaning or a graph link). The rest are only the nearest entries, not evidence.`+(U?` \u23F3 ${U}`:"")+`
|
|
26
|
+
`)}if(te.push(...hn(x.slice(0,Be),we)),te.length>0&&se.push(...te.map(L=>`> ${L}`),""),Te.length>1){const L=new Map,U=Zt({ueberLimit:Re,gesamt:x.length,volleTiefe:r??Qn});for(const j of x.slice(0,U.sichtbar)){const H=j.subQuery??d;L.has(H)||L.set(H,[]),L.get(H).push(j)}for(const[j,H]of L){se.push(`**Topic: "${j}"** (${H.length} results)
|
|
27
|
+
`);for(const B of H.slice(0,ve?2:r??4)){const O=B.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),K=B.matchType==="ckg"?`CKG: ${(B.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:B.ckgScore!==void 0&&B.bm25Score!==void 0?`BM25: ${B.bm25Score.toFixed(2)}, CKG: ${B.ckgScore.toFixed(2)}, \u{1F500} hybrid`:B.matchType==="hybrid"?`BM25: ${(B.bm25Score??0).toFixed(2)}, sem: ${((B.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:B.matchType==="semantic"?`sem: ${((B.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(B.bm25Score??0).toFixed(2)}, matched: ${B.matchedWords?.join(", ")}`,le=ve?ht(B.key,B.content,300):ht(B.key,B.content,Nt,300);if(se.push(ve?` **${O}**`:` **${O}** _(${K})_`),B.key.startsWith("cachly:lesson:best:")){const he=await t.get(B.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(B.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),$e=he?P(he,{}):{};$e.title&&se.push(` \u{1F4D6} **${$e.title}** \u2014 ${$e.summary??""}`)}{const he=B.key.startsWith("cachly:lesson:best:")?ts(B.content):"";he&&se.push(` ${he}`)}for(const he of le)se.push(` > ${he}`);se.push("")}}const ee=[...L.keys()],b=Te.filter(j=>!ee.includes(j));b.length>0&&se.push(`
|
|
28
|
+
\u26A0\uFE0F **No results for:** ${b.map(j=>`"${j}"`).join(", ")}`)}else for(const L of x.slice(0,Be)){const U=L.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let ee="";if(L.key.startsWith("cachly:lesson:best:")){const O=P(L.content,{});O.author&&(ee=` \xB7 \u{1F464} ${O.author}`)}const b=L.contextBoost?" \xB7 \u{1F4C1} context match":"",j=L.matchType==="hybrid"?`BM25: ${(L.bm25Score??0).toFixed(2)}, sem: ${((L.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:L.matchType==="semantic"?`sem: ${((L.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(L.bm25Score??0).toFixed(2)}, matched: ${L.matchedWords?.join(", ")}`,H=ht(L.key,L.content,ve?Et:Nt,Et),B=Ee.belegte>0&&Ee.belegte<x.length&&!Tt({wortBelege:L.wortBelege,semScore:L.semScore,ckgScore:L.ckgScore})?" \xB7 \u26A0\uFE0F no evidence":"";se.push(ve?`**${U}**${B}`:`**${U}**${ee}${b} _(${j})_${B}`);{const O=P(L.content??"",{});O.entscheidung?.gegen&&se.push(Kt({gegen:O.entscheidung.gegen,grund:O.entscheidung.grund??null}))}if(L.key.startsWith("cachly:lesson:best:")){const O=await t.get(L.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(L.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),K=O?P(O,{}):{};K.title&&se.push(`\u{1F4D6} **${K.title}** \u2014 ${K.summary??""}`)}{const O=L.key.startsWith("cachly:lesson:best:")?ts(L.content):"";O&&se.push(O)}for(const O of H)se.push(`> ${O}`);se.push("")}if(Re&&ge.zurueckgehalten>0){const L=ge.zurueckgehalten;se.push(`\u{1F512} **Free recall limit reached** (${Me.used}/${Me.limit} this month). Showing your top match; ${L} further relevant lesson${L!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${To}
|
|
29
|
+
`)}}else{se.push(`\u26A0\uFE0F No matches found for: "${d}"`),te.length>0&&se.push("",...te.map(R=>`> ${R}`));const u=dt(d),y=[];if(Bt.size>0&&u.length>0)for(const R of u.slice(0,3)){if(R.length<4)continue;let re=3,L="";for(const U of Bt){if(U.length<3||Math.abs(U.length-R.length)>4)continue;const ee=Ks(R,U);ee>0&&ee<re&&(re=ee,L=U)}L&&y.push(`"${L}" (instead of "${R}")`)}y.length>0?se.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(se.push(`
|
|
30
|
+
\u{1F4A1} Tips:`),se.push(" \u2022 Try different keywords"),se.push(" \u2022 Use `list_remembered` to see available context"),se.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!ve&&x.length>0){se.push(""),se.push('\u21A9\uFE0E Did one of these help? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` (not in your tool list? use `cachly_tool(tool="recall_feedback", arguments={\u2026})`) \u2014 and if the right lesson was **not** in the list: the same call with `rank=0`. That is the only number that improves the ranking.');const u=x.filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));if(u.length>0)try{await t.setex(`cachly:letzter-recall:${n}`,7200,JSON.stringify({frage:d,themen:u}))}catch{}}if(ve&&x.length>0){const u=ws();u&&(se.push(""),se.push(u))}if(ue!==null&&be){const u=x.slice(0,Be).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return Ls(t,fe,{...be,themen:u},se.join(`
|
|
31
|
+
`))}return se.join(`
|
|
32
|
+
`)}case"session_start":{const{instance_id:h,focus:n="",author:p="",provider:w="",workspace_path:o=""}=A;if(await Lt(h,ce))return F(h).then(async l=>{await cs(l),await ls(l,n,w),await l.set("cachly:mcp:version:last_seen",Ye,"EX",365*86400)}).catch(()=>{}),ye("session_start: neues Brain startet noch \u2014 sofort geantwortet"),Js({instanzId:h,provider:w,...await ft(h)});const a=await F(h),N=[],d=a.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((l,k)=>{d.on("data",T=>N.push(...T)),d.on("end",l),d.on("error",k)});const r=[];let S=0;if(N.length>0){const l=await a.mget(...N);for(const k of l){const T=P(k??null,null);if(T){if(Qt(T)){S++;continue}ns(T.topic)||r.push(T)}}}r.sort((l,k)=>new Date(k.ts).getTime()-new Date(l.ts).getTime());let t=0;const s=a.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((l,k)=>{s.on("data",T=>{t+=T.filter(E=>!E.endsWith(":meta")).length}),s.on("end",l),s.on("error",k)});const C=await a.get("cachly:session:last"),i=P(C,null),c=n.toLowerCase().split(/\s+/).filter(Boolean),$=c.length>0?r.filter(l=>c.some(k=>l.topic.toLowerCase().includes(k)||(l.tags??[]).some(T=>T.toLowerCase().includes(k)))):[],{tage:m,rekord:g}=await cs(a);let M="";m>=7?M=`\u{1F525} **${m}-day streak!** ${m===g?" New record!":`Best: ${g}d`}`:m>1&&(M=`\u{1F525} ${m}-day streak`),await ls(a,n,w);const e=[`\u{1F9E0} **Session Briefing**${w?` \xB7 ${w}`:""}`,""];M&&e.push(M,"");const V=await hs(h,ce),ie=Yn({used:V.used,limit:V.limit});if(ie&&e.push(ie,""),V.notice&&!as.has(h)&&(as.add(h),e.push(V.notice,"")),i?.ts){const l=new Date(i.ts).getTime(),k=Math.floor((Date.now()-l)/864e5);if(k>=7&&!Number.isNaN(l)){const T=r.filter(E=>{const _=new Date(E.ts).getTime();return!Number.isNaN(_)&&_>l});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${k} days since your last session.`),T.length>0){const E=T.slice(0,3).map(_=>`\`${_.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${T.length} lesson${T.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${E}${T.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${r.length} lesson${r.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 a.get("cachly:mcp:version:last_seen")!==Ye){await a.set("cachly:mcp:version:last_seen",Ye,"EX",365*86400);const k=xo[Ye];if(k){e.push(...k,"");const T=Co();T&&e.push(`\u{1F4CA} ${T} MCP tools`,"")}}}catch{}const ae=!i&&r.length===0&&S===0&&t===0;ae&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),o?(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="${h}")\``),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(""));const de=$.slice(0,4),Y=new Set(de.map(l=>l.topic));if(p&&!ae)try{const l=`cachly:team:first_briefing:${p}`;if(!await a.get(l)){const T=r.filter(E=>E.author&&E.author!==p&&!Y.has(E.topic));if(T.length>0){await a.set(l,"1","EX",365*86400);const E=new Map;for(const _ of T){const v=_.author;E.has(v)||E.set(v,[]),E.get(v).push(_)}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[_,v]of E){e.push(` \u{1F464} **${_}** fixed ${v.length} thing${v.length>1?"s":""}:`);for(const z of v.slice(0,2)){const G=z.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${G} \`${z.topic}\` \u2014 ${z.what_worked.slice(0,90)}`),Y.add(z.topic)}v.length>2&&e.push(` \u2026 and ${v.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 f=await a.get("cachly:session:handoff");if(f)try{const l=JSON.parse(f),k=Math.round((Date.now()-new Date(l.ts).getTime())/6e4),T=k<60?`${k}m ago`:k<1440?`${Math.round(k/60)}h ago`:`${Math.round(k/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${T}):`),l.context_summary&&e.push(` ${l.context_summary}`),l.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const _ of l.remaining_tasks)e.push(` - ${_}`)}l.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${l.completed_tasks.join(", ")}`);const E=(l.files_changed??[]).filter(_=>_.status==="broken"||_.status==="partial");E.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${E.map(_=>`\`${_.path}\` (${_.status}${_.description?": "+_.description:""})`).join(", ")}`),l.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${l.blocked_on}`),l.instructions&&e.push(` \u{1F4DD} **Instructions:** ${l.instructions}`),e.push("")}catch{}const J=await a.get("cachly:session:checkpoint");if(J)try{const l=JSON.parse(J),k=new Date(l.ts).getTime(),T=i?new Date(i.ts).getTime():0;if(k>T){const E=Math.round((Date.now()-k)/6e4),_=E<60?`${E}m ago`:E<1440?`${Math.round(E/60)}h ago`:`${Math.round(E/1440)}d ago`,v=l.provider?` [${l.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${v} (${_}): ${l.task}`),l.files_touched.length>0&&e.push(` Files: ${l.files_touched.slice(0,5).map(z=>`\`${z}\``).join(", ")}`),l.next_step&&e.push(` \u{1F4CD} Next step was: ${l.next_step}`),(!i||k-T>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}const Z=i?null:nt(o);if(Z)try{const l=We(Z,["log","--oneline","--format=%h %s","-15"]).trim();let k;try{k=We(Z,["diff","--stat","HEAD~3"]).trim()}catch{k=We(Z,["diff","--stat"]).trim()}if(l){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const T of l.split(`
|
|
33
33
|
`).slice(0,8))e.push(` ${T}`);if(k){const T=k.split(`
|
|
34
|
-
`).filter(E=>E.includes("|")||E.includes("changed"));if(T.length>0){e.push(" **Recent changes:**");for(const E of T.slice(0,5))e.push(` ${E.trim()}`)}}e.push("")}}catch{}if(i){const l=Math.round((Date.now()-new Date(i.ts).getTime())/6e4),k=l<60?`${l}m ago`:l<1440?`${Math.round(l/60)}h ago`:`${Math.round(l/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${k}): ${i.summary}`),i.duration_min&&e.push(` Duration: ${i.duration_min} min`),(i.files_changed??[]).length>0&&e.push(` Files: ${(i.files_changed??[]).slice(0,5).map(T=>`\`${T}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${r.length} lessons \xB7 ${t} context entries`,""),S>0&&e.push(`\u26A0 ${S} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const k=await o.lrange(`cachly:wirkung:${h}`,0,-1).catch(()=>[]),T=In(k.map(v=>j(v,null)).filter(Boolean)),E=v=>T.get(v)??{geholfen:0,geoeffnet:0},_=r.filter(v=>!vs(v)).filter(v=>{if(v.outcome!=="success")return!1;const P=E(v.topic);return v.pinned===!0||P.geholfen>=1||P.geoeffnet>=2}).filter(v=>!U.has(v.topic)).sort((v,P)=>{const G=E(v.topic),x=E(P.topic);return x.geholfen-G.geholfen||x.geoeffnet-G.geoeffnet||(P.recall_count??0)-(v.recall_count??0)}).slice(0,5);if(_.length>0){e.push("\u{1F4CC} **Confirmed lessons** (pinned, reported helpful, or opened after a search \u2014 being shown does not count):");for(const v of _){U.add(v.topic);const P=v.severity==="critical"?"\u{1F534}":v.severity==="major"?"\u{1F7E1}":"",G=E(v.topic),x=[v.pinned===!0?"pinned":"",G.geholfen>0?`reported helpful ${G.geholfen}\xD7`:"",G.geoeffnet>0?`opened ${G.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),ee=Xe(v);e.push(` \u2705${P} \`${v.topic}\` _(${x})_ \u2014 ${ee[0]??""}`,...ee.slice(1))}e.push("")}}try{const l=[],k=o.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((T,E)=>{k.on("data",_=>l.push(..._)),k.on("end",T),k.on("error",E)}),l.length>0){e.push(`\u26A1 **Active belief conflicts (${l.length}):**`);for(const T of l.slice(0,3)){const E=await o.get(T);if(!E)continue;const _=j(E,null);_&&e.push(` \u26A0\uFE0F \`${_.topic}\` \u2014 previously confirmed fix (${(_.fix_confidence*100).toFixed(0)}%, n=${_.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${me(_.topic)}")\``)}e.push("")}}catch{}if(de.length>0){e.push(`\u{1F3AF} **Relevant for "${n}":**`);for(const l of de){const k=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",T=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",E=Xe(l);e.push(` ${k}${T} \`${l.topic}\` \u2014 ${E[0]??""}`,...E.slice(1))}e.push("")}if(r.length>0){const l=($.length>0?r.filter(k=>!$.includes(k)):r).filter(k=>!U.has(k.topic)).slice(0,$.length>0?3:4);if(l.length>0){e.push("\u{1F550} **Recent lessons:**");for(const k of l){U.add(k.topic);const T=k.outcome==="success"?"\u2705":k.outcome==="partial"?"\u26A0\uFE0F":"\u274C",E=k.severity==="critical"?"\u{1F534}":k.severity==="major"?"\u{1F7E1}":"",_=Xe(k);e.push(` ${T}${E} \`${k.topic}\` \u2014 ${_[0]??""}`,..._.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");r.length>=10&&(r.some(k=>k.author)||(e.push(`\u{1F91D} **Your Brain has ${r.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const X=await Wn(o,r);if(X.length>0){e.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const l of X.slice(0,3))e.push(` \`${l.neu}\` \u2248 \`${l.alt}\` (${l.naehe.toFixed(2)})`);e.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),e.push("")}const Z=i;if(Z?.decision_log?.length){const l=Z.decision_log,k=l.filter((_,v)=>!U.has(_.topic)&&l.findIndex(P=>P.topic===_.topic)===v),T=k.filter(_=>_.outcome==="success"),E=k.filter(_=>_.outcome==="failure");if(T.length>0||E.length>0){e.push(`\u{1F3AC} **Last session decisions** (${l.length} lessons stored):`),T.length>0&&e.push(` \u2705 Worked: ${T.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),E.length>0&&e.push(` \u274C Failed: ${E.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),e.push("");for(const _ of[...T.slice(0,3),...E.slice(0,3)])U.add(_.topic)}}{const l=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"]),k=v=>{const P=new Set;for(const G of v)for(const x of G.toLowerCase().split(/[/\\._-]/))x.length>3&&!l.has(x)&&P.add(x);return[...P]};let T=c,E=n,_=!1;if(T.length===0&&i){const v=k(i.files_changed??[]),P=(i.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(G=>G.length>3&&!l.has(G));T=[...new Set([...v,...P])],E="where you left off last session",_=!0}if(T.length>0){const v=r.filter(P=>{if(P.outcome==="success")return!1;const G=P.topic.split(":")[0];return T.some(x=>P.topic.toLowerCase().includes(x)||G===x||(P.tags??[]).some(ee=>ee.toLowerCase()===x))});if(v.length>=1){const G=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",_?` You're likely to continue **${E}** \u2014 ${v.length} known pitfall${v.length>1?"s":""} there:`:` Known pitfalls for **"${E}"** (${v.length} past failure${v.length>1?"s":""}):`,...v.slice(0,3).map(x=>` \u274C \`${x.topic}\` \u2014 ${(x.what_failed??x.what_worked).slice(0,80)}`),""];e.splice(2,0,...G)}}}if(m){const l=Date.now()-6048e5,k=r.filter(T=>T.author&&T.author!==m&&new Date(T.ts).getTime()>l&&!U.has(T.topic));if(k.length>0){const T=new Map;for(const E of k){const _=E.author;T.has(_)||T.set(_,[]),T.get(_).push(E)}e.push(`\u{1F465} **Team this week** (${k.length} lesson${k.length>1?"s":""} from teammates):`);for(const[E,_]of T){e.push(` \u{1F464} **${E}**:`);for(const v of _.slice(0,3)){const P=v.outcome==="success"?"\u2705":v.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${P} \`${v.topic}\` \u2014 ${v.what_worked.slice(0,80)}`),U.add(v.topic)}_.length>3&&e.push(` \u2026 and ${_.length-3} more`)}e.push("")}}try{const l=await o.get("cachly:crystal:latest");if(l){const k=j(l,null);if(k&&Math.round((Date.now()-new Date(k.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${k.label} \xB7 ${k.session_count} sessions compressed):`);for(const E of k.top_patterns.slice(0,3))e.push(` \u2022 **${E.category}** (${E.count}\xD7): ${E.insight.slice(0,90)}`);e.push("")}}}catch{}try{const l=await o.hgetall(`cachly:roadmap:${h}`);if(l&&Object.keys(l).length>0){const k={critical:0,high:1,medium:2,low:3},T={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},E=new Set(["planned","in-progress","blocked"]),_=Object.values(l).flatMap(G=>{const x=j(G,null);return x?[x]:[]}),v=_.filter(G=>E.has(G.status)).sort((G,x)=>G.status==="in-progress"&&x.status!=="in-progress"?-1:x.status==="in-progress"&&G.status!=="in-progress"?1:(k[G.priority]??99)-(k[x.priority]??99)),P=_.filter(G=>G.status==="done").length;if(v.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${v.length} open \xB7 ${P} done):`);for(const G of v.slice(0,5)){const x=G.status==="in-progress"?"\u26A1":G.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${x} ${T[G.priority]??"\u26AA"} \`${G.id}\` **${G.title}**`)}v.length>5&&e.push(` \u2026 and ${v.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}try{const l=await o.get("cachly:mcm:calibration:last"),k=j(l,null)?.ts??0;if((Date.now()-k)/864e5>=30&&r.length>=5){const E=r.filter(v=>v.outcome==="success"&&(v.recall_count??0)>0),_=r.filter(v=>(v.recall_count??0)>0);if(_.length>=3){const v=_.length>0?E.length/_.length:1,P=[],G=new Map;for(const x of _){const ee=x.topic.split(":")[0]??"other";G.has(ee)||G.set(ee,{success:0,total:0});const we=G.get(ee);we.total++,x.outcome==="success"&&we.success++}for(const[x,ee]of G)ee.total>=2&&ee.success/ee.total<.6&&P.push(x);await o.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:v,recalled:_.length,low_precision_domains:P})),(P.length>0||v<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${_.length} recalled lessons):`),e.push(` Overall precision: **${(v*100).toFixed(0)}%** recalled lessons actually worked`),P.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${P.map(x=>`\`${x}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await o.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const V=r.filter(l=>l.outcome==="failure"||l.outcome==="partial").length,se=r.filter(l=>l.outcome==="success"&&vt(l)<gs).length;if(r.length===0||V>0||se>0){const l=[];r.length===0&&l.push("brain is empty"),V>0&&l.push(`${V} open failure${V>1?"s":""}`),se>0&&l.push(`${se} stale lesson${se>1?"s":""}`),e.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${l.join(", ")}._`)}try{if(await o.get(`cachly:prefs:auto_changelog:${h}`).catch(()=>null)!=="false"&&i?.ts&&!ae){const T=new Date(i.ts).getTime();if(!Number.isNaN(T)){const E=r.filter(v=>{const P=new Date(v.ts).getTime();return!Number.isNaN(P)&&P>T}),_=E.filter(v=>!U.has(v.topic));if(_.length>0){const v=Math.round((Date.now()-T)/6e4),P=v<60?`${v}m`:v<1440?`${Math.round(v/60)}h`:`${Math.round(v/1440)}d`,G=E.length-_.length;e.push(""),e.push(`\u{1F4CB} **${E.length} new lesson${E.length!==1?"s":""} since your last session** (${P} ago${G>0?`, ${G} already listed above`:""}):`);const x=new Map;for(const ee of _.slice(0,20)){const we=ee.topic.includes(":")?ee.topic.split(":")[0]:"general",ne=x.get(we)??[];ne.push(ee),x.set(we,ne)}for(const[ee,we]of x){e.push(` **${ee}**`);for(const ne of we){const ue=ne.outcome==="failure"?"\u274C":ne.severity==="critical"?"\u{1F6A8}":ne.severity==="major"?"\u26A0\uFE0F":"\u2705",fe=(ne.outcome==="failure"?ne.what_failed:ne.what_worked)??"";e.push(` ${ue} \`${ne.topic}\`${fe?` \u2014 ${fe.slice(0,80)}`:""}`)}}_.length>20&&e.push(` \u2026 and ${_.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${h}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
|
|
35
|
-
`)}case"session_start_summary":{const{instance_id:h,focus:n,top_n:
|
|
36
|
-
`);const S=r.length>
|
|
37
|
-
`)}case"session_end":{const{instance_id:h,summary:n,files_changed:
|
|
38
|
-
`).map(fe=>fe.trim()).filter(Boolean).slice(0,12):[],ue=[];for(const fe of
|
|
34
|
+
`).filter(E=>E.includes("|")||E.includes("changed"));if(T.length>0){e.push(" **Recent changes:**");for(const E of T.slice(0,5))e.push(` ${E.trim()}`)}}e.push("")}}catch{}if(i){const l=Math.round((Date.now()-new Date(i.ts).getTime())/6e4),k=l<60?`${l}m ago`:l<1440?`${Math.round(l/60)}h ago`:`${Math.round(l/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${k}): ${i.summary}`),i.duration_min&&e.push(` Duration: ${i.duration_min} min`),(i.files_changed??[]).length>0&&e.push(` Files: ${(i.files_changed??[]).slice(0,5).map(T=>`\`${T}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${r.length} lessons \xB7 ${t} context entries`,""),S>0&&e.push(`\u26A0 ${S} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const k=await a.lrange(`cachly:wirkung:${h}`,0,-1).catch(()=>[]),T=In(k.map(v=>P(v,null)).filter(Boolean)),E=v=>T.get(v)??{geholfen:0,geoeffnet:0},_=r.filter(v=>!vs(v)).filter(v=>{if(v.outcome!=="success")return!1;const z=E(v.topic);return v.pinned===!0||z.geholfen>=1||z.geoeffnet>=2}).filter(v=>!Y.has(v.topic)).sort((v,z)=>{const G=E(v.topic),x=E(z.topic);return x.geholfen-G.geholfen||x.geoeffnet-G.geoeffnet||(z.recall_count??0)-(v.recall_count??0)}).slice(0,5);if(_.length>0){e.push("\u{1F4CC} **Confirmed lessons** (pinned, reported helpful, or opened after a search \u2014 being shown does not count):");for(const v of _){Y.add(v.topic);const z=v.severity==="critical"?"\u{1F534}":v.severity==="major"?"\u{1F7E1}":"",G=E(v.topic),x=[v.pinned===!0?"pinned":"",G.geholfen>0?`reported helpful ${G.geholfen}\xD7`:"",G.geoeffnet>0?`opened ${G.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),te=Xe(v);e.push(` \u2705${z} \`${v.topic}\` _(${x})_ \u2014 ${te[0]??""}`,...te.slice(1))}e.push("")}}try{const l=[],k=a.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((T,E)=>{k.on("data",_=>l.push(..._)),k.on("end",T),k.on("error",E)}),l.length>0){e.push(`\u26A1 **Active belief conflicts (${l.length}):**`);for(const T of l.slice(0,3)){const E=await a.get(T);if(!E)continue;const _=P(E,null);_&&e.push(` \u26A0\uFE0F \`${_.topic}\` \u2014 previously confirmed fix (${(_.fix_confidence*100).toFixed(0)}%, n=${_.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${me(_.topic)}")\``)}e.push("")}}catch{}if(de.length>0){e.push(`\u{1F3AF} **Relevant for "${n}":**`);for(const l of de){const k=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",T=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",E=Xe(l);e.push(` ${k}${T} \`${l.topic}\` \u2014 ${E[0]??""}`,...E.slice(1))}e.push("")}if(r.length>0){const l=($.length>0?r.filter(k=>!$.includes(k)):r).filter(k=>!Y.has(k.topic)).slice(0,$.length>0?3:4);if(l.length>0){e.push("\u{1F550} **Recent lessons:**");for(const k of l){Y.add(k.topic);const T=k.outcome==="success"?"\u2705":k.outcome==="partial"?"\u26A0\uFE0F":"\u274C",E=k.severity==="critical"?"\u{1F534}":k.severity==="major"?"\u{1F7E1}":"",_=Xe(k);e.push(` ${T}${E} \`${k.topic}\` \u2014 ${_[0]??""}`,..._.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");r.length>=10&&(r.some(k=>k.author)||(e.push(`\u{1F91D} **Your Brain has ${r.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Q=await Wn(a,r);if(Q.length>0){e.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const l of Q.slice(0,3))e.push(` \`${l.neu}\` \u2248 \`${l.alt}\` (${l.naehe.toFixed(2)})`);e.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),e.push("")}const X=i;if(X?.decision_log?.length){const l=X.decision_log,k=l.filter((_,v)=>!Y.has(_.topic)&&l.findIndex(z=>z.topic===_.topic)===v),T=k.filter(_=>_.outcome==="success"),E=k.filter(_=>_.outcome==="failure");if(T.length>0||E.length>0){e.push(`\u{1F3AC} **Last session decisions** (${l.length} lessons stored):`),T.length>0&&e.push(` \u2705 Worked: ${T.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),E.length>0&&e.push(` \u274C Failed: ${E.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),e.push("");for(const _ of[...T.slice(0,3),...E.slice(0,3)])Y.add(_.topic)}}{const l=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"]),k=v=>{const z=new Set;for(const G of v)for(const x of G.toLowerCase().split(/[/\\._-]/))x.length>3&&!l.has(x)&&z.add(x);return[...z]};let T=c,E=n,_=!1;if(T.length===0&&i){const v=k(i.files_changed??[]),z=(i.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(G=>G.length>3&&!l.has(G));T=[...new Set([...v,...z])],E="where you left off last session",_=!0}if(T.length>0){const v=r.filter(z=>{if(z.outcome==="success")return!1;const G=z.topic.split(":")[0];return T.some(x=>z.topic.toLowerCase().includes(x)||G===x||(z.tags??[]).some(te=>te.toLowerCase()===x))});if(v.length>=1){const G=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",_?` You're likely to continue **${E}** \u2014 ${v.length} known pitfall${v.length>1?"s":""} there:`:` Known pitfalls for **"${E}"** (${v.length} past failure${v.length>1?"s":""}):`,...v.slice(0,3).map(x=>` \u274C \`${x.topic}\` \u2014 ${(x.what_failed??x.what_worked).slice(0,80)}`),""];e.splice(2,0,...G)}}}if(p){const l=Date.now()-6048e5,k=r.filter(T=>T.author&&T.author!==p&&new Date(T.ts).getTime()>l&&!Y.has(T.topic));if(k.length>0){const T=new Map;for(const E of k){const _=E.author;T.has(_)||T.set(_,[]),T.get(_).push(E)}e.push(`\u{1F465} **Team this week** (${k.length} lesson${k.length>1?"s":""} from teammates):`);for(const[E,_]of T){e.push(` \u{1F464} **${E}**:`);for(const v of _.slice(0,3)){const z=v.outcome==="success"?"\u2705":v.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${z} \`${v.topic}\` \u2014 ${v.what_worked.slice(0,80)}`),Y.add(v.topic)}_.length>3&&e.push(` \u2026 and ${_.length-3} more`)}e.push("")}}try{const l=await a.get("cachly:crystal:latest");if(l){const k=P(l,null);if(k&&Math.round((Date.now()-new Date(k.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${k.label} \xB7 ${k.session_count} sessions compressed):`);for(const E of k.top_patterns.slice(0,3))e.push(` \u2022 **${E.category}** (${E.count}\xD7): ${E.insight.slice(0,90)}`);e.push("")}}}catch{}try{const l=await a.hgetall(`cachly:roadmap:${h}`);if(l&&Object.keys(l).length>0){const k={critical:0,high:1,medium:2,low:3},T={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},E=new Set(["planned","in-progress","blocked"]),_=Object.values(l).flatMap(G=>{const x=P(G,null);return x?[x]:[]}),v=_.filter(G=>E.has(G.status)).sort((G,x)=>G.status==="in-progress"&&x.status!=="in-progress"?-1:x.status==="in-progress"&&G.status!=="in-progress"?1:(k[G.priority]??99)-(k[x.priority]??99)),z=_.filter(G=>G.status==="done").length;if(v.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${v.length} open \xB7 ${z} done):`);for(const G of v.slice(0,5)){const x=G.status==="in-progress"?"\u26A1":G.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${x} ${T[G.priority]??"\u26AA"} \`${G.id}\` **${G.title}**`)}v.length>5&&e.push(` \u2026 and ${v.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}try{const l=await a.get("cachly:mcm:calibration:last"),k=P(l,null)?.ts??0;if((Date.now()-k)/864e5>=30&&r.length>=5){const E=r.filter(v=>v.outcome==="success"&&(v.recall_count??0)>0),_=r.filter(v=>(v.recall_count??0)>0);if(_.length>=3){const v=_.length>0?E.length/_.length:1,z=[],G=new Map;for(const x of _){const te=x.topic.split(":")[0]??"other";G.has(te)||G.set(te,{success:0,total:0});const we=G.get(te);we.total++,x.outcome==="success"&&we.success++}for(const[x,te]of G)te.total>=2&&te.success/te.total<.6&&z.push(x);await a.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:v,recalled:_.length,low_precision_domains:z})),(z.length>0||v<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${_.length} recalled lessons):`),e.push(` Overall precision: **${(v*100).toFixed(0)}%** recalled lessons actually worked`),z.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${z.map(x=>`\`${x}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await a.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const q=r.filter(l=>l.outcome==="failure"||l.outcome==="partial").length,ne=r.filter(l=>l.outcome==="success"&&vt(l)<gs).length;if(r.length===0||q>0||ne>0){const l=[];r.length===0&&l.push("brain is empty"),q>0&&l.push(`${q} open failure${q>1?"s":""}`),ne>0&&l.push(`${ne} stale lesson${ne>1?"s":""}`),e.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${l.join(", ")}._`)}try{if(await a.get(`cachly:prefs:auto_changelog:${h}`).catch(()=>null)!=="false"&&i?.ts&&!ae){const T=new Date(i.ts).getTime();if(!Number.isNaN(T)){const E=r.filter(v=>{const z=new Date(v.ts).getTime();return!Number.isNaN(z)&&z>T}),_=E.filter(v=>!Y.has(v.topic));if(_.length>0){const v=Math.round((Date.now()-T)/6e4),z=v<60?`${v}m`:v<1440?`${Math.round(v/60)}h`:`${Math.round(v/1440)}d`,G=E.length-_.length;e.push(""),e.push(`\u{1F4CB} **${E.length} new lesson${E.length!==1?"s":""} since your last session** (${z} ago${G>0?`, ${G} already listed above`:""}):`);const x=new Map;for(const te of _.slice(0,20)){const we=te.topic.includes(":")?te.topic.split(":")[0]:"general",oe=x.get(we)??[];oe.push(te),x.set(we,oe)}for(const[te,we]of x){e.push(` **${te}**`);for(const oe of we){const ue=oe.outcome==="failure"?"\u274C":oe.severity==="critical"?"\u{1F6A8}":oe.severity==="major"?"\u26A0\uFE0F":"\u2705",fe=(oe.outcome==="failure"?oe.what_failed:oe.what_worked)??"";e.push(` ${ue} \`${oe.topic}\`${fe?` \u2014 ${fe.slice(0,80)}`:""}`)}}_.length>20&&e.push(` \u2026 and ${_.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${h}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
|
|
35
|
+
`)}case"session_start_summary":{const{instance_id:h,focus:n,top_n:p=10,author:w=""}=A;if(!n||!n.trim())throw new Error("focus is required for session_start_summary");const o=Math.min(Math.max(1,Math.floor(Number(p)||10)),25),a=await F(h),N=[],d=a.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,V)=>{d.on("data",ie=>N.push(...ie)),d.on("end",e),d.on("error",V)});const r=[];if(N.length>0){const e=await a.mget(...N);for(const V of e){const ie=P(V??null,null);ie&&!Qt(ie)&&!ns(ie.topic)&&r.push(ie)}}if(r.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="${h}")\` to bootstrap with 16 universal lessons.`].join(`
|
|
36
|
+
`);const S=r.length>o,t=n.toLowerCase().split(/\s+/).filter(Boolean),s=Date.now(),C=r.map(e=>{const V=t.filter(q=>e.topic.toLowerCase().includes(q)).length,ie=t.filter(q=>(e.tags??[]).some(ne=>ne.toLowerCase().includes(q))).length,ae=V*2+ie,de=Math.max(0,e.recall_count??0),Y=Math.min(1.5,Math.log1p(de)/10),f=e.severity==="critical"?1:e.severity==="major"?.5:0,J=(s-new Date(e.verified_at??e.ts).getTime())/864e5,Z=J<30?.5*(1-J/30):0,Q=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,X=ae+Y+f+Z+Q;return{lesson:e,score:X}});C.sort((e,V)=>V.score!==e.score?V.score-e.score:new Date(V.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const i=(S?C.slice(0,o):C).map(e=>e.lesson),c=r.length,$=i.length,M=[S?`\u{1F9E0} Brain Summary \u2014 top ${$} of ${c} lessons for "${n}"`:`\u{1F9E0} Brain Summary \u2014 all ${$} lesson${$!==1?"s":""} for "${n}"`,"\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 V=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",ie=e.severity?`[${e.severity}] `:"[minor] ",ae=e.recall_count??0,de=ae>0?` (in ${ae} answer${ae===1?"":"s"})`:"",Y=e.what_worked.slice(0,110),f=go(e.author,w);M.push(`${V} ${ie}\`${e.topic}\` \u2014 ${Y}${de}${f}`)}M.push("");const I=wo(i,w);return I>0&&M.push(`\u{1F465} ${I} of these ${I===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),S?M.push(`\u{1F4A1} Showing top ${$} of ${c} lessons \xB7 \`session_start\` for full briefing`):M.push(`\u{1F4A1} All ${$} lesson${$!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),M.join(`
|
|
37
|
+
`)}case"session_end":{const{instance_id:h,summary:n,files_changed:p=[],lessons_learned:w,workspace_path:o=""}=A,a=je({summary:n,files_changed:p}),N=a.felder.summary,d=a.felder.files_changed,r=await F(h),S=new Date;let t;const s=await r.get("cachly:session:current");if(!s)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 C=P(s,null);C?.started&&(t=Math.round((S.getTime()-new Date(C.started).getTime())/6e4));let i=[];try{i=(await r.lrange("cachly:session:decision-log",0,-1)).flatMap(de=>{const Y=P(de,null);return Y?[Y]:[]}),await r.del("cachly:session:decision-log")}catch{}const c=Hn(h);Jn(h);const $={ts:S.toISOString(),summary:N,files_changed:d,...c.recalls>0?{memory_cost:c}:{},...a.verdacht.length?{verdacht:a.verdacht}:{},...w!==void 0?{lessons_learned:w}:{},...t!==void 0?{duration_min:t}:{},...i.length>0?{decision_log:i}:{}};await r.set("cachly:session:last",JSON.stringify($)),await r.lpush("cachly:session:history",JSON.stringify($)),await r.ltrim("cachly:session:history",0,49),await r.expire("cachly:session:history",90*86400),await r.del("cachly:session:current");const m=[];try{const ae=/\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,de=N.split(/[.!\n]+/).map(Y=>Y.trim()).filter(Y=>Y.length>20&&ae.test(Y));for(const Y of de.slice(0,6)){const J=Y.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(ne=>ne.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(ne)).slice(0,4).join("-");if(!J)continue;const Z=`auto:${J}`,Q=`cachly:lesson:best:${Z}`,X=await r.get(Q);if(X)try{if(JSON.parse(X).outcome==="success")continue}catch{}const q={topic:Z,outcome:"success",what_worked:Y,context:`Auto-learned from session summary. Full summary: ${N.slice(0,300)}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,session_ts:S.toISOString(),version:2,...a.verdacht.length?{tags:[_t]}:{}};await r.set(Q,JSON.stringify(q)),await r.expire(Q,90*86400),m.push(Z)}}catch{}const g=[],M=nt(o);let I=0,e=0;if(M)try{const de=`--since=${(s?(()=>{try{return JSON.parse(s).started??""}catch{return""}})():"")||"1 hour ago"}`,Y=We(M,["log",de,"--oneline","--format=%H|||%s|||%b|||%ai|||ENDE"]).trim();if(Y){const f=/\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,J=Y.split("|||ENDE").map(Z=>Z.trim()).filter(Boolean);for(const Z of J.slice(0,10)){const[Q,X,q,ne]=Z.split("|||"),l=je({msg:X??"",body:q??""}),k=l.felder.msg,T=l.felder.body;if(fs(Q))try{const te=We(M,["diff-tree","--no-commit-id","--name-only","-r","--root",Q]).trim(),oe=te?te.split(`
|
|
38
|
+
`).map(fe=>fe.trim()).filter(Boolean).slice(0,12):[],ue=[];for(const fe of oe)ue.push(await St(r,fe));for(let fe=0;fe<ue.length;fe++)for(let be=fe+1;be<ue.length;be++)await _e(r,ue[fe],"co-occurs",ue[be],!0),await _e(r,ue[be],"co-occurs",ue[fe],!0)}catch{}if(!k||!f.test(k))continue;const E=(T??"").trim();if(E.length<120)continue;const _=k.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(!_)continue;const v=`git:${_}`,z=`cachly:lesson:best:${v}`;if(await r.get(z))continue;const x={topic:v,outcome:"success",what_worked:`${k}
|
|
39
39
|
|
|
40
|
-
${E.slice(0,1200)}`,context:`Auto-learned from git commit ${(
|
|
41
|
-
`)}case"session_ping":{const{instance_id:h,task:n,files_touched:
|
|
42
|
-
\u{1F4CD} **Next step:** ${r}`:"";return[`\u{1F4CC} **Checkpoint saved**${C} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${N}${i}`,c,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...Ve(
|
|
43
|
-
`)}case"session_handoff":{const{instance_id:h,completed_tasks:n=[],remaining_tasks:
|
|
40
|
+
${E.slice(0,1200)}`,context:`Auto-learned from git commit ${(Q??"").slice(0,7)} at ${ne??""} in ${M}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3,...l.verdacht.length?{tags:[_t]}:{}};await r.set(z,JSON.stringify(x)),await r.expire(z,60*86400),g.push(v),l.geschwaerzt.length&&I++,l.verdacht.length&&e++}}}catch{}const V=t!==void 0?` \xB7 ${t} min`:"",ie=m.length+g.length;return[`\u2705 **Session saved**${V}`,"",`\u{1F4CB} **Summary:** ${N}`,d.length>0?`\u{1F4C1} **Files changed:** ${d.map(ae=>`\`${ae}\``).join(", ")}`:"",w!==void 0?`\u{1F9E0} **Lessons stored:** ${w}`:"",...Vn(c),m.length>0?`\u{1F916} **Auto-learned:** ${m.length} lessons extracted from summary (${m.slice(0,3).map(ae=>`\`${ae}\``).join(", ")}${m.length>3?"\u2026":""})`:"",g.length>0?`\u{1F33F} **Ambient git learning:** ${g.length} commit${g.length>1?"s":""} auto-learned (${g.slice(0,3).map(ae=>`\`${ae}\``).join(", ")}${g.length>3?"\u2026":""})`:"",...Ve(a,"notiz"),...ss(I,e,`${g.length} git lessons`),ie>0?`\u{1F4DA} **Learned this session:** ${ie} lesson${ie>1?"s":""}`:"","",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(ae=>ae!=="").join(`
|
|
41
|
+
`)}case"session_ping":{const{instance_id:h,task:n,files_touched:p=[],next_step:w="",provider:o=""}=A,a=je({task:n,files_touched:p,next_step:w,provider:o}),{task:N,files_touched:d,next_step:r,provider:S}=a.felder,t=await F(h),s={ts:new Date().toISOString(),task:N,files_touched:d,next_step:r,provider:S,...a.verdacht.length?{verdacht:a.verdacht}:{}};await t.set("cachly:session:checkpoint",JSON.stringify(s),"EX",86400*3),await t.lpush("cachly:session:checkpoint:log",JSON.stringify(s)),await t.ltrim("cachly:session:checkpoint:log",0,19);const C=S?` [${S}]`:"",i=d.length>0?` \xB7 ${d.length} file${d.length>1?"s":""} touched`:"",c=r?`
|
|
42
|
+
\u{1F4CD} **Next step:** ${r}`:"";return[`\u{1F4CC} **Checkpoint saved**${C} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${N}${i}`,c,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...Ve(a,"notiz")].filter($=>$!=="").join(`
|
|
43
|
+
`)}case"session_handoff":{const{instance_id:h,completed_tasks:n=[],remaining_tasks:p=[],files_changed:w=[],instructions:o="",context_summary:a="",blocked_on:N=""}=A,d=je({completed_tasks:n,remaining_tasks:p,files_changed:w,instructions:o,context_summary:a,blocked_on:N}),{completed_tasks:r,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:i}=d.felder,c=await F(h),m={ts:new Date().toISOString(),completed_tasks:r,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:i,...d.verdacht.length?{verdacht:d.verdacht}:{}};await c.set("cachly:session:handoff",JSON.stringify(m)),await c.lpush("cachly:session:handoff:history",JSON.stringify(m)),await c.ltrim("cachly:session:handoff:history",0,19);const g=r.length+S.length,M=g>0?Math.round(r.length/g*100):0,I=t.filter(e=>e.status==="broken"||e.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${r.length}/${g} tasks done (${M}%)`,"",r.length>0?`\u2705 **Completed:**
|
|
44
44
|
${r.map(e=>` - ${e}`).join(`
|
|
45
45
|
`)}`:"",S.length>0?`
|
|
46
46
|
\u23F3 **Remaining for next window:**
|
|
47
47
|
${S.map(e=>` - ${e}`).join(`
|
|
48
|
-
`)}`:"",
|
|
49
|
-
\u26A0\uFE0F **Needs attention:** ${
|
|
48
|
+
`)}`:"",I.length>0?`
|
|
49
|
+
\u26A0\uFE0F **Needs attention:** ${I.map(e=>`\`${e.path}\` (${e.status})`).join(", ")}`:"",i?`
|
|
50
50
|
\u{1F6AB} **Blocked on:** ${i}`:"",s?`
|
|
51
51
|
\u{1F4DD} **Instructions:** ${s}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically.",...Ve(d,"notiz")].filter(e=>e!=="").join(`
|
|
52
|
-
`)}case"auto_learn_session":{const{instance_id:h,observations:n}=
|
|
53
|
-
`)}case"brain_who_knows":{const{instance_id:h,topic:n,limit:
|
|
54
|
-
`);const S=[...r.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,w),t=[],s=S[0];if(s)try{const i=await
|
|
55
|
-
`)}case"brain_file_map":{const{instance_id:h,file_paths:n=[]}=
|
|
56
|
-
`)}case"team_expertise_map":{const{instance_id:h,top_n:n=20}=
|
|
57
|
-
`);const
|
|
58
|
-
`)}case"skill_gaps":{const{instance_id:h,min_failures:n=1}=
|
|
59
|
-
`)}case"brain_coverage":{const{instance_id:h,repo_path:n="."}=
|
|
60
|
-
`).filter(Boolean).length,d=String(N)}catch{}let r=0,S=0,t=0;const s=new Set;for(const
|
|
61
|
-
`)}case"brain_metrics":{const{instance_id:h}=
|
|
62
|
-
`),
|
|
63
|
-
`)}case"brain_service_map":{const{instance_id:h,service:n}=
|
|
64
|
-
`);const i=
|
|
65
|
-
`)}case"brain_collab_pairs":{const{instance_id:h,min_weight:n=1}=
|
|
66
|
-
`);const N=new Map;for(const[s,C]of
|
|
67
|
-
`)}case"brain_portability":{const{instance_id:h}=
|
|
68
|
-
`)}case"brain_changelog":{const{instance_id:h,days:n=7,max_lessons:
|
|
69
|
-
`);const S=new Map;for(const c of r){const $=c.topic.includes(":")?c.topic.split(":")[0]:"general",
|
|
70
|
-
`)}case"brain_set_pref":{const{instance_id:h,key:n,value:
|
|
71
|
-
`)}case"brain_get_pref":{const{instance_id:h,key:n}=
|
|
72
|
-
`)}default:return null}}async function Mo(
|
|
52
|
+
`)}case"auto_learn_session":{const{instance_id:h,observations:n}=A,p=await F(h),w=[],o=[];let a=0,N=0;for(const r of n){const S=je(r),t=S.felder,s=t.topic??t.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),C=s.includes(":")?s:`auto:${s}`,i=`cachly:lesson:best:${C}`,c=await p.get(i);if(c&&JSON.parse(c).outcome==="success"&&t.outcome!=="success"){o.push(C);continue}const $={topic:C,outcome:t.outcome,what_worked:t.outcome==="success"?t.action:t.details??t.action,what_failed:t.outcome==="failure"?t.action:void 0,context:t.details,severity:t.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2,...S.verdacht.length?{tags:[_t]}:{}},m=JSON.stringify($);S.geschwaerzt.length&&a++,S.verdacht.length&&N++,await p.set(i,m);const g=`cachly:lessons:${C}`;await p.rpush(g,m),await p.ltrim(g,-100,-1),await p.expire(g,90*86400);try{const M=C.split(":")[0]??"auto",I=me(C);if(await Fe(p,I,M,M),t.outcome==="success"||t.outcome==="partial"){const e=t.details?ot(t.details):null;if(e){const V=me(`problem:${e}`);await Fe(p,V,"problem","problem"),await _e(p,I,"fixes",V,t.outcome==="success",t.outcome==="partial")}}}catch{}w.push(`${t.outcome==="success"?"\u2705":t.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${C}\``)}const d=[`\u{1F916} **Auto-learn complete**: ${w.length} stored, ${o.length} skipped`,""];return w.length>0&&d.push("**Stored:**",...w.map(r=>" "+r),""),o.length>0&&d.push(`**Skipped** (better lesson already exists): ${o.map(r=>`\`${r}\``).join(", ")}`),d.push(...ss(a,N,`${w.length} observations`)),d.join(`
|
|
53
|
+
`)}case"brain_who_knows":{const{instance_id:h,topic:n,limit:p=10}=A;if(!n||typeof n!="string"||!n.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const w=Math.max(1,Math.min(Number(p)||10,50)),o=await F(h),a=me(n),N=dt(n).filter(i=>i.length>=3).slice(0,5),d=new Set([a]);for(const i of N.slice(0,3)){const c=o.scanStream({match:`cachly:ckg:node:*${i}*`,count:30});await new Promise(($,m)=>{c.on("data",g=>{for(const M of g.slice(0,10)){const I=M.replace("cachly:ckg:node:","");!I.startsWith("person:")&&!I.startsWith("file:")&&d.add(I)}}),c.on("end",$),c.on("error",m)})}const r=new Map;for(const i of[...d].slice(0,25)){const c=await o.smembers(`cachly:ckg:idx:to:${i}`);for(const $ of c){const m=await o.get($);if(!m)continue;const g=P(m,null);if(!g||g.edgeType!=="authored")continue;const M=await o.get(`cachly:ckg:node:${g.from}`);if(!M)continue;const I=P(M,null);if(!I||I.type!=="person")continue;const e=r.get(g.from);e?(e.lessonCount++,e.totalConfidence+=g.confidence,e.domains.add(I.domain),g.last_updated>e.lastActive&&(e.lastActive=g.last_updated)):r.set(g.from,{handle:I.handle,lessonCount:1,totalConfidence:g.confidence,domains:new Set([I.domain]),lastActive:I.last_active??g.last_updated})}}if(r.size===0)return[`## \u{1F465} Who Knows About \`${n}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${n}", author="your-handle", ...)\``].join(`
|
|
54
|
+
`);const S=[...r.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,w),t=[],s=S[0];if(s)try{const i=await o.smembers(`cachly:ckg:idx:from:${s.id}`),c=[];for(const $ of i){const m=await o.get($);if(!m)continue;const g=P(m,null);if(!g||g.edgeType!=="collaborates")continue;const M=await o.get(`cachly:ckg:node:${g.to}`),I=M?P(M,null):null;I?.handle&&c.push({handle:I.handle,trials:g.trials})}c.sort(($,m)=>m.trials-$.trials);for(const $ of c.slice(0,3))t.push($.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${n}\`?`,"",`**${S.length}** contributor${S.length!==1?"s":""} with relevant lessons:`,""];for(const[i,c]of S.entries()){const $=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}.`,m=(c.avgConfidence*100).toFixed(0),g=Math.floor((Date.now()-new Date(c.lastActive).getTime())/864e5),M=g<1?"today":g<7?`${g}d ago`:g<30?`${Math.floor(g/7)}w ago`:`${Math.floor(g/30)}mo ago`,I=await ut(o,h,c.handle).catch(()=>null),e=I?` ${zs[I]}`:"";C.push(`${$} **${c.handle}**${e} \u2014 ${c.lessonCount} lesson${c.lessonCount!==1?"s":""} \xB7 ${m}% confidence \xB7 last active ${M}`,` _domains: ${c.domains}_`,"")}return t.length>0&&s&&C.push(`\u{1F91D} **${s.handle}** frequently works with: ${t.map(i=>`**${i}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),C.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),C.join(`
|
|
55
|
+
`)}case"brain_file_map":{const{instance_id:h,file_paths:n=[]}=A,p=(Array.isArray(n)?n:[]).filter(a=>typeof a=="string"&&a.trim().length>0).map(a=>a.trim());if(!p.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const w=await F(h),o=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const a of p.slice(0,10)){o.push(`### \`${a}\``);const N=`file:${me(a)}`,d=await w.smembers(`cachly:ckg:idx:to:${N}`),r=[];for(const C of d){const i=await w.get(C);if(!i)continue;const c=P(i,null);if(!c||c.edgeType!=="touched")continue;const $=await w.get(`cachly:ckg:node:${c.from}`);if(!$)continue;const m=P($,null);!m||m.type!=="person"||r.push({handle:m.handle,touches:c.trials,lastSeen:c.last_updated})}if(r.sort((C,i)=>i.touches-C.touches),r.length>0){const C=r.slice(0,5).map((i,c)=>{const $=c===0?"\u{1F947}":c===1?"\u{1F948}":c===2?"\u{1F949}":`${c+1}.`,m=Math.floor((Date.now()-new Date(i.lastSeen).getTime())/864e5),g=m<1?"today":m<7?`${m}d ago`:`${Math.floor(m/7)}w ago`;return`${$} **${i.handle}** (${i.touches}\xD7 \xB7 ${g})`}).join(" \xB7 ");o.push(`**Experts:** ${C}`)}else o.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const t=a.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),s=[];if(t)try{const C=await et(w,["cachly:lesson:best:*"],t,4);for(const i of C){const c=De(i.content);if(!Ke(c))continue;const $=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=c.severity==="critical"?" \u{1F534}":c.severity==="major"?" \u{1F7E1}":"",g=c.author?` \xB7 \u{1F464} ${c.author}`:"",M=i.key.replace("cachly:lesson:best:","");s.push(` - ${$} \`${M}\`${m}${g} \u2014 ${(c.what_worked??"").slice(0,100)}`)}}catch{}if(s.length<2){const C=await Ae(w,"cachly:lesson:best:*",{max:1500});for(const i of C.slice(0,300)){const c=await w.get(i);if(!c)continue;const $=De(c);if(!Ke($)||!($.file_paths??[]).includes(a))continue;const m=i.replace("cachly:lesson:best:","");if(s.some(e=>e.includes(`\`${m}\``)))continue;const g=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C",M=$.severity==="critical"?" \u{1F534}":$.severity==="major"?" \u{1F7E1}":"",I=$.author?` \xB7 \u{1F464} ${$.author}`:"";s.push(` - ${g} \`${m}\`${M}${I} \u2014 ${($.what_worked??"").slice(0,100)}`)}}s.length>0?(o.push("**Related lessons:**"),o.push(...s.slice(0,5))):o.push("**Related lessons:** _None yet_"),o.push("")}return o.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),o.join(`
|
|
56
|
+
`)}case"team_expertise_map":{const{instance_id:h,top_n:n=20}=A,p=await F(h),w=await Ae(p,"cachly:ckg:node:person:*",{max:2e3});if(w.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(`
|
|
57
|
+
`);const o=[];for(const d of w){const r=await p.get(d);if(!r)continue;const S=P(r,null);if(!S||S.type!=="person")continue;const t=await p.smembers(`cachly:ckg:idx:from:${S.id}`),s=new Map;let C=0;for(const i of t){const c=await p.get(i);if(!c)continue;const $=P(c,null);if(!$||$.edgeType!=="authored")continue;C++;const m=$.to.split(":")[0]??"unknown";s.set(m,(s.get(m)??0)+1)}o.push({handle:S.handle,lessonCount:C,domains:s,lastActive:S.last_active})}o.sort((d,r)=>r.lessonCount-d.lessonCount);const a=o.slice(0,n),N=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${a.length}** contributor${a.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[d,r]of a.entries()){const S=d===0?"\u{1F947}":d===1?"\u{1F948}":d===2?"\u{1F949}":`${d+1}`,t=Math.floor((Date.now()-new Date(r.lastActive).getTime())/864e5),s=t<1?"today":t<7?`${t}d ago`:t<30?`${Math.floor(t/7)}w ago`:`${Math.floor(t/30)}mo ago`,C=[...r.domains.entries()].sort((i,c)=>c[1]-i[1]).slice(0,3).map(([i,c])=>`${i}(${c})`).join(", ")||"\u2014";N.push(`| ${S} | **${r.handle}** | ${r.lessonCount} | ${C} | ${s} |`)}return N.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),N.join(`
|
|
58
|
+
`)}case"skill_gaps":{const{instance_id:h,min_failures:n=1}=A,p=await F(h),w=await Ae(p,"cachly:lesson:best:*",{max:3e3}),o=new Map;let a=0,N=0;for(const S of w){const t=await p.get(S);if(!t)continue;const s=De(t);if(s===null)continue;const C=(s.topic??"").split(":")[0]??"unknown",i=o.get(C)??{successes:0,failures:0,attributed:0,topics:[]};s.outcome==="success"||s.outcome==="partial"?i.successes++:i.failures++,s.author&&(i.attributed++,a++),s.visibility==="private"&&N++,i.topics.push(s.topic??""),o.set(C,i)}const d=[];for(const[S,t]of o)t.failures>=n&&t.successes===0&&d.push({domain:S,type:"unresolved failures",severity:t.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${t.failures} failure${t.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),t.successes+t.failures>=3&&t.attributed===0&&d.push({domain:S,type:"no attribution",severity:"\u{1F535} info",detail:`${t.successes+t.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const r=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${w.length}** lessons scanned \xB7 **${a}** attributed \xB7 **${d.length}** gap${d.length!==1?"s":""} found`,N>0?`_(${N} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(d.length===0)r.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const S=[...d.filter(t=>t.severity.includes("critical")),...d.filter(t=>t.severity.includes("warn")),...d.filter(t=>t.severity.includes("info"))];for(const t of S.slice(0,15))r.push(`${t.severity} **\`${t.domain}\`** \u2014 ${t.type}`),r.push(` ${t.detail}`),r.push("");d.length>15&&r.push(`_\u2026and ${d.length-15} more gaps. Fix critical ones first._`)}return r.push("---",`_Fix gaps with \`learn_from_attempts(topic="${d[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),r.join(`
|
|
59
|
+
`)}case"brain_coverage":{const{instance_id:h,repo_path:n="."}=A,p=await F(h),[w,o,a]=await Promise.all([Ae(p,"cachly:lesson:best:*",{max:5e3}),Ae(p,"cachly:ckg:node:person:*",{max:2e3}),Ae(p,"cachly:ckg:node:file:*",{max:5e3})]);let N=0,d="n/a";try{const m=nt(n);if(!m)throw new Error("repo_path ist kein Ordner");N=We(m,["ls-files"],{timeoutMs:3e4}).trim().split(`
|
|
60
|
+
`).filter(Boolean).length,d=String(N)}catch{}let r=0,S=0,t=0;const s=new Set;for(const m of w){const g=await p.get(m);if(!g)continue;const M=P(g,{});M.outcome==="success"||M.outcome==="partial"?r++:S++,M.author&&t++,s.add((M.topic??"").split(":")[0]??"unknown")}const C=N>0?`${Math.round(a.length/N*100)}% (${a.length}/${N} files)`:`${a.length} files tracked`,i=w.length>0?Math.round(t/w.length*100):0,c=Math.round(Math.min(1,w.length/50)*25+Math.min(1,r/Math.max(1,w.length))*25+Math.min(1,i/100)*25+Math.min(1,o.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 | **${w.length}** (${r} success \xB7 ${S} failure) |`,`| Problem domains | **${s.size}** |`,`| Attribution | **${t}/${w.length}** (${i}%) |`,`| Contributors | **${o.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,w.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,r/Math.max(1,w.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,o.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(`
|
|
61
|
+
`)}case"brain_metrics":{const{instance_id:h}=A,n=await F(h),[p,w,o,a,N,d]=await Promise.all([n.get(`cachly:stats:born_at:${h}`).catch(()=>null),n.get(`cachly:stats:first_recall_at:${h}`).catch(()=>null),n.get(`cachly:stats:recalls_total:${h}`).catch(()=>null),n.get(`cachly:stats:cross_author_recalls:${h}`).catch(()=>null),n.get(`cachly:stats:time_saved_mins:${h}`).catch(()=>null),n.smembers(`cachly:stats:reuse_pairs:${h}`).catch(()=>[])]);let r={};try{r=await n.hgetall(rs(h))??{}}catch{r={}}let S={};try{S=await n.hgetall(Wt(h))??{}}catch{S={}}const t={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const f=await n.lrange(jt(h),0,499),J=new Map;for(const Z of f){const Q=P(Z,{ts:"",themen:[]});if(!(!Q.ts||!Array.isArray(Q.themen)))for(const X of Q.themen){if(t.lieferungen++,!J.has(X)){const ne=await n.get(`cachly:lesson:best:${X}`).catch(()=>null);J.set(X,ne?P(ne,{}):null)}const q=fn(Q.ts,J.get(X)??null);if(q.length===0){t.ohneEreignis++;continue}for(const ne of q)t[ne]++}}}catch{}let s=0,C=0;try{const f=await n.lrange(`cachly:wirkung:${h}`,0,-1);for(const J of f){const Z=P(J,{});C++,Z.geholfen===!0&&s++}}catch{}let i={};try{i=await n.hgetall(to(h))??{}}catch{i={}}const c=so(i,10);let $={token:0,abrufe:0,treffer:0};try{const f=await n.get(ao(h)),J=await n.hgetall(ro(h))??{};$={token:f??0,abrufe:J.abrufe??0,treffer:J.treffer??0}}catch{}const m=oo($);let g;if(p&&w){const f=new Date(w).getTime()-new Date(p).getTime(),J=Math.max(0,Math.round(f/6e4)),Z=J<1?"<1 min":J<60?`${J} min`:`${(J/60).toFixed(1)} h`,Q=f<=2*6e4?"\u{1F7E2} under 2 min target":f<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";g=`**${Z}** from first lesson \u2192 first proven recall \xB7 ${Q}`}else p&&!w?g="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":g="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const M=["\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(`
|
|
62
|
+
`),I=Number(o??0),e=Number(a??0),V=I>0?Math.round(e/I*100):0,ie=V>=30?"\u{1F7E2} above 30 % target":I===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",ae=Math.round(Number(N??0)),de=ae<60?`${ae} min`:`${(ae/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",g,"","### 2. Recall-lift _(the moat proof)_",M,"_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)_",`**${V}%** of proven recalls used a teammate's lesson (${e}/${I}) \xB7 ${ie}`,d.length>0?`**${d.length}** distinct reuse relationship${d.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",no(m),"",m.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${de} 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 ${de} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,I===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 f=Number(r.beantwortet??0),J=Number(r.knapp??0),Z=Number(r.schweigen??0),Q=f+J+Z;if(Q===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const X=q=>`${Math.round(100*q/Q)} %`;return`**${Q}** Suchen: ${X(f)} beantwortet \xB7 ${X(J)} als knapper Sieg markiert \xB7 ${X(Z)} 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 f=X=>Number(S[X]??0),J=[["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)"]],Z=J.reduce((X,[q])=>X+f(q),0);if(Z===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const Q=J.filter(([X])=>X!=="ohne-vorwissen").sort((X,q)=>f(q[0])-f(X[0]))[0];return`**${Z}** klassifizierte Fehlschlaege: `+J.map(([X,q])=>`${f(X)} ${q}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${Q[1]}** (${f(Q[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)_",t.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${t.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${t.widersprochen} widersprochen \xB7 ${t.korrigiert} korrigiert \xB7 ${t.veraltet} veraltet \xB7 ${t.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 f=Number(t.widersprochen)+Number(t.veraltet);if(C===0&&f===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const J=s-f;return`**${J>=0?"+":""}${J}** = ${s} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${f} Schadenslieferungen (${t.widersprochen} spaeter widerlegt + ${t.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",eo(c,po.length),...c.spitze.length>0?c.spitze.map((f,J)=>` ${String(J+1).padStart(2)}. \`${f.name}\` \u2014 ${f.aufrufe}\xD7 (${Math.round(f.anteil*100)} %)`):[]].filter(Boolean).join(`
|
|
63
|
+
`)}case"brain_service_map":{const{instance_id:h,service:n}=A;if(!n||typeof n!="string"||!n.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const p=await F(h),w=`service:${me(n.trim())}`,o=await p.get(`cachly:ckg:node:${w}`).catch(()=>null),a=o?P(o,null):null,N=await p.smembers(`cachly:ckg:idx:to:${w}`).catch(()=>[]),d=[],r=[],S=[];for(const g of N){const M=await p.get(g).catch(()=>null);if(!M)continue;const I=P(M,null);if(I)if(I.edgeType==="operates"){const e=await p.get(`cachly:ckg:node:${I.from}`).catch(()=>null),V=e?P(e,null):null;V?.handle&&d.push({handle:V.handle,trials:I.trials})}else if(I.edgeType==="runs_in"){const e=await p.get(`cachly:ckg:node:${I.from}`).catch(()=>null),V=e?P(e,null):null;V?.path&&r.push({path:V.path,trials:I.trials})}else I.edgeType==="affects"&&S.push({id:I.from,confidence:I.confidence})}d.sort((g,M)=>M.trials-g.trials),r.sort((g,M)=>M.trials-g.trials),S.sort((g,M)=>M.confidence-g.confidence);const t=[],s=await Ae(p,"cachly:lesson:best:*",{max:1500}),C=n.trim().toLowerCase();for(const g of s.slice(0,400)){const M=await p.get(g).catch(()=>null);if(!M)continue;const I=De(M);Ke(I)&&(I.service??"").toLowerCase()===C&&t.push({...I,topic:g.replace("cachly:lesson:best:","")})}if(!a&&t.length===0&&d.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${n}\``,"","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="${n}", author="you", file_paths=[...])\``].join(`
|
|
64
|
+
`);const i=a?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${a?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${n}\``,"",a?`_${i} \xB7 ${a.count} lesson${a.count!==1?"s":""} referenced \xB7 domain: ${a.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(d.length>0){const g=d.slice(0,5).map((M,I)=>`${I===0?"\u{1F947}":I===1?"\u{1F948}":I===2?"\u{1F949}":`${I+1}.`} **${M.handle}** (${M.trials}\xD7)`).join(" \xB7 ");c.push(`**Operators:** ${g}`,"")}else c.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const $=t.filter(g=>g.outcome==="failure"),m=t.filter(g=>g.outcome!=="failure");if($.length>0){c.push(`**\u26A0\uFE0F Known failures (${$.length}):**`);for(const g of $.slice(0,6)){const M=g.severity==="critical"?" \u{1F534}":g.severity==="major"?" \u{1F7E1}":"",I=g.author?` \xB7 \u{1F464} ${g.author}`:"";c.push(` - \u274C \`${g.topic}\`${M}${I} \u2014 ${(g.what_worked??"").slice(0,100)}`)}c.push("")}if(m.length>0){c.push(`**\u2705 Proven fixes (${m.length}):**`);for(const g of m.slice(0,6)){const M=g.outcome==="partial"?"\u26A0\uFE0F":"\u2705",I=g.author?` \xB7 \u{1F464} ${g.author}`:"";c.push(` - ${M} \`${g.topic}\`${I} \u2014 ${(g.what_worked??"").slice(0,100)}`)}c.push("")}return r.length>0&&c.push(`**Files in this service:** ${r.slice(0,8).map(g=>`\`${g.path}\``).join(", ")}`,""),c.push("---",`_Tag lessons with \`service="${n}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),c.join(`
|
|
65
|
+
`)}case"brain_collab_pairs":{const{instance_id:h,min_weight:n=1}=A,p=await F(h),w=typeof n=="number"&&n>=1?Math.floor(n):1,o=await Ae(p,"cachly:ckg:node:person:*",{max:500}),a=new Map;for(const s of o){const C=await p.get(s);if(!C)continue;const i=P(C,null);!i||i.type!=="person"||a.set(i.id,{id:i.id,handle:i.handle,domain:i.domain,count:i.count})}if(a.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(`
|
|
66
|
+
`);const N=new Map;for(const[s,C]of a){const i=await p.smembers(`cachly:ckg:idx:from:${s}`);for(const c of i){const $=await p.get(c);if(!$)continue;const m=P($,null);if(!m||m.edgeType!=="collaborates")continue;const g=a.get(m.to);if(!g)continue;const[M,I]=s<m.to?[s,m.to]:[m.to,s],e=`${M}||${I}`,V=N.get(e);if(V)V.trials+=m.trials;else{const[ie,ae]=s<m.to?[C,g]:[g,C];N.set(e,{a:ie,b:ae,trials:m.trials,confidence:m.confidence})}}}const d=[...N.values()].filter(s=>s.trials>=w).sort((s,C)=>C.trials-s.trials),r=new Set;for(const s of d)r.add(s.a.id),r.add(s.b.id);const S=[...a.values()].filter(s=>!r.has(s.id)),t=["## \u{1F91D} Team Collaboration Graph",""];if(d.length===0)t.push(`No collaboration pairs yet (min weight: ${w}).`,"","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{t.push(`**${d.length} collaboration pair${d.length!==1?"s":""}** across ${r.size} contributor${r.size!==1?"s":""}:`,"");for(const s of d.slice(0,20)){const C=(s.confidence*100).toFixed(0),i=[s.a.domain,s.b.domain].filter((c,$,m)=>c&&m.indexOf(c)===$).map(c=>`\`${c}\``).join(", ");t.push(`### @${s.a.handle} \u2194 @${s.b.handle}`,`- **${s.trials} collaboration event${s.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${i||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${s.a.handle}** und **@${s.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}d.length>20&&t.push(`_...and ${d.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return S.length>0&&t.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${S.length} contributor${S.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...S.slice(0,10).map(s=>`- **@${s.handle}** \u2014 ${s.count} lesson${s.count!==1?"s":""} \xB7 domain: \`${s.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),t.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),t.join(`
|
|
67
|
+
`)}case"brain_portability":{const{instance_id:h}=A,n=[{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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}]},null,2)}],p=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${h}\``,"","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 (${n.length} supported)`,""];for(const w of n)p.push(`#### ${w.icon} ${w.name}`,`Config: \`${w.configPath}\``,"","```json",w.configBlock,"```","");return p.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 \`${h}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),p.join(`
|
|
68
|
+
`)}case"brain_changelog":{const{instance_id:h,days:n=7,max_lessons:p=30,include_failures:w=!0}=A,o=await F(h),a=Date.now()-Number(n)*864e5,N=await Ae(o,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),d=[];for(const c of N){const $=await o.get(c).catch(()=>null);if(!$)continue;const m=P($,{});if((m.ts?new Date(m.ts).getTime():0)<a||!w&&m.outcome==="failure")continue;const M=c.replace("cachly:lesson:best:","");d.push({...m,topic:M})}d.sort((c,$)=>{const m=c.ts?new Date(c.ts).getTime():0;return($.ts?new Date($.ts).getTime():0)-m});const r=d.slice(0,Number(p));if(r.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${n} day${Number(n)!==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(`
|
|
69
|
+
`);const S=new Map;for(const c of r){const $=c.topic.includes(":")?c.topic.split(":")[0]:"general",m=S.get($)??[];m.push(c),S.set($,m)}const t=c=>c==="critical"?"\u{1F6A8}":c==="major"?"\u26A0\uFE0F":c==="minor"?"\u{1F4A1}":"\u2728",s=c=>c==="failure"?"\u274C":c==="partial"?"\u{1F536}":"\u2705",i=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${n} day${Number(n)!==1?"s":""})`,"",`_${r.length} lesson${r.length!==1?"s":""} learned across ${S.size} topic area${S.size!==1?"s":""}_`,""];for(const[c,$]of Array.from(S.entries()).sort((m,g)=>g[1].length-m[1].length)){i.push(`### ${c}`),i.push("");for(const m of $){const g=m.outcome==="failure"?s(m.outcome):t(m.severity),M=m.outcome==="failure"?m.what_failed:m.what_worked,I=[];m.author&&I.push(`by **${m.author}**`),m.recall_count&&I.push(`${m.recall_count} recall${m.recall_count!==1?"s":""}`),m.confidence!==void 0&&I.push(`${Math.round(m.confidence*100)}% confidence`),i.push(`- ${g} **${m.topic}**${M?` \u2014 ${M}`:""}`),I.length&&i.push(` _${I.join(" \xB7 ")}_`)}i.push("")}return i.push("---",`_Generated from Brain \`${h}\` \xB7 Share this in your standup or Slack_`),i.join(`
|
|
70
|
+
`)}case"brain_set_pref":{const{instance_id:h,key:n,value:p}=A;if(!n||!n.trim())throw new Error("key is required");const w=je({value:String(p)}),o=w.felder.value,a=await F(h),N=`cachly:prefs:${n.trim()}:${h}`;return await a.set(N,o),[`\u2705 Preference \`${n}\` set to \`${o}\` for this Brain instance.`,...Ve(w,"wert")].join(`
|
|
71
|
+
`)}case"brain_get_pref":{const{instance_id:h,key:n}=A,p=await F(h);if(n&&n.trim()){const N=await p.get(`cachly:prefs:${n.trim()}:${h}`).catch(()=>null);return N===null?`\u2139\uFE0F Preference \`${n}\` is not set (using default).`:`\u{1F527} Preference \`${n}\` = \`${N}\``}const w=await Ae(p,`cachly:prefs:*:${h}`,{max:200,timeoutMs:2e3});if(w.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const o=await p.mget(...w),a=["\u{1F527} **Brain preferences:**",""];for(let N=0;N<w.length;N++){const d=w[N].replace("cachly:prefs:","").replace(`:${h}`,"");a.push(`- \`${d}\` = \`${o[N]??"(null)"}\``)}return a.join(`
|
|
72
|
+
`)}default:return null}}async function Mo(D,A){try{if(!ze()||xe!=="cachly"&&xe!=="ollama")return 0;const{vektor:F,zweit:ce}=yt(D);let h=0;for(const n of F.themen()){if(h>=A)break;if(ce.hat(n)||await D.exists(`${Ge}${n}`))continue;const p=await D.get(`cachly:lesson:best:${n}`);if(!p)continue;const w=P(p,{});try{const o=await Ce(He(w),{geduld:"lang",modell:Ue});o?.length&&(await D.set(`${Ge}${n}`,Pe(o)),h++)}catch{}}return h}catch{return 0}}async function us(D,A,F){try{if(!ze())return;const ce=await D.srandmember(Je,F),h=Array.isArray(ce)?ce:ce?[ce]:[];for(const n of h){if(n===A)continue;const p=await D.get(`cachly:lesson:best:${n}`);if(!p){await D.srem(Je,n);continue}const w=P(p,{});try{const o=await Ce(He(w),{geduld:"lang"});if(o?.length)await D.set(`${Dt}${n}`,Pe(o)),await D.srem(Je,n);else continue;if(xe==="cachly"||xe==="ollama")try{const a=await Ce(He(w),{geduld:"lang",modell:Ue});a?.length&&(await D.set(`${Ge}${n}`,Pe(a)),await D.srem(st,n))}catch{}}catch{}}await ds(D,tt,pt,A,F,n=>{const p=zt(n);return p?Ce(p,{geduld:"lang"}):Promise.resolve(null)}),(xe==="cachly"||xe==="ollama")&&await ds(D,st,Ge,A,F,(n,p)=>Ce(He(p),{geduld:"lang",modell:Ue}))}catch{}}async function ds(D,A,F,ce,h,n){const p=await D.srandmember(A,h),w=Array.isArray(p)?p:p?[p]:[];for(const o of w){if(o===ce)continue;const a=await D.get(`cachly:lesson:best:${o}`);if(!a){await D.srem(A,o);continue}if(await D.exists(`${F}${o}`)){await D.srem(A,o);continue}try{const N=await n(o,P(a,{}));N===null?await D.srem(A,o):N?.length&&(await D.set(`${F}${o}`,Pe(N)),await D.srem(A,o))}catch{}}}export{Ba as BRAIN_TOOL_NAMES,Et as RECALL_ROH_ZEICHEN,Nt as RECALL_VOLLTEXT_ZEICHEN,yt as bestaendeFuer,La as handleBrainTool,At as recallNurLesen,ht as recallVorschau};
|
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.230",
|
|
4
4
|
"mcpName": "io.github.cachly-dev/mcp-server",
|
|
5
5
|
"description": "Solve it once. From then on, your AI knows. Experience for coding agents, EU-hosted: an MCP server for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run.",
|
|
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.230",
|
|
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.230",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|