@cachly-dev/mcp-server 0.10.217 → 0.10.219
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/handlers/cache.js +25 -26
- package/dist/src/handlers/instances.js +7 -6
- package/dist/src/handlers/team.js +33 -33
- package/dist/src/tools.js +1 -1
- package/dist/src/zeit-normalisieren.js +1 -1
- package/dist/src/zugang.js +2 -2
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,55 +1,54 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as R}from"node:crypto";import{McpError as V,ErrorCode as Y}from"@modelcontextprotocol/sdk/types.js";import{readdir as B,stat as z,readFile as G}from"node:fs/promises";import{join as Q,relative as Z,extname as ee}from"node:path";import{computeEmbedding as P,hasEmbedProvider as K,embedProviderHint as J}from"../embeddings.js";import{einbettTakt as te}from"../einbett-takt.js";import{detectNamespace as U}from"../namespace.js";import{simpleHash as se}from"../confidence.js";import{scanKeys as ae}from"../utils.js";import{cachlyUrl as X}from"../cachly-url.js";const ue=new Set(["cache_get","cache_set","cache_delete","cache_exists","cache_ttl","cache_keys","cache_stats","semantic_search","detect_namespace","cache_warmup","index_project","cache_mset","cache_mget","cache_lock_acquire","cache_lock_release","cache_stream_set","cache_stream_get","cache_org_stats","set_cost_per_call"]);async function $e(F,_,f,b){switch(F){case"cache_get":{const{instance_id:n,key:e,org_id:a}=_,t=await f(n);let s=await t.get(e),i="direct";if(s===null&&a){const r=`org:${a}:sem:${e}`;s=await t.get(r),s!==null&&(i=`org:${a}:sem`)}if(s===null)return`Key \`${e}\` \u2192 **not found** (null)`;let c=s;try{c=JSON.stringify(JSON.parse(s),null,2)}catch{}const o=i!=="direct"?` _(from shared org namespace \`${i}\`)_`:"";return`Key \`${e}\`:${o}
|
|
2
2
|
\`\`\`
|
|
3
3
|
${c}
|
|
4
|
-
\`\`\``}case"cache_set":{const{instance_id:n,key:e,value:a,ttl:t,org_id:s}=
|
|
4
|
+
\`\`\``}case"cache_set":{const{instance_id:n,key:e,value:a,ttl:t,org_id:s}=_,i=await f(n);return t&&t>0?(await i.set(e,a,"EX",t),s&&await i.set(`org:${s}:sem:${e}`,a,"EX",t),`\u2705 Set \`${e}\` (TTL: ${t}s)${s?` + shared to \`org:${s}:sem\``:""}`):(await i.set(e,a),s&&await i.set(`org:${s}:sem:${e}`,a),`\u2705 Set \`${e}\` (no expiry)${s?` + shared to \`org:${s}:sem\``:""}`)}case"cache_delete":{const{instance_id:n,keys:e}=_;return`\u2705 Deleted **${await(await f(n)).del(...e)}** of ${e.length} key(s): ${e.map(s=>`\`${s}\``).join(", ")}`}case"cache_exists":{const{instance_id:n,keys:e}=_;return`**${await(await f(n)).exists(...e)}** of ${e.length} key(s) exist in cache.`}case"cache_ttl":{const{instance_id:n,key:e}=_,t=await(await f(n)).ttl(e);if(t===-2)return`Key \`${e}\` \u2192 **does not exist**`;if(t===-1)return`Key \`${e}\` \u2192 **no expiry** (persists forever)`;const s=Math.floor(t/60),i=t%60;return`Key \`${e}\` \u2192 TTL: **${t}s** (${s}m ${i}s remaining)`}case"cache_keys":{const{instance_id:n,pattern:e="*",count:a=50}=_,t=Math.min(a,500),s=await f(n),i=[],c=s.scanStream({match:e,count:100});await new Promise((r,u)=>{c.on("data",d=>{i.push(...d),i.length>=t&&(c.destroy(),r())}),c.on("end",r),c.on("error",u)});const o=i.slice(0,t);return o.length===0?`No keys found matching pattern \`${e}\`.`:[`Found **${o.length}** key(s) matching \`${e}\`:`,...o.map(r=>` \u2022 \`${r}\``),o.length===t?`
|
|
5
5
|
_(showing first ${t} \u2014 narrow pattern to see more)_`:""].filter(Boolean).join(`
|
|
6
|
-
`)}case"cache_stats":{const{instance_id:n}=
|
|
7
|
-
]+)`))?.[1]?.trim()??"n/a",c=i(a,"used_memory_human"),o=i(a,"used_memory_peak_human"),r=i(t,"keyspace_hits"),
|
|
8
|
-
`).filter(w=>w.startsWith("db")).map(w=>` ${w.trim()}`),p=[`\u{1F4CA} **Cache Stats for instance \`${n}\`:**`,"",` \u{1F4BE} Memory used: ${c} (peak: ${o})`,` \u26A1 Ops/sec: ${d}`,` \u{1F3AF} Hit rate: ${
|
|
6
|
+
`)}case"cache_stats":{const{instance_id:n}=_,e=await f(n),[a,t,s]=await Promise.all([e.info("memory"),e.info("stats"),e.info("keyspace")]),i=(w,L)=>w.match(new RegExp(`${L}:([^\r
|
|
7
|
+
]+)`))?.[1]?.trim()??"n/a",c=i(a,"used_memory_human"),o=i(a,"used_memory_peak_human"),r=i(t,"keyspace_hits"),u=i(t,"keyspace_misses"),d=i(t,"instantaneous_ops_per_sec"),h=(await e.info("clients")).match(/connected_clients:(\d+)/)?.[1]??"n/a",y=parseInt(r)||0,g=parseInt(u)||0,T=y+g,S=T>0?(y/T*100).toFixed(1):"n/a",v=s.split(`
|
|
8
|
+
`).filter(w=>w.startsWith("db")).map(w=>` ${w.trim()}`),p=[`\u{1F4CA} **Cache Stats for instance \`${n}\`:**`,"",` \u{1F4BE} Memory used: ${c} (peak: ${o})`,` \u26A1 Ops/sec: ${d}`,` \u{1F3AF} Hit rate: ${S}% (${r} hits / ${u} misses)`,` \u{1F517} Clients: ${h}`,"",v.length>0?` \u{1F5C2}\uFE0F Keyspace:
|
|
9
9
|
${v.join(`
|
|
10
|
-
`)}`:" \u{1F5C2}\uFE0F Keyspace: (empty)"];try{const w=await
|
|
11
|
-
`)}case"semantic_search":{const{instance_id:n,query:e,threshold:a=.82,namespace:t="cachly:sem",top_k:s=5,use_hybrid:i=!1,auto_namespace:c=!1}=
|
|
10
|
+
`)}`:" \u{1F5C2}\uFE0F Keyspace: (empty)"];try{const w=await b(`/api/v1/instances/${n}`);if(w.vector_token){const L=process.env.CACHLY_VECTOR_URL??"https://api.cachly.dev",N=await fetch(`${L}/v1/sem/${w.vector_token}/stats`,{signal:AbortSignal.timeout(5e3)});if(N.ok){const m=await N.json(),A=(l,$=2)=>l!==void 0?l.toLocaleString("en-US",{minimumFractionDigits:$,maximumFractionDigits:$}):"n/a",j=l=>l!==void 0?l.toLocaleString("en-US"):"n/a",k=m.total_hits??0,x=m.total_entries??0;if(k===0&&x===0){const l=$=>($*50*.25*.002*30).toFixed(2);p.push("","\u{1F4B0} **Tokenmaxxing ROI \u2014 Projection:**"," \u{1F4ED} No cache hits yet \u2014 you're just getting started.",""," \u{1F4CA} Typical savings for your team size:",` 5 devs \xD7 50 LLM calls/day \xD7 25% hit-rate \u2192 ~$${l(5)}/month`,` 10 devs \xD7 50 LLM calls/day \xD7 25% hit-rate \u2192 ~$${l(10)}/month`,` 20 devs \xD7 50 LLM calls/day \xD7 25% hit-rate \u2192 ~$${l(20)}/month`," (Assumes avg $0.002/call saved per cache hit)",""," \u{1F680} Next: route LLM calls through cachly to start accumulating hits.",` Docs: ${X("/docs/semantic","cache-stats")}`)}else{const l=m.savings?.week_over_week_pct,$=l!==void 0?` ${l>=0?"\u{1F4C8}":"\u{1F4C9}"} 7d trend: ${l>=0?"+":""}${l.toFixed(1)}% vs prev week`:"";p.push("","\u{1F4B0} **Tokenmaxxing ROI:**",` \u{1F4E6} Semantic entries: ${j(m.total_entries)}`,` \u{1F3AF} Total cache hits: ${j(m.total_hits)}`,` \u23F1\uFE0F Hits last 24h: ${j(m.savings?.hits_last_24h)}`,` \u{1F4C5} Hits last 7d: ${j(m.savings?.hits_last_7d)}`,...$?[$]:[],` \u{1F4B5} Total saved: $${A(m.savings?.estimated_total_saved_usd)}`,` \u{1F4C8} Projected/month: $${A(m.savings?.estimated_monthly_saved_usd)}`,` \u{1F4CA} Avg per hit: $${A(m.savings?.avg_cost_per_call_usd,4)}`)}m.top_hits&&m.top_hits.length>0&&(p.push("","\u{1F51D} Top cached prompts:"),m.top_hits.slice(0,3).forEach(($,O)=>{const C=$.prompt.length>50?`${$.prompt.slice(0,50)}\u2026`:$.prompt;p.push(` ${O+1}. "${C}" (hit ${$.hit_count}\xD7)`)}))}}}catch{}return p.join(`
|
|
11
|
+
`)}case"semantic_search":{const{instance_id:n,query:e,threshold:a=.82,namespace:t="cachly:sem",top_k:s=5,use_hybrid:i=!1,auto_namespace:c=!1}=_,o=c?U(e):t;if(!K())return`\u274C semantic_search requires an embedding provider.
|
|
12
12
|
|
|
13
13
|
Current: ${J()}
|
|
14
14
|
|
|
15
15
|
Easiest: sign in (CACHLY_JWT). Embeddings then run on the cachly servers in the EU, no extra key.
|
|
16
16
|
Or set OLLAMA_BASE_URL to use a local model (no key needed).
|
|
17
|
-
Your own key with a third-party provider works only if you name the provider yourself: CACHLY_EMBED_PROVIDER=<openai|gemini|mistral|cohere> plus its API key. The text is then sent to that provider.`;const r=await
|
|
17
|
+
Your own key with a third-party provider works only if you name the provider yourself: CACHLY_EMBED_PROVIDER=<openai|gemini|mistral|cohere> plus its API key. The text is then sent to that provider.`;const r=await b(`/api/v1/instances/${n}`);if(!r.vector_token)return`\u274C Instance "${r.name}" needs a vector token for semantic search.
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
Upgrade at ${X(`/instances/${n}`,"upgrade")}`;const _=await R(e),d=process.env.CACHLY_VECTOR_URL??`https://api.cachly.dev/v1/sem/${r.vector_token}`,h={embedding:_,namespace:o,threshold:a,top_k:s};i&&(h.hybrid=!0,h.prompt=e);const y=await fetch(`${d}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new V(Y.InternalError,`Vector search failed: ${y.statusText}`);const g=await y.json();if(!g.length||g.length===1&&!g[0].found)return`\u{1F50D} No semantically similar entries found for:
|
|
19
|
+
Every tier includes one. Open ${X(`/instances/${n}`,"health")} and rotate the vector token.`;const u=await P(e),d=process.env.CACHLY_VECTOR_URL??`https://api.cachly.dev/v1/sem/${r.vector_token}`,h={embedding:u,namespace:o,threshold:a,top_k:s};i&&(h.hybrid=!0,h.prompt=e);const y=await fetch(`${d}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new V(Y.InternalError,`Vector search failed: ${y.statusText}`);const g=await y.json();if(!g.length||g.length===1&&!g[0].found)return`\u{1F50D} No semantically similar entries found for:
|
|
21
20
|
_"${e}"_
|
|
22
21
|
|
|
23
|
-
Try lowering the threshold (current: ${a}) or using different keywords.`;const T=await f(n),
|
|
24
|
-
`)}case"detect_namespace":{const{prompt:n}=
|
|
25
|
-
`)}case"cache_warmup":{const{instance_id:n,entries:e,namespace:a="cachly:sem",ttl:t,auto_namespace:s=!1}=
|
|
22
|
+
Try lowering the threshold (current: ${a}) or using different keywords.`;const T=await f(n),S=[`\u{1F50D} **Semantic search results** for: _"${e}"_`,` Threshold: ${a} \xB7 Namespace: \`${o}\``,""];for(const v of g){if(!v.found||!v.id)continue;const p=await T.get(`${o}:val:${v.id}`);S.push(`**Match** (similarity: ${((v.similarity??0)*100).toFixed(1)}%)`,` Prompt: _"${v.prompt??"(unknown)"}"_`,p?` Value: \`${p.slice(0,200)}${p.length>200?"\u2026":""}\``:" Value: _(evicted from cache)_","")}return S.join(`
|
|
23
|
+
`)}case"detect_namespace":{const{prompt:n}=_,e=U(n),a=e.split(":").pop(),t={code:"\u{1F4BB} Code \u2014 contains programming constructs or syntax",translation:"\u{1F310} Translation \u2014 asks to translate between languages",summary:"\u{1F4DD} Summary \u2014 requests a summary or key points (TL;DR)",qa:"\u2753 Q&A \u2014 a direct question or query",creative:"\u{1F3A8} Creative \u2014 general, creative, or conversational prompt"};return[`**Detected namespace:** \`${e}\``,`**Type:** ${t[a]??a}`,"",`_Prompt: "${n.slice(0,120)}${n.length>120?"\u2026":""}"_`,"","\u{1F4A1} Use this namespace in `semantic_search` or `cache_warmup` for better hit rates."," Set `auto_namespace: true` to apply this detection automatically."].join(`
|
|
24
|
+
`)}case"cache_warmup":{const{instance_id:n,entries:e,namespace:a="cachly:sem",ttl:t,auto_namespace:s=!1}=_;if(!K())return`\u274C cache_warmup requires an embedding provider.
|
|
26
25
|
|
|
27
26
|
Current: ${J()}
|
|
28
27
|
|
|
29
28
|
Supported: openai (default) \xB7 mistral \xB7 cohere \xB7 ollama (local) \xB7 gemini
|
|
30
|
-
Set CACHLY_EMBED_PROVIDER and the matching API key env var.`;const i=await
|
|
31
|
-
`)}case"index_project":{const{instance_id:n,dir:e,extensions:a,max_files:t=100,ttl:s=86400,summary_chars:i=1200,namespace:c="cachly:sem:code",hintergrund:o=!1}=
|
|
32
|
-
Extensions checked: ${[...r].join(", ")}`;const h=await
|
|
33
|
-
${H}`;if(s>0?await m.set(M,I,"EX",s):await m.set(M,I),s>0?await m.set(
|
|
34
|
-
${H}`;await
|
|
35
|
-
`)}case"cache_mset":{const{instance_id:n,items:e}=
|
|
29
|
+
Set CACHLY_EMBED_PROVIDER and the matching API key env var.`;const i=await b(`/api/v1/instances/${n}`),c=process.env.CACHLY_VECTOR_URL??(i.vector_token?`https://api.cachly.dev/v1/sem/${i.vector_token}`:null),o=await f(n);let r=0,u=0;const d=[];for(const h of e){const y=h.namespace??(s?U(h.prompt):a),g=await P(h.prompt);let T=!1;if(c){const p=await fetch(`${c}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:g,namespace:y,threshold:.98}),signal:AbortSignal.timeout(8e3)}).catch(()=>null);p?.ok&&(T=(await p.json())[0]?.found??!1)}if(T){u++,d.push(` \u23ED\uFE0F _"${h.prompt.slice(0,60)}${h.prompt.length>60?"\u2026":""}"_ \u2192 already cached`);continue}const S=R(),v=`${y}:val:${S}`;if(t&&t>0?await o.set(v,h.value,"EX",t):await o.set(v,h.value),c){const p={id:S,prompt:h.prompt,namespace:y,embedding:g};t&&t>0&&(p.expires_at=new Date(Date.now()+t*1e3).toISOString()),await fetch(`${c}/entries`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(8e3)}).catch(()=>{})}else{const p=`${y}:emb:${S}`,w=JSON.stringify({embedding:g,prompt:h.prompt});t&&t>0?await o.set(p,w,"EX",t):await o.set(p,w)}r++,d.push(` \u2705 _"${h.prompt.slice(0,60)}${h.prompt.length>60?"\u2026":""}"_ \u2192 \`${y}\``)}return["\u{1F525} **Cache Warmup Complete**","",` \u2705 Warmed: **${r}** new entries`,` \u23ED\uFE0F Skipped: **${u}** (already cached at \u2265 0.98 similarity)`,` \u{1F4E6} Total: ${e.length}`,s?" \u{1F3F7}\uFE0F Namespacing: auto-detected per prompt":` \u{1F3F7}\uFE0F Namespace: \`${a}\``,c?" \u{1F50D} Mode: pgvector HNSW":" \u{1F50D} Mode: Valkey SCAN (set CACHLY_VECTOR_URL for pgvector search)","",...d].join(`
|
|
30
|
+
`)}case"index_project":{const{instance_id:n,dir:e,extensions:a,max_files:t=100,ttl:s=86400,summary_chars:i=1200,namespace:c="cachly:sem:code",hintergrund:o=!1}=_,r=new Set((a??["ts","js","tsx","jsx","go","py","java","rs","md","kt","swift"]).map(k=>k.startsWith(".")?k:`.${k}`)),u=[];async function d(k){if(u.length>=t)return;const x=await B(k,{withFileTypes:!0}).catch(()=>null);if(x)for(const l of x){if(u.length>=t)break;const $=Q(k,l.name);if(l.isDirectory()){if([".git","node_modules","dist","build",".next","__pycache__","vendor"].includes(l.name))continue;await d($)}else l.isFile()&&r.has(ee(l.name).toLowerCase())&&u.push($)}}if(await d(e),u.length===0)return`\u274C No matching files found in \`${e}\`.
|
|
31
|
+
Extensions checked: ${[...r].join(", ")}`;const h=await b(`/api/v1/instances/${n}`),y=process.env.CACHLY_VECTOR_URL??(h.vector_token?`https://api.cachly.dev/v1/sem/${h.vector_token}`:null),g=y&&K();let T=0,S=0,v=0,p=0,w=0;const L=[],N=new Date(Date.now()+s*1e3).toISOString(),m=await f(n),A=te({hintergrund:o});for(const k of u){const x=Z(e,k);let l,$;try{const E=await z(k);if(E.size>2e5){S++;continue}$=E.size,l=await G(k,"utf-8")}catch{v++;continue}const O=`cachly:idx:hash:${x}`,C=`${$}:${l.length}:${se(l)}`;if(await m.get(O)===C){const E=`cachly:idx:${x}`;s>0&&await m.expire(E,s),s>0&&await m.expire(O,s),w++;continue}const H=l.slice(0,i).replace(/\s+/g," ").trim(),M=`cachly:idx:${x}`,I=`File: ${x}
|
|
32
|
+
${H}`;if(s>0?await m.set(M,I,"EX",s):await m.set(M,I),s>0?await m.set(O,C,"EX",s):await m.set(O,C),T++,L.push(` \u2705 ${x}`),g&&A.darf())try{const E=`File: ${x}
|
|
33
|
+
${H}`;await A.warte();const W=await P(E).catch(q=>{throw A.fehler(q),q}),D=R();await fetch(`${y}/entries`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:D,prompt:E,namespace:c,embedding:W,expires_at:N}),signal:AbortSignal.timeout(8e3)}),await m.set(`${c}:val:${D}`,x,"EX",s),p++}catch{}}return[`\u{1F4C2} **index_project Complete** \u2014 ${g?"\u{1F50D} Keyword + \u{1F3AF} Semantic":"\u{1F50D} Keyword only (no embedding provider)"}`,"",` \u{1F4C1} Dir: ${e}`,` \u2705 Indexed: **${T}** files (new/changed)`,` \u267B\uFE0F Unchanged: ${w} files (hash match \u2014 skipped)`,...g?[` \u{1F3AF} Semantic: **${p}** files (vector-searchable)`]:[],` \u23ED\uFE0F Skipped: ${S} (too large or filtered)`,` \u274C Errors: ${v}`,` \u23F1\uFE0F TTL: ${s}s (${Math.round(s/3600)}h)`,"","\u{1F4A1} **Next steps:**",' 1. Use `smart_recall("how does auth work")` to find relevant files.'," 2. Re-run index_project after major refactors.",...g?[]:[" 3. Sign in (CACHLY_JWT) or set OLLAMA_BASE_URL to also enable semantic search."],"",...L.length<=20?L:[...L.slice(0,20),` \u2026 and ${L.length-20} more`]].join(`
|
|
34
|
+
`)}case"cache_mset":{const{instance_id:n,items:e}=_;if(!Array.isArray(e)||e.length===0)return"\u26A0\uFE0F No items provided.";const t=(await f(n)).pipeline();for(const s of e){const i=typeof s.value=="string"?s.value:JSON.stringify(s.value);s.ttl&&s.ttl>0?t.set(s.key,i,"EX",s.ttl):t.set(s.key,i)}return await t.exec(),`\u2705 **cache_mset** \u2013 ${e.length} key(s) written in one pipeline round-trip.
|
|
36
35
|
`+e.map(s=>` \u2022 \`${s.key}\`${s.ttl?` (TTL ${s.ttl}s)`:""}`).join(`
|
|
37
|
-
`)}case"cache_mget":{const{instance_id:n,keys:e}=
|
|
36
|
+
`)}case"cache_mget":{const{instance_id:n,keys:e}=_;if(!Array.isArray(e)||e.length===0)return"\u26A0\uFE0F No keys provided.";const t=await(await f(n)).mget(...e),s=e.map((i,c)=>{const o=t[c];return o===null?` \u2022 \`${i}\`: _null (miss)_`:` \u2022 \`${i}\`: ${o}`});return`\u2705 **cache_mget** \u2013 ${e.length} key(s) fetched in one round-trip.
|
|
38
37
|
`+s.join(`
|
|
39
|
-
`)}case"cache_lock_acquire":{const{instance_id:n,key:e,ttl_ms:a=5e3,retries:t=3,retry_delay_ms:s=50}=
|
|
38
|
+
`)}case"cache_lock_acquire":{const{instance_id:n,key:e,ttl_ms:a=5e3,retries:t=3,retry_delay_ms:s=50}=_,i=await f(n),c=`cachly:lock:${e}`,o=R();for(let r=0;r<=t;r++){if(await i.set(c,o,"PX",a,"NX")==="OK")return`\u{1F512} **cache_lock_acquire** \u2013 Lock acquired!
|
|
40
39
|
|
|
41
40
|
Key: \`${e}\`
|
|
42
41
|
Token: \`${o}\`
|
|
43
42
|
TTL: ${a} ms
|
|
44
43
|
|
|
45
|
-
\u{1F4A1} Use **cache_lock_release** with this token to release early.`;r<t&&await new Promise(d=>setTimeout(d,s))}return`\u274C **cache_lock_acquire** \u2013 Could not acquire lock for \`${e}\` after ${t+1} attempts.`}case"cache_lock_release":{const{instance_id:n,key:e,token:a}=
|
|
44
|
+
\u{1F4A1} Use **cache_lock_release** with this token to release early.`;r<t&&await new Promise(d=>setTimeout(d,s))}return`\u274C **cache_lock_acquire** \u2013 Could not acquire lock for \`${e}\` after ${t+1} attempts.`}case"cache_lock_release":{const{instance_id:n,key:e,token:a}=_;return await(await f(n)).eval('if redis.call("get",KEYS[1])==ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end',1,`cachly:lock:${e}`,a)===1?`\u{1F513} **cache_lock_release** \u2013 Lock \`${e}\` released.`:`\u26A0\uFE0F **cache_lock_release** \u2013 Lock \`${e}\` expired or token mismatch.`}case"cache_stream_set":{const{instance_id:n,key:e,chunks:a,ttl:t}=_;if(!Array.isArray(a)||a.length===0)return"\u26A0\uFE0F No chunks provided.";const s=await f(n),i=`cachly:stream:${e}`;await s.del(i);const c=s.pipeline();for(const o of a)c.rpush(i,o);return t&&t>0&&c.expire(i,t),await c.exec(),`\u2705 **cache_stream_set** \u2013 ${a.length} chunk(s) stored.
|
|
46
45
|
Key: \`${e}\`
|
|
47
46
|
${t?` TTL: ${t}s
|
|
48
|
-
`:""} Total size: ${a.reduce((o,r)=>o+r.length,0)} chars`}case"cache_stream_get":{const{instance_id:n,key:e}=
|
|
47
|
+
`:""} Total size: ${a.reduce((o,r)=>o+r.length,0)} chars`}case"cache_stream_get":{const{instance_id:n,key:e}=_,a=await f(n),t=`cachly:stream:${e}`,s=await a.llen(t);if(s===0)return`\u26A0\uFE0F **cache_stream_get** \u2013 Cache miss for key \`${e}\`.`;const c=(await a.lrange(t,0,-1)).join(""),o=c.slice(0,500);return`\u2705 **cache_stream_get** \u2013 ${s} chunk(s) retrieved for \`${e}\`.
|
|
49
48
|
|
|
50
49
|
**Preview** (first 500 chars):
|
|
51
50
|
\`\`\`
|
|
52
51
|
${o}${o.length<c.length?"\u2026":""}
|
|
53
|
-
\`\`\``}case"cache_org_stats":{const{instance_id:n,org_id:e}=
|
|
54
|
-
`)}case"set_cost_per_call":{const{instance_id:n,cost_per_call_usd:e}=
|
|
55
|
-
`)}default:return null}}export{
|
|
52
|
+
\`\`\``}case"cache_org_stats":{const{instance_id:n,org_id:e}=_,a=await f(n),t=`org:${e}:sem`,i=(await ae(a,`${t}:*`,{max:1e4,timeoutMs:5e3})).length,c=[`\u{1F3E2} Org Cache Stats for org \`${e}\`:`,` \u{1F4E6} Shared entries: ${i}`,` \u{1F511} Namespace: ${t}`," \u{1F465} Benefit: All instances sharing this org_id serve from the same cache","",`\u{1F4A1} To enable sharing: set org_id="${e}" in cache_set calls`];try{const o=await b(`/api/v1/orgs/${e}/savings`),r=d=>`$${(d??0).toFixed(2)}`;c.push("","\u{1F4B0} Org-wide Tokenmaxxing ROI:",` \u{1F5A5}\uFE0F Instances: ${o.instance_count}`,` \u{1F3AF} Total cache hits: ${o.total_hits.toLocaleString("en-US")}`,` \u23F1\uFE0F Hits last 24h: ${o.hits_last_24h.toLocaleString("en-US")}`,` \u{1F4B5} Total saved: ${r(o.estimated_total_saved_usd)}`,` \u{1F4C8} Projected/month: ${r(o.estimated_monthly_saved_usd)}`);const u=[...o.per_instance??[]].sort((d,h)=>h.estimated_total_saved_usd-d.estimated_total_saved_usd).slice(0,5);if(u.length>0){c.push(""," Top instances by savings:");for(const d of u)c.push(` \u2022 ${d.name||d.instance_id}: ${r(d.estimated_total_saved_usd)} (${d.total_hits.toLocaleString("en-US")} hits)`)}}catch{}return c.join(`
|
|
53
|
+
`)}case"set_cost_per_call":{const{instance_id:n,cost_per_call_usd:e}=_;if(!e||e<=0||e>100)throw new V(Y.InvalidParams,"cost_per_call_usd must be a positive number \u2264 100");await b(`/api/v1/instances/${n}/cost-per-call`,{method:"PUT",body:JSON.stringify({cost_per_call_usd:e})});const a={"0.02":"claude-opus-4.8","0.015":"gpt-5.5","0.009":"claude-sonnet-4.6","0.002":"gpt-5.5-mini","0.001":"claude-haiku-4.5"},t=a[e.toString()]?` (${a[e.toString()]})`:"";return[`\u2705 **Cost per call updated** \u2014 $${e.toFixed(4)}${t}`,"",`ROI savings in \`cache_stats\` will now use $${e.toFixed(4)} per avoided LLM call.`,"Run `cache_stats` to see your updated savings estimate."].join(`
|
|
54
|
+
`)}default:return null}}export{ue as CACHE_TOOL_NAMES,$e as handleCacheTool};
|
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
const g=new Set(["list_instances","create_instance","get_instance","get_connection_string","delete_instance","list_orgs","create_org","invite_member","get_org_plan"]);function m(a){const i=a.status==="running"?"\u{1F7E2}":a.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",c=a.memory_mb>=1024?`${a.memory_mb/1024}GB`:`${a.memory_mb}MB`;return`${i} **${a.name}** (\`${a.id}\`) \xB7 ${a.tier} \xB7 ${c} \xB7 ${a.region}`}function
|
|
1
|
+
const g=new Set(["list_instances","create_instance","get_instance","get_connection_string","delete_instance","list_orgs","create_org","invite_member","get_org_plan"]);function m(a){const i=a.status==="running"?"\u{1F7E2}":a.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",c=a.memory_mb>=1024?`${a.memory_mb/1024}GB`:`${a.memory_mb}MB`;return`${i} **${a.name}** (\`${a.id}\`) \xB7 ${a.tier} \xB7 ${c} \xB7 ${a.region}`}function l(a){if(!a.host)return"\u274C Instance not ready yet.";const i=a.tls_enabled?"rediss":"redis",c=a.password?`:${a.password}@`:"";return`${i}://${c}${a.host}:${a.port??6379}`}async function u(a,i,c,r){switch(a){case"list_instances":{const e=(await r("/api/v1/instances")).data??[];return e.length===0?"You have no cache instances yet. Use `create_instance` to create one.":[`Found ${e.length} instance(s):
|
|
2
2
|
`,...e.map(m)].join(`
|
|
3
3
|
`)}case"create_instance":{const{name:n,tier:e}=i,t=await r("/api/v1/instances",{method:"POST",body:JSON.stringify({name:n,tier:e,created_via:"api"})});return t.checkout_url?[`\u2705 Instance **${n}** (${e}) created! ID: \`${t.instance_id}\``,"","\u{1F4B3} This is a paid tier. Complete payment to activate:",` ${t.checkout_url}`,"","After payment, provisioning starts automatically (~30 seconds)."].join(`
|
|
4
4
|
`):[`\u2705 Instance **${n}** (${e}) created and provisioning started!`,` ID: \`${t.instance_id}\``,` Status: ${t.status}`,"","Use `get_instance` or `get_connection_string` to get your connection details."].join(`
|
|
5
|
-
`)}case"get_instance":{const n=await r(`/api/v1/instances/${i.instance_id}`);return m(n)}case"get_connection_string":{const n=await r(`/api/v1/instances/${i.instance_id}`);if(n.status!=="running")return`Instance is not running yet (status: ${n.status}). Provisioning takes ~30 seconds after payment.`;let e={},t=!1;try{e=await r(`/api/v1/instances/${i.instance_id}/connection`)}catch{t=!0}const s=e.connection_string||
|
|
5
|
+
`)}case"get_instance":{const n=await r(`/api/v1/instances/${i.instance_id}`);return m(n)}case"get_connection_string":{const n=await r(`/api/v1/instances/${i.instance_id}`);if(n.status!=="running")return`Instance is not running yet (status: ${n.status}). Provisioning takes ~30 seconds after payment.`;let e={},t=!1;try{e=await r(`/api/v1/instances/${i.instance_id}/connection`)}catch{t=!0}const s=e.connection_string||l(n);return[...!s.includes("@")?t?["\u26A0\uFE0F Could not read the credentials endpoint \u2014 this string has NO password and will fail with NOAUTH if the instance requires one.",""]:e.password?["\u26A0\uFE0F The server returned a password but this string carries none \u2014 please report this.",""]:[]:[],`**Connection string for ${n.name}:**`,"```",s,"```","","**Environment variable:**","```bash",`REDIS_URL="${s}"`,`CACHLY_URL="${s}"`,"```","","**Quick test:**","```bash",`redis-cli -u "${s}" PING`,"```"].join(`
|
|
6
6
|
`)}case"delete_instance":{const{instance_id:n,confirm:e}=i;if(!e)return"Deletion cancelled. Set `confirm: true` to proceed.";try{c._pool?.delete?.(n)}catch{}return await r(`/api/v1/instances/${n}`,{method:"DELETE"}),`\u2705 Instance \`${n}\` has been deleted and all data removed.`}case"list_orgs":{const e=(await r("/api/v1/orgs")).orgs??[];return e.length===0?`\u{1F4ED} No organizations yet.
|
|
7
7
|
|
|
8
8
|
Create one with \`create_org(name="My Team")\`.
|
|
9
|
-
|
|
9
|
+
Organizations are free. Up to 5 people share the Brain tier Team (\u20AC49/mo, everything included).
|
|
10
|
+
Org plans: Business \u20AC199/mo (20 seats, SSO), Enterprise custom.`:[`\u{1F3E2} **Your organizations (${e.length})**
|
|
10
11
|
`,...e.map(t=>`\u2022 **${t.name}** (\`${t.slug}\`) \u2014 plan: ${t.plan} \xB7 seats: ${t.member_count??"?"}/${t.max_members}
|
|
11
12
|
ID: \`${t.id}\``),"\n_Manage: `get_org_plan`, `invite_member`, dashboard \u2192 /team_"].join(`
|
|
12
|
-
`)}case"create_org":{const{name:n,slug:e}=i,t={name:n};e&&(t.slug=e);const s=await r("/api/v1/orgs",{method:"POST",body:JSON.stringify(t)});return[`\u2705 **Organization created:** ${s.name}`,` ID: \`${s.id}\` \xB7 Slug: \`${s.slug}\` \xB7 Plan: ${s.plan}`,"","**Next steps:**",`1. Invite team members: \`invite_member(org_id="${s.id}", email="dev@example.com")\``,"2.
|
|
13
|
+
`)}case"create_org":{const{name:n,slug:e}=i,t={name:n};e&&(t.slug=e);const s=await r("/api/v1/orgs",{method:"POST",body:JSON.stringify(t)});return[`\u2705 **Organization created:** ${s.name}`,` ID: \`${s.id}\` \xB7 Slug: \`${s.slug}\` \xB7 Plan: ${s.plan}`,"","**Next steps:**",`1. Invite team members: \`invite_member(org_id="${s.id}", email="dev@example.com")\``,"2. Up to 5 people: Brain tier Team, \u20AC49/mo, everything included (dashboard \u2192 /billing)"," Org plan Business: \u20AC199/mo (20 seats, SSO)"].join(`
|
|
13
14
|
`)}case"invite_member":{const{org_id:n,email:e,role:t="member"}=i;return await r(`/api/v1/orgs/${n}/members`,{method:"POST",body:JSON.stringify({email:e,role:t})}),`\u2705 Invite sent to **${e}** as \`${t}\` in org \`${n}\`.
|
|
14
15
|
|
|
15
|
-
They will receive an email to join the organization.`}case"get_org_plan":{const{org_id:n}=i,e=await r(`/api/v1/orgs/${n}`),t=(e.members??[]).filter(o=>o.accepted_at).length,s=(e.members??[]).filter(o=>!o.accepted_at).length,
|
|
16
|
-
`)}default:return null}}export{g as INSTANCE_TOOL_NAMES,
|
|
16
|
+
They will receive an email to join the organization.`}case"get_org_plan":{const{org_id:n}=i,e=await r(`/api/v1/orgs/${n}`),t=(e.members??[]).filter(o=>o.accepted_at).length,s=(e.members??[]).filter(o=>!o.accepted_at).length,d={free:"\u20AC0",team:"legacy",business:"\u20AC199/mo",enterprise:"custom"};return[`\u{1F3E2} **${e.name}** \u2014 Plan: **${e.plan}** (${d[e.plan]??e.plan})`,` Seats: ${t} active + ${s} pending / ${e.max_members} max`,"","**Members:**",...(e.members??[]).map(o=>` \u2022 ${o.invite_email} (${o.role})${o.accepted_at?"":" \u2014 pending"}`),"",e.stripe_customer_id?"\u{1F4B3} Billing: managed via Stripe. Upgrade/cancel: dashboard \u2192 /billing":"\u{1F4B3} Add a payment method for Business: dashboard \u2192 /billing \u2192 Teams"].join(`
|
|
17
|
+
`)}default:return null}}export{g as INSTANCE_TOOL_NAMES,l as buildConnectionString,m as formatInstance,u as handleInstanceTool};
|
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
import{readFileSync as fe}from"node:fs";import{bauabdruck as ge,formatiereBauabdruck as we}from"../bauabdruck.js";import{beurteileSpeicher as ye,zahlAusInfo as ie}from"../speicherlage.js";import{beurteileDeckung as _e}from"../eingaenge.js";import{VEKTOR_NACHTRAG as $e,NAME_VEKTOR_NACHTRAG as ve,ZWEIT_VEKTOR_NACHTRAG as be}from"../bedeutung.js";import{join as I}from"node:path";import{calculateConfidence as q,CONFIDENCE_STALE_VALUE as te,CONFIDENCE_WARN_VALUE as ke,CONFIDENCE_WARN_DAYS as ce,CONFIDENCE_STALE_DAYS as le}from"../confidence.js";import{safeJsonParse as C}from"../utils.js";import{ersparteMinuten as Se,istStarterLektion as xe,fmtStunden as ue}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Le,buildClaudeMdBlock as je,setzeAnweisungsblock as Ae}from"../projektdateien.js";import{leseVermerke as Oe}from"../aussetzer.js";import{schwaerzeFelder as Re}from"../geheimnis-filter.js";import{VERDACHT_TAG as Ne,pruefeFelder as Ce,verdachtsWarnung as Ee}from"../tuersteher.js";import{fuerEigenenSpeicher as se,fuerWeitergabe as De,fuerZusammenfassung as he,hinweise as ne,markiert as Te,markierungsWarnung as Me,weitergabeHinweis as Ie}from"../schreibtor.js";const it=new Set(["sync_file_changes","team_learn","team_confirm","team_recall","team_synthesize","memory_crystalize","team_crystallize","brain_doctor","brain_hygiene","recall_at","trace_dependency","global_learn","global_recall","publish_lesson","import_public_brain","setup_ai_memory","team_assign_role","team_whoami","team_roster","team_grant_scope","team_scopes","team_audit"]),Y={admin:4,reviewer:3,contributor:2,viewer:1},K={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},oe={admin:"assign roles \xB7 delete lessons \xB7 all reviewer + contributor actions",reviewer:"senior-review lessons (\u{1F6E1}\uFE0F) \xB7 all contributor actions",contributor:"store lessons \xB7 peer-review lessons (\u2714\uFE0F) \xB7 recall",viewer:"recall only \u2014 cannot store or review lessons"},B=L=>`cachly:team:roles:${L}`;async function G(L,w,_){return await L.hget(B(w),_.toLowerCase()).catch(()=>null)}function Z(L,w){return L?(Y[L]??0)>=(Y[w]??0):!1}function ze(L){return L==="admin"||L==="reviewer"?"senior":"peer"}async function Pe(L,w){const _=await L.hgetall(B(w)).catch(()=>({}));return Object.values(_).includes("admin")}async function ae(L,w,_,E,l){if(!await Pe(L,w))return null;const
|
|
1
|
+
import{readFileSync as fe}from"node:fs";import{bauabdruck as ge,formatiereBauabdruck as we}from"../bauabdruck.js";import{beurteileSpeicher as ye,zahlAusInfo as ie}from"../speicherlage.js";import{beurteileDeckung as _e}from"../eingaenge.js";import{VEKTOR_NACHTRAG as $e,NAME_VEKTOR_NACHTRAG as ve,ZWEIT_VEKTOR_NACHTRAG as be}from"../bedeutung.js";import{join as I}from"node:path";import{calculateConfidence as q,CONFIDENCE_STALE_VALUE as te,CONFIDENCE_WARN_VALUE as ke,CONFIDENCE_WARN_DAYS as ce,CONFIDENCE_STALE_DAYS as le}from"../confidence.js";import{safeJsonParse as C}from"../utils.js";import{ersparteMinuten as Se,istStarterLektion as xe,fmtStunden as ue}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Le,buildClaudeMdBlock as je,setzeAnweisungsblock as Ae}from"../projektdateien.js";import{leseVermerke as Oe}from"../aussetzer.js";import{schwaerzeFelder as Re}from"../geheimnis-filter.js";import{VERDACHT_TAG as Ne,pruefeFelder as Ce,verdachtsWarnung as Ee}from"../tuersteher.js";import{fuerEigenenSpeicher as se,fuerWeitergabe as De,fuerZusammenfassung as he,hinweise as ne,markiert as Te,markierungsWarnung as Me,weitergabeHinweis as Ie}from"../schreibtor.js";const it=new Set(["sync_file_changes","team_learn","team_confirm","team_recall","team_synthesize","memory_crystalize","team_crystallize","brain_doctor","brain_hygiene","recall_at","trace_dependency","global_learn","global_recall","publish_lesson","import_public_brain","setup_ai_memory","team_assign_role","team_whoami","team_roster","team_grant_scope","team_scopes","team_audit"]),Y={admin:4,reviewer:3,contributor:2,viewer:1},K={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},oe={admin:"assign roles \xB7 delete lessons \xB7 all reviewer + contributor actions",reviewer:"senior-review lessons (\u{1F6E1}\uFE0F) \xB7 all contributor actions",contributor:"store lessons \xB7 peer-review lessons (\u2714\uFE0F) \xB7 recall",viewer:"recall only \u2014 cannot store or review lessons"},B=L=>`cachly:team:roles:${L}`;async function G(L,w,_){return await L.hget(B(w),_.toLowerCase()).catch(()=>null)}function Z(L,w){return L?(Y[L]??0)>=(Y[w]??0):!1}function ze(L){return L==="admin"||L==="reviewer"?"senior":"peer"}async function Pe(L,w){const _=await L.hgetall(B(w)).catch(()=>({}));return Object.values(_).includes("admin")}async function ae(L,w,_,E,l){if(!await Pe(L,w))return null;const t=_?await G(L,w,_):null;if(Z(t,E))return null;const i=t?`${K[t]} ${t}`:"no role";return[`\u{1F512} **Permission denied** \u2014 to ${l} you need at least \`${E}\` ${K[E]} (you have: ${i}).`,"","Ask an admin to grant it:",`\`team_assign_role(instance_id="${w}", handle="${_||"<your-handle>"}", role="${E}", assigned_by="<admin>")\``,"_Governance is active on this brain. Run `team_whoami` to check your role._"].join(`
|
|
2
2
|
`)}async function de(L,w,_){const E=`cachly:team:audit:${w}`,l=JSON.stringify({..._,ts:new Date().toISOString()});await L.rpush(E,l).catch(()=>{}),await L.ltrim(E,-500,-1).catch(()=>{}),await L.expire(E,365*2*86400).catch(()=>{})}const Be="cachly:team:review_mode",Fe="cachly:lesson:proposed:",Ue=90*86400;async function Ke(L,w){const _=await L.get(Be).catch(()=>null);return _==="1"||_==="true"||_==="on"}async function Je(L,w,_){const E={..._,proposed_at:new Date().toISOString(),status:"pending"};await L.set(`${Fe}${w}`,JSON.stringify(E),"EX",Ue).catch(()=>{});const l=typeof _.author=="string"&&_.author?` by **${_.author}**`:"";return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${w}\`${l} is now a pending proposal.`,"","This team requires review before knowledge enters the Team Brain (org setting).","An org owner/admin can approve or reject it in the dashboard under **Team \u2192 Review**.","Until approved it will NOT surface in `smart_recall` / `team_recall`."].join(`
|
|
3
|
-
`)}const V=L=>`cachly:team:groups:${L}`,W=(L,w)=>`cachly:team:group:${L}:${w.toLowerCase()}`;async function Ge(L,w,_){const E=await L.smembers(V(w)).catch(()=>[]),l=new Set;for(const
|
|
4
|
-
`)}case"team_learn":{const l=Re(w).felder,
|
|
5
|
-
\u{1F4A1} ${c.slice(0,120)}${
|
|
6
|
-
${Ee(
|
|
3
|
+
`)}const V=L=>`cachly:team:groups:${L}`,W=(L,w)=>`cachly:team:group:${L}:${w.toLowerCase()}`;async function Ge(L,w,_){const E=await L.smembers(V(w)).catch(()=>[]),l=new Set;for(const t of E)await L.sismember(W(w,t),_.toLowerCase()).catch(()=>0)&&l.add(t.toLowerCase());return l}function ct(L,w,_){return!L||_?!0:w.has(L.toLowerCase())}async function lt(L,w,_,E){switch(L){case"sync_file_changes":{const{instance_id:l,changed_files:t,git_diff_stat:i,commit_msg:a}=w,o=se({changed_files:t,git_diff_stat:i,commit_msg:a}),{changed_files:e,git_diff_stat:c,commit_msg:r}=o.felder,h=await _(l),s={ts:new Date().toISOString(),files:e,commit_msg:r,diff_stat:c?.slice(0,500),...o.verdacht.length?{verdacht:o.verdacht}:{}};await h.lpush("cachly:session:file_changes",JSON.stringify(s)),await h.ltrim("cachly:session:file_changes",0,99),await h.expire("cachly:session:file_changes",30*86400);const n=[],m=h.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise(($,b)=>{m.on("data",S=>n.push(...S)),m.on("end",$),m.on("error",b)});const g=[],v=n.length>0?await h.mget(...n):[];for(const $ of v){if(!$)continue;const b=C($,null);if(!b)continue;const S=b.topic.toLowerCase().split(/[:\-_]/);if(e.some(u=>{const p=u.split("/").pop()?.replace(/\.[^.]+$/,"").toLowerCase()??"";return S.some(k=>k.length>3&&p.includes(k))||(b.file_paths??[]).some(k=>u.includes(k)||k.includes(u))})){const u=b.outcome==="success"?"\u2705":"\u26A0\uFE0F";g.push(` ${u} \`${b.topic}\` \u2014 ${b.what_worked.slice(0,80)}`)}}const j=[`\u{1F4C1} **File sync recorded**: ${e.length} files`,r?`\u{1F4DD} Commit: "${r}"`:"","",`**Changed:** ${e.slice(0,8).map($=>`\`${$}\``).join(", ")}${e.length>8?` +${e.length-8} more`:""}`,"",...ne(o,"notiz")];return g.length>0?j.push(`\u{1F9E0} **Relevant brain lessons (${g.length}):**`,...g):j.push("\u{1F4A1} No existing lessons match these files yet. Add them with `learn_from_attempts`."),j.filter(Boolean).join(`
|
|
4
|
+
`)}case"team_learn":{const l=Re(w).felder,t=Ce(l),{instance_id:i,author:a,topic:o,outcome:e,what_worked:c,what_failed:r,severity:h,file_paths:s,commands:n,tags:m}=l;if(!a||!o||!e||!c)return"\u274C Required: author, topic, outcome, what_worked";const g=i;if(!g)return"\u274C instance_id required";const v=await _(g),j=await ae(v,g,a,"contributor","store team lessons");if(j)return j;const $={topic:o,outcome:e,what_worked:c,what_failed:r??"",severity:h??"minor",author:a,file_paths:s??[],commands:n??[],tags:[...m??[],"team",...t.length?[Ne]:[]],timestamp:new Date().toISOString(),recall_count:0,version:2};if(await Ke(v,g))return Je(v,o,$);const b=`cachly:lessons:${o}`;return await v.rpush(b,JSON.stringify($)),e==="success"&&await v.set(`cachly:lesson:best:${o}`,JSON.stringify($)),`\u2705 Team lesson stored by **${a}**: \`${o}\` (${e})
|
|
5
|
+
\u{1F4A1} ${c.slice(0,120)}${t.length?`
|
|
6
|
+
${Ee(t)}`:""}`}case"team_confirm":{const{instance_id:l,topic:t,reviewer:i,level:a,note:o=""}=w,e=se({note:o}),c=e.felder.note;if(!l)return"\u274C instance_id required";if(!t||!i)return"\u274C Required: topic, reviewer";const r=await _(l),h=await ae(r,l,i,"reviewer","confirm team lessons");if(h)return h;const s=await G(r,l,i),n=ze(s),m=a==="peer"?"peer":a==="senior"&&Z(s,"reviewer")?"senior":n,g=s?` (role: ${K[s]} ${s})`:" (no role assigned \u2014 peer weight applied)",v=`cachly:lesson:best:${t}`,j=await r.get(v),$=C(j,null);if(!$)return`\u{1F4ED} No best-solution lesson found for \`${t}\`.
|
|
7
7
|
|
|
8
|
-
A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;const b=`cachly:lesson:endorsers:${
|
|
8
|
+
A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;const b=`cachly:lesson:endorsers:${t}`,S=await r.sadd(b,i)===1;await r.expire(b,365*86400);const d=await r.scard(b),p=($.review_level??"")==="senior"?"senior":m,k={...$,reviewed_by:i,review_level:p,endorsements:d,reviewed_at:new Date().toISOString()};await r.set(v,JSON.stringify(k));const x={reviewer:i,level:m,note:c.slice(0,280),ts:new Date().toISOString(),...e.verdacht.length?{verdacht:e.verdacht}:{}},A=`cachly:lesson:reviews:${t}`;await r.rpush(A,JSON.stringify(x)),await r.ltrim(A,-50,-1),await r.expire(A,365*86400),await de(r,l,{action:"team_confirm",actor:i,topic:t,level:p});const T=p==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",z=S?"":` (already endorsed by ${i} \u2014 no change to rank)`;return`${T} \u2014 \`${t}\` confirmed by **${i}**${g} (${d} distinct endorsement${d===1?"":"s"})${z}.
|
|
9
9
|
\u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.${c?`
|
|
10
10
|
\u{1F4DD} ${c.slice(0,200)}`:""}${ne(e,"notiz").map(R=>`
|
|
11
|
-
${R}`).join("")}`}case"team_recall":{const{instance_id:l,topic:
|
|
11
|
+
${R}`).join("")}`}case"team_recall":{const{instance_id:l,topic:t,author:i,limit:a=10}=w,o=await _(l),e=[],c=o.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((n,m)=>{c.on("data",g=>e.push(...g)),c.on("end",n),c.on("error",m)});let r=[];if(e.length>0){const n=await o.mget(...e);for(const m of n){const g=C(m??null,null);g&&r.push(g)}}if(t){const n=t.toLowerCase();r=r.filter(m=>m.topic.toLowerCase().includes(n)||(m.tags??[]).some(g=>g.toLowerCase().includes(n)))}if(i){const n=i.toLowerCase();r=r.filter(m=>m.author?.toLowerCase().includes(n))}const h=n=>n.reviewed_by?n.review_level==="senior"?2:1:0;if(r.sort((n,m)=>h(m)-h(n)||(m.recall_count??0)-(n.recall_count??0)),r=r.slice(0,a),r.length===0)return t?`\u{1F4ED} No team lessons found for \`${t}\`.
|
|
12
12
|
|
|
13
13
|
Shared instance: add lessons with \`learn_from_attempts\` and include an \`author\` field.`:`\u{1F4ED} No lessons in this brain yet.
|
|
14
14
|
|
|
15
|
-
All team members sharing this instance will see lessons here.`;const
|
|
16
|
-
`)}case"team_synthesize":{const{instance_id:l,topic:
|
|
15
|
+
All team members sharing this instance will see lessons here.`;const s=[`\u{1F465} **Team Brain** \u2014 ${r.length} lesson${r.length>1?"s":""}`,""];for(const n of r){const m=n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C",g=n.severity==="critical"?"\u{1F534} ":n.severity==="major"?"\u{1F7E1} ":"",v=n.reviewed_by?n.review_level==="senior"?" \u{1F6E1}\uFE0F":" \u2714\uFE0F":"",j=n.author?` \xB7 _by ${n.author}_`:"",$=n.reviewed_by?` \xB7 reviewed by ${n.reviewed_by}${(n.endorsements??0)>1?` +${(n.endorsements??0)-1}`:""}`:"",b=(n.recall_count??0)>0?` \xB7 recalled ${n.recall_count}\xD7`:"",S=Math.round((Date.now()-new Date(n.ts).getTime())/864e5),d=S===0?"today":S===1?"yesterday":`${S}d ago`;s.push(`${m} ${g}**\`${n.topic}\`**${v}${j}${$}${b} \xB7 ${d}`);const u=Me(n);u&&s.push(` ${u}`),s.push(` ${n.what_worked.slice(0,120)}`),s.push("")}return s.join(`
|
|
16
|
+
`)}case"team_synthesize":{const{instance_id:l,topic:t}=w,i=await _(l),a=`cachly:lessons:${t}`,o=await i.lrange(a,0,-1);if(o.length<2)return`\u{1F4ED} Need at least 2 entries for topic \`${t}\` to synthesize.
|
|
17
17
|
|
|
18
18
|
Currently: ${o.length} entr${o.length===1?"y":"ies"}.
|
|
19
19
|
|
|
20
|
-
Have team members store lessons via \`learn_from_attempts(topic="${
|
|
21
|
-
`)}case"memory_crystalize":{const{instance_id:l,label:
|
|
22
|
-
`)}case"team_crystallize":{const{instance_id:l,min_authors:
|
|
20
|
+
Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=o.map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null),c=e.filter(d=>d.outcome==="success"),r=e.filter(d=>d.outcome==="failure"),h=e.filter(d=>d.outcome==="partial"),s=[...new Set(e.map(d=>d.author).filter(Boolean))],n=s.length>1,m=c.sort((d,u)=>new Date(u.ts).getTime()-new Date(d.ts).getTime())[0],v=c.map(d=>d.what_worked).filter(d=>d&&d.length>10).sort((d,u)=>u.length-d.length)[0]??m?.what_worked??"",j=[...new Set([...r,...h].map(d=>d.what_failed).filter(d=>!!d&&d.length>5))],$=e.map(d=>d.severity).filter(Boolean),b=$.includes("critical")?"critical":$.includes("major")?"major":"minor";return[`\u{1F9EC} **Team Brain Synthesis: \`${t}\`**`,`_${e.length} entries from ${s.length} author${s.length===1?"":"s"}${n?` (${s.join(", ")})`:""} \xB7 ${c.length} success \xB7 ${r.length} failure \xB7 ${h.length} partial_`,"",'**Canonical "what worked":**',`> ${v}`,"",j.length>0?"**Avoid (combined failures):**":"",...j.map(d=>`> \u274C ${d}`),(j.length>0,""),"**Suggested canonical lesson:**","```","learn_from_attempts(",` topic = "${t}",`,' outcome = "success",',` what_worked = "${v.replace(/"/g,"'")}",`,j.length>0?` what_failed = "${j[0].replace(/"/g,"'")}",`:"",` severity = "${b}",`,")","```","",n?`\u{1F4A1} _${s.length} team members contributed to this synthesis. Store the canonical version to replace individual entries._`:"\u{1F4A1} _Single author \u2014 more value when multiple team members contribute to the same topic._"].filter(d=>d!==void 0).join(`
|
|
21
|
+
`)}case"memory_crystalize":{const{instance_id:l,label:t=""}=w,i=await _(l),a=new Date,o=`${a.getFullYear()}-W${String(Math.ceil((a.getDate()-a.getDay()+10)/7)).padStart(2,"0")}`,e=t||`${a.toISOString().slice(0,7)} Crystal`,c=await i.lrange("cachly:session:history",0,49),r=[],h=i.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((S,d)=>{h.on("data",u=>r.push(...u)),h.on("end",S),h.on("error",d)});const s=[];let n=0,m=0;if(r.length>0){const S=await i.mget(...r);for(const d of S){const u=C(d??null,null);if(!u)continue;const p=he(u);if(!p){n++;continue}p.geschwaerzt&&m++,s.push(p.lektion)}}const g=new Map;for(const S of s){const d=S.topic.split(":")[0]||"misc";g.has(d)||g.set(d,[]),g.get(d).push(S)}const v=[];for(const[S,d]of[...g.entries()].sort((u,p)=>p[1].length-u[1].length).slice(0,8)){const p=d.filter(k=>k.outcome==="success")[0]??d[0];p&&v.push({category:S,insight:p.what_worked.slice(0,120),count:d.length})}const j={label:e,ts:a.toISOString(),session_count:c.length,lesson_count:s.length,top_patterns:v,categories:[...g.keys()],created_from:`${c.length} sessions, ${s.length} lessons`,...n>0?{ausgelassen:n}:{}},$=JSON.stringify(j);return await i.set("cachly:crystal:latest",$),await i.expire("cachly:crystal:latest",90*86400),await i.set(`cachly:crystal:${o}`,$),await i.expire(`cachly:crystal:${o}`,365*86400),[`\u{1F48E} **Memory Crystal created: ${e}**`,"",`\u{1F4CA} Compressed: **${c.length} sessions** + **${s.length} lessons** \u2192 ${v.length} top patterns`,"","**Top patterns by category:**",...v.slice(0,6).map(S=>` \u2022 **${S.category}** (${S.count}\xD7): ${S.insight.slice(0,90)}`),"","\u{1F4A1} This crystal will appear in every future `session_start` briefing.","\u{1F4A1} Re-run `memory_crystalize` monthly to keep it fresh.",...n>0?["",`\u26A0 ${n} Lektion(en) nicht zusammengefasst: beim Speichern als verd\xE4chtig markiert oder heute vom Tuersteher als Anweisung/gef\xE4hrlicher Befehl erkannt. Pr\xFCfen oder neu speichern.`]:[],...m>0?[`\u{1F512} In ${m} Lektion(en) standen Geheimnisse \u2014 vor dem Zusammenfassen geschw\xE4rzt (die Lektionen selbst bleiben unver\xE4ndert).`]:[]].join(`
|
|
22
|
+
`)}case"team_crystallize":{const{instance_id:l,min_authors:t=2,label:i=""}=w,a=await _(l),o=new Date,e=Math.max(2,Number(t)||2),c=[],r=a.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((p,k)=>{r.on("data",x=>c.push(...x)),r.on("end",p),r.on("error",k)});const h=[];let s=0,n=0;if(c.length>0){const p=await a.mget(...c);for(const k of p){const x=C(k??null,null);if(!x||x.outcome!=="success"||!x.author)continue;const A=he(x);if(!A){s++;continue}A.geschwaerzt&&n++,h.push(A.lektion)}}const m=[...s>0?[`\u26A0 ${s} Lektion(en) nicht zusammengefasst: beim Speichern als verd\xE4chtig markiert oder heute vom Tuersteher als Anweisung/gef\xE4hrlicher Befehl erkannt. Pr\xFCfen oder neu speichern.`]:[],...n>0?[`\u{1F512} In ${n} Lektion(en) standen Geheimnisse \u2014 vor dem Zusammenfassen geschw\xE4rzt (die Lektionen selbst bleiben unver\xE4ndert).`]:[]],g=new Set(["the","and","for","with","from","that","this","fix","bug","error","issue","use","via","add","set","team"]),v=p=>{const[k,...x]=p.topic.split(":"),A=(p.tags??[]).map(R=>R.toLowerCase().trim()).filter(R=>R.length>3&&!g.has(R)).sort();return A.length>0?A[0]:x.join("-").toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/[\s-]+/).filter(R=>R.length>3&&!g.has(R)).sort((R,U)=>U.length-R.length||R.localeCompare(U))[0]??k},j=new Map;for(const p of h){const k=v(p);let x=j.get(k);x||(x={concept:k,authors:new Set,lessons:[],namespaces:new Set,bestFix:p},j.set(k,x)),x.authors.add(p.author.toLowerCase()),x.lessons.push(p),x.namespaces.add(p.topic.split(":")[0]||"misc");const A=T=>(T.endorsements??0)*10+(T.confirm_count??0)+(T.review_level==="senior"?5:0);A(p)>A(x.bestFix)&&(x.bestFix=p)}const b=[...j.values()].filter(p=>p.authors.size>=e).sort((p,k)=>k.authors.size-p.authors.size||k.lessons.length-p.lessons.length).slice(0,10).map(p=>({concept:p.concept,author_count:p.authors.size,authors:[...p.authors],lesson_count:p.lessons.length,spans:[...p.namespaces],convergent_fix:p.bestFix.what_worked.slice(0,200),fix_topic:p.bestFix.topic})),S=i||`${o.toISOString().slice(0,7)} Team Crystal`,d={label:S,ts:o.toISOString(),kind:"team",contributors:new Set(h.map(p=>p.author.toLowerCase())).size,analysed:h.length,patterns:b,...s>0?{ausgelassen:s}:{}};if(await a.set("cachly:crystal:team:latest",JSON.stringify(d)),await a.expire("cachly:crystal:team:latest",180*86400),b.length===0)return["\u{1F4A0} **Team Crystal \u2014 not enough cross-person convergence yet**","",`Analysed **${h.length}** attributed success lessons from **${d.contributors}** contributor${d.contributors!==1?"s":""}, but no concept had **${e}+ distinct authors** converge on it yet.`,"","This is the one thing a per-user memory can't build \u2014 it needs your team to accumulate shared, attributed lessons.",'Keep using `learn_from_attempts(author="...")` / `team_learn`; re-run as the team grows.',...m.length?["",...m]:[]].join(`
|
|
23
23
|
`);const u=[`\u{1F4A0} **Team Crystal created: ${S}**`,"",`\u{1F9EC} **${b.length} cross-person pattern${b.length!==1?"s":""}** \u2014 fixes that ${e}+ teammates independently converged on.`,`_Compressed from ${h.length} attributed lessons across ${d.contributors} contributors. This is the team-wide, causal layer a per-user "Dreaming" process structurally cannot produce._`,""];for(const p of b.slice(0,6)){const k=p.spans.length>1?` \xB7 spans ${p.spans.map(x=>`\`${x}\``).join(", ")}`:"";u.push(`### \u{1F9E9} \`${p.concept}\` \u2014 ${p.author_count} people converged${k}`,`**Convergent fix** (from \`${p.fix_topic}\`): ${p.convergent_fix}`,`**Who solved it together:** ${p.authors.map(x=>`@${x}`).join(", ")} _(ask them \u2014 they've each hit this)_`,"")}return u.push("---","\u{1F4A1} Surfaces in `crystal_view` and onboarding. Re-run `team_crystallize` monthly.",...m.length?["",...m]:[]),u.join(`
|
|
24
|
-
`)}case"brain_doctor":{const{instance_id:l,workspace_path:
|
|
25
|
-
`)}case"brain_hygiene":{const{instance_id:l,dry_run:
|
|
26
|
-
`)}case"recall_at":{const{instance_id:l,topic:
|
|
27
|
-
`)}case"trace_dependency":{const{instance_id:l,dependency:
|
|
24
|
+
`)}case"brain_doctor":{const{instance_id:l,workspace_path:t=""}=w,i=await _(l),a=[],o=[],e=[],c=i.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,y)=>{c.on("data",O=>e.push(...O)),c.on("end",f),c.on("error",y)});let r=0;const h=i.scanStream({match:"cachly:ctx:*",count:200});await new Promise((f,y)=>{h.on("data",O=>{r+=O.filter(N=>!N.endsWith(":meta")).length}),h.on("end",f),h.on("error",y)});const s=[];if(e.length>0){const f=await i.mget(...e);for(const y of f){const O=C(y??null,null);O&&s.push(O)}}const n=await i.get("cachly:session:last"),m=C(n,null),g=s.filter(f=>f.outcome==="failure"||f.outcome==="partial"),v=s.filter(f=>(f.recall_count??0)===0),j=s.filter(f=>f.severity==="critical"),$=s.filter(f=>f.outcome==="success"&&q(f)<te),b=s.filter(f=>f.outcome==="success"&&q(f)>=te&&q(f)<ke),S=s.filter(f=>(f.audit_trail??[]).length>1),d=s.filter(f=>f.author),u=new Set(s.map(f=>f.author).filter(Boolean)),p=s.reduce((f,y)=>f+(y.recall_count??0),0),k=s.length>0?Math.min(100,Math.round(p/s.length*10)):0,x=async f=>{let y=0;const O=i.scanStream({match:f,count:200});return await new Promise((N,F)=>{O.on("data",M=>{y+=M.length}),O.on("end",N),O.on("error",F)}),y},A=await x("cachly:lesson:vec:*"),T=await x("cachly:lesson:vecname:*"),z=await x("cachly:lesson:eing:*"),R=await x("cachly:lesson:pfad:*"),U=await x("cachly:lesson:vec2:*"),X=A>0?Math.round(U/A*100):0;A>0&&o.push(X>=80?`\u2705 **Second-model coverage: ${X}%** \u2014 ${U} of ${A} embedded lessons also carry the second-model vector; the second ranking feature is ON`:`\u{1F7E1} **Second-model coverage: ${X}%** \u2014 ${A-U} lessons still lack the second-model vector; the second ranking feature stays OFF below 80% and backfills three lessons per recall`);const H=await Promise.all([$e,ve,be].map(f=>i.smembers(f).then(y=>y.length).catch(()=>0)));H.some(f=>f>0)&&o.push(`\u{1F7E1} **Vector backfill pending:** ${H[0]} full-text, ${H[1]} topic-name, ${H[2]} second-model \u2014 retried on the next write or recall`);const Q=e.length>0?Math.round(A/e.length*100):100,ee=_e(e.length,A);e.length>0&&(ee==="aus"?(a.push(`semantic search is OFF: not a single lesson has an embedding (0 of ${e.length}). Recall falls back to keyword matching only. Fix: run the backfill (sdk/mcp/src/eingaenge-nachruesten.ts).`),o.push(`\u{1F534} **Semantic search: OFF** \u2014 0 of ${e.length} lessons have an embedding`)):ee==="luecke"?(a.push(`only ${Q}% of lessons have an embedding (${A} of ${e.length}) \u2014 the rest can never be found by meaning.`),o.push(`\u{1F7E1} **Semantic coverage: ${Q}%** \u2014 ${e.length-A} lessons without an embedding`)):(o.push(`\u2705 **Semantic coverage: ${Q}%** \u2014 ${A} full-text, ${T} topic-name, ${z} with error-text entries`+(R>0?`, ${R} with learned question paths`:"")),R===0&&e.length>=20&&o.push("\u{1F4A4} **No learned question paths yet** \u2014 a question that finds the same lesson twice becomes its own entry. Needs repeated real use.")));try{const f=await Oe(i);for(const y of f??[])o.push(`\u26A0\uFE0F **Write-path failure noted:** ${y.grund} \u2014 ${y.anzahl}\xD7 (last: ${y.zuletzt})`+(y.text?` \xB7 ${String(y.text).slice(0,140)}`:"")),a.push(`write-path failures recorded for "${y.grund}" (${y.anzahl}\xD7) \u2014 see check above for the reason.`)}catch{}let D=50;e.length>=5&&(D+=10),e.length>=20&&(D+=10),r>=3&&(D+=10),r>=10&&(D+=5),m&&(D+=10),g.length===0&&(D+=5);const re=s.length>0?v.length/s.length:0;re<.5&&(D+=10),$.length===0&&(D+=5),u.size>=2&&(D+=5),ee!=="gut"&&(D-=20),D=Math.max(0,Math.min(100,D));const pe=D>=80?"\u{1F7E2}":D>=50?"\u{1F7E1}":"\u{1F534}",me=k>=50?"\u{1F680}":k>=20?"\u{1F4C8}":"\u{1F4A4}";o.push(`${pe} **Brain Quality Score: ${D}/100**`),o.push(`${me} **Effective IQ Boost: ${k}%** (${p} recalls across ${s.length} lessons)`);try{const y=(await i.lrange("cachly:recall:spread",0,199)).map(O=>C(O,null)?.spread).filter(O=>typeof O=="number"&&Number.isFinite(O));if(y.length===0)o.push("\u{1F4CF} **Rank spread:** not measured yet \u2014 recorded from the next `smart_recall` on (score gap rank 1 \u2192 rank 5).");else{const O=y.reduce((M,J)=>M+J,0)/y.length,N=y.filter(M=>M<.05).length,F=`mean ${O.toFixed(3)} over ${y.length} recall${y.length===1?"":"s"} (${N} flat, < 0.05)`;y.length>=20&&O<.05?(o.push(`\u{1F7E1} **Rank spread: ${F}** \u2014 ranking has stopped separating hits; provisional threshold, see card 0u9s8qoopwhr`),a.push("Rank spread is flat: the top hits score alike. Check whether the store has grown past what the ranking separates (near-duplicates, one embedding for everything).")):o.push(`\u{1F4CF} **Rank spread:** ${F}`)}}catch{}o.push(`\u{1F4DA} **Lessons:** ${e.length} (${j.length} critical \xB7 ${S.length} with audit trail \xB7 ${d.length} from team)`),o.push(`\u{1F4BE} **Context entries:** ${r}`),o.push(`\u{1F3AF} **Confidence:** ${s.length-$.length-b.length} fresh \xB7 ${b.length} warn \xB7 ${$.length} stale`),o.push(`\u23F1\uFE0F **Decay config:** warn after ${ce}d \xB7 stale after ${le}d`),o.push(we(ge));try{const f=await i.info("memory");let y=null;try{const N=await i.config("GET","maxmemory-policy");y=Array.isArray(N)&&N.length>1?String(N[1]):null}catch{y=null}const O={benutzt:ie(f,"used_memory"),grenze:ie(f,"maxmemory"),richtlinie:y};for(const N of ye(O)){const M=`${N.art==="fehler"?"\u{1F534}":N.art==="hinweis"?"\u{1F7E1}":N.art==="ungemessen"?"\u26AA":"\u{1F7E2}"} **Speicher:** ${N.text}`;N.art==="fehler"||N.art==="ungemessen"?a.push(M):o.push(M)}}catch{a.push("\u26AA **Speicher:** Lage nicht abfragbar \u2014 unbekannt, ob dieser Speicher bei Platzmangel still loescht.")}u.size>=2&&o.push(`\u{1F465} **Team:** ${u.size} contributors (${[...u].join(", ")})`);try{const f=await i.get("cachly:index:last_run");if(f){const y=Math.round((Date.now()-new Date(f).getTime())/864e5);y>7?a.push(`\u{1F504} Index is ${y}d stale \u2014 run \`index_project\` to re-sync semantic search`):o.push(`\u{1F5C2}\uFE0F **Semantic index:** ${y}d old (fresh)`)}else a.push('\u{1F4A1} No semantic index \u2014 run `index_project(dir="<your-src>")` to enable semantic search')}catch{}try{const f=await i.get("cachly:crystal:latest");if(f){const y=JSON.parse(f),O=Math.round((Date.now()-new Date(y.ts).getTime())/864e5);o.push(`\u{1F48E} **Memory Crystal:** ${y.label} (${O}d ago)`),O>30&&a.push(`\u{1F4A1} Memory Crystal is ${O}d old \u2014 re-run \`memory_crystalize\` to compress new sessions`)}else e.length>=10&&a.push(`\u{1F4A1} ${e.length} lessons but no Memory Crystal \u2014 run \`memory_crystalize\` to compress wisdom`)}catch{}if(t)try{const f=t.replace(/\/$/,"")+"/package.json",y=fe(f,"utf-8"),O=JSON.parse(y),N={...O.dependencies,...O.devDependencies},F=["openai","@anthropic-ai/sdk","@google/generative-ai","mistralai","cohere-ai"].some(J=>J in N),M="@cachly-dev/openclaw"in N;F&&!M?(a.push(`\u{1F4A1} **openclaw missing:** you use LLM APIs (${Object.keys(N).filter(J=>["openai","@anthropic-ai/sdk"].includes(J)).join(", ")}) but not \`@cachly-dev/openclaw\``),a.push(" \u2192 `npm install @cachly-dev/openclaw` cuts LLM costs 60\u201390% with 3 lines of code")):M&&o.push("\u2705 **@cachly-dev/openclaw installed** (LLM cost caching active)")}catch{}if(m){const f=Math.round((Date.now()-new Date(m.ts).getTime())/6e4),y=f<60?`${f}m`:f<1440?`${Math.round(f/60)}h`:`${Math.round(f/1440)}d`;o.push(`\u{1F550} **Last session:** ${y} ago`)}else a.push("\u274C No session history \u2014 call `session_start` + `session_end` to start tracking");e.length===0?a.push("\u274C No lessons \u2014 call `learn_from_attempts` after solving bugs"):e.length<5&&a.push(`\u{1F4A1} Only ${e.length} lessons \u2014 add more after each problem solved`),k===0&&s.length>=5&&a.push("\u{1F4A4} **IQ Boost is 0%** \u2014 lessons exist but are never recalled. Use `recall_best_solution` BEFORE tasks."),r===0&&a.push("\u{1F4A1} No context \u2014 use `remember_context` to cache architecture docs, ADRs, etc."),g.length>0&&a.push(`\u26A0\uFE0F ${g.length} unresolved failure${g.length>1?"s":""}: ${g.slice(0,3).map(f=>`\`${f.topic}\``).join(", ")}`),$.length>0&&(a.push(`\u{1F534} ${$.length} STALE lesson${$.length>1?"s":""} (>${le}d, confidence <${te*100}%): ${$.slice(0,3).map(f=>`\`${f.topic}\``).join(", ")}`),a.push(" \u2192 Re-verify with `recall_best_solution` to reset confidence clock")),b.length>0&&a.push(`\u26A0\uFE0F ${b.length} lesson${b.length>1?"s":""} aging (>${ce}d): ${b.slice(0,3).map(f=>`\`${f.topic}\``).join(", ")}`),re>.7&&s.length>5&&a.push(`\u{1F4A1} ${v.length} lessons never recalled \u2014 verify topics match your workflow`);const P=["\u{1FA7A} **Brain Doctor**",`\`${"\u2500".repeat(48)}\``,"","**\u{1F4CA} Health Checks**",...o.map(f=>" "+f),""];return a.length>0?(P.push(`**\u{1F527} Action Items** (${a.length} issue${a.length>1?"s":""})`),a.forEach((f,y)=>P.push(` ${y+1}. ${f}`)),P.push(""),P.push("_Fix the action items above, then re-run `brain_doctor` to verify._")):(P.push("**\u2705 All checks passed** \u2014 Brain is healthy!"),P.push(""),P.push("_Keep the brain sharp: `session_start` \u2192 work \u2192 `learn_from_attempts` \u2192 `session_end`_")),P.join(`
|
|
25
|
+
`)}case"brain_hygiene":{const{instance_id:l,dry_run:t=!1,provisional_threshold:i=.5,archive_days:a=30}=w,o=await _(l),e=[],c=o.scanStream({match:"cachly:lesson:best:*",count:200});if(await new Promise((u,p)=>{c.on("data",k=>e.push(...k)),c.on("end",u),c.on("error",p)}),e.length===0)return"\u{1F9F9} **Brain Hygiene** \u2014 no lessons found. Nothing to sweep.";const r=await o.mget(...e),h=[];for(let u=0;u<e.length;u++){const p=r[u],k=C(p??null,null);k&&h.push({...k,_key:e[u]})}const s=Date.now(),n=[],m=[],g=[],v=new Map;for(const u of h){const p=u.state??"active";if(p==="archived")continue;const k=q(u),x=new Date(u.verified_at??u.ts).getTime(),A=(s-x)/864e5;if(k<=i){const T=u.recall_count??0;if(p==="provisional"&&T<2&&A>a){if(m.push(u.topic),!t){const R={...u,state:"archived",audit_trail:[...u.audit_trail??[],{ts:new Date().toISOString(),action:"archived",prev_state:"provisional"}]};v.set(u._key,R)}}else if(p==="active"&&(n.push(u.topic),!t)){const R={...u,state:"provisional",audit_trail:[...u.audit_trail??[],{ts:new Date().toISOString(),action:"flagged_provisional",prev_state:"active"}]};v.set(u._key,R)}}}for(const u of h){const p=u.state??"active";if(p==="archived"||v.has(u._key)&&v.get(u._key).state==="archived"||u.outcome!=="failure"||(u.recall_count??0)>0)continue;const x=new Date(u.verified_at??u.ts).getTime(),A=(s-x)/864e5;if(A<=a)continue;const T=n.indexOf(u.topic);if(T!==-1&&n.splice(T,1),g.push(`${u.topic} (failure, never recalled, ${Math.round(A)}d old)`),!t){const z=v.get(u._key)??u,R={...z,state:"archived",audit_trail:[...z.audit_trail??[],{ts:new Date().toISOString(),action:"orphan_failure_archived",prev_state:p}]};v.set(u._key,R)}}let j=0,$=0;const b=parseFloat(await o.get(`cachly:stats:time_saved_mins:${l}`)??"0")||0;for(const u of h){if(xe(u)){if((u.recall_count??0)>0){j++;const p=v.get(u._key)??u;v.set(u._key,{...p,recall_count:0})}continue}(u.recall_count??0)>0&&($+=Se(u))}if(t||await o.set(`cachly:stats:time_saved_mins:${l}`,String($)).catch(()=>{}),!t&&v.size>0){const u=o.pipeline();for(const[p,k]of v){const{_key:x,...A}=k;u.set(p,JSON.stringify(A))}await u.exec()}const d=[`${t?"\u{1F50D} **Brain Hygiene (dry run)**":"\u{1F9F9} **Brain Hygiene**"} \u2014 scanned **${h.length}** lessons`,"","| Action | Count |","|---|---|",`| Flagged provisional (confidence < ${i}) | ${n.length} |`,`| Archived (stale + low-recall + age > ${a}d) | ${m.length} |`,`| Contradictions auto-resolved | ${g.length} |`,`| Startvorrat entwertet (Z\xE4hler auf 0) | ${j} |`,""];return Math.round(b)!==Math.round($)&&d.push(`**\u23F1\uFE0F Zeitersparnis neu gerechnet:** ${ue(b)} \u2192 **${ue($)}**`,"_Nur eigene Lektionen, und jede genau einmal. Der mitgelieferte Startvorrat ist Allgemeinwissen, kein gelerntes; und wer dieselbe Lektion zum zweiten Mal liest, spart keine zweite Recherche._",""),n.length>0&&(d.push("**\u26A0\uFE0F Provisional (verify or re-learn):**"),n.slice(0,10).forEach(u=>d.push(` - \`${u}\``)),n.length>10&&d.push(` - _\u2026and ${n.length-10} more_`),d.push("")),m.length>0&&(d.push("**\u{1F4E6} Archived (excluded from recall):**"),m.slice(0,5).forEach(u=>d.push(` - \`${u}\``)),m.length>5&&d.push(` - _\u2026and ${m.length-5} more_`),d.push("")),g.length>0&&(d.push("**\u2694\uFE0F Contradictions resolved (failure archived, success kept):**"),g.slice(0,5).forEach(u=>d.push(` - ${u}`)),d.push("")),t?d.push("_Run `brain_hygiene(dry_run=false)` to apply these changes._"):n.length+m.length+g.length===0?d.push("\u2705 Brain is clean \u2014 no hygiene actions needed."):d.push("_Changes applied. Run `brain_doctor` to verify the updated health score._"),d.join(`
|
|
26
|
+
`)}case"recall_at":{const{instance_id:l,topic:t,date:i}=w,a=await _(l),o=new Date(i).getTime();if(isNaN(o))return`\u274C Invalid date "${i}". Use ISO format: "2026-01-15"`;const e=`cachly:lessons:${t}`,c=await a.lrange(e,0,-1);if(c.length===0)return`\u{1F4ED} No history found for \`${t}\`. Lessons are stored via \`learn_from_attempts\`.`;const r=c.map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null&&new Date(s.ts).getTime()<=o).sort((s,n)=>new Date(s.ts).getTime()-new Date(n.ts).getTime());if(r.length===0){const s=C(c[0]??null,null),n=s?.ts?new Date(s.ts).toLocaleDateString("de-DE"):"unknown";return`\u{1F4ED} No entries for \`${t}\` found before **${i}**. Earliest entry: ${n}.`}const h=[`\u{1F3FA} **Brain Archaeology: \`${t}\` before ${i}**`,`_${r.length} of ${c.length} total entries shown_`,""];for(const s of r.slice(-10)){const n=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=new Date(s.ts).toLocaleDateString("de-DE");h.push(`**${m}** ${n} ${s.outcome}`),s.what_worked&&h.push(` \u2192 ${s.what_worked.slice(0,100)}`),h.push("")}return h.push(`_Full evolution: ${c.map(s=>{try{const n=JSON.parse(s);return n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C"}catch{return"?"}}).join(" \u2192 ")}_`),h.join(`
|
|
27
|
+
`)}case"trace_dependency":{const{instance_id:l,dependency:t,mark_review:i=!1}=w,a=await _(l),o=`cachly:dep:${t}`,e=await a.get(o);if(!e)return`\u{1F4ED} No lessons found that depend on \`${t}\`.
|
|
28
28
|
|
|
29
|
-
Add dependencies via: \`learn_from_attempts(..., depends_on=["${
|
|
30
|
-
`)}case"global_learn":{const{instance_id:l,topic:
|
|
29
|
+
Add dependencies via: \`learn_from_attempts(..., depends_on=["${t}"])\``;const c=C(e,[]),r=[`\u{1F517} **Causal Chain: \`${t}\`** \u2014 ${c.length} dependent lesson${c.length===1?"":"s"}`,""];for(const h of c){const s=await a.get(`cachly:lesson:best:${h}`);if(!s){r.push(` \u2022 \`${h}\` _(lesson deleted)_`);continue}const n=C(s,null);if(!n){r.push(` \u2022 \`${h}\` _(lesson corrupted)_`);continue}const m=n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C",g=n.needs_review?" \u{1F50D} **needs_review**":"";if(r.push(` ${m} \`${h}\` (${n.severity??"major"})${g}`),i){const v={...n,needs_review:!0};await a.set(`cachly:lesson:best:${h}`,JSON.stringify(v))}}return i?r.push("",`\u{1F50D} All ${c.length} lessons marked as **needs_review** \u2014 verify they still work with the changed dependency.`):r.push("","_Run with `mark_review: true` to flag all dependent lessons for re-verification._"),r.join(`
|
|
30
|
+
`)}case"global_learn":{const{instance_id:l,topic:t,lesson:i,severity:a="minor",tags:o=[]}=w,e=se({topic:t,lesson:i,tags:o}),{topic:c,lesson:r}=e.felder,h=await _(l),s=`cachly:global:lesson:${c}`,n={topic:c,lesson:r,severity:a,tags:Te(e.felder.tags,e.verdacht),ts:new Date().toISOString(),scope:"global",recall_count:0},m=await h.get(s);if(m){const g=C(m,null);n.recall_count=g?.recall_count??0}return await h.set(s,JSON.stringify(n)),[`\u{1F310} **Global lesson stored**: \`${c}\`
|
|
31
31
|
|
|
32
32
|
${r}
|
|
33
33
|
|
|
34
34
|
Recallable from any project via \`global_recall(topic="${c}")\`.`,...ne(e)].join(`
|
|
35
|
-
`)}case"global_recall":{const{instance_id:l,topic:
|
|
35
|
+
`)}case"global_recall":{const{instance_id:l,topic:t}=w,i=await _(l),a=[],o=i.scanStream({match:"cachly:global:lesson:*",count:200});await new Promise((r,h)=>{o.on("data",s=>a.push(...s)),o.on("end",r),o.on("error",h)});let e=[];if(a.length>0){const r=await i.mget(...a);for(const h of r){const s=C(h??null,null);s&&e.push(s)}}if(t){const r=t.toLowerCase();e=e.filter(h=>h.topic.toLowerCase().includes(r))}if(e.length===0)return`\u{1F4ED} No global lessons${t?` for \`${t}\``:""}.
|
|
36
36
|
|
|
37
|
-
Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;for(const r of e){const h=`cachly:global:lesson:${r.topic}`,
|
|
38
|
-
`)}case"publish_lesson":{const{instance_id:l,topic:
|
|
39
|
-
`)}case"import_public_brain":{const{instance_id:l,framework:
|
|
37
|
+
Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;for(const r of e){const h=`cachly:global:lesson:${r.topic}`,s=await i.get(h);if(s){const n=C(s,null);if(!n)continue;n.recall_count=(n.recall_count??0)+1,n.last_recalled_at=new Date().toISOString(),await i.set(h,JSON.stringify(n))}}const c=[`\u{1F310} **Global Brain** \u2014 ${e.length} lesson${e.length>1?"s":""}`,""];for(const r of e){const h=r.severity==="critical"?"\u{1F534} ":r.severity==="major"?"\u{1F7E1} ":"";c.push(`${h}**\`${r.topic}\`**`),c.push(r.lesson.slice(0,200)),c.push("")}return c.join(`
|
|
38
|
+
`)}case"publish_lesson":{const{instance_id:l,topic:t,lesson:i,framework:a="general",severity:o="minor"}=w,e=De({topic:t,lesson:i,framework:a},"die oeffentliche Bibliothek");if(!e.ok)return e.meldung;const{topic:c,lesson:r,framework:h}=e.felder,s=await _(l),n=r.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,"[email]").replace(/\b(sk-|cky_live_|Bearer\s)[A-Za-z0-9_-]{8,}/g,"[token]").replace(/\/Users\/[^\s/]+/g,"/Users/[user]").replace(/\/home\/[^\s/]+/g,"/home/[user]"),m={topic:c,lesson:n,framework:h,severity:o,ts:new Date().toISOString(),published:!0,votes:0},g=`cachly:public:lesson:${h}:${c}`;return await s.set(g,JSON.stringify(m),"EX",365*86400),["\u{1F4E2} **Lesson published!**","",`**Topic:** \`${c}\``,`**Framework:** ${h}`,`**Content:** ${n.slice(0,200)}${n.length>200?"\u2026":""}`,"","This lesson is now available in the Public Brain for other developers.",`Import it anywhere: \`import_public_brain(framework="${h}")\``,...e.geschwaerzt.length?["",Ie(e.geschwaerzt)]:[]].join(`
|
|
39
|
+
`)}case"import_public_brain":{const{instance_id:l,framework:t,limit:i=20}=w,a=await _(l),o={nextjs:[{topic:"nextjs:image-layout",lesson:'Use fill + relative parent instead of layout="fill" (deprecated since Next.js 13)',severity:"major"},{topic:"nextjs:app-router-fetch",lesson:'fetch() in Server Components is cached by default \u2014 add {cache:"no-store"} for dynamic data',severity:"major"},{topic:"nextjs:metadata-export",lesson:"Export metadata const or generateMetadata() \u2014 never both in same file",severity:"minor"},{topic:"nextjs:client-boundary",lesson:'"use client" propagates down \u2014 keep it at the lowest component, not at page level',severity:"major"},{topic:"nextjs:env-prefix",lesson:"Only NEXT_PUBLIC_* env vars are exposed to client \u2014 others are server-only",severity:"critical"},{topic:"nextjs:revalidate",lesson:"export const revalidate = 0 disables caching for entire route; use revalidatePath() for on-demand",severity:"minor"}],fastapi:[{topic:"fastapi:async-db",lesson:"Use async session with asyncpg \u2014 sync SQLAlchemy blocks the event loop",severity:"critical"},{topic:"fastapi:pydantic-v2",lesson:"Pydantic v2: use model_validate() instead of parse_obj(), .dict() \u2192 .model_dump()",severity:"major"},{topic:"fastapi:lifespan",lesson:"Use lifespan context manager instead of deprecated on_event startup/shutdown",severity:"minor"},{topic:"fastapi:background-tasks",lesson:"BackgroundTasks run after response is sent \u2014 not in a separate thread pool",severity:"major"},{topic:"fastapi:cors-order",lesson:"CORSMiddleware must be added before other middleware to work correctly",severity:"critical"}],go:[{topic:"go:context-cancel",lesson:"Always call cancel() from context.WithCancel \u2014 leak goroutines if not cancelled",severity:"critical"},{topic:"go:defer-in-loop",lesson:"defer in a loop runs at function return, not loop iteration \u2014 use IIFE or explicit close",severity:"major"},{topic:"go:nil-interface",lesson:"nil interface != interface containing nil pointer \u2014 use explicit nil checks",severity:"major"},{topic:"go:goroutine-leak",lesson:"Goroutines with channel sends block forever if receiver is gone \u2014 use select with done chan",severity:"critical"},{topic:"go:embed-path",lesson:"//go:embed path must be relative and known at compile time \u2014 no os.Getenv",severity:"minor"}],docker:[{topic:"docker:layer-cache",lesson:"Copy package.json before source code \u2014 Docker caches layers, npm install only reruns on dep changes",severity:"major"},{topic:"docker:non-root",lesson:"Run as non-root user (USER 1001) \u2014 some k8s clusters reject root containers by policy",severity:"critical"},{topic:"docker:build-arg-secret",lesson:"Never use ARG for secrets \u2014 visible in image history. Use --secret mount instead",severity:"critical"},{topic:"docker:entrypoint-exec",lesson:'Use exec form ["cmd","arg"] not shell form "cmd arg" \u2014 shell form ignores SIGTERM',severity:"major"},{topic:"docker:multi-stage",lesson:"Multi-stage builds: copy only built artifacts to final stage \u2014 keep image small",severity:"minor"}],kubernetes:[{topic:"k8s:resource-limits",lesson:"Always set resource limits \u2014 unbounded pods cause node evictions and OOMKill",severity:"critical"},{topic:"k8s:liveness-vs-readiness",lesson:"Liveness failures restart pod; Readiness failures remove from LB. Use different endpoints",severity:"major"},{topic:"k8s:imagepullpolicy",lesson:"imagePullPolicy: Always in production \u2014 IfNotPresent can serve stale images",severity:"major"},{topic:"k8s:configmap-env",lesson:"ConfigMap changes don't restart pods \u2014 use rollout restart or mount as volume",severity:"critical"},{topic:"k8s:pdb",lesson:"Set PodDisruptionBudget for stateful apps \u2014 node drains kill all pods without it",severity:"major"}],react:[{topic:"react:useeffect-deps",lesson:"Omitting dependencies from useEffect deps array causes stale closure bugs \u2014 use exhaustive-deps ESLint rule",severity:"critical"},{topic:"react:key-index",lesson:"Never use array index as key in lists \u2014 causes subtle re-render bugs on reorder/delete",severity:"major"},{topic:"react:setState-in-render",lesson:"setState() during render causes infinite loop \u2014 move to useEffect or event handler",severity:"critical"},{topic:"react:memo-reference",lesson:"Object/array literals in JSX recreate on every render \u2014 useMemo for expensive derived values",severity:"minor"}],typescript:[{topic:"ts:type-guard",lesson:'Use "x is Type" return type for type guard functions \u2014 not "boolean"',severity:"minor"},{topic:"ts:strict-null",lesson:"Enable strictNullChecks in tsconfig \u2014 catches 90% of runtime null errors at compile time",severity:"critical"},{topic:"ts:enum-avoid",lesson:'Prefer union types ("a"|"b") over enum \u2014 enums have surprising runtime behavior',severity:"minor"},{topic:"ts:satisfies",lesson:'Use "satisfies" operator to validate type without widening \u2014 more precise than explicit annotation',severity:"minor"}],python:[{topic:"python:mutable-default",lesson:"Never use mutable default arguments (def f(x=[])) \u2014 shared across all calls. Use None + guard",severity:"critical"},{topic:"python:walrus-operator",lesson:":= (walrus) assigns and returns \u2014 useful in while/comprehensions but hard to read in complex expr",severity:"minor"},{topic:"python:asyncio-run",lesson:"asyncio.run() creates new event loop \u2014 calling it inside an existing loop raises RuntimeError",severity:"major"},{topic:"python:typing-optional",lesson:"Optional[X] == Union[X, None] \u2014 in Python 3.10+ use X | None syntax",severity:"minor"}]},e=t.toLowerCase(),c=o[e];if(!c){const n=Object.keys(o).join(", ");return`\u274C No public brain available for \`${t}\`.
|
|
40
40
|
|
|
41
41
|
Available: ${n}
|
|
42
42
|
|
|
43
|
-
Or publish your own: \`publish_lesson(framework="${
|
|
44
|
-
`)}case"setup_ai_memory":{const{instance_id:l,project_dir:
|
|
45
|
-
`)}case"team_assign_role":{const{instance_id:l,handle:
|
|
46
|
-
`)}const h=c[
|
|
47
|
-
`)}case"team_whoami":{const{instance_id:l,handle:
|
|
48
|
-
\`team_assign_role(handle="${
|
|
49
|
-
`)}return[`## ${K[a]} ${
|
|
43
|
+
Or publish your own: \`publish_lesson(framework="${t}", ...)\``}const r=c.slice(0,i);let h=0;for(const n of r){const m=`cachly:lesson:best:${n.topic}`;await a.get(m)||(await a.set(m,JSON.stringify({...n,what_worked:n.lesson,outcome:"success",ts:new Date().toISOString(),recall_count:0,source:"public_brain",version:2})),h++)}return[`\u{1F4E5} **Public Brain imported: ${t}**`,"",`${h} new lessons added (${r.length-h} already existed)`,"","**Imported topics:**",...r.map(n=>` ${n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":"\u{1F4A1}"} \`${n.topic}\``),"","These lessons will now appear in `session_start` when relevant.",`Recall any time: \`recall_best_solution(topic="${e}:...")\``].join(`
|
|
44
|
+
`)}case"setup_ai_memory":{const{instance_id:l,project_dir:t,embed_provider:i="openai",project_description:a="a software project"}=w,o=await E(`/api/v1/instances/${l}`),e={openai:{key:"OPENAI_API_KEY",hint:"Get at: https://platform.openai.com/api-keys"},mistral:{key:"MISTRAL_API_KEY",hint:"Get at: https://console.mistral.ai/api-keys"},cohere:{key:"COHERE_API_KEY",hint:"Get at: https://dashboard.cohere.com/api-keys"},ollama:{key:"OLLAMA_BASE_URL",hint:"Run: brew install ollama && ollama serve (free, local, no key needed)"},gemini:{key:"GEMINI_API_KEY",hint:"Get at: https://aistudio.google.com/app/apikey"}},c=e[i]??e.openai,r=!!o.vector_token,h=JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"your-api-token-from-cachly.dev/settings",[c.key]:i==="ollama"?"http://localhost:11434":"your-key-here",...i!=="openai"?{CACHLY_EMBED_PROVIDER:i}:{}}}}},null,2),s=o.tier.toUpperCase(),n=je(l),m=["\u{1F9E0} **cachly AI Memory Setup Complete**","",`**Project:** ${a}`,`**Instance:** ${o.name} (${s}) \xB7 ID: \`${l}\``,`**Embedding Provider:** ${i}`,`**Semantic Search:** ${r?"\u2705 pgvector HNSW available":"\u26A0\uFE0F needs a vector token \u2014 rotate it in the dashboard (every tier includes one)"}`,"","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**Step 1 \u2014 Add to .mcp.json:**","```json",h,"```","",`**Step 2 \u2014 Set your ${i} key:**`,"```bash",`export ${c.key}="your-key-here"`,"```",`_(${c.hint})_`,"","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**Step 3 \u2014 Brain rules (Layer 3 Autopilot):**","",...t?[`\u{1F50D} Detecting IDEs in \`${t}\`\u2026`]:["Copy this to `.github/copilot-instructions.md` (Copilot), `CLAUDE.md` (Claude Code), or `.cursor/rules` (Cursor) in your project:"],"","```markdown",n,"```","","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**How the 3 layers work together:**"," Layer 1 \u2192 Your Valkey instance stores all lessons + context (persists forever)"," Layer 2 \u2192 MCP tools (learn_from_attempts, recall_best_solution, smart_recall) read/write it"," Layer 3 \u2192 copilot-instructions.md makes your AI run them automatically","","Result: Your AI never solves the same problem twice. \u{1F680}"];if(t){const{access:g}=await import("node:fs/promises"),{constants:v}=await import("node:fs"),j=async S=>g(S,v.F_OK).then(()=>!0).catch(()=>!1),$=[{ide:"GitHub Copilot",path:I(t,".github","copilot-instructions.md")}];(await j(I(t,"CLAUDE.md"))||await j(I(t,".claude")))&&$.push({ide:"Claude Code",path:I(t,"CLAUDE.md")}),(await j(I(t,".cursor"))||await j(I(t,".cursorrules")))&&$.push({ide:"Cursor",path:I(t,".cursor","rules","cachly.mdc"),prefix:Le}),(await j(I(t,".windsurfrules"))||await j(I(t,".windsurf")))&&$.push({ide:"Windsurf",path:I(t,".windsurfrules")});const b=[];for(const S of $){const d=await Ae(S.path,n,S.prefix),u=d==="written"?"written":d==="updated"?"cachly block updated, rest of the file unchanged":"cachly block appended, your text kept";b.push(`\u2705 [${S.ide}] \u2192 \`${S.path.replace(t,".")}\` (${u})`)}b.push("\u2139\uFE0F Hooks (session briefing, per-prompt recall) are set up by `npx @cachly-dev/mcp-server@latest init` or `autopilot`."),m.push(...b)}return m.join(`
|
|
45
|
+
`)}case"team_assign_role":{const{instance_id:l,handle:t,role:i,assigned_by:a=""}=w;if(!l||!t||!i)return"\u274C Required: instance_id, handle, role";const o=["admin","reviewer","contributor","viewer"].includes(i)?i:null;if(!o)return`\u274C Unknown role \`${i}\`. Valid: admin \xB7 reviewer \xB7 contributor \xB7 viewer`;const e=await _(l),c=await e.hgetall(B(l)).catch(()=>({})),r=Object.values(c).includes("admin");if(r){const m=a?await G(e,l,a):null;if(!Z(m,"admin"))return["\u274C **Permission denied** \u2014 only an `admin` can assign roles.","","Ask an existing admin to run:",`\`team_assign_role(instance_id="${l}", handle="${t}", role="${i}", assigned_by="<their-handle>")\``].join(`
|
|
46
|
+
`)}const h=c[t.toLowerCase()]??null;await e.hset(B(l),t.toLowerCase(),o),await e.expire(B(l),365*2*86400),await de(e,l,{action:"team_assign_role",actor:a||"(bootstrap)",handle:t.toLowerCase(),from:h,to:o});const s=!r;return[`${K[o]} **Role assigned** \u2014 **${t}** is now a \`${o}\``,"",`**Capabilities:** ${oe[o]}`,"",s?"_First admin bootstrapped \u2014 governance is now active on this brain._":`_Assigned by ${a||"(bootstrap)"}_`,"","Run `team_roster` to see all current roles."].join(`
|
|
47
|
+
`)}case"team_whoami":{const{instance_id:l,handle:t}=w;if(!l||!t)return"\u274C Required: instance_id, handle";const i=await _(l),a=await G(i,l,t);if(!a){const e=await i.hgetall(B(l)).catch(()=>({})),c=Object.values(e).includes("admin");return[`\u{1F441}\uFE0F **${t}** has no assigned role on this brain.`,"",c?`Ask an admin to run \`team_assign_role(handle="${t}", role="contributor")\` to add you.`:`This brain has no roles set up yet. Establish governance:
|
|
48
|
+
\`team_assign_role(handle="${t}", role="admin")\``].join(`
|
|
49
|
+
`)}return[`## ${K[a]} ${t} \u2014 \`${a}\``,"",`**You can:** ${oe[a]}`,"","Run `team_roster` to see all team members and their roles."].join(`
|
|
50
50
|
`)}case"team_roster":{const{instance_id:l}=w;if(!l)return"\u274C Required: instance_id";const i=await(await _(l)).hgetall(B(l)).catch(()=>({}));if(Object.keys(i).length===0)return["## \u{1F465} Team Roster","","No roles assigned yet. Establish governance with:",`\`team_assign_role(instance_id="${l}", handle="<your-handle>", role="admin")\``].join(`
|
|
51
51
|
`);const a=Object.entries(i).map(([e,c])=>({handle:e,role:c})).sort((e,c)=>(Y[c.role]??0)-(Y[e.role]??0)||e.handle.localeCompare(c.handle)),o=[`## \u{1F465} Team Roster (${a.length} member${a.length!==1?"s":""})`,"","| Role | Handle | Capabilities |","|---|---|---|"];for(const e of a){const c=K[e.role]??"?";o.push(`| ${c} ${e.role} | **${e.handle}** | ${oe[e.role].split(" \xB7 ").slice(0,2).join(", ")} |`)}return o.push("","_Manage with `team_assign_role`. Any admin can add or change roles._"),o.join(`
|
|
52
|
-
`)}case"team_audit":{const{instance_id:l,requester:
|
|
53
|
-
`);const r=c.map(
|
|
54
|
-
`)}case"team_grant_scope":{const{instance_id:l,handle:
|
|
55
|
-
`))}case"team_scopes":{const{instance_id:l,handle:
|
|
52
|
+
`)}case"team_audit":{const{instance_id:l,requester:t="",limit:i=50}=w;if(!l)return"\u274C Required: instance_id";const a=await _(l),o=await ae(a,l,t,"admin","view the governance audit log");if(o)return o;const e=Math.min(Math.max(1,Number(i)||50),200),c=await a.lrange(`cachly:team:audit:${l}`,-e,-1).catch(()=>[]);if(c.length===0)return["## \u{1F4DC} Governance Audit Log","","No governance events recorded yet.","Events are logged automatically on `team_assign_role` and `team_confirm`."].join(`
|
|
53
|
+
`);const r=c.map(s=>C(s,null)).filter(s=>s!==null).reverse(),h=s=>{const n=s.ts?new Date(s.ts).toISOString().replace("T"," ").slice(0,16):"?";return s.action==="team_assign_role"?`| ${n} | \u{1F451} role | **${s.actor}** set \`${s.handle}\`: ${s.from??"\u2014"} \u2192 **${s.to}** |`:s.action==="team_confirm"?`| ${n} | \u2705 confirm | **${s.actor}** confirmed \`${s.topic}\` (${s.level}) |`:`| ${n} | ${s.action??"?"} | ${s.actor??"?"} |`};return[`## \u{1F4DC} Governance Audit Log (${r.length} event${r.length!==1?"s":""})`,"","| When (UTC) | Type | Detail |","|---|---|---|",...r.map(h),"",`_Immutable trail \xB7 2-year retention \xB7 last ${e} events. Admin-only._`].join(`
|
|
54
|
+
`)}case"team_grant_scope":{const{instance_id:l,handle:t,group:i,action:a="add",assigned_by:o=""}=w;if(!l||!t||!i)return"\u274C Required: instance_id, handle, group";const e=String(i).toLowerCase().trim();if(!e)return'\u274C `group` must be a non-empty name (e.g. "backend", "security")';const c=await _(l),r=await c.hgetall(B(l)).catch(()=>({}));if(Object.values(r).includes("admin")){const s=o?await G(c,l,o):null;if(!Z(s,"admin"))return"\u274C **Permission denied** \u2014 only an `admin` can manage group scopes. Ask an admin to set `assigned_by`."}return a==="remove"?(await c.srem(W(l,e),t.toLowerCase()),`\u{1F513} **${t}** removed from group \`${e}\`.`):(await c.sadd(V(l),e),await c.sadd(W(l,e),t.toLowerCase()),await c.expire(V(l),365*2*86400),await c.expire(W(l,e),365*2*86400),[`\u{1F510} **Scope granted** \u2014 **${t}** is now in group \`${e}\`.`,"",`Lessons stored with \`group="${e}"\` will surface in recall for ${t} (and other \`${e}\` members + admins) only.`,"",`Store a scoped lesson: \`learn_from_attempts(topic="...", group="${e}", ...)\``].join(`
|
|
55
|
+
`))}case"team_scopes":{const{instance_id:l,handle:t}=w;if(!l)return"\u274C Required: instance_id";const i=await _(l);if(t){const e=await Ge(i,l,t);return e.size===0?`\u{1F441}\uFE0F **${t}** is in no groups \u2014 sees only team-wide + public lessons.`:`\u{1F510} **${t}** belongs to: ${[...e].map(c=>`\`${c}\``).join(", ")}`}const a=await i.smembers(V(l)).catch(()=>[]);if(a.length===0)return["## \u{1F510} Team Scopes","","No groups defined yet. Create one by adding a member:",`\`team_grant_scope(instance_id="${l}", handle="alice", group="backend")\``].join(`
|
|
56
56
|
`);const o=[`## \u{1F510} Team Scopes (${a.length} group${a.length!==1?"s":""})`,""];for(const e of a.sort()){const c=await i.smembers(W(l,e)).catch(()=>[]);o.push(`- **\`${e}\`** (${c.length}): ${c.length?c.map(r=>`**${r}**`).join(", "):"_empty_"}`)}return o.push("",'_Scope a lesson to a group with `learn_from_attempts(group="...")`. Members + admins see it; others don\'t._'),o.join(`
|
|
57
57
|
`)}default:return null}}export{V as GROUPS_INDEX_KEY,W as GROUP_KEY,Fe as PROPOSED_LESSON_PREFIX,Be as REVIEW_MODE_KEY,B as ROLES_KEY,K as ROLE_BADGE,it as TEAM_TOOL_NAMES,de as auditLog,G as getRole,Ge as getScopes,lt as handleTeamTool,Z as hasPermission,ct as lessonVisibleToScope,Pe as rbacActive,ae as requireRole,Ke as reviewModeEnabled,ze as roleToReviewLevel,Je as storeLessonProposal};
|
package/dist/src/tools.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=[{name:"list_instances",description:"List all your cachly cache instances with their status and connection details. Read-only. Returns an array of instance objects \u2014 each with id, name, tier, status, region, RAM, and redis:// connection string. Returns an empty array if no instances exist. No pagination: all instances are returned in one call (typical accounts have < 20). Use this first to discover instance UUIDs required by get_instance, cache_get, cache_set, and all other cache tools. Use get_instance to retrieve full metadata for a single instance.",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_instance",description:"Create a new managed Valkey/Redis cache instance on cachly.dev. Free tier provisions in ~30 seconds. Paid tiers return a Stripe checkout URL. Available tiers: free (25 MB), dev (200 MB, \u20AC19/mo), pro (900 MB, \u20AC49/mo), speed (900 MB Dragonfly + Semantic Cache, \u20AC79/mo), business (7 GB, \u20AC199/mo).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Unique name for the instance (min 3 chars)"},tier:{type:"string",enum:["free","dev","pro","speed","business"],description:'Pricing tier. Start with "free" for testing.'}},required:["name","tier"]}},{name:"get_instance",description:"Get full metadata for a specific cache instance: name, tier, status (provisioning / running / paused), region, RAM limit, Redis connection string, created_at, and expiry. Read-only. Returns an error if the instance_id is not found or belongs to another account. Call list_instances first to discover valid UUIDs. Use get_connection_string instead if you only need the redis:// URL for your app config.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance (from list_instances)"}},required:[]}},{name:"get_connection_string",description:"Get the Redis/Valkey connection string (redis:// URL) for a running instance. Use this to configure your application or set environment variables.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance."}},required:[]}},{name:"delete_instance",description:"Permanently delete a cache instance. Deprovisions the Kubernetes workload and removes all data. This action is irreversible.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance to delete"},confirm:{type:"boolean",description:"Must be true to confirm deletion"}},required:["confirm"]}},{name:"cache_get",description:"Get a value from a running cache instance by key. Returns the stored value (string or deserialized JSON object) or null if the key does not exist or has expired. Read-only \u2014 no side effects. Use cache_mget when you need multiple keys in one round-trip. Use cache_exists to check existence without retrieving the value. Use semantic_search when you need fuzzy/vector search across stored values.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance."},key:{type:"string",description:"Cache key to retrieve"},org_id:{type:"string",description:"Optional org ID \u2014 if the direct key misses, falls back to the shared org namespace org:{org_id}:sem:{key}"}},required:["key"]}},{name:"cache_set",description:'Set a key-value pair in a running cache instance. Overwrites any existing value at the key \u2014 not idempotent for new data. Returns "OK" on success; returns an error if the instance_id is invalid or the instance is paused. Value can be a string or a JSON-serialized object. Optionally set a TTL in seconds (omit for no expiry). Use cache_mset instead for setting multiple keys in a single pipeline round-trip. Use cache_stream_set instead for caching LLM token streams (ordered string chunks).',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},key:{type:"string",description:"Cache key"},value:{type:"string",description:"Value to store (string or JSON)"},ttl:{type:"number",description:"Time-to-live in seconds (optional, omit for no expiry)"},org_id:{type:"string",description:"Optional org ID \u2014 also writes the key to the shared org namespace org:{org_id}:sem:{key} with the same TTL"}},required:["key","value"]}},{name:"cache_delete",description:"Permanently delete one or more keys from a running cache instance (uses Redis DEL). This operation is destructive and irreversible \u2014 deleted keys cannot be recovered. Deleting a non-existent key is safe and returns 0 for that key (no error). Returns the count of keys that were actually deleted (existing keys only). Use this to explicitly remove stale entries; prefer cache_set with a short TTL for auto-expiring data. Do NOT use this to clear an entire instance \u2014 use the dashboard or delete_instance for that.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to delete keys from (get from list_instances)"},keys:{type:"array",items:{type:"string"},description:"One or more cache keys to delete. Accepts exact keys only (no glob patterns \u2014 use cache_keys to list first)."}},required:["keys"]}},{name:"cache_exists",description:"Check whether one or more keys exist in a running cache instance (uses Redis EXISTS). Read-only \u2014 no side effects. Returns the count of keys that currently exist (integer 0 to N). If none of the keys exist, returns 0. If all exist, returns the total key count passed in. Duplicate keys in the input array are each counted separately (Redis behavior). Use this to check presence before a cache_get to avoid null handling, or to verify a cache warm-up completed. Use cache_get instead if you also need the value; use cache_ttl if you need expiry info.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to check (get from list_instances)"},keys:{type:"array",items:{type:"string"},description:"Keys to check for existence. Accepts exact keys only (no glob patterns)."}},required:["keys"]}},{name:"cache_ttl",description:"Get the remaining time-to-live (TTL) of a key in seconds. Returns -1 if the key exists but has no expiry, -2 if the key does not exist. Read-only \u2014 no side effects. Use cache_set with a ttl parameter to set or update the expiry.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},key:{type:"string",description:"Cache key to inspect"}},required:["key"]}},{name:"cache_keys",description:'List keys in a cache instance matching an optional glob pattern (e.g. "user:*", "session:*"). Uses SCAN to avoid blocking the server. Returns at most `count` keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string"},pattern:{type:"string",description:"Glob pattern (default: *)"},count:{type:"number",description:"Max keys to return (default: 50, max: 500)"}},required:[]}},{name:"cache_stats",description:"Get real-time stats for a cache instance: memory usage, hit/miss rate, commands/sec, connected clients, keyspace info, and uptime. Read-only \u2014 no side effects. The instance_id identifies the target instance (obtain from list_instances). Use this for monitoring, capacity planning, or debugging performance issues \u2014 not for reading cached values (use cache_get for that). Use cache_exists or cache_ttl if you only need key-level information.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"}},required:[]}},{name:"semantic_search",description:'Find cached entries that are semantically similar to a natural-language query. Read-only \u2014 no side effects. Returns an array of objects, each with: key, value, similarity_score (0\u20131), and namespace. Returns an empty array if no entries meet the similarity threshold. Requires OPENAI_API_KEY (or compatible provider) and the Speed/Business tier with CACHLY_VECTOR_URL. Embeddings are computed server-side and never leave Germany (pgvector HNSW index). Example: "find all cached responses about password reset" or "what did we answer about pricing?". Use cache_get for exact key lookup; use smart_recall for brain lessons.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},query:{type:"string",description:"Natural-language query to find similar cached content"},threshold:{type:"number",description:"Minimum cosine similarity 0\u20131 (default: 0.82). Lower = broader matches."},namespace:{type:"string",description:"Semantic namespace to search in (default: cachly:sem)"},top_k:{type:"number",description:"Maximum number of results to return (default: 5)"},use_hybrid:{type:"boolean",description:"Enable Hybrid BM25+Vector RRF fusion search. Passes `hybrid: true` and the query text to the pgvector API for higher precision on named entities. Default: false."},auto_namespace:{type:"boolean",description:"Auto-detect the namespace from the query text using text heuristics instead of using the `namespace` parameter. Returns results only from the matching domain (code/translation/summary/qa/creative)."}},required:["query"]}},{name:"detect_namespace",description:"Classify a prompt into one of 5 semantic namespaces using text heuristics. Overhead: <0.1 ms, no embedding required. Useful to understand which namespace cachly will use for a given prompt. Returns one of: cachly:sem:code, cachly:sem:translation, cachly:sem:summary, cachly:sem:qa, cachly:sem:creative.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The text prompt to classify into a semantic namespace"}},required:["prompt"]}},{name:"cache_warmup",description:"Pre-warm the semantic cache with a list of prompt/value pairs. For each entry: computes an embedding, checks if a similar entry already exists (similarity \u2265 0.98), and writes new entries to Valkey + pgvector index. Use this to seed FAQ responses, product descriptions, or known-good LLM answers before the first real user traffic. Requires OPENAI_API_KEY.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},entries:{type:"array",description:"List of prompt/value pairs to pre-warm into the cache",items:{type:"object",properties:{prompt:{type:"string",description:"The query or question to cache"},value:{type:"string",description:"The answer or response to store for this prompt"},namespace:{type:"string",description:"Optional per-entry namespace override"}},required:["prompt","value"]}},namespace:{type:"string",description:"Default namespace for all entries (default: cachly:sem)"},ttl:{type:"number",description:"Time-to-live in seconds for warmed entries (omit for no expiry)"},auto_namespace:{type:"boolean",description:"Auto-detect the namespace per prompt using text heuristics. Overrides `namespace` when no per-entry namespace is set."}},required:["entries"]}},{name:"index_project",description:"Index local source files into the cachly semantic cache so AI assistants can use semantic_search to find relevant files instead of re-reading the whole codebase every time. Walks a directory recursively, reads each matching file, and stores a summary + path as a semantic cache entry (prompt = file path + content excerpt, value = relative path). Requires an embedding provider (OPENAI_API_KEY or CACHLY_EMBED_PROVIDER + key). Run once, then re-run after major refactors. TTL=86400 (24h) keeps entries fresh.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cachly instance"},dir:{type:"string",description:"Absolute path to the directory to index (e.g. /Users/you/myproject/src)"},extensions:{type:"array",items:{type:"string"},description:'File extensions to include (default: ["ts","js","go","py","java","rs","md","kt","swift"])'},max_files:{type:"number",description:"Maximum number of files to index (default: 100)"},ttl:{type:"number",description:"TTL in seconds for indexed entries (default: 86400 = 24 h)"},summary_chars:{type:"number",description:"Characters to use as summary per file (default: 1200)"},namespace:{type:"string",description:"Semantic namespace to store under (default: cachly:sem:code)"}},required:["dir"]}},{name:"cache_mset",description:"Set multiple key-value pairs in a single pipeline round-trip. Supports per-key TTL \u2013 unlike native MSET. Uses one TCP round-trip for N keys via Redis pipeline. Each item overwrites any existing value for that key. On partial failure the successfully pipelined keys are committed; a per-key error list is returned for any that failed. Returns a summary: { set: N, errors: [...] }. Use cache_set for a single key; use cache_stream_set for large streaming payloads.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},items:{type:"array",description:"Key-value pairs to set",items:{type:"object",properties:{key:{type:"string",description:"Cache key"},value:{description:"Value to store (JSON-serialised)"},ttl:{type:"number",description:"Per-key TTL in seconds (optional)"}},required:["key","value"]}}},required:["items"]}},{name:"cache_mget",description:"Retrieve multiple keys in one round-trip using native Redis MGET. Returns values in the same order as the keys array; missing keys are null.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},keys:{type:"array",items:{type:"string"},description:"List of keys to fetch"}},required:["keys"]}},{name:"cache_lock_acquire",description:"Acquire a distributed lock using Redis SET NX PX (Redlock-lite). Returns a fencing token on success. The lock auto-expires after ttl_ms to prevent deadlocks. Use cache_lock_release to free the lock early.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Lock resource identifier"},ttl_ms:{type:"number",description:"Safety TTL in milliseconds (e.g. 5000)"},retries:{type:"number",description:"Max acquire attempts (default: 3)"},retry_delay_ms:{type:"number",description:"Milliseconds between retries (default: 50)"}},required:["key","ttl_ms"]}},{name:"cache_lock_release",description:"Release a previously acquired distributed lock. Uses a Lua script for atomic release \u2013 only deletes the key if the fencing token matches.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Lock resource identifier (same as in cache_lock_acquire)"},token:{type:"string",description:"Fencing token returned by cache_lock_acquire"}},required:["key","token"]}},{name:"get_api_status",description:"Full diagnostic for your cachly Brain \u2014 call this FIRST whenever anything is not working. Returns: API reachability, JWT validity + expiry, your user ID, all Brain instances with live status (\u{1F7E2} running / \u{1F7E1} provisioning / \u{1F534} stopped), Redis ping on the active connection, and actionable fix steps for every issue found. Workflow: run get_api_status \u2192 read the issue it flags \u2192 fix it \u2192 retry your tool.",inputSchema:{type:"object",properties:{},required:[]}},{name:"remember_context",description:'Save context information to the cache so you can recall it later without re-computing. Perfect for caching: codebase overviews, file summaries, project structure, frequently-accessed data, or "thinking" results like dependency analysis. The AI assistant can use this to avoid re-reading the entire codebase every time. Overwrites any existing value stored under the same key. Returns { key, stored_at, ttl } confirming the saved context. Example: remember_context("project overview", "This is a Next.js app with...") then later: recall_context("project overview"). Use recall_context to retrieve; use list_remembered to see all stored keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:'Descriptive key like "project_overview", "auth_architecture", "file:src/index.ts"'},content:{type:"string",description:"The context/summary/analysis to remember"},category:{type:"string",enum:["overview","architecture","file_summary","dependency","thinking","custom"],description:"Category for organization (default: custom)"},ttl:{type:"number",description:"Time-to-live in seconds (default: 86400 = 24h, use 0 for no expiry)"}},required:["key","content"]}},{name:"recall_context",description:'Retrieve previously saved context from the cache. Returns the saved content or null if not found. Use this at the START of any task to check if you already have relevant context cached, before doing expensive operations like reading many files. Supports glob patterns: "file:*" matches all file summaries, "arch*" matches architecture-related keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:'The key to look up (supports glob pattern like "file:*")'}},required:["key"]}},{name:"list_remembered",description:"List all cached context entries for this project. Shows what knowledge the AI assistant has already cached, so you can decide whether to recall existing context or refresh it. Returns: key, category, size, TTL remaining, and a content preview.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},category:{type:"string",enum:["overview","architecture","file_summary","dependency","thinking","custom","all"],description:"Filter by category (default: all)"},limit:{type:"number",description:"Max entries to return (default: 50)"}},required:[]}},{name:"forget_context",description:'Delete one or more cached context entries. Use when context is stale or you want to force a fresh analysis. Supports glob patterns: "file:*" deletes all file summaries.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},keys:{type:"array",items:{type:"string"},description:"Keys to delete (supports glob)"}},required:["keys"]}},{name:"learn_from_attempts",description:'Store a lesson AFTER any non-trivial task (deploy, debug, fix, decision); future sessions recall it. instance_id may be omitted; the configured instance is used \u2014 never guess one. If the topic already exists, the write is an UPDATE and REQUIRES `grund` (one line: WHY the previous version was wrong) \u2014 without it the update is rejected. A conflicting outcome triggers a contradiction warning. Example: learn_from_attempts(topic="deploy:api", outcome="success", what_worked="PORT 3095 SERVES WHISPER \u2014 nohup docker compose up -d", severity="critical")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Short slug, e.g. "deploy:web", "debug:redis-tls", "fix:generate-series"'},outcome:{type:"string",enum:["success","failure","partial"],description:"Did it work?"},what_worked:{type:"string",description:"What solved it. LEAD WITH THE DECISIVE FACT (the number, address, command) in the first 100 characters \u2014 briefings truncate there."},what_failed:{type:"string",description:"What did NOT work (optional but valuable)"},context:{type:"string",description:'The SYMPTOM in the words someone would search for, before they knew the fix ("deploy stuck, rollout not finishing"). Plus error messages and root cause. Optional but high-value: it is what closes the gap between the question and the answer.'},severity:{type:"string",enum:["critical","major","minor"],description:"Impact severity: critical (blocks work/deploy), major (significant slowdown), minor (nice to know). Default: major."},file_paths:{type:"array",items:{type:"string"},description:'Files involved in this lesson (e.g. ["infra/deploy.sh", ".env"])'},commands:{type:"array",items:{type:"string"},description:'Commands that worked or failed (e.g. ["rsync -avz ...", "docker compose up -d"])'},tags:{type:"array",items:{type:"string"},description:'Topic tags for filtering (e.g. ["bash", "deploy", "env"])'},depends_on:{type:"array",items:{type:"string"},description:'Prerequisites, e.g. ["node:>=20", "docker:running"]. A stale one flags dependent lessons for review.'},author:{type:"string",description:'Who is storing this lesson, e.g. "alice". Enables cross-author reuse tracking.'},grund:{type:"string",description:"One line: WHY the previous version was wrong, like a commit message. REQUIRED when the topic already exists; optional on first write."},ersetzt:{type:"string",description:'Topic slug of an OLDER lesson this one refutes. The old one is suppressed in smart_recall and shows a "superseded" banner.'},gilt_ab:{type:"string",description:"ISO date since when the FACT is true (vs. when written). Omit if unknown. A replacement sets gilt_bis on the old lesson (then shown as history). About the fact, NOT an age decay."},gilt_fuer:{type:"array",items:{type:"string"},description:'Version scope of the FACT, package@range, all must hold: ["next@<15", "react@>=18 <19", "go@>=1.22", "python:fastapi@<0.110"]. Recall ranks a lesson that does not fit the project versions last, marked, never hidden; unknown = no change. Omit on update to keep, [] clears.'},visibility:{type:"string",enum:["team","private","public"],description:'Who can see it: "team" (default) = all members, "private" = only via exact recall_best_solution, "public" = same as team for now.'},service:{type:"string",description:'Service or system this lesson concerns, e.g. "prometheus", "auth-service".'},service_kind:{type:"string",enum:["service","system"],description:'"service" (default) for an application, "system" for infrastructure like prometheus or redis.'},group:{type:"string",description:'Optional sub-team scope, e.g. "backend". Only that group and admins see it. Independent of visibility.'}},required:["topic","outcome","what_worked"]}},{name:"recall_best_solution",description:'Recall the best known solution for a topic from past lessons. Call this BEFORE attempting any task that might have been done before. Returns the most recent successful lesson for the topic, with confidence indicator. \u26A0\uFE0F badge = lesson is >5d old (verify before applying). \u{1F534} = >10d old (likely stale!). Recalling a lesson resets its confidence clock to 1.0 (marks as recently verified). A superseded lesson shows a banner naming its successor; if the successor was deleted, the banner says so and the lesson counts as the best remaining answer. Example: recall_best_solution(topic="deploy:web") \u2192 returns the working deploy command.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Topic slug to look up, e.g. "deploy:web". Supports partial match.'},author:{type:"string",description:'Who is asking (optional). Required to read a group-scoped lesson: without it, group-scoped lessons answer like "not found". Team-wide lessons need no author.'}},required:["topic"]}},{name:"recall_feedback",description:'Tell the Brain whether a recalled lesson ACTUALLY SOLVED your problem. This is the one signal the Brain cannot infer: recall_count only means "it was shown". Call it right after a lesson helped you \u2014 or after you solved something the Brain should have found. IMPORTANT: rank=0 means the lesson was NOT in the answer at all. That is the most valuable feedback there is, because it says the ranking never surfaced it. Example: recall_feedback(query="why does the deploy abort", topic="ci:timeout-reports-cancelled", helped=true, rank=0)',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},query:{type:"string",description:"The question you asked, as you asked it. Not a summary \u2014 the ranking has to learn from the real wording."},topic:{type:"string",description:"Topic of the lesson this is about. May be a lesson that was NOT returned (then set rank=0)."},helped:{type:"boolean",description:'Did it solve your problem? true or false. There is deliberately no "not sure" \u2014 a guessed value is worse than none.'},rank:{type:"number",description:"Where it stood in the answer, 1-based. 0 = it was NOT in the answer at all (the most valuable case)."},note:{type:"string",description:"Optional: what was missing, or why it did not fit."},author:{type:"string",description:"Optional: your handle."}},required:["query","topic","helped","rank"]}},{name:"lesson_verified",description:'Report that you RAN the check for a lesson and what came back. This is the only way a lesson gets fresh again \u2014 reading one does not verify it, and since 0.10.165 recall no longer pretends otherwise. The server never runs the command itself: you run it, you report the result. holds=true refreshes verified_at and clears any earlier failed check. holds=false marks the lesson as questionable and REQUIRES `befund` \u2014 it deletes nothing, because a check can fail for reasons that have nothing to do with the lesson. Example: lesson_verified(topic="deploy:web", holds=true, geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic slug of the lesson you checked."},haelt:{type:"boolean",description:'Did the check confirm the lesson? true or false. There is deliberately no "not sure": guessing true makes an unchecked lesson look fresh, guessing false flags a correct one.'},geprueft_mit:{type:"string",description:"The command you actually ran, one line. Shown in later recalls so the next reader can repeat it."},befund:{type:"string",description:"What you saw instead. REQUIRED when haelt=false \u2014 a warning without content is noise."},author:{type:"string",description:"Optional: your handle."}},required:["topic","haelt"]}},{name:"smart_recall",description:'Returns the fixes, decisions and pitfalls this team already learned for the task at hand. Call it FIRST at the start of every coding task \u2014 before reading files or editing \u2014 with one line about the task, e.g. smart_recall("fix login redirect loop"). Finds lessons by meaning, not exact words. instance_id may be omitted; the configured instance is used \u2014 never guess one. Falls back to remember_context keys if no semantic match is found.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},query:{type:"string",description:"Natural language query to find relevant cached context"},threshold:{type:"number",description:"Similarity threshold 0-1 (default: 0.78)"},author:{type:"string",description:"Who is recalling (optional). Counts cross-author reuse."},context_files:{type:"array",items:{type:"string"},description:'Files you are working on, e.g. ["src/auth/service.ts"]. Lessons learned around these files rank higher.'},limit:{type:"number",description:"Max results, 1-20 (default 8)."}},required:["query"]}},{name:"session_start",description:"Single-call session briefing. Call this at the START of every session INSTEAD of multiple separate smart_recall/recall_best_solution calls. Returns: last session summary, recent lessons sorted by recency, relevant lessons for your focus area, brain health stats (counts of open failures and stale lessons), team telepathy (what teammates learned this week), predictive pre-warnings (if your focus area has known failure patterns), and memory crystals (compressed wisdom from old sessions). Also saves a session start marker so session_end can compute duration.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},focus:{type:"string",description:'Keywords for what you plan to work on today (e.g. "deploy infra api"). Used to surface relevant lessons at the top.'},author:{type:"string",description:'Your name or handle (e.g. "alice"). Enables Team Telepathy \u2014 filters YOUR lessons vs TEAM lessons from past 7 days.'},provider:{type:"string",description:'Current AI provider (e.g. "claude-code", "copilot", "cursor", "windsurf"). Shown in the briefing header and saved so the next provider can see who was last active.'},workspace_path:{type:"string",description:"Absolute path to the project root. If no session_end was found (e.g. context limit hit), reads git log to reconstruct what happened since last session."}},required:[]}},{name:"session_start_summary",description:"Focused session briefing for large brains. Returns only the top-N most relevant lessons for the given focus topic, scored by relevance, recall count, severity, recency, and outcome. Ideal when session_start returns too many lessons to fit in context (1000+ lesson brains). Use session_start for the full briefing including handoffs, streak, roadmap, and team telepathy.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},focus:{type:"string",description:'The topic or task you are about to work on (e.g. "deploy infra", "api auth"). Used to score and rank lessons by relevance.'},top_n:{type:"number",description:"Number of lessons to return (default 10, max 25). Lessons are ranked by relevance to focus."},author:{type:"string",description:"Your name or handle (optional). Same as session_start \u2014 used for team lesson filtering."}},required:["focus"]}},{name:"session_end",description:'Save a session summary when you finish working. Records what was accomplished, files changed, and lesson count. The next session_start will show this summary as "Last session". Call this when ending a work session, before going idle, or before summarizing. Ambient Learning: if workspace_path is provided, reads git log since session start and auto-learns from commits.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},summary:{type:"string",description:"Brief summary of what was accomplished this session (2-3 sentences)"},files_changed:{type:"array",items:{type:"string"},description:"Key files changed this session (optional)"},lessons_learned:{type:"number",description:"Number of new lessons stored this session (optional)"},workspace_path:{type:"string",description:'Absolute path to the project root (e.g. "/Users/you/myproject"). Enables Ambient Learning \u2014 reads git log since session start and auto-learns from commit messages.'}},required:["summary"]}},{name:"session_handoff",description:'Save a detailed handoff for the NEXT chat window / session. Stores: current progress, TODO list (done + remaining), changed files with descriptions, instructions for the next assistant, and any incomplete work. The next session_start automatically includes this handoff so the new window knows EXACTLY what happened and what remains. Call this BEFORE closing a chat window, especially if work is incomplete. This prevents the "continue" problem where new windows lose context, skip tasks, or produce broken code.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},completed_tasks:{type:"array",items:{type:"string"},description:'Tasks that were fully completed (e.g. "Implemented brainSearch() in JS SDK")'},remaining_tasks:{type:"array",items:{type:"string"},description:"Tasks NOT yet done \u2014 the next window MUST pick these up"},files_changed:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"File path relative to project root"},status:{type:"string",enum:["complete","partial","broken"],description:"State of this file"},description:{type:"string",description:"What was changed and what still needs work"}},required:["path","status"]},description:"Changed files with their current state \u2014 marks partial/broken files so next window knows to fix them"},instructions:{type:"string",description:"Free-form instructions for the next assistant. Be specific: what to do next, what to avoid, what broke."},context_summary:{type:"string",description:"Brief summary of what happened this session (architecture decisions, key findings, blockers)"},blocked_on:{type:"string",description:'If work is blocked, describe what is needed to unblock (e.g. "waiting for API deploy", "needs user input on design")'}},required:["completed_tasks","remaining_tasks"]}},{name:"session_ping",description:"Lightweight checkpoint \u2014 call this every ~5 tool calls or whenever you complete a significant step. Stores the current task + files touched so session_start on the NEXT provider can reconstruct what happened even if session_end was never called (e.g. Claude context limit hit, window crashed). This solves the provider-switching problem: Claude \u2192 Copilot \u2192 Cursor all see the same last checkpoint. Extremely fast \u2014 one Redis SET, no blocking operations.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},task:{type:"string",description:'What you are currently working on (e.g. "Implementing invite handler in handler/invite.go")'},files_touched:{type:"array",items:{type:"string"},description:"Files modified so far this session"},next_step:{type:"string",description:"What the NEXT step is after this checkpoint (helps next provider resume immediately)"},provider:{type:"string",description:'Current AI provider (e.g. "claude-code", "copilot", "cursor", "windsurf")'}},required:["task"]}},{name:"auto_learn_session",description:"Auto-learn from a list of session observations WITHOUT explicit learn_from_attempts calls. Pass what happened (commands run, errors seen, solutions found) and the brain classifies and stores lessons automatically. Use at session_end to capture everything you did, even if you forgot to call learn_from_attempts. Returns a summary of what was auto-stored.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},observations:{type:"array",description:"List of observations from this session",items:{type:"object",properties:{action:{type:"string",description:"What was tried (command, approach, code change)"},outcome:{type:"string",enum:["success","failure","partial"],description:"Result"},details:{type:"string",description:"Error message, output, or explanation"},topic:{type:"string",description:"Optional topic key (auto-generated if omitted)"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity (default: minor)"}},required:["action","outcome"]}}},required:["observations"]}},{name:"brain_who_knows",description:'Find who in your team has the most expertise on a given topic. Queries the org-wide knowledge graph (built automatically from learn_from_attempts author fields) and returns a ranked list of contributors whose lessons match the query, ordered by lesson count and confidence. Use to find the right person to ask before starting a task, or to understand knowledge distribution. Example: brain_who_knows(topic="kubernetes deployment") \u2192 "\u{1F947} alice \u2014 5 lessons, 94% confidence".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic or question to find experts for"},limit:{type:"number",description:"Max number of experts to return (default: 10)"}},required:["topic"]}},{name:"brain_file_map",description:'Show what cachly knows about a list of files \u2014 experts + related lessons per file. Call this before starting work on unfamiliar files, or in sync_file_changes to see what knowledge exists. For each file path: shows who has previously touched it (from learn_from_attempts author+file_paths) and which lessons reference it. Example: brain_file_map(file_paths=["src/auth/jwt.ts"]) \u2192 "\u{1F947} alice (3\xD7 \xB7 today) \u2014 related: fix:jwt-expiry".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},file_paths:{type:"array",items:{type:"string"},description:"File paths to look up (max 10)"}},required:["file_paths"]}},{name:"team_expertise_map",description:"Full team expertise overview \u2014 who knows what, at a glance. Returns a ranked table of all contributors with their lesson count, top domains, and last-active date. Use for onboarding (who to ask about X?), retrospectives, or to find knowledge gaps. Built automatically from learn_from_attempts(author=...) calls \u2014 no setup needed.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},top_n:{type:"number",description:"Max contributors to show (default: 20)"}},required:[]}},{name:"brain_collab_pairs",description:`Show the Person\u2194Person Collaboration Graph for your team (W5). Lists every pair of contributors who have worked together \u2014 either by touching the same files in learn_from_attempts or by recalling each other's lessons via smart_recall(requester=...). Each pair includes a "Frag @X und @Y" routing suggestion \u2014 ideal for onboarding and bus-factor analysis. Also flags solo contributors whose knowledge no teammate has yet recalled (bus-factor risk). Example: brain_collab_pairs() \u2192 "@alice \u2194 @bob \u2014 12 events \xB7 ask them together about auth/payments".`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_weight:{type:"number",description:"Minimum collaboration events to show a pair (default: 1)"}},required:[]}},{name:"brain_portability",description:"Bring your own model, keep your brain: the same memory in every AI editor. Returns your Brain ID plus ready-to-paste MCP config snippets for every compatible AI client: Claude Code, Cursor, Windsurf, GitHub Copilot (VS Code), Cline, Zed, Continue. All 7 clients connect to the same Brain \u2014 same lessons, crystals, predictions, and team data. Use autopilot to configure all detected editors in one command. Example: brain_portability() \u2192 config blocks for 7 clients + model-neutrality proof table.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."}},required:[]}},{name:"skill_gaps",description:"Show knowledge blind spots in your Brain \u2014 domains with unresolved failures, lessons with missing attribution, and areas where brain_who_knows cannot help. Run periodically to find where to focus knowledge capture effort. Returns a prioritized list: \u{1F534} critical (failures with no solutions) \u2192 \u{1F7E1} warn \u2192 \u{1F535} info. Pairs with brain_coverage for a full knowledge-health picture.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_failures:{type:"number",description:"Min failure count to flag a domain as a gap (default: 1)"}},required:[]}},{name:"brain_coverage",description:'Knowledge-coverage health score for your codebase \u2014 scored 0-100. Reports: total lessons, success ratio, attribution completeness, team engagement, and file coverage vs git ls-files. Run after brain_from_git or periodically to track knowledge-capture progress. Use skill_gaps to find what to fix. Example: brain_coverage() \u2192 "\u{1F7E2} Overall score: 78/100 \xB7 42 lessons \xB7 6 contributors \xB7 31% files covered".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},repo_path:{type:"string",description:"Path to the git repository (default: current directory)"}},required:[]}},{name:"brain_metrics",description:`Report the three decisive Brain metrics: (1) time-to-first-recall (onboarding friction), (2) recall-lift vs. raw BM25 (the moat proof, from Cachly-Bench), and (3) team-knowledge-reuse \u2014 what % of proven recalls used a teammate's lesson. Use to track whether the Brain is delivering its core value. Pass author="handle" to smart_recall so cross-author reuse can be measured.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."}},required:[]}},{name:"brain_changelog",description:`Generate a human-readable Markdown changelog of lessons learned in the last N days. Groups lessons by topic category, annotates with author, recall count and confidence. Ideal for weekly standups, sprint retros, or async team updates \u2014 share the output directly in Slack or a doc. Example: brain_changelog(instance_id="...", days=7) \u2192 grouped Markdown changelog of the week's learning.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},days:{type:"number",description:"How many days back to include (default: 7)"},max_lessons:{type:"number",description:"Maximum number of lessons to include (default: 30)"},include_failures:{type:"boolean",description:"Include failure-outcome lessons (default: true)"}},required:[]}},{name:"brain_service_map",description:'Map everything the Brain knows about a running service or system: who operates it, which files run in it, every known failure, and every proven fix. Built from lessons tagged with `service="..."` in learn_from_attempts. Ideal for incident triage \u2014 when a service is misbehaving (e.g. a restarting pod), instantly surface who knows it and what has gone wrong with it before. Example: brain_service_map(service="prometheus") \u2192 operators, known OOM failures, and the fixes that worked.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},service:{type:"string",description:'Name of the service/system to map (e.g. "prometheus", "cachly-web", "auth-service"). Matches the `service` tag on stored lessons.'}},required:["service"]}},{name:"sync_file_changes",description:"Associate recent file changes with brain knowledge. Pass a list of changed file paths (from `git diff --stat`). Returns lessons relevant to those files, and records the file changes in session history. Call this after commits so the brain tracks what changed and why.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},changed_files:{type:"array",items:{type:"string"},description:"List of changed file paths"},git_diff_stat:{type:"string",description:"Output of `git diff --stat` (optional)"},commit_msg:{type:"string",description:"Commit message (optional)"}},required:["changed_files"]}},{name:"team_learn",description:'Store a lesson in a shared team brain so all team members benefit. Like learn_from_attempts, but REQUIRES an author name for attribution. Shows up in team_recall with "by <author>" so the team knows who learned it.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},author:{type:"string",description:"Your name or handle (required for team attribution)"},topic:{type:"string",description:'Topic in category:keyword format (e.g. "deploy:api")'},outcome:{type:"string",enum:["success","failure","partial"],description:"What happened"},what_worked:{type:"string",description:"What worked (the solution)"},what_failed:{type:"string",description:"What did NOT work (avoid this)"},severity:{type:"string",enum:["critical","major","minor"],description:"Impact level"},file_paths:{type:"array",items:{type:"string"},description:"Relevant file paths"},commands:{type:"array",items:{type:"string"},description:"Commands that worked"},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["author","topic","outcome","what_worked"]}},{name:"team_confirm",description:"Endorse (review-confirm) a team lesson so trusted, human-reviewed knowledge ranks above unreviewed auto-learned entries. A senior review weighs more than a peer review; distinct endorsements add a small boost. Confirmed lessons surface higher in smart_recall and team_recall and carry a \u{1F6E1}\uFE0F/\u2714\uFE0F badge. Use this in code review or knowledge reviews to bless the canonical solution for a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:'Topic slug of the lesson to confirm (e.g. "deploy:api")'},reviewer:{type:"string",description:"Your name or handle (the reviewer endorsing this lesson)"},level:{type:"string",enum:["senior","peer"],description:'Review weight \u2014 "senior" ranks higher than "peer" (default: peer)'},note:{type:"string",description:"Optional review note (kept in the lesson audit trail)"}},required:["topic","reviewer"]}},{name:"team_assign_role",description:'Assign a role (admin | reviewer | contributor | viewer) to a team member on a shared brain instance. Roles control what each person can do: admin can manage roles and delete lessons; reviewer can senior-review (\u{1F6E1}\uFE0F badge, stronger recall boost); contributor can store lessons and peer-review (\u2714\uFE0F badge); viewer is read-only. First call bootstraps governance (no auth required when no admins exist yet). After that, only an admin can assign or change roles. Example: team_assign_role(handle="alice", role="reviewer", assigned_by="bob") \u2014 bob must be an admin.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Handle or name of the team member to assign a role to"},role:{type:"string",enum:["admin","reviewer","contributor","viewer"],description:"Role to assign. admin: manage roles + all actions. reviewer: senior-review (\u{1F6E1}\uFE0F). contributor: store + peer-review. viewer: read-only."},assigned_by:{type:"string",description:"Handle of the admin performing the assignment (required after governance bootstrap)"}},required:["handle","role"]}},{name:"team_whoami",description:"Show your own role and capabilities on a shared brain instance. Tells you what you can do (store, review, manage roles) and who to contact if you need a higher role. Run this after onboarding to confirm your role was set correctly.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Your handle or name"}},required:["handle"]}},{name:"team_roster",description:"Show all team members and their assigned roles on a shared brain instance. Returns a table of handles, roles (\u{1F451} admin \xB7 \u{1F6E1}\uFE0F reviewer \xB7 \u270F\uFE0F contributor \xB7 \u{1F441}\uFE0F viewer), and capabilities. Use during onboarding to see who can do what, or to verify role assignments.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"}},required:[]}},{name:"team_audit",description:'View the governance audit log for a shared brain \u2014 an immutable trail of who changed roles and who confirmed which lessons, with timestamps. Essential for enterprise compliance and security reviews. Admin-only once governance is active (an admin has been assigned). Events are recorded automatically on team_assign_role and team_confirm \u2014 no setup. Example: team_audit(requester="alice") \u2192 "\u{1F451} role: bob set carol viewer \u2192 contributor \xB7 \u2705 confirm: dave confirmed auth:jwt-skew (senior)".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},requester:{type:"string",description:"Your handle \u2014 must be an admin once governance is active"},limit:{type:"number",description:"Max events to show, newest first (default: 50, max: 200)"}},required:[]}},{name:"team_grant_scope",description:'Add or remove a team member to/from a named group (sub-team) on a shared brain. Group-scoped lessons (stored with group="...") only surface in smart_recall for members of that group (and admins). This is team-level visibility, orthogonal to lesson-level private. Admin-gated after the role model is bootstrapped. Example: team_grant_scope(handle="alice", group="security", assigned_by="bob") \u2014 bob must be admin.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Handle of the team member to add/remove"},group:{type:"string",description:'Group/sub-team name (e.g. "backend", "security", "platform")'},action:{type:"string",enum:["add","remove"],description:"add (default) or remove the member from the group"},assigned_by:{type:"string",description:"Handle of the admin performing the change (required after governance bootstrap)"}},required:["handle","group"]}},{name:"team_scopes",description:"List team groups and their members, or the groups a specific person belongs to. Pass handle to see one person's scopes; omit it to see all groups on the instance. Use to audit who can see group-scoped lessons.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Optional \u2014 show only this person's group memberships"}},required:[]}},{name:"team_recall",description:"Recall lessons from a shared team brain, showing who learned what. Works on any shared instance (all team members using the same instance_id). Shows author, recency, and severity for each lesson. Use this to onboard new team members or find who knows about a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:"Topic or keyword to filter lessons (optional)"},author:{type:"string",description:"Filter by author name (optional)"},limit:{type:"number",description:"Max lessons to return (default: 10)"}},required:[]}},{name:"team_synthesize",description:"Team Brain Synthesis \u2014 merge multiple contributors' lessons on the same topic into one canonical version. When 2+ developers store lessons for the same topic with different details, this proposes the best merged version. Shows: all contributions by author, what worked (consensus), what failed (union), canonical lesson to store. Use this when onboarding new team members or before documenting a process.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:'Topic slug to synthesize (e.g. "deploy:api")'}},required:["topic"]}},{name:"memory_crystalize",description:"Compress the last 30-50 sessions and auto-learned lessons into a dense Memory Crystal. A crystal is a compact, structured summary of everything the brain learned \u2014 grouped by category (deploy, fix, debug, \u2026). Crystals survive session cleanup and appear in session_start once enough sessions have accumulated. Run this monthly or after a big milestone to preserve institutional knowledge. Returns a digest of what was crystallized.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},label:{type:"string",description:'Optional label for this crystal (e.g. "Q1 2026", "v2 launch"). Auto-generated from date if omitted.'}},required:[]}},{name:"team_crystallize",description:'Create a Team Crystal \u2014 the team-wide, causal counterpart to memory_crystalize. Where memory_crystalize compresses ONE brain by category, team_crystallize surfaces what a per-user memory structurally cannot: which fixes solved structurally SIMILAR problems across MULTIPLE people. A pattern only crystallizes when 2+ distinct authors independently converged on it \u2014 that cross-person signal is the moat against single-user "Dreaming"-style memory. Needs attributed lessons (learn_from_attempts(author=...) / team_learn). Surfaces in crystal_view. Example: team_crystallize() \u2192 "\u{1F9E9} pool \u2014 3 people converged (alice, bob, carol): bounded pool + timeout".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},min_authors:{type:"number",description:"Min distinct authors that must converge for a pattern to crystallize (default: 2, min: 2)"},label:{type:"string",description:'Optional label (e.g. "Q1 2026"). Auto-generated from date if omitted.'}},required:[]}},{name:"roadmap_add",description:"Add a new item to the persistent project roadmap stored in the Brain. Items survive across sessions and editors \u2014 the roadmap is always up to date. Use for features, bugs, refactors, or any planned work. Call roadmap_list to see all open items, roadmap_next to get the next actionable item.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},title:{type:"string",description:"Short title of the task/feature (3\u201310 words)"},description:{type:"string",description:"What needs to be done, acceptance criteria, context"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:'Tags for filtering (e.g. ["api", "web", "sdk", "infra"])'},milestone:{type:"string",description:"Milestone/epic this belongs to (optional)"}},required:["title"]}},{name:"roadmap_update",description:"Update the status, priority, or details of a roadmap item. Use to move items through the lifecycle: planned \u2192 in-progress \u2192 done (or blocked/cancelled). Also use to add notes/findings while working on an item.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},id:{type:"string",description:"Item ID returned by roadmap_add or roadmap_list"},status:{type:"string",enum:["planned","in-progress","done","blocked","cancelled"],description:"New status for the item"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Updated priority (optional)"},notes:{type:"string",description:"Progress notes, findings, or blockers (appended to existing notes)"},title:{type:"string",description:"Updated title (optional)"},description:{type:"string",description:"Updated description (optional)"}},required:["id"]}},{name:"roadmap_list",description:"List all roadmap items, optionally filtered by status, priority, tag, or milestone. Returns items sorted by priority then creation date. Called automatically by session_start to show open work.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},status:{type:"string",enum:["planned","in-progress","done","blocked","cancelled","open"],description:"Filter by status. Use 'open' to see planned+in-progress+blocked (default: open)"},tag:{type:"string",description:"Filter by tag (optional)"},milestone:{type:"string",description:"Filter by milestone (optional)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Filter by minimum priority (optional)"}},required:[]}},{name:"roadmap_next",description:"Get the single most important next actionable roadmap item. Returns the highest-priority in-progress item first, then planned items, sorted by priority. Call at session start to immediately know what to work on next.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},tag:{type:"string",description:"Filter by tag (optional)"}},required:[]}},{name:"brain_doctor",description:"Check the health of your AI Brain and get actionable recommendations. Reports: lesson count, context entries, last session age, open failures, quality score, effective IQ boost, stale index. Returns a prioritized list of issues with fix instructions.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},workspace_path:{type:"string",description:"Absolute path to workspace root \u2014 enables package.json analysis for openclaw cross-promo (optional)"}},required:[]}},{name:"brain_hygiene",description:"Autonomously sweep and maintain your Brain \u2014 flags stale lessons as provisional, archives long-dormant ones, and resolves contradictions where success clearly dominates failure. Safe to run on a schedule (weekly CI job) or on-demand before a big release. Lesson state lifecycle: active \u2192 provisional (confidence < threshold) \u2192 archived (stale + low-recall + old). Archived lessons are excluded from smart_recall but preserved for audit. dry_run=true (default false) shows what would change without writing anything.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dry_run:{type:"boolean",description:"Report changes without applying them (default false)"},provisional_threshold:{type:"number",description:"Confidence below which a lesson is flagged provisional (default 0.5)"},archive_days:{type:"number",description:"Days after which a provisional low-recall lesson is archived (default 30)"}},required:[]}},{name:"global_learn",description:'Store a lesson that applies across ALL your projects (cross-project knowledge). Idempotent: if a lesson with the same topic already exists, it is updated in place \u2014 no duplicates are created. Returns a confirmation with the stored lesson key. No rate limits. Global lessons are stored with the prefix cachly:global:lesson: and recalled from any instance via global_recall. Use for tool preferences, personal workflows, platform quirks, and universal gotchas. Example: global_learn(topic="bash:macos-arrays", lesson="Arrays work differently on macOS bash 3.2"). Use learn_from_attempts for project-specific session lessons; use team_learn to share lessons with your team.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (used for connection)"},topic:{type:"string",description:'Topic key in format "category:keyword"'},lesson:{type:"string",description:"The lesson content"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity (default: minor)"},tags:{type:"array",items:{type:"string"},description:"Optional tags"}},required:["topic","lesson"]}},{name:"global_recall",description:"Read-only retrieval of cross-project lessons stored via global_learn. No side effects. Returns a list of matching global lesson objects, each with topic, lesson text, severity, and tags. If no topic is provided, returns all global lessons (up to 50). If topic is provided, returns all lessons whose topic key contains that string (partial match). Use this for lessons that apply universally across all projects (tool quirks, shell gotchas, platform behavior). Use recall_best_solution instead for project-specific lessons; use team_recall for org-scoped lessons.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (used for connection)"},topic:{type:"string",description:"Topic or keyword filter (optional)"}},required:[]}},{name:"publish_lesson",description:"Publish a lesson to the Cachly Public Brain (anonymized community knowledge base). Published lessons can be imported by other developers via import_public_brain. PII is stripped automatically. Visible under the framework/category tag. Returns { lesson_id, topic, framework, published_at } confirming the publish. Irreversible \u2014 once published to the public brain, lessons cannot be deleted via the MCP interface. Use learn_from_attempts or global_learn for private lessons; use syndicate for anonymized global sharing without framework tagging.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic key (used as public category)"},lesson:{type:"string",description:"Lesson to publish (PII will be stripped)"},framework:{type:"string",description:"Framework/platform tag (nextjs, fastapi, go, docker, etc.)"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity"}},required:["topic","lesson"]}},{name:"import_public_brain",description:"Import community lessons from the Cachly Public Brain for a framework. Non-destructive: existing lessons with the same topic key are not overwritten. Returns the count of lessons imported and their topic slugs. Available frameworks: nextjs, fastapi, go, docker, kubernetes, react, typescript, python, rust, laravel, rails, spring. Use this to bootstrap a new brain with battle-tested community knowledge before your first session_start. Use publish_lesson to contribute your own lessons to the Public Brain; use learn_from_attempts for storing lessons from your own sessions.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to import into"},framework:{type:"string",description:"Framework/platform to import lessons for"},limit:{type:"number",description:"Max lessons to import (default: 20)"}},required:["framework"]}},{name:"recall_at",description:'Brain Archaeology \u2014 see what a lesson looked like at a specific point in time. "What did we know about deployments 3 months ago?" Returns the history of a topic filtered to entries before the given date. Shows how the lesson evolved: failure \u2192 partial \u2192 success. Also useful to understand WHY old code decisions were made.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Topic slug to look up, e.g. "deploy:api"'},date:{type:"string",description:'ISO date string (e.g. "2026-01-15") \u2014 returns entries stored BEFORE this date'}},required:["topic","date"]}},{name:"trace_dependency",description:'Causal Chain \u2014 find all lessons that depend on a given prerequisite. "What lessons are affected if node version changes?" When a dependency changes (new version, different provider, new OS), call this to see which lessons need review. Lessons store dependencies via the depends_on field in learn_from_attempts.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dependency:{type:"string",description:'Dependency to trace (e.g. "node:>=20", "docker:running", "wireguard:active")'},mark_review:{type:"boolean",description:"If true, marks all dependent lessons as needs_review (default: false)"}},required:["dependency"]}},{name:"list_orgs",description:"List your Cachly organizations (team/org plans). Returns each org with plan, seat count, and member info. Org plans (Team \u20AC49, Business \u20AC199, Enterprise custom) are billed separately from cache tiers.",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_org",description:"Create a new Cachly organization for team collaboration. After creation, invite team members with invite_member and upgrade the plan via the billing portal. Org plans: Team (\u20AC49/mo, 5 seats), Business (\u20AC199/mo, 20 seats), Enterprise (custom).",inputSchema:{type:"object",properties:{name:{type:"string",description:'Organization display name (e.g. "Acme Engineering")'},slug:{type:"string",description:'URL-safe slug (e.g. "acme-eng"). Auto-generated from name if omitted.'}},required:["name"]}},{name:"invite_member",description:"MUTATION \u2014 sends an invite email immediately and cannot be undone via MCP. Invite a team member to a Cachly organization by email. Requires the caller to be an admin or owner of the organization. Valid roles: admin (manage members + instances), member (read + cache ops). Default role: member. Returns an error if the email is already a member or has a pending invite.",inputSchema:{type:"object",properties:{org_id:{type:"string",description:"UUID of the organization"},email:{type:"string",description:"Email address to invite"},role:{type:"string",enum:["admin","member"],description:"Role for the invited member (default: member)"}},required:["org_id","email"]}},{name:"get_org_plan",description:"Get the current org plan, seat usage, and billing info for an organization. Shows: plan name, price, seats used/max, next billing date. To upgrade: use the billing portal URL returned by this tool.",inputSchema:{type:"object",properties:{org_id:{type:"string",description:"UUID of the organization"}},required:["org_id"]}},{name:"setup_ai_memory",description:`One-shot setup of the cachly 3-layer AI Memory system for a project.
|
|
1
|
+
const e=[{name:"list_instances",description:"List all your cachly cache instances with their status and connection details. Read-only. Returns an array of instance objects \u2014 each with id, name, tier, status, region, RAM, and redis:// connection string. Returns an empty array if no instances exist. No pagination: all instances are returned in one call (typical accounts have < 20). Use this first to discover instance UUIDs required by get_instance, cache_get, cache_set, and all other cache tools. Use get_instance to retrieve full metadata for a single instance.",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_instance",description:"Create a new managed Valkey/Redis cache instance on cachly.dev. Free tier provisions in ~30 seconds. Paid tiers return a Stripe checkout URL. Available tiers (id = name): free = Free (25 MB), dev = Solo (200 MB, \u20AC19/mo, one person), pro = Team (900 MB, \u20AC49/mo, up to 5 people, everything included), business = Business (7 GB, \u20AC199/mo).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Unique name for the instance (min 3 chars)"},tier:{type:"string",enum:["free","dev","pro","speed","business"],description:'Pricing tier. Start with "free" for testing.'}},required:["name","tier"]}},{name:"get_instance",description:"Get full metadata for a specific cache instance: name, tier, status (provisioning / running / paused), region, RAM limit, Redis connection string, created_at, and expiry. Read-only. Returns an error if the instance_id is not found or belongs to another account. Call list_instances first to discover valid UUIDs. Use get_connection_string instead if you only need the redis:// URL for your app config.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance (from list_instances)"}},required:[]}},{name:"get_connection_string",description:"Get the Redis/Valkey connection string (redis:// URL) for a running instance. Use this to configure your application or set environment variables.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance."}},required:[]}},{name:"delete_instance",description:"Permanently delete a cache instance. Deprovisions the Kubernetes workload and removes all data. This action is irreversible.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance to delete"},confirm:{type:"boolean",description:"Must be true to confirm deletion"}},required:["confirm"]}},{name:"cache_get",description:"Get a value from a running cache instance by key. Returns the stored value (string or deserialized JSON object) or null if the key does not exist or has expired. Read-only \u2014 no side effects. Use cache_mget when you need multiple keys in one round-trip. Use cache_exists to check existence without retrieving the value. Use semantic_search when you need fuzzy/vector search across stored values.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the instance."},key:{type:"string",description:"Cache key to retrieve"},org_id:{type:"string",description:"Optional org ID \u2014 if the direct key misses, falls back to the shared org namespace org:{org_id}:sem:{key}"}},required:["key"]}},{name:"cache_set",description:'Set a key-value pair in a running cache instance. Overwrites any existing value at the key \u2014 not idempotent for new data. Returns "OK" on success; returns an error if the instance_id is invalid or the instance is paused. Value can be a string or a JSON-serialized object. Optionally set a TTL in seconds (omit for no expiry). Use cache_mset instead for setting multiple keys in a single pipeline round-trip. Use cache_stream_set instead for caching LLM token streams (ordered string chunks).',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},key:{type:"string",description:"Cache key"},value:{type:"string",description:"Value to store (string or JSON)"},ttl:{type:"number",description:"Time-to-live in seconds (optional, omit for no expiry)"},org_id:{type:"string",description:"Optional org ID \u2014 also writes the key to the shared org namespace org:{org_id}:sem:{key} with the same TTL"}},required:["key","value"]}},{name:"cache_delete",description:"Permanently delete one or more keys from a running cache instance (uses Redis DEL). This operation is destructive and irreversible \u2014 deleted keys cannot be recovered. Deleting a non-existent key is safe and returns 0 for that key (no error). Returns the count of keys that were actually deleted (existing keys only). Use this to explicitly remove stale entries; prefer cache_set with a short TTL for auto-expiring data. Do NOT use this to clear an entire instance \u2014 use the dashboard or delete_instance for that.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to delete keys from (get from list_instances)"},keys:{type:"array",items:{type:"string"},description:"One or more cache keys to delete. Accepts exact keys only (no glob patterns \u2014 use cache_keys to list first)."}},required:["keys"]}},{name:"cache_exists",description:"Check whether one or more keys exist in a running cache instance (uses Redis EXISTS). Read-only \u2014 no side effects. Returns the count of keys that currently exist (integer 0 to N). If none of the keys exist, returns 0. If all exist, returns the total key count passed in. Duplicate keys in the input array are each counted separately (Redis behavior). Use this to check presence before a cache_get to avoid null handling, or to verify a cache warm-up completed. Use cache_get instead if you also need the value; use cache_ttl if you need expiry info.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to check (get from list_instances)"},keys:{type:"array",items:{type:"string"},description:"Keys to check for existence. Accepts exact keys only (no glob patterns)."}},required:["keys"]}},{name:"cache_ttl",description:"Get the remaining time-to-live (TTL) of a key in seconds. Returns -1 if the key exists but has no expiry, -2 if the key does not exist. Read-only \u2014 no side effects. Use cache_set with a ttl parameter to set or update the expiry.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},key:{type:"string",description:"Cache key to inspect"}},required:["key"]}},{name:"cache_keys",description:'List keys in a cache instance matching an optional glob pattern (e.g. "user:*", "session:*"). Uses SCAN to avoid blocking the server. Returns at most `count` keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string"},pattern:{type:"string",description:"Glob pattern (default: *)"},count:{type:"number",description:"Max keys to return (default: 50, max: 500)"}},required:[]}},{name:"cache_stats",description:"Get real-time stats for a cache instance: memory usage, hit/miss rate, commands/sec, connected clients, keyspace info, and uptime. Read-only \u2014 no side effects. The instance_id identifies the target instance (obtain from list_instances). Use this for monitoring, capacity planning, or debugging performance issues \u2014 not for reading cached values (use cache_get for that). Use cache_exists or cache_ttl if you only need key-level information.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"}},required:[]}},{name:"semantic_search",description:'Find cached entries that are semantically similar to a natural-language query. Read-only \u2014 no side effects. Returns an array of objects, each with: key, value, similarity_score (0\u20131), and namespace. Returns an empty array if no entries meet the similarity threshold. Requires OPENAI_API_KEY (or compatible provider) and CACHLY_VECTOR_URL; every tier includes a vector token. Embeddings are computed server-side and never leave Germany (pgvector HNSW index). Example: "find all cached responses about password reset" or "what did we answer about pricing?". Use cache_get for exact key lookup; use smart_recall for brain lessons.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (from list_instances)"},query:{type:"string",description:"Natural-language query to find similar cached content"},threshold:{type:"number",description:"Minimum cosine similarity 0\u20131 (default: 0.82). Lower = broader matches."},namespace:{type:"string",description:"Semantic namespace to search in (default: cachly:sem)"},top_k:{type:"number",description:"Maximum number of results to return (default: 5)"},use_hybrid:{type:"boolean",description:"Enable Hybrid BM25+Vector RRF fusion search. Passes `hybrid: true` and the query text to the pgvector API for higher precision on named entities. Default: false."},auto_namespace:{type:"boolean",description:"Auto-detect the namespace from the query text using text heuristics instead of using the `namespace` parameter. Returns results only from the matching domain (code/translation/summary/qa/creative)."}},required:["query"]}},{name:"detect_namespace",description:"Classify a prompt into one of 5 semantic namespaces using text heuristics. Overhead: <0.1 ms, no embedding required. Useful to understand which namespace cachly will use for a given prompt. Returns one of: cachly:sem:code, cachly:sem:translation, cachly:sem:summary, cachly:sem:qa, cachly:sem:creative.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The text prompt to classify into a semantic namespace"}},required:["prompt"]}},{name:"cache_warmup",description:"Pre-warm the semantic cache with a list of prompt/value pairs. For each entry: computes an embedding, checks if a similar entry already exists (similarity \u2265 0.98), and writes new entries to Valkey + pgvector index. Use this to seed FAQ responses, product descriptions, or known-good LLM answers before the first real user traffic. Requires OPENAI_API_KEY.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},entries:{type:"array",description:"List of prompt/value pairs to pre-warm into the cache",items:{type:"object",properties:{prompt:{type:"string",description:"The query or question to cache"},value:{type:"string",description:"The answer or response to store for this prompt"},namespace:{type:"string",description:"Optional per-entry namespace override"}},required:["prompt","value"]}},namespace:{type:"string",description:"Default namespace for all entries (default: cachly:sem)"},ttl:{type:"number",description:"Time-to-live in seconds for warmed entries (omit for no expiry)"},auto_namespace:{type:"boolean",description:"Auto-detect the namespace per prompt using text heuristics. Overrides `namespace` when no per-entry namespace is set."}},required:["entries"]}},{name:"index_project",description:"Index local source files into the cachly semantic cache so AI assistants can use semantic_search to find relevant files instead of re-reading the whole codebase every time. Walks a directory recursively, reads each matching file, and stores a summary + path as a semantic cache entry (prompt = file path + content excerpt, value = relative path). Requires an embedding provider (OPENAI_API_KEY or CACHLY_EMBED_PROVIDER + key). Run once, then re-run after major refactors. TTL=86400 (24h) keeps entries fresh.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cachly instance"},dir:{type:"string",description:"Absolute path to the directory to index (e.g. /Users/you/myproject/src)"},extensions:{type:"array",items:{type:"string"},description:'File extensions to include (default: ["ts","js","go","py","java","rs","md","kt","swift"])'},max_files:{type:"number",description:"Maximum number of files to index (default: 100)"},ttl:{type:"number",description:"TTL in seconds for indexed entries (default: 86400 = 24 h)"},summary_chars:{type:"number",description:"Characters to use as summary per file (default: 1200)"},namespace:{type:"string",description:"Semantic namespace to store under (default: cachly:sem:code)"}},required:["dir"]}},{name:"cache_mset",description:"Set multiple key-value pairs in a single pipeline round-trip. Supports per-key TTL \u2013 unlike native MSET. Uses one TCP round-trip for N keys via Redis pipeline. Each item overwrites any existing value for that key. On partial failure the successfully pipelined keys are committed; a per-key error list is returned for any that failed. Returns a summary: { set: N, errors: [...] }. Use cache_set for a single key; use cache_stream_set for large streaming payloads.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},items:{type:"array",description:"Key-value pairs to set",items:{type:"object",properties:{key:{type:"string",description:"Cache key"},value:{description:"Value to store (JSON-serialised)"},ttl:{type:"number",description:"Per-key TTL in seconds (optional)"}},required:["key","value"]}}},required:["items"]}},{name:"cache_mget",description:"Retrieve multiple keys in one round-trip using native Redis MGET. Returns values in the same order as the keys array; missing keys are null.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},keys:{type:"array",items:{type:"string"},description:"List of keys to fetch"}},required:["keys"]}},{name:"cache_lock_acquire",description:"Acquire a distributed lock using Redis SET NX PX (Redlock-lite). Returns a fencing token on success. The lock auto-expires after ttl_ms to prevent deadlocks. Use cache_lock_release to free the lock early.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Lock resource identifier"},ttl_ms:{type:"number",description:"Safety TTL in milliseconds (e.g. 5000)"},retries:{type:"number",description:"Max acquire attempts (default: 3)"},retry_delay_ms:{type:"number",description:"Milliseconds between retries (default: 50)"}},required:["key","ttl_ms"]}},{name:"cache_lock_release",description:"Release a previously acquired distributed lock. Uses a Lua script for atomic release \u2013 only deletes the key if the fencing token matches.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:"Lock resource identifier (same as in cache_lock_acquire)"},token:{type:"string",description:"Fencing token returned by cache_lock_acquire"}},required:["key","token"]}},{name:"get_api_status",description:"Full diagnostic for your cachly Brain \u2014 call this FIRST whenever anything is not working. Returns: API reachability, JWT validity + expiry, your user ID, all Brain instances with live status (\u{1F7E2} running / \u{1F7E1} provisioning / \u{1F534} stopped), Redis ping on the active connection, and actionable fix steps for every issue found. Workflow: run get_api_status \u2192 read the issue it flags \u2192 fix it \u2192 retry your tool.",inputSchema:{type:"object",properties:{},required:[]}},{name:"remember_context",description:'Save context information to the cache so you can recall it later without re-computing. Perfect for caching: codebase overviews, file summaries, project structure, frequently-accessed data, or "thinking" results like dependency analysis. The AI assistant can use this to avoid re-reading the entire codebase every time. Overwrites any existing value stored under the same key. Returns { key, stored_at, ttl } confirming the saved context. Example: remember_context("project overview", "This is a Next.js app with...") then later: recall_context("project overview"). Use recall_context to retrieve; use list_remembered to see all stored keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:'Descriptive key like "project_overview", "auth_architecture", "file:src/index.ts"'},content:{type:"string",description:"The context/summary/analysis to remember"},category:{type:"string",enum:["overview","architecture","file_summary","dependency","thinking","custom"],description:"Category for organization (default: custom)"},ttl:{type:"number",description:"Time-to-live in seconds (default: 86400 = 24h, use 0 for no expiry)"}},required:["key","content"]}},{name:"recall_context",description:'Retrieve previously saved context from the cache. Returns the saved content or null if not found. Use this at the START of any task to check if you already have relevant context cached, before doing expensive operations like reading many files. Supports glob patterns: "file:*" matches all file summaries, "arch*" matches architecture-related keys.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},key:{type:"string",description:'The key to look up (supports glob pattern like "file:*")'}},required:["key"]}},{name:"list_remembered",description:"List all cached context entries for this project. Shows what knowledge the AI assistant has already cached, so you can decide whether to recall existing context or refresh it. Returns: key, category, size, TTL remaining, and a content preview.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},category:{type:"string",enum:["overview","architecture","file_summary","dependency","thinking","custom","all"],description:"Filter by category (default: all)"},limit:{type:"number",description:"Max entries to return (default: 50)"}},required:[]}},{name:"forget_context",description:'Delete one or more cached context entries. Use when context is stale or you want to force a fresh analysis. Supports glob patterns: "file:*" deletes all file summaries.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},keys:{type:"array",items:{type:"string"},description:"Keys to delete (supports glob)"}},required:["keys"]}},{name:"learn_from_attempts",description:'Store a lesson AFTER any non-trivial task (deploy, debug, fix, decision); future sessions recall it. instance_id may be omitted; the configured instance is used \u2014 never guess one. If the topic already exists, the write is an UPDATE and REQUIRES `grund` (one line: WHY the previous version was wrong) \u2014 without it the update is rejected. A conflicting outcome triggers a contradiction warning. Example: learn_from_attempts(topic="deploy:api", outcome="success", what_worked="PORT 3095 SERVES WHISPER \u2014 nohup docker compose up -d", severity="critical")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Short slug, e.g. "deploy:web", "debug:redis-tls", "fix:generate-series"'},outcome:{type:"string",enum:["success","failure","partial"],description:"Did it work?"},what_worked:{type:"string",description:"What solved it. LEAD WITH THE DECISIVE FACT (the number, address, command) in the first 100 characters \u2014 briefings truncate there."},what_failed:{type:"string",description:"What did NOT work (optional but valuable)"},context:{type:"string",description:'The SYMPTOM in the words someone would search for, before they knew the fix ("deploy stuck, rollout not finishing"). Plus error messages and root cause. Optional but high-value: it is what closes the gap between the question and the answer.'},severity:{type:"string",enum:["critical","major","minor"],description:"Impact severity: critical (blocks work/deploy), major (significant slowdown), minor (nice to know). Default: major."},file_paths:{type:"array",items:{type:"string"},description:'Files involved in this lesson (e.g. ["infra/deploy.sh", ".env"])'},commands:{type:"array",items:{type:"string"},description:'Commands that worked or failed (e.g. ["rsync -avz ...", "docker compose up -d"])'},tags:{type:"array",items:{type:"string"},description:'Topic tags for filtering (e.g. ["bash", "deploy", "env"])'},depends_on:{type:"array",items:{type:"string"},description:'Prerequisites, e.g. ["node:>=20", "docker:running"]. A stale one flags dependent lessons for review.'},author:{type:"string",description:'Who is storing this lesson, e.g. "alice". Enables cross-author reuse tracking.'},grund:{type:"string",description:"One line: WHY the previous version was wrong, like a commit message. REQUIRED when the topic already exists; optional on first write."},ersetzt:{type:"string",description:'Topic slug of an OLDER lesson this one refutes. The old one is suppressed in smart_recall and shows a "superseded" banner.'},gilt_ab:{type:"string",description:"ISO date since when the FACT is true (vs. when written). Omit if unknown. A replacement sets gilt_bis on the old lesson (then shown as history). About the fact, NOT an age decay."},gilt_fuer:{type:"array",items:{type:"string"},description:'Version scope of the FACT, package@range, all must hold: ["next@<15", "react@>=18 <19", "go@>=1.22", "python:fastapi@<0.110"]. Recall ranks a lesson that does not fit the project versions last, marked, never hidden; unknown = no change. Omit on update to keep, [] clears.'},visibility:{type:"string",enum:["team","private","public"],description:'Who can see it: "team" (default) = all members, "private" = only via exact recall_best_solution, "public" = same as team for now.'},service:{type:"string",description:'Service or system this lesson concerns, e.g. "prometheus", "auth-service".'},service_kind:{type:"string",enum:["service","system"],description:'"service" (default) for an application, "system" for infrastructure like prometheus or redis.'},group:{type:"string",description:'Optional sub-team scope, e.g. "backend". Only that group and admins see it. Independent of visibility.'}},required:["topic","outcome","what_worked"]}},{name:"recall_best_solution",description:'Recall the best known solution for a topic from past lessons. Call this BEFORE attempting any task that might have been done before. Returns the most recent successful lesson for the topic, with confidence indicator. \u26A0\uFE0F badge = lesson is >5d old (verify before applying). \u{1F534} = >10d old (likely stale!). Recalling a lesson resets its confidence clock to 1.0 (marks as recently verified). A superseded lesson shows a banner naming its successor; if the successor was deleted, the banner says so and the lesson counts as the best remaining answer. Example: recall_best_solution(topic="deploy:web") \u2192 returns the working deploy command.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Topic slug to look up, e.g. "deploy:web". Supports partial match.'},author:{type:"string",description:'Who is asking (optional). Required to read a group-scoped lesson: without it, group-scoped lessons answer like "not found". Team-wide lessons need no author.'}},required:["topic"]}},{name:"recall_feedback",description:'Tell the Brain whether a recalled lesson ACTUALLY SOLVED your problem. This is the one signal the Brain cannot infer: recall_count only means "it was shown". Call it right after a lesson helped you \u2014 or after you solved something the Brain should have found. IMPORTANT: rank=0 means the lesson was NOT in the answer at all. That is the most valuable feedback there is, because it says the ranking never surfaced it. Example: recall_feedback(query="why does the deploy abort", topic="ci:timeout-reports-cancelled", helped=true, rank=0)',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},query:{type:"string",description:"The question you asked, as you asked it. Not a summary \u2014 the ranking has to learn from the real wording."},topic:{type:"string",description:"Topic of the lesson this is about. May be a lesson that was NOT returned (then set rank=0)."},helped:{type:"boolean",description:'Did it solve your problem? true or false. There is deliberately no "not sure" \u2014 a guessed value is worse than none.'},rank:{type:"number",description:"Where it stood in the answer, 1-based. 0 = it was NOT in the answer at all (the most valuable case)."},note:{type:"string",description:"Optional: what was missing, or why it did not fit."},author:{type:"string",description:"Optional: your handle."}},required:["query","topic","helped","rank"]}},{name:"lesson_verified",description:'Report that you RAN the check for a lesson and what came back. This is the only way a lesson gets fresh again \u2014 reading one does not verify it, and since 0.10.165 recall no longer pretends otherwise. The server never runs the command itself: you run it, you report the result. holds=true refreshes verified_at and clears any earlier failed check. holds=false marks the lesson as questionable and REQUIRES `befund` \u2014 it deletes nothing, because a check can fail for reasons that have nothing to do with the lesson. Example: lesson_verified(topic="deploy:web", holds=true, geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic slug of the lesson you checked."},haelt:{type:"boolean",description:'Did the check confirm the lesson? true or false. There is deliberately no "not sure": guessing true makes an unchecked lesson look fresh, guessing false flags a correct one.'},geprueft_mit:{type:"string",description:"The command you actually ran, one line. Shown in later recalls so the next reader can repeat it."},befund:{type:"string",description:"What you saw instead. REQUIRED when haelt=false \u2014 a warning without content is noise."},author:{type:"string",description:"Optional: your handle."}},required:["topic","haelt"]}},{name:"smart_recall",description:'Returns the fixes, decisions and pitfalls this team already learned for the task at hand. Call it FIRST at the start of every coding task \u2014 before reading files or editing \u2014 with one line about the task, e.g. smart_recall("fix login redirect loop"). Finds lessons by meaning, not exact words. instance_id may be omitted; the configured instance is used \u2014 never guess one. Falls back to remember_context keys if no semantic match is found.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},query:{type:"string",description:"Natural language query to find relevant cached context"},threshold:{type:"number",description:"Similarity threshold 0-1 (default: 0.78)"},author:{type:"string",description:"Who is recalling (optional). Counts cross-author reuse."},context_files:{type:"array",items:{type:"string"},description:'Files you are working on, e.g. ["src/auth/service.ts"]. Lessons learned around these files rank higher.'},limit:{type:"number",description:"Max results, 1-20 (default 8)."}},required:["query"]}},{name:"session_start",description:"Single-call session briefing. Call this at the START of every session INSTEAD of multiple separate smart_recall/recall_best_solution calls. Returns: last session summary, recent lessons sorted by recency, relevant lessons for your focus area, brain health stats (counts of open failures and stale lessons), team telepathy (what teammates learned this week), predictive pre-warnings (if your focus area has known failure patterns), and memory crystals (compressed wisdom from old sessions). Also saves a session start marker so session_end can compute duration.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},focus:{type:"string",description:'Keywords for what you plan to work on today (e.g. "deploy infra api"). Used to surface relevant lessons at the top.'},author:{type:"string",description:'Your name or handle (e.g. "alice"). Enables Team Telepathy \u2014 filters YOUR lessons vs TEAM lessons from past 7 days.'},provider:{type:"string",description:'Current AI provider (e.g. "claude-code", "copilot", "cursor", "windsurf"). Shown in the briefing header and saved so the next provider can see who was last active.'},workspace_path:{type:"string",description:"Absolute path to the project root. If no session_end was found (e.g. context limit hit), reads git log to reconstruct what happened since last session."}},required:[]}},{name:"session_start_summary",description:"Focused session briefing for large brains. Returns only the top-N most relevant lessons for the given focus topic, scored by relevance, recall count, severity, recency, and outcome. Ideal when session_start returns too many lessons to fit in context (1000+ lesson brains). Use session_start for the full briefing including handoffs, streak, roadmap, and team telepathy.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},focus:{type:"string",description:'The topic or task you are about to work on (e.g. "deploy infra", "api auth"). Used to score and rank lessons by relevance.'},top_n:{type:"number",description:"Number of lessons to return (default 10, max 25). Lessons are ranked by relevance to focus."},author:{type:"string",description:"Your name or handle (optional). Same as session_start \u2014 used for team lesson filtering."}},required:["focus"]}},{name:"session_end",description:'Save a session summary when you finish working. Records what was accomplished, files changed, and lesson count. The next session_start will show this summary as "Last session". Call this when ending a work session, before going idle, or before summarizing. Ambient Learning: if workspace_path is provided, reads git log since session start and auto-learns from commits.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},summary:{type:"string",description:"Brief summary of what was accomplished this session (2-3 sentences)"},files_changed:{type:"array",items:{type:"string"},description:"Key files changed this session (optional)"},lessons_learned:{type:"number",description:"Number of new lessons stored this session (optional)"},workspace_path:{type:"string",description:'Absolute path to the project root (e.g. "/Users/you/myproject"). Enables Ambient Learning \u2014 reads git log since session start and auto-learns from commit messages.'}},required:["summary"]}},{name:"session_handoff",description:'Save a detailed handoff for the NEXT chat window / session. Stores: current progress, TODO list (done + remaining), changed files with descriptions, instructions for the next assistant, and any incomplete work. The next session_start automatically includes this handoff so the new window knows EXACTLY what happened and what remains. Call this BEFORE closing a chat window, especially if work is incomplete. This prevents the "continue" problem where new windows lose context, skip tasks, or produce broken code.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},completed_tasks:{type:"array",items:{type:"string"},description:'Tasks that were fully completed (e.g. "Implemented brainSearch() in JS SDK")'},remaining_tasks:{type:"array",items:{type:"string"},description:"Tasks NOT yet done \u2014 the next window MUST pick these up"},files_changed:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"File path relative to project root"},status:{type:"string",enum:["complete","partial","broken"],description:"State of this file"},description:{type:"string",description:"What was changed and what still needs work"}},required:["path","status"]},description:"Changed files with their current state \u2014 marks partial/broken files so next window knows to fix them"},instructions:{type:"string",description:"Free-form instructions for the next assistant. Be specific: what to do next, what to avoid, what broke."},context_summary:{type:"string",description:"Brief summary of what happened this session (architecture decisions, key findings, blockers)"},blocked_on:{type:"string",description:'If work is blocked, describe what is needed to unblock (e.g. "waiting for API deploy", "needs user input on design")'}},required:["completed_tasks","remaining_tasks"]}},{name:"session_ping",description:"Lightweight checkpoint \u2014 call this every ~5 tool calls or whenever you complete a significant step. Stores the current task + files touched so session_start on the NEXT provider can reconstruct what happened even if session_end was never called (e.g. Claude context limit hit, window crashed). This solves the provider-switching problem: Claude \u2192 Copilot \u2192 Cursor all see the same last checkpoint. Extremely fast \u2014 one Redis SET, no blocking operations.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},task:{type:"string",description:'What you are currently working on (e.g. "Implementing invite handler in handler/invite.go")'},files_touched:{type:"array",items:{type:"string"},description:"Files modified so far this session"},next_step:{type:"string",description:"What the NEXT step is after this checkpoint (helps next provider resume immediately)"},provider:{type:"string",description:'Current AI provider (e.g. "claude-code", "copilot", "cursor", "windsurf")'}},required:["task"]}},{name:"auto_learn_session",description:"Auto-learn from a list of session observations WITHOUT explicit learn_from_attempts calls. Pass what happened (commands run, errors seen, solutions found) and the brain classifies and stores lessons automatically. Use at session_end to capture everything you did, even if you forgot to call learn_from_attempts. Returns a summary of what was auto-stored.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},observations:{type:"array",description:"List of observations from this session",items:{type:"object",properties:{action:{type:"string",description:"What was tried (command, approach, code change)"},outcome:{type:"string",enum:["success","failure","partial"],description:"Result"},details:{type:"string",description:"Error message, output, or explanation"},topic:{type:"string",description:"Optional topic key (auto-generated if omitted)"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity (default: minor)"}},required:["action","outcome"]}}},required:["observations"]}},{name:"brain_who_knows",description:'Find who in your team has the most expertise on a given topic. Queries the org-wide knowledge graph (built automatically from learn_from_attempts author fields) and returns a ranked list of contributors whose lessons match the query, ordered by lesson count and confidence. Use to find the right person to ask before starting a task, or to understand knowledge distribution. Example: brain_who_knows(topic="kubernetes deployment") \u2192 "\u{1F947} alice \u2014 5 lessons, 94% confidence".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic or question to find experts for"},limit:{type:"number",description:"Max number of experts to return (default: 10)"}},required:["topic"]}},{name:"brain_file_map",description:'Show what cachly knows about a list of files \u2014 experts + related lessons per file. Call this before starting work on unfamiliar files, or in sync_file_changes to see what knowledge exists. For each file path: shows who has previously touched it (from learn_from_attempts author+file_paths) and which lessons reference it. Example: brain_file_map(file_paths=["src/auth/jwt.ts"]) \u2192 "\u{1F947} alice (3\xD7 \xB7 today) \u2014 related: fix:jwt-expiry".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},file_paths:{type:"array",items:{type:"string"},description:"File paths to look up (max 10)"}},required:["file_paths"]}},{name:"team_expertise_map",description:"Full team expertise overview \u2014 who knows what, at a glance. Returns a ranked table of all contributors with their lesson count, top domains, and last-active date. Use for onboarding (who to ask about X?), retrospectives, or to find knowledge gaps. Built automatically from learn_from_attempts(author=...) calls \u2014 no setup needed.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},top_n:{type:"number",description:"Max contributors to show (default: 20)"}},required:[]}},{name:"brain_collab_pairs",description:`Show the Person\u2194Person Collaboration Graph for your team (W5). Lists every pair of contributors who have worked together \u2014 either by touching the same files in learn_from_attempts or by recalling each other's lessons via smart_recall(requester=...). Each pair includes a "Frag @X und @Y" routing suggestion \u2014 ideal for onboarding and bus-factor analysis. Also flags solo contributors whose knowledge no teammate has yet recalled (bus-factor risk). Example: brain_collab_pairs() \u2192 "@alice \u2194 @bob \u2014 12 events \xB7 ask them together about auth/payments".`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_weight:{type:"number",description:"Minimum collaboration events to show a pair (default: 1)"}},required:[]}},{name:"brain_portability",description:"Bring your own model, keep your brain: the same memory in every AI editor. Returns your Brain ID plus ready-to-paste MCP config snippets for every compatible AI client: Claude Code, Cursor, Windsurf, GitHub Copilot (VS Code), Cline, Zed, Continue. All 7 clients connect to the same Brain \u2014 same lessons, crystals, predictions, and team data. Use autopilot to configure all detected editors in one command. Example: brain_portability() \u2192 config blocks for 7 clients + model-neutrality proof table.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."}},required:[]}},{name:"skill_gaps",description:"Show knowledge blind spots in your Brain \u2014 domains with unresolved failures, lessons with missing attribution, and areas where brain_who_knows cannot help. Run periodically to find where to focus knowledge capture effort. Returns a prioritized list: \u{1F534} critical (failures with no solutions) \u2192 \u{1F7E1} warn \u2192 \u{1F535} info. Pairs with brain_coverage for a full knowledge-health picture.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},min_failures:{type:"number",description:"Min failure count to flag a domain as a gap (default: 1)"}},required:[]}},{name:"brain_coverage",description:'Knowledge-coverage health score for your codebase \u2014 scored 0-100. Reports: total lessons, success ratio, attribution completeness, team engagement, and file coverage vs git ls-files. Run after brain_from_git or periodically to track knowledge-capture progress. Use skill_gaps to find what to fix. Example: brain_coverage() \u2192 "\u{1F7E2} Overall score: 78/100 \xB7 42 lessons \xB7 6 contributors \xB7 31% files covered".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},repo_path:{type:"string",description:"Path to the git repository (default: current directory)"}},required:[]}},{name:"brain_metrics",description:`Report the three decisive Brain metrics: (1) time-to-first-recall (onboarding friction), (2) recall-lift vs. raw BM25 (the moat proof, from Cachly-Bench), and (3) team-knowledge-reuse \u2014 what % of proven recalls used a teammate's lesson. Use to track whether the Brain is delivering its core value. Pass author="handle" to smart_recall so cross-author reuse can be measured.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."}},required:[]}},{name:"brain_changelog",description:`Generate a human-readable Markdown changelog of lessons learned in the last N days. Groups lessons by topic category, annotates with author, recall count and confidence. Ideal for weekly standups, sprint retros, or async team updates \u2014 share the output directly in Slack or a doc. Example: brain_changelog(instance_id="...", days=7) \u2192 grouped Markdown changelog of the week's learning.`,inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},days:{type:"number",description:"How many days back to include (default: 7)"},max_lessons:{type:"number",description:"Maximum number of lessons to include (default: 30)"},include_failures:{type:"boolean",description:"Include failure-outcome lessons (default: true)"}},required:[]}},{name:"brain_service_map",description:'Map everything the Brain knows about a running service or system: who operates it, which files run in it, every known failure, and every proven fix. Built from lessons tagged with `service="..."` in learn_from_attempts. Ideal for incident triage \u2014 when a service is misbehaving (e.g. a restarting pod), instantly surface who knows it and what has gone wrong with it before. Example: brain_service_map(service="prometheus") \u2192 operators, known OOM failures, and the fixes that worked.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},service:{type:"string",description:'Name of the service/system to map (e.g. "prometheus", "cachly-web", "auth-service"). Matches the `service` tag on stored lessons.'}},required:["service"]}},{name:"sync_file_changes",description:"Associate recent file changes with brain knowledge. Pass a list of changed file paths (from `git diff --stat`). Returns lessons relevant to those files, and records the file changes in session history. Call this after commits so the brain tracks what changed and why.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},changed_files:{type:"array",items:{type:"string"},description:"List of changed file paths"},git_diff_stat:{type:"string",description:"Output of `git diff --stat` (optional)"},commit_msg:{type:"string",description:"Commit message (optional)"}},required:["changed_files"]}},{name:"team_learn",description:'Store a lesson in a shared team brain so all team members benefit. Like learn_from_attempts, but REQUIRES an author name for attribution. Shows up in team_recall with "by <author>" so the team knows who learned it.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},author:{type:"string",description:"Your name or handle (required for team attribution)"},topic:{type:"string",description:'Topic in category:keyword format (e.g. "deploy:api")'},outcome:{type:"string",enum:["success","failure","partial"],description:"What happened"},what_worked:{type:"string",description:"What worked (the solution)"},what_failed:{type:"string",description:"What did NOT work (avoid this)"},severity:{type:"string",enum:["critical","major","minor"],description:"Impact level"},file_paths:{type:"array",items:{type:"string"},description:"Relevant file paths"},commands:{type:"array",items:{type:"string"},description:"Commands that worked"},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["author","topic","outcome","what_worked"]}},{name:"team_confirm",description:"Endorse (review-confirm) a team lesson so trusted, human-reviewed knowledge ranks above unreviewed auto-learned entries. A senior review weighs more than a peer review; distinct endorsements add a small boost. Confirmed lessons surface higher in smart_recall and team_recall and carry a \u{1F6E1}\uFE0F/\u2714\uFE0F badge. Use this in code review or knowledge reviews to bless the canonical solution for a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:'Topic slug of the lesson to confirm (e.g. "deploy:api")'},reviewer:{type:"string",description:"Your name or handle (the reviewer endorsing this lesson)"},level:{type:"string",enum:["senior","peer"],description:'Review weight \u2014 "senior" ranks higher than "peer" (default: peer)'},note:{type:"string",description:"Optional review note (kept in the lesson audit trail)"}},required:["topic","reviewer"]}},{name:"team_assign_role",description:'Assign a role (admin | reviewer | contributor | viewer) to a team member on a shared brain instance. Roles control what each person can do: admin can manage roles and delete lessons; reviewer can senior-review (\u{1F6E1}\uFE0F badge, stronger recall boost); contributor can store lessons and peer-review (\u2714\uFE0F badge); viewer is read-only. First call bootstraps governance (no auth required when no admins exist yet). After that, only an admin can assign or change roles. Example: team_assign_role(handle="alice", role="reviewer", assigned_by="bob") \u2014 bob must be an admin.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Handle or name of the team member to assign a role to"},role:{type:"string",enum:["admin","reviewer","contributor","viewer"],description:"Role to assign. admin: manage roles + all actions. reviewer: senior-review (\u{1F6E1}\uFE0F). contributor: store + peer-review. viewer: read-only."},assigned_by:{type:"string",description:"Handle of the admin performing the assignment (required after governance bootstrap)"}},required:["handle","role"]}},{name:"team_whoami",description:"Show your own role and capabilities on a shared brain instance. Tells you what you can do (store, review, manage roles) and who to contact if you need a higher role. Run this after onboarding to confirm your role was set correctly.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Your handle or name"}},required:["handle"]}},{name:"team_roster",description:"Show all team members and their assigned roles on a shared brain instance. Returns a table of handles, roles (\u{1F451} admin \xB7 \u{1F6E1}\uFE0F reviewer \xB7 \u270F\uFE0F contributor \xB7 \u{1F441}\uFE0F viewer), and capabilities. Use during onboarding to see who can do what, or to verify role assignments.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"}},required:[]}},{name:"team_audit",description:'View the governance audit log for a shared brain \u2014 an immutable trail of who changed roles and who confirmed which lessons, with timestamps. Essential for enterprise compliance and security reviews. Admin-only once governance is active (an admin has been assigned). Events are recorded automatically on team_assign_role and team_confirm \u2014 no setup. Example: team_audit(requester="alice") \u2192 "\u{1F451} role: bob set carol viewer \u2192 contributor \xB7 \u2705 confirm: dave confirmed auth:jwt-skew (senior)".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},requester:{type:"string",description:"Your handle \u2014 must be an admin once governance is active"},limit:{type:"number",description:"Max events to show, newest first (default: 50, max: 200)"}},required:[]}},{name:"team_grant_scope",description:'Add or remove a team member to/from a named group (sub-team) on a shared brain. Group-scoped lessons (stored with group="...") only surface in smart_recall for members of that group (and admins). This is team-level visibility, orthogonal to lesson-level private. Admin-gated after the role model is bootstrapped. Example: team_grant_scope(handle="alice", group="security", assigned_by="bob") \u2014 bob must be admin.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Handle of the team member to add/remove"},group:{type:"string",description:'Group/sub-team name (e.g. "backend", "security", "platform")'},action:{type:"string",enum:["add","remove"],description:"add (default) or remove the member from the group"},assigned_by:{type:"string",description:"Handle of the admin performing the change (required after governance bootstrap)"}},required:["handle","group"]}},{name:"team_scopes",description:"List team groups and their members, or the groups a specific person belongs to. Pass handle to see one person's scopes; omit it to see all groups on the instance. Use to audit who can see group-scoped lessons.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},handle:{type:"string",description:"Optional \u2014 show only this person's group memberships"}},required:[]}},{name:"team_recall",description:"Recall lessons from a shared team brain, showing who learned what. Works on any shared instance (all team members using the same instance_id). Shows author, recency, and severity for each lesson. Use this to onboard new team members or find who knows about a topic.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:"Topic or keyword to filter lessons (optional)"},author:{type:"string",description:"Filter by author name (optional)"},limit:{type:"number",description:"Max lessons to return (default: 10)"}},required:[]}},{name:"team_synthesize",description:"Team Brain Synthesis \u2014 merge multiple contributors' lessons on the same topic into one canonical version. When 2+ developers store lessons for the same topic with different details, this proposes the best merged version. Shows: all contributions by author, what worked (consensus), what failed (union), canonical lesson to store. Use this when onboarding new team members or before documenting a process.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},topic:{type:"string",description:'Topic slug to synthesize (e.g. "deploy:api")'}},required:["topic"]}},{name:"memory_crystalize",description:"Compress the last 30-50 sessions and auto-learned lessons into a dense Memory Crystal. A crystal is a compact, structured summary of everything the brain learned \u2014 grouped by category (deploy, fix, debug, \u2026). Crystals survive session cleanup and appear in session_start once enough sessions have accumulated. Run this monthly or after a big milestone to preserve institutional knowledge. Returns a digest of what was crystallized.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},label:{type:"string",description:'Optional label for this crystal (e.g. "Q1 2026", "v2 launch"). Auto-generated from date if omitted.'}},required:[]}},{name:"team_crystallize",description:'Create a Team Crystal \u2014 the team-wide, causal counterpart to memory_crystalize. Where memory_crystalize compresses ONE brain by category, team_crystallize surfaces what a per-user memory structurally cannot: which fixes solved structurally SIMILAR problems across MULTIPLE people. A pattern only crystallizes when 2+ distinct authors independently converged on it \u2014 that cross-person signal is the moat against single-user "Dreaming"-style memory. Needs attributed lessons (learn_from_attempts(author=...) / team_learn). Surfaces in crystal_view. Example: team_crystallize() \u2192 "\u{1F9E9} pool \u2014 3 people converged (alice, bob, carol): bounded pool + timeout".',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the shared team brain instance"},min_authors:{type:"number",description:"Min distinct authors that must converge for a pattern to crystallize (default: 2, min: 2)"},label:{type:"string",description:'Optional label (e.g. "Q1 2026"). Auto-generated from date if omitted.'}},required:[]}},{name:"roadmap_add",description:"Add a new item to the persistent project roadmap stored in the Brain. Items survive across sessions and editors \u2014 the roadmap is always up to date. Use for features, bugs, refactors, or any planned work. Call roadmap_list to see all open items, roadmap_next to get the next actionable item.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},title:{type:"string",description:"Short title of the task/feature (3\u201310 words)"},description:{type:"string",description:"What needs to be done, acceptance criteria, context"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:'Tags for filtering (e.g. ["api", "web", "sdk", "infra"])'},milestone:{type:"string",description:"Milestone/epic this belongs to (optional)"}},required:["title"]}},{name:"roadmap_update",description:"Update the status, priority, or details of a roadmap item. Use to move items through the lifecycle: planned \u2192 in-progress \u2192 done (or blocked/cancelled). Also use to add notes/findings while working on an item.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},id:{type:"string",description:"Item ID returned by roadmap_add or roadmap_list"},status:{type:"string",enum:["planned","in-progress","done","blocked","cancelled"],description:"New status for the item"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Updated priority (optional)"},notes:{type:"string",description:"Progress notes, findings, or blockers (appended to existing notes)"},title:{type:"string",description:"Updated title (optional)"},description:{type:"string",description:"Updated description (optional)"}},required:["id"]}},{name:"roadmap_list",description:"List all roadmap items, optionally filtered by status, priority, tag, or milestone. Returns items sorted by priority then creation date. Called automatically by session_start to show open work.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},status:{type:"string",enum:["planned","in-progress","done","blocked","cancelled","open"],description:"Filter by status. Use 'open' to see planned+in-progress+blocked (default: open)"},tag:{type:"string",description:"Filter by tag (optional)"},milestone:{type:"string",description:"Filter by milestone (optional)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Filter by minimum priority (optional)"}},required:[]}},{name:"roadmap_next",description:"Get the single most important next actionable roadmap item. Returns the highest-priority in-progress item first, then planned items, sorted by priority. Call at session start to immediately know what to work on next.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},tag:{type:"string",description:"Filter by tag (optional)"}},required:[]}},{name:"brain_doctor",description:"Check the health of your AI Brain and get actionable recommendations. Reports: lesson count, context entries, last session age, open failures, quality score, effective IQ boost, stale index. Returns a prioritized list of issues with fix instructions.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},workspace_path:{type:"string",description:"Absolute path to workspace root \u2014 enables package.json analysis for openclaw cross-promo (optional)"}},required:[]}},{name:"brain_hygiene",description:"Autonomously sweep and maintain your Brain \u2014 flags stale lessons as provisional, archives long-dormant ones, and resolves contradictions where success clearly dominates failure. Safe to run on a schedule (weekly CI job) or on-demand before a big release. Lesson state lifecycle: active \u2192 provisional (confidence < threshold) \u2192 archived (stale + low-recall + old). Archived lessons are excluded from smart_recall but preserved for audit. dry_run=true (default false) shows what would change without writing anything.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dry_run:{type:"boolean",description:"Report changes without applying them (default false)"},provisional_threshold:{type:"number",description:"Confidence below which a lesson is flagged provisional (default 0.5)"},archive_days:{type:"number",description:"Days after which a provisional low-recall lesson is archived (default 30)"}},required:[]}},{name:"global_learn",description:'Store a lesson that applies across ALL your projects (cross-project knowledge). Idempotent: if a lesson with the same topic already exists, it is updated in place \u2014 no duplicates are created. Returns a confirmation with the stored lesson key. No rate limits. Global lessons are stored with the prefix cachly:global:lesson: and recalled from any instance via global_recall. Use for tool preferences, personal workflows, platform quirks, and universal gotchas. Example: global_learn(topic="bash:macos-arrays", lesson="Arrays work differently on macOS bash 3.2"). Use learn_from_attempts for project-specific session lessons; use team_learn to share lessons with your team.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (used for connection)"},topic:{type:"string",description:'Topic key in format "category:keyword"'},lesson:{type:"string",description:"The lesson content"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity (default: minor)"},tags:{type:"array",items:{type:"string"},description:"Optional tags"}},required:["topic","lesson"]}},{name:"global_recall",description:"Read-only retrieval of cross-project lessons stored via global_learn. No side effects. Returns a list of matching global lesson objects, each with topic, lesson text, severity, and tags. If no topic is provided, returns all global lessons (up to 50). If topic is provided, returns all lessons whose topic key contains that string (partial match). Use this for lessons that apply universally across all projects (tool quirks, shell gotchas, platform behavior). Use recall_best_solution instead for project-specific lessons; use team_recall for org-scoped lessons.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance (used for connection)"},topic:{type:"string",description:"Topic or keyword filter (optional)"}},required:[]}},{name:"publish_lesson",description:"Publish a lesson to the Cachly Public Brain (anonymized community knowledge base). Published lessons can be imported by other developers via import_public_brain. PII is stripped automatically. Visible under the framework/category tag. Returns { lesson_id, topic, framework, published_at } confirming the publish. Irreversible \u2014 once published to the public brain, lessons cannot be deleted via the MCP interface. Use learn_from_attempts or global_learn for private lessons; use syndicate for anonymized global sharing without framework tagging.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:"Topic key (used as public category)"},lesson:{type:"string",description:"Lesson to publish (PII will be stripped)"},framework:{type:"string",description:"Framework/platform tag (nextjs, fastapi, go, docker, etc.)"},severity:{type:"string",enum:["critical","major","minor"],description:"Severity"}},required:["topic","lesson"]}},{name:"import_public_brain",description:"Import community lessons from the Cachly Public Brain for a framework. Non-destructive: existing lessons with the same topic key are not overwritten. Returns the count of lessons imported and their topic slugs. Available frameworks: nextjs, fastapi, go, docker, kubernetes, react, typescript, python, rust, laravel, rails, spring. Use this to bootstrap a new brain with battle-tested community knowledge before your first session_start. Use publish_lesson to contribute your own lessons to the Public Brain; use learn_from_attempts for storing lessons from your own sessions.",inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance to import into"},framework:{type:"string",description:"Framework/platform to import lessons for"},limit:{type:"number",description:"Max lessons to import (default: 20)"}},required:["framework"]}},{name:"recall_at",description:'Brain Archaeology \u2014 see what a lesson looked like at a specific point in time. "What did we know about deployments 3 months ago?" Returns the history of a topic filtered to entries before the given date. Shows how the lesson evolved: failure \u2192 partial \u2192 success. Also useful to understand WHY old code decisions were made.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},topic:{type:"string",description:'Topic slug to look up, e.g. "deploy:api"'},date:{type:"string",description:'ISO date string (e.g. "2026-01-15") \u2014 returns entries stored BEFORE this date'}},required:["topic","date"]}},{name:"trace_dependency",description:'Causal Chain \u2014 find all lessons that depend on a given prerequisite. "What lessons are affected if node version changes?" When a dependency changes (new version, different provider, new OS), call this to see which lessons need review. Lessons store dependencies via the depends_on field in learn_from_attempts.',inputSchema:{type:"object",properties:{instance_id:{type:"string",description:"UUID of the cache instance."},dependency:{type:"string",description:'Dependency to trace (e.g. "node:>=20", "docker:running", "wireguard:active")'},mark_review:{type:"boolean",description:"If true, marks all dependent lessons as needs_review (default: false)"}},required:["dependency"]}},{name:"list_orgs",description:"List your Cachly organizations. Returns each org with plan, seat count, and member info. Organizations are free. A team of up to 5 people buys the Brain tier Team (Team \u20AC49/mo, everything included). Org plans: Business \u20AC199 (SSO, 20 seats), Enterprise (custom).",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_org",description:"Create a new Cachly organization for team collaboration; organizations are free. After creation, invite team members with invite_member. Up to 5 people share the Brain tier Team (\u20AC49/mo, everything included). Org plans: Business (\u20AC199/mo, 20 seats, SSO), Enterprise (custom).",inputSchema:{type:"object",properties:{name:{type:"string",description:'Organization display name (e.g. "Acme Engineering")'},slug:{type:"string",description:'URL-safe slug (e.g. "acme-eng"). Auto-generated from name if omitted.'}},required:["name"]}},{name:"invite_member",description:"MUTATION \u2014 sends an invite email immediately and cannot be undone via MCP. Invite a team member to a Cachly organization by email. Requires the caller to be an admin or owner of the organization. Valid roles: admin (manage members + instances), member (read + cache ops). Default role: member. Returns an error if the email is already a member or has a pending invite.",inputSchema:{type:"object",properties:{org_id:{type:"string",description:"UUID of the organization"},email:{type:"string",description:"Email address to invite"},role:{type:"string",enum:["admin","member"],description:"Role for the invited member (default: member)"}},required:["org_id","email"]}},{name:"get_org_plan",description:"Get the current org plan, seat usage, and billing info for an organization. Shows: plan name, price, seats used/max, next billing date. To upgrade: use the billing portal URL returned by this tool.",inputSchema:{type:"object",properties:{org_id:{type:"string",description:"UUID of the organization"}},required:["org_id"]}},{name:"setup_ai_memory",description:`One-shot setup of the cachly 3-layer AI Memory system for a project.
|
|
2
2
|
|
|
3
3
|
Layer 1 \u2014 Storage: your cachly instance (Valkey, persistent across sessions)
|
|
4
4
|
Layer 2 \u2014 Tools: learn_from_attempts + recall_best_solution + smart_recall (the memory API)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function s(e){const n=e.getFullYear(),t=String(e.getMonth()+1).padStart(2,"0"),a=String(e.getDate()).padStart(2,"0");return`${n}-${t}-${a}`}function o(e,n){const t=new Date(e.getTime());return t.setDate(t.getDate()-n),t}function d(e,n){const t=new Date(e.getTime());return t.setMonth(t.getMonth()-n),t}function c(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}`}const r=e=>s(e),N=(e,n)=>`${n} week${n===1?"":"s"} before ${s(e)}`,E=(e,n)=>`${n} Wochen vor dem ${s(e)}`;function W(e,n){return o(e,(e.getDay()-n+7)%7||7)}const p={sonntag:0,montag:1,dienstag:2,mittwoch:3,donnerstag:4,freitag:5,samstag:6,sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6,sun:0,mon:1,tue:2,tues:2,wed:3,thu:4,thur:4,thurs:4,fri:5,sat:6},w=(e,n)=>{const t=p[n[2].toLowerCase()];return t===void 0?null:r(W(e,t))},v=String.raw`(?!\s+(?:im|des|eines|jedes|of|in)\b)`,M=[{re:/\bvorgestern\b/gi,angabe:e=>r(o(e,2))},{re:/\buebermorgen\b|\bübermorgen\b/gi,angabe:e=>r(o(e,-2))},{re:/\bgestern\b/gi,angabe:e=>r(o(e,1))},{re:/\bmorgen\b/gi,angabe:e=>r(o(e,-1))},{re:/\bheute\b/gi,angabe:e=>r(e)},{re:/\bvor\s+(\d{1,3})\s+Tagen\b/gi,angabe:(e,n)=>r(o(e,Number(n[1])))},{re:/\bvor\s+(\d{1,3})\s+Wochen\b/gi,angabe:(e,n)=>E(e,Number(n[1]))},{re:/\bvor\s+(\d{1,3})\s+Monaten\b/gi,angabe:(e,n)=>c(d(e,Number(n[1])))},{re:/\bvor\s+einer\s+Woche\b/gi,angabe:e=>`eine Woche vor dem ${s(e)}`},{re:/\bvor\s+einem\s+Monat\b/gi,angabe:e=>c(d(e,1))},{re:/\b(letztes|vergangenes|voriges|letzten|vergangenen|vorigen)\s+Wochenende\b/gi,angabe:e=>`das Wochenende vor dem ${s(e)}`},{re:/\b(letzte|letzten|letzter|vorige|vorigen)\s+Woche\b/gi,angabe:e=>`die Woche vor dem ${s(e)}`},{re:/\b(letzten|letzter|vorigen)\s+Monat\b/gi,angabe:e=>c(d(e,1))},{re:new RegExp(String.raw`\b(letzten|vergangenen|vorigen)\s+(Montag|Dienstag|Mittwoch|Donnerstag|Freitag|Samstag|Sonntag)\b${v}`,"gi"),angabe:w},{re:/\bthe\s+day\s+before\s+yesterday\b/gi,angabe:e=>r(o(e,2))},{re:/\byesterday\b/gi,angabe:e=>r(o(e,1))},{re:/\btomorrow\b/gi,angabe:e=>r(o(e,-1))},{re:/\btoday\b/gi,angabe:e=>r(e)},{re:/\b(\d{1,3})\s+days?\s+ago\b/gi,angabe:(e,n)=>r(o(e,Number(n[1])))},{re:/\b(\d{1,3})\s+weeks?\s+ago\b/gi,angabe:(e,n)=>N(e,Number(n[1]))},{re:/\b(\d{1,3})\s+months?\s+ago\b/gi,angabe:(e,n)=>c(d(e,Number(n[1])))},{re:/\blast\s+weekend\b/gi,angabe:e=>`the weekend before ${s(e)}`},{re:/\blast\s+week\b/gi,angabe:e=>`the week before ${s(e)}`},{re:/\blast\s+month\b/gi,angabe:e=>c(d(e,1))},{re:new RegExp(String.raw`\b(last)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b${v}`,"gi"),angabe:w},{re:new RegExp(String.raw`\b([Ll]ast)\s+(Mon|Tues?|Wed|Thu(?:rs?)?|Fri|Sat|Sun)\b${v}`,"g"),angabe:w}],y=String.raw`\((?:\d{4}-\d{2}(?:-\d{2})?|(?:the week(?:end)? before|\d{1,3} weeks? before|die Woche vor dem|das Wochenende vor dem|eine Woche vor dem|\d{1,3} Wochen vor dem) \d{4}-\d{2}-\d{2})\)`,T=new RegExp(String.raw`^\s*${y}`),$=new RegExp(y,"g");function D(e){const n=[];for(const t of[/```[\s\S]*?```/g,/`[^`\n]*`/g,/"[^"\n]*"/g,/„[^“\n]*“/g,/«[^»\n]*»/g])for(const a of e.matchAll(t))a.index!==void 0&&n.push([a.index,a.index+a[0].length]);return n}const S=(e,n,t)=>e.some(([a,u])=>n<u&&t>a);function k(e,n){if(!e)return e;const t=D(e),a=[],u=[];for(const{re:g,angabe:f}of M){g.lastIndex=0;for(const m of e.matchAll(g)){const b=m.index;if(b===void 0)continue;const i=b+m[0].length;if(S(t,b,i)||S(u,b,i)||T.test(e.slice(i))||Number.isNaN(n.getTime()))continue;const l=f(n,m);!l||l.includes("NaN")||(u.push([b,i]),a.push({ende:i,angabe:l}))}}if(a.length===0)return e;a.sort((g,f)=>f.ende-g.ende);let h=e;for(const g of a)h=`${h.slice(0,g.ende)} (${g.angabe})${h.slice(g.ende)}`;return h}function z(e,n){if(!e)return 0;const t=(e.match($)??[]).length;return(k(e,n).match($)??[]).length-t}export{k as normalisiereZeit,z as zaehleZeitangaben};
|
package/dist/src/zugang.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{istPlatzhalter as o}from"./credentials.js";function c(e){if(typeof e!="string")return"";const t=e.trim();return t&&!o(t)?t:""}const
|
|
1
|
+
import{istPlatzhalter as o}from"./credentials.js";function c(e){if(typeof e!="string")return"";const t=e.trim();return t&&!o(t)?t:""}const l=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function s(e){return l.test(c(e))}const a="npx @cachly-dev/mcp-server@latest claim";function u(e){return["","","---",`\u2139\uFE0F **cachly:** no API key was found, so a test Brain was created on EU servers \u2014 no sign-up. Tell the user once: it keeps working without an account (${e.tarifEndetAm&&/^\d{4}-\d{2}-\d{2}/.test(e.tarifEndetAm)?`Solo tier until ${e.tarifEndetAm.slice(0,10)}`:"14 days of Solo tier"}, then the free tier, same key). To keep this Brain and its lessons in their own cachly account, they run \`${a}\` in a terminal and sign in \u2014 the Brain moves over and gets a new key.`].join(`
|
|
2
2
|
`)}let r=null;function d(){r=null}async function g(e){if(e.schluessel)return e.werkzeug();if(s(e.konfigurierteInstanz)||s(e.aufrufInstanz))return e.anmelden();const t=r===null;t&&(r=e.holeSofortTest());const n=await r;if(!n)return e.anmelden();if(!t)return e.werkzeug();e.ablagen.setzeSchluessel(n.apiKey),e.ablagen.setEmbedJwt(n.apiKey),e.ablagen.saveApiKey(n.apiKey),e.ablagen.merkeInstanz(n.instanzId),await e.ablagen.persistApiKeyToConfig(n.apiKey),await e.ablagen.persistInstanceIdToConfig(n.instanzId),e.meldeEreignis("instant_trial_started",{tool:e.werkzeugName,instance_id:n.instanzId}),(e.protokoll??(i=>{process.stderr.write(i)}))(`
|
|
3
3
|
cachly: no API key found \u2014 created a test Brain on EU servers (instance ${n.instanzId}).
|
|
4
4
|
cachly: the key is stored in ~/.cachly/credentials.json. Keep this Brain in your own account: ${a}
|
|
5
5
|
|
|
6
|
-
`);try{return await e.werkzeug()+
|
|
6
|
+
`);try{return await e.werkzeug()+u(n)}finally{try{e.neuesBrain?.(n.instanzId)}catch{}}}export{a as CLAIM_BEFEHL,d as _zugangZuruecksetzen,c as echterWert,s as istInstanzKennung,g as sichereZugang,u as sofortTestHinweis};
|
package/glama.json
CHANGED
|
@@ -38,7 +38,7 @@ ${re(s)}
|
|
|
38
38
|
`,"utf-8");let n=await vc(e,"utf-8");if(Buffer.byteLength(n,"utf-8")>Nc){let s=n.split(`
|
|
39
39
|
`).filter(Boolean).slice(-Rc).join(`
|
|
40
40
|
`)+`
|
|
41
|
-
`,i=e+".tmp";await xc(i,s,"utf-8"),await Sc(i,e)}}catch{}}function ls(t,e,n=fetch){return!t.instanceId||!t.jwt||process.env.CACHLY_NO_TELEMETRY==="1"?Promise.resolve():n(`${t.apiUrl}/api/v1/instances/${t.instanceId}/ambient-events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.jwt}`},body:JSON.stringify({events:[e]}),signal:AbortSignal.timeout(3e3)}).then(()=>{},()=>{})}import{readdirSync as Pc,readFileSync as Mc}from"node:fs";import{homedir as jc}from"node:os";import{join as v}from"node:path";function xe(t){if(typeof t!="string")return"";let e=t.trim();return e&&!ft(e)?e:""}var Oc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kt(t){return Oc.test(xe(t))}var Cc="npx @cachly-dev/mcp-server@latest claim";function gs(t){return["","","---",`\u2139\uFE0F **cachly:** no API key was found, so a test Brain was created on EU servers \u2014 no sign-up. Tell the user once: it keeps working without an account (${t.tarifEndetAm&&/^\d{4}-\d{2}-\d{2}/.test(t.tarifEndetAm)?`
|
|
41
|
+
`,i=e+".tmp";await xc(i,s,"utf-8"),await Sc(i,e)}}catch{}}function ls(t,e,n=fetch){return!t.instanceId||!t.jwt||process.env.CACHLY_NO_TELEMETRY==="1"?Promise.resolve():n(`${t.apiUrl}/api/v1/instances/${t.instanceId}/ambient-events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.jwt}`},body:JSON.stringify({events:[e]}),signal:AbortSignal.timeout(3e3)}).then(()=>{},()=>{})}import{readdirSync as Pc,readFileSync as Mc}from"node:fs";import{homedir as jc}from"node:os";import{join as v}from"node:path";function xe(t){if(typeof t!="string")return"";let e=t.trim();return e&&!ft(e)?e:""}var Oc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kt(t){return Oc.test(xe(t))}var Cc="npx @cachly-dev/mcp-server@latest claim";function gs(t){return["","","---",`\u2139\uFE0F **cachly:** no API key was found, so a test Brain was created on EU servers \u2014 no sign-up. Tell the user once: it keeps working without an account (${t.tarifEndetAm&&/^\d{4}-\d{2}-\d{2}/.test(t.tarifEndetAm)?`Solo tier until ${t.tarifEndetAm.slice(0,10)}`:"14 days of Solo tier"}, then the free tier, same key). To keep this Brain and its lessons in their own cachly account, they run \`${Cc}\` in a terminal and sign in \u2014 the Brain moves over and gets a new key.`].join(`
|
|
42
42
|
`)}function _e(t=process.env){return{env:t,heim:t.HOME||t.USERPROFILE||jc(),projekt:t.CLAUDE_PROJECT_DIR||process.cwd()}}function Y(t){try{return JSON.parse(Mc(t,"utf8"))}catch{return null}}function fs(t){return[v(t.heim,".claude","mcp.json"),v(t.projekt,".mcp.json"),v(t.heim,".cursor","mcp.json"),v(t.heim,".codeium","windsurf","mcp_config.json")].map(e=>{let n=Y(e)?.mcpServers?.cachly?.env;return n&&typeof n=="object"?n:{}})}function ds(...t){for(let e of t){let n=xe(e);if(n)return n}return""}function Ae(t){return ds(t.env.CLAUDE_PLUGIN_OPTION_API_KEY,Vr({env:t.env,home:t.heim,cwd:t.projekt}),...fs(t).map(e=>e.CACHLY_JWT))}function Te(t){return ds(t.env.CLAUDE_PLUGIN_OPTION_INSTANCE_ID,t.env.CACHLY_BRAIN_INSTANCE_ID,we({home:t.heim}),...fs(t).map(e=>e.CACHLY_BRAIN_INSTANCE_ID))}function hs(t){let e=xe(t.env.CLAUDE_PLUGIN_ROOT);if(!e)return"unbekannt";let n=Y(v(e,".claude-plugin","plugin.json"))?.version;return typeof n=="string"&&/^\d[0-9A-Za-z.+-]{0,30}$/.test(n)?n:"unbekannt"}var wt="cachly-ambient-";function ps(t){return[v(t.projekt,".cursor","hooks.json"),v(t.heim,".cursor","hooks.json")].some(e=>{let n=Y(e)?.hooks;return!!n&&typeof n=="object"&&Object.values(n).some(r=>Array.isArray(r)&&r.some(s=>String(s?.command??"").includes(wt)))})}function Hc(t){let e=t;return[e?.command,e?.bash,e?.powershell].some(n=>String(n??"").includes(wt))}function ms(t){let e=t.env.COPILOT_HOME?v(t.env.COPILOT_HOME,"hooks"):v(t.heim,".copilot","hooks");return[v(t.projekt,".github","hooks"),e].some(n=>{let r;try{r=Pc(n).filter(s=>s.endsWith(".json"))}catch{return!1}return r.some(s=>{let i=Y(v(n,s))?.hooks;return!!i&&typeof i=="object"&&Object.values(i).some(o=>Array.isArray(o)&&o.some(Hc))})})}function bs(t,e){return[v(e.projekt,".claude","settings.json"),v(e.projekt,".claude","settings.local.json"),v(e.heim,".claude","settings.json")].some(n=>{let r=Y(n)?.hooks?.[t];return Array.isArray(r)&&r.some(s=>Array.isArray(s?.hooks)&&s.hooks.some(i=>String(i?.command??"").includes(wt)))})}import{createHash as $c}from"node:crypto";import{mkdirSync as Uc,readFileSync as Bc,renameSync as Wc,rmSync as ks,writeFileSync as Kc}from"node:fs";import{tmpdir as Fc}from"node:os";import{join as St}from"node:path";var Q="--cursor";var Et={sessionStart:"sessionStart",SessionStart:"sessionStart",beforeSubmitPrompt:"beforeSubmitPrompt",UserPromptSubmit:"beforeSubmitPrompt",postToolUse:"postToolUse",PostToolUse:"postToolUse"};function xt(t){let e=t?.cursor_version;return typeof e=="string"&&e.trim()!==""}function ze(t,e){let n=t?.hook_event_name??e.find(r=>Object.hasOwn(Et,r));return n&&Object.hasOwn(Et,n)?Et[n]:null}function Dc(t,e){let n=e.conversation_id??e.session_id,r=e.workspace_roots?.[0];return t==="sessionStart"?{hook_event_name:"SessionStart",source:"startup",session_id:n,cwd:r}:{hook_event_name:"UserPromptSubmit",prompt:e.prompt??"",session_id:n,cwd:r}}function R(t){if(!t)return"";try{let e=JSON.parse(t)?.hookSpecificOutput?.additionalContext;return typeof e=="string"?e:""}catch{return""}}function vt(t,e){return t==="beforeSubmitPrompt"?JSON.stringify({continue:!0}):e?JSON.stringify({additional_context:e}):"{}"}function X(t){return t?vt(t,""):""}var Gc=St(Fc(),"cachly-cursor-einblendung");function H(t,e=Gc){return St(e,`${$c("sha256").update(t).digest("hex").slice(0,32)}.json`)}function Ie(t,e,n){if(!n){ks(t,{force:!0});return}Uc(St(t,".."),{recursive:!0});let r={generation_id:e??null,kontext:n,at:Date.now()};Kc(t,JSON.stringify(r),"utf8")}function ys(t){try{let e=JSON.parse(Bc(t,"utf8"));return e&&typeof e.kontext=="string"?e:null}catch{return null}}function _t(t,e){let n=e??null,r=ys(t);if(!r||r.generation_id!==n)return"";let s=`${t}.${process.pid}.${Date.now()}`;try{Wc(t,s)}catch{return""}let i=ys(s);return ks(s,{force:!0}),i&&i.generation_id===n?i.kontext:""}async function ws(t){let e=ze(t.payload,t.args);if(!e)return"";try{let n=t.payload??{};if(e==="postToolUse")return n.conversation_id?vt(e,_t(H(n.conversation_id,t.ablageOrdner),n.generation_id)):X(e);if(e==="beforeSubmitPrompt"&&!n.conversation_id)return X(e);let r=Dc(e,n),s=R(await t.claudeLauf(JSON.stringify(r),r.hook_event_name));return e==="beforeSubmitPrompt"&&Ie(H(n.conversation_id,t.ablageOrdner),n.generation_id,s),vt(e,s)}catch{return X(e)}}import{tmpdir as Zc}from"node:os";import{join as Vc}from"node:path";var Le="--copilot";var At={sessionStart:"sessionStart",SessionStart:"sessionStart",userPromptSubmitted:"userPromptSubmitted",UserPromptSubmit:"userPromptSubmitted",postToolUse:"postToolUse",PostToolUse:"postToolUse"};function Tt(t,e){let n=t?.hook_event_name??e.find(r=>Object.hasOwn(At,r));return n&&Object.hasOwn(At,n)?At[n]:null}function Jc(t){return typeof t?.hook_event_name=="string"&&t.hook_event_name!==""?"vscode":"cli"}function vs(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e!==""?e:void 0}function qc(t,e){let n=vs(e),r=typeof e.cwd=="string"?e.cwd:void 0;return t==="sessionStart"?{hook_event_name:"SessionStart",source:typeof e.source=="string"?e.source:"startup",session_id:n,cwd:r}:{hook_event_name:"UserPromptSubmit",prompt:typeof e.prompt=="string"?e.prompt:"",session_id:n,cwd:r}}var Yc={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",postToolUse:"PostToolUse"};function Es(t,e,n){return n?e==="cli"?t==="userPromptSubmitted"?"{}":JSON.stringify({additionalContext:n}):JSON.stringify({hookSpecificOutput:{hookEventName:Yc[t],additionalContext:n}}):"{}"}function zt(t){let e=t?.timestamp;return typeof e=="string"&&e!==""||typeof e=="number"}var Xc=Vc(Zc(),"cachly-copilot-einblendung");async function Ss(t){let e=Tt(t.payload,t.args);if(!e)return"";try{let n=t.payload??{},r=Jc(n),s=vs(n),i=t.ablageOrdner??Xc;if(e==="postToolUse")return r==="vscode"||!s?"{}":Es(e,r,_t(H(s,i),void 0));let o=e==="userPromptSubmitted"&&r==="cli";if(o){if(!s)return"{}";Ie(H(s,i),void 0,"")}let a=qc(e,n),u=R(await t.claudeLauf(JSON.stringify(a),a.hook_event_name));return o&&Ie(H(s,i),void 0,u),Es(e,r,u)}catch{return"{}"}}var It="--codex",Qc=["SessionStart","UserPromptSubmit"];var xs=new Set(Qc);function eu(t,e){let n=t?.hook_event_name??e.find(r=>xs.has(r));return n&&xs.has(n)?n:null}function tu(t,e){let n=typeof e.session_id=="string"?e.session_id:void 0,r=typeof e.cwd=="string"?e.cwd:void 0;return t==="SessionStart"?{hook_event_name:"SessionStart",source:typeof e.source=="string"?e.source:"startup",session_id:n,cwd:r}:{hook_event_name:"UserPromptSubmit",prompt:typeof e.prompt=="string"?e.prompt:"",session_id:n,cwd:r}}async function _s(t){let e=eu(t.payload,t.args);if(!e)return"";try{let n=tu(e,t.payload??{});return j(e,R(await t.claudeLauf(JSON.stringify(n),e)))}catch{return""}}var Ne="--gemini",nu=["SessionStart","BeforeAgent"],As=new Set(nu);function Lt(t,e){let n=t?.hook_event_name??e.find(r=>As.has(r));return n&&As.has(n)?n:null}function ru(t,e){let n=typeof e.session_id=="string"?e.session_id:void 0,r=typeof e.cwd=="string"?e.cwd:void 0;return t==="SessionStart"?{hook_event_name:"SessionStart",source:typeof e.source=="string"?e.source:"startup",session_id:n,cwd:r}:{hook_event_name:"UserPromptSubmit",prompt:typeof e.prompt=="string"?e.prompt:"",session_id:n,cwd:r}}function su(t,e){return e?JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:e}}):"{}"}async function Ts(t){let e=Lt(t.payload,t.args);if(!e)return"";try{let n=ru(e,t.payload??{});return su(e,R(await t.claudeLauf(JSON.stringify(n),n.hook_event_name)))}catch{return"{}"}}var au="https://api.cachly.dev",zs=5e3,Rt="ambient-auffrischen",Is=new Set(["SessionStart","UserPromptSubmit","PreToolUse","Stop"]);async function cu(t,e){if(!t.args.includes(Q)&&(ze(e,t.args)!=="sessionStart"||ps(t.umfeld)))return"";let r=t.args.filter(s=>s==="--plugin");return ws({payload:e,args:t.args,claudeLauf:(s,i)=>Ot({...t,raw:s,args:[i,...r]}),ablageOrdner:t.cursorAblage})}function uu(t,e){let n=(r,s)=>Ot({...t,raw:r,args:[s]});return t.args.includes(Le)?Ss({payload:e,args:t.args,claudeLauf:n,ablageOrdner:t.copilotAblage}):t.args.includes(It)?_s({payload:e,args:t.args,claudeLauf:n}):t.args.includes(Ne)?Ts({payload:e,args:t.args,claudeLauf:n}):null}function lu(t,e){return t.includes(Q)||xt(e)?"cursor":t.includes(Le)?"copilot":t.includes(It)?"codex":t.includes(Ne)?"gemini":zt(e)?"vscode":"claude"}async function gu(t){let e=await ns({apiUrl:t.apiUrl,version:hs(t.umfeld),home:t.umfeld.heim,env:{...t.umfeld.env,CACHLY_QUELLE:"claude-code-plugin"},fristMs:zs,anfrageMs:zs,abkuehlungMs:es,holen:t.fetchFn});if(e.art==="vorhanden")return{apiKey:e.apiKey,instanzId:e.instanzId,hinweis:""};if(e.art!=="angelegt")return null;if(Se(t.umfeld.env)){let n={apiUrl:t.apiUrl,jwt:e.test.apiKey,instanceId:e.test.instanzId};t.selbst&&(t.nebenlauf??at)(n,[t.selbst,q,t.umfeld.projekt],{zweck:q,ordner:ou()})||yt({instanzId:e.test.instanzId,projekt:t.umfeld.projekt},{home:t.umfeld.heim})}return{apiKey:e.test.apiKey,instanzId:e.test.instanzId,hinweis:gs(e.test)}}function fu(t,e){let n=e.replace(/^\s+/,"");if(!t)return j("SessionStart",n);try{let r=JSON.parse(t),s=r.hookSpecificOutput?.additionalContext;return!r.hookSpecificOutput||typeof s!="string"?t:(r.hookSpecificOutput.additionalContext=`${n}
|
|
43
43
|
|
|
44
44
|
${s}`,JSON.stringify(r))}catch{return t}}async function Ot(t){try{let e=pe(t.raw),n={...t,editor:t.editor??lu(t.args,e)};if(n.args.includes(Q)||xt(e))return await cu(n,e);let r=uu(n,e);if(r)return await r;let s=e?.hook_event_name??n.args.find(f=>Is.has(f))??n.umfeld.env.CACHLY_HOOK_EVENT??"";if(zt(e)&&(s!=="SessionStart"&&s!=="UserPromptSubmit"||ms(n.umfeld))||n.args.includes("--plugin")&&s&&bs(s,n.umfeld))return"";let i=null;if(s==="Stop"&&e?.transcript_path)try{i=iu(e.transcript_path,"utf-8").split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cachly-dev/mcp-server",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.219",
|
|
4
4
|
"mcpName": "io.github.cachly-dev/mcp-server",
|
|
5
5
|
"description": "Solve it once. From then on, your AI knows. Experience for coding agents, EU-hosted: an MCP server for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run.",
|
|
6
6
|
"type": "module",
|
package/server.json
CHANGED
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
"url": "https://github.com/cachly-dev/cachly-mcp",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.10.
|
|
9
|
+
"version": "0.10.219",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"name": "@cachly-dev/mcp-server",
|
|
14
14
|
"identifier": "@cachly-dev/mcp-server",
|
|
15
|
-
"version": "0.10.
|
|
15
|
+
"version": "0.10.219",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|