@cachly-dev/mcp-server 0.10.265 → 0.10.266

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/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as oo}from"./herkunft.js";import{jwtExpiryMs as no,checkJwt as so,handleApiError as io,diagnoseAuth as Pe,planAuthHeal as Ze,readClientCredentialsFromEnv as ro,buildClientCredentialsBody as ao,clientCredentialsTokenUrl as co}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as lo}from"./werkzeug-nutzung.js";import{istLieferung as uo,lieferSchluessel as po,tokenDerAntwort as mo,hatTreffer as go,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as fo}from"node:module";import{execFile as Le}from"node:child_process";const ho=process.argv[1]!=null&&(process.argv[1]===et(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as tt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as yo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as bo}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as it,ListToolsRequestSchema as rt,McpError as Z}from"@modelcontextprotocol/sdk/types.js";import{Redis as at}from"ioredis";let w=process.env.CACHLY_API_URL??"https://api.cachly.dev",S=Fe()??"";oe(S);const Pi=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=fo(import.meta.url);for(const t of["../../package.json","../package.json"])try{const n=e(t);if(n.name==="@cachly-dev/mcp-server"&&n.version)return n.version}catch{}}catch{}return"0.10.100"})(),vo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=Ie(process.env.CACHLY_BRAIN_INSTANCE_ID);function ve(){return W()?xe()?.schluessel??"":S}function wo(){return W()?xe()?.instanzId??"":N}function X(){return S||Fe()||""}function U(){return Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||Te()||""}let Q=0,ue=null,ct=!1;async function lt(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Ts({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function re(){return ct?Et(process.env):!1}function Oe(e,t,n){!e||!re()||ks({instanzId:e,vomHook:n,verbindung:O,ausGit:o=>Je("brain_from_git",o,O,L),projektOrdner:t?async()=>t:lt,einbetten:o=>gt(o,{geduld:"lang"}),hatEinbettung:Bo,einbettenZweit:o=>gt(o,{geduld:"lang",modell:Zo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,O,L),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function He(){return re()&&Is()}const xo=7e3,_o=12e3,$o=18e4;let we=null;function Me(e){return we||(we=ko(e).finally(()=>{we=null})),we}async function ko(e){try{if(!S){const t=Date.now()+e;for(;!Ce()&&hs({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,ms));const n=Ce();if(!n)return!1;S=n,oe(n);const o=Te();o&&!N&&(N=o,Q=0),await pe(n),o&&await me(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(re()&&It()){const t=gs();t&&(Ye(t.instanzId,re(),He()),Oe(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function So(){if(!Et(process.env))return;const e=Date.now()+$o,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!It()||Me(0)},500);t.unref(),Me(0)}async function Ao(){if(!S||W())return"";try{const e=await fetch(`${w}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),n=t.instance?.id??t.instance_id;if(n)return n}else fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function dt(){if(W())return wo();if(N)return N;if(!S)return"";if(ue)return ue;const e=Date.now();if(Q>0&&e-Q<3e4)return"";Q=e,ue=(async()=>{try{const t=await fetch(`${w}/api/v1/instances`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(r=>r.status==="running")??o.find(r=>r.status==="provisioning");if(s)return N=s.id,Q=0,N;const i=await Ao();if(i)return N=i,Q=0,Ye(i,re(),He()),me(i),Oe(i),N}}catch{}return""})();try{return await ue}finally{ue=null}}let ze=0;const Co=6e4;let ae="";async function pe(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const d=await n(a,"utf-8"),u=JSON.parse(d),l=u?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_JWT=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ae(e,{apiKey:S});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const d=JSON.parse(await n(a,"utf-8")),u=d?.mcpServers?.cachly;u?.env&&(u.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(d,null,2),"utf-8"))}catch{}}))}catch{}}}async function To(){try{const e=await fetch(`${w}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({name:"cachly-mcp-selfheal",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(!e.ok)return!1;const t=await e.json();return t.key?(S=t.key,oe(t.key),pe(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function De(){const e=Pe(S),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-ze>=Co&&(ze=n,await To())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(r,a)=>{try{t?.(r,a)}catch{}},o=r=>{r?n(!1,r.code??r.message):n(!0)},s=Ln(e);if(!s){n(!1,"keine-http-adresse");return}const i=On(s);try{process.platform==="win32"?Le("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Le("open",[s],o):Le("xdg-open",[s],o)}catch(r){n(!1,r instanceof Error?r.message:"unknown")}}let K=null;async function Io(){try{const e=await fetch(`${w}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),n=t.verification_uri||j("/device","ambient-signin"),o=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:o,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+ut(t.expires_in),polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+ut(n.expires_in),polling:!1}}catch{return null}}function ut(e){const t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:600;return Math.min(t,3600)*1e3}function Eo(){const e=os(w);return e?{deviceCode:e.deviceCode,userCode:e.userCode,verifyUrl:e.verifyUrl,pollInterval:e.pollInterval,deadline:e.deadline,polling:!1}:null}async function Ro(e){if(Date.now()>e.deadline)return Ct(e.deviceCode),"expired";const t=async()=>{const o=await fetch(`${w}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return o.ok?o.json():null},n=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let o=await t().catch(()=>null);if(o||(o=await n().catch(()=>null)),!o)return"pending";if(o.access_token){let s=o.access_token;try{const i=await fetch(`${w}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(i.ok){const r=await i.json();r.key&&(s=r.key)}}catch{}return S=s,oe(s),K=null,Ct(e.deviceCode),A("device_flow_completed"),pe(s),ne(s),Q=0,await dt(),N&&me(N),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function pt(e){if(e.polling)return"pending";e.polling=!0;try{return await Ro(e)}finally{e.polling=!1}}function mt(e,t=pt,n=s=>K===s,o=jo){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(K=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function jo(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as gt,hasEmbedProvider as Bo,EMBED_PROVIDER as ft,erzwingeEmbedAnbieterRemote as No}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as Po,mandantKontext as xe,imMandant as Lo,baueKontext as Oo,poolSchluessel as Ho,leseBearer as Mo,leseInstanzKopf as zo,BegrenzterSpeicher as Do,baueZugangsAufloeser as Uo,ZugangAbgelehnt as Wo,bauePruefGrenze as Jo,leseAufruferIp as Fo,imAufrufer as Yo,installiereApiKoepfe as Ko,ANLEITUNG_OHNE_KOPF as Ue,istRemoteErlaubt as Go,nurLokalText as qo,bereinigeArgumente as Vo}from"./remote-zugang.js";import{ZWEIT_MODELL as Zo}from"./rangfolge-stellschrauben.js";import{tokenize as Xo,splitMultiQuery as Qo,levenshtein as en,recencyBoost as tn,extractTimestamp as on,STOPWORDS as nn,katakanaToRomaji as sn,arabicLightStem as rn,expandCrossLingual as an,CROSS_LINGUAL_MAP as cn}from"./search.js";const ge=new Map,ln=200,dn=10*6e4,_e=new Do({max:ln,ttlMs:dn,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...ge.values(),..._e.werte()]}function un(e){return e<=1?200:null}async function O(e){if(!e)throw new Z(te.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
2
+ import{setzeClientKennung as oo}from"./herkunft.js";import{jwtExpiryMs as no,checkJwt as so,handleApiError as io,diagnoseAuth as Pe,planAuthHeal as Ze,readClientCredentialsFromEnv as ro,buildClientCredentialsBody as ao,clientCredentialsTokenUrl as co}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as lo}from"./werkzeug-nutzung.js";import{istLieferung as uo,lieferSchluessel as po,tokenDerAntwort as mo,hatTreffer as fo,trefferSchluessel as Qe}from"./geliefert.js";import{notify as Xe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as go}from"node:module";import{execFile as Le}from"node:child_process";const ho=process.argv[1]!=null&&(process.argv[1]===et(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as tt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as yo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as bo}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as it,ListToolsRequestSchema as rt,McpError as Z}from"@modelcontextprotocol/sdk/types.js";import{Redis as at}from"ioredis";let w=process.env.CACHLY_API_URL??"https://api.cachly.dev",S=Fe()??"";oe(S);const Pi=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=go(import.meta.url);for(const t of["../../package.json","../package.json"])try{const n=e(t);if(n.name==="@cachly-dev/mcp-server"&&n.version)return n.version}catch{}}catch{}return"0.10.100"})(),vo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=Ie(process.env.CACHLY_BRAIN_INSTANCE_ID);function ve(){return W()?xe()?.schluessel??"":S}function wo(){return W()?xe()?.instanzId??"":N}function Q(){return S||Fe()||""}function U(){return Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||Te()||""}let X=0,ue=null,ct=!1;async function lt(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Ts({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function re(){return ct?Et(process.env):!1}function Oe(e,t,n){!e||!re()||ks({instanzId:e,vomHook:n,verbindung:O,ausGit:o=>Je("brain_from_git",o,O,L),projektOrdner:t?async()=>t:lt,einbetten:o=>ft(o,{geduld:"lang"}),hatEinbettung:Bo,einbettenZweit:o=>ft(o,{geduld:"lang",modell:Zo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,O,L),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function He(){return re()&&Is()}const xo=7e3,_o=12e3,$o=18e4;let we=null;function Me(e){return we||(we=ko(e).finally(()=>{we=null})),we}async function ko(e){try{if(!S){const t=Date.now()+e;for(;!Ce()&&hs({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,ms));const n=Ce();if(!n)return!1;S=n,oe(n);const o=Te();o&&!N&&(N=o,X=0),await pe(n),o&&await me(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(re()&&It()){const t=fs();t&&(Ye(t.instanzId,re(),He()),Oe(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function So(){if(!Et(process.env))return;const e=Date.now()+$o,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!It()||Me(0)},500);t.unref(),Me(0)}async function Ao(){if(!S||W())return"";try{const e=await fetch(`${w}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),n=t.instance?.id??t.instance_id;if(n)return n}else fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function dt(){if(W())return wo();if(N)return N;if(!S)return"";if(ue)return ue;const e=Date.now();if(X>0&&e-X<3e4)return"";X=e,ue=(async()=>{try{const t=await fetch(`${w}/api/v1/instances`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(r=>r.status==="running")??o.find(r=>r.status==="provisioning");if(s)return N=s.id,X=0,N;const i=await Ao();if(i)return N=i,X=0,Ye(i,re(),He()),me(i),Oe(i),N}}catch{}return""})();try{return await ue}finally{ue=null}}let ze=0;const Co=6e4;let ae="";async function pe(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const d=await n(a,"utf-8"),u=JSON.parse(d),l=u?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_JWT=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ae(e,{apiKey:S});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const d=JSON.parse(await n(a,"utf-8")),u=d?.mcpServers?.cachly;u?.env&&(u.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(d,null,2),"utf-8"))}catch{}}))}catch{}}}async function To(){try{const e=await fetch(`${w}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({name:"cachly-mcp-selfheal",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(!e.ok)return!1;const t=await e.json();return t.key?(S=t.key,oe(t.key),pe(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function De(){const e=Pe(S),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-ze>=Co&&(ze=n,await To())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(r,a)=>{try{t?.(r,a)}catch{}},o=r=>{r?n(!1,r.code??r.message):n(!0)},s=Ln(e);if(!s){n(!1,"keine-http-adresse");return}const i=On(s);try{process.platform==="win32"?Le("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Le("open",[s],o):Le("xdg-open",[s],o)}catch(r){n(!1,r instanceof Error?r.message:"unknown")}}let K=null;async function Io(){try{const e=await fetch(`${w}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),n=t.verification_uri||j("/device","ambient-signin"),o=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:o,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+ut(t.expires_in),polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+ut(n.expires_in),polling:!1}}catch{return null}}function ut(e){const t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:600;return Math.min(t,3600)*1e3}function Eo(){const e=os(w);return e?{deviceCode:e.deviceCode,userCode:e.userCode,verifyUrl:e.verifyUrl,pollInterval:e.pollInterval,deadline:e.deadline,polling:!1}:null}async function Ro(e){if(Date.now()>e.deadline)return Ct(e.deviceCode),"expired";const t=async()=>{const o=await fetch(`${w}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return o.ok?o.json():null},n=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let o=await t().catch(()=>null);if(o||(o=await n().catch(()=>null)),!o)return"pending";if(o.access_token){let s=o.access_token;try{const i=await fetch(`${w}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(i.ok){const r=await i.json();r.key&&(s=r.key)}}catch{}return S=s,oe(s),K=null,Ct(e.deviceCode),A("device_flow_completed"),pe(s),ne(s),X=0,await dt(),N&&me(N),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function pt(e){if(e.polling)return"pending";e.polling=!0;try{return await Ro(e)}finally{e.polling=!1}}function mt(e,t=pt,n=s=>K===s,o=jo){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(K=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function jo(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as ft,hasEmbedProvider as Bo,EMBED_PROVIDER as gt,erzwingeEmbedAnbieterRemote as No}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as Po,mandantKontext as xe,imMandant as Lo,baueKontext as Oo,poolSchluessel as Ho,leseBearer as Mo,leseInstanzKopf as zo,BegrenzterSpeicher as Do,baueZugangsAufloeser as Uo,ZugangAbgelehnt as Wo,bauePruefGrenze as Jo,leseAufruferIp as Fo,imAufrufer as Yo,installiereApiKoepfe as Ko,ANLEITUNG_OHNE_KOPF as Ue,istRemoteErlaubt as Go,nurLokalText as qo,bereinigeArgumente as Vo}from"./remote-zugang.js";import{ZWEIT_MODELL as Zo}from"./rangfolge-stellschrauben.js";import{tokenize as Qo,splitMultiQuery as Xo,levenshtein as en,recencyBoost as tn,extractTimestamp as on,STOPWORDS as nn,katakanaToRomaji as sn,arabicLightStem as rn,expandCrossLingual as an,CROSS_LINGUAL_MAP as cn}from"./search.js";const fe=new Map,ln=200,dn=10*6e4,_e=new Do({max:ln,ttlMs:dn,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...fe.values(),..._e.werte()]}function un(e){return e<=1?200:null}async function O(e){if(!e)throw new Z(te.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
3
3
 
4
4
  This usually resolves in a few seconds \u2014 just call the tool again and it will connect automatically.
5
5
 
6
6
  If it keeps happening:
7
7
  \u2022 Run \`list_instances\` to check your instances, or
8
8
  \u2022 Set CACHLY_BRAIN_INSTANCE_ID in your MCP config, or
9
- \u2022 Reach us at support@cachly.dev.`);const t=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,Ue);const n=t?Ho(t.schluessel,e):e,o=t?_e.get(n):ge.get(e);return o||xs(pn,n,()=>mn(e,n,!!t))}const pn=new Map;async function mn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await L(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await ws(o,()=>L(`/api/v1/instances/${e}`),{fristMs:vo,melde:u=>Y(`verbindung: Instanz ${u.status}`)}),o.status!=="running"){n||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let u;throw o.status==="provisioning"?u=`\u23F3 Brain instance "${o.name}" is still starting up.
9
+ \u2022 Reach us at support@cachly.dev.`);const t=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,Ue);const n=t?Ho(t.schluessel,e):e,o=t?_e.get(n):fe.get(e);return o||xs(pn,n,()=>mn(e,n,!!t))}const pn=new Map;async function mn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await L(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await ws(o,()=>L(`/api/v1/instances/${e}`),{fristMs:vo,melde:u=>Y(`verbindung: Instanz ${u.status}`)}),o.status!=="running"){n||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let u;throw o.status==="provisioning"?u=`\u23F3 Brain instance "${o.name}" is still starting up.
10
10
 
11
11
  First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:o.status==="failed"?u=`\u274C Brain instance "${o.name}" failed to start.
12
12
 
@@ -18,11 +18,11 @@ Update your payment method at: ${j("/billing","upgrade")}`:o.status==="pending_p
18
18
  Complete your checkout at: ${j("/instances","upgrade")}`:u=`Brain instance "${o.name}" is not reachable (status: ${o.status}).
19
19
 
20
20
  \u2022 View your instance at: ${j("/instances","instance-error")}
21
- \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,u)}if(!o.host||!o.port)throw new Z(te.InternalError,`Instance "${o.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let s,i;try{const u=await L(`/api/v1/instances/${e}/connection`);s=u.password??void 0,i=u,Y("verbindung: Zugangsdaten da")}catch(u){const l=u instanceof Error?u.message:String(u);if(l.includes("401")||l.includes("403")||l.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const r=Nt({host:o.host,port:o.port,tls_enabled:o.tls_enabled},i),a=new at({host:r.host,port:r.port,password:s||void 0,commandTimeout:8e3,...r.tls?{tls:r.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:un,maxRetriesPerRequest:1,keepAlive:15e3}),d=()=>{n?_e.vergissWenn(t,a):ge.delete(e),a.disconnect()};a.on("error",d),a.on("end",d);try{await a.connect()}catch(u){a.disconnect();const l=u instanceof Error?u.message:String(u);throw n||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:l,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(te.InternalError,`Could not reach Brain instance "${o.name}" (${o.host}:${o.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,u)}if(!o.host||!o.port)throw new Z(te.InternalError,`Instance "${o.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let s,i;try{const u=await L(`/api/v1/instances/${e}/connection`);s=u.password??void 0,i=u,Y("verbindung: Zugangsdaten da")}catch(u){const l=u instanceof Error?u.message:String(u);if(l.includes("401")||l.includes("403")||l.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const r=Nt({host:o.host,port:o.port,tls_enabled:o.tls_enabled},i),a=new at({host:r.host,port:r.port,password:s||void 0,commandTimeout:8e3,...r.tls?{tls:r.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:un,maxRetriesPerRequest:1,keepAlive:15e3}),d=()=>{n?_e.vergissWenn(t,a):fe.delete(e),a.disconnect()};a.on("error",d),a.on("end",d);try{await a.connect()}catch(u){a.disconnect();const l=u instanceof Error?u.message:String(u);throw n||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:l,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(te.InternalError,`Could not reach Brain instance "${o.name}" (${o.host}:${o.port}).
22
22
 
23
23
  \u2022 Check your network connection
24
24
  \u2022 Run \`get_api_status\` to verify instance status
25
- \u2022 Technical detail: ${l}`)}return n?_e.set(t,a):ge.set(e,a),Y("verbindung: Valkey verbunden"),a}async function L(e,t={},n=!1){!n&&!W()&&Ze(Pe(S))!=="none"&&await De();const o=ve();so(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${w}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!i.ok){if(i.status===401&&!n&&!W()&&(ze=0,await De()))return L(e,t,!0);const a=(await i.json().catch(()=>({error:i.statusText}))).error??i.statusText;io(i.status,a)}if(i.status!==204)return i.json()}import{handleBrainTool as gn}from"./handlers/brain.js";import{handleContextTool as fn}from"./handlers/context.js";import{handleInstanceTool as hn}from"./handlers/instances.js";import{handleCacheTool as yn}from"./handlers/cache.js";import{handleTeamTool as bn}from"./handlers/team.js";import{handleRoadmapTool as vn}from"./handlers/roadmap.js";import{handleAdvancedTool as wn}from"./handlers/advanced.js";import{handleSyndicateTool as xn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as $e}from"./handlers/fedbrain.js";import{extractFirstRecallProof as _n,extractTopHit as $n,fuersTerminal as ht,renderFirstRecallProof as kn}from"./first-recall-proof.js";import{aussetzerLeise as Sn}from"./aussetzer.js";import{gitHookOrdner as An,installClsPostCommitHook as yt,CLS_HOOK_VERSION as bt}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Cn,CLAUDE_MD_MARKER_END as Tn,EDITOR_FILES as ke,ANWEISUNGS_DATEIEN as In,buildClaudeMdBlock as vt,setzeAnweisungsblock as En,sollSchreiben as Rn,globaleMcpDatei as Se,globalerEditorDa as wt,diesesHeim as fe,mcpZiel as xt}from"./projektdateien.js";import{klassiereArgument as jn,leseFlag as _t,flagsOhneWert as Bn,pruefeInitEingaben as Nn}from"./cli-argumente.js";import{uninstallBefehl as Pn}from"./uninstall.js";import{gitLesen as $t}from"./git-ohne-shell.js";import{browserAdresse as Ln,fuerCmd as On}from"./browser-adresse.js";import{installAmbientHooks as kt,installCursorHooks as Hn,installCopilotHooks as Mn,installCodexHooks as zn,installGeminiHooks as Dn,AMBIENT_HOOK_VERSION as St,COPILOT_HOOKS_DATEI as Un,CODEX_HOOKS_DATEI as Wn,GEMINI_SETTINGS_DATEI as Jn}from"./ambient-hooks.js";import{hookHauptlauf as Fn,auffrischenHauptlauf as Yn,startwissenImportHauptlauf as Kn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as Gn}from"./startwissen-hook.js";import{rahmeAntwort as qn}from"./antwort-rahmen.js";import{appendLedgerEntry as Vn,readLedger as At,defaultLedgerPath as Zn,reportLedgerEntry as Xn,teileNachInstanz as Qn}from"./ambient-ledger.js";import{installCodexMcp as es,installGeminiMcp as ts}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ae,readSavedApiKey as Ce,readInstanceId as Te}from"./credentials.js";import{ladeLaufendeAnmeldung as os,merkeAnmeldung as ns,vergissAnmeldung as Ct}from"./laufende-anmeldung.js";import{KEYCLOAK_BASIS as Tt,istTestSchluessel as ss,waehleTestSchluessel as is,starteKeycloakAnmeldung as rs,warteAufKeycloakAnmeldung as as,uebernimm as cs,brainImKonto as ls,erfolgsText as ds,fehlerText as us,ersetzeSchluessel as ps}from"./uebernahme.js";import{WARTE_TAKT_MS as ms,auftragLiegt as It,nimmAuftrag as gs,sichereKonto as fs,sperreLiegt as hs,startwissenEingeschaltet as Et}from"./konto-anlegen.js";import{sichereZugang as ys,echterWert as Ie}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as bs,SITZUNGS_WERKZEUGE as vs}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as ws,gemeinsamerAufbau as xs}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as _s,setzeCommitQuelle as $s}from"./leeres-brain.js";import{starteStartwissen as ks,startwissenGestartet as Ss,beanspruchStartwissen as As,holeStartwissenHinweis as Cs,waehleProjektOrdner as Ts,startvorratErlaubt as Is,projektCommits as Es}from"./startwissen.js";import{eigeneFassung as Rs,pruefeNeueFassung as js,holeNeueFassungHinweis as Bs}from"./neue-fassung.js";import{beiStdinEnde as Ns}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Ps,starteBrandWachhund as Ls}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Os,VERTEILER as Rt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Hs}from"./pflichtfelder.js";import{buildLessonsMarkdown as Ms,buildLessonsJsonl as zs,vonRohLektion as Ds}from"./brain-export.js";import{detectEditor as Us}from"./editor.js";import{milestoneSent as jt,markMilestoneSent as Bt}from"./funnel-milestones.js";import{meldeKopf as Ws,meldeRumpf as Js}from"./melde-weg.js";import{kostprobeUebrig as Fs,kostprobeVerbrauchen as Ys,kostprobeHinweis as Ks,kostprobePfadJeInstanz as Gs,schrankeNachKostproben as qs}from"./kostprobe.js";import{netBalance as Vs}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as Zs}from"./handlers/viz.js";import{commitArt as Xs,istRueckbau as Qs,zaehleLektionen as ei}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Nt}from"./brains-tls.js";let Pt=!1,Lt=!1,Ee=!1;function Ot(){return Us()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:Ws(S),body:JSON.stringify(Js({event:e,version:H,editor:Ot()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function ti(e,t){return Xn({apiUrl:w,jwt:S,instanceId:e},t)}async function oi(e){if(!(Pt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){Pt=!0;try{await fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Ot(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const ni=new Set(["causal_trace","brain_predict","brain_plan","brain_predict_failures","team_learn","team_confirm","team_recall","team_synthesize","team_crystallize","global_learn","global_recall"]),si={causal_trace:"Causal root-cause tracing \u2014 follow the failure chain to the real cause, not just the symptom.",brain_predict:"Predictive risk \u2014 your Brain warns you what will break *before* you run it.",brain_plan:"Generative planning \u2014 turn a goal into an ordered, risk-aware plan from your own history.",brain_predict_failures:"Failure prediction \u2014 catch CI/build breakage before it happens.",team_learn:"Team Brain \u2014 one shared memory across your whole team.",team_confirm:"Team Brain \u2014 peer + senior review that raises lesson trust.",team_recall:"Team Brain \u2014 recall everything your teammates have already solved.",team_synthesize:"Team Brain \u2014 synthesize collective knowledge across authors.",team_crystallize:"Team Brain \u2014 compress your team's wisdom into a shareable crystal.",global_learn:"Team Brain \u2014 contribute to your organization's shared memory.",global_recall:"Team Brain \u2014 recall across your entire organization."},Ht=j("/billing","upgrade"),Mt=new Map;async function ii(e){const t=Mt.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await L(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Mt.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function ri(e,t){if(!ni.has(e)||!t)return null;const{isFree:n}=await ii(t);if(!n)return null;const o=si[e]??"A Premium intelligence feature.",s=W()?Gs(t):void 0;if(Fs(e,s)){const i=Ys(e,s);return{kostprobe:Ks(e,i,Ht)}}return{sperre:qs(e,o,Ht)}}async function ai(e,t){try{await(await O(e)).hincrby(lo(e),t,1)}catch{}}async function ci(e,t,n){if(uo(t))try{const o=await O(e),s=go(n);await o.incrby(po(e),s?mo(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function li(e){const t=await Io();return t?(K=t,ns({deviceCode:t.deviceCode,userCode:t.userCode,verifyUrl:t.verifyUrl,pollInterval:t.pollInterval,deadline:t.deadline,apiUrl:w}),A("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
25
+ \u2022 Technical detail: ${l}`)}return n?_e.set(t,a):fe.set(e,a),Y("verbindung: Valkey verbunden"),a}async function L(e,t={},n=!1){!n&&!W()&&Ze(Pe(S))!=="none"&&await De();const o=ve();so(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${w}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!i.ok){if(i.status===401&&!n&&!W()&&(ze=0,await De()))return L(e,t,!0);const a=(await i.json().catch(()=>({error:i.statusText}))).error??i.statusText;io(i.status,a)}if(i.status!==204)return i.json()}import{handleBrainTool as fn}from"./handlers/brain.js";import{handleContextTool as gn}from"./handlers/context.js";import{handleInstanceTool as hn}from"./handlers/instances.js";import{handleCacheTool as yn}from"./handlers/cache.js";import{handleTeamTool as bn}from"./handlers/team.js";import{handleRoadmapTool as vn}from"./handlers/roadmap.js";import{handleAdvancedTool as wn}from"./handlers/advanced.js";import{handleSyndicateTool as xn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as $e}from"./handlers/fedbrain.js";import{extractFirstRecallProof as _n,extractTopHit as $n,fuersTerminal as ht,renderFirstRecallProof as kn}from"./first-recall-proof.js";import{aussetzerLeise as Sn}from"./aussetzer.js";import{gitHookOrdner as An,installClsPostCommitHook as yt,CLS_HOOK_VERSION as bt}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Cn,CLAUDE_MD_MARKER_END as Tn,EDITOR_FILES as ke,ANWEISUNGS_DATEIEN as In,buildClaudeMdBlock as vt,setzeAnweisungsblock as En,sollSchreiben as Rn,globaleMcpDatei as Se,globalerEditorDa as wt,diesesHeim as ge,mcpZiel as xt}from"./projektdateien.js";import{klassiereArgument as jn,leseFlag as _t,flagsOhneWert as Bn,pruefeInitEingaben as Nn}from"./cli-argumente.js";import{uninstallBefehl as Pn}from"./uninstall.js";import{gitLesen as $t}from"./git-ohne-shell.js";import{browserAdresse as Ln,fuerCmd as On}from"./browser-adresse.js";import{installAmbientHooks as kt,installCursorHooks as Hn,installCopilotHooks as Mn,installCodexHooks as zn,installGeminiHooks as Dn,AMBIENT_HOOK_VERSION as St,COPILOT_HOOKS_DATEI as Un,CODEX_HOOKS_DATEI as Wn,GEMINI_SETTINGS_DATEI as Jn}from"./ambient-hooks.js";import{hookHauptlauf as Fn,auffrischenHauptlauf as Yn,startwissenImportHauptlauf as Kn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as Gn}from"./startwissen-hook.js";import{rahmeAntwort as qn}from"./antwort-rahmen.js";import{appendLedgerEntry as Vn,readLedger as At,defaultLedgerPath as Zn,reportLedgerEntry as Qn,teileNachInstanz as Xn}from"./ambient-ledger.js";import{installCodexMcp as es,installGeminiMcp as ts}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ae,readSavedApiKey as Ce,readInstanceId as Te}from"./credentials.js";import{ladeLaufendeAnmeldung as os,merkeAnmeldung as ns,vergissAnmeldung as Ct}from"./laufende-anmeldung.js";import{KEYCLOAK_BASIS as Tt,istTestSchluessel as ss,waehleTestSchluessel as is,starteKeycloakAnmeldung as rs,warteAufKeycloakAnmeldung as as,uebernimm as cs,brainImKonto as ls,erfolgsText as ds,fehlerText as us,ersetzeSchluessel as ps}from"./uebernahme.js";import{WARTE_TAKT_MS as ms,auftragLiegt as It,nimmAuftrag as fs,sichereKonto as gs,sperreLiegt as hs,startwissenEingeschaltet as Et}from"./konto-anlegen.js";import{sichereZugang as ys,echterWert as Ie}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as bs,SITZUNGS_WERKZEUGE as vs}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as ws,gemeinsamerAufbau as xs}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as _s,setzeCommitQuelle as $s}from"./leeres-brain.js";import{starteStartwissen as ks,startwissenGestartet as Ss,beanspruchStartwissen as As,holeStartwissenHinweis as Cs,waehleProjektOrdner as Ts,startvorratErlaubt as Is,projektCommits as Es}from"./startwissen.js";import{eigeneFassung as Rs,pruefeNeueFassung as js,holeNeueFassungHinweis as Bs}from"./neue-fassung.js";import{beiStdinEnde as Ns}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Ps,starteBrandWachhund as Ls}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Os,VERTEILER as Rt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Hs}from"./pflichtfelder.js";import{buildLessonsMarkdown as Ms,buildLessonsJsonl as zs,vonRohLektion as Ds}from"./brain-export.js";import{detectEditor as Us}from"./editor.js";import{milestoneSent as jt,markMilestoneSent as Bt}from"./funnel-milestones.js";import{meldeKopf as Ws,meldeRumpf as Js}from"./melde-weg.js";import{kostprobeUebrig as Fs,kostprobeVerbrauchen as Ys,kostprobeHinweis as Ks,kostprobePfadJeInstanz as Gs,schrankeNachKostproben as qs}from"./kostprobe.js";import{netBalance as Vs}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as Zs}from"./handlers/viz.js";import{commitArt as Qs,istRueckbau as Xs,zaehleLektionen as ei}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Nt}from"./brains-tls.js";let Pt=!1,Lt=!1,Ee=!1;function Ot(){return Us()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:Ws(S),body:JSON.stringify(Js({event:e,version:H,editor:Ot()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function ti(e,t){return Qn({apiUrl:w,jwt:S,instanceId:e},t)}async function oi(e){if(!(Pt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){Pt=!0;try{await fetch(`${w}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Ot(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const ni=new Set(["causal_trace","brain_predict","brain_plan","brain_predict_failures","team_learn","team_confirm","team_recall","team_synthesize","team_crystallize","global_learn","global_recall"]),si={causal_trace:"Causal root-cause tracing \u2014 follow the failure chain to the real cause, not just the symptom.",brain_predict:"Predictive risk \u2014 your Brain warns you what will break *before* you run it.",brain_plan:"Generative planning \u2014 turn a goal into an ordered, risk-aware plan from your own history.",brain_predict_failures:"Failure prediction \u2014 catch CI/build breakage before it happens.",team_learn:"Team Brain \u2014 one shared memory across your whole team.",team_confirm:"Team Brain \u2014 peer + senior review that raises lesson trust.",team_recall:"Team Brain \u2014 recall everything your teammates have already solved.",team_synthesize:"Team Brain \u2014 synthesize collective knowledge across authors.",team_crystallize:"Team Brain \u2014 compress your team's wisdom into a shareable crystal.",global_learn:"Team Brain \u2014 contribute to your organization's shared memory.",global_recall:"Team Brain \u2014 recall across your entire organization."},Ht=j("/billing","upgrade"),Mt=new Map;async function ii(e){const t=Mt.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await L(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Mt.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function ri(e,t){if(!ni.has(e)||!t)return null;const{isFree:n}=await ii(t);if(!n)return null;const o=si[e]??"A Premium intelligence feature.",s=W()?Gs(t):void 0;if(Fs(e,s)){const i=Ys(e,s);return{kostprobe:Ks(e,i,Ht)}}return{sperre:qs(e,o,Ht)}}async function ai(e,t){try{await(await O(e)).hincrby(lo(e),t,1)}catch{}}async function ci(e,t,n){if(uo(t))try{const o=await O(e),s=fo(n);await o.incrby(po(e),s?mo(n):0),await o.hincrby(Qe(e),"abrufe",1),s&&await o.hincrby(Qe(e),"treffer",1)}catch{}}async function li(e){const t=await Io();return t?(K=t,ns({deviceCode:t.deviceCode,userCode:t.userCode,verifyUrl:t.verifyUrl,pollInterval:t.pollInterval,deadline:t.deadline,apiUrl:w}),A("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
26
26
  cachly: could not open a browser (${o??"unknown"}).
27
27
  cachly: open this yourself to finish signing in:
28
28
  cachly: ${t.verifyUrl}
@@ -31,49 +31,49 @@ cachly: code ${t.userCode}
31
31
  `)}),mt(t),["\u{1F9E0} **cachly AI Brain \u2014 the user must sign in once.**","","**Show the following link and code to the user verbatim \u2014 they cannot","continue without them.**","",`\u{1F449} **${t.verifyUrl}**`,"",`Code: **${t.userCode}**`,"","A browser may have opened automatically with the code pre-filled. If it","did not, the link above is the whole step.","","Once signed in, the Brain activates on its own \u2014 no further action, no","restart. The next request arrives brain-powered.","",`\u2728 ${le.length} MCP tools \xB7 GDPR \xB7 EU servers \xB7 free tier, no credit card`].join(`
32
32
  `)):["\u{1F9E0} **cachly AI Brain \u2014 Setup required**","","Run the setup wizard once in your terminal:"," ```"," npx @cachly-dev/mcp-server@latest autopilot"," ```","",`Or get your API key at: ${j("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
33
33
  `)}async function di(e){if(!e)return!0;if(Ss(e))return!1;try{return await As(await O(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(W()&&!ve())return Ue;if(!ve()&&await Me(xo))return J(e,t);if(!ve()){if(oi(e),!K){const c=Eo();c&&(K=c,A("device_flow_resumed",{tool:e}),mt(c))}if(K){const c=await pt(K);return c==="done"?J(e,t):c==="expired"?(A("device_flow_failed",{reason:"timeout"}),K=null,"\u231B **Authentication timed out.** Please call any tool again to restart the sign-in flow."):["\u23F3 **Signing you in\u2026**","",`Finish in your browser: **${K.verifyUrl}**`,`Code: **${K.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
- `)}return ys({schluessel:S,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const c=await fs({apiUrl:w,version:H,fristMs:_o}),f=c.art==="angelegt"?c.test:c.art==="vorhanden"&&c.instanzId?{apiKey:c.apiKey,instanzId:c.instanzId}:null;return Y(`sofort-test: ${f?"Brain angelegt":"kein Test"}`),f&&Ye(f.instanzId,re(),He()),f},ablagen:{setzeSchluessel:c=>{S=c},setEmbedJwt:oe,saveApiKey:c=>ne(c),persistApiKeyToConfig:pe,merkeInstanz:c=>{N=c,Q=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>li(e),neuesBrain:Oe})}if(!t.instance_id){const c=await dt();c&&(t={...t,instance_id:c})}const n=await ri(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&ai(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await gn(e,t,O,L);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&ci(t.instance_id,e,String(s??"")),!Ee&&S&&(Ee=!0,jt("first_call_success")||(Bt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""})));const c=t.instance_id??N??"",f={instance_id:c};if(e==="recall_best_solution")A("recall_best_solution",f);else if(e==="learn_from_attempts")A("learn_from_attempts",f);else if(e==="session_start"){A("session_start",f,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.includes("Welcome! Your AI Brain is live.");if(!_s(c)){if(!C&&h.length>100)A("recall_best_solution",f);else if(C&&t.workspace_path&&await di(c))try{const k=await Je("brain_from_git",{instance_id:c,repo_path:t.workspace_path,limit:50},O,L);if(k!==null){A("brain_from_git",{...f,...$e??{}}),A("recall_best_solution",f);let R="";if(($e?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:c},O,L);M&&(A("brain_seed_starter",{...f,auto:!0},{seeded_count:16,auto:!0}),R=`
34
+ `)}return ys({schluessel:S,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const c=await gs({apiUrl:w,version:H,fristMs:_o}),g=c.art==="angelegt"?c.test:c.art==="vorhanden"&&c.instanzId?{apiKey:c.apiKey,instanzId:c.instanzId}:null;return Y(`sofort-test: ${g?"Brain angelegt":"kein Test"}`),g&&Ye(g.instanzId,re(),He()),g},ablagen:{setzeSchluessel:c=>{S=c},setEmbedJwt:oe,saveApiKey:c=>ne(c),persistApiKeyToConfig:pe,merkeInstanz:c=>{N=c,X=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>li(e),neuesBrain:Oe})}if(!t.instance_id){const c=await dt();c&&(t={...t,instance_id:c})}const n=await ri(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&ai(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await fn(e,t,O,L);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&ci(t.instance_id,e,String(s??"")),!Ee&&S&&(Ee=!0,jt("first_call_success")||(Bt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""})));const c=t.instance_id??N??"",g={instance_id:c};if(e==="recall_best_solution")A("recall_best_solution",g);else if(e==="learn_from_attempts")A("learn_from_attempts",g);else if(e==="session_start"){A("session_start",g,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.includes("Welcome! Your AI Brain is live.");if(!_s(c)){if(!C&&h.length>100)A("recall_best_solution",g);else if(C&&t.workspace_path&&await di(c))try{const k=await Je("brain_from_git",{instance_id:c,repo_path:t.workspace_path,limit:50},O,L);if(k!==null){A("brain_from_git",{...g,...$e??{}}),A("recall_best_solution",g);let R="";if(($e?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:c},O,L);M&&(A("brain_seed_starter",{...g,auto:!0},{seeded_count:16,auto:!0}),R=`
35
35
  ---
36
36
  `+String(M))}catch{}const I=String(k),$=$e?.total??0,E=$>0?`
37
37
  \u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(I||R||E)return String(s)+E+`
38
38
  ---
39
- `+I+R}}catch(k){return A("brain_from_git_failed",{...f,reason:k instanceof Error?k.message.slice(0,120):"unknown"}),String(s)+`
39
+ `+I+R}}catch(k){return A("brain_from_git_failed",{...g,reason:k instanceof Error?k.message.slice(0,120):"unknown"}),String(s)+`
40
40
 
41
41
  > \u26A0\uFE0F **Auto-bootstrap from git history failed** \u2014 your Brain is live but starts empty.
42
- > Run \`brain_from_git(instance_id="`+c+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}}else if(e==="session_end")A("session_end",f);else if(e==="smart_recall"){const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if(A("smart_recall",f,{hit:C,topic:String(t.query??"").slice(0,80)}),C&&A("recall_best_solution",f),ae&&typeof s=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ae.split(`
42
+ > Run \`brain_from_git(instance_id="`+c+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}}else if(e==="session_end")A("session_end",g);else if(e==="smart_recall"){const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if(A("smart_recall",g,{hit:C,topic:String(t.query??"").slice(0,80)}),C&&A("recall_best_solution",g),ae&&typeof s=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ae.split(`
43
43
  `)[0]}
44
44
 
45
- ${s}`}return s}const i=await fn(e,t,O,L);if(i!==null)return!Ee&&S&&(Ee=!0,jt("first_call_success")||(Bt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const r=await hn(e,t,O,L);if(r!==null)return r;const a=await yn(e,t,O,L);if(a!==null)return a;const d=c=>o?c+o:c,u=await bn(e,t,O,L);if(u!==null)return d(u);const l=await vn(e,t,O,L);if(l!==null)return l;const p=await wn(e,t,O,L);if(p!==null)return d(p);const b=await xn(e,t,O,L);if(b!==null){if(e==="brain_predict"){const f={instance_id:t.instance_id??N??""};A("brain_predict",f)}return d(b)}const m=await Ke(e,t,O,L);if(m!==null)return m;const v=await Zs(e,t,O,L);if(v!==null)return v;const g=await Je(e,t,O,L);if(g!==null){const f={instance_id:t.instance_id??N??""};if(e==="brain_from_git"){const h=$e;A("brain_from_git",{...f,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",f);return g}switch(e){case"get_api_status":{let c="unknown";try{const k=await fetch(`${w}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();c=`${_.status??"ok"} (db: ${_.db??"?"})`}else c=`HTTP ${k.status}`}catch(k){c=`unreachable: ${k.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${w}`,` \u{1F493} Health: ${c}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
- `);let f="\u274C invalid JWT format";try{const k=S.split(".");if(k.length===3){const _=JSON.parse(Buffer.from(k[1],"base64url").toString("utf-8")),R=_.sub??"(unknown)",I=_.iss??"(unknown)",$=I.includes("keycloak")?"Keycloak":"OIDC",E=_.exp?new Date(_.exp*1e3):null,M=E?E<new Date:!1;f=["\u2705 JWT decoded",` Sub (user ID): ${R}`,` Provider: ${$}`,` Issuer: ${I}`,` Expires: ${E?E.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
- `)}}catch{f="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const _=(await L("/api/v1/instances")).data??[];if(_.length===0)h=`
45
+ ${s}`}return s}const i=await gn(e,t,O,L);if(i!==null)return!Ee&&S&&(Ee=!0,jt("first_call_success")||(Bt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const r=await hn(e,t,O,L);if(r!==null)return r;const a=await yn(e,t,O,L);if(a!==null)return a;const d=c=>o?c+o:c,u=await bn(e,t,O,L);if(u!==null)return d(u);const l=await vn(e,t,O,L);if(l!==null)return l;const p=await wn(e,t,O,L);if(p!==null)return d(p);const b=await xn(e,t,O,L);if(b!==null){if(e==="brain_predict"){const g={instance_id:t.instance_id??N??""};A("brain_predict",g)}return d(b)}const m=await Ke(e,t,O,L);if(m!==null)return m;const v=await Zs(e,t,O,L);if(v!==null)return v;const f=await Je(e,t,O,L);if(f!==null){const g={instance_id:t.instance_id??N??""};if(e==="brain_from_git"){const h=$e;A("brain_from_git",{...g,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",g);return f}switch(e){case"get_api_status":{let c="unknown";try{const k=await fetch(`${w}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();c=`${_.status??"ok"} (db: ${_.db??"?"})`}else c=`HTTP ${k.status}`}catch(k){c=`unreachable: ${k.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${w}`,` \u{1F493} Health: ${c}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
+ `);let g="\u274C invalid JWT format";try{const k=S.split(".");if(k.length===3){const _=JSON.parse(Buffer.from(k[1],"base64url").toString("utf-8")),R=_.sub??"(unknown)",I=_.iss??"(unknown)",$=I.includes("keycloak")?"Keycloak":"OIDC",E=_.exp?new Date(_.exp*1e3):null,M=E?E<new Date:!1;g=["\u2705 JWT decoded",` Sub (user ID): ${R}`,` Provider: ${$}`,` Issuer: ${I}`,` Expires: ${E?E.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
+ `)}}catch{g="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const _=(await L("/api/v1/instances")).data??[];if(_.length===0)h=`
48
48
 
49
49
  \u{1F9E0} **Brain Instances:** none \u2014 create one at ${j("/instances","api-status")}`;else{const R=[`
50
50
 
51
- \u{1F9E0} **Brain Instances:**`];for(const I of _){const $=I.status==="running"?"\u{1F7E2}":I.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",E=I.id===N?" \u2190 active":"";if(R.push(` ${$} **${I.name}** (\`${I.id}\`) \xB7 ${I.status}${E}`),I.status==="running"&&I.host){const M=ge.get(I.id);if(M)try{await M.ping(),R.push(" \u{1F493} Redis: connected")}catch{R.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else R.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else I.status==="provisioning"?R.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):I.status!=="running"&&R.push(` \u274C Not reachable (status: ${I.status})`)}h=R.join(`
51
+ \u{1F9E0} **Brain Instances:**`];for(const I of _){const $=I.status==="running"?"\u{1F7E2}":I.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",E=I.id===N?" \u2190 active":"";if(R.push(` ${$} **${I.name}** (\`${I.id}\`) \xB7 ${I.status}${E}`),I.status==="running"&&I.host){const M=fe.get(I.id);if(M)try{await M.ping(),R.push(" \u{1F493} Redis: connected")}catch{R.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else R.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else I.status==="provisioning"?R.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):I.status!=="running"&&R.push(` \u274C Not reachable (status: ${I.status})`)}h=R.join(`
52
52
  `)}}catch(k){h=`
53
53
 
54
54
  \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await De();const C=Pe(S),x=C.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":C.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${C.expiresInMs?` (${Math.round(C.expiresInMs/36e5)}h left)`:""}`:C.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${C.message.split(`
55
- `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${w}`,` \u{1F493} Health: ${c}`,` ${x}`,"","\u{1F511} **Auth:**",f,h].join(`
55
+ `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${w}`,` \u{1F493} Health: ${c}`,` ${x}`,"","\u{1F511} **Auth:**",g,h].join(`
56
56
  `)}default:throw new zt(`Unknown tool: ${e}`)}}class zt extends Error{}const Dt=`REQUIRED FIRST STEP for every task in this project: before you read or edit any file, call the cachly tool smart_recall with one line describing the task (if it is not loaded yet, load it with your tool search first). It returns fixes, decisions and known traps from earlier sessions in THIS codebase. Do this even for small tasks.
57
57
 
58
58
  This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase.
59
59
 
60
60
  - At the START of every task, before reading files or editing: call smart_recall with one line about the task. If it returns lessons, apply them before researching from scratch.
61
61
  - WHEN debugging an error: call causal_trace with the exact error first \u2014 a known fix may already exist.
62
- - AFTER a fix, deploy, or discovery: call learn_from_attempts so the knowledge persists.
62
+ - REQUIRED LAST STEP after a fix, decision or discovery: call learn_from_attempts once, decisive fact (number, command, cause) first. Skipping it loses the lesson for every later session.
63
63
  - BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
64
64
 
65
65
  You do not need to pass instance_id: the server uses CACHLY_BRAIN_INSTANCE_ID if it is set, and otherwise the Brain saved by \`cachly setup\` in ~/.cachly/credentials.json.
66
- session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,Ut={tools:{},resources:{},prompts:{}},Wt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Os(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Jt(){return{resources:[]}}async function Ft(){return{resourceTemplates:[]}}async function Yt(){return{prompts:[]}}function ui(e){e.setRequestHandler(rt,Wt),e.setRequestHandler(ot,Vt),e.setRequestHandler(it,Jt),e.setRequestHandler(st,Ft),e.setRequestHandler(nt,Yt)}function pi(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Ut,instructions:Dt});return ui(e),Kt(e),e}function Kt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),oo(n?.name,n?.version)}catch{}Lt||(Lt=!0,A("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt({name:"cachly-mcp",version:H},{capabilities:Ut,instructions:Dt});Kt(q),q.setRequestHandler(rt,Wt),q.setRequestHandler(it,Jt),q.setRequestHandler(st,Ft),q.setRequestHandler(nt,Yt);let Re=null,de=!1,se=null,Gt=0;async function mi(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,Re=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,qt(e)}}function gi(e){de=!0,Re=e}function qt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await O(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!Re)){de=!1;try{await J("session_end",{instance_id:Re,summary:`Auto-ended after ${Gt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Vt=async e=>{let{name:t,arguments:n}=e.params;if(t===Rt){const i=n??{},r=typeof i.tool=="string"?i.tool:"";if(!r)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const a=le.find(d=>d.name===r);if(!a)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${Rt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:a.name,description:a.description,inputSchema:a.inputSchema},null,2)}]};t=r,n=i.arguments??{}}if(W()){const i=xe();if(!i)return{content:[{type:"text",text:Ue}],isError:!0};if(!Go(t))return{content:[{type:"text",text:qo(t)}],isError:!0};const r=Vo(n??{},i.instanzId);if("fehler"in r)return{content:[{type:"text",text:r.fehler}],isError:!0};n=r.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=le.find(a=>a.name===t),r=i?Hs(t,i.inputSchema,n??{}):null;if(r)return{content:[{type:"text",text:r}],isError:!0}}const o=Ie(n?.instance_id)||N||Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":bs(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await mi(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&gi(o),!W()&&!vs.has(t)&&Gt++;try{Ps(),Y(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&qt(o),{content:[{type:"text",text:qn(t,i)+Cs()+Bs(t)}]}}catch(i){if(i instanceof zt)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Z)throw i;const r=i.message??String(i);throw Qe("cachly","tool_error",{tool:t,error:r}).catch(()=>{}),new Z(te.InternalError,r)}};q.setRequestHandler(ot,Vt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
66
+ session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,Ut={tools:{},resources:{},prompts:{}},Wt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Os(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Jt(){return{resources:[]}}async function Ft(){return{resourceTemplates:[]}}async function Yt(){return{prompts:[]}}function ui(e){e.setRequestHandler(rt,Wt),e.setRequestHandler(ot,Vt),e.setRequestHandler(it,Jt),e.setRequestHandler(st,Ft),e.setRequestHandler(nt,Yt)}function pi(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Ut,instructions:Dt});return ui(e),Kt(e),e}function Kt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),oo(n?.name,n?.version)}catch{}Lt||(Lt=!0,A("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt({name:"cachly-mcp",version:H},{capabilities:Ut,instructions:Dt});Kt(q),q.setRequestHandler(rt,Wt),q.setRequestHandler(it,Jt),q.setRequestHandler(st,Ft),q.setRequestHandler(nt,Yt);let Re=null,de=!1,se=null,Gt=0;async function mi(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,Re=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,qt(e)}}function fi(e){de=!0,Re=e}function qt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await O(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!Re)){de=!1;try{await J("session_end",{instance_id:Re,summary:`Auto-ended after ${Gt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Vt=async e=>{let{name:t,arguments:n}=e.params;if(t===Rt){const i=n??{},r=typeof i.tool=="string"?i.tool:"";if(!r)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const a=le.find(d=>d.name===r);if(!a)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${Rt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:a.name,description:a.description,inputSchema:a.inputSchema},null,2)}]};t=r,n=i.arguments??{}}if(W()){const i=xe();if(!i)return{content:[{type:"text",text:Ue}],isError:!0};if(!Go(t))return{content:[{type:"text",text:qo(t)}],isError:!0};const r=Vo(n??{},i.instanzId);if("fehler"in r)return{content:[{type:"text",text:r.fehler}],isError:!0};n=r.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=le.find(a=>a.name===t),r=i?Hs(t,i.inputSchema,n??{}):null;if(r)return{content:[{type:"text",text:r}],isError:!0}}const o=Ie(n?.instance_id)||N||Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":bs(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await mi(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&fi(o),!W()&&!vs.has(t)&&Gt++;try{Ps(),Y(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&qt(o),{content:[{type:"text",text:qn(t,i)+Cs()+Bs(t)}]}}catch(i){if(i instanceof zt)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Z)throw i;const r=i.message??String(i);throw Xe("cachly","tool_error",{tool:t,error:r}).catch(()=>{}),new Z(te.InternalError,r)}};q.setRequestHandler(ot,Vt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
67
67
  `)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
68
- `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function fi(e,t){const n=Object.entries(t).map(([o,s])=>`${o}=${s}`);return e==="codex"?{befehl:`codex mcp add cachly ${n.map(o=>`--env ${o}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${n.map(o=>`-e ${o}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const Zt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),w&&w!==Zt&&(o.CACHLY_API_URL=w),o}function hi(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:ee(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)},settings:{}}}},null,2):Xt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2)}function Xt(e){return ke[e]===".vscode/mcp.json"}function he(e,t){ss(e)||ne(e,t)}async function Qt(e,t,n,o,s,i={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return hi(t,n,o);let a={};try{a=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:p}=await import("node:fs/promises");await p(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
- `)}catch{}}if(o==="continue"){const p=a.experimental??{},b=p.modelContextProtocolServers??[];let m;for(const g of b){const c=g.env??{};if(c.CACHLY_JWT){m=c.CACHLY_JWT;break}}m&&he(m,i);const v=b.filter(g=>{const c=g.env??{};return!c.CACHLY_JWT&&!c.CACHLY_BRAIN_INSTANCE_ID});return v.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...p,modelContextProtocolServers:v},JSON.stringify(a,null,2)}if(o==="zed"){const p=a.context_servers??{},m=p.cachly?.command?.env?.CACHLY_JWT;return m&&he(m,i),p.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=p,JSON.stringify(a,null,2)}if(Xt(o)){const p=a.mcpServers??void 0,m=p?.cachly?.env?.CACHLY_JWT;m&&he(m,i),p&&"cachly"in p&&(delete p.cachly,Object.keys(p).length===0&&delete a.mcpServers);const v=a.servers??{},g=v.cachly,c=g?.env?.CACHLY_JWT;return c&&he(c,i),v.cachly=g?.envFile?{type:"stdio",...r,envFile:g.envFile}:{type:"stdio",...r},a.servers=v,JSON.stringify(a,null,2)}const d=a.mcpServers??{},l=d.cachly?.env?.CACHLY_JWT;return l&&he(l,i),d.cachly=r,a.mcpServers=d,JSON.stringify(a,null,2)}async function eo(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:r}=await import("node:os"),a=n??r(),d=In.filter(p=>Rn(p,e,a,s,i,o)).map(p=>({path:i(e,...p.pfad),prefix:p.prefix})),u=vt(t),l={};for(const{path:p,prefix:b}of d)try{l[p]=await En(p,u,b)}catch(m){l[p]=`failed:${m.message}`}return l}function to(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=X(),t=U();(!e||!t)&&(console.log(`
68
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function gi(e,t){const n=Object.entries(t).map(([o,s])=>`${o}=${s}`);return e==="codex"?{befehl:`codex mcp add cachly ${n.map(o=>`--env ${o}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${n.map(o=>`-e ${o}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const Zt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),w&&w!==Zt&&(o.CACHLY_API_URL=w),o}function hi(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:ee(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)},settings:{}}}},null,2):Qt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2)}function Qt(e){return ke[e]===".vscode/mcp.json"}function he(e,t){ss(e)||ne(e,t)}async function Xt(e,t,n,o,s,i={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return hi(t,n,o);let a={};try{a=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:p}=await import("node:fs/promises");await p(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
+ `)}catch{}}if(o==="continue"){const p=a.experimental??{},b=p.modelContextProtocolServers??[];let m;for(const f of b){const c=f.env??{};if(c.CACHLY_JWT){m=c.CACHLY_JWT;break}}m&&he(m,i);const v=b.filter(f=>{const c=f.env??{};return!c.CACHLY_JWT&&!c.CACHLY_BRAIN_INSTANCE_ID});return v.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...p,modelContextProtocolServers:v},JSON.stringify(a,null,2)}if(o==="zed"){const p=a.context_servers??{},m=p.cachly?.command?.env?.CACHLY_JWT;return m&&he(m,i),p.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=p,JSON.stringify(a,null,2)}if(Qt(o)){const p=a.mcpServers??void 0,m=p?.cachly?.env?.CACHLY_JWT;m&&he(m,i),p&&"cachly"in p&&(delete p.cachly,Object.keys(p).length===0&&delete a.mcpServers);const v=a.servers??{},f=v.cachly,c=f?.env?.CACHLY_JWT;return c&&he(c,i),v.cachly=f?.envFile?{type:"stdio",...r,envFile:f.envFile}:{type:"stdio",...r},a.servers=v,JSON.stringify(a,null,2)}const d=a.mcpServers??{},l=d.cachly?.env?.CACHLY_JWT;return l&&he(l,i),d.cachly=r,a.mcpServers=d,JSON.stringify(a,null,2)}async function eo(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:r}=await import("node:os"),a=n??r(),d=In.filter(p=>Rn(p,e,a,s,i,o)).map(p=>({path:i(e,...p.pfad),prefix:p.prefix})),u=vt(t),l={};for(const{path:p,prefix:b}of d)try{l[p]=await En(p,u,b)}catch(m){l[p]=`failed:${m.message}`}return l}function to(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=Q(),t=U();(!e||!t)&&(console.log(`
70
70
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
71
71
  `),process.exit(1)),process.stdout.write(`
72
72
  \u{1F9E0} Fetching your weekly Brain digest...
73
73
 
74
- `);try{const n=await fetch(`${w}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,i=o.total_recall_count??0,r=Math.round(o.iq_boost_pct??0),a=(o.top_lessons??[]).slice(0,5),d=o.team_authors??[],u=i*1200,l=s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",p=new Date,b=new Date(p);b.setDate(p.getDate()-7);const m=f=>f.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} Brain Weekly Digest\x1B[0m \x1B[90m${m(b)} \u2013 ${m(p)}\x1B[0m \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total lessons : \x1B[33m${String(s).padEnd(8)}\x1B[0m Brain level : \x1B[32m${l.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(r).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(u/1e3)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),d.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${d.slice(0,5).join(", ").slice(0,42).padEnd(42)} \u2502`)),a.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const f of a){const h=`${f.topic}: ${f.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${h.padEnd(58)}\x1B[0m\u2502`)}}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const v=a[0],g=[`\u{1F9E0} My AI Brain weekly digest (${m(b)} \u2013 ${m(p)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${i} recalls \xB7 ~${Math.round(u/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${l}`,v?` \u{1F525} Top lesson: "${v.topic}: ${v.what_worked.slice(0,60)}${v.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
75
- `),c="https://twitter.com/intent/tweet?text="+encodeURIComponent(g);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const f of g.split(`
76
- `))console.log(` ${f}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${c.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
74
+ `);try{const n=await fetch(`${w}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,i=o.total_recall_count??0,r=Math.round(o.iq_boost_pct??0),a=(o.top_lessons??[]).slice(0,5),d=o.team_authors??[],u=i*1200,l=s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",p=new Date,b=new Date(p);b.setDate(p.getDate()-7);const m=g=>g.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} Brain Weekly Digest\x1B[0m \x1B[90m${m(b)} \u2013 ${m(p)}\x1B[0m \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total lessons : \x1B[33m${String(s).padEnd(8)}\x1B[0m Brain level : \x1B[32m${l.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(r).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(u/1e3)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),d.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${d.slice(0,5).join(", ").slice(0,42).padEnd(42)} \u2502`)),a.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const g of a){const h=`${g.topic}: ${g.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${h.padEnd(58)}\x1B[0m\u2502`)}}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const v=a[0],f=[`\u{1F9E0} My AI Brain weekly digest (${m(b)} \u2013 ${m(p)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${i} recalls \xB7 ~${Math.round(u/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${l}`,v?` \u{1F525} Top lesson: "${v.topic}: ${v.what_worked.slice(0,60)}${v.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
75
+ `),c="https://twitter.com/intent/tweet?text="+encodeURIComponent(f);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const g of f.split(`
76
+ `))console.log(` ${g}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${c.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
77
77
  \u274C Could not fetch digest: ${n.message}
78
78
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),o=process.argv.slice(3),s=u=>{const l=o.indexOf(`--${u}`);return l!==-1?o[l+1]:void 0},i=s("format")??"both";i!=="md"&&i!=="jsonl"&&i!=="both"&&(console.log(`
79
79
  \u274C Unknown --format "${i}" \u2014 use md, jsonl, or both.
@@ -82,10 +82,10 @@ session_start gives a briefing at the start of a session; it does not replace sm
82
82
  `),process.exit(1)),process.stdout.write(`
83
83
  \u{1F4E4} Exporting your Brain...
84
84
 
85
- `);try{let u=[],l="";const p=await fetch(`${w}/api/v1/instances/${d}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(p.ok){const m=await p.json();u=(m.lessons??[]).map(Ds).filter(v=>v!==null),m.complete===!1?l=m.note??"the server reported an incomplete read":typeof m.lesson_count=="number"&&u.length<m.lesson_count&&(l=`the server counts ${m.lesson_count} lessons, but only ${u.length} could be read as lessons`)}else if(p.status===404){const m=await fetch(`${w}/api/v1/instances/${d}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!m.ok)throw new Error(`memory HTTP ${m.status}`);u=((await m.json()).top_lessons??[]).map(g=>({topic:g.topic,outcome:g.outcome,severity:g.severity,tags:g.tags,whatWorked:g.what_worked,ts:g.ts,author:g.author,recallCount:g.recall_count})),l="this server has no /export endpoint yet, so this is the DASHBOARD SUMMARY: at most 50 lessons, each shortened to 120 characters. Update the server for a full export."}else throw new Error(`export HTTP ${p.status}`);u.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
85
+ `);try{let u=[],l="";const p=await fetch(`${w}/api/v1/instances/${d}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(p.ok){const m=await p.json();u=(m.lessons??[]).map(Ds).filter(v=>v!==null),m.complete===!1?l=m.note??"the server reported an incomplete read":typeof m.lesson_count=="number"&&u.length<m.lesson_count&&(l=`the server counts ${m.lesson_count} lessons, but only ${u.length} could be read as lessons`)}else if(p.status===404){const m=await fetch(`${w}/api/v1/instances/${d}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!m.ok)throw new Error(`memory HTTP ${m.status}`);u=((await m.json()).top_lessons??[]).map(f=>({topic:f.topic,outcome:f.outcome,severity:f.severity,tags:f.tags,whatWorked:f.what_worked,ts:f.ts,author:f.author,recallCount:f.recall_count})),l="this server has no /export endpoint yet, so this is the DASHBOARD SUMMARY: at most 50 lessons, each shortened to 120 characters. Update the server for a full export."}else throw new Error(`export HTTP ${p.status}`);u.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
86
  `),process.exit(0)),await t(r,{recursive:!0});const b=[];if(i==="md"||i==="both"){const m=n(r,"lessons.md");await e(m,Ms(u),"utf-8"),b.push(`${u.length} lesson${u.length===1?"":"s"} \u2192 ${m}`)}if(i==="jsonl"||i==="both"){const m=n(r,"lessons.jsonl");await e(m,zs(u),"utf-8"),b.push(`${u.length} lesson${u.length===1?"":"s"} \u2192 ${m}`)}l?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${l}`),console.log("")):console.log("\u2705 Export complete:");for(const m of b)console.log(` ${m}`);console.log("")}catch(u){console.log(`
87
87
  \u274C Could not export your Brain: ${u.message}
88
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=X(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
88
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=Q(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
89
89
  Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Example: npx @cachly-dev/mcp-server@latest invite teammate@example.com"),console.log(` Your referral link: npx @cachly-dev/mcp-server@latest refer
90
90
  `),process.exit(1)),e||(console.log(`
91
91
  \u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
@@ -99,7 +99,7 @@ Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Ex
99
99
  \u2139\uFE0F ${t} already has access to this Brain. Nothing was sent.
100
100
  `),process.exit(1)),!o.ok)throw new Error(`HTTP ${o.status}`);const s=await o.json(),i=s.invite_sent_to??t,r=s.instance?.name??n;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${i}\x1B[0m`),console.log(` Brain: \x1B[1m${r}\x1B[0m`),console.log(""),console.log(" They get an email. They accept it in one of two ways:"),console.log(" \u2022 open the link in the email, or"),console.log(" \u2022 run the command from the email: npx @cachly-dev/mcp-server@latest join <token>"),console.log(""),console.log(" Members can read and learn. Deleting the Brain, rotating its password and billing stay with you."),console.log("")}catch(o){console.log(`
101
101
  \u274C Could not send the invitation: ${o.message}
102
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=X();e||(console.log(`
102
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=Q();e||(console.log(`
103
103
  \u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
104
104
  `),process.exit(1));try{const t=await fetch(`${w}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json(),o=n.url??j(`/r/${n.code}`,"refer"),s=n.referral_count??0,i=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
105
105
 
@@ -146,7 +146,7 @@ Try it free: ${o}
146
146
  Cancelled.
147
147
  `),process.exit(1)),k=x[I-1]}b=k.id,m=k.name??k.id,console.log(`
148
148
  \u2705 Invitation accepted. Brain: \x1B[1m${m}\x1B[0m
149
- `)}l!==S&&ne(l);const v=process.cwd(),g=r(),c=[{label:".mcp.json (Claude Code project)",path:s(v,".mcp.json")},{label:".cursor/mcp.json",path:s(v,".cursor","mcp.json")},{label:"~/.codeium/windsurf/mcp_config.json (Windsurf)",path:Se("windsurf",fe())},{label:"cline_mcp_settings.json (Cline)",path:Se("cline",fe())},{label:".vscode/mcp.json (Copilot)",path:s(v,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(g,".claude","mcp.json"),global:!0}];let f=0;for(const{label:h,path:C,global:x}of c){const k=i(C);if(!(!x&&!o(k)&&!o(C)))try{await n(k,{recursive:!0});let _={};if(o(C))try{_=JSON.parse(await t(C,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(C,C+".bak")}catch{}}const R=_.mcpServers??{},I=R.cachly??{},$=I.env??{};$.CACHLY_BRAIN_INSTANCE_ID=b,l&&x&&!$.CACHLY_JWT&&($.CACHLY_JWT=l),w!==Zt&&($.CACHLY_API_URL=w),R.cachly={...I,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},_.mcpServers=R,await e(C,JSON.stringify(_,null,2),"utf-8"),console.log(` \u2705 ${h}`),f++}catch(_){_.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${h}: ${_.message}`)}}console.log(""),f===0?console.log(" \u26A0\uFE0F No editor configs found \u2014 run `cachly setup` first.\n"):(console.log(` \u{1F9E0} You're now sharing Brain: \x1B[1m${m}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
149
+ `)}l!==S&&ne(l);const v=process.cwd(),f=r(),c=[{label:".mcp.json (Claude Code project)",path:s(v,".mcp.json")},{label:".cursor/mcp.json",path:s(v,".cursor","mcp.json")},{label:"~/.codeium/windsurf/mcp_config.json (Windsurf)",path:Se("windsurf",ge())},{label:"cline_mcp_settings.json (Cline)",path:Se("cline",ge())},{label:".vscode/mcp.json (Copilot)",path:s(v,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(f,".claude","mcp.json"),global:!0}];let g=0;for(const{label:h,path:C,global:x}of c){const k=i(C);if(!(!x&&!o(k)&&!o(C)))try{await n(k,{recursive:!0});let _={};if(o(C))try{_=JSON.parse(await t(C,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(C,C+".bak")}catch{}}const R=_.mcpServers??{},I=R.cachly??{},$=I.env??{};$.CACHLY_BRAIN_INSTANCE_ID=b,l&&x&&!$.CACHLY_JWT&&($.CACHLY_JWT=l),w!==Zt&&($.CACHLY_API_URL=w),R.cachly={...I,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},_.mcpServers=R,await e(C,JSON.stringify(_,null,2),"utf-8"),console.log(` \u2705 ${h}`),g++}catch(_){_.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${h}: ${_.message}`)}}console.log(""),g===0?console.log(" \u26A0\uFE0F No editor configs found \u2014 run `cachly setup` first.\n"):(console.log(` \u{1F9E0} You're now sharing Brain: \x1B[1m${m}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
150
150
  `),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
151
151
  `)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
152
152
  \u23F3 Checking for updates...
@@ -154,7 +154,7 @@ Try it free: ${o}
154
154
  \u2705 Already on the latest version: \x1B[32mv${H}\x1B[0m
155
155
  `):(console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly update available\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Current : \x1B[31mv${H}\x1B[0m`),console.log(` Latest : \x1B[32mv${n}\x1B[0m`),console.log(""),console.log(" Update your editor configs to pick up the new version:"),console.log(""),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(" \x1B[2m(npx always fetches the latest when @latest is specified)\x1B[0m"),console.log(""))}catch(e){console.log(`
156
156
  \u274C Could not check for updates: ${e.message}
157
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:n}=await import("node:path"),{loadExternalCorpus:o,runExternalBenchmark:s}=await import("./bench/external-corpus.js"),i=process.argv.includes("--json"),r=process.argv.slice(3).find(u=>!u.startsWith("--")),a=t(e(import.meta.url)),d=r?n(process.cwd(),r):n(a,"bench","external","sample-corpus.json");try{const u=await o(d),l=await s(u);i&&(console.log(JSON.stringify({corpus:u.name,lessons:l.corpusSize,queries:l.queryCount,cachly_p1:Math.round(l.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(l.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(l.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(l.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((l.cachly.precisionAt1-l.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((l.cachly.mrr-l.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const p=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),b=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),m=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),v=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",g=l.cachly.mrr>=l.flatfile.mrr?"\x1B[32m+":"\x1B[31m";console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly recall quality benchmark\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Corpus : ${u.name??d}`),console.log(` Dataset: ${l.corpusSize} lessons \xB7 ${l.queryCount} queries \xB7 10 engineering domains`),console.log(" (k8s, DB, auth, CI, frontend, API, payments, observability, Node.js, infra)"),console.log(""),console.log(" \x1B[1mPrecision@1\x1B[0m (finds the right lesson at rank #1):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(l.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.precisionAt1*100).toFixed(1)}%\x1B[0m (BM25 + quality reranking)`),console.log(""),console.log(" \x1B[1mMean Reciprocal Rank\x1B[0m (average rank of the right answer):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(l.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.mrr*100).toFixed(1)}%\x1B[0m`),console.log(""),console.log(" \x1B[1mLift vs flat-file memory\x1B[0m (what you get by switching from plain memory files):"),console.log(` Precision@1 : ${v}${p}%\x1B[0m`),console.log(` MRR : ${g}${b}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${m}%\x1B[0m Precision@1 (quality reranking on top of keyword search)`),console.log(""),console.log(" \x1B[2mFlat-file = lexical overlap over raw text files (how Anthropic/Claude Memory works).\x1B[0m"),console.log(" \x1B[2mAdversarial distractors included \u2014 failure lessons that share the exact query vocabulary.\x1B[0m"),console.log(" \x1B[2mcachly ignores them because they have low confidence / failed outcome.\x1B[0m"),console.log(""),console.log(" Share your results:"),console.log(` \x1B[36m"My Brain: Precision@1 ${(l.cachly.precisionAt1*100).toFixed(1)}% (${v}${p}% vs flat-file memory, ${l.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${j("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(u){console.error(`
157
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:n}=await import("node:path"),{loadExternalCorpus:o,runExternalBenchmark:s}=await import("./bench/external-corpus.js"),i=process.argv.includes("--json"),r=process.argv.slice(3).find(u=>!u.startsWith("--")),a=t(e(import.meta.url)),d=r?n(process.cwd(),r):n(a,"bench","external","sample-corpus.json");try{const u=await o(d),l=await s(u);i&&(console.log(JSON.stringify({corpus:u.name,lessons:l.corpusSize,queries:l.queryCount,cachly_p1:Math.round(l.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(l.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(l.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(l.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((l.cachly.precisionAt1-l.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((l.cachly.mrr-l.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const p=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),b=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),m=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),v=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",f=l.cachly.mrr>=l.flatfile.mrr?"\x1B[32m+":"\x1B[31m";console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly recall quality benchmark\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Corpus : ${u.name??d}`),console.log(` Dataset: ${l.corpusSize} lessons \xB7 ${l.queryCount} queries \xB7 10 engineering domains`),console.log(" (k8s, DB, auth, CI, frontend, API, payments, observability, Node.js, infra)"),console.log(""),console.log(" \x1B[1mPrecision@1\x1B[0m (finds the right lesson at rank #1):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(l.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.precisionAt1*100).toFixed(1)}%\x1B[0m (BM25 + quality reranking)`),console.log(""),console.log(" \x1B[1mMean Reciprocal Rank\x1B[0m (average rank of the right answer):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(l.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.mrr*100).toFixed(1)}%\x1B[0m`),console.log(""),console.log(" \x1B[1mLift vs flat-file memory\x1B[0m (what you get by switching from plain memory files):"),console.log(` Precision@1 : ${v}${p}%\x1B[0m`),console.log(` MRR : ${f}${b}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${m}%\x1B[0m Precision@1 (quality reranking on top of keyword search)`),console.log(""),console.log(" \x1B[2mFlat-file = lexical overlap over raw text files (how Anthropic/Claude Memory works).\x1B[0m"),console.log(" \x1B[2mAdversarial distractors included \u2014 failure lessons that share the exact query vocabulary.\x1B[0m"),console.log(" \x1B[2mcachly ignores them because they have low confidence / failed outcome.\x1B[0m"),console.log(""),console.log(" Share your results:"),console.log(` \x1B[36m"My Brain: Precision@1 ${(l.cachly.precisionAt1*100).toFixed(1)}% (${v}${p}% vs flat-file memory, ${l.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${j("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(u){console.error(`
158
158
  \u274C bench failed: ${u.message}
159
159
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:n,basename:o}=await import("node:path"),s=process.cwd();console.log(`
160
160
  \x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
@@ -163,7 +163,7 @@ Try it free: ${o}
163
163
  `),process.exit(0));let i="";try{i=$t(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let r=o(s);try{const $=JSON.parse(t(n(s,"package.json"),"utf-8"));$.name&&(r=$.name.replace(/^@[^/]+\//,""))}catch{}let a="";try{a=$t(s,["log","HEAD","--pretty=format:%H|||%s|||%ad|||%an","--date=short","--no-merges","-n","200"],{timeoutMs:3e4})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
164
164
  `),process.exit(0)}const d=a.trim().split(`
165
165
  `).filter(Boolean).map($=>{const[E,M,Ne,ie]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(M??"").trim(),date:(Ne??"").trim(),author:(ie??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
- `),process.exit(0));const u=new Map,l=[],p=[],b=[],m=new Set;let v=0;for(const $ of d){const E=Xs($.subject);u.set(E,(u.get(E)??0)+1),Qs($.subject)&&v++,E==="fix"&&l.length<5&&l.push($.subject.slice(0,72)),E==="feat"&&p.length<5&&p.push($.subject.slice(0,72)),E==="security"&&b.length<3&&b.push($.subject.slice(0,72)),$.author&&m.add($.author)}const g=ei(d.map($=>$.subject)),c=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,f=g>=501?"Oracle":g>=201?"Architect":g>=51?"Expert":g>=11?"Explorer":"Apprentice",C=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${r}`;process.stdout.write("\x1B[2K\r"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} ${C.slice(0,58).padEnd(58)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Commits analysed : \x1B[33m${String(d.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${c.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(g).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(m.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${f.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(v).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const x=[...u.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...x.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of x){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(b.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of b)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(l.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of l.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(p.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of p.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u{1F4A1} With cachly, your AI arrives pre-briefed every session.\x1B[0m \u2502"),console.log("\u2502 \x1B[32m No more re-explaining. No more repeated mistakes.\x1B[0m \u2502"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const R=new URLSearchParams({repo:r,commits:String(d.length),lessons:String(g),level:f,authors:String(m.size),reverts:String(v)}),I=j(`/preview?${R.toString()}`,"demo");console.log(" \x1B[1mMake this permanent (free, 1\u20135 minutes):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(` \x1B[90m\u{1F517} Shareable preview:\x1B[0m \x1B[36m${I}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" GDPR \xB7 German servers \xB7 free tier, no credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=X(),t=U();(!e||!t)&&(console.log(`
166
+ `),process.exit(0));const u=new Map,l=[],p=[],b=[],m=new Set;let v=0;for(const $ of d){const E=Qs($.subject);u.set(E,(u.get(E)??0)+1),Xs($.subject)&&v++,E==="fix"&&l.length<5&&l.push($.subject.slice(0,72)),E==="feat"&&p.length<5&&p.push($.subject.slice(0,72)),E==="security"&&b.length<3&&b.push($.subject.slice(0,72)),$.author&&m.add($.author)}const f=ei(d.map($=>$.subject)),c=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,g=f>=501?"Oracle":f>=201?"Architect":f>=51?"Expert":f>=11?"Explorer":"Apprentice",C=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${r}`;process.stdout.write("\x1B[2K\r"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} ${C.slice(0,58).padEnd(58)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Commits analysed : \x1B[33m${String(d.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${c.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(f).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(m.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${g.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(v).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const x=[...u.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...x.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of x){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(b.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of b)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(l.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of l.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(p.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of p.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u{1F4A1} With cachly, your AI arrives pre-briefed every session.\x1B[0m \u2502"),console.log("\u2502 \x1B[32m No more re-explaining. No more repeated mistakes.\x1B[0m \u2502"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const R=new URLSearchParams({repo:r,commits:String(d.length),lessons:String(f),level:g,authors:String(m.size),reverts:String(v)}),I=j(`/preview?${R.toString()}`,"demo");console.log(" \x1B[1mMake this permanent (free, 1\u20135 minutes):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(` \x1B[90m\u{1F517} Shareable preview:\x1B[0m \x1B[36m${I}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" GDPR \xB7 German servers \xB7 free tier, no credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=Q(),t=U();(!e||!t)&&(console.log(`
167
167
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
168
168
  `),process.exit(1)),process.stdout.write(`
169
169
  \u{1F9E0} Fetching your Brain stats...
@@ -179,7 +179,7 @@ ${u}
179
179
  `).map(p=>` ${p}`).join(`
180
180
  `)),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(""),console.log(" \x1B[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1B[0m"),console.log(" \x1B[2mAlso add a live badge to your README:\x1B[0m"),console.log(" \x1B[90m npx @cachly-dev/mcp-server@latest badge\x1B[0m"),console.log("")}catch(n){console.log(`
181
181
  \u274C Could not fetch stats: ${n.message}
182
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=X(),t=U();(!e||!t)&&(console.log(`
182
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=Q(),t=U();(!e||!t)&&(console.log(`
183
183
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
184
184
  `),process.exit(1));const n=process.argv.indexOf("--title"),o=n!==-1?process.argv[n+1]??"My Brain Snapshot":"My Brain Snapshot",s=process.argv.includes("--public");process.stdout.write(`
185
185
  \u{1F9E0} Publishing Brain snapshot...
@@ -193,44 +193,44 @@ ${u}
193
193
  \u26A0\uFE0F No Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
194
194
  `),process.exit(1));const t=`${w}/api/v1/badge/${e}`,n=j("/","badge"),o=`[![cachly Brain](${t})](${n})`,s=`<a href="${n}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${o}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${s}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const ye=jn(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
195
195
  `,()=>process.exit(0)),await new Promise(()=>{})),ye==="unbekannt"&&console.error(`
196
- Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,n)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${n}`);console.log(" \x1B[1mStart:\x1B[0m \x1B[1m\x1B[32mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" Every command below runs as: npx @cachly-dev/mcp-server@latest <command>"),console.log(""),console.log(" \x1B[1mEvery day:\x1B[0m"),e("status","Lessons, recalls and team at a glance"),e("ambient-stats","Tokens injected vs saved \u2014 the honest net, even when negative"),e("doctor","Diagnose a broken or missing install"),e("health","Check key, API, editor configs and git hook"),e("digest","What your Brain learned this week"),console.log(" \x1B[1mSet up:\x1B[0m"),e("demo","Try it first (no account)"),e("setup","Interactive setup (pick editors)"),e("init","Write the config for one editor (flags)"),e("claim","Keep a test Brain in your own account"),e("upgrade","Check for updates"),e("uninstall","Take cachly out of this project (--dry-run first)"),console.log(" \x1B[1mYour data:\x1B[0m"),e("export","Write your lessons to disk (md / jsonl)"),e("index [dir]","Index a project into the Brain (CI)"),e("learn-git [repo]","Learn lessons from recent commits (CI)"),console.log(" \x1B[1mTeam & sharing:\x1B[0m"),e("invite <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const yi={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Un,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:Wn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:Jn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function bi(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=yi[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${n}${o} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${s} hooks not wired`);return}const r=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",a=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${r}${n}${a}: ${o} (Ambient Recall for ${s} \u2014 ${i})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?es:ts)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const d=fi(e,n);console.log(`\u26A0\uFE0F ${o}${i?`${i.datei} ${i.grund??"could not be read"} \u2014 left untouched.`:`${s} MCP entry could not be written.`} Register cachly yourself:`),d&&console.log(` ${o}${d.befehl}`);return}const r=i.status==="unchanged"?"\u2713 ":"\u2705 ",a=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${r}${o}${a}: ${i.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Hn,copilot:Mn,codex:zn,gemini:Dn}[e];bi(e,await s(t,n).catch(()=>null),o)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:o}=await import("node:fs/promises"),{resolve:s,dirname:i,relative:r}=await import("node:path"),a=process.argv.slice(3),d=x=>_t(a,x),u=Bn(a,["instance-id","api-key","editor","project-dir","api-url"]);u.length>0&&(console.error(`
196
+ Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,n)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${n}`);console.log(" \x1B[1mStart:\x1B[0m \x1B[1m\x1B[32mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" Every command below runs as: npx @cachly-dev/mcp-server@latest <command>"),console.log(""),console.log(" \x1B[1mEvery day:\x1B[0m"),e("status","Lessons, recalls and team at a glance"),e("ambient-stats","Tokens injected vs saved \u2014 the honest net, even when negative"),e("doctor","Diagnose a broken or missing install"),e("health","Check key, API, editor configs and git hook"),e("digest","What your Brain learned this week"),console.log(" \x1B[1mSet up:\x1B[0m"),e("demo","Try it first (no account)"),e("setup","Interactive setup (pick editors)"),e("init","Write the config for one editor (flags)"),e("claim","Keep a test Brain in your own account"),e("upgrade","Check for updates"),e("uninstall","Take cachly out of this project (--dry-run first)"),console.log(" \x1B[1mYour data:\x1B[0m"),e("export","Write your lessons to disk (md / jsonl)"),e("index [dir]","Index a project into the Brain (CI)"),e("learn-git [repo]","Learn lessons from recent commits (CI)"),console.log(" \x1B[1mTeam & sharing:\x1B[0m"),e("invite <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const yi={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Un,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:Wn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:Jn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function bi(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=yi[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${n}${o} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${s} hooks not wired`);return}const r=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",a=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${r}${n}${a}: ${o} (Ambient Recall for ${s} \u2014 ${i})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?es:ts)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const d=gi(e,n);console.log(`\u26A0\uFE0F ${o}${i?`${i.datei} ${i.grund??"could not be read"} \u2014 left untouched.`:`${s} MCP entry could not be written.`} Register cachly yourself:`),d&&console.log(` ${o}${d.befehl}`);return}const r=i.status==="unchanged"?"\u2713 ":"\u2705 ",a=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${r}${o}${a}: ${i.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Hn,copilot:Mn,codex:zn,gemini:Dn}[e];bi(e,await s(t,n).catch(()=>null),o)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:o}=await import("node:fs/promises"),{resolve:s,dirname:i,relative:r}=await import("node:path"),a=process.argv.slice(3),d=x=>_t(a,x),u=Bn(a,["instance-id","api-key","editor","project-dir","api-url"]);u.length>0&&(console.error(`
197
197
  Missing value for ${u.map(x=>`--${x}`).join(", ")}. Nothing was written.
198
198
  `),process.exit(1));let l=d("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,p=d("api-key")??process.env.CACHLY_JWT;const b=(d("editor")??"claude").toLowerCase(),m=s(d("project-dir")??"."),v=d("api-url");if(v&&(w=v.replace(/\/+$/,"")),!l||!p){const x=Ce(),k=Te();x&&k&&(p??=x,l??=k,p===x&&l===k&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!l||!p)try{const{existsSync:x}=await import("node:fs"),k=process.env.HOME??process.env.USERPROFILE??"",_=k?s(k,".claude","mcp.json"):"";if(_&&x(_)){const I=JSON.parse(await o(_,"utf-8")).mcpServers?.cachly?.env??{};p??=I.CACHLY_JWT,l??=I.CACHLY_BRAIN_INSTANCE_ID,p&&l&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!l||!p)&&(console.error(`
199
199
  Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue|cline|zed|codex|gemini] [--all-editors] [--project-dir /path] [--api-url https://your-self-hosted-backend]
200
200
  `),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
201
201
  `),console.error(`Get your credentials from: ${j("/setup-ai","init")}
202
- `),process.exit(1));const g=Nn({instanceId:l,apiKey:p,editor:b},[...Object.keys(ke),"codex","gemini"]);if(g.length>0){console.error(`
203
- Nothing was written:`);for(const x of g)console.error(` - ${x}`);console.error(""),process.exit(1)}try{const x=await fetch(`${w}/api/v1/instances/${l}/memory`,{headers:{Authorization:`Bearer ${p}`},signal:AbortSignal.timeout(8e3)});(x.status===401||x.status===403||x.status===404)&&(console.error(`
202
+ `),process.exit(1));const f=Nn({instanceId:l,apiKey:p,editor:b},[...Object.keys(ke),"codex","gemini"]);if(f.length>0){console.error(`
203
+ Nothing was written:`);for(const x of f)console.error(` - ${x}`);console.error(""),process.exit(1)}try{const x=await fetch(`${w}/api/v1/instances/${l}/memory`,{headers:{Authorization:`Bearer ${p}`},signal:AbortSignal.timeout(8e3)});(x.status===401||x.status===403||x.status===404)&&(console.error(`
204
204
  The server does not accept this key and instance (HTTP ${x.status}). Nothing was written.`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
205
- `),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const c=()=>{ne(p),Te()||Ae(l,{apiKey:p})};if(b==="codex"||b==="gemini")c(),console.log(""),await qe(b,m,ee(p,l),"");else{const x=xt(b,m),k=x.anzeige,_=x.pfad;await n(i(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";c();const E=await Qt(_,p,l,x.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
205
+ `),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const c=()=>{ne(p),Te()||Ae(l,{apiKey:p})};if(b==="codex"||b==="gemini")c(),console.log(""),await qe(b,m,ee(p,l),"");else{const x=xt(b,m),k=x.anzeige,_=x.pfad;await n(i(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";c();const E=await Xt(_,p,l,x.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
206
206
  \u2705 ${I?"Updated":"Written"}: ${k}`)):console.log(`
207
- \u2713 Already configured: ${k} (no change)`)}const f=a.includes("--all-editors"),h=await eo(m,l,void 0,f?void 0:b);for(const[x,k]of Object.entries(h))console.log(to(x.split(/[\\/]/).pop()??x,k));try{const x=await yt(m,l),k=r(m,s(An(m),"post-commit")).replace(/\\/g,"/");x==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):x==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${bt})`):x==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):x==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(b==="claude")try{const x=await kt(m,l);if(x.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${x.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=x.scripts==="written"?"\u2705 Written":x.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${St})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),x.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):x.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}(b==="cursor"||b==="copilot"||b==="codex"||b==="gemini")&&await be(b,m,l,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
207
+ \u2713 Already configured: ${k} (no change)`)}const g=a.includes("--all-editors"),h=await eo(m,l,void 0,g?void 0:b);for(const[x,k]of Object.entries(h))console.log(to(x.split(/[\\/]/).pop()??x,k));try{const x=await yt(m,l),k=r(m,s(An(m),"post-commit")).replace(/\\/g,"/");x==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):x==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${bt})`):x==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):x==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(b==="claude")try{const x=await kt(m,l);if(x.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${x.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=x.scripts==="written"?"\u2705 Written":x.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${St})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),x.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):x.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}(b==="cursor"||b==="copilot"||b==="codex"||b==="gemini")&&await be(b,m,l,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
208
208
  \u{1F9E0} Cachly AI Brain configured for ${b==="claude"?"Claude Code":b}! (${C}s)`),console.log(b==="codex"||b==="gemini"?` Start ${b} in this folder and trust it when asked \u2014 the \`cachly\` MCP tools will appear.`:" Restart your editor \u2014 the `cachly` MCP tools will appear."),console.log(" Re-run `init` anytime \u2014 it's idempotent (only writes what changed)."),console.log(`
209
209
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
210
- `),process.exit(0)}if(process.argv[2]==="status"){const e=X(),t=U();(!e||!t)&&(console.log(`
210
+ `),process.exit(0)}if(process.argv[2]==="status"){const e=Q(),t=U();(!e||!t)&&(console.log(`
211
211
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
212
212
  `),process.exit(1));try{const[n,o]=await Promise.all([fetch(`${w}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${w}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),i=o.ok?await o.json():null,r=s.lesson_count??0,a=s.total_recall_count??0,d=Math.round(s.iq_boost_pct??0),u=s.team_authors??[],l=i?.referral_count??0,p=i?.url??"",b=r===0?"Intern \u{1F331}":r<10?"Junior Dev \u{1F527}":r<30?"Mid Dev \u26A1":r<60?"Senior Dev \u{1F9E0}":r<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",m=r>0?"\x1B[32m\u25CF\x1B[0m":"\x1B[33m\u25CF\x1B[0m";if(console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 ${m} \x1B[1mBrain status\x1B[0m \xB7 instance ${t.slice(0,8)}... \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons : \x1B[33m${String(r).padEnd(8)}\x1B[0m Level : \x1B[32m${b.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(d).padEnd(3)}%\x1B[0m \u2502`),u.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const v=u.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(u.length).padEnd(2)} developer${u.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-v.length))} \u2502`),console.log(`\u2502 ${v.slice(0,56).padEnd(56)} \u2502`)}if(p){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const v=`${p.slice(0,44)}${p.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Referral link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${v.padEnd(56)}\x1B[0m \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),r===0&&(console.log(" \x1B[33m\u{1F4A1} No lessons yet.\x1B[0m Run a session with cachly connected to start learning."),console.log(""))}catch(n){console.log(`
213
213
  \u274C Could not fetch status: ${n.message}
214
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),o=process.cwd();let s=0,i=0;const r=g=>{console.log(` \u2705 ${g}`),s++},a=g=>{console.log(` \u26A0\uFE0F ${g}`)},d=g=>{console.log(` \u274C ${g}`),i++};console.log(`
214
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),o=process.cwd();let s=0,i=0;const r=f=>{console.log(` \u2705 ${f}`),s++},a=f=>{console.log(` \u26A0\uFE0F ${f}`)},d=f=>{console.log(` \u274C ${f}`),i++};console.log(`
215
215
  \u{1F9E0} cachly health check
216
- `),console.log("\u{1F511} Auth token");const u=X();if(!u)d("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(u.startsWith("cky_"))r("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const g=u.split(".");if(g.length!==3)throw new Error("not a JWT");const c=JSON.parse(Buffer.from(g[1],"base64url").toString("utf-8")),f=c.exp?c.exp*1e3:null,h=f?Math.floor((f-Date.now())/6e4):null;f&&f<Date.now()?d(`JWT expired ${Math.abs(h)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):h!==null&&h<30?a(`JWT expires in ${h} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):r(`JWT valid${h!==null?` (expires in ${Math.floor(h/60)}h ${h%60}m)`:""}`)}catch{d("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
217
- \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const g=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(g.ok){const c=await g.json();r(`${l} reachable (status: ${c.status??"ok"})`)}else g.status===401||g.status===403?r(`${l} reachable (auth required \u2014 expected)`):d(`${l}/health returned HTTP ${g.status}`)}catch(g){d(`${l} unreachable \u2014 ${g.message}`)}console.log(`
218
- \u{1F9E0} Brain instance`);const p=U();if(!p)a("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(u)try{const g=await fetch(`${l}/api/v1/instances/${p}`,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(g.ok){const c=await g.json();if(c.status==="running")if(r(`Instance "${c.name}" (${p.slice(0,8)}\u2026) is running`),console.log(`
219
- \u{1F50C} Redis connectivity`),c.host&&c.port)try{let f,h;try{const _=await fetch(`${l}/api/v1/instances/${p}/connection`,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(_.ok){const R=await _.json();f=R.password,h=R}}catch{}const C=Nt({host:c.host,port:c.port,tls_enabled:c.tls_enabled},h),x=new at({host:C.host,port:C.port,password:f,...C.tls?{tls:C.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await x.connect();const k=await x.ping();x.disconnect(),k==="PONG"?r(`Redis PING \u2192 PONG (${C.host}:${C.port}, ${C.art==="klartext"?"unencrypted":"TLS"})`):a(`Redis responded but not PONG: ${k}`)}catch(f){d(`Redis unreachable \u2014 ${f.message}`)}else a("Instance has no host/port yet");else a(`Instance "${c.name}" status: ${c.status}`)}else d(`Instance ${p.slice(0,8)}\u2026 not found (HTTP ${g.status})`)}catch(g){d(`Could not check instance \u2014 ${g.message}`)}console.log(`
220
- \u{1F6E0} Editor configs (project dir)`);const b=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:Se("windsurf",fe())},{editor:"Cline",path:Se("cline",fe())},{editor:"Copilot",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"},{editor:"Codex",path:".codex/config.toml"},{editor:"Gemini CLI",path:".gemini/settings.json"}];let m=0;for(const{editor:g,path:c}of b){const f=n(o,c);if(e(f))try{const h=await t(f,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(r(`${g}: ${c}`),m++):a(`${g}: ${c} exists but cachly not found inside`)}catch{a(`${g}: ${c} exists but could not read`)}}m===0&&d("No editor MCP configs found in this folder \u2014 run: npx @cachly-dev/mcp-server@latest init (add --editor cursor|copilot|codex|gemini if needed)"),console.log(`
216
+ `),console.log("\u{1F511} Auth token");const u=Q();if(!u)d("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(u.startsWith("cky_"))r("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const f=u.split(".");if(f.length!==3)throw new Error("not a JWT");const c=JSON.parse(Buffer.from(f[1],"base64url").toString("utf-8")),g=c.exp?c.exp*1e3:null,h=g?Math.floor((g-Date.now())/6e4):null;g&&g<Date.now()?d(`JWT expired ${Math.abs(h)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):h!==null&&h<30?a(`JWT expires in ${h} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):r(`JWT valid${h!==null?` (expires in ${Math.floor(h/60)}h ${h%60}m)`:""}`)}catch{d("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
217
+ \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const f=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(f.ok){const c=await f.json();r(`${l} reachable (status: ${c.status??"ok"})`)}else f.status===401||f.status===403?r(`${l} reachable (auth required \u2014 expected)`):d(`${l}/health returned HTTP ${f.status}`)}catch(f){d(`${l} unreachable \u2014 ${f.message}`)}console.log(`
218
+ \u{1F9E0} Brain instance`);const p=U();if(!p)a("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(u)try{const f=await fetch(`${l}/api/v1/instances/${p}`,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(f.ok){const c=await f.json();if(c.status==="running")if(r(`Instance "${c.name}" (${p.slice(0,8)}\u2026) is running`),console.log(`
219
+ \u{1F50C} Redis connectivity`),c.host&&c.port)try{let g,h;try{const _=await fetch(`${l}/api/v1/instances/${p}/connection`,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(_.ok){const R=await _.json();g=R.password,h=R}}catch{}const C=Nt({host:c.host,port:c.port,tls_enabled:c.tls_enabled},h),x=new at({host:C.host,port:C.port,password:g,...C.tls?{tls:C.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await x.connect();const k=await x.ping();x.disconnect(),k==="PONG"?r(`Redis PING \u2192 PONG (${C.host}:${C.port}, ${C.art==="klartext"?"unencrypted":"TLS"})`):a(`Redis responded but not PONG: ${k}`)}catch(g){d(`Redis unreachable \u2014 ${g.message}`)}else a("Instance has no host/port yet");else a(`Instance "${c.name}" status: ${c.status}`)}else d(`Instance ${p.slice(0,8)}\u2026 not found (HTTP ${f.status})`)}catch(f){d(`Could not check instance \u2014 ${f.message}`)}console.log(`
220
+ \u{1F6E0} Editor configs (project dir)`);const b=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:Se("windsurf",ge())},{editor:"Cline",path:Se("cline",ge())},{editor:"Copilot",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"},{editor:"Codex",path:".codex/config.toml"},{editor:"Gemini CLI",path:".gemini/settings.json"}];let m=0;for(const{editor:f,path:c}of b){const g=n(o,c);if(e(g))try{const h=await t(g,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(r(`${f}: ${c}`),m++):a(`${f}: ${c} exists but cachly not found inside`)}catch{a(`${f}: ${c} exists but could not read`)}}m===0&&d("No editor MCP configs found in this folder \u2014 run: npx @cachly-dev/mcp-server@latest init (add --editor cursor|copilot|codex|gemini if needed)"),console.log(`
221
221
  \u{1FA9D} Git hook (ambient learning)`);const v=n(o,".git","hooks","post-commit");if(!e(n(o,".git")))a("Not in a git repository \u2014 skip");else if(e(v))try{(await t(v,"utf-8")).includes("cachly")?r(".git/hooks/post-commit (cachly CLS hook present)"):a(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{a(".git/hooks/post-commit exists but could not read")}else a(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
222
- \u{1F9EC} Embedding provider (semantic search)`);{const g=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],c=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(c&&c!=="cachly"){const f=g.find(([,h])=>h===c)?.[0];f&&process.env[f]?r(`BYOK: ${c} (key present in ${f})`):a(`CACHLY_EMBED_PROVIDER=${c} but its key env var is not set \u2014 semantic search will fail`)}else{ft==="ollama"?r("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):ft==="cachly"?r("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):a("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[f,h]of g)h!=="ollama"&&process.env[f]&&r(`${f} is set but not used \u2014 ${h} runs only if you name it with CACHLY_EMBED_PROVIDER=${h}`)}}console.log(`
222
+ \u{1F9EC} Embedding provider (semantic search)`);{const f=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],c=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(c&&c!=="cachly"){const g=f.find(([,h])=>h===c)?.[0];g&&process.env[g]?r(`BYOK: ${c} (key present in ${g})`):a(`CACHLY_EMBED_PROVIDER=${c} but its key env var is not set \u2014 semantic search will fail`)}else{gt==="ollama"?r("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):gt==="cachly"?r("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):a("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[g,h]of f)h!=="ollama"&&process.env[g]&&r(`${g} is set but not used \u2014 ${h} runs only if you name it with CACHLY_EMBED_PROVIDER=${h}`)}}console.log(`
223
223
  ${"\u2500".repeat(40)}`),i===0?console.log(`\u2705 All checks passed (${s} ok)
224
224
  `):(console.log(`\u274C ${i} check(s) failed, ${s} passed
225
225
  `),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
226
- `),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),{homedir:s}=await import("node:os"),i=c=>{const f=process.argv.indexOf(`--${c}`);return f!==-1?process.argv[f+1]:void 0};w=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const r=(i("auth-url")??Tt).replace(/\/+$/,"");console.log(`
226
+ `),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),{homedir:s}=await import("node:os"),i=c=>{const g=process.argv.indexOf(`--${c}`);return g!==-1?process.argv[g+1]:void 0};w=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const r=(i("auth-url")??Tt).replace(/\/+$/,"");console.log(`
227
227
  \u{1F9E0} cachly \u2014 keep your test Brain in your own account
228
228
  `),(w!=="https://api.cachly.dev"||r!==Tt)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${w}, sign-in ${r}
229
229
  `);const a=is({argument:i("key"),credentials:Ce()});a||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
230
230
  `),process.exit(1));const d=a.schluessel,u={argument:"--key",credentials:"~/.cachly/credentials.json"}[a.quelle];console.log(`Test key: ${d.slice(0,14)}\u2026 (from ${u})
231
231
  `);let l="";try{console.log(`Step 1: Sign in to your cachly account
232
232
  `);const c=await rs(fetch,r);console.log(` Code: \x1B[1;33m${c.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${c.adresse}
233
- `),ce(c.adresse,(f,h)=>{f||console.log(`
233
+ `),ce(c.adresse,(g,h)=>{g||console.log(`
234
234
  \u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),l=await as(fetch,c,{basis:r,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
235
235
  `)}catch(c){console.error(`
236
236
 
@@ -239,7 +239,7 @@ ${c.message}. Nothing was changed.
239
239
  `)}catch(c){console.error(`
240
240
 
241
241
  ${us(c)}
242
- `),process.exit(1)}S=p.apiKey,ne(p.apiKey),Ae(p.instanceId,{apiKey:p.apiKey}),await pe(p.apiKey),await me(p.instanceId);const b=s(),m=new Set([...Object.values(ke).map(c=>o(process.cwd(),c)),o(b,".claude.json"),o(b,".claude","mcp.json"),o(b,".cursor","mcp.json"),o(b,".codeium","windsurf","mcp_config.json")]);let v=0;for(const c of m)if(n(c))try{const f=ps(await e(c,"utf-8"),d,p.apiKey);f.ersetzt&&(await t(c,f.text,"utf-8"),v++)}catch{}const g=await ls(fetch,w,p.apiKey,p.instanceId);console.log(ds(p,g)),console.log(`
242
+ `),process.exit(1)}S=p.apiKey,ne(p.apiKey),Ae(p.instanceId,{apiKey:p.apiKey}),await pe(p.apiKey),await me(p.instanceId);const b=s(),m=new Set([...Object.values(ke).map(c=>o(process.cwd(),c)),o(b,".claude.json"),o(b,".claude","mcp.json"),o(b,".cursor","mcp.json"),o(b,".codeium","windsurf","mcp_config.json")]);let v=0;for(const c of m)if(n(c))try{const g=ps(await e(c,"utf-8"),d,p.apiKey);g.ersetzt&&(await t(c,g.text,"utf-8"),v++)}catch{}const f=await ls(fetch,w,p.apiKey,p.instanceId);console.log(ds(p,f)),console.log(`
243
243
  New key stored in ~/.cachly/credentials.json${v?` and in ${v} editor config file(s) that held the test key`:""}.`),console.log(`Restart your editor (or reload its MCP servers) so it uses the new key.
244
244
  `),process.exit(0)}const je=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||je){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{createInterface:r}=await import("node:readline"),a=Date.now(),d=je?"autopilot":"setup";Sn();const u=process.argv.indexOf("--api-url");u!==-1&&process.argv[u+1]&&(w=process.argv[u+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${w}
245
245
  `)),A("setup_started");const l=process.stdin.isTTY===!0,p=je||process.argv.includes("--yes")||process.argv.includes("-y")||!l;je?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
@@ -265,18 +265,18 @@ Timed out waiting for authorization. Aborting.
265
265
  API key is required. Aborting.
266
266
  `),b.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(v.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const y=await fetch(`${w}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!y.ok)throw new Error(`HTTP ${y.status}`);const T=await y.json();if(!T.key)throw new Error("no key in response");v=T.key,console.log(` \u2713
267
267
  `)}catch{console.log(` (skipped)
268
- `)}}process.stdout.write("\u23F3 Fetching your instances...");let g=[];try{const y=await fetch(`${w}/api/v1/instances`,{headers:{Authorization:`Bearer ${v}`}});if(!y.ok)throw new Error(`HTTP ${y.status}`);g=((await y.json()).data??[]).filter(B=>B.status==="running")}catch(y){const T=y.message;console.error(`
268
+ `)}}process.stdout.write("\u23F3 Fetching your instances...");let f=[];try{const y=await fetch(`${w}/api/v1/instances`,{headers:{Authorization:`Bearer ${v}`}});if(!y.ok)throw new Error(`HTTP ${y.status}`);f=((await y.json()).data??[]).filter(B=>B.status==="running")}catch(y){const T=y.message;console.error(`
269
269
 
270
270
  Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejected. Get a valid token at ${j("/setup-ai",d)}
271
- `),ce(j("/setup-ai",d))),b.close(),process.exit(1)}if(console.log(` found ${g.length}
272
- `),g.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const y=await fetch(`${w}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"}});if(!y.ok)throw new Error(`HTTP ${y.status}`);const T=await y.json();if(T.instance)g=[T.instance];else if(T.instance_id){const B=T.instance_id;console.log(` \u2713 created (${B.slice(0,8)}\u2026)
273
- `),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(F=>setTimeout(F,3e3)),process.stdout.write(".");try{const F=await fetch(`${w}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${v}`}});if(F.ok){const G=await F.json();if(G.status==="running"){g=[G];break}}}catch{}}console.log("")}}catch(y){console.log(` failed: ${y.message}
274
- `)}g.length===0&&(console.error(`
271
+ `),ce(j("/setup-ai",d))),b.close(),process.exit(1)}if(console.log(` found ${f.length}
272
+ `),f.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const y=await fetch(`${w}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"}});if(!y.ok)throw new Error(`HTTP ${y.status}`);const T=await y.json();if(T.instance)f=[T.instance];else if(T.instance_id){const B=T.instance_id;console.log(` \u2713 created (${B.slice(0,8)}\u2026)
273
+ `),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(F=>setTimeout(F,3e3)),process.stdout.write(".");try{const F=await fetch(`${w}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${v}`}});if(F.ok){const G=await F.json();if(G.status==="running"){f=[G];break}}}catch{}}console.log("")}}catch(y){console.log(` failed: ${y.message}
274
+ `)}f.length===0&&(console.error(`
275
275
  Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
276
- `),ce(j("/instances",d)),b.close(),process.exit(1))}const c=g[0];g.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${c.name}`),console.log(` (Run with --instance-id <id> to use a different one)
276
+ `),ce(j("/instances",d)),b.close(),process.exit(1))}const c=f[0];f.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${c.name}`),console.log(` (Run with --instance-id <id> to use a different one)
277
277
  `)),console.log(`\u2713 Instance: ${c.name} (${c.id.slice(0,8)}\u2026)
278
- `),A("setup_instance_ready",{instance_id:c.id});const f=process.cwd(),h=[],{homedir:C}=await import("node:os"),x=C();h.push("claude"),o(s(f,".cursor"))&&h.push("cursor");const k=fe();(o(s(f,".windsurf"))||wt("windsurf",k,o))&&h.push("windsurf"),o(s(f,".vscode"))&&h.push("copilot"),o(s(f,".continue"))&&h.push("continue"),wt("cline",k,o)&&h.push("cline");const _=process.platform==="darwin"?s(x,"Library/Application Support/Zed"):s(x,".config/zed");o(_)&&h.push("zed");const R=y=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[y]??y,I=h;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
- `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(v),Ae(c.id,{apiKey:v});for(const y of I){const T=xt(y,f),B=T.anzeige,z=T.pfad;try{await t(i(z),{recursive:!0});const F=$(z),G=await Qt(z,v,c.id,T.format,{readFile:n,existsSync:$});await e(z,G,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${B}`),M++}catch(F){const G=F.message;console.log(`\u26A0\uFE0F Could not write ${B}: ${G}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:B,reason:G})}}const Ne=await eo(f,c.id);for(const[y,T]of Object.entries(Ne)){const{relative:B}=await import("node:path");console.log(to(B(f,y)||y,T))}S=v;let ie=0;if(o(s(f,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const y=await J("brain_from_git",{instance_id:c.id,repo_path:f,limit:100});if(y.startsWith("\u274C"))console.log(` (skipped: ${ht(y.replace(/^❌\s*/,"")).split(`
278
+ `),A("setup_instance_ready",{instance_id:c.id});const g=process.cwd(),h=[],{homedir:C}=await import("node:os"),x=C();h.push("claude"),o(s(g,".cursor"))&&h.push("cursor");const k=ge();(o(s(g,".windsurf"))||wt("windsurf",k,o))&&h.push("windsurf"),o(s(g,".vscode"))&&h.push("copilot"),o(s(g,".continue"))&&h.push("continue"),wt("cline",k,o)&&h.push("cline");const _=process.platform==="darwin"?s(x,"Library/Application Support/Zed"):s(x,".config/zed");o(_)&&h.push("zed");const R=y=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[y]??y,I=h;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
+ `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(v),Ae(c.id,{apiKey:v});for(const y of I){const T=xt(y,g),B=T.anzeige,z=T.pfad;try{await t(i(z),{recursive:!0});const F=$(z),G=await Xt(z,v,c.id,T.format,{readFile:n,existsSync:$});await e(z,G,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${B}`),M++}catch(F){const G=F.message;console.log(`\u26A0\uFE0F Could not write ${B}: ${G}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:B,reason:G})}}const Ne=await eo(g,c.id);for(const[y,T]of Object.entries(Ne)){const{relative:B}=await import("node:path");console.log(to(B(g,y)||y,T))}S=v;let ie=0;if(o(s(g,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const y=await J("brain_from_git",{instance_id:c.id,repo_path:g,limit:100});if(y.startsWith("\u274C"))console.log(` (skipped: ${ht(y.replace(/^❌\s*/,"")).split(`
280
280
  `)[0].slice(0,160)})`);else{const T=y.match(/Ingested: \*\*(\d+)\*\*/);ie=T?parseInt(T[1],10):0,console.log(` \u2713 ${ie} lesson${ie===1?"":"s"} extracted from git history`);const B=_n(y);B&&(console.log(""),console.log(ht(B)))}}catch(y){console.log(` (skipped: ${y.message.slice(0,80)})`)}}if(ie===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await J("brain_seed_starter",{instance_id:c.id}),console.log(" \u2713");try{const y=await J("smart_recall",{instance_id:c.id,query:"docker build slow"}),T=$n(y);T&&(console.log(""),console.log(kn(T.topic,T.what)))}catch{}}catch(y){console.log(` (skipped: ${y.message.slice(0,60)})`)}}try{const y=await fetch(`${w}/api/v1/instances/${c.id}/memory`,{headers:{Authorization:`Bearer ${v}`},signal:AbortSignal.timeout(6e3)});if(y.ok){const B=(await y.json()).lesson_count??0;console.log(B===0?`
281
281
  \u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
282
282
  \u{1F9E0} Your Brain now holds ${B} lesson${B===1?"":"s"}.`)}}catch{}if(!p)try{if(console.log(`
@@ -287,7 +287,7 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
287
287
  `)}catch{}}try{const y=await yt(process.cwd(),c.id);y==="written"?console.log(`
288
288
  \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):y==="upgraded"?console.log(`
289
289
  \u2705 CLS git hook upgraded to ${bt}.`):y==="appended"&&console.log(`
290
- \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const y=await kt(process.cwd(),c.id);if(y.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${y.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=y.scripts==="written"?"\u2705 Written":y.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${St})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),y.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):y.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}I.includes("cursor")&&await be("cursor",process.cwd(),c.id," "),I.includes("copilot")&&await be("copilot",process.cwd(),c.id," "),(o(s(x,".codex"))||o(s(f,".codex")))&&(await be("codex",process.cwd(),c.id," "),await qe("codex",process.cwd(),ee("",c.id)," ")),(o(s(x,".gemini"))||o(s(f,".gemini")))&&(await be("gemini",process.cwd(),c.id," "),await qe("gemini",process.cwd(),ee("",c.id)," ")),S=v;const Ve=Math.round((Date.now()-a)/1e3);if(E.length>0&&A("setup_config_write_failed",{instance_id:c.id,failed:E.length,succeeded:M}),A("setup_completed",{instance_id:c.id,elapsed_s:Ve,config_failures:E.length}),E.length>0&&M===0){console.log(`
290
+ \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const y=await kt(process.cwd(),c.id);if(y.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${y.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=y.scripts==="written"?"\u2705 Written":y.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${St})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),y.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):y.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}I.includes("cursor")&&await be("cursor",process.cwd(),c.id," "),I.includes("copilot")&&await be("copilot",process.cwd(),c.id," "),(o(s(x,".codex"))||o(s(g,".codex")))&&(await be("codex",process.cwd(),c.id," "),await qe("codex",process.cwd(),ee("",c.id)," ")),(o(s(x,".gemini"))||o(s(g,".gemini")))&&(await be("gemini",process.cwd(),c.id," "),await qe("gemini",process.cwd(),ee("",c.id)," ")),S=v;const Ve=Math.round((Date.now()-a)/1e3);if(E.length>0&&A("setup_config_write_failed",{instance_id:c.id,failed:E.length,succeeded:M}),A("setup_completed",{instance_id:c.id,elapsed_s:Ve,config_failures:E.length}),E.length>0&&M===0){console.log(`
291
291
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u26A0\uFE0F Setup incomplete \u2014 no editor config was written \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(`
292
292
  Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const y of E)console.log(` \u2022 ${y.file} \u2014 ${y.reason}`);console.log(`
293
293
  Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${v.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${c.id}`),console.log(` Docs: ${j("/docs/mcp",d)}
@@ -314,11 +314,11 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
314
314
  \u2705 Brain learned from your commits.
315
315
  `),await new Promise(a=>setTimeout(a,300))}catch(r){console.error(`
316
316
  \u274C learn-git failed: ${r.message}
317
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await Fn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Yn(),process.argv[2]===Gn&&await Kn(process.argv[3]??""),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await Vn(o),await ti(process.env.CACHLY_BRAIN_INSTANCE_ID??N,o),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=U(),t=Qn(await At(),e||void 0),n=t.eigene,o=Vs(n),s=n.slice(-5);if(console.log(`
317
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await Fn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Yn(),process.argv[2]===Gn&&await Kn(process.argv[3]??""),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await Vn(o),await ti(process.env.CACHLY_BRAIN_INSTANCE_ID??N,o),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=U(),t=Xn(await At(),e||void 0),n=t.eigene,o=Vs(n),s=n.slice(-5);if(console.log(`
318
318
  \u{1F9E0} Ambient Recall \u2014 net-token ledger
319
319
  `),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${n.length}`),console.log(` Injected tokens: ${o.injected}`),console.log(` Prevented tokens: ${o.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${o.net>=0?"+":""}${o.net} tokens`),s.length>0){console.log(`
320
320
  Last entries:`);for(const i of s){const r=i.prevented>0?`+${i.prevented} prevented`:`-${i.injected} injected`;console.log(` \u2022 ${i.ts.slice(0,19)} ${i.event}: ${r}${i.note?` (${i.note})`:""}`)}}(t.ohneInstanz>0||t.andereInstanzen>0)&&(console.log(`
321
- Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:n}=await import("node:path"),{createInterface:o}=await import("node:readline/promises"),s=process.argv.slice(3),r={projekt:n((a=>{const d=s.indexOf(`--${a}`);return d!==-1?s[d+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:w,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const d=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await d.question(a)).trim())}finally{d.close()}}};process.exit(await Pn(s,r))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:r,checkHooks:a,checkLedger:d,renderDoctorReport:u,doctorExitCode:l}=await import("./doctor.js"),p=[e(),t(S),await n(w),await o(w,S),s(U()||N),await i(w,S,U()||N),a(r(process.cwd())),d(await At(),Zn())];console.log(u(p)),process.exit(l(p))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!S)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??N;(!n||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!S){const e=ro();if(e)try{const t=await fetch(co(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:ao(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(S=n.access_token,oe(n.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
321
+ Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:n}=await import("node:path"),{createInterface:o}=await import("node:readline/promises"),s=process.argv.slice(3),r={projekt:n((a=>{const d=s.indexOf(`--${a}`);return d!==-1?s[d+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:Q(),instanz:U(),apiUrl:w,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const d=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await d.question(a)).trim())}finally{d.close()}}};process.exit(await Pn(s,r))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:r,checkHooks:a,checkLedger:d,renderDoctorReport:u,doctorExitCode:l}=await import("./doctor.js"),p=[e(),t(S),await n(w),await o(w,S),s(U()||N),await i(w,S,U()||N),a(r(process.cwd())),d(await At(),Zn())];console.log(u(p)),process.exit(l(p))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!S)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??N;(!n||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!S){const e=ro();if(e)try{const t=await fetch(co(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:ao(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(S=n.access_token,oe(n.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
322
322
  `))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
323
323
  `),A("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
324
324
  `),A("m2m_auth_failed",{reason:"network"})}}const vi=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","refer","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor","uninstall"];if(!S&&!vi.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&ho){const o=`
@@ -350,7 +350,7 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
350
350
  Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
351
351
 
352
352
  `)}}process.env.PORT||js({aktuelle:Rs(H)});const Be=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Be){Po(!0),S="",N="",oe(""),No();const e=Ko(w,process.env.MCP_INTERNAL_SECRET?.trim());process.stderr.write(`cachly-mcp HTTP: API ${w}, Aufrufer-Weitergabe ${e?"an":"aus (MCP_INTERNAL_SECRET fehlt oder zu kurz)"}
353
- `);const t=Uo(async(i,r)=>{const a=await fetch(`${w}${i}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),d=a.ok?await a.json().catch(()=>null):null,u=Number(a.headers.get("retry-after"));return{status:a.status,body:d,retryAfterS:Number.isFinite(u)&&u>0?u:void 0}},{grenze:Jo()}),{createServer:n}=await import("node:http"),o=(i,r,a,d)=>{i.headersSent||(i.writeHead(r,{"Content-Type":"application/json",...r===429&&d?{"Retry-After":String(d)}:{},...r===401?{"WWW-Authenticate":'Bearer realm="cachly"'}:{}}),i.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:a},id:null})))};n((i,r)=>{const a=new URL(i.url??"/",`http://localhost:${Be}`);if(a.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(a.pathname==="/mcp"||a.pathname==="/"){const d=Fo(i.headers["x-real-ip"],i.socket.remoteAddress);Yo(d,async()=>{const u=Mo(i.headersDistinct?.authorization??i.headers.authorization);if(u.art==="abgelehnt"){const m=u.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":u.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":u.grund==="kein-bearer"?'Nur "Authorization: Bearer cky_..." wird akzeptiert.':"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return o(r,401,m)}const l=zo(i.headers["x-cachly-instance"]);if(l.art==="abgelehnt")return o(r,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");let p;if(u.art==="ok")try{const m=await t.loese(u.schluessel,l.art==="ok"?l.instanzId:void 0,d);p=Oo(u.schluessel,m)}catch(m){return m instanceof Wo?o(r,m.httpStatus,m.message,m.retryAfterS):o(r,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const b=async()=>{const m=pi(),v=new bo({sessionIdGenerator:void 0});r.on("close",()=>{v.close().catch(()=>{}),m.close().catch(()=>{})});try{await m.connect(v),await v.handleRequest(i,r)}catch(g){process.stderr.write(`cachly-mcp HTTP: ${g.message}
354
- `),r.headersSent||(r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:g.message})))}};await(p?Lo(p,b):b())});return}r.writeHead(404),r.end("not found")}).listen(Be,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Be}
353
+ `);const t=Uo(async(i,r)=>{const a=await fetch(`${w}${i}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),d=a.ok?await a.json().catch(()=>null):null,u=Number(a.headers.get("retry-after"));return{status:a.status,body:d,retryAfterS:Number.isFinite(u)&&u>0?u:void 0}},{grenze:Jo()}),{createServer:n}=await import("node:http"),o=(i,r,a,d)=>{i.headersSent||(i.writeHead(r,{"Content-Type":"application/json",...r===429&&d?{"Retry-After":String(d)}:{},...r===401?{"WWW-Authenticate":'Bearer realm="cachly"'}:{}}),i.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:a},id:null})))};n((i,r)=>{const a=new URL(i.url??"/",`http://localhost:${Be}`);if(a.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(a.pathname==="/mcp"||a.pathname==="/"){const d=Fo(i.headers["x-real-ip"],i.socket.remoteAddress);Yo(d,async()=>{const u=Mo(i.headersDistinct?.authorization??i.headers.authorization);if(u.art==="abgelehnt"){const m=u.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":u.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":u.grund==="kein-bearer"?'Nur "Authorization: Bearer cky_..." wird akzeptiert.':"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return o(r,401,m)}const l=zo(i.headers["x-cachly-instance"]);if(l.art==="abgelehnt")return o(r,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");let p;if(u.art==="ok")try{const m=await t.loese(u.schluessel,l.art==="ok"?l.instanzId:void 0,d);p=Oo(u.schluessel,m)}catch(m){return m instanceof Wo?o(r,m.httpStatus,m.message,m.retryAfterS):o(r,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const b=async()=>{const m=pi(),v=new bo({sessionIdGenerator:void 0});r.on("close",()=>{v.close().catch(()=>{}),m.close().catch(()=>{})});try{await m.connect(v),await v.handleRequest(i,r)}catch(f){process.stderr.write(`cachly-mcp HTTP: ${f.message}
354
+ `),r.headersSent||(r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:f.message})))}};await(p?Lo(p,b):b())});return}r.writeHead(404),r.end("not found")}).listen(Be,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Be}
355
355
  `)})}else{const e=new yo;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,$s(()=>Es(lt)),So(),Ls(),Ns(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
356
- `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Qe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Tn as CLAUDE_MD_MARKER_END,Cn as CLAUDE_MD_MARKER_START,cn as CROSS_LINGUAL_MAP,ke as EDITOR_FILES,nn as STOPWORDS,to as anweisungsZeile,rn as arabicLightStem,vt as buildClaudeMdBlock,hi as buildMcpConfig,ee as buildServerEnv,an as expandCrossLingual,on as extractTimestamp,ut as fristMs,sn as katakanaToRomaji,en as levenshtein,fi as mcpAddBefehl,Qt as mergeMcpConfig,tn as recencyBoost,un as reconnectOnce,Qo as splitMultiQuery,mt as startBackgroundDevicePoll,Xo as tokenize,eo as writeInstructions};
356
+ `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Xe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Tn as CLAUDE_MD_MARKER_END,Cn as CLAUDE_MD_MARKER_START,cn as CROSS_LINGUAL_MAP,ke as EDITOR_FILES,nn as STOPWORDS,to as anweisungsZeile,rn as arabicLightStem,vt as buildClaudeMdBlock,hi as buildMcpConfig,ee as buildServerEnv,an as expandCrossLingual,on as extractTimestamp,ut as fristMs,sn as katakanaToRomaji,en as levenshtein,gi as mcpAddBefehl,Xt as mergeMcpConfig,tn as recencyBoost,un as reconnectOnce,Xo as splitMultiQuery,mt as startBackgroundDevicePoll,Qo as tokenize,eo as writeInstructions};