@cachly-dev/mcp-server 0.10.257 → 0.10.259

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,59 +1,59 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as Wt}from"./herkunft.js";import{jwtExpiryMs as Jt,checkJwt as Ft,handleApiError as Yt,diagnoseAuth as Ie,planAuthHeal as We,readClientCredentialsFromEnv as Kt,buildClientCredentialsBody as qt,clientCredentialsTokenUrl as Gt}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as Vt}from"./werkzeug-nutzung.js";import{istLieferung as Zt,lieferSchluessel as Qt,tokenDerAntwort as Xt,hatTreffer as eo,trefferSchluessel as Je}from"./geliefert.js";import{notify as Fe}from"./notifier.js";import{fileURLToPath as Ye}from"node:url";import{createRequire as to}from"node:module";import{execFile as Ee}from"node:child_process";const oo=process.argv[1]!=null&&(process.argv[1]===Ye(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Ke}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as no}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as so}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as qe,ErrorCode as ne,ListPromptsRequestSchema as Ge,ListResourceTemplatesRequestSchema as Ve,ListResourcesRequestSchema as Ze,ListToolsRequestSchema as Qe,McpError as Q}from"@modelcontextprotocol/sdk/types.js";import{Redis as Xe}from"ioredis";let x=process.env.CACHLY_API_URL??"https://api.cachly.dev",S=Oe()??"";ae(S);const ti=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=to(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"})(),io=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=$e(process.env.CACHLY_BRAIN_INSTANCE_ID);function G(){return S||Oe()||""}function z(){return $e(process.env.CACHLY_BRAIN_INSTANCE_ID)||_e()||""}let V=0,pe=null,et=!1;async function tt(){let e=[];try{K.getClientCapabilities()?.roots&&(e=(await K.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Gn({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Ye})}function se(){return et?yt(process.env):!1}function Re(e,t,n){!e||!se()||Fn({instanzId:e,vomHook:n,verbindung:O,ausGit:o=>Le("brain_from_git",o,O,L),projektOrdner:t?async()=>t:tt,einbetten:o=>st(o,{geduld:"lang"}),hatEinbettung:wo,einbettenZweit:o=>st(o,{geduld:"lang",modell:vo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Me("brain_seed_starter",o,O,L),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function je(){return se()&&Vn()}const ro=7e3,ao=12e3,co=18e4;let be=null;function Be(e){return be||(be=lo(e).finally(()=>{be=null})),be}async function lo(e){try{if(!S){const t=Date.now()+e;for(;!xe()&&On({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,Nn));const n=xe();if(!n)return!1;S=n,ae(n);const o=_e();o&&!N&&(N=o,V=0),await me(n),o&&await ge(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(se()&&ft()){const t=Pn();t&&(He(t.instanzId,se(),je()),Re(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function uo(){if(!yt(process.env))return;const e=Date.now()+co,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!ft()||Be(0)},500);t.unref(),Be(0)}async function po(){if(!S)return"";try{const e=await fetch(`${x}/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(`${x}/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(`${x}/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 ot(){if(N)return N;if(!S)return"";if(pe)return pe;const e=Date.now();if(V>0&&e-V<3e4)return"";V=e,pe=(async()=>{try{const t=await fetch(`${x}/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(a=>a.status==="running")??o.find(a=>a.status==="provisioning");if(s)return N=s.id,V=0,N;const i=await po();if(i)return N=i,V=0,He(i,se(),je()),ge(i),Re(i),N}}catch{}return""})();try{return await pe}finally{pe=null}}let Ne=0;const mo=6e4;let ie="";async function me(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 a=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(a.map(async r=>{if(o(r))try{const d=await n(r,"utf-8"),f=JSON.parse(d),l=f?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_JWT=e,await t(r,JSON.stringify(f,null,2),"utf-8"))}catch{}}))}catch{}}async function ge(e){if(e){ve(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 a=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(a.map(async r=>{if(o(r))try{const d=JSON.parse(await n(r,"utf-8")),f=d?.mcpServers?.cachly;f?.env&&(f.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(r,JSON.stringify(d,null,2),"utf-8"))}catch{}}))}catch{}}}async function go(){try{const e=await fetch(`${x}/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,ae(t.key),me(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Pe(){const e=Ie(S),t=We(e);if(t==="none")return ie="",!0;if(t==="refresh"){const n=Date.now();return n-Ne>=mo&&(Ne=n,await go())?(ie="",!0):(ie=e.message,e.usable)}return ie=e.message,!1}function re(e,t){const n=(a,r)=>{try{t?.(a,r)}catch{}},o=a=>{a?n(!1,a.code??a.message):n(!0)},s=sn(e);if(!s){n(!1,"keine-http-adresse");return}const i=rn(s);try{process.platform==="win32"?Ee("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Ee("open",[s],o):Ee("xdg-open",[s],o)}catch(a){n(!1,a instanceof Error?a.message:"unknown")}}let Y=null;async function ho(){try{const e=await fetch(`${x}/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()+600*1e3,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()+600*1e3,polling:!1}}catch{return null}}async function fo(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const o=await fetch(`${x}/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(`${x}/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 a=await i.json();a.key&&(s=a.key)}}catch{}return S=s,ae(s),Y=null,A("device_flow_completed"),me(s),ee(s),V=0,await ot(),N&&ge(N),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function nt(e){if(e.polling)return"pending";e.polling=!0;try{return await fo(e)}finally{e.polling=!1}}function yo(e,t=nt,n=s=>Y===s,o=bo){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(Y=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function bo(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ae,computeEmbedding as st,hasEmbedProvider as wo,EMBED_PROVIDER as it}from"./embeddings.js";import{ZWEIT_MODELL as vo}from"./rangfolge-stellschrauben.js";import{tokenize as xo,splitMultiQuery as _o,levenshtein as $o,recencyBoost as ko,extractTimestamp as So,STOPWORDS as Ao,katakanaToRomaji as Co,arabicLightStem as To,expandCrossLingual as Io,CROSS_LINGUAL_MAP as Eo,ZERO_RESULTS_LOG as Ro,zeroResultsTotal as jo}from"./search.js";const X=new Map;function Bo(e){return e<=1?200:null}async function O(e){if(!e)throw new Q(ne.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
2
+ import{setzeClientKennung as Qt}from"./herkunft.js";import{jwtExpiryMs as eo,checkJwt as to,handleApiError as oo,diagnoseAuth as Ne,planAuthHeal as Ze,readClientCredentialsFromEnv as no,buildClientCredentialsBody as so,clientCredentialsTokenUrl as io}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as ro}from"./werkzeug-nutzung.js";import{istLieferung as ao,lieferSchluessel as co,tokenDerAntwort as lo,hatTreffer as uo,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as po}from"node:module";import{execFile as Oe}from"node:child_process";const mo=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 go}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ho}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 x=process.env.CACHLY_API_URL??"https://api.cachly.dev",S=Fe()??"";oe(S);const Ai=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=po(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"})(),fo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let P=Ie(process.env.CACHLY_BRAIN_INSTANCE_ID);function we(){return W()?xe()?.schluessel??"":S}function yo(){return W()?xe()?.instanzId??"":P}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 ws({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function re(){return ct?Ct(process.env):!1}function Le(e,t,n){!e||!re()||hs({instanzId:e,vomHook:n,verbindung:L,ausGit:o=>Je("brain_from_git",o,L,O),projektOrdner:t?async()=>t:lt,einbetten:o=>pt(o,{geduld:"lang"}),hatEinbettung:Eo,einbettenZweit:o=>pt(o,{geduld:"lang",modell:Jo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,L,O),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function He(){return re()&&vs()}const bo=7e3,wo=12e3,vo=18e4;let ve=null;function Me(e){return ve||(ve=xo(e).finally(()=>{ve=null})),ve}async function xo(e){try{if(!S){const t=Date.now()+e;for(;!Ce()&&as({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,ss));const n=Ce();if(!n)return!1;S=n,oe(n);const o=Te();o&&!P&&(P=o,Q=0),await pe(n),o&&await me(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(re()&&At()){const t=is();t&&(Ye(t.instanzId,re(),He()),Le(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function _o(){if(!Ct(process.env))return;const e=Date.now()+vo,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!At()||Me(0)},500);t.unref(),Me(0)}async function $o(){if(!S||W())return"";try{const e=await fetch(`${x}/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(`${x}/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(`${x}/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 yo();if(P)return P;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(`${x}/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 P=s.id,Q=0,P;const i=await $o();if(i)return P=i,Q=0,Ye(i,re(),He()),me(i),Le(i),P}}catch{}return""})();try{return await ue}finally{ue=null}}let ze=0;const ko=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 u=await n(a,"utf-8"),p=JSON.parse(u),c=p?.mcpServers?.cachly;c?.env&&(c.env.CACHLY_JWT=e,await t(a,JSON.stringify(p,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 u=JSON.parse(await n(a,"utf-8")),p=u?.mcpServers?.cachly;p?.env&&(p.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function So(){try{const e=await fetch(`${x}/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=Ne(S),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-ze>=ko&&(ze=n,await So())?(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=In(e);if(!s){n(!1,"keine-http-adresse");return}const i=En(s);try{process.platform==="win32"?Oe("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Oe("open",[s],o):Oe("xdg-open",[s],o)}catch(r){n(!1,r instanceof Error?r.message:"unknown")}}let G=null;async function Ao(){try{const e=await fetch(`${x}/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()+600*1e3,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()+600*1e3,polling:!1}}catch{return null}}async function Co(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const o=await fetch(`${x}/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(`${x}/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),G=null,A("device_flow_completed"),pe(s),ne(s),Q=0,await dt(),P&&me(P),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function ut(e){if(e.polling)return"pending";e.polling=!0;try{return await Co(e)}finally{e.polling=!1}}function To(e,t=ut,n=s=>G===s,o=Io){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(G=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function Io(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as pt,hasEmbedProvider as Eo,EMBED_PROVIDER as mt,erzwingeEmbedAnbieterRemote as Ro}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as jo,mandantKontext as xe,imMandant as Bo,baueKontext as Po,poolSchluessel as No,leseBearer as Oo,leseInstanzKopf as Lo,BegrenzterSpeicher as Ho,baueZugangsAufloeser as Mo,ZugangAbgelehnt as zo,ANLEITUNG_OHNE_KOPF as Ue,istRemoteErlaubt as Do,nurLokalText as Uo,bereinigeArgumente as Wo}from"./remote-zugang.js";import{ZWEIT_MODELL as Jo}from"./rangfolge-stellschrauben.js";import{tokenize as Fo,splitMultiQuery as Yo,levenshtein as Ko,recencyBoost as Go,extractTimestamp as qo,STOPWORDS as Vo,katakanaToRomaji as Zo,arabicLightStem as Xo,expandCrossLingual as Qo,CROSS_LINGUAL_MAP as en}from"./search.js";const ge=new Map,tn=200,on=10*6e4,_e=new Ho({max:tn,ttlMs:on,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...ge.values(),..._e.werte()]}function nn(e){return e<=1?200:null}async function L(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=X.get(e);return t||Un(No,e,()=>Po(e))}const No=new Map;async function Po(e){F("verbindung: Instanz abfragen");let t=await L(`/api/v1/instances/${e}`);if(F(`verbindung: Instanz ${t.status}`),t=await zn(t,()=>L(`/api/v1/instances/${e}`),{fristMs:io,melde:r=>F(`verbindung: Instanz ${r.status}`)}),t.status!=="running"){fetch(`${x}/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:t.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let r;throw t.status==="provisioning"?r=`\u23F3 Brain instance "${t.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?No(t.schluessel,e):e,o=t?_e.get(n):ge.get(e);return o||ps(sn,n,()=>rn(e,n,!!t))}const sn=new Map;async function rn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await O(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await us(o,()=>O(`/api/v1/instances/${e}`),{fristMs:fo,melde:p=>Y(`verbindung: Instanz ${p.status}`)}),o.status!=="running"){n||fetch(`${x}/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 p;throw o.status==="provisioning"?p=`\u23F3 Brain instance "${o.name}" is still starting up.
10
10
 
11
- First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:t.status==="failed"?r=`\u274C Brain instance "${t.name}" failed to start.
11
+ First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:o.status==="failed"?p=`\u274C Brain instance "${o.name}" failed to start.
12
12
 
13
13
  Our system will retry automatically. Check status at: ${j("/instances","instance-error")}
14
- If this persists, contact support@cachly.dev.`:t.status==="suspended"?r=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
14
+ If this persists, contact support@cachly.dev.`:o.status==="suspended"?p=`\u23F8 Brain instance "${o.name}" is suspended (billing issue).
15
15
 
16
- Update your payment method at: ${j("/billing","upgrade")}`:t.status==="pending_payment"?r=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
16
+ Update your payment method at: ${j("/billing","upgrade")}`:o.status==="pending_payment"?p=`\u{1F4B3} Brain instance "${o.name}" is waiting for payment.
17
17
 
18
- Complete your checkout at: ${j("/instances","upgrade")}`:r=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
18
+ Complete your checkout at: ${j("/instances","upgrade")}`:p=`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 Q(ne.InvalidRequest,r)}if(!t.host||!t.port)throw new Q(ne.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,o;try{const r=await L(`/api/v1/instances/${e}/connection`);n=r.password??void 0,o=r,F("verbindung: Zugangsdaten da")}catch(r){const d=r instanceof Error?r.message:String(r);if(d.includes("401")||d.includes("403")||d.includes("Unauthorized"))throw new Q(ne.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const s=xt({host:t.host,port:t.port,tls_enabled:t.tls_enabled},o),i=new Xe({host:s.host,port:s.port,password:n||void 0,commandTimeout:8e3,...s.tls?{tls:s.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:Bo,maxRetriesPerRequest:1,keepAlive:15e3}),a=()=>{X.delete(e),i.disconnect()};i.on("error",a),i.on("end",a);try{await i.connect()}catch(r){i.disconnect();const d=r instanceof Error?r.message:String(r);throw fetch(`${x}/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:t.host,port:t.port,error:d,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Q(ne.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,p)}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 p=await O(`/api/v1/instances/${e}/connection`);s=p.password??void 0,i=p,Y("verbindung: Zugangsdaten da")}catch(p){const c=p instanceof Error?p.message:String(p);if(c.includes("401")||c.includes("403")||c.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const r=Rt({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:nn,maxRetriesPerRequest:1,keepAlive:15e3}),u=()=>{n?_e.vergissWenn(t,a):ge.delete(e),a.disconnect()};a.on("error",u),a.on("end",u);try{await a.connect()}catch(p){a.disconnect();const c=p instanceof Error?p.message:String(p);throw n||fetch(`${x}/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:c,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: ${d}`)}return X.set(e,i),F("verbindung: Valkey verbunden"),i}async function L(e,t={},n=!1){n||We(Ie(S))!=="none"&&await Pe(),Ft(S);const o=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),s=await fetch(`${x}${e}`,{...t,signal:AbortSignal.timeout(o),headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,...t.headers}});if(!s.ok){if(s.status===401&&!n&&(Ne=0,await Pe()))return L(e,t,!0);const a=(await s.json().catch(()=>({error:s.statusText}))).error??s.statusText;Yt(s.status,a)}if(s.status!==204)return s.json()}import{handleBrainTool as Lo}from"./handlers/brain.js";import{handleContextTool as Oo}from"./handlers/context.js";import{handleInstanceTool as Ho}from"./handlers/instances.js";import{handleCacheTool as Mo}from"./handlers/cache.js";import{handleTeamTool as Do}from"./handlers/team.js";import{handleRoadmapTool as zo}from"./handlers/roadmap.js";import{handleAdvancedTool as Uo}from"./handlers/advanced.js";import{handleSyndicateTool as Wo}from"./handlers/syndicate.js";import{handleFedbrainTool as Le,_lastBrainFromGitCounts as we}from"./handlers/fedbrain.js";import{extractFirstRecallProof as Jo,extractTopHit as Fo,fuersTerminal as rt,renderFirstRecallProof as Yo}from"./first-recall-proof.js";import{aussetzerLeise as Ko}from"./aussetzer.js";import{gitHookOrdner as qo,installClsPostCommitHook as at,CLS_HOOK_VERSION as ct}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Go,CLAUDE_MD_MARKER_END as Vo,EDITOR_FILES as ce,ANWEISUNGS_DATEIEN as Zo,buildClaudeMdBlock as lt,setzeAnweisungsblock as Qo,sollSchreiben as Xo}from"./projektdateien.js";import{klassiereArgument as en,leseFlag as dt,flagsOhneWert as tn,pruefeInitEingaben as on}from"./cli-argumente.js";import{uninstallBefehl as nn}from"./uninstall.js";import{gitLesen as ut}from"./git-ohne-shell.js";import{browserAdresse as sn,fuerCmd as rn}from"./browser-adresse.js";import{installAmbientHooks as pt,installCursorHooks as an,installCopilotHooks as cn,installCodexHooks as ln,installGeminiHooks as dn,AMBIENT_HOOK_VERSION as mt,COPILOT_HOOKS_DATEI as un,CODEX_HOOKS_DATEI as pn,GEMINI_SETTINGS_DATEI as mn}from"./ambient-hooks.js";import{hookHauptlauf as gn,auffrischenHauptlauf as hn,startwissenImportHauptlauf as fn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as yn}from"./startwissen-hook.js";import{rahmeAntwort as bn}from"./antwort-rahmen.js";import{appendLedgerEntry as wn,readLedger as gt,defaultLedgerPath as vn,reportLedgerEntry as xn,teileNachInstanz as _n}from"./ambient-ledger.js";import{installCodexMcp as $n,installGeminiMcp as kn}from"./editor-mcp-eintrag.js";import{resolveApiKey as Oe,saveApiKey as ee,saveInstanceId as ve,readSavedApiKey as xe,readInstanceId as _e}from"./credentials.js";import{KEYCLOAK_BASIS as ht,istTestSchluessel as Sn,waehleTestSchluessel as An,starteKeycloakAnmeldung as Cn,warteAufKeycloakAnmeldung as Tn,uebernimm as In,brainImKonto as En,erfolgsText as Rn,fehlerText as jn,ersetzeSchluessel as Bn}from"./uebernahme.js";import{WARTE_TAKT_MS as Nn,auftragLiegt as ft,nimmAuftrag as Pn,sichereKonto as Ln,sperreLiegt as On,startwissenEingeschaltet as yt}from"./konto-anlegen.js";import{sichereZugang as Hn,echterWert as $e}from"./zugang.js";import{zeitpunkt as F}from"./zeitmessung.js";import{autoSitzungsSchritt as Mn,SITZUNGS_WERKZEUGE as Dn}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as zn,gemeinsamerAufbau as Un}from"./instanz-warten.js";import{merkeNeuesBrain as He,startetLautLetztemBlick as Wn,setzeCommitQuelle as Jn}from"./leeres-brain.js";import{starteStartwissen as Fn,startwissenGestartet as Yn,beanspruchStartwissen as Kn,holeStartwissenHinweis as qn,waehleProjektOrdner as Gn,startvorratErlaubt as Vn,projektCommits as Zn}from"./startwissen.js";import{eigeneFassung as Qn,pruefeNeueFassung as Xn,holeNeueFassungHinweis as es}from"./neue-fassung.js";import{beiStdinEnde as ts}from"./stdin-ende.js";import{merkeWerkzeugAufruf as os,starteBrandWachhund as ns}from"./brand-wachhund.js";import{sichtbareWerkzeuge as ss,VERTEILER as bt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as is}from"./pflichtfelder.js";import{buildLessonsMarkdown as rs,buildLessonsJsonl as as,vonRohLektion as cs}from"./brain-export.js";import{detectEditor as ls}from"./editor.js";import{milestoneSent as wt,markMilestoneSent as vt}from"./funnel-milestones.js";import{meldeKopf as ds,meldeRumpf as us}from"./melde-weg.js";import{kostprobeUebrig as ps,kostprobeVerbrauchen as ms,kostprobeHinweis as gs,schrankeNachKostproben as hs}from"./kostprobe.js";import{netBalance as fs}from"./ambient-recall.js";import{handleShareTool as Me}from"./handlers/share.js";import{handleVizTool as ys}from"./handlers/viz.js";import{commitArt as bs,istRueckbau as ws,zaehleLektionen as vs}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as xt}from"./brains-tls.js";let _t=!1,$t=!1,ke=!1;function kt(){return ls()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:ds(S),body:JSON.stringify(us({event:e,version:H,editor:kt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function xs(e,t){return xn({apiUrl:x,jwt:S,instanceId:e},t)}async function _s(e){if(!_t&&process.env.CACHLY_NO_TELEMETRY!=="1"){_t=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:kt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const $s=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"]),ks={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."},St=j("/billing","upgrade"),At=new Map;async function Ss(e){const t=At.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 At.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function As(e,t){if(!$s.has(e)||!t)return null;const{isFree:n}=await Ss(t);if(!n)return null;const o=ks[e]??"A Premium intelligence feature.";if(ps(e)){const s=ms(e);return{kostprobe:gs(e,s,St)}}return{sperre:hs(e,o,St)}}async function Cs(e,t){try{await(await O(e)).hincrby(Vt(e),t,1)}catch{}}async function Ts(e,t,n){if(Zt(t))try{const o=await O(e),s=eo(n);await o.incrby(Qt(e),s?Xt(n):0),await o.hincrby(Je(e),"abrufe",1),s&&await o.hincrby(Je(e),"treffer",1)}catch{}}async function Is(e){const t=await ho();return t?(Y=t,A("device_flow_started",{tool:e}),re(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: ${c}`)}return n?_e.set(t,a):ge.set(e,a),Y("verbindung: Valkey verbunden"),a}async function O(e,t={},n=!1){!n&&!W()&&Ze(Ne(S))!=="none"&&await De();const o=we();to(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${x}${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 O(e,t,!0);const a=(await i.json().catch(()=>({error:i.statusText}))).error??i.statusText;oo(i.status,a)}if(i.status!==204)return i.json()}import{handleBrainTool as an}from"./handlers/brain.js";import{handleContextTool as cn}from"./handlers/context.js";import{handleInstanceTool as ln}from"./handlers/instances.js";import{handleCacheTool as dn}from"./handlers/cache.js";import{handleTeamTool as un}from"./handlers/team.js";import{handleRoadmapTool as pn}from"./handlers/roadmap.js";import{handleAdvancedTool as mn}from"./handlers/advanced.js";import{handleSyndicateTool as gn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as $e}from"./handlers/fedbrain.js";import{extractFirstRecallProof as hn,extractTopHit as fn,fuersTerminal as gt,renderFirstRecallProof as yn}from"./first-recall-proof.js";import{aussetzerLeise as bn}from"./aussetzer.js";import{gitHookOrdner as wn,installClsPostCommitHook as ht,CLS_HOOK_VERSION as ft}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as vn,CLAUDE_MD_MARKER_END as xn,EDITOR_FILES as ke,ANWEISUNGS_DATEIEN as _n,buildClaudeMdBlock as yt,setzeAnweisungsblock as $n,sollSchreiben as kn,globaleMcpDatei as Se,globalerEditorDa as bt,diesesHeim as he,mcpZiel as wt}from"./projektdateien.js";import{klassiereArgument as Sn,leseFlag as vt,flagsOhneWert as An,pruefeInitEingaben as Cn}from"./cli-argumente.js";import{uninstallBefehl as Tn}from"./uninstall.js";import{gitLesen as xt}from"./git-ohne-shell.js";import{browserAdresse as In,fuerCmd as En}from"./browser-adresse.js";import{installAmbientHooks as _t,installCursorHooks as Rn,installCopilotHooks as jn,installCodexHooks as Bn,installGeminiHooks as Pn,AMBIENT_HOOK_VERSION as $t,COPILOT_HOOKS_DATEI as Nn,CODEX_HOOKS_DATEI as On,GEMINI_SETTINGS_DATEI as Ln}from"./ambient-hooks.js";import{hookHauptlauf as Hn,auffrischenHauptlauf as Mn,startwissenImportHauptlauf as zn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as Dn}from"./startwissen-hook.js";import{rahmeAntwort as Un}from"./antwort-rahmen.js";import{appendLedgerEntry as Wn,readLedger as kt,defaultLedgerPath as Jn,reportLedgerEntry as Fn,teileNachInstanz as Yn}from"./ambient-ledger.js";import{installCodexMcp as Kn,installGeminiMcp as Gn}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{KEYCLOAK_BASIS as St,istTestSchluessel as qn,waehleTestSchluessel as Vn,starteKeycloakAnmeldung as Zn,warteAufKeycloakAnmeldung as Xn,uebernimm as Qn,brainImKonto as es,erfolgsText as ts,fehlerText as os,ersetzeSchluessel as ns}from"./uebernahme.js";import{WARTE_TAKT_MS as ss,auftragLiegt as At,nimmAuftrag as is,sichereKonto as rs,sperreLiegt as as,startwissenEingeschaltet as Ct}from"./konto-anlegen.js";import{sichereZugang as cs,echterWert as Ie}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as ls,SITZUNGS_WERKZEUGE as ds}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as us,gemeinsamerAufbau as ps}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as ms,setzeCommitQuelle as gs}from"./leeres-brain.js";import{starteStartwissen as hs,startwissenGestartet as fs,beanspruchStartwissen as ys,holeStartwissenHinweis as bs,waehleProjektOrdner as ws,startvorratErlaubt as vs,projektCommits as xs}from"./startwissen.js";import{eigeneFassung as _s,pruefeNeueFassung as $s,holeNeueFassungHinweis as ks}from"./neue-fassung.js";import{beiStdinEnde as Ss}from"./stdin-ende.js";import{merkeWerkzeugAufruf as As,starteBrandWachhund as Cs}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Ts,VERTEILER as Tt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Is}from"./pflichtfelder.js";import{buildLessonsMarkdown as Es,buildLessonsJsonl as Rs,vonRohLektion as js}from"./brain-export.js";import{detectEditor as Bs}from"./editor.js";import{milestoneSent as It,markMilestoneSent as Et}from"./funnel-milestones.js";import{meldeKopf as Ps,meldeRumpf as Ns}from"./melde-weg.js";import{kostprobeUebrig as Os,kostprobeVerbrauchen as Ls,kostprobeHinweis as Hs,kostprobePfadJeInstanz as Ms,schrankeNachKostproben as zs}from"./kostprobe.js";import{netBalance as Ds}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as Us}from"./handlers/viz.js";import{commitArt as Ws,istRueckbau as Js,zaehleLektionen as Fs}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Rt}from"./brains-tls.js";let jt=!1,Bt=!1,Ee=!1;function Pt(){return Bs()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:Ps(S),body:JSON.stringify(Ns({event:e,version:H,editor:Pt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function Ys(e,t){return Fn({apiUrl:x,jwt:S,instanceId:e},t)}async function Ks(e){if(!(jt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){jt=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Pt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const Gs=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"]),qs={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."},Nt=j("/billing","upgrade"),Ot=new Map;async function Vs(e){const t=Ot.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Ot.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function Zs(e,t){if(!Gs.has(e)||!t)return null;const{isFree:n}=await Vs(t);if(!n)return null;const o=qs[e]??"A Premium intelligence feature.",s=W()?Ms(t):void 0;if(Os(e,s)){const i=Ls(e,s);return{kostprobe:Hs(e,i,Nt)}}return{sperre:zs(e,o,Nt)}}async function Xs(e,t){try{await(await L(e)).hincrby(ro(e),t,1)}catch{}}async function Qs(e,t,n){if(ao(t))try{const o=await L(e),s=uo(n);await o.incrby(co(e),s?lo(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function ei(e){const t=await Ao();return t?(G=t,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}
29
29
  cachly: code ${t.userCode}
30
30
 
31
- `)}),yo(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(`
31
+ `)}),To(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
- `)}async function Es(e){if(!e)return!0;if(Yn(e))return!1;try{return await Kn(await O(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(!S&&await Be(ro))return J(e,t);if(!S){if(_s(e),Y){const c=await nt(Y);return c==="done"?J(e,t):c==="expired"?(A("device_flow_failed",{reason:"timeout"}),Y=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: **${Y.verifyUrl}**`,`Code: **${Y.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
- `)}return Hn({schluessel:S,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{F("sofort-test: Anfang");const c=await Ln({apiUrl:x,version:H,fristMs:ao}),p=c.art==="angelegt"?c.test:c.art==="vorhanden"&&c.instanzId?{apiKey:c.apiKey,instanzId:c.instanzId}:null;return F(`sofort-test: ${p?"Brain angelegt":"kein Test"}`),p&&He(p.instanzId,se(),je()),p},ablagen:{setzeSchluessel:c=>{S=c},setEmbedJwt:ae,saveApiKey:c=>ee(c),persistApiKeyToConfig:me,merkeInstanz:c=>{N=c,V=0},persistInstanceIdToConfig:ge},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>Is(e),neuesBrain:Re})}if(!t.instance_id){const c=await ot();c&&(t={...t,instance_id:c})}const n=await As(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&&Cs(t.instance_id,e),F(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await Lo(e,t,O,L);if(F(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&Ts(t.instance_id,e,String(s??"")),!ke&&S&&(ke=!0,wt("first_call_success")||(vt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""})));const c=t.instance_id??N??"",p={instance_id:c};if(e==="recall_best_solution")A("recall_best_solution",p);else if(e==="learn_from_attempts")A("learn_from_attempts",p);else if(e==="session_start"){A("session_start",p,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const g=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=g.includes("Welcome! Your AI Brain is live.");if(!Wn(c)){if(!C&&g.length>100)A("recall_best_solution",p);else if(C&&t.workspace_path&&await Es(c))try{const _=await Le("brain_from_git",{instance_id:c,repo_path:t.workspace_path,limit:50},O,L);if(_!==null){A("brain_from_git",{...p,...we??{}}),A("recall_best_solution",p);let I="";if((we?.total??0)===0)try{const M=await Me("brain_seed_starter",{instance_id:c},O,L);M&&(A("brain_seed_starter",{...p,auto:!0},{seeded_count:16,auto:!0}),I=`
33
+ `)}async function ti(e){if(!e)return!0;if(fs(e))return!1;try{return await ys(await L(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(W()&&!we())return Ue;if(!we()&&await Me(bo))return J(e,t);if(!we()){if(Ks(e),G){const l=await ut(G);return l==="done"?J(e,t):l==="expired"?(A("device_flow_failed",{reason:"timeout"}),G=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: **${G.verifyUrl}**`,`Code: **${G.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
+ `)}return cs({schluessel:S,konfigurierteInstanz:P,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const l=await rs({apiUrl:x,version:H,fristMs:wo}),m=l.art==="angelegt"?l.test:l.art==="vorhanden"&&l.instanzId?{apiKey:l.apiKey,instanzId:l.instanzId}:null;return Y(`sofort-test: ${m?"Brain angelegt":"kein Test"}`),m&&Ye(m.instanzId,re(),He()),m},ablagen:{setzeSchluessel:l=>{S=l},setEmbedJwt:oe,saveApiKey:l=>ne(l),persistApiKeyToConfig:pe,merkeInstanz:l=>{P=l,Q=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>ei(e),neuesBrain:Le})}if(!t.instance_id){const l=await dt();l&&(t={...t,instance_id:l})}const n=await Zs(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&&Xs(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await an(e,t,L,O);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&Qs(t.instance_id,e,String(s??"")),!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??P??""})));const l=t.instance_id??P??"",m={instance_id:l};if(e==="recall_best_solution")A("recall_best_solution",m);else if(e==="learn_from_attempts")A("learn_from_attempts",m);else if(e==="session_start"){A("session_start",m,{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(!ms(l)){if(!C&&h.length>100)A("recall_best_solution",m);else if(C&&t.workspace_path&&await ti(l))try{const k=await Je("brain_from_git",{instance_id:l,repo_path:t.workspace_path,limit:50},L,O);if(k!==null){A("brain_from_git",{...m,...$e??{}}),A("recall_best_solution",m);let R="";if(($e?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:l},L,O);M&&(A("brain_seed_starter",{...m,auto:!0},{seeded_count:16,auto:!0}),R=`
35
35
  ---
36
- `+String(M))}catch{}const E=String(_),$=we?.total??0,R=$>0?`
37
- \u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(E||I||R)return String(s)+R+`
36
+ `+String(M))}catch{}const I=String(k),$=$e?.total??0,E=$>0?`
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
- `+E+I}}catch(_){return A("brain_from_git_failed",{...p,reason:_ instanceof Error?_.message.slice(0,120):"unknown"}),String(s)+`
39
+ `+I+R}}catch(k){return A("brain_from_git_failed",{...m,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",p);else if(e==="smart_recall"){const g=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=g.length>50&&!g.includes("No lessons found")&&!g.includes("no lessons")&&!g.includes("No matches found");if(A("smart_recall",p,{hit:C,topic:String(t.query??"").slice(0,80)}),C&&A("recall_best_solution",p),ie&&typeof s=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ie.split(`
42
+ > Run \`brain_from_git(instance_id="`+l+'", 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",m);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",m,{hit:C,topic:String(t.query??"").slice(0,80)}),C&&A("recall_best_solution",m),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 Oo(e,t,O,L);if(i!==null)return!ke&&S&&(ke=!0,wt("first_call_success")||(vt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const a=await Ho(e,t,O,L);if(a!==null)return a;const r=await Mo(e,t,O,L);if(r!==null)return r;const d=c=>o?c+o:c,f=await Do(e,t,O,L);if(f!==null)return d(f);const l=await zo(e,t,O,L);if(l!==null)return l;const u=await Uo(e,t,O,L);if(u!==null)return d(u);const y=await Wo(e,t,O,L);if(y!==null){if(e==="brain_predict"){const p={instance_id:t.instance_id??N??""};A("brain_predict",p)}return d(y)}const b=await Me(e,t,O,L);if(b!==null)return b;const v=await ys(e,t,O,L);if(v!==null)return v;const m=await Le(e,t,O,L);if(m!==null){const p={instance_id:t.instance_id??N??""};if(e==="brain_from_git"){const g=we;A("brain_from_git",{...p,...g??{}},g?{fixes:g.fixes,features:g.features,refactors:g.refactors,total:g.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",p);return m}switch(e){case"get_api_status":{let c="unknown";try{const _=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(_.ok){const k=await _.json();c=`${k.status??"ok"} (db: ${k.db??"?"})`}else c=`HTTP ${_.status}`}catch(_){c=`unreachable: ${_.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \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 p="\u274C invalid JWT format";try{const _=S.split(".");if(_.length===3){const k=JSON.parse(Buffer.from(_[1],"base64url").toString("utf-8")),I=k.sub??"(unknown)",E=k.iss??"(unknown)",$=E.includes("keycloak")?"Keycloak":"OIDC",R=k.exp?new Date(k.exp*1e3):null,M=R?R<new Date:!1;p=["\u2705 JWT decoded",` Sub (user ID): ${I}`,` Provider: ${$}`,` Issuer: ${E}`,` Expires: ${R?R.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
- `)}}catch{p="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let g="";try{const k=(await L("/api/v1/instances")).data??[];if(k.length===0)g=`
45
+ ${s}`}return s}const i=await cn(e,t,L,O);if(i!==null)return!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??P??""}))),i;const r=await ln(e,t,L,O);if(r!==null)return r;const a=await dn(e,t,L,O);if(a!==null)return a;const u=l=>o?l+o:l,p=await un(e,t,L,O);if(p!==null)return u(p);const c=await pn(e,t,L,O);if(c!==null)return c;const d=await mn(e,t,L,O);if(d!==null)return u(d);const f=await gn(e,t,L,O);if(f!==null){if(e==="brain_predict"){const m={instance_id:t.instance_id??P??""};A("brain_predict",m)}return u(f)}const y=await Ke(e,t,L,O);if(y!==null)return y;const w=await Us(e,t,L,O);if(w!==null)return w;const g=await Je(e,t,L,O);if(g!==null){const m={instance_id:t.instance_id??P??""};if(e==="brain_from_git"){const h=$e;A("brain_from_git",{...m,...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",m);return g}switch(e){case"get_api_status":{let l="unknown";try{const k=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();l=`${_.status??"ok"} (db: ${_.db??"?"})`}else l=`HTTP ${k.status}`}catch(k){l=`unreachable: ${k.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${l}`," \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 m="\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;m=["\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{m="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const _=(await O("/api/v1/instances")).data??[];if(_.length===0)h=`
48
48
 
49
- \u{1F9E0} **Brain Instances:** none \u2014 create one at ${j("/instances","api-status")}`;else{const I=[`
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 E of k){const $=E.status==="running"?"\u{1F7E2}":E.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",R=E.id===N?" \u2190 active":"";if(I.push(` ${$} **${E.name}** (\`${E.id}\`) \xB7 ${E.status}${R}`),E.status==="running"&&E.host){const M=X.get(E.id);if(M)try{await M.ping(),I.push(" \u{1F493} Redis: connected")}catch{I.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else I.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else E.status==="provisioning"?I.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):E.status!=="running"&&I.push(` \u274C Not reachable (status: ${E.status})`)}g=I.join(`
52
- `)}}catch(_){g=`
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===P?" \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(`
52
+ `)}}catch(k){h=`
53
53
 
54
- \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${_.message}`}await Pe();const C=Ie(S),w=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: ${x}`,` \u{1F493} Health: ${c}`,` ${w}`,"","\u{1F511} **Auth:**",p,g].join(`
56
- `)}default:throw new Ct(`Unknown tool: ${e}`)}}class Ct extends Error{}const Tt=`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.
54
+ \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await De();const C=Ne(S),v=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: ${x}`,` \u{1F493} Health: ${l}`,` ${v}`,"","\u{1F511} **Auth:**",m,h].join(`
56
+ `)}default:throw new Lt(`Unknown tool: ${e}`)}}class Lt extends Error{}const Ht=`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
 
@@ -63,33 +63,33 @@ This project has a Cachly AI Brain \u2014 persistent, cross-session memory of pa
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.`,It={tools:{},resources:{},prompts:{}},Et=async()=>{const{katalog:e,unbekannteKernnamen:t}=ss(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Rt(){return{resources:[]}}async function jt(){return{resourceTemplates:[]}}async function Bt(){return{prompts:[]}}function Rs(e){e.setRequestHandler(Qe,Et),e.setRequestHandler(qe,Ot),e.setRequestHandler(Ze,Rt),e.setRequestHandler(Ve,jt),e.setRequestHandler(Ge,Bt)}function js(){const e=new Ke({name:"cachly-mcp",version:H},{capabilities:It,instructions:Tt});return Rs(e),Nt(e),e}function Nt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),Wt(n?.name,n?.version)}catch{}$t||($t=!0,A("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const K=new Ke({name:"cachly-mcp",version:H},{capabilities:It,instructions:Tt});Nt(K),K.setRequestHandler(Qe,Et),K.setRequestHandler(Ze,Rt),K.setRequestHandler(Ve,jt),K.setRequestHandler(Ge,Bt);let Se=null,de=!1,te=null,Pt=0;async function Bs(e){if(!de){if(te){await te;return}te=(async()=>{de=!0,Se=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{te=null}})(),await te,Lt(e)}}function Ns(e){de=!0,Se=e}function Lt(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 De(){if(!(!de||!Se)){de=!1;try{await J("session_end",{instance_id:Se,summary:`Auto-ended after ${Pt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Ot=async e=>{let{name:t,arguments:n}=e.params;if(t===bt){const i=n??{},a=typeof i.tool=="string"?i.tool:"";if(!a)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const r=le.find(d=>d.name===a);if(!r)return{content:[{type:"text",text:`Kein Werkzeug namens "${a}". Die Liste steht in der Beschreibung von ${bt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:r.name,description:r.description,inputSchema:r.inputSchema},null,2)}]};t=a,n=i.arguments??{}}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=le.find(r=>r.name===t),a=i?is(t,i.inputSchema,n??{}):null;if(a)return{content:[{type:"text",text:a}],isError:!0}}const o=$e(n?.instance_id)||N||$e(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=Mn(t,{gestartet:de,startetGerade:te!==null,instanz:o});s==="starten"?await Bs(o).catch(()=>{}):s==="abwarten"?await te?.catch(()=>{}):s==="als-gestartet-merken"&&Ns(o),Dn.has(t)||Pt++;try{os(),F(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return F(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Lt(o),{content:[{type:"text",text:bn(t,i)+qn()+es(t)}]}}catch(i){if(i instanceof Ct)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Q)throw i;const a=i.message??String(i);throw Fe("cachly","tool_error",{tool:t,error:a}).catch(()=>{}),new Q(ne.InternalError,a)}};K.setRequestHandler(qe,Ot),process.on("SIGTERM",async()=>{await De().catch(()=>{});for(const[,e]of X)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await De().catch(()=>{});for(const[,e]of X)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.`,Mt={tools:{},resources:{},prompts:{}},zt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Ts(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Dt(){return{resources:[]}}async function Ut(){return{resourceTemplates:[]}}async function Wt(){return{prompts:[]}}function oi(e){e.setRequestHandler(rt,zt),e.setRequestHandler(ot,Kt),e.setRequestHandler(it,Dt),e.setRequestHandler(st,Ut),e.setRequestHandler(nt,Wt)}function ni(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Mt,instructions:Ht});return oi(e),Jt(e),e}function Jt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),Qt(n?.name,n?.version)}catch{}Bt||(Bt=!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:Mt,instructions:Ht});Jt(q),q.setRequestHandler(rt,zt),q.setRequestHandler(it,Dt),q.setRequestHandler(st,Ut),q.setRequestHandler(nt,Wt);let Re=null,de=!1,se=null,Ft=0;async function si(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,Yt(e)}}function ii(e){de=!0,Re=e}function Yt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await L(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 ${Ft} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Kt=async e=>{let{name:t,arguments:n}=e.params;if(t===Tt){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(u=>u.name===r);if(!a)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${Tt}.`}],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(!Do(t))return{content:[{type:"text",text:Uo(t)}],isError:!0};const r=Wo(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?Is(t,i.inputSchema,n??{}):null;if(r)return{content:[{type:"text",text:r}],isError:!0}}const o=Ie(n?.instance_id)||P||Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":ls(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await si(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&ii(o),!W()&&!ds.has(t)&&Ft++;try{As(),Y(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Yt(o),{content:[{type:"text",text:Un(t,i)+bs()+ks(t)}]}}catch(i){if(i instanceof Lt)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,Kt),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 Ps(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 Ht="https://api.cachly.dev";function Z(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==Ht&&(o.CACHLY_API_URL=x),o}function Ls(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:Z(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Z(e,t)},settings:{}}}},null,2):Mt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Z(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Z(e,t)}}},null,2)}function Mt(e){return ce[e]===".vscode/mcp.json"}function he(e,t){Sn(e)||ee(e,t)}async function Dt(e,t,n,o,s,i={}){const a={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Z(t,n)};if(!s.existsSync(e))return Ls(t,n,o);let r={};try{r=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:u}=await import("node:fs/promises");await u(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 u=r.experimental??{},y=u.modelContextProtocolServers??[];let b;for(const m of y){const c=m.env??{};if(c.CACHLY_JWT){b=c.CACHLY_JWT;break}}b&&he(b,i);const v=y.filter(m=>{const c=m.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:a.env}),r.experimental={...u,modelContextProtocolServers:v},JSON.stringify(r,null,2)}if(o==="zed"){const u=r.context_servers??{},b=u.cachly?.command?.env?.CACHLY_JWT;return b&&he(b,i),u.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:a.env},settings:{}},r.context_servers=u,JSON.stringify(r,null,2)}if(Mt(o)){const u=r.mcpServers??void 0,b=u?.cachly?.env?.CACHLY_JWT;b&&he(b,i),u&&"cachly"in u&&(delete u.cachly,Object.keys(u).length===0&&delete r.mcpServers);const v=r.servers??{},m=v.cachly,c=m?.env?.CACHLY_JWT;return c&&he(c,i),v.cachly=m?.envFile?{type:"stdio",...a,envFile:m.envFile}:{type:"stdio",...a},r.servers=v,JSON.stringify(r,null,2)}const d=r.mcpServers??{},l=d.cachly?.env?.CACHLY_JWT;return l&&he(l,i),d.cachly=a,r.mcpServers=d,JSON.stringify(r,null,2)}async function zt(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:a}=await import("node:os"),r=n??a(),d=Zo.filter(u=>Xo(u,e,r,s,i,o)).map(u=>({path:i(e,...u.pfad),prefix:u.prefix})),f=lt(t),l={};for(const{path:u,prefix:y}of d)try{l[u]=await Qo(u,f,y)}catch(b){l[u]=`failed:${b.message}`}return l}function Ut(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=G(),t=z();(!e||!t)&&(console.log(`
68
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function ri(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 Gt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==Gt&&(o.CACHLY_API_URL=x),o}function ai(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 fe(e,t){qn(e)||ne(e,t)}async function Vt(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 ai(t,n,o);let a={};try{a=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:d}=await import("node:fs/promises");await d(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 d=a.experimental??{},f=d.modelContextProtocolServers??[];let y;for(const g of f){const l=g.env??{};if(l.CACHLY_JWT){y=l.CACHLY_JWT;break}}y&&fe(y,i);const w=f.filter(g=>{const l=g.env??{};return!l.CACHLY_JWT&&!l.CACHLY_BRAIN_INSTANCE_ID});return w.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...d,modelContextProtocolServers:w},JSON.stringify(a,null,2)}if(o==="zed"){const d=a.context_servers??{},y=d.cachly?.command?.env?.CACHLY_JWT;return y&&fe(y,i),d.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=d,JSON.stringify(a,null,2)}if(qt(o)){const d=a.mcpServers??void 0,y=d?.cachly?.env?.CACHLY_JWT;y&&fe(y,i),d&&"cachly"in d&&(delete d.cachly,Object.keys(d).length===0&&delete a.mcpServers);const w=a.servers??{},g=w.cachly,l=g?.env?.CACHLY_JWT;return l&&fe(l,i),w.cachly=g?.envFile?{type:"stdio",...r,envFile:g.envFile}:{type:"stdio",...r},a.servers=w,JSON.stringify(a,null,2)}const u=a.mcpServers??{},c=u.cachly?.env?.CACHLY_JWT;return c&&fe(c,i),u.cachly=r,a.mcpServers=u,JSON.stringify(a,null,2)}async function Zt(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(),u=_n.filter(d=>kn(d,e,a,s,i,o)).map(d=>({path:i(e,...d.pfad),prefix:d.prefix})),p=yt(t),c={};for(const{path:d,prefix:f}of u)try{c[d]=await $n(d,p,f)}catch(y){c[d]=`failed:${y.message}`}return c}function Xt(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(`
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(`${x}/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,a=Math.round(o.iq_boost_pct??0),r=(o.top_lessons??[]).slice(0,5),d=o.team_authors??[],f=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}",u=new Date,y=new Date(u);y.setDate(u.getDate()-7);const b=p=>p.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${b(y)} \u2013 ${b(u)}\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(a).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(f/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`)),r.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 p of r){const g=`${p.topic}: ${p.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${g.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=r[0],m=[`\u{1F9E0} My AI Brain weekly digest (${b(y)} \u2013 ${b(u)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${i} recalls \xB7 ~${Math.round(f/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(m);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const p of m.split(`
76
- `))console.log(` ${p}`);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(`${x}/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),u=o.team_authors??[],p=i*1200,c=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}",d=new Date,f=new Date(d);f.setDate(d.getDate()-7);const y=m=>m.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${y(f)} \u2013 ${y(d)}\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${c.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(p/1e3)+"K (est.)").padEnd(42)}\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"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${u.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 m of a){const h=`${m.topic}: ${m.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 w=a[0],g=[`\u{1F9E0} My AI Brain weekly digest (${y(f)} \u2013 ${y(d)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${i} recalls \xB7 ~${Math.round(p/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${c}`,w?` \u{1F525} Top lesson: "${w.topic}: ${w.what_worked.slice(0,60)}${w.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
75
+ `),l="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 m of g.split(`
76
+ `))console.log(` ${m}`);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${l.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
- `),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=f=>{const l=o.indexOf(`--${f}`);return l!==-1?o[l+1]:void 0},i=s("format")??"both";i!=="md"&&i!=="jsonl"&&i!=="both"&&(console.log(`
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=p=>{const c=o.indexOf(`--${p}`);return c!==-1?o[c+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.
80
- `),process.exit(1));const a=n(s("out")??"."),r=S||Oe()||"",d=z();(!r||!d)&&(console.log(`
80
+ `),process.exit(1));const r=n(s("out")??"."),a=S||Fe()||"",u=U();(!a||!u)&&(console.log(`
81
81
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
82
82
  `),process.exit(1)),process.stdout.write(`
83
83
  \u{1F4E4} Exporting your Brain...
84
84
 
85
- `);try{let f=[],l="";const u=await fetch(`${x}/api/v1/instances/${d}/export`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(12e4)});if(u.ok){const b=await u.json();f=(b.lessons??[]).map(cs).filter(v=>v!==null),b.complete===!1?l=b.note??"the server reported an incomplete read":typeof b.lesson_count=="number"&&f.length<b.lesson_count&&(l=`the server counts ${b.lesson_count} lessons, but only ${f.length} could be read as lessons`)}else if(u.status===404){const b=await fetch(`${x}/api/v1/instances/${d}/memory`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(8e3)});if(!b.ok)throw new Error(`memory HTTP ${b.status}`);f=((await b.json()).top_lessons??[]).map(m=>({topic:m.topic,outcome:m.outcome,severity:m.severity,tags:m.tags,whatWorked:m.what_worked,ts:m.ts,author:m.author,recallCount:m.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 ${u.status}`);f.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
- `),process.exit(0)),await t(a,{recursive:!0});const y=[];if(i==="md"||i==="both"){const b=n(a,"lessons.md");await e(b,rs(f),"utf-8"),y.push(`${f.length} lesson${f.length===1?"":"s"} \u2192 ${b}`)}if(i==="jsonl"||i==="both"){const b=n(a,"lessons.jsonl");await e(b,as(f),"utf-8"),y.push(`${f.length} lesson${f.length===1?"":"s"} \u2192 ${b}`)}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 b of y)console.log(` ${b}`);console.log("")}catch(f){console.log(`
87
- \u274C Could not export your Brain: ${f.message}
88
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=G(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
85
+ `);try{let p=[],c="";const d=await fetch(`${x}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(d.ok){const y=await d.json();p=(y.lessons??[]).map(js).filter(w=>w!==null),y.complete===!1?c=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&p.length<y.lesson_count&&(c=`the server counts ${y.lesson_count} lessons, but only ${p.length} could be read as lessons`)}else if(d.status===404){const y=await fetch(`${x}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new Error(`memory HTTP ${y.status}`);p=((await y.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})),c="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 ${d.status}`);p.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
+ `),process.exit(0)),await t(r,{recursive:!0});const f=[];if(i==="md"||i==="both"){const y=n(r,"lessons.md");await e(y,Es(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}if(i==="jsonl"||i==="both"){const y=n(r,"lessons.jsonl");await e(y,Rs(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}c?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${c}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(p){console.log(`
87
+ \u274C Could not export your Brain: ${p.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(`
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
92
- `),process.exit(1));const n=z();n||(console.log(`
92
+ `),process.exit(1));const n=U();n||(console.log(`
93
93
  \u26A0\uFE0F No Brain selected. Set CACHLY_BRAIN_INSTANCE_ID or run:`),console.log(` npx @cachly-dev/mcp-server@latest setup
94
94
  `),process.exit(1));try{const o=await fetch(`${x}/api/v1/instances/${encodeURIComponent(n)}/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({email:t}),signal:AbortSignal.timeout(15e3)});if(o.status===400&&(console.log(`
95
95
  \u274C "${t}" is not a valid email address.
@@ -97,56 +97,56 @@ Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Ex
97
97
  \u274C This Brain was not found in your account. Only the owner of a Brain can invite people.`),console.log(` Brain: ${n}
98
98
  `),process.exit(1)),o.status===409&&(console.log(`
99
99
  \u2139\uFE0F ${t} already has access to this Brain. Nothing was sent.
100
- `),process.exit(1)),!o.ok)throw new Error(`HTTP ${o.status}`);const s=await o.json(),i=s.invite_sent_to??t,a=s.instance?.name??n;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${i}\x1B[0m`),console.log(` Brain: \x1B[1m${a}\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(`
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=G();e||(console.log(`
102
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=X();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(`${x}/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
 
106
- You get a free Brain: ${o}`,a=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
106
+ You get a free Brain: ${o}`,r=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
107
107
 
108
108
  Try it free: ${o}
109
109
 
110
- @cachlydev`);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 \u{1F9E0} Your cachly referral link \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 ${o.padEnd(61)}\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"),s>0&&(console.log(`\u2502 \x1B[32m\u2713 ${s} developer${s===1?"":"s"} joined via your link so far\x1B[0m`.padEnd(72)+"\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[33mSlack / DM message:\x1B[0m \u2502"),console.log("\u2502 \u2502");for(const r of i.split(`
111
- `))console.log(`\u2502 \x1B[90m${r.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \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[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${a.slice(0,10)}... \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(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("\x1B[2m To give someone access to your Brain: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log("")}catch(t){console.log(`
110
+ @cachlydev`);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 \u{1F9E0} Your cachly referral link \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 ${o.padEnd(61)}\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"),s>0&&(console.log(`\u2502 \x1B[32m\u2713 ${s} developer${s===1?"":"s"} joined via your link so far\x1B[0m`.padEnd(72)+"\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[33mSlack / DM message:\x1B[0m \u2502"),console.log("\u2502 \u2502");for(const a of i.split(`
111
+ `))console.log(`\u2502 \x1B[90m${a.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \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[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${r.slice(0,10)}... \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(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("\x1B[2m To give someone access to your Brain: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log("")}catch(t){console.log(`
112
112
  \u274C Could not fetch referral link: ${t.message}
113
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{homedir:a}=await import("node:os"),{createInterface:r}=await import("node:readline"),d=dt(process.argv,"brain"),f=d===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!f&&!d&&(console.log(`
113
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{homedir:r}=await import("node:os"),{createInterface:a}=await import("node:readline"),u=vt(process.argv,"brain"),p=u===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!p&&!u&&(console.log(`
114
114
  \u274C Usage: npx @cachly-dev/mcp-server@latest join <token>`),console.log(` npx @cachly-dev/mcp-server@latest join --brain <instance-id>
115
115
  `),console.log(" The token is in the invitation email. A teammate sends one with:"),console.log(` npx @cachly-dev/mcp-server@latest invite <email>
116
- `),process.exit(1));let l=S;if(!l){console.log(`
116
+ `),process.exit(1));let c=S;if(!c){console.log(`
117
117
  No API key found \u2014 starting sign-in (10 seconds)...
118
- `);try{const g=await fetch(`${x}/api/v1/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(1e4)});if(g.ok){const C=await g.json();console.log(` \u{1F449} Open: \x1B[36m${C.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${C.user_code}\x1B[0m
119
- `);const w=(C.interval??5)*1e3;for(let _=0;_<24;_++){await new Promise(k=>setTimeout(k,w));try{const k=await fetch(`${x}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:C.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(k.ok){const I=await k.json();if(I.access_token){l=I.access_token;break}}}catch{}}l||(console.log(`
118
+ `);try{const h=await fetch(`${x}/api/v1/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(1e4)});if(h.ok){const C=await h.json();console.log(` \u{1F449} Open: \x1B[36m${C.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${C.user_code}\x1B[0m
119
+ `);const v=(C.interval??5)*1e3;for(let k=0;k<24;k++){await new Promise(_=>setTimeout(_,v));try{const _=await fetch(`${x}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:C.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(_.ok){const R=await _.json();if(R.access_token){c=R.access_token;break}}}catch{}}c||(console.log(`
120
120
  \u274C Sign-in timed out. Run the command again.
121
121
  `),process.exit(1)),console.log(` \u2705 Signed in!
122
- `)}}catch(g){console.log(`
123
- \u26A0\uFE0F Could not start sign-in: ${g.message}`),console.log(` Set CACHLY_JWT manually from ${j("/setup-ai","join")}
124
- `),process.exit(1)}}l||(console.log(`
122
+ `)}}catch(h){console.log(`
123
+ \u26A0\uFE0F Could not start sign-in: ${h.message}`),console.log(` Set CACHLY_JWT manually from ${j("/setup-ai","join")}
124
+ `),process.exit(1)}}c||(console.log(`
125
125
  \u274C Sign-in did not return a key. Run the command again.
126
- `),process.exit(1));const u={Authorization:`Bearer ${l}`};let y="",b="";if(d){console.log(`
127
- \u23F3 Checking access to Brain ${d}...`);try{const g=await fetch(`${x}/api/v1/instances/${encodeURIComponent(d)}`,{headers:u,signal:AbortSignal.timeout(1e4)});g.status===401&&(console.log(`
126
+ `),process.exit(1));const d={Authorization:`Bearer ${c}`};let f="",y="";if(u){console.log(`
127
+ \u23F3 Checking access to Brain ${u}...`);try{const h=await fetch(`${x}/api/v1/instances/${encodeURIComponent(u)}`,{headers:d,signal:AbortSignal.timeout(1e4)});h.status===401&&(console.log(`
128
128
  \u274C Your key was not accepted. Sign in again: npx @cachly-dev/mcp-server@latest autopilot
129
- `),process.exit(1)),(g.status===403||g.status===404)&&(console.log(`
129
+ `),process.exit(1)),(h.status===403||h.status===404)&&(console.log(`
130
130
  \u274C You do not have access to this Brain (or it does not exist).`),console.log(` Ask the owner for an invitation: invite <your-email>. Accept it, then run this command again.
131
- `),process.exit(1)),g.ok||(console.log(`
132
- \u274C Could not check the Brain: HTTP ${g.status}
133
- `),process.exit(1));const C=await g.json();y=C.id??d,b=C.name??y}catch(g){console.log(`
134
- \u274C Network error: ${g.message}
131
+ `),process.exit(1)),h.ok||(console.log(`
132
+ \u274C Could not check the Brain: HTTP ${h.status}
133
+ `),process.exit(1));const C=await h.json();f=C.id??u,y=C.name??f}catch(h){console.log(`
134
+ \u274C Network error: ${h.message}
135
135
  `),process.exit(1)}}else{console.log(`
136
- \u23F3 Accepting invitation...`);let g=null,C="";try{const k=await fetch(`${x}/api/v1/orgs/accept-invite`,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({token:f}),signal:AbortSignal.timeout(15e3)});if(k.ok){const I=await k.json();g=I.data&&typeof I.data=="object"?I.data:I}else C=k.status===401?"your key was not accepted (HTTP 401)":`HTTP ${k.status}`}catch(k){console.log(`
137
- \u274C Network error: ${k.message}
138
- `),process.exit(1)}if(!g){let k=!1;try{k=(await fetch(`${x}/api/invite/${encodeURIComponent(f)}`,{signal:AbortSignal.timeout(8e3)})).ok}catch{}k?(console.log(`
136
+ \u23F3 Accepting invitation...`);let h=null,C="";try{const _=await fetch(`${x}/api/v1/orgs/accept-invite`,{method:"POST",headers:{...d,"Content-Type":"application/json"},body:JSON.stringify({token:p}),signal:AbortSignal.timeout(15e3)});if(_.ok){const R=await _.json();h=R.data&&typeof R.data=="object"?R.data:R}else C=_.status===401?"your key was not accepted (HTTP 401)":`HTTP ${_.status}`}catch(_){console.log(`
137
+ \u274C Network error: ${_.message}
138
+ `),process.exit(1)}if(!h){let _=!1;try{_=(await fetch(`${x}/api/invite/${encodeURIComponent(p)}`,{signal:AbortSignal.timeout(8e3)})).ok}catch{}_?(console.log(`
139
139
  \u274C This old link type does not give access to the Brain.`),console.log(` Ask the owner for a new invitation: npx @cachly-dev/mcp-server@latest invite <your-email>
140
140
  `)):(console.log(`
141
141
  \u274C Could not accept the invitation: ${C}.`),console.log(` The token may be wrong, expired or already used. Ask for a new invitation.
142
- `)),process.exit(1)}const w=(g.instances??[]).filter(k=>k&&k.id);w.length===0&&(console.log(`
142
+ `)),process.exit(1)}const v=(h.instances??[]).filter(_=>_&&_.id);v.length===0&&(console.log(`
143
143
  \u2705 Invitation accepted, but this organisation has no Brain yet.`),console.log(` When the owner adds one, connect it with: npx @cachly-dev/mcp-server@latest join --brain <instance-id>
144
- `),process.exit(0));let _=w[0];if(w.length>1){console.log(`
145
- This organisation has several Brains:`),w.forEach(($,R)=>console.log(` ${R+1}) ${$.name??$.id} (${$.id})`));const k=r({input:process.stdin,output:process.stdout}),I=await new Promise($=>{k.question(" Which one? [1] ",R=>{k.close(),$(R.trim()||"1")})}),E=Number.parseInt(I,10);(!Number.isInteger(E)||E<1||E>w.length)&&(console.log(`
144
+ `),process.exit(0));let k=v[0];if(v.length>1){console.log(`
145
+ This organisation has several Brains:`),v.forEach(($,E)=>console.log(` ${E+1}) ${$.name??$.id} (${$.id})`));const _=a({input:process.stdin,output:process.stdout}),R=await new Promise($=>{_.question(" Which one? [1] ",E=>{_.close(),$(E.trim()||"1")})}),I=Number.parseInt(R,10);(!Number.isInteger(I)||I<1||I>v.length)&&(console.log(`
146
146
  Cancelled.
147
- `),process.exit(1)),_=w[E-1]}y=_.id,b=_.name??_.id,console.log(`
148
- \u2705 Invitation accepted. Brain: \x1B[1m${b}\x1B[0m
149
- `)}l!==S&&ee(l);const v=process.cwd(),m=a(),c=[{label:".mcp.json (Claude Code project)",path:s(v,".mcp.json")},{label:".cursor/mcp.json",path:s(v,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:s(v,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:s(v,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(m,".claude","mcp.json"),global:!0}];let p=0;for(const{label:g,path:C,global:w}of c){const _=i(C);if(!(!w&&!o(_)&&!o(C)))try{await n(_,{recursive:!0});let k={};if(o(C))try{k=JSON.parse(await t(C,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(C,C+".bak")}catch{}}const I=k.mcpServers??{},E=I.cachly??{},$=E.env??{};$.CACHLY_BRAIN_INSTANCE_ID=y,l&&w&&!$.CACHLY_JWT&&($.CACHLY_JWT=l),x!==Ht&&($.CACHLY_API_URL=x),I.cachly={...E,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},k.mcpServers=I,await e(C,JSON.stringify(k,null,2),"utf-8"),console.log(` \u2705 ${g}`),p++}catch(k){k.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${g}: ${k.message}`)}}console.log(""),p===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${b}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
147
+ `),process.exit(1)),k=v[I-1]}f=k.id,y=k.name??k.id,console.log(`
148
+ \u2705 Invitation accepted. Brain: \x1B[1m${y}\x1B[0m
149
+ `)}c!==S&&ne(c);const w=process.cwd(),g=r(),l=[{label:".mcp.json (Claude Code project)",path:s(w,".mcp.json")},{label:".cursor/mcp.json",path:s(w,".cursor","mcp.json")},{label:"~/.codeium/windsurf/mcp_config.json (Windsurf)",path:Se("windsurf",he())},{label:"cline_mcp_settings.json (Cline)",path:Se("cline",he())},{label:".vscode/mcp.json (Copilot)",path:s(w,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(g,".claude","mcp.json"),global:!0}];let m=0;for(const{label:h,path:C,global:v}of l){const k=i(C);if(!(!v&&!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=f,c&&v&&!$.CACHLY_JWT&&($.CACHLY_JWT=c),x!==Gt&&($.CACHLY_API_URL=x),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}`),m++}catch(_){_.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${h}: ${_.message}`)}}console.log(""),m===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${y}\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,174 +154,174 @@ 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"),a=process.argv.slice(3).find(f=>!f.startsWith("--")),r=t(e(import.meta.url)),d=a?n(process.cwd(),a):n(r,"bench","external","sample-corpus.json");try{const f=await o(d),l=await s(f);i&&(console.log(JSON.stringify({corpus:f.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 u=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),y=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),b=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),v=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",m=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 : ${f.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}${u}%\x1B[0m`),console.log(` MRR : ${m}${y}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${b}%\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}${u}% 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(f){console.error(`
158
- \u274C bench failed: ${f.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(p=>!p.startsWith("--")),a=t(e(import.meta.url)),u=r?n(process.cwd(),r):n(a,"bench","external","sample-corpus.json");try{const p=await o(u),c=await s(p);i&&(console.log(JSON.stringify({corpus:p.name,lessons:c.corpusSize,queries:c.queryCount,cachly_p1:Math.round(c.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(c.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(c.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(c.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((c.cachly.precisionAt1-c.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((c.cachly.mrr-c.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const d=((c.cachly.precisionAt1-c.flatfile.precisionAt1)*100).toFixed(1),f=((c.cachly.mrr-c.flatfile.mrr)*100).toFixed(1),y=((c.cachly.precisionAt1-c.baseline.precisionAt1)*100).toFixed(1),w=c.cachly.precisionAt1>=c.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",g=c.cachly.mrr>=c.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 : ${p.name??u}`),console.log(` Dataset: ${c.corpusSize} lessons \xB7 ${c.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${(c.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(c.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(c.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${(c.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(c.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(c.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 : ${w}${d}%\x1B[0m`),console.log(` MRR : ${g}${f}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${y}%\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 ${(c.cachly.precisionAt1*100).toFixed(1)}% (${w}${d}% vs flat-file memory, ${c.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(p){console.error(`
158
+ \u274C bench failed: ${p.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
161
161
  `),e(n(s,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
162
162
  `),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
163
- `),process.exit(0));let i="";try{i=ut(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let a=o(s);try{const $=JSON.parse(t(n(s,"package.json"),"utf-8"));$.name&&(a=$.name.replace(/^@[^/]+\//,""))}catch{}let r="";try{r=ut(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
- `),process.exit(0)}const d=r.trim().split(`
165
- `).filter(Boolean).map($=>{const[R,M,Te,oe]=$.split("|||");return{sha:(R??"").trim().slice(0,8),subject:(M??"").trim(),date:(Te??"").trim(),author:(oe??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
- `),process.exit(0));const f=new Map,l=[],u=[],y=[],b=new Set;let v=0;for(const $ of d){const R=bs($.subject);f.set(R,(f.get(R)??0)+1),ws($.subject)&&v++,R==="fix"&&l.length<5&&l.push($.subject.slice(0,72)),R==="feat"&&u.length<5&&u.push($.subject.slice(0,72)),R==="security"&&y.length<3&&y.push($.subject.slice(0,72)),$.author&&b.add($.author)}const m=vs(d.map($=>$.subject)),c=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,p=m>=501?"Oracle":m>=201?"Architect":m>=51?"Expert":m>=11?"Explorer":"Apprentice",C=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${a}`;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(m).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(b.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${p.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 w=[...f.entries()].filter(([$])=>$!=="chore").sort(($,R)=>R[1]-$[1]),_=($,R)=>"\u2588".repeat(Math.round($/R*20)).padEnd(20),k=Math.max(...w.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,R]of w){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${_(R,k)}\x1B[0m \x1B[33m${String(R).padStart(3)}\x1B[0m \u2502`)}if(y.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 y)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(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"),console.log("\u2502 \x1B[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of u.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 I=new URLSearchParams({repo:a,commits:String(d.length),lessons:String(m),level:p,authors:String(b.size),reverts:String(v)}),E=j(`/preview?${I.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${E}\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=G(),t=z();(!e||!t)&&(console.log(`
163
+ `),process.exit(0));let i="";try{i=xt(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=xt(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
+ `),process.exit(0)}const u=a.trim().split(`
165
+ `).filter(Boolean).map($=>{const[E,M,Pe,ie]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(M??"").trim(),date:(Pe??"").trim(),author:(ie??"").trim()}});u.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
+ `),process.exit(0));const p=new Map,c=[],d=[],f=[],y=new Set;let w=0;for(const $ of u){const E=Ws($.subject);p.set(E,(p.get(E)??0)+1),Js($.subject)&&w++,E==="fix"&&c.length<5&&c.push($.subject.slice(0,72)),E==="feat"&&d.length<5&&d.push($.subject.slice(0,72)),E==="security"&&f.length<3&&f.push($.subject.slice(0,72)),$.author&&y.add($.author)}const g=Fs(u.map($=>$.subject)),l=`${u[u.length-1]?.date??"?"} \u2192 ${u[0]?.date??"?"}`,m=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(u.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${l.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(y.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${m.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(w).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 v=[...p.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...v.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of v){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(f.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 f)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(c.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 c.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(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[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of d.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(u.length),lessons:String(g),level:m,authors:String(y.size),reverts:String(w)}),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(`
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...
170
- `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,i=o.total_recall_count??0,a=Math.round(o.iq_boost_pct??0),r=i*1200,d=s===0?"Intern \u{1F331}":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}";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 \u{1F9E0} My AI Brain \xB7 powered by \x1B[35mcachly.dev\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 Lessons stored : \x1B[33m${String(s).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(a).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+(r/1e3).toFixed(0)+"K (est.)").padEnd(42)}\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 Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \u2502"),console.log("\u2502 Free \xB7 GDPR \xB7 German servers \u2502"),console.log("\u2502 \x1B[35mnpx @cachly-dev/mcp-server@latest autopilot\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 f=j("/","share"),l=`\u{1F9E0} My AI coding assistant now has persistent memory.
170
+ `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`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=i*1200,u=s===0?"Intern \u{1F331}":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}";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 \u{1F9E0} My AI Brain \xB7 powered by \x1B[35mcachly.dev\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 Lessons stored : \x1B[33m${String(s).padEnd(8)}\x1B[0m Brain level: \x1B[32m${u.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${("~"+(a/1e3).toFixed(0)+"K (est.)").padEnd(42)}\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 Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \u2502"),console.log("\u2502 Free \xB7 GDPR \xB7 German servers \u2502"),console.log("\u2502 \x1B[35mnpx @cachly-dev/mcp-server@latest autopilot\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 p=j("/","share"),c=`\u{1F9E0} My AI coding assistant now has persistent memory.
171
171
 
172
- ${s} lessons stored \xB7 ${i} recalls \xB7 ${d}
172
+ ${s} lessons stored \xB7 ${i} recalls \xB7 ${u}
173
173
 
174
174
  Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.
175
175
 
176
- ${f}
176
+ ${p}
177
177
 
178
- #AIMemory #ClaudeCode #Cursor #DeveloperTools`;console.log(" \x1B[1m\u{1F4CB} Share on Twitter/X (copy this):\x1B[0m"),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(l.split(`
179
- `).map(u=>` ${u}`).join(`
178
+ #AIMemory #ClaudeCode #Cursor #DeveloperTools`;console.log(" \x1B[1m\u{1F4CB} Share on Twitter/X (copy this):\x1B[0m"),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(c.split(`
179
+ `).map(d=>` ${d}`).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=G(),t=z();(!e||!t)&&(console.log(`
182
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=X(),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...
186
- `);try{const i=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let a=0,r=0;if(i.ok){const y=await i.json();a=y.lesson_count??0,r=y.total_recall_count??0}const d=await fetch(`${x}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:o,visibility:s?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!d.ok)throw new Error(`HTTP ${d.status}`);const l=(await d.json()).share_id??"unavailable",u=j(`/brain/share/${l}`,"publish");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 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\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 Title : \x1B[33m${o.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(a).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(r).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${s?"32":"33"}m${(s?"public (discoverable)":"unlisted (link only)").padEnd(44)}\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[1mShare URL:\x1B[0m \x1B[36m${u.padEnd(51)}\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[2mAnyone can import with:\x1B[0m \u2502"),console.log(`\u2502 \x1B[90m brain_import(instance_id="...", share_id="${l.slice(0,17)}")\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(""),console.log(" \x1B[1m\u{1F4CB} Share this with your team:\x1B[0m"),console.log(` ${u}`),console.log(""),console.log(` \x1B[2mTo list all your shares:\x1B[0m brain_share_list(instance_id="${t.slice(0,24)}...")`),console.log(` \x1B[2mTo revoke this share:\x1B[0m brain_unshare(share_id="${l.slice(0,24)}...")`),console.log("")}catch(i){console.log(`
186
+ `);try{const i=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let r=0,a=0;if(i.ok){const f=await i.json();r=f.lesson_count??0,a=f.total_recall_count??0}const u=await fetch(`${x}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:o,visibility:s?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);const c=(await u.json()).share_id??"unavailable",d=j(`/brain/share/${c}`,"publish");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 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\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 Title : \x1B[33m${o.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(r).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(a).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${s?"32":"33"}m${(s?"public (discoverable)":"unlisted (link only)").padEnd(44)}\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[1mShare URL:\x1B[0m \x1B[36m${d.padEnd(51)}\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[2mAnyone can import with:\x1B[0m \u2502"),console.log(`\u2502 \x1B[90m brain_import(instance_id="...", share_id="${c.slice(0,17)}")\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(""),console.log(" \x1B[1m\u{1F4CB} Share this with your team:\x1B[0m"),console.log(` ${d}`),console.log(""),console.log(` \x1B[2mTo list all your shares:\x1B[0m brain_share_list(instance_id="${t.slice(0,24)}...")`),console.log(` \x1B[2mTo revoke this share:\x1B[0m brain_unshare(share_id="${c.slice(0,24)}...")`),console.log("")}catch(i){console.log(`
187
187
  \u274C Could not publish Brain: ${i.message}
188
188
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="tool-specs"||process.argv[2]==="openapi"){const{renderToolSpecs:e}=await import("./toolspecs.js");let t="openapi";if(process.argv[2]!=="openapi"){const o=process.argv.find(s=>s.startsWith("--format="));if(o)t=o.slice(9);else{const s=process.argv.indexOf("--format");s!==-1&&(t=process.argv[s+1]??"openapi")}}const n=["openapi","openai","anthropic","langchain"];n.includes(t)||(process.stderr.write(`
189
189
  \u274C Unknown format "${t}". Use one of: ${n.join(", ")}
190
190
 
191
191
  `),process.exit(1)),process.stdout.write(e(le,t,H)+`
192
- `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=z();e||(console.log(`
192
+ `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=U();e||(console.log(`
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
- `),process.exit(1));const t=`${x}/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 fe=en(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(fe==="version"&&(process.stdout.write(`${H}
195
- `,()=>process.exit(0)),await new Promise(()=>{})),fe==="unbekannt"&&console.error(`
196
- Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||fe==="hilfe"||fe==="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(fe==="unbekannt"?1:0)}const Os={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:pn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:mn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function Hs(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=Os[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 a=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",r=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${a}${n}${r}: ${o} (Ambient Recall for ${s} \u2014 ${i})`)}async function ze(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?$n:kn)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const d=Ps(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 a=i.status==="unchanged"?"\u2713 ":"\u2705 ",r=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${a}${o}${r}: ${i.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function ye(e,t,n,o){const s={cursor:an,copilot:cn,codex:ln,gemini:dn}[e];Hs(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:a}=await import("node:path"),r=process.argv.slice(3),d=w=>dt(r,w),f=tn(r,["instance-id","api-key","editor","project-dir","api-url"]);f.length>0&&(console.error(`
197
- Missing value for ${f.map(w=>`--${w}`).join(", ")}. Nothing was written.
198
- `),process.exit(1));let l=d("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,u=d("api-key")??process.env.CACHLY_JWT;const y=(d("editor")??"claude").toLowerCase(),b=s(d("project-dir")??"."),v=d("api-url");if(v&&(x=v.replace(/\/+$/,"")),!l||!u){const w=xe(),_=_e();w&&_&&(u??=w,l??=_,u===w&&l===_&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!l||!u)try{const{existsSync:w}=await import("node:fs"),_=process.env.HOME??process.env.USERPROFILE??"",k=_?s(_,".claude","mcp.json"):"";if(k&&w(k)){const E=JSON.parse(await o(k,"utf-8")).mcpServers?.cachly?.env??{};u??=E.CACHLY_JWT,l??=E.CACHLY_BRAIN_INSTANCE_ID,u&&l&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!l||!u)&&(console.error(`
194
+ `),process.exit(1));const t=`${x}/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=Sn(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
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 ci={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Nn,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:On,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:Ln,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function li(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=ci[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"?Kn:Gn)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const u=ri(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:`),u&&console.log(` ${o}${u.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:Rn,copilot:jn,codex:Bn,gemini:Pn}[e];li(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),u=v=>vt(a,v),p=An(a,["instance-id","api-key","editor","project-dir","api-url"]);p.length>0&&(console.error(`
197
+ Missing value for ${p.map(v=>`--${v}`).join(", ")}. Nothing was written.
198
+ `),process.exit(1));let c=u("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=u("api-key")??process.env.CACHLY_JWT;const f=(u("editor")??"claude").toLowerCase(),y=s(u("project-dir")??"."),w=u("api-url");if(w&&(x=w.replace(/\/+$/,"")),!c||!d){const v=Ce(),k=Te();v&&k&&(d??=v,c??=k,d===v&&c===k&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!c||!d)try{const{existsSync:v}=await import("node:fs"),k=process.env.HOME??process.env.USERPROFILE??"",_=k?s(k,".claude","mcp.json"):"";if(_&&v(_)){const I=JSON.parse(await o(_,"utf-8")).mcpServers?.cachly?.env??{};d??=I.CACHLY_JWT,c??=I.CACHLY_BRAIN_INSTANCE_ID,d&&c&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!c||!d)&&(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 m=on({instanceId:l,apiKey:u,editor:y},[...Object.keys(ce),"codex","gemini"]);if(m.length>0){console.error(`
203
- Nothing was written:`);for(const w of m)console.error(` - ${w}`);console.error(""),process.exit(1)}try{const w=await fetch(`${x}/api/v1/instances/${l}/memory`,{headers:{Authorization:`Bearer ${u}`},signal:AbortSignal.timeout(8e3)});(w.status===401||w.status===403||w.status===404)&&(console.error(`
204
- The server does not accept this key and instance (HTTP ${w.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=()=>{ee(u),_e()||ve(l,{apiKey:u})};if(y==="codex"||y==="gemini")c(),console.log(""),await ze(y,b,Z(u,l),"");else{const w=ce[y]??".mcp.json",_=s(b,w);await n(i(_),{recursive:!0});const{existsSync:k}=await import("node:fs"),I=k(_),E=I?await o(_,"utf-8").catch(()=>""):"";c();const $=await Dt(_,u,l,y,{readFile:o,existsSync:k});$!==E?(await t(_,$,"utf-8"),console.log(`
206
- \u2705 ${I?"Updated":"Written"}: ${w}`)):console.log(`
207
- \u2713 Already configured: ${w} (no change)`)}const p=r.includes("--all-editors"),g=await zt(b,l,void 0,p?void 0:y);for(const[w,_]of Object.entries(g))console.log(Ut(w.split(/[\\/]/).pop()??w,_));try{const w=await at(b,l),_=a(b,s(qo(b),"post-commit")).replace(/\\/g,"/");w==="written"?console.log(`\u2705 Written: ${_} (CLS hook)`):w==="upgraded"?console.log(`\u2705 Upgraded: ${_} (CLS hook \u2192 ${ct})`):w==="appended"?console.log(`\u2705 Appended: ${_} (CLS hook)`):w==="unchanged"&&console.log(`\u2713 CLS hook already current in ${_}`)}catch{}if(y==="claude")try{const w=await pt(b,l);if(w.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${w.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const _=w.scripts==="written"?"\u2705 Written":w.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${mt})`:"\u2713 Unchanged";console.log(`${_}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),w.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):w.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{}(y==="cursor"||y==="copilot"||y==="codex"||y==="gemini")&&await ye(y,b,l,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
208
- \u{1F9E0} Cachly AI Brain configured for ${y==="claude"?"Claude Code":y}! (${C}s)`),console.log(y==="codex"||y==="gemini"?` Start ${y} 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(`
202
+ `),process.exit(1));const g=Cn({instanceId:c,apiKey:d,editor:f},[...Object.keys(ke),"codex","gemini"]);if(g.length>0){console.error(`
203
+ Nothing was written:`);for(const v of g)console.error(` - ${v}`);console.error(""),process.exit(1)}try{const v=await fetch(`${x}/api/v1/instances/${c}/memory`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(8e3)});(v.status===401||v.status===403||v.status===404)&&(console.error(`
204
+ The server does not accept this key and instance (HTTP ${v.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 l=()=>{ne(d),Te()||Ae(c,{apiKey:d})};if(f==="codex"||f==="gemini")l(),console.log(""),await qe(f,y,ee(d,c),"");else{const v=wt(f,y),k=v.anzeige,_=v.pfad;await n(i(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";l();const E=await Vt(_,d,c,v.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
206
+ \u2705 ${I?"Updated":"Written"}: ${k}`)):console.log(`
207
+ \u2713 Already configured: ${k} (no change)`)}const m=a.includes("--all-editors"),h=await Zt(y,c,void 0,m?void 0:f);for(const[v,k]of Object.entries(h))console.log(Xt(v.split(/[\\/]/).pop()??v,k));try{const v=await ht(y,c),k=r(y,s(wn(y),"post-commit")).replace(/\\/g,"/");v==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):v==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${ft})`):v==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):v==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(f==="claude")try{const v=await _t(y,c);if(v.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${v.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=v.scripts==="written"?"\u2705 Written":v.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${$t})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),v.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):v.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{}(f==="cursor"||f==="copilot"||f==="codex"||f==="gemini")&&await be(f,y,c,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
208
+ \u{1F9E0} Cachly AI Brain configured for ${f==="claude"?"Claude Code":f}! (${C}s)`),console.log(f==="codex"||f==="gemini"?` Start ${f} 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=G(),t=z();(!e||!t)&&(console.log(`
210
+ `),process.exit(0)}if(process.argv[2]==="status"){const e=X(),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
- `),process.exit(1));try{const[n,o]=await Promise.all([fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${x}/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,a=s.lesson_count??0,r=s.total_recall_count??0,d=Math.round(s.iq_boost_pct??0),f=s.team_authors??[],l=i?.referral_count??0,u=i?.url??"",y=a===0?"Intern \u{1F331}":a<10?"Junior Dev \u{1F527}":a<30?"Mid Dev \u26A1":a<60?"Senior Dev \u{1F9E0}":a<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",b=a>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 ${b} \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(a).padEnd(8)}\x1B[0m Level : \x1B[32m${y.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(d).padEnd(3)}%\x1B[0m \u2502`),f.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=f.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(f.length).padEnd(2)} developer${f.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-v.length))} \u2502`),console.log(`\u2502 ${v.slice(0,56).padEnd(56)} \u2502`)}if(u){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,44)}${u.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(""),a===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(`
212
+ `),process.exit(1));try{const[n,o]=await Promise.all([fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${x}/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,u=Math.round(s.iq_boost_pct??0),p=s.team_authors??[],c=i?.referral_count??0,d=i?.url??"",f=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}",y=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 ${y} \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${f.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(u).padEnd(3)}%\x1B[0m \u2502`),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");const w=p.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(p.length).padEnd(2)} developer${p.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-w.length))} \u2502`),console.log(`\u2502 ${w.slice(0,56).padEnd(56)} \u2502`)}if(d){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 w=`${d.slice(0,44)}${d.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Referral link\x1B[0m \xB7 ${c>0?`\x1B[32m${c} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(c).length))} \u2502`),console.log(`\u2502 \x1B[2m${w.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 a=m=>{console.log(` \u2705 ${m}`),s++},r=m=>{console.log(` \u26A0\uFE0F ${m}`)},d=m=>{console.log(` \u274C ${m}`),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=g=>{console.log(` \u2705 ${g}`),s++},a=g=>{console.log(` \u26A0\uFE0F ${g}`)},u=g=>{console.log(` \u274C ${g}`),i++};console.log(`
215
215
  \u{1F9E0} cachly health check
216
- `),console.log("\u{1F511} Auth token");const f=G();if(!f)d("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(f.startsWith("cky_"))a("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const m=f.split(".");if(m.length!==3)throw new Error("not a JWT");const c=JSON.parse(Buffer.from(m[1],"base64url").toString("utf-8")),p=c.exp?c.exp*1e3:null,g=p?Math.floor((p-Date.now())/6e4):null;p&&p<Date.now()?d(`JWT expired ${Math.abs(g)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):g!==null&&g<30?r(`JWT expires in ${g} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):a(`JWT valid${g!==null?` (expires in ${Math.floor(g/60)}h ${g%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 m=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(m.ok){const c=await m.json();a(`${l} reachable (status: ${c.status??"ok"})`)}else m.status===401||m.status===403?a(`${l} reachable (auth required \u2014 expected)`):d(`${l}/health returned HTTP ${m.status}`)}catch(m){d(`${l} unreachable \u2014 ${m.message}`)}console.log(`
218
- \u{1F9E0} Brain instance`);const u=z();if(!u)r("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(f)try{const m=await fetch(`${l}/api/v1/instances/${u}`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(m.ok){const c=await m.json();if(c.status==="running")if(a(`Instance "${c.name}" (${u.slice(0,8)}\u2026) is running`),console.log(`
219
- \u{1F50C} Redis connectivity`),c.host&&c.port)try{let p,g;try{const k=await fetch(`${l}/api/v1/instances/${u}/connection`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(k.ok){const I=await k.json();p=I.password,g=I}}catch{}const C=xt({host:c.host,port:c.port,tls_enabled:c.tls_enabled},g),w=new Xe({host:C.host,port:C.port,password:p,...C.tls?{tls:C.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await w.connect();const _=await w.ping();w.disconnect(),_==="PONG"?a(`Redis PING \u2192 PONG (${C.host}:${C.port}, ${C.art==="klartext"?"unencrypted":"TLS"})`):r(`Redis responded but not PONG: ${_}`)}catch(p){d(`Redis unreachable \u2014 ${p.message}`)}else r("Instance has no host/port yet");else r(`Instance "${c.name}" status: ${c.status}`)}else d(`Instance ${u.slice(0,8)}\u2026 not found (HTTP ${m.status})`)}catch(m){d(`Could not check instance \u2014 ${m.message}`)}console.log(`
220
- \u{1F6E0} Editor configs (project dir)`);const y=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:".windsurf/mcp.json"},{editor:"Copilot / Cline",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 b=0;for(const{editor:m,path:c}of y){const p=n(o,c);if(e(p))try{const g=await t(p,"utf-8");g.includes("@cachly-dev/mcp-server")||g.includes("cachly")?(a(`${m}: ${c}`),b++):r(`${m}: ${c} exists but cachly not found inside`)}catch{r(`${m}: ${c} exists but could not read`)}}b===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
- \u{1FA9D} Git hook (ambient learning)`);const v=n(o,".git","hooks","post-commit");if(!e(n(o,".git")))r("Not in a git repository \u2014 skip");else if(e(v))try{(await t(v,"utf-8")).includes("cachly")?a(".git/hooks/post-commit (cachly CLS hook present)"):r(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{r(".git/hooks/post-commit exists but could not read")}else r(".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 m=[["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 p=m.find(([,g])=>g===c)?.[0];p&&process.env[p]?a(`BYOK: ${c} (key present in ${p})`):r(`CACHLY_EMBED_PROVIDER=${c} but its key env var is not set \u2014 semantic search will fail`)}else{it==="ollama"?a("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):it==="cachly"?a("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):r("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[p,g]of m)g!=="ollama"&&process.env[p]&&a(`${p} is set but not used \u2014 ${g} runs only if you name it with CACHLY_EMBED_PROVIDER=${g}`)}}console.log(`
216
+ `),console.log("\u{1F511} Auth token");const p=X();if(!p)u("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(p.startsWith("cky_"))r("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const g=p.split(".");if(g.length!==3)throw new Error("not a JWT");const l=JSON.parse(Buffer.from(g[1],"base64url").toString("utf-8")),m=l.exp?l.exp*1e3:null,h=m?Math.floor((m-Date.now())/6e4):null;m&&m<Date.now()?u(`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{u("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
217
+ \u{1F310} Brain API`);const c=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const g=await fetch(`${c}/health`,{signal:AbortSignal.timeout(5e3)});if(g.ok){const l=await g.json();r(`${c} reachable (status: ${l.status??"ok"})`)}else g.status===401||g.status===403?r(`${c} reachable (auth required \u2014 expected)`):u(`${c}/health returned HTTP ${g.status}`)}catch(g){u(`${c} unreachable \u2014 ${g.message}`)}console.log(`
218
+ \u{1F9E0} Brain instance`);const d=U();if(!d)a("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(p)try{const g=await fetch(`${c}/api/v1/instances/${d}`,{headers:{Authorization:`Bearer ${p}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(g.ok){const l=await g.json();if(l.status==="running")if(r(`Instance "${l.name}" (${d.slice(0,8)}\u2026) is running`),console.log(`
219
+ \u{1F50C} Redis connectivity`),l.host&&l.port)try{let m,h;try{const _=await fetch(`${c}/api/v1/instances/${d}/connection`,{headers:{Authorization:`Bearer ${p}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(_.ok){const R=await _.json();m=R.password,h=R}}catch{}const C=Rt({host:l.host,port:l.port,tls_enabled:l.tls_enabled},h),v=new at({host:C.host,port:C.port,password:m,...C.tls?{tls:C.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await v.connect();const k=await v.ping();v.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(m){u(`Redis unreachable \u2014 ${m.message}`)}else a("Instance has no host/port yet");else a(`Instance "${l.name}" status: ${l.status}`)}else u(`Instance ${d.slice(0,8)}\u2026 not found (HTTP ${g.status})`)}catch(g){u(`Could not check instance \u2014 ${g.message}`)}console.log(`
220
+ \u{1F6E0} Editor configs (project dir)`);const f=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:Se("windsurf",he())},{editor:"Cline",path:Se("cline",he())},{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 y=0;for(const{editor:g,path:l}of f){const m=n(o,l);if(e(m))try{const h=await t(m,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(r(`${g}: ${l}`),y++):a(`${g}: ${l} exists but cachly not found inside`)}catch{a(`${g}: ${l} exists but could not read`)}}y===0&&u("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
+ \u{1FA9D} Git hook (ambient learning)`);const w=n(o,".git","hooks","post-commit");if(!e(n(o,".git")))a("Not in a git repository \u2014 skip");else if(e(w))try{(await t(w,"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"]],l=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(l&&l!=="cachly"){const m=g.find(([,h])=>h===l)?.[0];m&&process.env[m]?r(`BYOK: ${l} (key present in ${m})`):a(`CACHLY_EMBED_PROVIDER=${l} but its key env var is not set \u2014 semantic search will fail`)}else{mt==="ollama"?r("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):mt==="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[m,h]of g)h!=="ollama"&&process.env[m]&&r(`${m} 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 p=process.argv.indexOf(`--${c}`);return p!==-1?process.argv[p+1]:void 0};x=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const a=(i("auth-url")??ht).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=l=>{const m=process.argv.indexOf(`--${l}`);return m!==-1?process.argv[m+1]:void 0};x=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const r=(i("auth-url")??St).replace(/\/+$/,"");console.log(`
227
227
  \u{1F9E0} cachly \u2014 keep your test Brain in your own account
228
- `),(x!=="https://api.cachly.dev"||a!==ht)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${x}, sign-in ${a}
229
- `);const r=An({argument:i("key"),credentials:xe()});r||(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
- `),process.exit(1));const d=r.schluessel,f={argument:"--key",credentials:"~/.cachly/credentials.json"}[r.quelle];console.log(`Test key: ${d.slice(0,14)}\u2026 (from ${f})
231
- `);let l="";try{console.log(`Step 1: Sign in to your cachly account
232
- `);const c=await Cn(fetch,a);console.log(` Code: \x1B[1;33m${c.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${c.adresse}
233
- `),re(c.adresse,(p,g)=>{p||console.log(`
234
- \u2139\uFE0F No browser could be opened here (${g??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),l=await Tn(fetch,c,{basis:a,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
235
- `)}catch(c){console.error(`
236
-
237
- ${c.message}. Nothing was changed.
238
- `),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let u;try{u=await In(fetch,x,l,d,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
239
- `)}catch(c){console.error(`
240
-
241
- ${jn(c)}
242
- `),process.exit(1)}S=u.apiKey,ee(u.apiKey),ve(u.instanceId,{apiKey:u.apiKey}),await me(u.apiKey),await ge(u.instanceId);const y=s(),b=new Set([...Object.values(ce).map(c=>o(process.cwd(),c)),o(y,".claude.json"),o(y,".claude","mcp.json"),o(y,".cursor","mcp.json"),o(y,".codeium","windsurf","mcp_config.json")]);let v=0;for(const c of b)if(n(c))try{const p=Bn(await e(c,"utf-8"),d,u.apiKey);p.ersetzt&&(await t(c,p.text,"utf-8"),v++)}catch{}const m=await En(fetch,x,u.apiKey,u.instanceId);console.log(Rn(u,m)),console.log(`
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
- `),process.exit(0)}const Ae=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||Ae){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:a}=await import("node:readline"),r=Date.now(),d=Ae?"autopilot":"setup";Ko();const f=process.argv.indexOf("--api-url");f!==-1&&process.argv[f+1]&&(x=process.argv[f+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
245
- `)),A("setup_started");const l=process.stdin.isTTY===!0,u=Ae||process.argv.includes("--yes")||process.argv.includes("-y")||!l;Ae?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
246
- `):!l&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
247
- `);const y=a({input:process.stdin,output:process.stdout}),b=(h,T="")=>u?(console.log(`${h}${T}`),Promise.resolve(T)):new Promise(B=>y.question(h,U=>B(U.trim()||T)));console.log(`
228
+ `),(x!=="https://api.cachly.dev"||r!==St)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${x}, sign-in ${r}
229
+ `);const a=Vn({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
+ `),process.exit(1));const u=a.schluessel,p={argument:"--key",credentials:"~/.cachly/credentials.json"}[a.quelle];console.log(`Test key: ${u.slice(0,14)}\u2026 (from ${p})
231
+ `);let c="";try{console.log(`Step 1: Sign in to your cachly account
232
+ `);const l=await Zn(fetch,r);console.log(` Code: \x1B[1;33m${l.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${l.adresse}
233
+ `),ce(l.adresse,(m,h)=>{m||console.log(`
234
+ \u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),c=await Xn(fetch,l,{basis:r,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
235
+ `)}catch(l){console.error(`
236
+
237
+ ${l.message}. Nothing was changed.
238
+ `),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let d;try{d=await Qn(fetch,x,c,u,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
239
+ `)}catch(l){console.error(`
240
+
241
+ ${os(l)}
242
+ `),process.exit(1)}S=d.apiKey,ne(d.apiKey),Ae(d.instanceId,{apiKey:d.apiKey}),await pe(d.apiKey),await me(d.instanceId);const f=s(),y=new Set([...Object.values(ke).map(l=>o(process.cwd(),l)),o(f,".claude.json"),o(f,".claude","mcp.json"),o(f,".cursor","mcp.json"),o(f,".codeium","windsurf","mcp_config.json")]);let w=0;for(const l of y)if(n(l))try{const m=ns(await e(l,"utf-8"),u,d.apiKey);m.ersetzt&&(await t(l,m.text,"utf-8"),w++)}catch{}const g=await es(fetch,x,d.apiKey,d.instanceId);console.log(ts(d,g)),console.log(`
243
+ New key stored in ~/.cachly/credentials.json${w?` and in ${w} 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
+ `),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(),u=je?"autopilot":"setup";bn();const p=process.argv.indexOf("--api-url");p!==-1&&process.argv[p+1]&&(x=process.argv[p+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
245
+ `)),A("setup_started");const c=process.stdin.isTTY===!0,d=je||process.argv.includes("--yes")||process.argv.includes("-y")||!c;je?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
246
+ `):!c&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
247
+ `);const f=r({input:process.stdin,output:process.stdout}),y=(b,T="")=>d?(console.log(`${b}${T}`),Promise.resolve(T)):new Promise(B=>f.question(b,z=>B(z.trim()||T)));console.log(`
248
248
  \u{1F9E0} cachly AI Brain \u2014 Setup`),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
249
- `);let v=process.env.CACHLY_JWT??"";if(v)console.log(`\u2713 Using token from CACHLY_JWT env var
249
+ `);let w=process.env.CACHLY_JWT??"";if(w)console.log(`\u2713 Using token from CACHLY_JWT env var
250
250
  `);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
251
- `),A("setup_auth_started");let h="",T="",B="",U=5e3,W=!1,ue="cachly";try{const q=await fetch(`${x}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(q.ok){const P=await q.json();h=P.device_code,T=P.user_code;const D=P.verification_uri||j("/device",d);B=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(T)}`,U=(P.interval??5)*1e3,W=!!h}}catch{}if(!W)try{const P=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(P.ok){const D=await P.json();h=D.device_code,T=D.user_code,B=D.verification_uri_complete,U=(D.interval??5)*1e3,W=!0,ue="keycloak"}}catch{}if(W&&h){console.log(` Code: \x1B[1;33m${T}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${B}
252
- `),re(B,(P,D)=>{if(P){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:D??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${D??"unknown"}) \u2014 please open the URL yourself.
253
- `)}),process.stdout.write(" Waiting for authorization");const q=Date.now()+600*1e3;for(;Date.now()<q;){await new Promise(P=>setTimeout(P,U)),process.stdout.write(".");try{let P=null;if(ue==="cachly")try{const D=await fetch(`${x}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:h}),signal:AbortSignal.timeout(8e3)});D.status<500&&(P=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{P=await(await fetch(`${D}/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=${h}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(P?.access_token){v=P.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
254
- `),A("setup_auth_completed"),A("device_flow_completed");break}P?.error==="slow_down"?U=Math.min(U+2e3,15e3):P?.error&&P.error!=="authorization_pending"&&(A("device_flow_failed",{reason:P.error}),console.error(`
255
- Auth error: ${P.error}. Aborting.
256
- `),y.close(),process.exit(1))}catch{}}v||(A("device_flow_failed",{reason:"timeout"}),console.error(`
251
+ `),A("setup_auth_started");let b="",T="",B="",z=5e3,F=!1,K="cachly";try{const V=await fetch(`${x}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(V.ok){const N=await V.json();b=N.device_code,T=N.user_code;const D=N.verification_uri||j("/device",u);B=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(T)}`,z=(N.interval??5)*1e3,F=!!b}}catch{}if(!F)try{const N=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(N.ok){const D=await N.json();b=D.device_code,T=D.user_code,B=D.verification_uri_complete,z=(D.interval??5)*1e3,F=!0,K="keycloak"}}catch{}if(F&&b){console.log(` Code: \x1B[1;33m${T}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${B}
252
+ `),ce(B,(N,D)=>{if(N){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:D??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${D??"unknown"}) \u2014 please open the URL yourself.
253
+ `)}),process.stdout.write(" Waiting for authorization");const V=Date.now()+600*1e3;for(;Date.now()<V;){await new Promise(N=>setTimeout(N,z)),process.stdout.write(".");try{let N=null;if(K==="cachly")try{const D=await fetch(`${x}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b}),signal:AbortSignal.timeout(8e3)});D.status<500&&(N=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{N=await(await fetch(`${D}/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=${b}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(N?.access_token){w=N.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
254
+ `),A("setup_auth_completed"),A("device_flow_completed");break}N?.error==="slow_down"?z=Math.min(z+2e3,15e3):N?.error&&N.error!=="authorization_pending"&&(A("device_flow_failed",{reason:N.error}),console.error(`
255
+ Auth error: ${N.error}. Aborting.
256
+ `),f.close(),process.exit(1))}catch{}}w||(A("device_flow_failed",{reason:"timeout"}),console.error(`
257
257
  Timed out waiting for authorization. Aborting.
258
- `),y.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const q=j("/setup-ai",d);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
259
- `),console.log(` URL: \x1B[36m${q}\x1B[0m`),console.log(" 1. Sign up / log in at the URL above"),console.log(" 2. Go to Settings \u2192 API Keys \u2192 Create new key"),console.log(` 3. Copy the key (starts with cky_live_...)
260
- `),re(q),u?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
258
+ `),f.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const V=j("/setup-ai",u);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
259
+ `),console.log(` URL: \x1B[36m${V}\x1B[0m`),console.log(" 1. Sign up / log in at the URL above"),console.log(" 2. Go to Settings \u2192 API Keys \u2192 Create new key"),console.log(` 3. Copy the key (starts with cky_live_...)
260
+ `),ce(V),d?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
261
261
  \u26A0\uFE0F This terminal is non-interactive, so the key cannot be pasted here.`),console.error(` Get your key at the URL above, then set it and re-run setup:
262
262
  `),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
263
263
  `),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
264
- `),y.close(),process.exit(1)):(v=await b(" Paste API key (cky_live_...): "),v||(console.error(`
264
+ `),f.close(),process.exit(1)):(w=await y(" Paste API key (cky_live_...): "),w||(console.error(`
265
265
  API key is required. Aborting.
266
- `),y.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(v.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const h=await fetch(`${x}/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(!h.ok)throw new Error(`HTTP ${h.status}`);const T=await h.json();if(!T.key)throw new Error("no key in response");v=T.key,console.log(` \u2713
266
+ `),f.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(w.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const b=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!b.ok)throw new Error(`HTTP ${b.status}`);const T=await b.json();if(!T.key)throw new Error("no key in response");w=T.key,console.log(` \u2713
267
267
  `)}catch{console.log(` (skipped)
268
- `)}}process.stdout.write("\u23F3 Fetching your instances...");let m=[];try{const h=await fetch(`${x}/api/v1/instances`,{headers:{Authorization:`Bearer ${v}`}});if(!h.ok)throw new Error(`HTTP ${h.status}`);m=((await h.json()).data??[]).filter(B=>B.status==="running")}catch(h){const T=h.message;console.error(`
269
-
270
- Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejected. Get a valid token at ${j("/setup-ai",d)}
271
- `),re(j("/setup-ai",d))),y.close(),process.exit(1)}if(console.log(` found ${m.length}
272
- `),m.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const h=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"}});if(!h.ok)throw new Error(`HTTP ${h.status}`);const T=await h.json();if(T.instance)m=[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 U=0;U<45;U++){await new Promise(W=>setTimeout(W,3e3)),process.stdout.write(".");try{const W=await fetch(`${x}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${v}`}});if(W.ok){const ue=await W.json();if(ue.status==="running"){m=[ue];break}}}catch{}}console.log("")}}catch(h){console.log(` failed: ${h.message}
274
- `)}m.length===0&&(console.error(`
275
- Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
276
- `),re(j("/instances",d)),y.close(),process.exit(1))}const c=m[0];m.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
- `)),console.log(`\u2713 Instance: ${c.name} (${c.id.slice(0,8)}\u2026)
278
- `),A("setup_instance_ready",{instance_id:c.id});const p=process.cwd(),g=[],{homedir:C}=await import("node:os"),w=C();g.push("claude"),o(s(p,".cursor"))&&g.push("cursor"),o(s(p,".windsurf"))&&g.push("windsurf"),o(s(p,".vscode"))&&g.push("copilot"),o(s(p,".continue"))&&g.push("continue");const _=process.platform==="darwin"?s(w,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):s(w,".vscode/extensions");(o(_)&&!g.includes("copilot")||o(_))&&g.push("cline");const k=process.platform==="darwin"?s(w,"Library/Application Support/Zed"):s(w,".config/zed");o(k)&&g.push("zed");const I=h=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[h]??h,E=g;console.log(`\u{1F527} Configuring for: ${E.map(I).join(", ")}
279
- `);const{existsSync:$}=await import("node:fs"),R=[];let M=0;ee(v),ve(c.id,{apiKey:v});for(const h of E){const T=ce[h]??".mcp.json",B=s(p,T);try{await t(i(B),{recursive:!0});const U=$(B),W=await Dt(B,v,c.id,h,{readFile:n,existsSync:$});await e(B,W,"utf-8"),console.log(`\u2705 ${U?"Updated":"Written"}: ${T}`),M++}catch(U){const W=U.message;console.log(`\u26A0\uFE0F Could not write ${T}: ${W}`),console.log(" Fix permissions or run with sudo, then re-run setup."),R.push({file:T,reason:W})}}const Te=await zt(p,c.id);for(const[h,T]of Object.entries(Te)){const{relative:B}=await import("node:path");console.log(Ut(B(p,h)||h,T))}S=v;let oe=0;if(o(s(p,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const h=await J("brain_from_git",{instance_id:c.id,repo_path:p,limit:100});if(h.startsWith("\u274C"))console.log(` (skipped: ${rt(h.replace(/^❌\s*/,"")).split(`
280
- `)[0].slice(0,160)})`);else{const T=h.match(/Ingested: \*\*(\d+)\*\*/);oe=T?parseInt(T[1],10):0,console.log(` \u2713 ${oe} lesson${oe===1?"":"s"} extracted from git history`);const B=Jo(h);B&&(console.log(""),console.log(rt(B)))}}catch(h){console.log(` (skipped: ${h.message.slice(0,80)})`)}}if(oe===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 h=await J("smart_recall",{instance_id:c.id,query:"docker build slow"}),T=Fo(h);T&&(console.log(""),console.log(Yo(T.topic,T.what)))}catch{}}catch(h){console.log(` (skipped: ${h.message.slice(0,60)})`)}}try{const h=await fetch(`${x}/api/v1/instances/${c.id}/memory`,{headers:{Authorization:`Bearer ${v}`},signal:AbortSignal.timeout(6e3)});if(h.ok){const B=(await h.json()).lesson_count??0;console.log(B===0?`
268
+ `)}}process.stdout.write("\u23F3 Fetching your instances...");let g=[];try{const b=await fetch(`${x}/api/v1/instances`,{headers:{Authorization:`Bearer ${w}`}});if(!b.ok)throw new Error(`HTTP ${b.status}`);g=((await b.json()).data??[]).filter(B=>B.status==="running")}catch(b){const T=b.message;console.error(`
269
+
270
+ Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejected. Get a valid token at ${j("/setup-ai",u)}
271
+ `),ce(j("/setup-ai",u))),f.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 b=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"}});if(!b.ok)throw new Error(`HTTP ${b.status}`);const T=await b.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(`${x}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${w}`}});if(F.ok){const K=await F.json();if(K.status==="running"){g=[K];break}}}catch{}}console.log("")}}catch(b){console.log(` failed: ${b.message}
274
+ `)}g.length===0&&(console.error(`
275
+ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
276
+ `),ce(j("/instances",u)),f.close(),process.exit(1))}const l=g[0];g.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${l.name}`),console.log(` (Run with --instance-id <id> to use a different one)
277
+ `)),console.log(`\u2713 Instance: ${l.name} (${l.id.slice(0,8)}\u2026)
278
+ `),A("setup_instance_ready",{instance_id:l.id});const m=process.cwd(),h=[],{homedir:C}=await import("node:os"),v=C();h.push("claude"),o(s(m,".cursor"))&&h.push("cursor");const k=he();(o(s(m,".windsurf"))||bt("windsurf",k,o))&&h.push("windsurf"),o(s(m,".vscode"))&&h.push("copilot"),o(s(m,".continue"))&&h.push("continue"),bt("cline",k,o)&&h.push("cline");const _=process.platform==="darwin"?s(v,"Library/Application Support/Zed"):s(v,".config/zed");o(_)&&h.push("zed");const R=b=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[b]??b,I=h;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
+ `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(w),Ae(l.id,{apiKey:w});for(const b of I){const T=wt(b,m),B=T.anzeige,z=T.pfad;try{await t(i(z),{recursive:!0});const F=$(z),K=await Vt(z,w,l.id,T.format,{readFile:n,existsSync:$});await e(z,K,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${B}`),M++}catch(F){const K=F.message;console.log(`\u26A0\uFE0F Could not write ${B}: ${K}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:B,reason:K})}}const Pe=await Zt(m,l.id);for(const[b,T]of Object.entries(Pe)){const{relative:B}=await import("node:path");console.log(Xt(B(m,b)||b,T))}S=w;let ie=0;if(o(s(m,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const b=await J("brain_from_git",{instance_id:l.id,repo_path:m,limit:100});if(b.startsWith("\u274C"))console.log(` (skipped: ${gt(b.replace(/^❌\s*/,"")).split(`
280
+ `)[0].slice(0,160)})`);else{const T=b.match(/Ingested: \*\*(\d+)\*\*/);ie=T?parseInt(T[1],10):0,console.log(` \u2713 ${ie} lesson${ie===1?"":"s"} extracted from git history`);const B=hn(b);B&&(console.log(""),console.log(gt(B)))}}catch(b){console.log(` (skipped: ${b.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:l.id}),console.log(" \u2713");try{const b=await J("smart_recall",{instance_id:l.id,query:"docker build slow"}),T=fn(b);T&&(console.log(""),console.log(yn(T.topic,T.what)))}catch{}}catch(b){console.log(` (skipped: ${b.message.slice(0,60)})`)}}try{const b=await fetch(`${x}/api/v1/instances/${l.id}/memory`,{headers:{Authorization:`Bearer ${w}`},signal:AbortSignal.timeout(6e3)});if(b.ok){const B=(await b.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
- \u{1F9E0} Your Brain now holds ${B} lesson${B===1?"":"s"}.`)}}catch{}if(!u)try{if(console.log(`
283
- \u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),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"),(await b(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const T=await b(' Your handle (e.g. "alice"): ');T.trim()&&await J("team_assign_role",{instance_id:c.id,handle:T.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${T.trim()} is now admin. Invite teammates:
284
- `),console.log(` team_assign_role(instance_id="${c.id}", handle="<teammate>", role="contributor", assigned_by="${T.trim()}")
282
+ \u{1F9E0} Your Brain now holds ${B} lesson${B===1?"":"s"}.`)}}catch{}if(!d)try{if(console.log(`
283
+ \u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),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"),(await y(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const T=await y(' Your handle (e.g. "alice"): ');T.trim()&&await J("team_assign_role",{instance_id:l.id,handle:T.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${T.trim()} is now admin. Invite teammates:
284
+ `),console.log(` team_assign_role(instance_id="${l.id}", handle="<teammate>", role="contributor", assigned_by="${T.trim()}")
285
285
  `))}else console.log(` Skipped \u2014 run team_assign_role at any time.
286
- `)}catch{}if(!u){const h=await b(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(h&&h.includes("@"))try{await fetch(`${x}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:h.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
287
- `)}catch{}}try{const h=await at(process.cwd(),c.id);h==="written"?console.log(`
288
- \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):h==="upgraded"?console.log(`
289
- \u2705 CLS git hook upgraded to ${ct}.`):h==="appended"&&console.log(`
290
- \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(E.includes("claude"))try{const h=await pt(process.cwd(),c.id);if(h.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${h.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=h.scripts==="written"?"\u2705 Written":h.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${mt})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),h.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):h.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{}E.includes("cursor")&&await ye("cursor",process.cwd(),c.id," "),E.includes("copilot")&&await ye("copilot",process.cwd(),c.id," "),(o(s(w,".codex"))||o(s(p,".codex")))&&(await ye("codex",process.cwd(),c.id," "),await ze("codex",process.cwd(),Z("",c.id)," ")),(o(s(w,".gemini"))||o(s(p,".gemini")))&&(await ye("gemini",process.cwd(),c.id," "),await ze("gemini",process.cwd(),Z("",c.id)," ")),S=v;const Ue=Math.round((Date.now()-r)/1e3);if(R.length>0&&A("setup_config_write_failed",{instance_id:c.id,failed:R.length,succeeded:M}),A("setup_completed",{instance_id:c.id,elapsed_s:Ue,config_failures:R.length}),R.length>0&&M===0){console.log(`
286
+ `)}catch{}if(!d){const b=await y(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(b&&b.includes("@"))try{await fetch(`${x}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:b.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
287
+ `)}catch{}}try{const b=await ht(process.cwd(),l.id);b==="written"?console.log(`
288
+ \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):b==="upgraded"?console.log(`
289
+ \u2705 CLS git hook upgraded to ${ft}.`):b==="appended"&&console.log(`
290
+ \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const b=await _t(process.cwd(),l.id);if(b.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${b.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=b.scripts==="written"?"\u2705 Written":b.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${$t})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),b.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):b.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(),l.id," "),I.includes("copilot")&&await be("copilot",process.cwd(),l.id," "),(o(s(v,".codex"))||o(s(m,".codex")))&&(await be("codex",process.cwd(),l.id," "),await qe("codex",process.cwd(),ee("",l.id)," ")),(o(s(v,".gemini"))||o(s(m,".gemini")))&&(await be("gemini",process.cwd(),l.id," "),await qe("gemini",process.cwd(),ee("",l.id)," ")),S=w;const Ve=Math.round((Date.now()-a)/1e3);if(E.length>0&&A("setup_config_write_failed",{instance_id:l.id,failed:E.length,succeeded:M}),A("setup_completed",{instance_id:l.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
- Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const h of R)console.log(` \u2022 ${h.file} \u2014 ${h.reason}`);console.log(`
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)}
294
- `),y.close(),await new Promise(h=>setTimeout(h,300)),process.exit(1)}if(console.log(`
295
- \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 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(Ue+"s").padEnd(5)} \u2014 restart your editor \u2551`),console.log("\u2551 and your AI arrives pre-briefed every session. \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"),R.length>0){console.log(`
296
- \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const h of R)console.log(` \u2022 ${h.file} \u2014 ${h.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(`
292
+ Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const b of E)console.log(` \u2022 ${b.file} \u2014 ${b.reason}`);console.log(`
293
+ Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${w.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${l.id}`),console.log(` Docs: ${j("/docs/mcp",u)}
294
+ `),f.close(),await new Promise(b=>setTimeout(b,300)),process.exit(1)}if(console.log(`
295
+ \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 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(Ve+"s").padEnd(5)} \u2014 restart your editor \u2551`),console.log("\u2551 and your AI arrives pre-briefed every session. \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"),E.length>0){console.log(`
296
+ \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const b of E)console.log(` \u2022 ${b.file} \u2014 ${b.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(`
297
297
  \u{1F449} Next: restart your editor, start a new chat and ask:`),console.log(" What does my cachly Brain know about this project?"),console.log(` Your AI should call the cachly tool smart_recall and answer from your Brain.
298
- `),console.log(` Dashboard: ${j(`/instances/${c.id}`,d)}`),console.log(` Step-by-step guide: ${j("/docs/setup",d)}
299
- `),y.close(),await new Promise(h=>setTimeout(h,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=r=>{const d=t.indexOf(`--${r}`);return d!==-1?t[d+1]:void 0},o=e(n("dir")??t.find(r=>!r.startsWith("--"))??"."),s=n("instance-id")||z(),i=parseInt(n("max-files")??"500",10),a=n("namespace")??"cachly:sem:code";(!s||!S)&&(console.error(`
298
+ `),console.log(` Dashboard: ${j(`/instances/${l.id}`,u)}`),console.log(` Step-by-step guide: ${j("/docs/setup",u)}
299
+ `),f.close(),await new Promise(b=>setTimeout(b,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=a=>{const u=t.indexOf(`--${a}`);return u!==-1?t[u+1]:void 0},o=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),s=n("instance-id")||U(),i=parseInt(n("max-files")??"500",10),r=n("namespace")??"cachly:sem:code";(!s||!S)&&(console.error(`
300
300
  \u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
301
301
  `),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest index ./my-project
302
302
  `),process.exit(1)),console.log(`
303
303
  \u{1F4C2} Indexing: ${o}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max files: ${i}
304
- `);try{const r=await J("index_project",{instance_id:s,dir:o,max_files:i,ttl:604800,namespace:a});console.log(r),console.log(`
304
+ `);try{const a=await J("index_project",{instance_id:s,dir:o,max_files:i,ttl:604800,namespace:r});console.log(a),console.log(`
305
305
  \u2705 Indexing complete.
306
- `)}catch(r){console.error(`
307
- \u274C Indexing failed: ${r.message}
308
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=a=>{const r=t.indexOf(`--${a}`);return r!==-1?t[r+1]:void 0},o=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),s=n("instance-id")||z(),i=parseInt(n("max-commits")??"50",10);(!s||!S)&&(console.error(`
306
+ `)}catch(a){console.error(`
307
+ \u274C Indexing failed: ${a.message}
308
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=r=>{const a=t.indexOf(`--${r}`);return a!==-1?t[a+1]:void 0},o=e(n("dir")??t.find(r=>!r.startsWith("--"))??"."),s=n("instance-id")||U(),i=parseInt(n("max-commits")??"50",10);(!s||!S)&&(console.error(`
309
309
  \u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
310
310
  `),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest learn-git .
311
311
  `),process.exit(1)),console.log(`
312
312
  \u{1F9E0} Learning from git history: ${o}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max commits: ${i}
313
- `);try{const a=await J("brain_from_git",{instance_id:s,repo_path:o,limit:i});console.log(a),A("brain_from_git",{instance_id:s}),console.log(`
313
+ `);try{const r=await J("brain_from_git",{instance_id:s,repo_path:o,limit:i});console.log(r),A("brain_from_git",{instance_id:s}),console.log(`
314
314
  \u2705 Brain learned from your commits.
315
- `),await new Promise(r=>setTimeout(r,300))}catch(a){console.error(`
316
- \u274C learn-git failed: ${a.message}
317
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await gn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await hn(),process.argv[2]===yn&&await fn(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:z()||void 0};await wn(o),await xs(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=z(),t=_n(await gt(),e||void 0),n=t.eigene,o=fs(n),s=n.slice(-5);if(console.log(`
315
+ `),await new Promise(a=>setTimeout(a,300))}catch(r){console.error(`
316
+ \u274C learn-git failed: ${r.message}
317
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await Hn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Mn(),process.argv[2]===Dn&&await zn(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 Wn(o),await Ys(process.env.CACHLY_BRAIN_INSTANCE_ID??P,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=Yn(await kt(),e||void 0),n=t.eigene,o=Ds(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
- Last entries:`);for(const i of s){const a=i.prevented>0?`+${i.prevented} prevented`:`-${i.injected} injected`;console.log(` \u2022 ${i.ts.slice(0,19)} ${i.event}: ${a}${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),a={projekt:n((r=>{const d=s.indexOf(`--${r}`);return d!==-1?s[d+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:G(),instanz:z(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:r=>console.log(r),frage:async r=>{const d=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await d.question(r)).trim())}finally{d.close()}}};process.exit(await nn(s,a))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:a,checkHooks:r,checkLedger:d,renderDoctorReport:f,doctorExitCode:l}=await import("./doctor.js"),u=[e(),t(S),await n(x),await o(x,S),s(z()||N),await i(x,S,z()||N),r(a(process.cwd())),d(await gt(),vn())];console.log(f(u)),process.exit(l(u))}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=Kt();if(e)try{const t=await fetch(Gt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:qt(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(S=n.access_token,ae(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).
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 u=s.indexOf(`--${a}`);return u!==-1?s[u+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const u=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await u.question(a)).trim())}finally{u.close()}}};process.exit(await Tn(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:u,renderDoctorReport:p,doctorExitCode:c}=await import("./doctor.js"),d=[e(),t(S),await n(x),await o(x,S),s(U()||P),await i(x,S,U()||P),a(r(process.cwd())),u(await kt(),Jn())];console.log(p(d)),process.exit(c(d))}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??P;(!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=no();if(e)try{const t=await fetch(io(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:so(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
- `),A("m2m_auth_failed",{reason:"network"})}}const Ms=["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&&!Ms.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&oo){const o=`
324
+ `),A("m2m_auth_failed",{reason:"network"})}}const di=["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&&!di.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&mo){const o=`
325
325
  \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\u2550\u2550\u2550\u2550\u2557
326
326
  \u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
327
327
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
@@ -341,7 +341,7 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
341
341
  \u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call opens the browser once to sign in (GitHub, Google or e-mail).
342
342
  (Own account: npx @cachly-dev/mcp-server@latest autopilot)
343
343
 
344
- `);else{const e=Jt(S);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
344
+ `);else{const e=eo(S);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
345
345
  \u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
346
346
  All tool calls will fail. Get a fresh token at ${j("/setup-ai","jwt-expiry")}
347
347
 
@@ -349,7 +349,7 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
349
349
  \u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
350
350
  Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
351
351
 
352
- `)}}process.env.PORT||Xn({aktuelle:Qn(H)});const Ce=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Ce){const{createServer:e}=await import("node:http");e((n,o)=>{const s=new URL(n.url??"/",`http://localhost:${Ce}`);if(s.pathname==="/health"){o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"ok",version:H,zeroResults:{total:jo,last10:Ro.slice(-10).map(i=>({query:i.query,ts:new Date(i.ts).toISOString()}))}}));return}if(s.pathname==="/mcp"||s.pathname==="/"){(async()=>{const i=js(),a=new so({sessionIdGenerator:void 0});o.on("close",()=>{a.close().catch(()=>{}),i.close().catch(()=>{})});try{await i.connect(a),await a.handleRequest(n,o)}catch(r){process.stderr.write(`cachly-mcp HTTP: ${r.message}
353
- `),o.headersSent||(o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:r.message})))}})();return}o.writeHead(404),o.end("not found")}).listen(Ce,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Ce}
354
- `)})}else{const e=new no;F("start: Module geladen, stdio verbinden"),await K.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(et=!0,Jn(()=>Zn(tt)),uo(),ns(),ts(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
355
- `),(async()=>{await De().catch(()=>{});for(const[,o]of X)await o.quit().catch(()=>{});process.exit(0)})()}))}Fe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Vo as CLAUDE_MD_MARKER_END,Go as CLAUDE_MD_MARKER_START,Eo as CROSS_LINGUAL_MAP,ce as EDITOR_FILES,Ao as STOPWORDS,Ut as anweisungsZeile,To as arabicLightStem,lt as buildClaudeMdBlock,Ls as buildMcpConfig,Z as buildServerEnv,Io as expandCrossLingual,So as extractTimestamp,Co as katakanaToRomaji,$o as levenshtein,Ps as mcpAddBefehl,Dt as mergeMcpConfig,ko as recencyBoost,Bo as reconnectOnce,_o as splitMultiQuery,yo as startBackgroundDevicePoll,xo as tokenize,zt as writeInstructions};
352
+ `)}}process.env.PORT||$s({aktuelle:_s(H)});const Be=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Be){jo(!0),S="",P="",oe(""),Ro();const e=Mo(async(s,i)=>{const r=await fetch(`${x}${s}`,{headers:{Authorization:`Bearer ${i}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),a=r.ok?await r.json().catch(()=>null):null;return{status:r.status,body:a}}),{createServer:t}=await import("node:http"),n=(s,i,r)=>{s.headersSent||(s.writeHead(i,{"Content-Type":"application/json",...i===401?{"WWW-Authenticate":'Bearer realm="cachly"'}:{}}),s.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:r},id:null})))};t((s,i)=>{const r=new URL(s.url??"/",`http://localhost:${Be}`);if(r.pathname==="/health"){i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(r.pathname==="/mcp"||r.pathname==="/"){(async()=>{const a=Oo(s.headersDistinct?.authorization??s.headers.authorization);if(a.art==="abgelehnt"){const d=a.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":a.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":a.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 n(i,401,d)}const u=Lo(s.headers["x-cachly-instance"]);if(u.art==="abgelehnt")return n(i,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");let p;if(a.art==="ok")try{const d=await e.loese(a.schluessel,u.art==="ok"?u.instanzId:void 0);p=Po(a.schluessel,d)}catch(d){return d instanceof zo?n(i,d.httpStatus,d.message):n(i,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const c=async()=>{const d=ni(),f=new ho({sessionIdGenerator:void 0});i.on("close",()=>{f.close().catch(()=>{}),d.close().catch(()=>{})});try{await d.connect(f),await f.handleRequest(s,i)}catch(y){process.stderr.write(`cachly-mcp HTTP: ${y.message}
353
+ `),i.headersSent||(i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:y.message})))}};await(p?Bo(p,c):c())})();return}i.writeHead(404),i.end("not found")}).listen(Be,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Be}
354
+ `)})}else{const e=new go;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,gs(()=>xs(lt)),_o(),Cs(),Ss(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
355
+ `),(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{xn as CLAUDE_MD_MARKER_END,vn as CLAUDE_MD_MARKER_START,en as CROSS_LINGUAL_MAP,ke as EDITOR_FILES,Vo as STOPWORDS,Xt as anweisungsZeile,Xo as arabicLightStem,yt as buildClaudeMdBlock,ai as buildMcpConfig,ee as buildServerEnv,Qo as expandCrossLingual,qo as extractTimestamp,Zo as katakanaToRomaji,Ko as levenshtein,ri as mcpAddBefehl,Vt as mergeMcpConfig,Go as recencyBoost,nn as reconnectOnce,Yo as splitMultiQuery,To as startBackgroundDevicePoll,Fo as tokenize,Zt as writeInstructions};