@cachly-dev/mcp-server 0.10.176 → 0.10.178

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,69 +1,69 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as gt}from"./herkunft.js";import{jwtExpiryMs as ht,checkJwt as ft,handleApiError as yt,diagnoseAuth as ge,planAuthHeal as Ae,readClientCredentialsFromEnv as bt,buildClientCredentialsBody as vt,clientCredentialsTokenUrl as xt}from"./auth.js";import{cachlyUrl as R}from"./cachly-url.js";import{nutzungsSchluessel as wt}from"./werkzeug-nutzung.js";import{istLieferung as _t,lieferSchluessel as $t,tokenDerAntwort as Ct,hatTreffer as At,trefferSchluessel as Se}from"./geliefert.js";import{notify as ke}from"./notifier.js";import{fileURLToPath as St}from"node:url";import{createRequire as kt}from"node:module";import{execFile as he}from"node:child_process";const Tt=process.argv[1]!=null&&(process.argv[1]===St(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Te}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as It}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as Et}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Ie,ErrorCode as oe,ListPromptsRequestSchema as Ee,ListResourceTemplatesRequestSchema as Re,ListResourcesRequestSchema as Ne,ListToolsRequestSchema as Le,McpError as Z}from"@modelcontextprotocol/sdk/types.js";import{Redis as Be}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",w=Ue()??"";re(w);const gn=process.env.CACHLY_EMBED_MODEL??"",D=(()=>{try{const e=kt(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"})(),Rt=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let B=xe(process.env.CACHLY_BRAIN_INSTANCE_ID),Q=0,se=null;async function Nt(){if(!w)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"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(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function je(){if(B)return B;if(!w)return"";if(se)return se;const e=Date.now();if(Q>0&&e-Q<3e4)return"";Q=e,se=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const s=(await t.json())?.data??[],o=s.find(i=>i.status==="running")??s.find(i=>i.status==="provisioning");if(o)return B=o.id,Q=0,B;const a=await Nt();if(a)return B=a,Q=0,be(a),B}}catch{}return""})();try{return await se}finally{se=null}}let fe=0;const Lt=6e4;let ne="";async function ye(e){try{const{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:a,dirname:i}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const p=a(r,".claude","mcp.json");let d={};if(o(p))try{d=JSON.parse(await s(p,"utf-8"))}catch{}d.mcpServers??={};const l=d.mcpServers.cachly;if(l)l.env??={},l.env.CACHLY_JWT=e;else{const y={};y.CACHLY_JWT=e,d.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:y}}await n(i(p),{recursive:!0}),await t(p,JSON.stringify(d,null,2),"utf-8");const h=[a(r,".cursor","mcp.json"),a(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(h.map(async y=>{if(o(y))try{const v=await s(y,"utf-8"),b=JSON.parse(v),u=b?.mcpServers?.cachly;u?.env&&(u.env.CACHLY_JWT=e,await t(y,JSON.stringify(b,null,2),"utf-8"))}catch{}}))}catch{}}async function be(e){if(e){ho(e,{apiKey:w});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),a=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!a)return;const i=[o(a,".claude","mcp.json"),o(a,".cursor","mcp.json"),o(a,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(i.map(async r=>{if(s(r))try{const p=JSON.parse(await n(r,"utf-8")),d=p?.mcpServers?.cachly;d?.env&&(d.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(r,JSON.stringify(p,null,2),"utf-8"))}catch{}}))}catch{}}}async function Bt(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`},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?(w=t.key,re(t.key),ye(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function ve(){const e=ge(w),t=Ae(e);if(t==="none")return ne="",!0;if(t==="refresh"){const n=Date.now();return n-fe>=Lt&&(fe=n,await Bt())?(ne="",!0):(ne=e.message,e.usable)}return ne=e.message,!1}function ie(e,t){const n=(o,a)=>{try{t?.(o,a)}catch{}},s=o=>{o?n(!1,o.code??o.message):n(!0)};try{process.platform==="win32"?he("cmd",["/c","start","",e],{windowsHide:!0},s):process.platform==="darwin"?he("open",[e],s):he("xdg-open",[e],s)}catch(o){n(!1,o instanceof Error?o.message:"unknown")}}let q=null;async function jt(){try{const e=await fetch(`${_}/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||R("/device","ambient-signin"),s=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:s,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 Ht(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return s.ok?s.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 s=await t().catch(()=>null);if(s||(s=await n().catch(()=>null)),!s)return"pending";if(s.access_token){let o=s.access_token;try{const a=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(a.ok){const i=await a.json();i.key&&(o=i.key)}}catch{}if(w=o,re(o),q=null,A("device_flow_completed"),ye(o),X(o),Q=0,await je(),B)try{const a=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(a.ok){const i=await a.json();if(i.status==="provisioning"){const r=Date.now()+2e4;for(;i.status==="provisioning"&&Date.now()<r;){await new Promise(d=>setTimeout(d,3e3));const p=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)}).catch(()=>null);if(p?.ok){const d=await p.json();i.status=d.status}else break}}}}catch{}return B&&be(B),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function He(e){if(e.polling)return"pending";e.polling=!0;try{return await Ht(e)}finally{e.polling=!1}}function Pt(e,t=He,n=o=>q===o,s=Ot){const o=async()=>{if(!n(e))return;let a="pending";try{a=await t(e)}catch{}if(a!=="done"){if(a==="expired"){n(e)&&(q=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function Ot(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as re}from"./embeddings.js";import{tokenize as Dt,splitMultiQuery as Mt,levenshtein as Jt,recencyBoost as Yt,extractTimestamp as Ut,STOPWORDS as Wt,katakanaToRomaji as Ft,arabicLightStem as zt,expandCrossLingual as qt,CROSS_LINGUAL_MAP as Gt,ZERO_RESULTS_LOG as Kt,zeroResultsTotal as Vt}from"./search.js";const G=new Map;function Zt(e){return e<=1?200:null}async function Y(e){if(!e)throw new Z(oe.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
2
+ import{setzeClientKennung as xt}from"./herkunft.js";import{jwtExpiryMs as _t,checkJwt as $t,handleApiError as Ct,diagnoseAuth as fe,planAuthHeal as Ie,readClientCredentialsFromEnv as At,buildClientCredentialsBody as St,clientCredentialsTokenUrl as kt}from"./auth.js";import{cachlyUrl as R}from"./cachly-url.js";import{nutzungsSchluessel as Tt}from"./werkzeug-nutzung.js";import{istLieferung as It,lieferSchluessel as Et,tokenDerAntwort as Rt,hatTreffer as Nt,trefferSchluessel as Ee}from"./geliefert.js";import{notify as Re}from"./notifier.js";import{fileURLToPath as Ne}from"node:url";import{createRequire as Lt}from"node:module";import{execFile as he}from"node:child_process";const Bt=process.argv[1]!=null&&(process.argv[1]===Ne(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Le}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as jt}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as Ht}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Be,ErrorCode as ne,ListPromptsRequestSchema as je,ListResourceTemplatesRequestSchema as He,ListResourcesRequestSchema as Pe,ListToolsRequestSchema as Oe,McpError as X}from"@modelcontextprotocol/sdk/types.js";import{Redis as De}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",x=Ke()??"";ce(x);const Bn=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=Lt(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"})(),Pt=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let B=$e(process.env.CACHLY_BRAIN_INSTANCE_ID),ee=0,ie=null,Me=!1;async function Ot(){let e=[];try{V.getClientCapabilities()?.roots&&(e=(await V.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Ho({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Ne})}function ye(){return Me?!/^(0|false|off|no|nein)$/i.test((process.env.CACHLY_STARTWISSEN??"").trim()):!1}function Je(e){!e||!ye()||No({instanzId:e,verbindung:D,ausGit:t=>_e("brain_from_git",t,D,P),projektOrdner:Ot,einbetten:t=>zt(t,{geduld:"lang"}),hatEinbettung:qt,melde:t=>A("brain_from_git",{...x?{api_key:x}:{},instance_id:e,total:t,auto:"startwissen"})})}async function Dt(){if(!x)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"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(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function Ye(){if(B)return B;if(!x)return"";if(ie)return ie;const e=Date.now();if(ee>0&&e-ee<3e4)return"";ee=e,ie=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const s=(await t.json())?.data??[],o=s.find(r=>r.status==="running")??s.find(r=>r.status==="provisioning");if(o)return B=o.id,ee=0,B;const c=await Dt();if(c)return B=c,ee=0,Ve(c,ye()),we(c),Je(c),B}}catch{}return""})();try{return await ie}finally{ie=null}}let be=0;const Mt=6e4;let se="";async function ve(e){try{const{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:c,dirname:r}=await import("node:path"),a=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!a)return;const u=c(a,".claude","mcp.json");let d={};if(o(u))try{d=JSON.parse(await s(u,"utf-8"))}catch{}d.mcpServers??={};const l=d.mcpServers.cachly;if(l)l.env??={},l.env.CACHLY_JWT=e;else{const y={};y.CACHLY_JWT=e,d.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:y}}await n(r(u),{recursive:!0}),await t(u,JSON.stringify(d,null,2),"utf-8");const g=[c(a,".cursor","mcp.json"),c(a,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(g.map(async y=>{if(o(y))try{const v=await s(y,"utf-8"),h=JSON.parse(v),p=h?.mcpServers?.cachly;p?.env&&(p.env.CACHLY_JWT=e,await t(y,JSON.stringify(h,null,2),"utf-8"))}catch{}}))}catch{}}async function we(e){if(e){So(e,{apiKey:x});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),c=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!c)return;const r=[o(c,".claude","mcp.json"),o(c,".cursor","mcp.json"),o(c,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(s(a))try{const u=JSON.parse(await n(a,"utf-8")),d=u?.mcpServers?.cachly;d?.env&&(d.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function Jt(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},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?(x=t.key,ce(t.key),ve(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function xe(){const e=fe(x),t=Ie(e);if(t==="none")return se="",!0;if(t==="refresh"){const n=Date.now();return n-be>=Mt&&(be=n,await Jt())?(se="",!0):(se=e.message,e.usable)}return se=e.message,!1}function ae(e,t){const n=(o,c)=>{try{t?.(o,c)}catch{}},s=o=>{o?n(!1,o.code??o.message):n(!0)};try{process.platform==="win32"?he("cmd",["/c","start","",e],{windowsHide:!0},s):process.platform==="darwin"?he("open",[e],s):he("xdg-open",[e],s)}catch(o){n(!1,o instanceof Error?o.message:"unknown")}}let G=null;async function Yt(){try{const e=await fetch(`${_}/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||R("/device","ambient-signin"),s=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:s,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 Ut(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return s.ok?s.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 s=await t().catch(()=>null);if(s||(s=await n().catch(()=>null)),!s)return"pending";if(s.access_token){let o=s.access_token;try{const c=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(c.ok){const r=await c.json();r.key&&(o=r.key)}}catch{}if(x=o,ce(o),G=null,A("device_flow_completed"),ve(o),K(o),ee=0,await Ye(),B)try{const c=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(c.ok){const r=await c.json();if(r.status==="provisioning"){const a=Date.now()+2e4;for(;r.status==="provisioning"&&Date.now()<a;){await new Promise(d=>setTimeout(d,Ro));const u=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)}).catch(()=>null);if(u?.ok){const d=await u.json();r.status=d.status}else break}}}}catch{}return B&&we(B),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function Ue(e){if(e.polling)return"pending";e.polling=!0;try{return await Ut(e)}finally{e.polling=!1}}function Wt(e,t=Ue,n=o=>G===o,s=Ft){const o=async()=>{if(!n(e))return;let c="pending";try{c=await t(e)}catch{}if(c!=="done"){if(c==="expired"){n(e)&&(G=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function Ft(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ce,computeEmbedding as zt,hasEmbedProvider as qt}from"./embeddings.js";import{tokenize as Gt,splitMultiQuery as Kt,levenshtein as Vt,recencyBoost as Zt,extractTimestamp as Qt,STOPWORDS as Xt,katakanaToRomaji as eo,arabicLightStem as to,expandCrossLingual as oo,CROSS_LINGUAL_MAP as no,ZERO_RESULTS_LOG as so,zeroResultsTotal as ro}from"./search.js";const te=new Map;function io(e){return e<=1?200:null}async function D(e){if(!e)throw new X(ne.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.`);if(G.has(e))return G.get(e);let t=await O(`/api/v1/instances/${e}`);if(t.status==="provisioning"){const i=Date.now()+Rt;for(;t.status==="provisioning"&&Date.now()<i;)await new Promise(r=>setTimeout(r,3e3)),t=await O(`/api/v1/instances/${e}`)}if(t.status!=="running"){fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...w?{Authorization:`Bearer ${w}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let i;throw t.status==="provisioning"?i=`\u23F3 Brain instance "${t.name}" is still starting up.
9
+ \u2022 Reach us at support@cachly.dev.`);const t=te.get(e);return t||Eo(ao,e,()=>co(e))}const ao=new Map;async function co(e){W("verbindung: Instanz abfragen");let t=await P(`/api/v1/instances/${e}`);if(W(`verbindung: Instanz ${t.status}`),t=await Io(t,()=>P(`/api/v1/instances/${e}`),{fristMs:Pt,melde:r=>W(`verbindung: Instanz ${r.status}`)}),t.status!=="running"){fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let r;throw t.status==="provisioning"?r=`\u23F3 Brain instance "${t.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"?i=`\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.`:t.status==="failed"?r=`\u274C Brain instance "${t.name}" failed to start.
12
12
 
13
13
  Our system will retry automatically. Check status at: ${R("/instances","instance-error")}
14
- If this persists, contact support@cachly.dev.`:t.status==="suspended"?i=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
14
+ If this persists, contact support@cachly.dev.`:t.status==="suspended"?r=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
15
15
 
16
- Update your payment method at: ${R("/billing","upgrade")}`:t.status==="pending_payment"?i=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
16
+ Update your payment method at: ${R("/billing","upgrade")}`:t.status==="pending_payment"?r=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
17
17
 
18
- Complete your checkout at: ${R("/instances","upgrade")}`:i=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
18
+ Complete your checkout at: ${R("/instances","upgrade")}`:r=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
19
19
 
20
20
  \u2022 View your instance at: ${R("/instances","instance-error")}
21
- \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(oe.InvalidRequest,i)}if(!t.host||!t.port)throw new Z(oe.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,s=t.tls_enabled!==!1;try{const i=await O(`/api/v1/instances/${e}/connection`);n=i.password??void 0,s=i.tls_enabled!==!1}catch(i){const r=i instanceof Error?i.message:String(i);if(r.includes("401")||r.includes("403")||r.includes("Unauthorized"))throw new Z(oe.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=new Be({host:t.host,port:t.port,password:n||void 0,commandTimeout:8e3,...s?{tls:{}}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:Zt,maxRetriesPerRequest:1,keepAlive:15e3}),a=()=>{G.delete(e),o.disconnect()};o.on("error",a),o.on("end",a);try{await o.connect()}catch(i){o.disconnect();const r=i instanceof Error?i.message:String(i);throw fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...w?{Authorization:`Bearer ${w}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:r,version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(oe.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new X(ne.InvalidRequest,r)}if(!t.host||!t.port)throw new X(ne.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,s=t.tls_enabled!==!1;try{const r=await P(`/api/v1/instances/${e}/connection`);n=r.password??void 0,s=r.tls_enabled!==!1,W("verbindung: Zugangsdaten da")}catch(r){const a=r instanceof Error?r.message:String(r);if(a.includes("401")||a.includes("403")||a.includes("Unauthorized"))throw new X(ne.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=new De({host:t.host,port:t.port,password:n||void 0,commandTimeout:8e3,...s?{tls:{}}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:io,maxRetriesPerRequest:1,keepAlive:15e3}),c=()=>{te.delete(e),o.disconnect()};o.on("error",c),o.on("end",c);try{await o.connect()}catch(r){o.disconnect();const a=r instanceof Error?r.message:String(r);throw fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:a,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new X(ne.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.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: ${r}`)}return G.set(e,o),o}async function O(e,t={},n=!1){n||Ae(ge(w))!=="none"&&await ve(),ft(w);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${_}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,...t.headers}});if(!o.ok){if(o.status===401&&!n&&(fe=0,await ve()))return O(e,t,!0);const i=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;yt(o.status,i)}if(o.status!==204)return o.json()}import{handleBrainTool as Qt}from"./handlers/brain.js";import{handleContextTool as Xt}from"./handlers/context.js";import{handleInstanceTool as eo}from"./handlers/instances.js";import{handleCacheTool as to}from"./handlers/cache.js";import{handleTeamTool as oo}from"./handlers/team.js";import{handleRoadmapTool as no}from"./handlers/roadmap.js";import{handleAdvancedTool as so}from"./handlers/advanced.js";import{handleSyndicateTool as io}from"./handlers/syndicate.js";import{handleFedbrainTool as Pe,_lastBrainFromGitCounts as de}from"./handlers/fedbrain.js";import{extractFirstRecallProof as ro,renderFirstRecallProof as ao}from"./first-recall-proof.js";import{installClsPostCommitHook as Oe,CLS_HOOK_VERSION as De}from"./cls-hook.js";import{installAmbientHooks as Me,AMBIENT_HOOK_VERSION as Je}from"./ambient-hooks.js";import{hookHauptlauf as co,auffrischenHauptlauf as lo}from"./ambient-hook.js";import{rahmeAntwort as po}from"./antwort-rahmen.js";import{appendLedgerEntry as uo,readLedger as Ye,defaultLedgerPath as mo,reportLedgerEntry as go}from"./ambient-ledger.js";import{resolveApiKey as Ue,saveApiKey as X,saveInstanceId as ho}from"./credentials.js";import{holeSofortTest as fo}from"./sofort-test.js";import{sichereZugang as yo,echterWert as xe}from"./zugang.js";import{beiStdinEnde as bo}from"./stdin-ende.js";import{merkeWerkzeugAufruf as vo,starteBrandWachhund as xo}from"./brand-wachhund.js";import{sichtbareWerkzeuge as wo,VERTEILER as We}from"./werkzeug-auswahl.js";import{buildLessonsMarkdown as _o,buildLessonsJsonl as $o,vonRohLektion as Co}from"./brain-export.js";import{detectEditor as Ao}from"./editor.js";import{milestoneSent as Fe,markMilestoneSent as ze}from"./funnel-milestones.js";import{kostprobeUebrig as So,kostprobeVerbrauchen as ko,kostprobeHinweis as To,schrankeNachKostproben as Io}from"./kostprobe.js";import{netBalance as Eo}from"./ambient-recall.js";import{handleShareTool as qe}from"./handlers/share.js";import{handleVizTool as Ro}from"./handlers/viz.js";import{commitArt as No,istRueckbau as Lo,zaehleLektionen as Bo}from"./commit-art.js";import{TOOLS as ae}from"./tools.js";let Ge=!1,pe=!1;function Ke(){return Ao()}function jo(e){if(!e)return null;const t=e.match(/\*\*💡\s+([^*]+)\*\*/),n=e.match(/^>\s+(.+)$/m);if(!t||!n)return null;const s=t[1].trim(),o=n[1].trim();return!s||!o?null:{topic:s,what:o}}function Ho(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!n.sub)return;let s=2166136261;for(let o=0;o<n.sub.length;o++)s^=n.sub.charCodeAt(o),s=s*16777619>>>0;return s.toString(16).padStart(8,"0")+n.sub.length.toString(16).padStart(4,"0")}catch{return}}function A(e,t,n){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const s=w?Ho(w):void 0;fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:D,editor:Ke(),...w?{jwt:w}:{},...s?{user_fingerprint:s}:{},...n?{metrics:n}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function Po(e,t){return go({apiUrl:_,jwt:w,instanceId:e},t)}async function Oo(e){if(!Ge&&process.env.CACHLY_NO_TELEMETRY!=="1"){Ge=!0;try{await fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:D,editor:Ke(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const Do=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"]),Mo={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."},Ve=R("/billing","upgrade"),Ze=new Map;async function Jo(e){const t=Ze.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const s=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:s,isFree:s==="free"||s===""};return Ze.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function Yo(e,t){if(!Do.has(e)||!t)return null;const{isFree:n}=await Jo(t);if(!n)return null;const s=Mo[e]??"A Premium intelligence feature.";if(So(e)){const o=ko(e);return{kostprobe:To(e,o,Ve)}}return{sperre:Io(e,s,Ve)}}async function Uo(e,t){try{await(await Y(e)).hincrby(wt(e),t,1)}catch{}}async function Wo(e,t,n){if(_t(t))try{const s=await Y(e),o=At(n);await s.incrby($t(e),o?Ct(n):0),await s.hincrby(Se(e),"abrufe",1),o&&await s.hincrby(Se(e),"treffer",1)}catch{}}async function Fo(e){const t=await jt();return t?(q=t,A("device_flow_started",{tool:e}),ie(t.verifyUrl,(n,s)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:s??"unknown",stelle:"tool"}),process.stderr.write(`
25
+ \u2022 Technical detail: ${a}`)}return te.set(e,o),W("verbindung: Valkey verbunden"),o}async function P(e,t={},n=!1){n||Ie(fe(x))!=="none"&&await xe(),$t(x);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${_}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`,...t.headers}});if(!o.ok){if(o.status===401&&!n&&(be=0,await xe()))return P(e,t,!0);const r=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;Ct(o.status,r)}if(o.status!==204)return o.json()}import{handleBrainTool as lo}from"./handlers/brain.js";import{handleContextTool as po}from"./handlers/context.js";import{handleInstanceTool as uo}from"./handlers/instances.js";import{handleCacheTool as mo}from"./handlers/cache.js";import{handleTeamTool as go}from"./handlers/team.js";import{handleRoadmapTool as fo}from"./handlers/roadmap.js";import{handleAdvancedTool as ho}from"./handlers/advanced.js";import{handleSyndicateTool as yo}from"./handlers/syndicate.js";import{handleFedbrainTool as _e,_lastBrainFromGitCounts as pe}from"./handlers/fedbrain.js";import{extractFirstRecallProof as bo,renderFirstRecallProof as vo}from"./first-recall-proof.js";import{installClsPostCommitHook as We,CLS_HOOK_VERSION as Fe}from"./cls-hook.js";import{installAmbientHooks as ze,AMBIENT_HOOK_VERSION as qe}from"./ambient-hooks.js";import{hookHauptlauf as wo,auffrischenHauptlauf as xo}from"./ambient-hook.js";import{rahmeAntwort as _o}from"./antwort-rahmen.js";import{appendLedgerEntry as $o,readLedger as Ge,defaultLedgerPath as Co,reportLedgerEntry as Ao}from"./ambient-ledger.js";import{resolveApiKey as Ke,saveApiKey as K,saveInstanceId as So}from"./credentials.js";import{holeSofortTest as ko}from"./sofort-test.js";import{sichereZugang as To,echterWert as $e}from"./zugang.js";import{zeitpunkt as W}from"./zeitmessung.js";import{warteAufLaufendeInstanz as Io,gemeinsamerAufbau as Eo,PROVISION_TAKT_MS as Ro}from"./instanz-warten.js";import{merkeNeuesBrain as Ve}from"./leeres-brain.js";import{starteStartwissen as No,startwissenGestartet as Lo,beanspruchStartwissen as Bo,holeStartwissenHinweis as jo,waehleProjektOrdner as Ho}from"./startwissen.js";import{beiStdinEnde as Po}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Oo,starteBrandWachhund as Do}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Mo,VERTEILER as Ze}from"./werkzeug-auswahl.js";import{buildLessonsMarkdown as Jo,buildLessonsJsonl as Yo,vonRohLektion as Uo}from"./brain-export.js";import{detectEditor as Wo}from"./editor.js";import{milestoneSent as Qe,markMilestoneSent as Xe}from"./funnel-milestones.js";import{kostprobeUebrig as Fo,kostprobeVerbrauchen as zo,kostprobeHinweis as qo,schrankeNachKostproben as Go}from"./kostprobe.js";import{netBalance as Ko}from"./ambient-recall.js";import{handleShareTool as et}from"./handlers/share.js";import{handleVizTool as Vo}from"./handlers/viz.js";import{commitArt as Zo,istRueckbau as Qo,zaehleLektionen as Xo}from"./commit-art.js";import{TOOLS as le}from"./tools.js";let tt=!1,ue=!1;function ot(){return Wo()}function en(e){if(!e)return null;const t=e.match(/\*\*💡\s+([^*]+)\*\*/),n=e.match(/^>\s+(.+)$/m);if(!t||!n)return null;const s=t[1].trim(),o=n[1].trim();return!s||!o?null:{topic:s,what:o}}function tn(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!n.sub)return;let s=2166136261;for(let o=0;o<n.sub.length;o++)s^=n.sub.charCodeAt(o),s=s*16777619>>>0;return s.toString(16).padStart(8,"0")+n.sub.length.toString(16).padStart(4,"0")}catch{return}}function A(e,t,n){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const s=x?tn(x):void 0;fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:M,editor:ot(),...x?{jwt:x}:{},...s?{user_fingerprint:s}:{},...n?{metrics:n}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function on(e,t){return Ao({apiUrl:_,jwt:x,instanceId:e},t)}async function nn(e){if(!tt&&process.env.CACHLY_NO_TELEMETRY!=="1"){tt=!0;try{await fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:M,editor:ot(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const sn=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"]),rn={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=R("/billing","upgrade"),st=new Map;async function an(e){const t=st.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const s=((await P(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:s,isFree:s==="free"||s===""};return st.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function cn(e,t){if(!sn.has(e)||!t)return null;const{isFree:n}=await an(t);if(!n)return null;const s=rn[e]??"A Premium intelligence feature.";if(Fo(e)){const o=zo(e);return{kostprobe:qo(e,o,nt)}}return{sperre:Go(e,s,nt)}}async function ln(e,t){try{await(await D(e)).hincrby(Tt(e),t,1)}catch{}}async function dn(e,t,n){if(It(t))try{const s=await D(e),o=Nt(n);await s.incrby(Et(e),o?Rt(n):0),await s.hincrby(Ee(e),"abrufe",1),o&&await s.hincrby(Ee(e),"treffer",1)}catch{}}async function pn(e){const t=await Yt();return t?(G=t,A("device_flow_started",{tool:e}),ae(t.verifyUrl,(n,s)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:s??"unknown",stelle:"tool"}),process.stderr.write(`
26
26
  cachly: could not open a browser (${s??"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
- `)}),Pt(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 Free forever \xB7 No credit card \xB7 ${ae.length} MCP tools \xB7 GDPR \xB7 EU servers`].join(`
31
+ `)}),Wt(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: ${R("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
33
- `)}async function U(e,t){if(!w){if(Oo(e),q){const c=await He(q);return c==="done"?U(e,t):c==="expired"?(A("device_flow_failed",{reason:"timeout"}),q=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: **${q.verifyUrl}**`,`Code: **${q.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
- `)}return yo({schluessel:w,konfigurierteInstanz:B,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:()=>fo({apiUrl:_,version:D,speichern:()=>{}}),ablagen:{setzeSchluessel:c=>{w=c},setEmbedJwt:re,saveApiKey:c=>X(c),persistApiKeyToConfig:ye,merkeInstanz:c=>{B=c,Q=0},persistInstanceIdToConfig:be},meldeEreignis:A,werkzeug:()=>U(e,t),anmelden:()=>Fo(e)})}if(!t.instance_id){const c=await je();c&&(t={...t,instance_id:c})}const n=await Yo(e,t.instance_id);let s="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;s=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&Uo(t.instance_id,e);const o=await Qt(e,t,Y,O);if(o!==null){typeof t.instance_id=="string"&&t.instance_id&&Wo(t.instance_id,e,String(o??"")),!pe&&w&&(pe=!0,Fe("first_call_success")||(ze("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""})));const c=t.instance_id??B??"",x=w?{api_key:w,instance_id:c}:{instance_id:c};if(e==="recall_best_solution")A("recall_best_solution",x);else if(e==="learn_from_attempts")A("learn_from_attempts",x);else if(e==="session_start"){A("session_start",x,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const g=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=g.includes("Welcome! Your AI Brain is live.");if(!N&&g.length>100)A("recall_best_solution",x);else if(N&&t.workspace_path)try{const j=await Pe("brain_from_git",{instance_id:c,repo_path:t.workspace_path,limit:50},Y,O);if(j!==null){A("brain_from_git",{...x,...de??{}}),A("recall_best_solution",x);let $="";if((de?.total??0)===0)try{const f=await qe("brain_seed_starter",{instance_id:c},Y,O);f&&(A("brain_seed_starter",{...x,auto:!0},{seeded_count:16,auto:!0}),$=`
33
+ `)}async function un(e){if(!e)return!0;if(Lo(e))return!1;try{return await Bo(await D(e),"sitzungsstart")}catch{return!0}}async function U(e,t){if(!x){if(nn(e),G){const i=await Ue(G);return i==="done"?U(e,t):i==="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 To({schluessel:x,konfigurierteInstanz:B,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{W("sofort-test: Anfang");const i=await ko({apiUrl:_,version:M,speichern:()=>{}});return W(`sofort-test: ${i?"Brain angelegt":"kein Test"}`),i&&Ve(i.instanzId,ye()),i},ablagen:{setzeSchluessel:i=>{x=i},setEmbedJwt:ce,saveApiKey:i=>K(i),persistApiKeyToConfig:ve,merkeInstanz:i=>{B=i,ee=0},persistInstanceIdToConfig:we},meldeEreignis:A,werkzeug:()=>U(e,t),anmelden:()=>pn(e),neuesBrain:Je})}if(!t.instance_id){const i=await Ye();i&&(t={...t,instance_id:i})}const n=await cn(e,t.instance_id);let s="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;s=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&ln(t.instance_id,e),W(`werkzeug ${e}: Zugang und Tarif geklaert`);const o=await lo(e,t,D,P);if(W(`werkzeug ${e}: Brain-Werkzeug fertig`),o!==null){typeof t.instance_id=="string"&&t.instance_id&&dn(t.instance_id,e,String(o??"")),!ue&&x&&(ue=!0,Qe("first_call_success")||(Xe("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""})));const i=t.instance_id??B??"",w=x?{api_key:x,instance_id:i}:{instance_id:i};if(e==="recall_best_solution")A("recall_best_solution",w);else if(e==="learn_from_attempts")A("learn_from_attempts",w);else if(e==="session_start"){A("session_start",w,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const f=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=f.includes("Welcome! Your AI Brain is live.");if(!N&&f.length>100)A("recall_best_solution",w);else if(N&&t.workspace_path&&await un(i))try{const j=await _e("brain_from_git",{instance_id:i,repo_path:t.workspace_path,limit:50},D,P);if(j!==null){A("brain_from_git",{...w,...pe??{}}),A("recall_best_solution",w);let $="";if((pe?.total??0)===0)try{const b=await et("brain_seed_starter",{instance_id:i},D,P);b&&(A("brain_seed_starter",{...w,auto:!0},{seeded_count:16,auto:!0}),$=`
35
35
  ---
36
- `+String(f))}catch{}const k=String(j),T=de?.total??0,H=T>0?`
36
+ `+String(b))}catch{}const k=String(j),T=pe?.total??0,H=T>0?`
37
37
  \u2705 **Brain bootstrapped from git \u2014 ${T} lesson${T===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(k||$||H)return String(o)+H+`
38
38
  ---
39
- `+k+$}}catch(j){return A("brain_from_git_failed",{...x,reason:j instanceof Error?j.message.slice(0,120):"unknown"}),String(o)+`
39
+ `+k+$}}catch(j){return A("brain_from_git_failed",{...w,reason:j instanceof Error?j.message.slice(0,120):"unknown"}),String(o)+`
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",x);else if(e==="smart_recall"){const g=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=g.length>50&&!g.includes("No lessons found")&&!g.includes("no lessons")&&!g.includes("No matches found");if(A("smart_recall",x,{hit:N,topic:String(t.query??"").slice(0,80)}),N&&A("recall_best_solution",x),ne&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ne.split(`
42
+ > Run \`brain_from_git(instance_id="`+i+'", 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",w);else if(e==="smart_recall"){const f=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=f.length>50&&!f.includes("No lessons found")&&!f.includes("no lessons")&&!f.includes("No matches found");if(A("smart_recall",w,{hit:N,topic:String(t.query??"").slice(0,80)}),N&&A("recall_best_solution",w),se&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${se.split(`
43
43
  `)[0]}
44
44
 
45
- ${o}`}return o}const a=await Xt(e,t,Y,O);if(a!==null)return!pe&&w&&(pe=!0,Fe("first_call_success")||(ze("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""}))),a;const i=await eo(e,t,Y,O);if(i!==null)return i;const r=await to(e,t,Y,O);if(r!==null)return r;const p=c=>s?c+s:c,d=await oo(e,t,Y,O);if(d!==null)return p(d);const l=await no(e,t,Y,O);if(l!==null)return l;const h=await so(e,t,Y,O);if(h!==null)return p(h);const y=await io(e,t,Y,O);if(y!==null){if(e==="brain_predict"){const c=t.instance_id??B??"";A("brain_predict",w?{api_key:w,instance_id:c}:{instance_id:c})}return p(y)}const v=await qe(e,t,Y,O);if(v!==null)return v;const b=await Ro(e,t,Y,O);if(b!==null)return b;const u=await Pe(e,t,Y,O);if(u!==null){const c=t.instance_id??B??"",x=w?{api_key:w,instance_id:c}:{instance_id:c};if(e==="brain_from_git"){const g=de;A("brain_from_git",{...x,...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",x);return u}switch(e){case"get_api_status":{let c="unknown";try{const S=await fetch(`${_}/health`,{signal:AbortSignal.timeout(8e3)});if(S.ok){const $=await S.json();c=`${$.status??"ok"} (db: ${$.db??"?"})`}else c=`HTTP ${S.status}`}catch(S){c=`unreachable: ${S.message}`}if(!w)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${c}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${R("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
- `);let x="\u274C invalid JWT format";try{const S=w.split(".");if(S.length===3){const $=JSON.parse(Buffer.from(S[1],"base64url").toString("utf-8")),k=$.sub??"(unknown)",T=$.iss??"(unknown)",H=T.includes("keycloak")?"Keycloak":"OIDC",f=$.exp?new Date($.exp*1e3):null,I=f?f<new Date:!1;x=["\u2705 JWT decoded",` Sub (user ID): ${k}`,` Provider: ${H}`,` Issuer: ${T}`,` Expires: ${f?f.toISOString():"never"} ${I?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
- `)}}catch{x="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let g="";try{const $=(await O("/api/v1/instances")).data??[];if($.length===0)g=`
45
+ ${o}`}return o}const c=await po(e,t,D,P);if(c!==null)return!ue&&x&&(ue=!0,Qe("first_call_success")||(Xe("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""}))),c;const r=await uo(e,t,D,P);if(r!==null)return r;const a=await mo(e,t,D,P);if(a!==null)return a;const u=i=>s?i+s:i,d=await go(e,t,D,P);if(d!==null)return u(d);const l=await fo(e,t,D,P);if(l!==null)return l;const g=await ho(e,t,D,P);if(g!==null)return u(g);const y=await yo(e,t,D,P);if(y!==null){if(e==="brain_predict"){const i=t.instance_id??B??"";A("brain_predict",x?{api_key:x,instance_id:i}:{instance_id:i})}return u(y)}const v=await et(e,t,D,P);if(v!==null)return v;const h=await Vo(e,t,D,P);if(h!==null)return h;const p=await _e(e,t,D,P);if(p!==null){const i=t.instance_id??B??"",w=x?{api_key:x,instance_id:i}:{instance_id:i};if(e==="brain_from_git"){const f=pe;A("brain_from_git",{...w,...f??{}},f?{fixes:f.fixes,features:f.features,refactors:f.refactors,total:f.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",w);return p}switch(e){case"get_api_status":{let i="unknown";try{const S=await fetch(`${_}/health`,{signal:AbortSignal.timeout(8e3)});if(S.ok){const $=await S.json();i=`${$.status??"ok"} (db: ${$.db??"?"})`}else i=`HTTP ${S.status}`}catch(S){i=`unreachable: ${S.message}`}if(!x)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${i}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${R("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
+ `);let w="\u274C invalid JWT format";try{const S=x.split(".");if(S.length===3){const $=JSON.parse(Buffer.from(S[1],"base64url").toString("utf-8")),k=$.sub??"(unknown)",T=$.iss??"(unknown)",H=T.includes("keycloak")?"Keycloak":"OIDC",b=$.exp?new Date($.exp*1e3):null,I=b?b<new Date:!1;w=["\u2705 JWT decoded",` Sub (user ID): ${k}`,` Provider: ${H}`,` Issuer: ${T}`,` Expires: ${b?b.toISOString():"never"} ${I?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
+ `)}}catch{w="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let f="";try{const $=(await P("/api/v1/instances")).data??[];if($.length===0)f=`
48
48
 
49
49
  \u{1F9E0} **Brain Instances:** none \u2014 create one at ${R("/instances","api-status")}`;else{const k=[`
50
50
 
51
- \u{1F9E0} **Brain Instances:**`];for(const T of $){const H=T.status==="running"?"\u{1F7E2}":T.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",f=T.id===B?" \u2190 active":"";if(k.push(` ${H} **${T.name}** (\`${T.id}\`) \xB7 ${T.status}${f}`),T.status==="running"&&T.host){const I=G.get(T.id);if(I)try{await I.ping(),k.push(" \u{1F493} Redis: connected")}catch{k.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else k.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else T.status==="provisioning"?k.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):T.status!=="running"&&k.push(` \u274C Not reachable (status: ${T.status})`)}g=k.join(`
52
- `)}}catch(S){g=`
51
+ \u{1F9E0} **Brain Instances:**`];for(const T of $){const H=T.status==="running"?"\u{1F7E2}":T.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",b=T.id===B?" \u2190 active":"";if(k.push(` ${H} **${T.name}** (\`${T.id}\`) \xB7 ${T.status}${b}`),T.status==="running"&&T.host){const I=te.get(T.id);if(I)try{await I.ping(),k.push(" \u{1F493} Redis: connected")}catch{k.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else k.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else T.status==="provisioning"?k.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):T.status!=="running"&&k.push(` \u274C Not reachable (status: ${T.status})`)}f=k.join(`
52
+ `)}}catch(S){f=`
53
53
 
54
- \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${S.message}`}await ve();const N=ge(w),j=N.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":N.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${N.expiresInMs?` (${Math.round(N.expiresInMs/36e5)}h left)`:""}`:N.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${N.message.split(`
55
- `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${c}`,` ${j}`,"","\u{1F511} **Auth:**",x,g].join(`
56
- `)}default:throw new Qe(`Unknown tool: ${e}`)}}class Qe extends Error{}const Xe=`This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase. Use it proactively; it makes you faster and stops you repeating known mistakes.
54
+ \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${S.message}`}await xe();const N=fe(x),j=N.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":N.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${N.expiresInMs?` (${Math.round(N.expiresInMs/36e5)}h left)`:""}`:N.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${N.message.split(`
55
+ `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${i}`,` ${j}`,"","\u{1F511} **Auth:**",w,f].join(`
56
+ `)}default:throw new rt(`Unknown tool: ${e}`)}}class rt extends Error{}const it=`This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase. Use it proactively; it makes you faster and stops you repeating known mistakes.
57
57
 
58
58
  - BEFORE a non-trivial task: call smart_recall with a short description of what you're about to do. If it returns lessons, apply them before researching from scratch.
59
59
  - WHEN debugging an error: call causal_trace with the exact error first \u2014 a known fix may already exist.
60
60
  - AFTER a fix, deploy, or discovery: call learn_from_attempts so the knowledge persists.
61
61
  - BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
62
62
 
63
- The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,et={tools:{},resources:{},prompts:{}},tt=async()=>{const{katalog:e,unbekannteKernnamen:t}=wo(ae);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function ot(){return{resources:[]}}async function nt(){return{resourceTemplates:[]}}async function st(){return{prompts:[]}}function zo(e){e.setRequestHandler(Le,tt),e.setRequestHandler(Ie,at),e.setRequestHandler(Ne,ot),e.setRequestHandler(Re,nt),e.setRequestHandler(Ee,st)}function qo(){const e=new Te({name:"cachly-mcp",version:D},{capabilities:et,instructions:Xe});return zo(e),it(e),e}function it(e){const t=e.oninitialized;e.oninitialized=()=>{try{const n=e.getClientVersion();gt(n?.name,n?.version)}catch{}t?.()}}const ee=new Te({name:"cachly-mcp",version:D},{capabilities:et,instructions:Xe});it(ee),ee.setRequestHandler(Le,tt),ee.setRequestHandler(Ne,ot),ee.setRequestHandler(Re,nt),ee.setRequestHandler(Ee,st);let we=null,ce=!1,K=null,rt=0;async function Go(e){if(!ce){if(K){await K;return}if(K=(async()=>{ce=!0,we=e;try{await U("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{K=null}})(),await K,process.env.CACHLY_AUTO_INDEX!=="false")try{const t=await Y(e),n=await t.get(`cachly:index:last_indexed:${e}`),s=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>s)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),U("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code"}).catch(()=>{}))}catch{}}}async function _e(){if(!(!ce||!we)){ce=!1;try{await U("session_end",{instance_id:we,summary:`Auto-ended after ${rt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const at=async e=>{let{name:t,arguments:n}=e.params;if(t===We){const o=n??{},a=typeof o.tool=="string"?o.tool:"";if(!a)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const i=ae.find(r=>r.name===a);if(!i)return{content:[{type:"text",text:`Kein Werkzeug namens "${a}". Die Liste steht in der Beschreibung von ${We}.`}],isError:!0};if(o.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:i.name,description:i.description,inputSchema:i.inputSchema},null,2)}]};t=a,n=o.arguments??{}}const s=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!s.has(t)&&!ce&&!K){const o=xe(n?.instance_id)||B||xe(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await Go(o).catch(()=>{})}else K&&await K.catch(()=>{});s.has(t)||rt++;try{vo();const o=await U(t,n??{});return{content:[{type:"text",text:po(t,o)}]}}catch(o){if(o instanceof Qe)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof Z)throw o;const a=o.message??String(o);throw ke("cachly","tool_error",{tool:t,error:a}).catch(()=>{}),new Z(oe.InternalError,a)}};ee.setRequestHandler(Ie,at),process.on("SIGTERM",async()=>{await _e().catch(()=>{});for(const[,e]of G)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await _e().catch(()=>{});for(const[,e]of G)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}
63
+ The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,at={tools:{},resources:{},prompts:{}},ct=async()=>{const{katalog:e,unbekannteKernnamen:t}=Mo(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function lt(){return{resources:[]}}async function dt(){return{resourceTemplates:[]}}async function pt(){return{prompts:[]}}function mn(e){e.setRequestHandler(Oe,ct),e.setRequestHandler(Be,gt),e.setRequestHandler(Pe,lt),e.setRequestHandler(He,dt),e.setRequestHandler(je,pt)}function gn(){const e=new Le({name:"cachly-mcp",version:M},{capabilities:at,instructions:it});return mn(e),ut(e),e}function ut(e){const t=e.oninitialized;e.oninitialized=()=>{try{const n=e.getClientVersion();xt(n?.name,n?.version)}catch{}t?.()}}const V=new Le({name:"cachly-mcp",version:M},{capabilities:at,instructions:it});ut(V),V.setRequestHandler(Oe,ct),V.setRequestHandler(Pe,lt),V.setRequestHandler(He,dt),V.setRequestHandler(je,pt);let Ce=null,de=!1,Z=null,mt=0;async function fn(e){if(!de){if(Z){await Z;return}if(Z=(async()=>{de=!0,Ce=e;try{await U("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{Z=null}})(),await Z,process.env.CACHLY_AUTO_INDEX!=="false")try{const t=await D(e),n=await t.get(`cachly:index:last_indexed:${e}`),s=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>s)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),U("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code"}).catch(()=>{}))}catch{}}}async function Ae(){if(!(!de||!Ce)){de=!1;try{await U("session_end",{instance_id:Ce,summary:`Auto-ended after ${mt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const gt=async e=>{let{name:t,arguments:n}=e.params;if(t===Ze){const o=n??{},c=typeof o.tool=="string"?o.tool:"";if(!c)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const r=le.find(a=>a.name===c);if(!r)return{content:[{type:"text",text:`Kein Werkzeug namens "${c}". Die Liste steht in der Beschreibung von ${Ze}.`}],isError:!0};if(o.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:r.name,description:r.description,inputSchema:r.inputSchema},null,2)}]};t=c,n=o.arguments??{}}const s=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!s.has(t)&&!de&&!Z){const o=$e(n?.instance_id)||B||$e(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await fn(o).catch(()=>{})}else Z&&await Z.catch(()=>{});s.has(t)||mt++;try{Oo(),W(`werkzeug ${t}: Anfang`);const o=await U(t,n??{});return W(`werkzeug ${t}: Antwort fertig`),{content:[{type:"text",text:_o(t,o)+jo()}]}}catch(o){if(o instanceof rt)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof X)throw o;const c=o.message??String(o);throw Re("cachly","tool_error",{tool:t,error:c}).catch(()=>{}),new X(ne.InternalError,c)}};V.setRequestHandler(Be,gt),process.on("SIGTERM",async()=>{await Ae().catch(()=>{});for(const[,e]of te)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ae().catch(()=>{});for(const[,e]of te)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}
64
64
  `)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
65
- `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});const ct={claude:".mcp.json",cursor:".cursor/mcp.json",windsurf:".windsurf/mcp.json",copilot:".vscode/mcp.json",continue:".continue/config.json",cline:".vscode/mcp.json",zed:".zed/settings.json"},$e="<!-- cachly-brain-start -->",lt="<!-- cachly-brain-end -->",dt="https://api.cachly.dev";function le(e,t,n={}){const s={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(s.CACHLY_JWT=e),_&&_!==dt&&(s.CACHLY_API_URL=_),s}function Ko(e,t,n){return JSON.stringify(n==="continue"?{experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:le(e,t)}]}}:n==="zed"?{context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:le(e,t)},settings:{}}}}:{mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:le(e,t)}}},null,2)}async function pt(e,t,n,s,o,a={}){const i={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:le(t,n)};if(!o.existsSync(e))return Ko(t,n,s);let r={};try{r=JSON.parse(await o.readFile(e,"utf-8"))}catch{try{const{rename:h}=await import("node:fs/promises");await h(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
66
- `)}catch{}}if(s==="continue"){const h=r.experimental??{},y=h.modelContextProtocolServers??[];let v;for(const u of y){const c=u.env??{};if(c.CACHLY_JWT){v=c.CACHLY_JWT;break}}v&&X(v,a);const b=y.filter(u=>{const c=u.env??{};return!c.CACHLY_JWT&&!c.CACHLY_BRAIN_INSTANCE_ID});return b.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:i.env}),r.experimental={...h,modelContextProtocolServers:b},JSON.stringify(r,null,2)}if(s==="zed"){const h=r.context_servers??{},v=h.cachly?.command?.env?.CACHLY_JWT;return v&&X(v,a),h.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:i.env},settings:{}},r.context_servers=h,JSON.stringify(r,null,2)}const p=r.mcpServers??{},l=p.cachly?.env?.CACHLY_JWT;return l&&X(l,a),p.cachly=i,r.mcpServers=p,JSON.stringify(r,null,2)}function ut(e){return`${$e}
65
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});const Se={claude:".mcp.json",cursor:".cursor/mcp.json",windsurf:".windsurf/mcp.json",copilot:".vscode/mcp.json",continue:".continue/config.json",cline:".vscode/mcp.json",zed:".zed/settings.json"},ke="<!-- cachly-brain-start -->",ft="<!-- cachly-brain-end -->",ht="https://api.cachly.dev";function re(e,t,n={}){const s={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(s.CACHLY_JWT=e),_&&_!==ht&&(s.CACHLY_API_URL=_),s}function hn(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:re(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)},settings:{}}}},null,2):yt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)}}},null,2)}function yt(e){return Se[e]===".vscode/mcp.json"}async function bt(e,t,n,s,o,c={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(t,n)};if(!o.existsSync(e))return hn(t,n,s);let a={};try{a=JSON.parse(await o.readFile(e,"utf-8"))}catch{try{const{rename:g}=await import("node:fs/promises");await g(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
66
+ `)}catch{}}if(s==="continue"){const g=a.experimental??{},y=g.modelContextProtocolServers??[];let v;for(const p of y){const i=p.env??{};if(i.CACHLY_JWT){v=i.CACHLY_JWT;break}}v&&K(v,c);const h=y.filter(p=>{const i=p.env??{};return!i.CACHLY_JWT&&!i.CACHLY_BRAIN_INSTANCE_ID});return h.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...g,modelContextProtocolServers:h},JSON.stringify(a,null,2)}if(s==="zed"){const g=a.context_servers??{},v=g.cachly?.command?.env?.CACHLY_JWT;return v&&K(v,c),g.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=g,JSON.stringify(a,null,2)}if(yt(s)){const g=a.mcpServers??void 0,v=g?.cachly?.env?.CACHLY_JWT;v&&K(v,c),g&&"cachly"in g&&(delete g.cachly,Object.keys(g).length===0&&delete a.mcpServers);const h=a.servers??{},p=h.cachly,i=p?.env?.CACHLY_JWT;return i&&K(i,c),h.cachly=p?.envFile?{type:"stdio",...r,envFile:p.envFile}:{type:"stdio",...r},a.servers=h,JSON.stringify(a,null,2)}const u=a.mcpServers??{},l=u.cachly?.env?.CACHLY_JWT;return l&&K(l,c),u.cachly=r,a.mcpServers=u,JSON.stringify(a,null,2)}function vt(e){return`${ke}
67
67
  ## Cachly AI Brain \u2014 Always Active
68
68
 
69
69
  The Brain MCP server runs automatically. Instance: \`${e}\`
@@ -118,48 +118,48 @@ Report predicted failure risks to the user before proceeding.
118
118
 
119
119
  ### Half-finished code rule:
120
120
  Never commit code that does not compile. Run \`tsc --noEmit\` / \`go build ./...\` before every commit.
121
- ${lt}`}const Vo=`---
121
+ ${ft}`}const yn=`---
122
122
  description: Cachly AI Brain \u2014 persistent memory protocol (recall before tasks, learn after fixes)
123
123
  alwaysApply: true
124
124
  ---
125
125
 
126
- `;async function mt(e,t){const{writeFile:n,appendFile:s,readFile:o,mkdir:a}=await import("node:fs/promises"),{existsSync:i}=await import("node:fs"),{resolve:r,dirname:p}=await import("node:path"),d=[{path:r(e,"CLAUDE.md")},{path:r(e,"AGENTS.md")},{path:r(e,".github","copilot-instructions.md")},{path:r(e,".cursor","rules","cachly.mdc"),prefix:Vo},{path:r(e,".windsurfrules")},{path:r(e,".clinerules")}],l=`
127
- `+ut(t)+`
128
- `,h={};for(const{path:y,prefix:v}of d){if(await a(p(y),{recursive:!0}),i(y)){const b=await o(y,"utf-8");if(b.includes($e)){const u=b.replace(new RegExp(`${$e}[\\s\\S]*?${lt}`),ut(t));await n(y,u,"utf-8"),h[y]="updated";continue}await s(y,l,"utf-8"),h[y]="appended";continue}await n(y,(v??"")+l.trimStart(),"utf-8"),h[y]="written"}return h}if(process.argv[2]==="digest"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
126
+ `;async function wt(e,t){const{writeFile:n,appendFile:s,readFile:o,mkdir:c}=await import("node:fs/promises"),{existsSync:r}=await import("node:fs"),{resolve:a,dirname:u}=await import("node:path"),d=[{path:a(e,"CLAUDE.md")},{path:a(e,"AGENTS.md")},{path:a(e,".github","copilot-instructions.md")},{path:a(e,".cursor","rules","cachly.mdc"),prefix:yn},{path:a(e,".windsurfrules")},{path:a(e,".clinerules")}],l=`
127
+ `+vt(t)+`
128
+ `,g={};for(const{path:y,prefix:v}of d){if(await c(u(y),{recursive:!0}),r(y)){const h=await o(y,"utf-8");if(h.includes(ke)){const p=h.replace(new RegExp(`${ke}[\\s\\S]*?${ft}`),vt(t));await n(y,p,"utf-8"),g[y]="updated";continue}await s(y,l,"utf-8"),g[y]="appended";continue}await n(y,(v??"")+l.trimStart(),"utf-8"),g[y]="written"}return g}if(process.argv[2]==="digest"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
129
129
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
130
130
  `),process.exit(1)),process.stdout.write(`
131
131
  \u{1F9E0} Fetching your weekly Brain digest...
132
132
 
133
- `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,a=s.total_recall_count??0,i=Math.round(s.iq_boost_pct??0),r=(s.top_lessons??[]).slice(0,5),p=s.team_authors??[],d=a*1200,l=(d*3e-6).toFixed(2),h=o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",y=new Date,v=new Date(y);v.setDate(y.getDate()-7);const b=g=>g.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} Brain Weekly Digest\x1B[0m \x1B[90m${b(v)} \u2013 ${b(y)}\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(o).padEnd(8)}\x1B[0m Brain level : \x1B[32m${h.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(i).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${(Math.round(d/1e3)+"K").padEnd(8)}\x1B[0m Cost saved : \x1B[32m$${l.padEnd(20)}\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"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${p.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 g of r){const N=`${g.topic}: ${g.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${N.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 u=r[0],c=[`\u{1F9E0} My AI Brain weekly digest (${b(v)} \u2013 ${b(y)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${a} recalls \xB7 ~${Math.round(d/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${h}`,u?` \u{1F525} Top lesson: "${u.topic}: ${u.what_worked.slice(0,60)}${u.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
134
- `),x="https://twitter.com/intent/tweet?text="+encodeURIComponent(c);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const g of c.split(`
135
- `))console.log(` ${g}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${x.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\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(`
133
+ `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,r=Math.round(s.iq_boost_pct??0),a=(s.top_lessons??[]).slice(0,5),u=s.team_authors??[],d=c*1200,l=(d*3e-6).toFixed(2),g=o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",y=new Date,v=new Date(y);v.setDate(y.getDate()-7);const h=f=>f.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} Brain Weekly Digest\x1B[0m \x1B[90m${h(v)} \u2013 ${h(y)}\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(o).padEnd(8)}\x1B[0m Brain level : \x1B[32m${g.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(r).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${(Math.round(d/1e3)+"K").padEnd(8)}\x1B[0m Cost saved : \x1B[32m$${l.padEnd(20)}\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 f of a){const N=`${f.topic}: ${f.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${N.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 p=a[0],i=[`\u{1F9E0} My AI Brain weekly digest (${h(v)} \u2013 ${h(y)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${c} recalls \xB7 ~${Math.round(d/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${g}`,p?` \u{1F525} Top lesson: "${p.topic}: ${p.what_worked.slice(0,60)}${p.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
134
+ `),w="https://twitter.com/intent/tweet?text="+encodeURIComponent(i);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const f of i.split(`
135
+ `))console.log(` ${f}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${w.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\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(`
136
136
  \u274C Could not fetch digest: ${n.message}
137
- `),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"),s=process.argv.slice(3),o=d=>{const l=s.indexOf(`--${d}`);return l!==-1?s[l+1]:void 0},a=o("format")??"both";a!=="md"&&a!=="jsonl"&&a!=="both"&&(console.log(`
138
- \u274C Unknown --format "${a}" \u2014 use md, jsonl, or both.
139
- `),process.exit(1));const i=n(o("out")??"."),r=w||Ue()||"",p=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!r||!p)&&(console.log(`
137
+ `),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"),s=process.argv.slice(3),o=d=>{const l=s.indexOf(`--${d}`);return l!==-1?s[l+1]:void 0},c=o("format")??"both";c!=="md"&&c!=="jsonl"&&c!=="both"&&(console.log(`
138
+ \u274C Unknown --format "${c}" \u2014 use md, jsonl, or both.
139
+ `),process.exit(1));const r=n(o("out")??"."),a=x||Ke()||"",u=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!a||!u)&&(console.log(`
140
140
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
141
141
  `),process.exit(1)),process.stdout.write(`
142
142
  \u{1F4E4} Exporting your Brain...
143
143
 
144
- `);try{let d=[],l="";const h=await fetch(`${_}/api/v1/instances/${p}/export`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(12e4)});if(h.ok){const v=await h.json();d=(v.lessons??[]).map(Co).filter(b=>b!==null),v.complete===!1&&(l=v.note??"the server reported an incomplete read")}else if(h.status===404){const v=await fetch(`${_}/api/v1/instances/${p}/memory`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(8e3)});if(!v.ok)throw new Error(`memory HTTP ${v.status}`);d=((await v.json()).top_lessons??[]).map(u=>({topic:u.topic,outcome:u.outcome,severity:u.severity,tags:u.tags,whatWorked:u.what_worked,ts:u.ts,author:u.author,recallCount:u.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 ${h.status}`);d.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
145
- `),process.exit(0)),await t(i,{recursive:!0});const y=[];if(a==="md"||a==="both"){const v=n(i,"lessons.md");await e(v,_o(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}if(a==="jsonl"||a==="both"){const v=n(i,"lessons.jsonl");await e(v,$o(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}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 v of y)console.log(` ${v}`);console.log("")}catch(d){console.log(`
144
+ `);try{let d=[],l="";const g=await fetch(`${_}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(g.ok){const v=await g.json();d=(v.lessons??[]).map(Uo).filter(h=>h!==null),v.complete===!1&&(l=v.note??"the server reported an incomplete read")}else if(g.status===404){const v=await fetch(`${_}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!v.ok)throw new Error(`memory HTTP ${v.status}`);d=((await v.json()).top_lessons??[]).map(p=>({topic:p.topic,outcome:p.outcome,severity:p.severity,tags:p.tags,whatWorked:p.what_worked,ts:p.ts,author:p.author,recallCount:p.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 ${g.status}`);d.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
145
+ `),process.exit(0)),await t(r,{recursive:!0});const y=[];if(c==="md"||c==="both"){const v=n(r,"lessons.md");await e(v,Jo(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}if(c==="jsonl"||c==="both"){const v=n(r,"lessons.jsonl");await e(v,Yo(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}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 v of y)console.log(` ${v}`);console.log("")}catch(d){console.log(`
146
146
  \u274C Could not export your Brain: ${d.message}
147
147
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=process.env.CACHLY_JWT??"";e||(console.log(`
148
148
  \u26A0\uFE0F CACHLY_JWT must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
149
- `),process.exit(1));try{const t=await fetch(`${_}/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(),s=n.url??R(`/r/${n.code}`,"invite"),o=n.referral_count??0,a=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
149
+ `),process.exit(1));try{const t=await fetch(`${_}/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(),s=n.url??R(`/r/${n.code}`,"invite"),o=n.referral_count??0,c=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
150
150
 
151
- You get a free Brain: ${s}`,i=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
151
+ You get a free Brain: ${s}`,r=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
152
152
 
153
153
  Try it free: ${s}
154
154
 
155
- @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 Brain invite 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 ${s.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"),o>0&&(console.log(`\u2502 \x1B[32m\u2713 ${o} developer${o===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 a.split(`
156
- `))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=${i.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("")}catch(t){console.log(`
155
+ @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 Brain invite 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 ${s.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"),o>0&&(console.log(`\u2502 \x1B[32m\u2713 ${o} developer${o===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 c.split(`
156
+ `))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("")}catch(t){console.log(`
157
157
  \u274C Could not fetch invite link: ${t.message}
158
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:a}=await import("node:path"),{homedir:i}=await import("node:os"),{createInterface:r}=await import("node:readline"),p=process.argv[3]??"";p||(console.log(`
158
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{homedir:r}=await import("node:os"),{createInterface:a}=await import("node:readline"),u=process.argv[3]??"";u||(console.log(`
159
159
  \u274C Usage: npx @cachly-dev/mcp-server@latest join <token>
160
160
  `),console.log(` Get a token from a teammate: npx @cachly-dev/mcp-server@latest invite
161
161
  `),process.exit(1)),console.log(`
162
- \u23F3 Looking up invite...`);let d;try{const $=await fetch(`${_}/api/invite/${p}`,{signal:AbortSignal.timeout(8e3)});$.status===404&&(console.log(`
162
+ \u23F3 Looking up invite...`);let d;try{const $=await fetch(`${_}/api/invite/${u}`,{signal:AbortSignal.timeout(8e3)});$.status===404&&(console.log(`
163
163
  \u274C Invite not found \u2014 the link may be invalid.
164
164
  `),process.exit(1)),$.status===410&&(console.log(`
165
165
  \u274C This invite link has expired (7-day limit).
@@ -167,46 +167,46 @@ Try it free: ${s}
167
167
  \u274C Could not fetch invite: HTTP ${$.status}
168
168
  `),process.exit(1)),d=await $.json()}catch($){console.log(`
169
169
  \u274C Network error: ${$.message}
170
- `),process.exit(1)}const{instance_id:l,instance_name:h,tier:y,label:v}=d,b=new Date(d.expires_at).toLocaleDateString();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} Brain Invite\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(` Brain : \x1B[1m${h}\x1B[0m`),console.log(` Tier : ${y}`),v&&console.log(` Note : ${v}`),console.log(` Expires : ${b}`),console.log("");const u=r({input:process.stdin,output:process.stdout}),c=await new Promise($=>{u.question(" Join this Brain? [Y/n] ",k=>{u.close(),$(k.trim().toLowerCase()||"y")})});c!=="y"&&c!=="yes"&&(console.log(`
170
+ `),process.exit(1)}const{instance_id:l,instance_name:g,tier:y,label:v}=d,h=new Date(d.expires_at).toLocaleDateString();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} Brain Invite\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(` Brain : \x1B[1m${g}\x1B[0m`),console.log(` Tier : ${y}`),v&&console.log(` Note : ${v}`),console.log(` Expires : ${h}`),console.log("");const p=a({input:process.stdin,output:process.stdout}),i=await new Promise($=>{p.question(" Join this Brain? [Y/n] ",k=>{p.close(),$(k.trim().toLowerCase()||"y")})});i!=="y"&&i!=="yes"&&(console.log(`
171
171
  Cancelled.
172
- `),process.exit(0));let x=w;if(!x){console.log(`
172
+ `),process.exit(0));let w=x;if(!w){console.log(`
173
173
  No API key found \u2014 starting sign-in (10 seconds)...
174
174
  `);try{const $=await fetch(`${_}/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($.ok){const k=await $.json();console.log(` \u{1F449} Open: \x1B[36m${k.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${k.user_code}\x1B[0m
175
- `);const T=(k.interval??5)*1e3;for(let H=0;H<24;H++){await new Promise(f=>setTimeout(f,T));try{const f=await fetch(`${_}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:k.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(f.ok){const I=await f.json();if(I.access_token){x=I.access_token;break}}}catch{}}x||(console.log(`
175
+ `);const T=(k.interval??5)*1e3;for(let H=0;H<24;H++){await new Promise(b=>setTimeout(b,T));try{const b=await fetch(`${_}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:k.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(b.ok){const I=await b.json();if(I.access_token){w=I.access_token;break}}}catch{}}w||(console.log(`
176
176
  \u274C Sign-in timed out. Run the command again.
177
177
  `),process.exit(1)),console.log(` \u2705 Signed in!
178
178
  `)}}catch($){console.log(`
179
179
  \u26A0\uFE0F Could not start sign-in: ${$.message}`),console.log(` Set CACHLY_JWT manually from ${R("/setup-ai","join")}
180
- `),process.exit(1)}}const g=process.cwd(),N=i(),j=[{label:".mcp.json (Claude Code project)",path:o(g,".mcp.json")},{label:".cursor/mcp.json",path:o(g,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(g,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(g,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(N,".claude","mcp.json"),global:!0}];let S=0;for(const{label:$,path:k,global:T}of j){const H=a(k);if(!(!T&&!s(H)&&!s(k)))try{await n(H,{recursive:!0});let f={};if(s(k))try{f=JSON.parse(await t(k,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(k,k+".bak")}catch{}}const I=f.mcpServers??{},W=I.cachly??{},F=W.env??{};F.CACHLY_BRAIN_INSTANCE_ID=l,x&&!F.CACHLY_JWT&&(F.CACHLY_JWT=x),_!==dt&&(F.CACHLY_API_URL=_),I.cachly={...W,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:F},f.mcpServers=I,await e(k,JSON.stringify(f,null,2),"utf-8"),console.log(` \u2705 ${$}`),S++}catch(f){f.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${$}: ${f.message}`)}}console.log(""),S===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${h}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
180
+ `),process.exit(1)}}const f=process.cwd(),N=r(),j=[{label:".mcp.json (Claude Code project)",path:o(f,".mcp.json")},{label:".cursor/mcp.json",path:o(f,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(f,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(f,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(N,".claude","mcp.json"),global:!0}];let S=0;for(const{label:$,path:k,global:T}of j){const H=c(k);if(!(!T&&!s(H)&&!s(k)))try{await n(H,{recursive:!0});let b={};if(s(k))try{b=JSON.parse(await t(k,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(k,k+".bak")}catch{}}const I=b.mcpServers??{},F=I.cachly??{},z=F.env??{};z.CACHLY_BRAIN_INSTANCE_ID=l,w&&!z.CACHLY_JWT&&(z.CACHLY_JWT=w),_!==ht&&(z.CACHLY_API_URL=_),I.cachly={...F,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:z},b.mcpServers=I,await e(k,JSON.stringify(b,null,2),"utf-8"),console.log(` \u2705 ${$}`),S++}catch(b){b.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${$}: ${b.message}`)}}console.log(""),S===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${g}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
181
181
  `),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
182
182
  `)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
183
183
  \u23F3 Checking for updates...
184
- `);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const n=(await e.json()).version;if(!n||!/^\d+\.\d+\.\d+/.test(n))throw new Error("npm registry returned unexpected response");n===D?console.log(`
185
- \u2705 Already on the latest version: \x1B[32mv${D}\x1B[0m
186
- `):(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${D}\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(`
184
+ `);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const n=(await e.json()).version;if(!n||!/^\d+\.\d+\.\d+/.test(n))throw new Error("npm registry returned unexpected response");n===M?console.log(`
185
+ \u2705 Already on the latest version: \x1B[32mv${M}\x1B[0m
186
+ `):(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${M}\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(`
187
187
  \u274C Could not check for updates: ${e.message}
188
- `),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:s,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),a=process.argv.includes("--json"),i=process.argv.slice(3).find(d=>!d.startsWith("--")),r=t(e(import.meta.url)),p=i?n(process.cwd(),i):n(r,"bench","external","sample-corpus.json");try{const d=await s(p),l=await o(d);a&&(console.log(JSON.stringify({corpus:d.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 h=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),y=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),v=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),b=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",u=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 : ${d.name??p}`),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 : ${b}${h}%\x1B[0m`),console.log(` MRR : ${u}${y}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${v}%\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)}% (${b}${h}% 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${R("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(d){console.error(`
188
+ `),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:s,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),c=process.argv.includes("--json"),r=process.argv.slice(3).find(d=>!d.startsWith("--")),a=t(e(import.meta.url)),u=r?n(process.cwd(),r):n(a,"bench","external","sample-corpus.json");try{const d=await s(u),l=await o(d);c&&(console.log(JSON.stringify({corpus:d.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 g=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),y=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),v=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),h=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",p=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 : ${d.name??u}`),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 : ${h}${g}%\x1B[0m`),console.log(` MRR : ${p}${y}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${v}%\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)}% (${h}${g}% 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${R("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(d){console.error(`
189
189
  \u274C bench failed: ${d.message}
190
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{execSync:e}=await import("node:child_process"),{existsSync:t,readFileSync:n}=await import("node:fs"),{resolve:s,basename:o}=await import("node:path"),a=process.cwd();console.log(`
190
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{execSync:e}=await import("node:child_process"),{existsSync:t,readFileSync:n}=await import("node:fs"),{resolve:s,basename:o}=await import("node:path"),c=process.cwd();console.log(`
191
191
  \x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
192
- `),t(s(a,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
192
+ `),t(s(c,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
193
193
  `),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
194
- `),process.exit(0));let i="";try{i=e("git config user.name",{cwd:a,encoding:"utf-8",stdio:"pipe"}).trim().split(" ")[0]??""}catch{}let r=o(a);try{const f=JSON.parse(n(s(a,"package.json"),"utf-8"));f.name&&(r=f.name.replace(/^@[^/]+\//,""))}catch{}let p="";try{p=e('git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',{cwd:a,encoding:"utf-8",stdio:"pipe"})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
195
- `),process.exit(0)}const d=p.trim().split(`
196
- `).filter(Boolean).map(f=>{const[I,W,F,te]=f.split("|||");return{sha:(I??"").trim().slice(0,8),subject:(W??"").trim(),date:(F??"").trim(),author:(te??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
197
- `),process.exit(0));const l=new Map,h=[],y=[],v=[],b=new Set;let u=0;for(const f of d){const I=No(f.subject);l.set(I,(l.get(I)??0)+1),Lo(f.subject)&&u++,I==="fix"&&h.length<5&&h.push(f.subject.slice(0,72)),I==="feat"&&y.length<5&&y.push(f.subject.slice(0,72)),I==="security"&&v.length<3&&v.push(f.subject.slice(0,72)),f.author&&b.add(f.author)}const c=Bo(d.map(f=>f.subject)),x=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,g=c>=501?"Oracle":c>=201?"Architect":c>=51?"Expert":c>=11?"Explorer":"Apprentice",j=`${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} ${j.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${x.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(c).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(b.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${g.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(u).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 S=[...l.entries()].filter(([f])=>f!=="chore").sort((f,I)=>I[1]-f[1]),$=(f,I)=>"\u2588".repeat(Math.round(f/I*20)).padEnd(20),k=Math.max(...S.map(([,f])=>f),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[f,I]of S){const W={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[f]??"\u2022";console.log(`\u2502 ${W} \x1B[36m${f.padEnd(10)}\x1B[0m \x1B[35m${$(I,k)}\x1B[0m \x1B[33m${String(I).padStart(3)}\x1B[0m \u2502`)}if(v.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 f of v)console.log(`\u2502 \x1B[90m\u2022 ${f.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(h.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 f of h.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${f.slice(0,58).padEnd(58)}\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[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const f of y.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${f.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 T=new URLSearchParams({repo:r,commits:String(d.length),lessons:String(c),level:g,authors:String(b.size),reverts:String(u)}),H=R(`/preview?${T.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${H}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" Free forever \xB7 GDPR \xB7 German servers \xB7 No credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
194
+ `),process.exit(0));let r="";try{r=e("git config user.name",{cwd:c,encoding:"utf-8",stdio:"pipe"}).trim().split(" ")[0]??""}catch{}let a=o(c);try{const b=JSON.parse(n(s(c,"package.json"),"utf-8"));b.name&&(a=b.name.replace(/^@[^/]+\//,""))}catch{}let u="";try{u=e('git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',{cwd:c,encoding:"utf-8",stdio:"pipe"})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
195
+ `),process.exit(0)}const d=u.trim().split(`
196
+ `).filter(Boolean).map(b=>{const[I,F,z,oe]=b.split("|||");return{sha:(I??"").trim().slice(0,8),subject:(F??"").trim(),date:(z??"").trim(),author:(oe??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
197
+ `),process.exit(0));const l=new Map,g=[],y=[],v=[],h=new Set;let p=0;for(const b of d){const I=Zo(b.subject);l.set(I,(l.get(I)??0)+1),Qo(b.subject)&&p++,I==="fix"&&g.length<5&&g.push(b.subject.slice(0,72)),I==="feat"&&y.length<5&&y.push(b.subject.slice(0,72)),I==="security"&&v.length<3&&v.push(b.subject.slice(0,72)),b.author&&h.add(b.author)}const i=Xo(d.map(b=>b.subject)),w=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,f=i>=501?"Oracle":i>=201?"Architect":i>=51?"Expert":i>=11?"Explorer":"Apprentice",j=`${r?`Hey ${r} \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} ${j.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${w.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(i).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(h.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${f.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(p).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 S=[...l.entries()].filter(([b])=>b!=="chore").sort((b,I)=>I[1]-b[1]),$=(b,I)=>"\u2588".repeat(Math.round(b/I*20)).padEnd(20),k=Math.max(...S.map(([,b])=>b),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[b,I]of S){const F={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[b]??"\u2022";console.log(`\u2502 ${F} \x1B[36m${b.padEnd(10)}\x1B[0m \x1B[35m${$(I,k)}\x1B[0m \x1B[33m${String(I).padStart(3)}\x1B[0m \u2502`)}if(v.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 b of v)console.log(`\u2502 \x1B[90m\u2022 ${b.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(g.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 b of g.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${b.slice(0,58).padEnd(58)}\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[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const b of y.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${b.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 T=new URLSearchParams({repo:a,commits:String(d.length),lessons:String(i),level:f,authors:String(h.size),reverts:String(p)}),H=R(`/preview?${T.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${H}\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=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
198
198
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
199
199
  `),process.exit(1)),process.stdout.write(`
200
200
  \u{1F9E0} Fetching your Brain stats...
201
- `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,a=s.total_recall_count??0,i=Math.round(s.iq_boost_pct??0),r=a*1200,p=(r*3e-6).toFixed(2),d=o===0?"Intern \u{1F331}":o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<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(o).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(i).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${((r/1e3).toFixed(0)+"K").padEnd(8)}\x1B[0m Cost saved: \x1B[32m$${p.padEnd(20)}\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 l=R("/","share"),h=`\u{1F9E0} My AI coding assistant now has persistent memory.
201
+ `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,r=Math.round(s.iq_boost_pct??0),a=c*1200,u=(a*3e-6).toFixed(2),d=o===0?"Intern \u{1F331}":o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<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(o).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).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").padEnd(8)}\x1B[0m Cost saved: \x1B[32m$${u.padEnd(20)}\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 l=R("/","share"),g=`\u{1F9E0} My AI coding assistant now has persistent memory.
202
202
 
203
- ${o} lessons stored \xB7 ${a} recalls \xB7 ${d}
203
+ ${o} lessons stored \xB7 ${c} recalls \xB7 ${d}
204
204
 
205
205
  Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.
206
206
 
207
207
  ${l}
208
208
 
209
- #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(h.split(`
209
+ #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(g.split(`
210
210
  `).map(y=>` ${y}`).join(`
211
211
  `)),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(`
212
212
  \u274C Could not fetch stats: ${n.message}
@@ -214,123 +214,123 @@ ${l}
214
214
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
215
215
  `),process.exit(1));const n=process.argv.indexOf("--title"),s=n!==-1?process.argv[n+1]??"My Brain Snapshot":"My Brain Snapshot",o=process.argv.includes("--public");process.stdout.write(`
216
216
  \u{1F9E0} Publishing Brain snapshot...
217
- `);try{const a=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let i=0,r=0;if(a.ok){const y=await a.json();i=y.lesson_count??0,r=y.total_recall_count??0}const p=await fetch(`${_}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:s,visibility:o?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!p.ok)throw new Error(`HTTP ${p.status}`);const l=(await p.json()).share_id??"unavailable",h=R(`/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${s.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(i).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(r).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${o?"32":"33"}m${(o?"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${h.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(` ${h}`),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(a){console.log(`
218
- \u274C Could not publish Brain: ${a.message}
217
+ `);try{const c=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let r=0,a=0;if(c.ok){const y=await c.json();r=y.lesson_count??0,a=y.total_recall_count??0}const u=await fetch(`${_}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:s,visibility:o?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);const l=(await u.json()).share_id??"unavailable",g=R(`/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${s.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[${o?"32":"33"}m${(o?"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${g.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(` ${g}`),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(c){console.log(`
218
+ \u274C Could not publish Brain: ${c.message}
219
219
  `),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 s=process.argv.find(o=>o.startsWith("--format="));if(s)t=s.slice(9);else{const o=process.argv.indexOf("--format");o!==-1&&(t=process.argv[o+1]??"openapi")}}const n=["openapi","openai","anthropic","langchain"];n.includes(t)||(process.stderr.write(`
220
220
  \u274C Unknown format "${t}". Use one of: ${n.join(", ")}
221
221
 
222
- `),process.exit(1)),process.stdout.write(e(ae,t,D)+`
222
+ `),process.exit(1)),process.stdout.write(e(le,t,M)+`
223
223
  `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=process.env.CACHLY_BRAIN_INSTANCE_ID??"";e||(console.log(`
224
224
  \u26A0\uFE0F CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
225
- `),process.exit(1));const t=`${_}/api/v1/badge/${e}`,n=R("/","badge"),s=`[![cachly Brain](${t})](${n})`,o=`<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${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(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${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(" 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)}if(!process.argv[2]&&process.stdout.isTTY&&(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(""),console.log(" \x1B[1mCommands:\x1B[0m"),console.log(" \x1B[1m\x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest demo\x1B[0m \u2190 Try it first (no account)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest setup\x1B[0m \u2190 Interactive setup (pick editors)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest health\x1B[0m \u2190 Check everything works"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest doctor\x1B[0m \u2190 Diagnose a broken or missing install"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest digest\x1B[0m \u2190 Weekly Brain summary"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest share\x1B[0m \u2190 Share your Brain stats"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest badge\x1B[0m \u2190 README badge for your Brain"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest invite\x1B[0m \u2190 Invite a teammate"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest join <token>\x1B[0m \u2190 Accept a Brain invite"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest bench\x1B[0m \u2190 Recall quality vs flat-file memory"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest upgrade\x1B[0m \u2190 Check for updates"),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[90mFree forever \xB7 GDPR \xB7 German servers \xB7 ${ae.length} MCP tools\x1B[0m`),console.log(""),process.exit(0)),process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{resolve:o,dirname:a}=await import("node:path"),i=process.argv.slice(3),r=S=>{const $=i.indexOf(`--${S}`);return $!==-1?i[$+1]:void 0};let p=r("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=r("api-key")??process.env.CACHLY_JWT;const l=(r("editor")??"claude").toLowerCase(),h=o(r("project-dir")??"."),y=r("api-url");if(y&&(_=y.replace(/\/+$/,"")),!p||!d)try{const{existsSync:S}=await import("node:fs"),$=process.env.HOME??process.env.USERPROFILE??"",k=$?o($,".claude","mcp.json"):"";if(k&&S(k)){const H=JSON.parse(await s(k,"utf-8")).mcpServers?.cachly?.env??{};d??=H.CACHLY_JWT,p??=H.CACHLY_BRAIN_INSTANCE_ID,d&&p&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!p||!d)&&(console.error(`
225
+ `),process.exit(1));const t=`${_}/api/v1/badge/${e}`,n=R("/","badge"),s=`[![cachly Brain](${t})](${n})`,o=`<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${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(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${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(" 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)}if(!process.argv[2]&&process.stdout.isTTY&&(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(""),console.log(" \x1B[1mCommands:\x1B[0m"),console.log(" \x1B[1m\x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest demo\x1B[0m \u2190 Try it first (no account)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest setup\x1B[0m \u2190 Interactive setup (pick editors)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest health\x1B[0m \u2190 Check everything works"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest doctor\x1B[0m \u2190 Diagnose a broken or missing install"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest digest\x1B[0m \u2190 Weekly Brain summary"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest share\x1B[0m \u2190 Share your Brain stats"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest badge\x1B[0m \u2190 README badge for your Brain"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest invite\x1B[0m \u2190 Invite a teammate"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest join <token>\x1B[0m \u2190 Accept a Brain invite"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest bench\x1B[0m \u2190 Recall quality vs flat-file memory"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest upgrade\x1B[0m \u2190 Check for updates"),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(0)),process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{resolve:o,dirname:c}=await import("node:path"),r=process.argv.slice(3),a=S=>{const $=r.indexOf(`--${S}`);return $!==-1?r[$+1]:void 0};let u=a("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=a("api-key")??process.env.CACHLY_JWT;const l=(a("editor")??"claude").toLowerCase(),g=o(a("project-dir")??"."),y=a("api-url");if(y&&(_=y.replace(/\/+$/,"")),!u||!d)try{const{existsSync:S}=await import("node:fs"),$=process.env.HOME??process.env.USERPROFILE??"",k=$?o($,".claude","mcp.json"):"";if(k&&S(k)){const H=JSON.parse(await s(k,"utf-8")).mcpServers?.cachly?.env??{};d??=H.CACHLY_JWT,u??=H.CACHLY_BRAIN_INSTANCE_ID,d&&u&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!u||!d)&&(console.error(`
226
226
  Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue] [--project-dir /path] [--api-url https://your-self-hosted-backend]
227
227
  `),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
228
228
  `),console.error(`Get your credentials from: ${R("/setup-ai","init")}
229
- `),process.exit(1));const v=ct[l]??".mcp.json",b=o(h,v);await n(a(b),{recursive:!0});const{existsSync:u}=await import("node:fs"),c=u(b),x=c?await s(b,"utf-8").catch(()=>""):"";X(d);const g=await pt(b,d,p,l,{readFile:s,existsSync:u});g!==x?(await t(b,g,"utf-8"),console.log(`
230
- \u2705 ${c?"Updated":"Written"}: ${v}`)):console.log(`
231
- \u2713 Already configured: ${v} (no change)`);const N=await mt(h,p);for(const[S,$]of Object.entries(N)){const k=$==="updated"?"\u2705 Updated":$==="appended"?"\u2705 Appended to":"\u2705 Written",T=S.split(/[\\/]/).pop()??S;console.log(`${k}: ${T}`)}try{const S=await Oe(h,p,w||void 0);S==="written"?console.log("\u2705 Written: .git/hooks/post-commit (CLS hook)"):S==="upgraded"?console.log(`\u2705 Upgraded: .git/hooks/post-commit (CLS hook \u2192 ${De})`):S==="appended"?console.log("\u2705 Appended: .git/hooks/post-commit (CLS hook)"):S==="unchanged"&&console.log("\u2713 CLS hook already current in .git/hooks/post-commit")}catch{}if(l==="claude")try{const S=await Me(h,p),$=S.scripts==="written"?"\u2705 Written":S.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Je})`:"\u2713 Unchanged";console.log(`${$}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),S.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):S.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{}const j=((Date.now()-e)/1e3).toFixed(1);console.log(`
229
+ `),process.exit(1));const v=Se[l]??".mcp.json",h=o(g,v);await n(c(h),{recursive:!0});const{existsSync:p}=await import("node:fs"),i=p(h),w=i?await s(h,"utf-8").catch(()=>""):"";K(d);const f=await bt(h,d,u,l,{readFile:s,existsSync:p});f!==w?(await t(h,f,"utf-8"),console.log(`
230
+ \u2705 ${i?"Updated":"Written"}: ${v}`)):console.log(`
231
+ \u2713 Already configured: ${v} (no change)`);const N=await wt(g,u);for(const[S,$]of Object.entries(N)){const k=$==="updated"?"\u2705 Updated":$==="appended"?"\u2705 Appended to":"\u2705 Written",T=S.split(/[\\/]/).pop()??S;console.log(`${k}: ${T}`)}try{const S=await We(g,u,x||void 0);S==="written"?console.log("\u2705 Written: .git/hooks/post-commit (CLS hook)"):S==="upgraded"?console.log(`\u2705 Upgraded: .git/hooks/post-commit (CLS hook \u2192 ${Fe})`):S==="appended"?console.log("\u2705 Appended: .git/hooks/post-commit (CLS hook)"):S==="unchanged"&&console.log("\u2713 CLS hook already current in .git/hooks/post-commit")}catch{}if(l==="claude")try{const S=await ze(g,u),$=S.scripts==="written"?"\u2705 Written":S.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${qe})`:"\u2713 Unchanged";console.log(`${$}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),S.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):S.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{}const j=((Date.now()-e)/1e3).toFixed(1);console.log(`
232
232
  \u{1F9E0} Cachly AI Brain configured for ${l==="claude"?"Claude Code":l}! (${j}s)`),console.log(" 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(`
233
233
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
234
234
  `),process.exit(0)}if(process.argv[2]==="status"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
235
235
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
236
- `),process.exit(1));try{const[n,s]=await Promise.all([fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),a=s.ok?await s.json():null,i=o.lesson_count??0,r=o.total_recall_count??0,p=Math.round(o.iq_boost_pct??0),d=o.team_authors??[],l=a?.referral_count??0,h=a?.url??"",y=i===0?"Intern \u{1F331}":i<10?"Junior Dev \u{1F527}":i<30?"Mid Dev \u26A1":i<60?"Senior Dev \u{1F9E0}":i<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",v=i>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 ${v} \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(i).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(p).padEnd(3)}%\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");const b=d.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(d.length).padEnd(2)} developer${d.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-b.length))} \u2502`),console.log(`\u2502 ${b.slice(0,56).padEnd(56)} \u2502`)}if(h){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 b=`${h.slice(0,44)}${h.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Invite link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to grow your team"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${b.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(""),i===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(`
236
+ `),process.exit(1));try{const[n,s]=await Promise.all([fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),c=s.ok?await s.json():null,r=o.lesson_count??0,a=o.total_recall_count??0,u=Math.round(o.iq_boost_pct??0),d=o.team_authors??[],l=c?.referral_count??0,g=c?.url??"",y=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}",v=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 ${v} \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${y.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`),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");const h=d.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(d.length).padEnd(2)} developer${d.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-h.length))} \u2502`),console.log(`\u2502 ${h.slice(0,56).padEnd(56)} \u2502`)}if(g){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 h=`${g.slice(0,44)}${g.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Invite link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to grow your team"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${h.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(`
237
237
  \u274C Could not fetch status: ${n.message}
238
- `),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"),s=process.cwd();let o=0,a=0;const i=u=>{console.log(` \u2705 ${u}`),o++},r=u=>{console.log(` \u26A0\uFE0F ${u}`)},p=u=>{console.log(` \u274C ${u}`),a++};console.log(`
238
+ `),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"),s=process.cwd();let o=0,c=0;const r=p=>{console.log(` \u2705 ${p}`),o++},a=p=>{console.log(` \u26A0\uFE0F ${p}`)},u=p=>{console.log(` \u274C ${p}`),c++};console.log(`
239
239
  \u{1F9E0} cachly health check
240
- `),console.log("\u{1F511} Auth token");const d=process.env.CACHLY_JWT??"";if(!d)p("CACHLY_JWT not set \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(d.startsWith("cky_"))i("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const u=d.split(".");if(u.length!==3)throw new Error("not a JWT");const c=JSON.parse(Buffer.from(u[1],"base64url").toString("utf-8")),x=c.exp?c.exp*1e3:null,g=x?Math.floor((x-Date.now())/6e4):null;x&&x<Date.now()?p(`JWT expired ${Math.abs(g)} minute(s) ago \u2014 get a new one: ${R("/setup-ai","health")}`):g!==null&&g<30?r(`JWT expires in ${g} minute(s) \u2014 refresh soon at ${R("/setup-ai","health")}`):i(`JWT valid${g!==null?` (expires in ${Math.floor(g/60)}h ${g%60}m)`:""}`)}catch{p("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
241
- \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const u=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(u.ok){const c=await u.json();i(`${l} reachable (status: ${c.status??"ok"})`)}else u.status===401||u.status===403?i(`${l} reachable (auth required \u2014 expected)`):p(`${l}/health returned HTTP ${u.status}`)}catch(u){p(`${l} unreachable \u2014 ${u.message}`)}console.log(`
242
- \u{1F9E0} Brain instance`);const h=process.env.CACHLY_BRAIN_INSTANCE_ID??"";if(!h)r("CACHLY_BRAIN_INSTANCE_ID not set \u2014 will auto-resolve on first tool call");else if(d)try{const u=await fetch(`${l}/api/v1/instances/${h}`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(u.ok){const c=await u.json();if(c.status==="running")if(i(`Instance "${c.name}" (${h.slice(0,8)}\u2026) is running`),console.log(`
243
- \u{1F50C} Redis connectivity`),c.host&&c.port)try{let x,g=c.tls_enabled!==!1;try{const S=await fetch(`${l}/api/v1/instances/${h}/connection`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(S.ok){const $=await S.json();x=$.password,g=$.tls_enabled!==!1}}catch{}const N=new Be({host:c.host,port:c.port,password:x,...g?{tls:{}}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await N.connect();const j=await N.ping();N.disconnect(),j==="PONG"?i(`Redis PING \u2192 PONG (${c.host}:${c.port})`):r(`Redis responded but not PONG: ${j}`)}catch(x){p(`Redis unreachable \u2014 ${x.message}`)}else r("Instance has no host/port yet");else r(`Instance "${c.name}" status: ${c.status}`)}else p(`Instance ${h.slice(0,8)}\u2026 not found (HTTP ${u.status})`)}catch(u){p(`Could not check instance \u2014 ${u.message}`)}console.log(`
244
- \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"}];let v=0;for(const{editor:u,path:c}of y){const x=n(s,c);if(e(x))try{const g=await t(x,"utf-8");g.includes("@cachly-dev/mcp-server")||g.includes("cachly")?(i(`${u}: ${c}`),v++):r(`${u}: ${c} exists but cachly not found inside`)}catch{r(`${u}: ${c} exists but could not read`)}}v===0&&p("No editor MCP configs found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot"),console.log(`
245
- \u{1FA9D} Git hook (ambient learning)`);const b=n(s,".git","hooks","post-commit");if(!e(n(s,".git")))r("Not in a git repository \u2014 skip");else if(e(b))try{(await t(b,"utf-8")).includes("cachly")?i(".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(`
246
- \u{1F9EC} Embedding provider (semantic search)`);{const u=[["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(),x=u.find(([g])=>process.env[g]);if(c&&c!=="cachly"){const g=u.find(([,N])=>N===c)?.[0];g&&process.env[g]?i(`BYOK: ${c} (key present in ${g})`):r(`CACHLY_EMBED_PROVIDER=${c} but its key env var is not set \u2014 semantic search will fail`)}else i(x?`BYOK: ${x[1]} auto-detected (${x[0]} present)`:"Server-side embeddings (cachly) \u2014 no key needed, uses your JWT")}console.log(`
247
- ${"\u2500".repeat(40)}`),a===0?console.log(`\u2705 All checks passed (${o} ok)
248
- `):(console.log(`\u274C ${a} check(s) failed, ${o} passed
240
+ `),console.log("\u{1F511} Auth token");const d=process.env.CACHLY_JWT??"";if(!d)u("CACHLY_JWT not set \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(d.startsWith("cky_"))r("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const p=d.split(".");if(p.length!==3)throw new Error("not a JWT");const i=JSON.parse(Buffer.from(p[1],"base64url").toString("utf-8")),w=i.exp?i.exp*1e3:null,f=w?Math.floor((w-Date.now())/6e4):null;w&&w<Date.now()?u(`JWT expired ${Math.abs(f)} minute(s) ago \u2014 get a new one: ${R("/setup-ai","health")}`):f!==null&&f<30?a(`JWT expires in ${f} minute(s) \u2014 refresh soon at ${R("/setup-ai","health")}`):r(`JWT valid${f!==null?` (expires in ${Math.floor(f/60)}h ${f%60}m)`:""}`)}catch{u("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
241
+ \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const p=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(p.ok){const i=await p.json();r(`${l} reachable (status: ${i.status??"ok"})`)}else p.status===401||p.status===403?r(`${l} reachable (auth required \u2014 expected)`):u(`${l}/health returned HTTP ${p.status}`)}catch(p){u(`${l} unreachable \u2014 ${p.message}`)}console.log(`
242
+ \u{1F9E0} Brain instance`);const g=process.env.CACHLY_BRAIN_INSTANCE_ID??"";if(!g)a("CACHLY_BRAIN_INSTANCE_ID not set \u2014 will auto-resolve on first tool call");else if(d)try{const p=await fetch(`${l}/api/v1/instances/${g}`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(p.ok){const i=await p.json();if(i.status==="running")if(r(`Instance "${i.name}" (${g.slice(0,8)}\u2026) is running`),console.log(`
243
+ \u{1F50C} Redis connectivity`),i.host&&i.port)try{let w,f=i.tls_enabled!==!1;try{const S=await fetch(`${l}/api/v1/instances/${g}/connection`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(S.ok){const $=await S.json();w=$.password,f=$.tls_enabled!==!1}}catch{}const N=new De({host:i.host,port:i.port,password:w,...f?{tls:{}}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await N.connect();const j=await N.ping();N.disconnect(),j==="PONG"?r(`Redis PING \u2192 PONG (${i.host}:${i.port})`):a(`Redis responded but not PONG: ${j}`)}catch(w){u(`Redis unreachable \u2014 ${w.message}`)}else a("Instance has no host/port yet");else a(`Instance "${i.name}" status: ${i.status}`)}else u(`Instance ${g.slice(0,8)}\u2026 not found (HTTP ${p.status})`)}catch(p){u(`Could not check instance \u2014 ${p.message}`)}console.log(`
244
+ \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"}];let v=0;for(const{editor:p,path:i}of y){const w=n(s,i);if(e(w))try{const f=await t(w,"utf-8");f.includes("@cachly-dev/mcp-server")||f.includes("cachly")?(r(`${p}: ${i}`),v++):a(`${p}: ${i} exists but cachly not found inside`)}catch{a(`${p}: ${i} exists but could not read`)}}v===0&&u("No editor MCP configs found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot"),console.log(`
245
+ \u{1FA9D} Git hook (ambient learning)`);const h=n(s,".git","hooks","post-commit");if(!e(n(s,".git")))a("Not in a git repository \u2014 skip");else if(e(h))try{(await t(h,"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(`
246
+ \u{1F9EC} Embedding provider (semantic search)`);{const p=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],i=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase(),w=p.find(([f])=>process.env[f]);if(i&&i!=="cachly"){const f=p.find(([,N])=>N===i)?.[0];f&&process.env[f]?r(`BYOK: ${i} (key present in ${f})`):a(`CACHLY_EMBED_PROVIDER=${i} but its key env var is not set \u2014 semantic search will fail`)}else r(w?`BYOK: ${w[1]} auto-detected (${w[0]} present)`:"Server-side embeddings (cachly) \u2014 no key needed, uses your JWT")}console.log(`
247
+ ${"\u2500".repeat(40)}`),c===0?console.log(`\u2705 All checks passed (${o} ok)
248
+ `):(console.log(`\u274C ${c} check(s) failed, ${o} passed
249
249
  `),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
250
- `),process.exit(1)),process.exit(0)}const ue=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||ue){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:a}=await import("node:path"),{createInterface:i}=await import("node:readline"),r=Date.now(),p=ue?"autopilot":"setup",d=process.argv.indexOf("--api-url");d!==-1&&process.argv[d+1]&&(_=process.argv[d+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${_}
251
- `)),A("setup_started");const l=process.stdin.isTTY===!0,h=ue||process.argv.includes("--yes")||process.argv.includes("-y")||!l;ue?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
250
+ `),process.exit(1)),process.exit(0)}const me=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||me){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{createInterface:r}=await import("node:readline"),a=Date.now(),u=me?"autopilot":"setup",d=process.argv.indexOf("--api-url");d!==-1&&process.argv[d+1]&&(_=process.argv[d+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${_}
251
+ `)),A("setup_started");const l=process.stdin.isTTY===!0,g=me||process.argv.includes("--yes")||process.argv.includes("-y")||!l;me?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
252
252
  `):!l&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
253
- `);const y=i({input:process.stdin,output:process.stdout}),v=(m,C="")=>h?(console.log(`${m}${C}`),Promise.resolve(C)):new Promise(E=>y.question(m,M=>E(M.trim()||C)));console.log(`
253
+ `);const y=r({input:process.stdin,output:process.stdout}),v=(m,C="")=>g?(console.log(`${m}${C}`),Promise.resolve(C)):new Promise(E=>y.question(m,J=>E(J.trim()||C)));console.log(`
254
254
  \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
255
- `);let b=process.env.CACHLY_JWT??"";if(b)console.log(`\u2713 Using token from CACHLY_JWT env var
255
+ `);let h=process.env.CACHLY_JWT??"";if(h)console.log(`\u2713 Using token from CACHLY_JWT env var
256
256
  `);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
257
- `),A("setup_auth_started");let m="",C="",E="",M=5e3,J=!1,V="cachly";try{const z=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(z.ok){const L=await z.json();m=L.device_code,C=L.user_code;const P=L.verification_uri||R("/device",p);E=`${P}${P.includes("?")?"&":"?"}code=${encodeURIComponent(C)}`,M=(L.interval??5)*1e3,J=!!m}}catch{}if(!J)try{const L=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(L.ok){const P=await L.json();m=P.device_code,C=P.user_code,E=P.verification_uri_complete,M=(P.interval??5)*1e3,J=!0,V="keycloak"}}catch{}if(J&&m){console.log(` Code: \x1B[1;33m${C}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${E}
258
- `),ie(E,(L,P)=>{if(L){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:P??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${P??"unknown"}) \u2014 please open the URL yourself.
259
- `)}),process.stdout.write(" Waiting for authorization");const z=Date.now()+600*1e3;for(;Date.now()<z;){await new Promise(L=>setTimeout(L,M)),process.stdout.write(".");try{let L=null;if(V==="cachly")try{const P=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:m}),signal:AbortSignal.timeout(8e3)});P.status<500&&(L=await P.json())}catch{}else{const P="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{L=await(await fetch(`${P}/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=${m}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(L?.access_token){b=L.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
260
- `),A("setup_auth_completed"),A("device_flow_completed");break}L?.error==="slow_down"?M=Math.min(M+2e3,15e3):L?.error&&L.error!=="authorization_pending"&&(A("device_flow_failed",{reason:L.error}),console.error(`
257
+ `),A("setup_auth_started");let m="",C="",E="",J=5e3,Y=!1,Q="cachly";try{const q=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(q.ok){const L=await q.json();m=L.device_code,C=L.user_code;const O=L.verification_uri||R("/device",u);E=`${O}${O.includes("?")?"&":"?"}code=${encodeURIComponent(C)}`,J=(L.interval??5)*1e3,Y=!!m}}catch{}if(!Y)try{const L=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(L.ok){const O=await L.json();m=O.device_code,C=O.user_code,E=O.verification_uri_complete,J=(O.interval??5)*1e3,Y=!0,Q="keycloak"}}catch{}if(Y&&m){console.log(` Code: \x1B[1;33m${C}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${E}
258
+ `),ae(E,(L,O)=>{if(L){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:O??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${O??"unknown"}) \u2014 please open the URL yourself.
259
+ `)}),process.stdout.write(" Waiting for authorization");const q=Date.now()+600*1e3;for(;Date.now()<q;){await new Promise(L=>setTimeout(L,J)),process.stdout.write(".");try{let L=null;if(Q==="cachly")try{const O=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:m}),signal:AbortSignal.timeout(8e3)});O.status<500&&(L=await O.json())}catch{}else{const O="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{L=await(await fetch(`${O}/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=${m}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(L?.access_token){h=L.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
260
+ `),A("setup_auth_completed"),A("device_flow_completed");break}L?.error==="slow_down"?J=Math.min(J+2e3,15e3):L?.error&&L.error!=="authorization_pending"&&(A("device_flow_failed",{reason:L.error}),console.error(`
261
261
  Auth error: ${L.error}. Aborting.
262
- `),y.close(),process.exit(1))}catch{}}b||(A("device_flow_failed",{reason:"timeout"}),console.error(`
262
+ `),y.close(),process.exit(1))}catch{}}h||(A("device_flow_failed",{reason:"timeout"}),console.error(`
263
263
  Timed out waiting for authorization. Aborting.
264
- `),y.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const z=R("/setup-ai",p);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
265
- `),console.log(` URL: \x1B[36m${z}\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_...)
266
- `),ie(z),h?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
264
+ `),y.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const q=R("/setup-ai",u);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
265
+ `),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_...)
266
+ `),ae(q),g?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
267
267
  \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:
268
268
  `),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
269
269
  `),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
270
- `),y.close(),process.exit(1)):(b=await v(" Paste API key (cky_live_...): "),b||(console.error(`
270
+ `),y.close(),process.exit(1)):(h=await v(" Paste API key (cky_live_...): "),h||(console.error(`
271
271
  API key is required. Aborting.
272
- `),y.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(b.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const m=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(!C.key)throw new Error("no key in response");b=C.key,console.log(` \u2713
272
+ `),y.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(h.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const m=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(!C.key)throw new Error("no key in response");h=C.key,console.log(` \u2713
273
273
  `)}catch{console.log(` (skipped)
274
- `)}}process.stdout.write("\u23F3 Fetching your instances...");let u=[];try{const m=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${b}`}});if(!m.ok)throw new Error(`HTTP ${m.status}`);u=((await m.json()).data??[]).filter(E=>E.status==="running")}catch(m){const C=m.message;console.error(`
275
-
276
- Failed to fetch instances: ${C}`),C.includes("401")&&(console.error(`Token rejected. Get a valid token at ${R("/setup-ai",p)}
277
- `),ie(R("/setup-ai",p))),y.close(),process.exit(1)}if(console.log(` found ${u.length}
278
- `),u.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const m=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json"}});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(C.instance)u=[C.instance];else if(C.instance_id){const E=C.instance_id;console.log(` \u2713 created (${E.slice(0,8)}\u2026)
279
- `),process.stdout.write("\u23F3 Waiting for instance to start");for(let M=0;M<45;M++){await new Promise(J=>setTimeout(J,3e3)),process.stdout.write(".");try{const J=await fetch(`${_}/api/v1/instances/${E}`,{headers:{Authorization:`Bearer ${b}`}});if(J.ok){const V=await J.json();if(V.status==="running"){u=[V];break}}}catch{}}console.log("")}}catch(m){console.log(` failed: ${m.message}
280
- `)}u.length===0&&(console.error(`
281
- Could not create an instance automatically. Opening ${R("/instances",p)} \u2026
282
- `),ie(R("/instances",p)),y.close(),process.exit(1))}const c=u[0];u.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)
283
- `)),console.log(`\u2713 Instance: ${c.name} (${c.id.slice(0,8)}\u2026)
284
- `),A("setup_instance_ready",{instance_id:c.id});const x=process.cwd(),g=[],{homedir:N}=await import("node:os"),j=N();g.push("claude"),s(o(x,".cursor"))&&g.push("cursor"),s(o(x,".windsurf"))&&g.push("windsurf"),s(o(x,".vscode"))&&g.push("copilot"),s(o(x,".continue"))&&g.push("continue");const S=process.platform==="darwin"?o(j,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(j,".vscode/extensions");(s(S)&&!g.includes("copilot")||s(S))&&g.push("cline");const $=process.platform==="darwin"?o(j,"Library/Application Support/Zed"):o(j,".config/zed");s($)&&g.push("zed");const k=m=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[m]??m,T=g;console.log(`Step 3: Configuring for: ${T.map(k).join(", ")}
285
- `);const{existsSync:H}=await import("node:fs"),f=[];let I=0;X(b);for(const m of T){const C=ct[m]??".mcp.json",E=o(x,C);try{await t(a(E),{recursive:!0});const M=H(E),J=await pt(E,b,c.id,m,{readFile:n,existsSync:H});await e(E,J,"utf-8"),console.log(`\u2705 ${M?"Updated":"Written"}: ${C}`),I++}catch(M){const J=M.message;console.log(`\u26A0\uFE0F Could not write ${C}: ${J}`),console.log(" Fix permissions or run with sudo, then re-run setup."),f.push({file:C,reason:J})}}const W=o(j,".claude","mcp.json");try{await t(a(W),{recursive:!0});let m={};if(s(W))try{m=JSON.parse(await n(W,"utf-8"))}catch{}m.mcpServers??={},m.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:le(b,c.id,{includeApiKey:!0})},await e(W,JSON.stringify(m,null,2),"utf-8"),console.log("\u2705 Written: ~/.claude/mcp.json (global \u2014 works in every project)"),I++}catch(m){const C=m.message;console.log(`\u26A0\uFE0F Could not write ~/.claude/mcp.json: ${C}`),f.push({file:"~/.claude/mcp.json",reason:C})}const F=await mt(x,c.id);for(const[m,C]of Object.entries(F))console.log(`${C==="updated"?"\u2705 Updated":C==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${m}`);w=b;let te=0;if(s(o(x,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const m=await U("brain_from_git",{instance_id:c.id,repo_path:x,limit:100}),C=m.match(/Ingested: \*\*(\d+)\*\*/);te=C?parseInt(C[1],10):0,console.log(` \u2713 ${te} lesson${te===1?"":"s"} extracted from git history`);const E=ro(m);E&&(console.log(""),console.log(E))}catch(m){console.log(` (skipped: ${m.message.slice(0,80)})`)}}if(te===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await U("brain_seed_starter",{instance_id:c.id}),console.log(" \u2713");try{const m=await U("smart_recall",{instance_id:c.id,query:"docker build slow"}),C=jo(m);C&&(console.log(""),console.log(ao(C.topic,C.what)))}catch{}}catch(m){console.log(` (skipped: ${m.message.slice(0,60)})`)}}process.stdout.write(`
286
- \u23F3 Fetching your Brain health preview...`);try{const m=await fetch(`${_}/api/v1/instances/${c.id}/memory`,{headers:{Authorization:`Bearer ${b}`},signal:AbortSignal.timeout(6e3)});if(m.ok){const C=await m.json(),E=C.lesson_count??0,M=C.context_count??0,J=Math.round(C.iq_boost_pct??0),V=E===0?"Intern \u{1F331}":E<10?"Junior Dev \u{1F527}":E<30?"Mid Dev \u26A1":E<60?"Senior Dev \u{1F9E0}":E<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";if(console.log(` \u2713
287
- `),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\u2510"),console.log("\u2502 \u{1F9E0} Brain Health Report \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\u2524"),console.log(`\u2502 Lessons stored : ${String(E).padEnd(6)} \u2502 Level: ${V.padEnd(20)}\u2502`),console.log(`\u2502 Context entries : ${String(M).padEnd(6)} \u2502 Quality score: ${String(J).padEnd(3)}% \u2502`),E===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\u2524"),console.log("\u2502 Your Brain is empty and ready to learn. \u2502"),console.log("\u2502 After your first coding session it will contain: \u2502"),console.log("\u2502 \u2022 Lessons from every bug you fixed \u2502"),console.log("\u2502 \u2022 Your project's indexed files \u2502"),console.log("\u2502 \u2022 A session summary for next time \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\u2518"),E>=5){process.stdout.write(`
288
- \u23F3 Running predictive risk scan...`);try{const L=(await U("brain_predict",{instance_id:c.id,context:"starting a new development session"})).split(`
289
- `).filter(P=>P.trim()).slice(0,6);if(L.length>0){console.log(` \u2713
290
- `),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\u2510"),console.log("\u2502 \u{1F52E} Brain Risk Preview (brain_predict) \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\u2524");for(const P of L)console.log(`\u2502 ${P.slice(0,51).padEnd(51)} \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\u2518")}else console.log(" (no risks found \u2014 clean slate!)")}catch{console.log(" (skipped)")}}}else console.log(" (skipped)")}catch{console.log(" (skipped)")}if(console.log(`
274
+ `)}}process.stdout.write("\u23F3 Fetching your instances...");let p=[];try{const m=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${h}`}});if(!m.ok)throw new Error(`HTTP ${m.status}`);p=((await m.json()).data??[]).filter(E=>E.status==="running")}catch(m){const C=m.message;console.error(`
275
+
276
+ Failed to fetch instances: ${C}`),C.includes("401")&&(console.error(`Token rejected. Get a valid token at ${R("/setup-ai",u)}
277
+ `),ae(R("/setup-ai",u))),y.close(),process.exit(1)}if(console.log(` found ${p.length}
278
+ `),p.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const m=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"}});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(C.instance)p=[C.instance];else if(C.instance_id){const E=C.instance_id;console.log(` \u2713 created (${E.slice(0,8)}\u2026)
279
+ `),process.stdout.write("\u23F3 Waiting for instance to start");for(let J=0;J<45;J++){await new Promise(Y=>setTimeout(Y,3e3)),process.stdout.write(".");try{const Y=await fetch(`${_}/api/v1/instances/${E}`,{headers:{Authorization:`Bearer ${h}`}});if(Y.ok){const Q=await Y.json();if(Q.status==="running"){p=[Q];break}}}catch{}}console.log("")}}catch(m){console.log(` failed: ${m.message}
280
+ `)}p.length===0&&(console.error(`
281
+ Could not create an instance automatically. Opening ${R("/instances",u)} \u2026
282
+ `),ae(R("/instances",u)),y.close(),process.exit(1))}const i=p[0];p.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${i.name}`),console.log(` (Run with --instance-id <id> to use a different one)
283
+ `)),console.log(`\u2713 Instance: ${i.name} (${i.id.slice(0,8)}\u2026)
284
+ `),A("setup_instance_ready",{instance_id:i.id});const w=process.cwd(),f=[],{homedir:N}=await import("node:os"),j=N();f.push("claude"),s(o(w,".cursor"))&&f.push("cursor"),s(o(w,".windsurf"))&&f.push("windsurf"),s(o(w,".vscode"))&&f.push("copilot"),s(o(w,".continue"))&&f.push("continue");const S=process.platform==="darwin"?o(j,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(j,".vscode/extensions");(s(S)&&!f.includes("copilot")||s(S))&&f.push("cline");const $=process.platform==="darwin"?o(j,"Library/Application Support/Zed"):o(j,".config/zed");s($)&&f.push("zed");const k=m=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[m]??m,T=f;console.log(`Step 3: Configuring for: ${T.map(k).join(", ")}
285
+ `);const{existsSync:H}=await import("node:fs"),b=[];let I=0;K(h);for(const m of T){const C=Se[m]??".mcp.json",E=o(w,C);try{await t(c(E),{recursive:!0});const J=H(E),Y=await bt(E,h,i.id,m,{readFile:n,existsSync:H});await e(E,Y,"utf-8"),console.log(`\u2705 ${J?"Updated":"Written"}: ${C}`),I++}catch(J){const Y=J.message;console.log(`\u26A0\uFE0F Could not write ${C}: ${Y}`),console.log(" Fix permissions or run with sudo, then re-run setup."),b.push({file:C,reason:Y})}}const F=o(j,".claude","mcp.json");try{await t(c(F),{recursive:!0});let m={};if(s(F))try{m=JSON.parse(await n(F,"utf-8"))}catch{}m.mcpServers??={},m.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(h,i.id,{includeApiKey:!0})},await e(F,JSON.stringify(m,null,2),"utf-8"),console.log("\u2705 Written: ~/.claude/mcp.json (global \u2014 works in every project)"),I++}catch(m){const C=m.message;console.log(`\u26A0\uFE0F Could not write ~/.claude/mcp.json: ${C}`),b.push({file:"~/.claude/mcp.json",reason:C})}const z=await wt(w,i.id);for(const[m,C]of Object.entries(z))console.log(`${C==="updated"?"\u2705 Updated":C==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${m}`);x=h;let oe=0;if(s(o(w,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const m=await U("brain_from_git",{instance_id:i.id,repo_path:w,limit:100}),C=m.match(/Ingested: \*\*(\d+)\*\*/);oe=C?parseInt(C[1],10):0,console.log(` \u2713 ${oe} lesson${oe===1?"":"s"} extracted from git history`);const E=bo(m);E&&(console.log(""),console.log(E))}catch(m){console.log(` (skipped: ${m.message.slice(0,80)})`)}}if(oe===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await U("brain_seed_starter",{instance_id:i.id}),console.log(" \u2713");try{const m=await U("smart_recall",{instance_id:i.id,query:"docker build slow"}),C=en(m);C&&(console.log(""),console.log(vo(C.topic,C.what)))}catch{}}catch(m){console.log(` (skipped: ${m.message.slice(0,60)})`)}}process.stdout.write(`
286
+ \u23F3 Fetching your Brain health preview...`);try{const m=await fetch(`${_}/api/v1/instances/${i.id}/memory`,{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(6e3)});if(m.ok){const C=await m.json(),E=C.lesson_count??0,J=C.context_count??0,Y=Math.round(C.iq_boost_pct??0),Q=E===0?"Intern \u{1F331}":E<10?"Junior Dev \u{1F527}":E<30?"Mid Dev \u26A1":E<60?"Senior Dev \u{1F9E0}":E<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";if(console.log(` \u2713
287
+ `),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\u2510"),console.log("\u2502 \u{1F9E0} Brain Health Report \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\u2524"),console.log(`\u2502 Lessons stored : ${String(E).padEnd(6)} \u2502 Level: ${Q.padEnd(20)}\u2502`),console.log(`\u2502 Context entries : ${String(J).padEnd(6)} \u2502 Quality score: ${String(Y).padEnd(3)}% \u2502`),E===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\u2524"),console.log("\u2502 Your Brain is empty and ready to learn. \u2502"),console.log("\u2502 After your first coding session it will contain: \u2502"),console.log("\u2502 \u2022 Lessons from every bug you fixed \u2502"),console.log("\u2502 \u2022 Your project's indexed files \u2502"),console.log("\u2502 \u2022 A session summary for next time \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\u2518"),E>=5){process.stdout.write(`
288
+ \u23F3 Running predictive risk scan...`);try{const L=(await U("brain_predict",{instance_id:i.id,context:"starting a new development session"})).split(`
289
+ `).filter(O=>O.trim()).slice(0,6);if(L.length>0){console.log(` \u2713
290
+ `),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\u2510"),console.log("\u2502 \u{1F52E} Brain Risk Preview (brain_predict) \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\u2524");for(const O of L)console.log(`\u2502 ${O.slice(0,51).padEnd(51)} \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\u2518")}else console.log(" (no risks found \u2014 clean slate!)")}catch{console.log(" (skipped)")}}}else console.log(" (skipped)")}catch{console.log(" (skipped)")}if(console.log(`
291
291
  \u{1F389} Your AI just got a permanent brain.`),console.log(` Restart your editor \u2014 from this session on, it arrives pre-briefed.
292
292
  `),console.log(` No more re-explaining your stack. No repeated mistakes.
293
- `),console.log(` Dashboard: ${R(`/instances/${c.id}`,p)}`),console.log(`
293
+ `),console.log(` Dashboard: ${R(`/instances/${i.id}`,u)}`),console.log(`
294
294
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
295
- `),!h)try{if(console.log(`
296
- \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 v(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const C=await v(' Your handle (e.g. "alice"): ');C.trim()&&await U("team_assign_role",{instance_id:c.id,handle:C.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${C.trim()} is now admin. Invite teammates:
297
- `),console.log(` team_assign_role(instance_id="${c.id}", handle="<teammate>", role="contributor", assigned_by="${C.trim()}")
295
+ `),!g)try{if(console.log(`
296
+ \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 v(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const C=await v(' Your handle (e.g. "alice"): ');C.trim()&&await U("team_assign_role",{instance_id:i.id,handle:C.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${C.trim()} is now admin. Invite teammates:
297
+ `),console.log(` team_assign_role(instance_id="${i.id}", handle="<teammate>", role="contributor", assigned_by="${C.trim()}")
298
298
  `))}else console.log(` Skipped \u2014 run team_assign_role at any time.
299
- `)}catch{}if(!h){const m=await v(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(m&&m.includes("@"))try{await fetch(`${_}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:m.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
300
- `)}catch{}}try{const m=await Oe(process.cwd(),c.id,b||void 0);m==="written"?console.log(`
299
+ `)}catch{}if(!g){const m=await v(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(m&&m.includes("@"))try{await fetch(`${_}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:m.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
300
+ `)}catch{}}try{const m=await We(process.cwd(),i.id,h||void 0);m==="written"?console.log(`
301
301
  \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):m==="upgraded"?console.log(`
302
- \u2705 CLS git hook upgraded to ${De}.`):m==="appended"&&console.log(`
303
- \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(T.includes("claude"))try{const m=await Me(process.cwd(),c.id),C=m.scripts==="written"?"\u2705 Written":m.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Je})`:"\u2713 Unchanged";console.log(`${C}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),m.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):m.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{}w=b;const Ce=Math.round((Date.now()-r)/1e3);if(f.length>0&&A("setup_config_write_failed",{instance_id:c.id,failed:f.length,succeeded:I}),A("setup_completed",{instance_id:c.id,elapsed_s:Ce,config_failures:f.length}),f.length>0&&I===0){console.log(`
302
+ \u2705 CLS git hook upgraded to ${Fe}.`):m==="appended"&&console.log(`
303
+ \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(T.includes("claude"))try{const m=await ze(process.cwd(),i.id),C=m.scripts==="written"?"\u2705 Written":m.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${qe})`:"\u2713 Unchanged";console.log(`${C}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),m.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):m.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{}x=h;const Te=Math.round((Date.now()-a)/1e3);if(b.length>0&&A("setup_config_write_failed",{instance_id:i.id,failed:b.length,succeeded:I}),A("setup_completed",{instance_id:i.id,elapsed_s:Te,config_failures:b.length}),b.length>0&&I===0){console.log(`
304
304
  \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(`
305
- Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const m of f)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(`
306
- Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${b.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${c.id}`),console.log(` Docs: ${R("/docs/mcp",p)}
305
+ Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const m of b)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(`
306
+ Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${h.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${i.id}`),console.log(` Docs: ${R("/docs/mcp",u)}
307
307
  `),y.close(),await new Promise(m=>setTimeout(m,300)),process.exit(1)}if(console.log(`
308
- \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 ${(Ce+"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"),f.length>0){console.log(`
309
- \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const m of f)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(""),y.close(),await new Promise(m=>setTimeout(m,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=r=>{const p=t.indexOf(`--${r}`);return p!==-1?t[p+1]:void 0},s=e(n("dir")??t.find(r=>!r.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,a=parseInt(n("max-files")??"500",10),i=n("namespace")??"cachly:sem:code";(!o||!w)&&(console.error(`
308
+ \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 ${(Te+"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"),b.length>0){console.log(`
309
+ \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const m of b)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(""),y.close(),await new Promise(m=>setTimeout(m,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},s=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-files")??"500",10),r=n("namespace")??"cachly:sem:code";(!o||!x)&&(console.error(`
310
310
  \u274C CACHLY_BRAIN_INSTANCE_ID and CACHLY_JWT must be set
311
311
  `),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
312
312
  `),process.exit(1)),console.log(`
313
- \u{1F4C2} Indexing: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max files: ${a}
314
- `);try{const r=await U("index_project",{instance_id:o,dir:s,max_files:a,ttl:604800,namespace:i});console.log(r),console.log(`
313
+ \u{1F4C2} Indexing: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max files: ${c}
314
+ `);try{const a=await U("index_project",{instance_id:o,dir:s,max_files:c,ttl:604800,namespace:r});console.log(a),console.log(`
315
315
  \u2705 Indexing complete.
316
- `)}catch(r){console.error(`
317
- \u274C Indexing failed: ${r.message}
318
- `),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=i=>{const r=t.indexOf(`--${i}`);return r!==-1?t[r+1]:void 0},s=e(n("dir")??t.find(i=>!i.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,a=parseInt(n("max-commits")??"50",10);(!o||!w)&&(console.error(`
316
+ `)}catch(a){console.error(`
317
+ \u274C Indexing failed: ${a.message}
318
+ `),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},s=e(n("dir")??t.find(r=>!r.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-commits")??"50",10);(!o||!x)&&(console.error(`
319
319
  \u274C CACHLY_BRAIN_INSTANCE_ID and CACHLY_JWT must be set
320
320
  `),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 .
321
321
  `),process.exit(1)),console.log(`
322
- \u{1F9E0} Learning from git history: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max commits: ${a}
323
- `);try{const i=await U("brain_from_git",{instance_id:o,repo_path:s,limit:a});console.log(i),A("brain_from_git",{api_key:w,instance_id:o}),console.log(`
322
+ \u{1F9E0} Learning from git history: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max commits: ${c}
323
+ `);try{const r=await U("brain_from_git",{instance_id:o,repo_path:s,limit:c});console.log(r),A("brain_from_git",{api_key:x,instance_id:o}),console.log(`
324
324
  \u2705 Brain learned from your commits.
325
- `),await new Promise(r=>setTimeout(r,300))}catch(i){console.error(`
326
- \u274C learn-git failed: ${i.message}
327
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await co(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await lo(),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,s={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n};await uo(s),await Po(process.env.CACHLY_BRAIN_INSTANCE_ID??B,s),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=await Ye(),t=Eo(e),n=e.slice(-5);if(console.log(`
325
+ `),await new Promise(a=>setTimeout(a,300))}catch(r){console.error(`
326
+ \u274C learn-git failed: ${r.message}
327
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await wo(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await xo(),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,s={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n};await $o(s),await on(process.env.CACHLY_BRAIN_INSTANCE_ID??B,s),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=await Ge(),t=Ko(e),n=e.slice(-5);if(console.log(`
328
328
  \u{1F9E0} Ambient Recall \u2014 net-token ledger
329
329
  `),console.log(` Turns recorded: ${e.length}`),console.log(` Injected tokens: ${t.injected}`),console.log(` Prevented tokens: ${t.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${t.net>=0?"+":""}${t.net} tokens`),n.length>0){console.log(`
330
- Last entries:`);for(const s of n){const o=s.prevented>0?`+${s.prevented} prevented`:`-${s.injected} injected`;console.log(` \u2022 ${s.ts.slice(0,19)} ${s.event}: ${o}${s.note?` (${s.note})`:""}`)}}console.log(""),process.exit(0)}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:s,checkInstance:o,checkVectorCoverage:a,inspectAmbientHooks:i,checkHooks:r,checkLedger:p,renderDoctorReport:d,doctorExitCode:l}=await import("./doctor.js"),h=[e(),t(w),await n(_),await s(_,w),o(process.env.CACHLY_BRAIN_INSTANCE_ID??B),await a(_,w,process.env.CACHLY_BRAIN_INSTANCE_ID??B),r(i(process.cwd())),p(await Ye(),mo())];console.log(d(h)),process.exit(l(h))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!w)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??B;(!n||!t.source)&&process.exit(0),await U("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!w){const e=bt();if(e)try{const t=await fetch(xt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:vt(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(w=n.access_token,re(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).
330
+ Last entries:`);for(const s of n){const o=s.prevented>0?`+${s.prevented} prevented`:`-${s.injected} injected`;console.log(` \u2022 ${s.ts.slice(0,19)} ${s.event}: ${o}${s.note?` (${s.note})`:""}`)}}console.log(""),process.exit(0)}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:s,checkInstance:o,checkVectorCoverage:c,inspectAmbientHooks:r,checkHooks:a,checkLedger:u,renderDoctorReport:d,doctorExitCode:l}=await import("./doctor.js"),g=[e(),t(x),await n(_),await s(_,x),o(process.env.CACHLY_BRAIN_INSTANCE_ID??B),await c(_,x,process.env.CACHLY_BRAIN_INSTANCE_ID??B),a(r(process.cwd())),u(await Ge(),Co())];console.log(d(g)),process.exit(l(g))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!x)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??B;(!n||!t.source)&&process.exit(0),await U("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!x){const e=At();if(e)try{const t=await fetch(kt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:St(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(x=n.access_token,ce(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).
331
331
  `))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
332
332
  `),A("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
333
- `),A("m2m_auth_failed",{reason:"network"})}}const Zo=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor"];if(!w&&!Zo.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Tt){const s=`
333
+ `),A("m2m_auth_failed",{reason:"network"})}}const bn=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor"];if(!x&&!bn.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Bt){const s=`
334
334
  \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
335
335
  \u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
336
336
  \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
@@ -350,7 +350,7 @@ Could not create an instance automatically. Opening ${R("/instances",p)} \u2026
350
350
  \u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call creates a test Brain on EU servers, no sign-up.
351
351
  (Own account: npx @cachly-dev/mcp-server@latest autopilot)
352
352
 
353
- `);else{const e=ht(w);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
353
+ `);else{const e=_t(x);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
354
354
  \u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
355
355
  All tool calls will fail. Get a fresh token at ${R("/setup-ai","jwt-expiry")}
356
356
 
@@ -358,11 +358,11 @@ Could not create an instance automatically. Opening ${R("/instances",p)} \u2026
358
358
  \u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
359
359
  Refresh it soon at ${R("/setup-ai","jwt-expiry")} to avoid interruptions.
360
360
 
361
- `)}}process.env.CACHLY_NO_UPDATE_CHECK||(async()=>{try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(4e3)});if(e.ok){const n=(await e.json())?.version??"";n&&n!==D&&process.stderr.write(`
362
- \u26A1 cachly update available: ${D} \u2192 ${n}
361
+ `)}}process.env.CACHLY_NO_UPDATE_CHECK||(async()=>{try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(4e3)});if(e.ok){const n=(await e.json())?.version??"";n&&n!==M&&process.stderr.write(`
362
+ \u26A1 cachly update available: ${M} \u2192 ${n}
363
363
  Run: npx @cachly-dev/mcp-server@latest autopilot
364
364
 
365
- `)}}catch{}})();const me=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(me){const{createServer:e}=await import("node:http");e((n,s)=>{const o=new URL(n.url??"/",`http://localhost:${me}`);if(o.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",version:D,zeroResults:{total:Vt,last10:Kt.slice(-10).map(a=>({query:a.query,ts:new Date(a.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const a=qo(),i=new Et({sessionIdGenerator:void 0});s.on("close",()=>{i.close().catch(()=>{}),a.close().catch(()=>{})});try{await a.connect(i),await i.handleRequest(n,s)}catch(r){process.stderr.write(`cachly-mcp HTTP: ${r.message}
366
- `),s.headersSent||(s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:r.message})))}})();return}s.writeHead(404),s.end("not found")}).listen(me,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${me}
367
- `)})}else{const e=new It;await ee.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(xo(),bo(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 Session zu Ende, Server geht mit
368
- `),(async()=>{await _e().catch(()=>{});for(const[,s]of G)await s.quit().catch(()=>{});process.exit(0)})()}))}ke("cachly","startup",{version:D,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{lt as CLAUDE_MD_MARKER_END,$e as CLAUDE_MD_MARKER_START,Gt as CROSS_LINGUAL_MAP,ct as EDITOR_FILES,Wt as STOPWORDS,zt as arabicLightStem,ut as buildClaudeMdBlock,Ko as buildMcpConfig,le as buildServerEnv,qt as expandCrossLingual,Ut as extractTimestamp,Ft as katakanaToRomaji,Jt as levenshtein,pt as mergeMcpConfig,Yt as recencyBoost,Zt as reconnectOnce,Mt as splitMultiQuery,Pt as startBackgroundDevicePoll,Dt as tokenize,mt as writeInstructions};
365
+ `)}}catch{}})();const ge=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(ge){const{createServer:e}=await import("node:http");e((n,s)=>{const o=new URL(n.url??"/",`http://localhost:${ge}`);if(o.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",version:M,zeroResults:{total:ro,last10:so.slice(-10).map(c=>({query:c.query,ts:new Date(c.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const c=gn(),r=new Ht({sessionIdGenerator:void 0});s.on("close",()=>{r.close().catch(()=>{}),c.close().catch(()=>{})});try{await c.connect(r),await r.handleRequest(n,s)}catch(a){process.stderr.write(`cachly-mcp HTTP: ${a.message}
366
+ `),s.headersSent||(s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:a.message})))}})();return}s.writeHead(404),s.end("not found")}).listen(ge,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${ge}
367
+ `)})}else{const e=new jt;W("start: Module geladen, stdio verbinden"),await V.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(Me=!0,Do(),Po(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 Session zu Ende, Server geht mit
368
+ `),(async()=>{await Ae().catch(()=>{});for(const[,s]of te)await s.quit().catch(()=>{});process.exit(0)})()}))}Re("cachly","startup",{version:M,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{ft as CLAUDE_MD_MARKER_END,ke as CLAUDE_MD_MARKER_START,no as CROSS_LINGUAL_MAP,Se as EDITOR_FILES,Xt as STOPWORDS,to as arabicLightStem,vt as buildClaudeMdBlock,hn as buildMcpConfig,re as buildServerEnv,oo as expandCrossLingual,Qt as extractTimestamp,eo as katakanaToRomaji,Vt as levenshtein,bt as mergeMcpConfig,Zt as recencyBoost,io as reconnectOnce,Kt as splitMultiQuery,Wt as startBackgroundDevicePoll,Gt as tokenize,wt as writeInstructions};