@cachly-dev/mcp-server 0.10.281 → 0.10.283

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.
@@ -1,33 +1,34 @@
1
- import{readFileSync as Oe}from"node:fs";import{bauabdruck as Ee,formatiereBauabdruck as Ce}from"../bauabdruck.js";import{beurteileSpeicher as Te,zahlAusInfo as ge}from"../speicherlage.js";import{beurteileDeckung as De}from"../eingaenge.js";import{VEKTOR_NACHTRAG as Me,NAME_VEKTOR_NACHTRAG as ze,ZWEIT_VEKTOR_NACHTRAG as Ie}from"../bedeutung.js";import{join as B}from"node:path";import{calculateConfidence as ee,CONFIDENCE_STALE_VALUE as ce,CONFIDENCE_WARN_VALUE as Pe,CONFIDENCE_WARN_DAYS as we,CONFIDENCE_STALE_DAYS as ye}from"../confidence.js";import{safeJsonParse as z,leseOderNull as _e,darfHeraus as Fe,teamweitLesbar as K}from"../utils.js";import{ersparteMinuten as Be,istStarterLektion as Ue,fmtStunden as $e}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Ke,buildClaudeMdBlock as Je,setzeAnweisungsblock as He}from"../projektdateien.js";import{aussetzerEinzelheit as Ge,aussetzerErklaerung as ve,leseVermerke as qe}from"../aussetzer.js";import{schwaerzeFelder as We}from"../geheimnis-filter.js";import{VERDACHT_TAG as be,pruefeFelder as Ve,verdachtsWarnung as Ye}from"../tuersteher.js";import{fuerEigenenSpeicher as le,fuerWeitergabe as Ze,fuerZusammenfassung as ke,hinweise as ue,markiert as Xe,markierungsWarnung as Qe,weitergabeHinweis as et}from"../schreibtor.js";import{holeRolle as H,istMitglied as he,rolleFuer as Se,lerneUeberApi as tt,bestaetigeUeberApi as st,ROLLEN_SEITE as Z}from"../rolle.js";const Lt=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"]),W={admin:4,reviewer:3,contributor:2,viewer:1},F={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},te={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"},G=w=>`cachly:team:roles:${w}`;async function V(w,m,y){return await w.hget(G(m),y.toLowerCase()).catch(()=>null)}async function nt(w,m,y){const R=await H(m);return R?R.role:y?V(w,m,y):null}const de={owner:"owner of this brain",org_admin:"organisation admin",assigned:"assigned by an admin",default:"default for members"};function pe(w){const m=de[w.source]??w.source;return m?`${w.role} (${m})`:w.role}function X(w,m){return w?(W[w]??0)>=(W[m]??0):!1}function ot(w){return w==="admin"||w==="reviewer"?"senior":"peer"}async function at(w,m){if(await H(m))return!0;const y=await w.hgetall(G(m)).catch(()=>({}));return Object.values(y).includes("admin")}async function me(w,m,y,R,a){const t=await H(m);if(t)return X(t.role,R)?null:[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${R}\` ${F[R]} (your role: ${F[t.role]} ${pe(t)}).`,"",`Roles are set by the brain owner or an organisation admin in the dashboard: ${Z}`,"_Run `team_whoami` to check your role._"].join(`
2
- `);if(!await at(w,m))return null;const n=y?await V(w,m,y):null;if(X(n,R))return null;const r=n?`${F[n]} ${n}`:"no role";return[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${R}\` ${F[R]} (you have: ${r}).`,"","Ask an admin to grant it:",`\`team_assign_role(instance_id="${m}", handle="${y||"<your-handle>"}", role="${R}", assigned_by="<admin>")\``,"_Governance is active on this brain. Run `team_whoami` to check your role._"].join(`
3
- `)}async function xe(w,m,y){const R=`cachly:team:audit:${m}`,a=JSON.stringify({...y,ts:new Date().toISOString()});await w.rpush(R,a).catch(()=>{}),await w.ltrim(R,-500,-1).catch(()=>{}),await w.expire(R,365*2*86400).catch(()=>{})}const rt="cachly:team:review_mode",it="cachly:lesson:proposed:",ct=90*86400;async function lt(w,m){const y=await w.get(rt).catch(()=>null);return y==="1"||y==="true"||y==="on"}async function ut(w,m,y){const R={...y,proposed_at:new Date().toISOString(),status:"pending"};await w.set(`${it}${m}`,JSON.stringify(R),"EX",ct).catch(()=>{});const a=typeof y.author=="string"&&y.author?` by **${y.author}**`:"";return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${m}\`${a} 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(`
4
- `)}const se=w=>`cachly:team:groups:${w}`,Q=(w,m)=>`cachly:team:group:${w}:${m.toLowerCase()}`;async function Ae(w,m,y){const R=await w.smembers(se(m)).catch(()=>[]),a=new Set;for(const t of R)await w.sismember(Q(m,t),y.toLowerCase()).catch(()=>0)&&a.add(t.toLowerCase());return a}function Re(w,m,y){return!w||y?!0:m.has(w.toLowerCase())}const ne=Object.freeze({scopes:new Set,isAdmin:!1});async function jt(w,m,y){const R=await H(m),a=(y??"").trim();if(!a)return R?.role==="admin"?{scopes:new Set,isAdmin:!0}:ne;const t=await Ae(w,m,a).catch(()=>new Set),n=R?R.role==="admin":await V(w,m,a).catch(()=>null)==="admin";return{scopes:t,isAdmin:n}}function ht(w,m){if(!Fe(w))return!1;const y=typeof w.group=="string"?w.group.trim():w.group?String(w.group):"";return Re(y||null,m.scopes,m.isAdmin)}function Nt(w,m=ne){const y=new Map;return async R=>{const a=y.get(R);if(a!==void 0)return a;const t=await w.get(`cachly:lesson:best:${R}`).catch(()=>null),n=t===null||ht(_e(t),m);return y.set(R,n),n}}function Le(w,m,y){const R=w.filter(t=>!m.has(t)),a=R.slice(0,y);return{namen:a,rest:w.length-a.length,davonVerborgen:w.length-R.length}}async function Ot(w,m,y,R){switch(w){case"sync_file_changes":{const{instance_id:a,changed_files:t,git_diff_stat:n,commit_msg:r}=m,i=le({changed_files:t,git_diff_stat:n,commit_msg:r}),{changed_files:e,git_diff_stat:o,commit_msg:l}=i.felder,c=await y(a),s={ts:new Date().toISOString(),files:e,commit_msg:l,diff_stat:o?.slice(0,500),...i.verdacht.length?{verdacht:i.verdacht}:{}};await c.lpush("cachly:session:file_changes",JSON.stringify(s)),await c.ltrim("cachly:session:file_changes",0,99),await c.expire("cachly:session:file_changes",30*86400);const d=[],u=c.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((j,A)=>{u.on("data",x=>d.push(...x)),u.on("end",j),u.on("error",A)});const _=[],k=d.length>0?await c.mget(...d):[];for(const j of k){const A=K(j);if(!A)continue;const x=A.topic.toLowerCase().split(/[:\-_]/);if(e.some(S=>{const g=S.split("/").pop()?.replace(/\.[^.]+$/,"").toLowerCase()??"";return x.some(h=>h.length>3&&g.includes(h))||(A.file_paths??[]).some(h=>S.includes(h)||h.includes(S))})){const S=A.outcome==="success"?"\u2705":"\u26A0\uFE0F";_.push(` ${S} \`${A.topic}\` \u2014 ${A.what_worked.slice(0,80)}`)}}const b=[`\u{1F4C1} **File sync recorded**: ${e.length} files`,l?`\u{1F4DD} Commit: "${l}"`:"","",`**Changed:** ${e.slice(0,8).map(j=>`\`${j}\``).join(", ")}${e.length>8?` +${e.length-8} more`:""}`,"",...ue(i,"notiz")];return _.length>0?b.push(`\u{1F9E0} **Relevant brain lessons (${_.length}):**`,..._):b.push("\u{1F4A1} No existing lessons match these files yet. Add them with `learn_from_attempts`."),b.filter(Boolean).join(`
5
- `)}case"team_learn":{const a=We(m).felder,t=Ve(a),{instance_id:n,author:r,topic:i,outcome:e,what_worked:o,what_failed:l,severity:c,file_paths:s,commands:d,tags:u}=a;if(!r||!i||!e||!o)return"\u274C Required: author, topic, outcome, what_worked";if(!["success","failure","partial"].includes(e))return"\u274C outcome must be one of: success, failure, partial";if(!r.trim())return"\u274C Required: author (a name or handle, not blank)";const _=n;if(!_)return"\u274C instance_id required";const k=await y(_),b=await me(k,_,r,"contributor","store team lessons");if(b)return b;if(he(k))return tt(R,_,{topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],author:r},Se(k));const j={topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",author:r,file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],timestamp:new Date().toISOString(),ts:new Date().toISOString(),recall_count:0,version:2};if(await lt(k,_))return ut(k,i,j);const A=`cachly:lessons:${i}`;return await k.rpush(A,JSON.stringify(j)),e==="success"&&await k.set(`cachly:lesson:best:${i}`,JSON.stringify(j)),`\u2705 Team lesson stored by **${r}**: \`${i}\` (${e})
1
+ import{readFileSync as Oe}from"node:fs";import{bauabdruck as Ee,formatiereBauabdruck as Ce}from"../bauabdruck.js";import{beurteileSpeicher as Te,zahlAusInfo as ge}from"../speicherlage.js";import{beurteileDeckung as De}from"../eingaenge.js";import{VEKTOR_NACHTRAG as Me,NAME_VEKTOR_NACHTRAG as ze,ZWEIT_VEKTOR_NACHTRAG as Ie}from"../bedeutung.js";import{join as B}from"node:path";import{calculateConfidence as ee,CONFIDENCE_STALE_VALUE as ce,CONFIDENCE_WARN_VALUE as Pe,CONFIDENCE_WARN_DAYS as we,CONFIDENCE_STALE_DAYS as ye}from"../confidence.js";import{safeJsonParse as z,leseOderNull as _e,darfHeraus as Fe,teamweitLesbar as J}from"../utils.js";import{ersparteMinuten as Be,istStarterLektion as Ue,fmtStunden as $e}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Ke,buildClaudeMdBlock as Je,setzeAnweisungsblock as Ge}from"../projektdateien.js";import{aussetzerEinzelheit as He,aussetzerErklaerung as ve,leseVermerke as qe}from"../aussetzer.js";import{schwaerzeFelder as We}from"../geheimnis-filter.js";import{VERDACHT_TAG as be,pruefeFelder as Ve,verdachtsWarnung as Ye}from"../tuersteher.js";import{fuerEigenenSpeicher as le,fuerWeitergabe as Ze,fuerZusammenfassung as ke,hinweise as ue,markiert as Xe,markierungsWarnung as Qe,weitergabeHinweis as et}from"../schreibtor.js";import{holeRolle as U,istMitglied as he,rolleFuer as Se,lerneUeberApi as tt,bestaetigeUeberApi as st,ROLLEN_SEITE as W}from"../rolle.js";const Lt=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"]),V={admin:4,reviewer:3,contributor:2,viewer:1},F={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},te={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"},H=w=>`cachly:team:roles:${w}`;async function Y(w,m,y){return await w.hget(H(m),y.toLowerCase()).catch(()=>null)}async function nt(w,m,y){const L=await U(m);return L?L.role:y?Y(w,m,y):null}const de={owner:"owner of this brain",org_admin:"organisation admin",assigned:"assigned by an admin",default:"default for members"};function pe(w){const m=de[w.source]??w.source;return m?`${w.role} (${m})`:w.role}function X(w,m){return w?(V[w]??0)>=(V[m]??0):!1}function ot(w){return w==="admin"||w==="reviewer"?"senior":"peer"}async function at(w,m){if(await U(m))return!0;const y=await w.hgetall(H(m)).catch(()=>({}));return Object.values(y).includes("admin")}async function me(w,m,y,L,a){const t=await U(m);if(t)return X(t.role,L)?null:[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${L}\` ${F[L]} (your role: ${F[t.role]} ${pe(t)}).`,"",`Roles are set by the brain owner or an organisation admin in the dashboard: ${W}`,"_Run `team_whoami` to check your role._"].join(`
2
+ `);if(!await at(w,m))return null;const n=y?await Y(w,m,y):null;if(X(n,L))return null;const r=n?`${F[n]} ${n}`:"no role";return[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${L}\` ${F[L]} (you have: ${r}).`,"","Ask an admin to grant it:",`\`team_assign_role(instance_id="${m}", handle="${y||"<your-handle>"}", role="${L}", assigned_by="<admin>")\``,"_Governance is active on this brain. Run `team_whoami` to check your role._"].join(`
3
+ `)}async function xe(w,m,y){const L=`cachly:team:audit:${m}`,a=JSON.stringify({...y,ts:new Date().toISOString()});await w.rpush(L,a).catch(()=>{}),await w.ltrim(L,-500,-1).catch(()=>{}),await w.expire(L,365*2*86400).catch(()=>{})}const rt="cachly:team:review_mode",it="cachly:lesson:proposed:",ct=90*86400;async function lt(w,m){const y=await w.get(rt).catch(()=>null);return y==="1"||y==="true"||y==="on"}async function ut(w,m,y){const L={...y,proposed_at:new Date().toISOString(),status:"pending"};await w.set(`${it}${m}`,JSON.stringify(L),"EX",ct).catch(()=>{});const a=typeof y.author=="string"&&y.author?` by **${y.author}**`:"";return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${m}\`${a} 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(`
4
+ `)}const se=w=>`cachly:team:groups:${w}`,Q=(w,m)=>`cachly:team:group:${w}:${m.toLowerCase()}`;async function Ae(w,m,y){const L=await w.smembers(se(m)).catch(()=>[]),a=new Set;for(const t of L)await w.sismember(Q(m,t),y.toLowerCase()).catch(()=>0)&&a.add(t.toLowerCase());return a}function Re(w,m,y){return!w||y?!0:m.has(w.toLowerCase())}const ne=Object.freeze({scopes:new Set,isAdmin:!1});async function jt(w,m,y){const L=await U(m),a=(y??"").trim();if(!a)return L?.role==="admin"?{scopes:new Set,isAdmin:!0}:ne;const t=await Ae(w,m,a).catch(()=>new Set),n=L?L.role==="admin":await Y(w,m,a).catch(()=>null)==="admin";return{scopes:t,isAdmin:n}}function ht(w,m){if(!Fe(w))return!1;const y=typeof w.group=="string"?w.group.trim():w.group?String(w.group):"";return Re(y||null,m.scopes,m.isAdmin)}function Nt(w,m=ne){const y=new Map;return async L=>{const a=y.get(L);if(a!==void 0)return a;const t=await w.get(`cachly:lesson:best:${L}`).catch(()=>null),n=t===null||ht(_e(t),m);return y.set(L,n),n}}function Le(w,m,y){const L=w.filter(t=>!m.has(t)),a=L.slice(0,y);return{namen:a,rest:w.length-a.length,davonVerborgen:w.length-L.length}}async function Ot(w,m,y,L){switch(w){case"sync_file_changes":{const{instance_id:a,changed_files:t,git_diff_stat:n,commit_msg:r}=m,i=le({changed_files:t,git_diff_stat:n,commit_msg:r}),{changed_files:e,git_diff_stat:o,commit_msg:l}=i.felder,c=await y(a),s={ts:new Date().toISOString(),files:e,commit_msg:l,diff_stat:o?.slice(0,500),...i.verdacht.length?{verdacht:i.verdacht}:{}};await c.lpush("cachly:session:file_changes",JSON.stringify(s)),await c.ltrim("cachly:session:file_changes",0,99),await c.expire("cachly:session:file_changes",30*86400);const d=[],u=c.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((R,A)=>{u.on("data",S=>d.push(...S)),u.on("end",R),u.on("error",A)});const _=[],x=d.length>0?await c.mget(...d):[];for(const R of x){const A=J(R);if(!A)continue;const S=A.topic.toLowerCase().split(/[:\-_]/);if(e.some(k=>{const g=k.split("/").pop()?.replace(/\.[^.]+$/,"").toLowerCase()??"";return S.some(h=>h.length>3&&g.includes(h))||(A.file_paths??[]).some(h=>k.includes(h)||h.includes(k))})){const k=A.outcome==="success"?"\u2705":"\u26A0\uFE0F";_.push(` ${k} \`${A.topic}\` \u2014 ${A.what_worked.slice(0,80)}`)}}const b=[`\u{1F4C1} **File sync recorded**: ${e.length} files`,l?`\u{1F4DD} Commit: "${l}"`:"","",`**Changed:** ${e.slice(0,8).map(R=>`\`${R}\``).join(", ")}${e.length>8?` +${e.length-8} more`:""}`,"",...ue(i,"notiz")];return _.length>0?b.push(`\u{1F9E0} **Relevant brain lessons (${_.length}):**`,..._):b.push("\u{1F4A1} No existing lessons match these files yet. Add them with `learn_from_attempts`."),b.filter(Boolean).join(`
5
+ `)}case"team_learn":{const a=We(m).felder,t=Ve(a),{instance_id:n,author:r,topic:i,outcome:e,what_worked:o,what_failed:l,severity:c,file_paths:s,commands:d,tags:u}=a,_=m.visibility==="private"?"private":void 0,x=String(m.group??"").trim().toLowerCase(),b=_!=="private"&&!x;if(!r||!i||!e||!o)return"\u274C Required: author, topic, outcome, what_worked";if(!["success","failure","partial"].includes(e))return"\u274C outcome must be one of: success, failure, partial";if(!r.trim())return"\u274C Required: author (a name or handle, not blank)";const R=n;if(!R)return"\u274C instance_id required";const A=await y(R),S=await me(A,R,r,"contributor","store team lessons");if(S)return S;if(he(A)||!b&&(await U(R))?.rooms===!0)return!b&&(await U(R))?.rooms!==!0?["\u26A0\uFE0F Nicht gespeichert: Die API dieses Brains kennt noch keine privaten Raeume und Gruppen-Raeume.","Ohne `visibility`/`group` erneut speichern, wenn die Lektion das ganze Team sehen soll."].join(`
6
+ `):tt(L,R,{topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],author:r,...b?{}:{visibility:_??"team",...x?{group:x}:{}}},Se(A));const k={topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",author:r,file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],timestamp:new Date().toISOString(),ts:new Date().toISOString(),recall_count:0,version:2};if(await lt(A,R))return ut(A,i,k);const g=`cachly:lessons:${i}`;return await A.rpush(g,JSON.stringify(k)),e==="success"&&await A.set(`cachly:lesson:best:${i}`,JSON.stringify(k)),`\u2705 Team lesson stored by **${r}**: \`${i}\` (${e})
6
7
  \u{1F4A1} ${o.slice(0,120)}${t.length?`
7
- ${Ye(t)}`:""}`}case"team_confirm":{const{instance_id:a,topic:t,reviewer:n,level:r,note:i=""}=m,e=le({note:i}),o=e.felder.note;if(!a)return"\u274C instance_id required";if(!t||!n)return"\u274C Required: topic, reviewer";const l=await y(a),c=await me(l,a,n,"reviewer","confirm team lessons");if(c)return c;if(he(l))return st(R,a,{topic:t,...r?{tier:r}:{},...o?{note:o.slice(0,280)}:{}},Se(l));const s=await nt(l,a,n),d=ot(s),u=r==="peer"?"peer":r==="senior"&&X(s,"reviewer")?"senior":d,_=s?` (role: ${F[s]} ${s})`:" (no role assigned \u2014 peer weight applied)",k=`cachly:lesson:best:${t}`,b=await l.get(k),j=z(b,null);if(!j)return`\u{1F4ED} No best-solution lesson found for \`${t}\`.
8
+ ${Ye(t)}`:""}`}case"team_confirm":{const{instance_id:a,topic:t,reviewer:n,level:r,note:i=""}=m,e=le({note:i}),o=e.felder.note;if(!a)return"\u274C instance_id required";if(!t||!n)return"\u274C Required: topic, reviewer";const l=await y(a),c=await me(l,a,n,"reviewer","confirm team lessons");if(c)return c;if(he(l))return st(L,a,{topic:t,...r?{tier:r}:{},...o?{note:o.slice(0,280)}:{}},Se(l));const s=await nt(l,a,n),d=ot(s),u=r==="peer"?"peer":r==="senior"&&X(s,"reviewer")?"senior":d,_=s?` (role: ${F[s]} ${s})`:" (no role assigned \u2014 peer weight applied)",x=`cachly:lesson:best:${t}`,b=await l.get(x),R=z(b,null);if(!R)return`\u{1F4ED} No best-solution lesson found for \`${t}\`.
8
9
 
9
- A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;const A=`cachly:lesson:endorsers:${t}`,x=await l.sadd(A,n)===1;await l.expire(A,365*86400);const p=await l.scard(A),g=(j.review_level??"")==="senior"?"senior":u,h={...j,reviewed_by:n,review_level:g,endorsements:p,reviewed_at:new Date().toISOString()};await l.set(k,JSON.stringify(h));const $={reviewer:n,level:u,note:o.slice(0,280),ts:new Date().toISOString(),...e.verdacht.length?{verdacht:e.verdacht}:{}},N=`cachly:lesson:reviews:${t}`;await l.rpush(N,JSON.stringify($)),await l.ltrim(N,-50,-1),await l.expire(N,365*86400),await xe(l,a,{action:"team_confirm",actor:n,topic:t,level:g});const T=g==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",O=x?"":` (already endorsed by ${n} \u2014 no change to rank)`;return`${T} \u2014 \`${t}\` confirmed by **${n}**${_} (${p} distinct endorsement${p===1?"":"s"})${O}.
10
+ A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;const A=`cachly:lesson:endorsers:${t}`,S=await l.sadd(A,n)===1;await l.expire(A,365*86400);const p=await l.scard(A),g=(R.review_level??"")==="senior"?"senior":u,h={...R,reviewed_by:n,review_level:g,endorsements:p,reviewed_at:new Date().toISOString()};await l.set(x,JSON.stringify(h));const $={reviewer:n,level:u,note:o.slice(0,280),ts:new Date().toISOString(),...e.verdacht.length?{verdacht:e.verdacht}:{}},N=`cachly:lesson:reviews:${t}`;await l.rpush(N,JSON.stringify($)),await l.ltrim(N,-50,-1),await l.expire(N,365*86400),await xe(l,a,{action:"team_confirm",actor:n,topic:t,level:g});const T=g==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",O=S?"":` (already endorsed by ${n} \u2014 no change to rank)`;return`${T} \u2014 \`${t}\` confirmed by **${n}**${_} (${p} distinct endorsement${p===1?"":"s"})${O}.
10
11
  \u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.${o?`
11
12
  \u{1F4DD} ${o.slice(0,200)}`:""}${ue(e,"notiz").map(E=>`
12
- ${E}`).join("")}`}case"team_recall":{const{instance_id:a,author:t,limit:n=10}=m,r=m.topic??(typeof m.query=="string"?m.query:void 0),i=Number.isFinite(Number(n))&&Number(n)>=1?Math.floor(Number(n)):10,e=await y(a),o=[],l=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((u,_)=>{l.on("data",k=>o.push(...k)),l.on("end",u),l.on("error",_)});let c=[];if(o.length>0){const u=await e.mget(...o);for(const _ of u){const k=K(_);k&&c.push(k)}}if(r){const u=r.toLowerCase();c=c.filter(_=>_.topic.toLowerCase().includes(u)||(_.tags??[]).some(k=>k.toLowerCase().includes(u)))}if(t){const u=t.toLowerCase();c=c.filter(_=>_.author?.toLowerCase().includes(u))}const s=u=>u.reviewed_by?u.review_level==="senior"?2:1:0;if(c.sort((u,_)=>s(_)-s(u)||(_.recall_count??0)-(u.recall_count??0)),c=c.slice(0,i),c.length===0)return r||t?`\u{1F4ED} No team lessons found for ${[r&&`topic \`${r}\``,t&&`author \`${t}\``].filter(Boolean).join(" and ")}.
13
+ ${E}`).join("")}`}case"team_recall":{const{instance_id:a,author:t,limit:n=10}=m,r=m.topic??(typeof m.query=="string"?m.query:void 0),i=Number.isFinite(Number(n))&&Number(n)>=1?Math.floor(Number(n)):10,e=await y(a),o=[],l=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((u,_)=>{l.on("data",x=>o.push(...x)),l.on("end",u),l.on("error",_)});let c=[];if(o.length>0){const u=await e.mget(...o);for(const _ of u){const x=J(_);x&&c.push(x)}}if(r){const u=r.toLowerCase();c=c.filter(_=>_.topic.toLowerCase().includes(u)||(_.tags??[]).some(x=>x.toLowerCase().includes(u)))}if(t){const u=t.toLowerCase();c=c.filter(_=>_.author?.toLowerCase().includes(u))}const s=u=>u.reviewed_by?u.review_level==="senior"?2:1:0;if(c.sort((u,_)=>s(_)-s(u)||(_.recall_count??0)-(u.recall_count??0)),c=c.slice(0,i),c.length===0)return r||t?`\u{1F4ED} No team lessons found for ${[r&&`topic \`${r}\``,t&&`author \`${t}\``].filter(Boolean).join(" and ")}.
13
14
 
14
15
  Add lessons with \`team_learn\` (requires an \`author\`).`:`\u{1F4ED} No lessons in this brain yet.
15
16
 
16
- All team members sharing this instance will see lessons here.`;const d=[`\u{1F465} **Team Brain** \u2014 ${c.length} lesson${c.length>1?"s":""}`,""];for(const u of c){const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",k=u.severity==="critical"?"\u{1F534} ":u.severity==="major"?"\u{1F7E1} ":"",b=u.reviewed_by?u.review_level==="senior"?" \u{1F6E1}\uFE0F":" \u2714\uFE0F":"",j=u.author?` \xB7 _by ${u.author}_`:"",A=u.reviewed_by?` \xB7 reviewed by ${u.reviewed_by}${(u.endorsements??0)>1?` +${(u.endorsements??0)-1}`:""}`:"",x=(u.recall_count??0)>0?` \xB7 in ${u.recall_count} answers`:"",p=new Date(u.ts??u.timestamp??"").getTime(),S=Math.max(0,Math.round((Date.now()-p)/864e5)),g=Number.isNaN(p)?"":S===0?" \xB7 today":S===1?" \xB7 yesterday":` \xB7 ${S}d ago`;d.push(`${_} ${k}**\`${u.topic}\`**${b}${j}${A}${x}${g}`);const h=Qe(u);h&&d.push(` ${h}`),d.push(` ${u.what_worked.slice(0,120)}`),d.push("")}return d.join(`
17
- `)}case"team_synthesize":{const{instance_id:a,topic:t}=m,n=await y(a),r=`cachly:lessons:${t}`,i=(await n.lrange(r,0,-1)).filter(p=>K(p)!==null);if(i.length<2)return`\u{1F4ED} Need at least 2 entries for topic \`${t}\` to synthesize.
17
+ All team members sharing this instance will see lessons here.`;const d=[`\u{1F465} **Team Brain** \u2014 ${c.length} lesson${c.length>1?"s":""}`,""];for(const u of c){const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",x=u.severity==="critical"?"\u{1F534} ":u.severity==="major"?"\u{1F7E1} ":"",b=u.reviewed_by?u.review_level==="senior"?" \u{1F6E1}\uFE0F":" \u2714\uFE0F":"",R=u.author?` \xB7 _by ${u.author}_`:"",A=u.reviewed_by?` \xB7 reviewed by ${u.reviewed_by}${(u.endorsements??0)>1?` +${(u.endorsements??0)-1}`:""}`:"",S=(u.recall_count??0)>0?` \xB7 in ${u.recall_count} answers`:"",p=new Date(u.ts??u.timestamp??"").getTime(),k=Math.max(0,Math.round((Date.now()-p)/864e5)),g=Number.isNaN(p)?"":k===0?" \xB7 today":k===1?" \xB7 yesterday":` \xB7 ${k}d ago`;d.push(`${_} ${x}**\`${u.topic}\`**${b}${R}${A}${S}${g}`);const h=Qe(u);h&&d.push(` ${h}`),d.push(` ${u.what_worked.slice(0,120)}`),d.push("")}return d.join(`
18
+ `)}case"team_synthesize":{const{instance_id:a,topic:t}=m,n=await y(a),r=`cachly:lessons:${t}`,i=(await n.lrange(r,0,-1)).filter(p=>J(p)!==null);if(i.length<2)return`\u{1F4ED} Need at least 2 entries for topic \`${t}\` to synthesize.
18
19
 
19
20
  Currently: ${i.length} entr${i.length===1?"y":"ies"}.
20
21
 
21
- Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=i.map(p=>{try{return JSON.parse(p)}catch{return null}}).filter(p=>p!==null),o=e.filter(p=>p.outcome==="success"),l=e.filter(p=>p.outcome==="failure"),c=e.filter(p=>p.outcome==="partial"),s=[...new Set(e.map(p=>p.author).filter(Boolean))],d=s.length>1,u=o.sort((p,S)=>new Date(S.ts).getTime()-new Date(p.ts).getTime())[0],k=o.map(p=>p.what_worked).filter(p=>p&&p.length>10).sort((p,S)=>S.length-p.length)[0]??u?.what_worked??"",b=[...new Set([...l,...c].map(p=>p.what_failed).filter(p=>!!p&&p.length>5))],j=e.map(p=>p.severity).filter(Boolean),A=j.includes("critical")?"critical":j.includes("major")?"major":"minor";return[`\u{1F9EC} **Team Brain Synthesis: \`${t}\`**`,`_${e.length} entries from ${s.length} author${s.length===1?"":"s"}${d?` (${s.join(", ")})`:""} \xB7 ${o.length} success \xB7 ${l.length} failure \xB7 ${c.length} partial_`,"",'**Canonical "what worked":**',`> ${k}`,"",b.length>0?"**Avoid (combined failures):**":"",...b.map(p=>`> \u274C ${p}`),(b.length>0,""),"**Suggested canonical lesson:**","```","learn_from_attempts(",` topic = "${t}",`,' outcome = "success",',` what_worked = "${k.replace(/"/g,"'")}",`,b.length>0?` what_failed = "${b[0].replace(/"/g,"'")}",`:"",` severity = "${A}",`,")","```","",d?`\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(p=>p!==void 0).join(`
22
- `)}case"memory_crystalize":{const{instance_id:a,label:t=""}=m,n=await y(a),r=new Date,i=`${r.getFullYear()}-W${String(Math.ceil((r.getDate()-r.getDay()+10)/7)).padStart(2,"0")}`,e=t||`${r.toISOString().slice(0,7)} Crystal`,o=await n.lrange("cachly:session:history",0,49),l=[],c=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((x,p)=>{c.on("data",S=>l.push(...S)),c.on("end",x),c.on("error",p)});const s=[];let d=0,u=0;if(l.length>0){const x=await n.mget(...l);for(const p of x){const S=K(p);if(!S)continue;const g=ke(S);if(!g){d++;continue}g.geschwaerzt&&u++,s.push(g.lektion)}}const _=new Map;for(const x of s){const p=x.topic.split(":")[0]||"misc";_.has(p)||_.set(p,[]),_.get(p).push(x)}const k=[];for(const[x,p]of[..._.entries()].sort((S,g)=>g[1].length-S[1].length).slice(0,8)){const g=p.filter(h=>h.outcome==="success")[0]??p[0];g&&k.push({category:x,insight:g.what_worked.slice(0,120),count:p.length})}const b={label:e,ts:r.toISOString(),session_count:o.length,lesson_count:s.length,top_patterns:k,categories:[..._.keys()],created_from:`${o.length} sessions, ${s.length} lessons`,...d>0?{ausgelassen:d}:{}},j=JSON.stringify(b);return await n.set("cachly:crystal:latest",j),await n.expire("cachly:crystal:latest",90*86400),await n.set(`cachly:crystal:${i}`,j),await n.expire(`cachly:crystal:${i}`,365*86400),[`\u{1F48E} **Memory Crystal created: ${e}**`,"",`\u{1F4CA} Compressed: **${o.length} sessions** + **${s.length} lessons** \u2192 ${k.length} top patterns`,"","**Top patterns by category:**",...k.slice(0,6).map(x=>` \u2022 **${x.category}** (${x.count}\xD7): ${x.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.",...d>0?["",`\u26A0 ${d} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...u>0?[`\u{1F512} ${u} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]].join(`
23
- `)}case"team_crystallize":{const{instance_id:a,min_authors:t=2,label:n=""}=m,r=await y(a),i=new Date,e=Math.max(2,Number(t)||2),o=[],l=r.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((g,h)=>{l.on("data",$=>o.push(...$)),l.on("end",g),l.on("error",h)});const c=[];let s=0,d=0;if(o.length>0){const g=await r.mget(...o);for(const h of g){const $=K(h);if(!$||$.outcome!=="success"||!$.author)continue;const N=ke($);if(!N){s++;continue}N.geschwaerzt&&d++,c.push(N.lektion)}}const u=[...s>0?[`\u26A0 ${s} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...d>0?[`\u{1F512} ${d} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]],_=new Set(["the","and","for","with","from","that","this","fix","bug","error","issue","use","via","add","set","team"]),k=g=>{const[h,...$]=g.topic.split(":"),N=(g.tags??[]).map(E=>E.toLowerCase().trim()).filter(E=>E.length>3&&!_.has(E)).sort();return N.length>0?N[0]:$.join("-").toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/[\s-]+/).filter(E=>E.length>3&&!_.has(E)).sort((E,M)=>M.length-E.length||E.localeCompare(M))[0]??h},b=new Map;for(const g of c){const h=k(g);let $=b.get(h);$||($={concept:h,authors:new Set,lessons:[],namespaces:new Set,bestFix:g},b.set(h,$)),$.authors.add(g.author.toLowerCase()),$.lessons.push(g),$.namespaces.add(g.topic.split(":")[0]||"misc");const N=T=>(T.endorsements??0)*10+(T.confirm_count??0)+(T.review_level==="senior"?5:0);N(g)>N($.bestFix)&&($.bestFix=g)}const A=[...b.values()].filter(g=>g.authors.size>=e).sort((g,h)=>h.authors.size-g.authors.size||h.lessons.length-g.lessons.length).slice(0,10).map(g=>({concept:g.concept,author_count:g.authors.size,authors:[...g.authors],lesson_count:g.lessons.length,spans:[...g.namespaces],convergent_fix:g.bestFix.what_worked.slice(0,200),fix_topic:g.bestFix.topic})),x=n||`${i.toISOString().slice(0,7)} Team Crystal`,p={label:x,ts:i.toISOString(),kind:"team",contributors:new Set(c.map(g=>g.author.toLowerCase())).size,analysed:c.length,patterns:A,...s>0?{ausgelassen:s}:{}};if(await r.set("cachly:crystal:team:latest",JSON.stringify(p)),await r.expire("cachly:crystal:team:latest",180*86400),A.length===0)return["\u{1F4A0} **Team Crystal \u2014 not enough cross-person convergence yet**","",`Analysed **${c.length}** attributed success lessons from **${p.contributors}** contributor${p.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.',...u.length?["",...u]:[]].join(`
24
- `);const S=[`\u{1F4A0} **Team Crystal created: ${x}**`,"",`\u{1F9EC} **${A.length} cross-person pattern${A.length!==1?"s":""}** \u2014 fixes that ${e}+ teammates independently converged on.`,`_Compressed from ${c.length} attributed lessons across ${p.contributors} contributors. This is the team-wide, causal layer a per-user "Dreaming" process structurally cannot produce._`,""];for(const g of A.slice(0,6)){const h=g.spans.length>1?` \xB7 spans ${g.spans.map($=>`\`${$}\``).join(", ")}`:"";S.push(`### \u{1F9E9} \`${g.concept}\` \u2014 ${g.author_count} people converged${h}`,`**Convergent fix** (from \`${g.fix_topic}\`): ${g.convergent_fix}`,`**Who solved it together:** ${g.authors.map($=>`@${$}`).join(", ")} _(ask them \u2014 they've each hit this)_`,"")}return S.push("---","\u{1F4A1} Surfaces in `crystal_view` and onboarding. Re-run `team_crystallize` monthly.",...u.length?["",...u]:[]),S.join(`
25
- `)}case"brain_doctor":{const{instance_id:a,workspace_path:t=""}=m,n=await y(a),r=[],i=[],e=[],o=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,v)=>{o.on("data",L=>e.push(...L)),o.on("end",f),o.on("error",v)});let l=0;const c=n.scanStream({match:"cachly:ctx:*",count:200});await new Promise((f,v)=>{c.on("data",L=>{l+=L.filter(C=>!C.endsWith(":meta")).length}),c.on("end",f),c.on("error",v)});const s=[],d=new Set;if(e.length>0){const f=await n.mget(...e);for(const v of f){const L=z(v??null,null);L&&(s.push(L),K(v)||d.add(L.topic))}}const u=f=>{const{namen:v,davonVerborgen:L}=Le(f.map(I=>I.topic),d,3),C=v.map(I=>`\`${I}\``);return L>0&&C.push(`${L} private or group-only, not named`),C.join(", ")},_=await n.get("cachly:session:last"),k=z(_,null),b=s.filter(f=>f.outcome==="failure"||f.outcome==="partial"),j=s.filter(f=>(f.recall_count??0)===0),A=s.filter(f=>f.severity==="critical"),x=s.filter(f=>f.outcome==="success"&&ee(f)<=ce),p=s.filter(f=>f.outcome==="success"&&ee(f)>ce&&ee(f)<=Pe),S=s.filter(f=>(f.audit_trail??[]).length>1),g=s.filter(f=>f.author),h=new Set(s.map(f=>f.author).filter(Boolean)),$=s.reduce((f,v)=>f+(v.recall_count??0),0),N=s.length>0?Math.min(100,Math.round($/s.length*10)):0,T=async f=>{let v=0;const L=n.scanStream({match:f,count:200});return await new Promise((C,I)=>{L.on("data",P=>{v+=P.length}),L.on("end",C),L.on("error",I)}),v},O=await T("cachly:lesson:vec:*"),E=await T("cachly:lesson:vecname:*"),M=await T("cachly:lesson:eing:*"),U=await T("cachly:lesson:pfad:*"),oe=await T("cachly:lesson:vec2:*"),ae=O>0?Math.round(oe/O*100):0;O>0&&i.push(ae>=80?`\u2705 **Second-model coverage: ${ae}%** \u2014 ${oe} of ${O} embedded lessons also carry the second-model vector; the second ranking feature is ON`:`\u{1F7E1} **Second-model coverage: ${ae}%** \u2014 ${O-oe} lessons still lack the second-model vector; the second ranking feature stays OFF below 80% and backfills three lessons per recall`);const q=await Promise.all([Me,ze,Ie].map(f=>n.smembers(f).then(v=>v.length).catch(()=>0)));if(q.some(f=>f>0)&&i.push(`\u{1F7E1} **Vector backfill pending:** ${q[0]} full-text, ${q[1]} topic-name, ${q[2]} second-model \u2014 retried on the next write or recall`),O>0){const f=Math.max(0,O-E),v=Math.max(0,f-q[1]);f===0?i.push(`\u2705 **Topic-name coverage: 100%** \u2014 all ${O} embedded lessons carry a topic-name vector`):i.push(`\u{1F7E1} **Topic-name coverage: ${Math.round(E/O*100)}%** \u2014 ${f} of ${O} embedded lessons lack a topic-name vector (${Math.min(f,q[1])} queued and healed on the next write or recall`+(v>0?`, ${v} older ones not queued and not healed automatically`:"")+")")}const re=e.length>0?Math.round(O/e.length*100):100,ie=De(e.length,O);e.length>0&&(ie==="aus"?(r.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).`),i.push(`\u{1F534} **Semantic search: OFF** \u2014 0 of ${e.length} lessons have an embedding`)):ie==="luecke"?(r.push(`only ${re}% of lessons have an embedding (${O} of ${e.length}) \u2014 the rest can never be found by meaning.`),i.push(`\u{1F7E1} **Semantic coverage: ${re}%** \u2014 ${e.length-O} lessons without an embedding`)):(i.push(`\u2705 **Semantic coverage: ${re}%** \u2014 ${O} full-text, ${E} topic-name, ${M} with error-text entries`+(U>0?`, ${U} with learned question paths`:"")),U===0&&e.length>=20&&i.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 qe(n);for(const v of f??[]){const L=Ge(v.text);i.push(`\u26A0\uFE0F **Failure noted:** ${ve(v.grund)} \u2014 ${v.anzahl}\xD7 (last: ${v.zuletzt})`+(L?` \xB7 ${L}`:"")),r.push(`failures recorded (${v.anzahl}\xD7): ${ve(v.grund)} \u2014 see the check above.`)}}catch{}let D=50;e.length>=5&&(D+=10),e.length>=20&&(D+=10),l>=3&&(D+=10),l>=10&&(D+=5),k&&(D+=10),b.length===0&&(D+=5);const fe=s.length>0?j.length/s.length:0;fe<.5&&(D+=10),x.length===0&&(D+=5),h.size>=2&&(D+=5),ie!=="gut"&&(D-=20),D=Math.max(0,Math.min(100,D));const je=D>=80?"\u{1F7E2}":D>=50?"\u{1F7E1}":"\u{1F534}",Ne=N>=50?"\u{1F680}":N>=20?"\u{1F4C8}":"\u{1F4A4}";i.push(`${je} **Brain Quality Score: ${D}/100**`),i.push(`${Ne} **Effective IQ Boost: ${N}%** (${$} recalls across ${s.length} lessons)`);try{const v=(await n.lrange("cachly:recall:spread",0,199)).map(L=>z(L,null)?.spread).filter(L=>typeof L=="number"&&Number.isFinite(L));if(v.length===0)i.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 L=v.reduce((P,Y)=>P+Y,0)/v.length,C=v.filter(P=>P<.05).length,I=`mean ${L.toFixed(3)} over ${v.length} recall${v.length===1?"":"s"} (${C} flat, < 0.05)`;v.length>=20&&L<.05?(i.push(`\u{1F7E1} **Rank spread: ${I}** \u2014 ranking has stopped separating hits; provisional threshold, see card 0u9s8qoopwhr`),r.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).")):i.push(`\u{1F4CF} **Rank spread:** ${I}`)}}catch{}i.push(`\u{1F4DA} **Lessons:** ${e.length} (${A.length} critical \xB7 ${S.length} with audit trail \xB7 ${g.length} from team)`),i.push(`\u{1F4BE} **Context entries:** ${l}`),i.push(`\u{1F3AF} **Confidence:** ${s.length-x.length-p.length} fresh \xB7 ${p.length} warn \xB7 ${x.length} stale`),i.push(`\u23F1\uFE0F **Decay config:** warn after ${we}d \xB7 stale after ${ye}d`),i.push(Ce(Ee));try{const f=await n.info("memory");let v=null;if(he(n))v=/^maxmemory_policy:(\S+)/m.exec(String(f))?.[1]??null;else try{const C=await n.config("GET","maxmemory-policy");v=Array.isArray(C)&&C.length>1?String(C[1]):null}catch{v=null}const L={benutzt:ge(f,"used_memory"),grenze:ge(f,"maxmemory"),richtlinie:v};for(const C of Te(L)){const P=`${C.art==="fehler"?"\u{1F534}":C.art==="hinweis"?"\u{1F7E1}":C.art==="ungemessen"?"\u26AA":"\u{1F7E2}"} **Storage:** ${C.text}`;C.art==="fehler"||C.art==="ungemessen"?r.push(P):i.push(P)}}catch{r.push("\u26AA **Storage:** state could not be read \u2014 unknown whether this store silently deletes when it is full.")}h.size>=2&&i.push(`\u{1F465} **Team:** ${h.size} contributors (${[...h].join(", ")})`);try{const f=await n.get("cachly:index:last_run");if(f){const v=Math.round((Date.now()-new Date(f).getTime())/864e5);v>7?r.push(`\u{1F504} Index is ${v}d stale \u2014 run \`index_project\` to re-sync semantic search`):i.push(`\u{1F5C2}\uFE0F **Semantic index:** ${v}d old (fresh)`)}else r.push('\u{1F4A1} No semantic index \u2014 run `index_project(dir="<your-src>")` to enable semantic search')}catch{}try{const f=await n.get("cachly:crystal:latest");if(f){const v=JSON.parse(f),L=Math.round((Date.now()-new Date(v.ts).getTime())/864e5);i.push(`\u{1F48E} **Memory Crystal:** ${v.label} (${L}d ago)`),L>30&&r.push(`\u{1F4A1} Memory Crystal is ${L}d old \u2014 re-run \`memory_crystalize\` to compress new sessions`)}else e.length>=10&&r.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",v=Oe(f,"utf-8"),L=JSON.parse(v),C={...L.dependencies,...L.devDependencies},I=["openai","@anthropic-ai/sdk","@google/generative-ai","mistralai","cohere-ai"].some(Y=>Y in C),P="@cachly-dev/openclaw"in C;I&&!P?(r.push(`\u{1F4A1} **openclaw missing:** you use LLM APIs (${Object.keys(C).filter(Y=>["openai","@anthropic-ai/sdk"].includes(Y)).join(", ")}) but not \`@cachly-dev/openclaw\``),r.push(" \u2192 `npm install @cachly-dev/openclaw` cuts LLM costs 60\u201390% with 3 lines of code")):P&&i.push("\u2705 **@cachly-dev/openclaw installed** (LLM cost caching active)")}catch{}if(k){const f=Math.round((Date.now()-new Date(k.ts).getTime())/6e4),v=f<60?`${f}m`:f<1440?`${Math.round(f/60)}h`:`${Math.round(f/1440)}d`;i.push(`\u{1F550} **Last session:** ${v} ago`)}else r.push("\u274C No session history \u2014 call `session_start` + `session_end` to start tracking");e.length===0?r.push("\u274C No lessons \u2014 call `learn_from_attempts` after solving bugs"):e.length<5&&r.push(`\u{1F4A1} Only ${e.length} lessons \u2014 add more after each problem solved`),N===0&&s.length>=5&&r.push("\u{1F4A4} **IQ Boost is 0%** \u2014 lessons exist but are never recalled. Use `recall_best_solution` BEFORE tasks."),l===0&&r.push("\u{1F4A1} No context \u2014 use `remember_context` to cache architecture docs, ADRs, etc."),b.length>0&&r.push(`\u26A0\uFE0F ${b.length} unresolved failure${b.length>1?"s":""}: ${u(b)}`),x.length>0&&(r.push(`\u{1F534} ${x.length} STALE lesson${x.length>1?"s":""} (${ye}d+ since written or checked, confidence ${ce*100}%): ${u(x)}`),r.push(" \u2192 Re-run each check, then confirm with `lesson_verified` (recalling does not reset the clock)")),p.length>0&&r.push(`\u26A0\uFE0F ${p.length} lesson${p.length>1?"s":""} aging (${we}d+): ${u(p)}`),fe>.7&&s.length>5&&r.push(`\u{1F4A1} ${j.length} lessons never recalled \u2014 verify topics match your workflow`);const J=["\u{1FA7A} **Brain Doctor**",`\`${"\u2500".repeat(48)}\``,"","**\u{1F4CA} Health Checks**",...i.map(f=>" "+f),""];return r.length>0?(J.push(`**\u{1F527} Action Items** (${r.length} issue${r.length>1?"s":""})`),r.forEach((f,v)=>J.push(` ${v+1}. ${f}`)),J.push(""),J.push("_brain_doctor only reports and changes nothing. Act on the items above, then run it again to check._")):(J.push("**\u2705 All checks passed** \u2014 Brain is healthy!"),J.push(""),J.push("_Keep the brain sharp: `session_start` \u2192 work \u2192 `learn_from_attempts` \u2192 `session_end`_")),J.join(`
26
- `)}case"brain_hygiene":{const{instance_id:a,dry_run:t=!1,provisional_threshold:n=.5,archive_days:r=30}=m,i=await y(a),e=[],o=i.scanStream({match:"cachly:lesson:best:*",count:200});if(await new Promise((h,$)=>{o.on("data",N=>e.push(...N)),o.on("end",h),o.on("error",$)}),e.length===0)return"\u{1F9F9} **Brain Hygiene** \u2014 no lessons found. Nothing to sweep.";const l=await i.mget(...e),c=[],s=new Set;for(let h=0;h<e.length;h++){const $=l[h],N=z($??null,null);N&&(c.push({...N,_key:e[h]}),K($)||s.add(N.topic))}const d=Date.now(),u=[],_=[],k=[],b=new Map;for(const h of c){const $=h.state??"active";if($==="archived")continue;const N=ee(h),T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(N<=n){const E=h.recall_count??0;if($==="provisional"&&E<2&&O>r){if(_.push(h.topic),!t){const U={...h,state:"archived",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"archived",prev_state:"provisional"}]};b.set(h._key,U)}}else if($==="active"&&(u.push(h.topic),!t)){const U={...h,state:"provisional",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"flagged_provisional",prev_state:"active"}]};b.set(h._key,U)}}}for(const h of c){const $=h.state??"active";if($==="archived"||b.has(h._key)&&b.get(h._key).state==="archived"||h.outcome!=="failure"||(h.recall_count??0)>0)continue;const T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(O<=r)continue;const E=u.indexOf(h.topic);if(E!==-1&&u.splice(E,1),k.push({topic:h.topic,text:`${h.topic} (failure, never recalled, ${Math.round(O)}d old)`}),!t){const M=b.get(h._key)??h,U={...M,state:"archived",audit_trail:[...M.audit_trail??[],{ts:new Date().toISOString(),action:"orphan_failure_archived",prev_state:$}]};b.set(h._key,U)}}let j=0,A=0;const x=parseFloat(await i.get(`cachly:stats:time_saved_mins:${a}`)??"0")||0;for(const h of c){if(Ue(h)){if((h.recall_count??0)>0){j++;const $=b.get(h._key)??h;b.set(h._key,{...$,recall_count:0})}continue}(h.recall_count??0)>0&&(A+=Be(h))}if(t||await i.set(`cachly:stats:time_saved_mins:${a}`,String(A)).catch(()=>{}),!t&&b.size>0){const h=i.pipeline();for(const[$,N]of b){const{_key:T,...O}=N;h.set($,JSON.stringify(O))}await h.exec()}const S=[`${t?"\u{1F50D} **Brain Hygiene (dry run)**":"\u{1F9F9} **Brain Hygiene**"} \u2014 scanned **${c.length}** lessons`,"","| Action | Count |","|---|---|",`| Flagged provisional (confidence < ${n}) | ${u.length} |`,`| Archived (stale + low-recall + age > ${r}d) | ${_.length} |`,`| Contradictions auto-resolved | ${k.length} |`,`| Startvorrat entwertet (Z\xE4hler auf 0) | ${j} |`,""];Math.round(x)!==Math.round(A)&&S.push(`**\u23F1\uFE0F Zeitersparnis neu gerechnet:** ${$e(x)} \u2192 **${$e(A)}**`,"_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._","");const g=(h,$,N)=>{const{namen:T,rest:O,davonVerborgen:E}=Le(h,s,$);if(T.forEach(M=>S.push(` - ${N(M)}`)),O>0){const M=E>0?` (${E} of them private or group-only, not named)`:"";S.push(` - _\u2026and ${O} more${M}_`)}};if(u.length>0&&(S.push("**\u26A0\uFE0F Provisional (verify or re-learn):**"),g(u,10,h=>`\`${h}\``),S.push("")),_.length>0&&(S.push("**\u{1F4E6} Archived (excluded from recall):**"),g(_,5,h=>`\`${h}\``),S.push("")),k.length>0){S.push("**\u2694\uFE0F Contradictions resolved (failure archived, success kept):**");const h=new Map(k.map($=>[$.topic,$.text]));g(k.map($=>$.topic),5,$=>h.get($)??`\`${$}\``),S.push("")}return t?S.push("_Run `brain_hygiene(dry_run=false)` to apply these changes._"):u.length+_.length+k.length===0?S.push("\u2705 Brain is clean \u2014 no hygiene actions needed."):S.push("_Changes applied. Run `brain_doctor` to verify the updated health score._"),S.join(`
22
+ Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=i.map(p=>{try{return JSON.parse(p)}catch{return null}}).filter(p=>p!==null),o=e.filter(p=>p.outcome==="success"),l=e.filter(p=>p.outcome==="failure"),c=e.filter(p=>p.outcome==="partial"),s=[...new Set(e.map(p=>p.author).filter(Boolean))],d=s.length>1,u=o.sort((p,k)=>new Date(k.ts).getTime()-new Date(p.ts).getTime())[0],x=o.map(p=>p.what_worked).filter(p=>p&&p.length>10).sort((p,k)=>k.length-p.length)[0]??u?.what_worked??"",b=[...new Set([...l,...c].map(p=>p.what_failed).filter(p=>!!p&&p.length>5))],R=e.map(p=>p.severity).filter(Boolean),A=R.includes("critical")?"critical":R.includes("major")?"major":"minor";return[`\u{1F9EC} **Team Brain Synthesis: \`${t}\`**`,`_${e.length} entries from ${s.length} author${s.length===1?"":"s"}${d?` (${s.join(", ")})`:""} \xB7 ${o.length} success \xB7 ${l.length} failure \xB7 ${c.length} partial_`,"",'**Canonical "what worked":**',`> ${x}`,"",b.length>0?"**Avoid (combined failures):**":"",...b.map(p=>`> \u274C ${p}`),(b.length>0,""),"**Suggested canonical lesson:**","```","learn_from_attempts(",` topic = "${t}",`,' outcome = "success",',` what_worked = "${x.replace(/"/g,"'")}",`,b.length>0?` what_failed = "${b[0].replace(/"/g,"'")}",`:"",` severity = "${A}",`,")","```","",d?`\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(p=>p!==void 0).join(`
23
+ `)}case"memory_crystalize":{const{instance_id:a,label:t=""}=m,n=await y(a),r=new Date,i=`${r.getFullYear()}-W${String(Math.ceil((r.getDate()-r.getDay()+10)/7)).padStart(2,"0")}`,e=t||`${r.toISOString().slice(0,7)} Crystal`,o=await n.lrange("cachly:session:history",0,49),l=[],c=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((S,p)=>{c.on("data",k=>l.push(...k)),c.on("end",S),c.on("error",p)});const s=[];let d=0,u=0;if(l.length>0){const S=await n.mget(...l);for(const p of S){const k=J(p);if(!k)continue;const g=ke(k);if(!g){d++;continue}g.geschwaerzt&&u++,s.push(g.lektion)}}const _=new Map;for(const S of s){const p=S.topic.split(":")[0]||"misc";_.has(p)||_.set(p,[]),_.get(p).push(S)}const x=[];for(const[S,p]of[..._.entries()].sort((k,g)=>g[1].length-k[1].length).slice(0,8)){const g=p.filter(h=>h.outcome==="success")[0]??p[0];g&&x.push({category:S,insight:g.what_worked.slice(0,120),count:p.length})}const b={label:e,ts:r.toISOString(),session_count:o.length,lesson_count:s.length,top_patterns:x,categories:[..._.keys()],created_from:`${o.length} sessions, ${s.length} lessons`,...d>0?{ausgelassen:d}:{}},R=JSON.stringify(b);return await n.set("cachly:crystal:latest",R),await n.expire("cachly:crystal:latest",90*86400),await n.set(`cachly:crystal:${i}`,R),await n.expire(`cachly:crystal:${i}`,365*86400),[`\u{1F48E} **Memory Crystal created: ${e}**`,"",`\u{1F4CA} Compressed: **${o.length} sessions** + **${s.length} lessons** \u2192 ${x.length} top patterns`,"","**Top patterns by category:**",...x.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.",...d>0?["",`\u26A0 ${d} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...u>0?[`\u{1F512} ${u} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]].join(`
24
+ `)}case"team_crystallize":{const{instance_id:a,min_authors:t=2,label:n=""}=m,r=await y(a),i=new Date,e=Math.max(2,Number(t)||2),o=[],l=r.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((g,h)=>{l.on("data",$=>o.push(...$)),l.on("end",g),l.on("error",h)});const c=[];let s=0,d=0;if(o.length>0){const g=await r.mget(...o);for(const h of g){const $=J(h);if(!$||$.outcome!=="success"||!$.author)continue;const N=ke($);if(!N){s++;continue}N.geschwaerzt&&d++,c.push(N.lektion)}}const u=[...s>0?[`\u26A0 ${s} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...d>0?[`\u{1F512} ${d} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]],_=new Set(["the","and","for","with","from","that","this","fix","bug","error","issue","use","via","add","set","team"]),x=g=>{const[h,...$]=g.topic.split(":"),N=(g.tags??[]).map(E=>E.toLowerCase().trim()).filter(E=>E.length>3&&!_.has(E)).sort();return N.length>0?N[0]:$.join("-").toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/[\s-]+/).filter(E=>E.length>3&&!_.has(E)).sort((E,M)=>M.length-E.length||E.localeCompare(M))[0]??h},b=new Map;for(const g of c){const h=x(g);let $=b.get(h);$||($={concept:h,authors:new Set,lessons:[],namespaces:new Set,bestFix:g},b.set(h,$)),$.authors.add(g.author.toLowerCase()),$.lessons.push(g),$.namespaces.add(g.topic.split(":")[0]||"misc");const N=T=>(T.endorsements??0)*10+(T.confirm_count??0)+(T.review_level==="senior"?5:0);N(g)>N($.bestFix)&&($.bestFix=g)}const A=[...b.values()].filter(g=>g.authors.size>=e).sort((g,h)=>h.authors.size-g.authors.size||h.lessons.length-g.lessons.length).slice(0,10).map(g=>({concept:g.concept,author_count:g.authors.size,authors:[...g.authors],lesson_count:g.lessons.length,spans:[...g.namespaces],convergent_fix:g.bestFix.what_worked.slice(0,200),fix_topic:g.bestFix.topic})),S=n||`${i.toISOString().slice(0,7)} Team Crystal`,p={label:S,ts:i.toISOString(),kind:"team",contributors:new Set(c.map(g=>g.author.toLowerCase())).size,analysed:c.length,patterns:A,...s>0?{ausgelassen:s}:{}};if(await r.set("cachly:crystal:team:latest",JSON.stringify(p)),await r.expire("cachly:crystal:team:latest",180*86400),A.length===0)return["\u{1F4A0} **Team Crystal \u2014 not enough cross-person convergence yet**","",`Analysed **${c.length}** attributed success lessons from **${p.contributors}** contributor${p.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.',...u.length?["",...u]:[]].join(`
25
+ `);const k=[`\u{1F4A0} **Team Crystal created: ${S}**`,"",`\u{1F9EC} **${A.length} cross-person pattern${A.length!==1?"s":""}** \u2014 fixes that ${e}+ teammates independently converged on.`,`_Compressed from ${c.length} attributed lessons across ${p.contributors} contributors. This is the team-wide, causal layer a per-user "Dreaming" process structurally cannot produce._`,""];for(const g of A.slice(0,6)){const h=g.spans.length>1?` \xB7 spans ${g.spans.map($=>`\`${$}\``).join(", ")}`:"";k.push(`### \u{1F9E9} \`${g.concept}\` \u2014 ${g.author_count} people converged${h}`,`**Convergent fix** (from \`${g.fix_topic}\`): ${g.convergent_fix}`,`**Who solved it together:** ${g.authors.map($=>`@${$}`).join(", ")} _(ask them \u2014 they've each hit this)_`,"")}return k.push("---","\u{1F4A1} Surfaces in `crystal_view` and onboarding. Re-run `team_crystallize` monthly.",...u.length?["",...u]:[]),k.join(`
26
+ `)}case"brain_doctor":{const{instance_id:a,workspace_path:t=""}=m,n=await y(a),r=[],i=[],e=[],o=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,v)=>{o.on("data",j=>e.push(...j)),o.on("end",f),o.on("error",v)});let l=0;const c=n.scanStream({match:"cachly:ctx:*",count:200});await new Promise((f,v)=>{c.on("data",j=>{l+=j.filter(C=>!C.endsWith(":meta")).length}),c.on("end",f),c.on("error",v)});const s=[],d=new Set;if(e.length>0){const f=await n.mget(...e);for(const v of f){const j=z(v??null,null);j&&(s.push(j),J(v)||d.add(j.topic))}}const u=f=>{const{namen:v,davonVerborgen:j}=Le(f.map(I=>I.topic),d,3),C=v.map(I=>`\`${I}\``);return j>0&&C.push(`${j} private or group-only, not named`),C.join(", ")},_=await n.get("cachly:session:last"),x=z(_,null),b=s.filter(f=>f.outcome==="failure"||f.outcome==="partial"),R=s.filter(f=>(f.recall_count??0)===0),A=s.filter(f=>f.severity==="critical"),S=s.filter(f=>f.outcome==="success"&&ee(f)<=ce),p=s.filter(f=>f.outcome==="success"&&ee(f)>ce&&ee(f)<=Pe),k=s.filter(f=>(f.audit_trail??[]).length>1),g=s.filter(f=>f.author),h=new Set(s.map(f=>f.author).filter(Boolean)),$=s.reduce((f,v)=>f+(v.recall_count??0),0),N=s.length>0?Math.min(100,Math.round($/s.length*10)):0,T=async f=>{let v=0;const j=n.scanStream({match:f,count:200});return await new Promise((C,I)=>{j.on("data",P=>{v+=P.length}),j.on("end",C),j.on("error",I)}),v},O=await T("cachly:lesson:vec:*"),E=await T("cachly:lesson:vecname:*"),M=await T("cachly:lesson:eing:*"),K=await T("cachly:lesson:pfad:*"),oe=await T("cachly:lesson:vec2:*"),ae=O>0?Math.round(oe/O*100):0;O>0&&i.push(ae>=80?`\u2705 **Second-model coverage: ${ae}%** \u2014 ${oe} of ${O} embedded lessons also carry the second-model vector; the second ranking feature is ON`:`\u{1F7E1} **Second-model coverage: ${ae}%** \u2014 ${O-oe} lessons still lack the second-model vector; the second ranking feature stays OFF below 80% and backfills three lessons per recall`);const q=await Promise.all([Me,ze,Ie].map(f=>n.smembers(f).then(v=>v.length).catch(()=>0)));if(q.some(f=>f>0)&&i.push(`\u{1F7E1} **Vector backfill pending:** ${q[0]} full-text, ${q[1]} topic-name, ${q[2]} second-model \u2014 retried on the next write or recall`),O>0){const f=Math.max(0,O-E),v=Math.max(0,f-q[1]);f===0?i.push(`\u2705 **Topic-name coverage: 100%** \u2014 all ${O} embedded lessons carry a topic-name vector`):i.push(`\u{1F7E1} **Topic-name coverage: ${Math.round(E/O*100)}%** \u2014 ${f} of ${O} embedded lessons lack a topic-name vector (${Math.min(f,q[1])} queued and healed on the next write or recall`+(v>0?`, ${v} older ones not queued and not healed automatically`:"")+")")}const re=e.length>0?Math.round(O/e.length*100):100,ie=De(e.length,O);e.length>0&&(ie==="aus"?(r.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).`),i.push(`\u{1F534} **Semantic search: OFF** \u2014 0 of ${e.length} lessons have an embedding`)):ie==="luecke"?(r.push(`only ${re}% of lessons have an embedding (${O} of ${e.length}) \u2014 the rest can never be found by meaning.`),i.push(`\u{1F7E1} **Semantic coverage: ${re}%** \u2014 ${e.length-O} lessons without an embedding`)):(i.push(`\u2705 **Semantic coverage: ${re}%** \u2014 ${O} full-text, ${E} topic-name, ${M} with error-text entries`+(K>0?`, ${K} with learned question paths`:"")),K===0&&e.length>=20&&i.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 qe(n);for(const v of f??[]){const j=He(v.text);i.push(`\u26A0\uFE0F **Failure noted:** ${ve(v.grund)} \u2014 ${v.anzahl}\xD7 (last: ${v.zuletzt})`+(j?` \xB7 ${j}`:"")),r.push(`failures recorded (${v.anzahl}\xD7): ${ve(v.grund)} \u2014 see the check above.`)}}catch{}let D=50;e.length>=5&&(D+=10),e.length>=20&&(D+=10),l>=3&&(D+=10),l>=10&&(D+=5),x&&(D+=10),b.length===0&&(D+=5);const fe=s.length>0?R.length/s.length:0;fe<.5&&(D+=10),S.length===0&&(D+=5),h.size>=2&&(D+=5),ie!=="gut"&&(D-=20),D=Math.max(0,Math.min(100,D));const je=D>=80?"\u{1F7E2}":D>=50?"\u{1F7E1}":"\u{1F534}",Ne=N>=50?"\u{1F680}":N>=20?"\u{1F4C8}":"\u{1F4A4}";i.push(`${je} **Brain Quality Score: ${D}/100**`),i.push(`${Ne} **Effective IQ Boost: ${N}%** (${$} recalls across ${s.length} lessons)`);try{const v=(await n.lrange("cachly:recall:spread",0,199)).map(j=>z(j,null)?.spread).filter(j=>typeof j=="number"&&Number.isFinite(j));if(v.length===0)i.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 j=v.reduce((P,Z)=>P+Z,0)/v.length,C=v.filter(P=>P<.05).length,I=`mean ${j.toFixed(3)} over ${v.length} recall${v.length===1?"":"s"} (${C} flat, < 0.05)`;v.length>=20&&j<.05?(i.push(`\u{1F7E1} **Rank spread: ${I}** \u2014 ranking has stopped separating hits; provisional threshold, see card 0u9s8qoopwhr`),r.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).")):i.push(`\u{1F4CF} **Rank spread:** ${I}`)}}catch{}i.push(`\u{1F4DA} **Lessons:** ${e.length} (${A.length} critical \xB7 ${k.length} with audit trail \xB7 ${g.length} from team)`),i.push(`\u{1F4BE} **Context entries:** ${l}`),i.push(`\u{1F3AF} **Confidence:** ${s.length-S.length-p.length} fresh \xB7 ${p.length} warn \xB7 ${S.length} stale`),i.push(`\u23F1\uFE0F **Decay config:** warn after ${we}d \xB7 stale after ${ye}d`),i.push(Ce(Ee));try{const f=await n.info("memory");let v=null;if(he(n))v=/^maxmemory_policy:(\S+)/m.exec(String(f))?.[1]??null;else try{const C=await n.config("GET","maxmemory-policy");v=Array.isArray(C)&&C.length>1?String(C[1]):null}catch{v=null}const j={benutzt:ge(f,"used_memory"),grenze:ge(f,"maxmemory"),richtlinie:v};for(const C of Te(j)){const P=`${C.art==="fehler"?"\u{1F534}":C.art==="hinweis"?"\u{1F7E1}":C.art==="ungemessen"?"\u26AA":"\u{1F7E2}"} **Storage:** ${C.text}`;C.art==="fehler"||C.art==="ungemessen"?r.push(P):i.push(P)}}catch{r.push("\u26AA **Storage:** state could not be read \u2014 unknown whether this store silently deletes when it is full.")}h.size>=2&&i.push(`\u{1F465} **Team:** ${h.size} contributors (${[...h].join(", ")})`);try{const f=await n.get("cachly:index:last_run");if(f){const v=Math.round((Date.now()-new Date(f).getTime())/864e5);v>7?r.push(`\u{1F504} Index is ${v}d stale \u2014 run \`index_project\` to re-sync semantic search`):i.push(`\u{1F5C2}\uFE0F **Semantic index:** ${v}d old (fresh)`)}else r.push('\u{1F4A1} No semantic index \u2014 run `index_project(dir="<your-src>")` to enable semantic search')}catch{}try{const f=await n.get("cachly:crystal:latest");if(f){const v=JSON.parse(f),j=Math.round((Date.now()-new Date(v.ts).getTime())/864e5);i.push(`\u{1F48E} **Memory Crystal:** ${v.label} (${j}d ago)`),j>30&&r.push(`\u{1F4A1} Memory Crystal is ${j}d old \u2014 re-run \`memory_crystalize\` to compress new sessions`)}else e.length>=10&&r.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",v=Oe(f,"utf-8"),j=JSON.parse(v),C={...j.dependencies,...j.devDependencies},I=["openai","@anthropic-ai/sdk","@google/generative-ai","mistralai","cohere-ai"].some(Z=>Z in C),P="@cachly-dev/openclaw"in C;I&&!P?(r.push(`\u{1F4A1} **openclaw missing:** you use LLM APIs (${Object.keys(C).filter(Z=>["openai","@anthropic-ai/sdk"].includes(Z)).join(", ")}) but not \`@cachly-dev/openclaw\``),r.push(" \u2192 `npm install @cachly-dev/openclaw` cuts LLM costs 60\u201390% with 3 lines of code")):P&&i.push("\u2705 **@cachly-dev/openclaw installed** (LLM cost caching active)")}catch{}if(x){const f=Math.round((Date.now()-new Date(x.ts).getTime())/6e4),v=f<60?`${f}m`:f<1440?`${Math.round(f/60)}h`:`${Math.round(f/1440)}d`;i.push(`\u{1F550} **Last session:** ${v} ago`)}else r.push("\u274C No session history \u2014 call `session_start` + `session_end` to start tracking");e.length===0?r.push("\u274C No lessons \u2014 call `learn_from_attempts` after solving bugs"):e.length<5&&r.push(`\u{1F4A1} Only ${e.length} lessons \u2014 add more after each problem solved`),N===0&&s.length>=5&&r.push("\u{1F4A4} **IQ Boost is 0%** \u2014 lessons exist but are never recalled. Use `recall_best_solution` BEFORE tasks."),l===0&&r.push("\u{1F4A1} No context \u2014 use `remember_context` to cache architecture docs, ADRs, etc."),b.length>0&&r.push(`\u26A0\uFE0F ${b.length} unresolved failure${b.length>1?"s":""}: ${u(b)}`),S.length>0&&(r.push(`\u{1F534} ${S.length} STALE lesson${S.length>1?"s":""} (${ye}d+ since written or checked, confidence ${ce*100}%): ${u(S)}`),r.push(" \u2192 Re-run each check, then confirm with `lesson_verified` (recalling does not reset the clock)")),p.length>0&&r.push(`\u26A0\uFE0F ${p.length} lesson${p.length>1?"s":""} aging (${we}d+): ${u(p)}`),fe>.7&&s.length>5&&r.push(`\u{1F4A1} ${R.length} lessons never recalled \u2014 verify topics match your workflow`);const G=["\u{1FA7A} **Brain Doctor**",`\`${"\u2500".repeat(48)}\``,"","**\u{1F4CA} Health Checks**",...i.map(f=>" "+f),""];return r.length>0?(G.push(`**\u{1F527} Action Items** (${r.length} issue${r.length>1?"s":""})`),r.forEach((f,v)=>G.push(` ${v+1}. ${f}`)),G.push(""),G.push("_brain_doctor only reports and changes nothing. Act on the items above, then run it again to check._")):(G.push("**\u2705 All checks passed** \u2014 Brain is healthy!"),G.push(""),G.push("_Keep the brain sharp: `session_start` \u2192 work \u2192 `learn_from_attempts` \u2192 `session_end`_")),G.join(`
27
+ `)}case"brain_hygiene":{const{instance_id:a,dry_run:t=!1,provisional_threshold:n=.5,archive_days:r=30}=m,i=await y(a),e=[],o=i.scanStream({match:"cachly:lesson:best:*",count:200});if(await new Promise((h,$)=>{o.on("data",N=>e.push(...N)),o.on("end",h),o.on("error",$)}),e.length===0)return"\u{1F9F9} **Brain Hygiene** \u2014 no lessons found. Nothing to sweep.";const l=await i.mget(...e),c=[],s=new Set;for(let h=0;h<e.length;h++){const $=l[h],N=z($??null,null);N&&(c.push({...N,_key:e[h]}),J($)||s.add(N.topic))}const d=Date.now(),u=[],_=[],x=[],b=new Map;for(const h of c){const $=h.state??"active";if($==="archived")continue;const N=ee(h),T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(N<=n){const E=h.recall_count??0;if($==="provisional"&&E<2&&O>r){if(_.push(h.topic),!t){const K={...h,state:"archived",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"archived",prev_state:"provisional"}]};b.set(h._key,K)}}else if($==="active"&&(u.push(h.topic),!t)){const K={...h,state:"provisional",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"flagged_provisional",prev_state:"active"}]};b.set(h._key,K)}}}for(const h of c){const $=h.state??"active";if($==="archived"||b.has(h._key)&&b.get(h._key).state==="archived"||h.outcome!=="failure"||(h.recall_count??0)>0)continue;const T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(O<=r)continue;const E=u.indexOf(h.topic);if(E!==-1&&u.splice(E,1),x.push({topic:h.topic,text:`${h.topic} (failure, never recalled, ${Math.round(O)}d old)`}),!t){const M=b.get(h._key)??h,K={...M,state:"archived",audit_trail:[...M.audit_trail??[],{ts:new Date().toISOString(),action:"orphan_failure_archived",prev_state:$}]};b.set(h._key,K)}}let R=0,A=0;const S=parseFloat(await i.get(`cachly:stats:time_saved_mins:${a}`)??"0")||0;for(const h of c){if(Ue(h)){if((h.recall_count??0)>0){R++;const $=b.get(h._key)??h;b.set(h._key,{...$,recall_count:0})}continue}(h.recall_count??0)>0&&(A+=Be(h))}if(t||await i.set(`cachly:stats:time_saved_mins:${a}`,String(A)).catch(()=>{}),!t&&b.size>0){const h=i.pipeline();for(const[$,N]of b){const{_key:T,...O}=N;h.set($,JSON.stringify(O))}await h.exec()}const k=[`${t?"\u{1F50D} **Brain Hygiene (dry run)**":"\u{1F9F9} **Brain Hygiene**"} \u2014 scanned **${c.length}** lessons`,"","| Action | Count |","|---|---|",`| Flagged provisional (confidence < ${n}) | ${u.length} |`,`| Archived (stale + low-recall + age > ${r}d) | ${_.length} |`,`| Contradictions auto-resolved | ${x.length} |`,`| Startvorrat entwertet (Z\xE4hler auf 0) | ${R} |`,""];Math.round(S)!==Math.round(A)&&k.push(`**\u23F1\uFE0F Zeitersparnis neu gerechnet:** ${$e(S)} \u2192 **${$e(A)}**`,"_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._","");const g=(h,$,N)=>{const{namen:T,rest:O,davonVerborgen:E}=Le(h,s,$);if(T.forEach(M=>k.push(` - ${N(M)}`)),O>0){const M=E>0?` (${E} of them private or group-only, not named)`:"";k.push(` - _\u2026and ${O} more${M}_`)}};if(u.length>0&&(k.push("**\u26A0\uFE0F Provisional (verify or re-learn):**"),g(u,10,h=>`\`${h}\``),k.push("")),_.length>0&&(k.push("**\u{1F4E6} Archived (excluded from recall):**"),g(_,5,h=>`\`${h}\``),k.push("")),x.length>0){k.push("**\u2694\uFE0F Contradictions resolved (failure archived, success kept):**");const h=new Map(x.map($=>[$.topic,$.text]));g(x.map($=>$.topic),5,$=>h.get($)??`\`${$}\``),k.push("")}return t?k.push("_Run `brain_hygiene(dry_run=false)` to apply these changes._"):u.length+_.length+x.length===0?k.push("\u2705 Brain is clean \u2014 no hygiene actions needed."):k.push("_Changes applied. Run `brain_doctor` to verify the updated health score._"),k.join(`
27
28
  `)}case"recall_at":{const{instance_id:a,topic:t,date:n}=m,r=await y(a),i=new Date(n).getTime();if(isNaN(i))return`\u274C Invalid date "${n}". Use ISO format: "2026-01-15"`;const e=`cachly:lessons:${t}`,o=(await r.lrange(e,0,-1)).filter(s=>{const d=_e(s);return d!==null&&Re(d.group,ne.scopes,ne.isAdmin)});if(o.length===0)return`\u{1F4ED} No history found for \`${t}\`. Lessons are stored via \`learn_from_attempts\`.`;const l=o.map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null&&new Date(s.ts).getTime()<=i).sort((s,d)=>new Date(s.ts).getTime()-new Date(d.ts).getTime());if(l.length===0){const s=z(o[0]??null,null),d=s?.ts?new Date(s.ts).toLocaleDateString("de-DE"):"unknown";return`\u{1F4ED} No entries for \`${t}\` found before **${n}**. Earliest entry: ${d}.`}const c=[`\u{1F3FA} **Brain Archaeology: \`${t}\` before ${n}**`,`_${l.length} of ${o.length} total entries shown_`,""];for(const s of l.slice(-10)){const d=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",u=new Date(s.ts).toLocaleDateString("de-DE");c.push(`**${u}** ${d} ${s.outcome}`),s.what_worked&&c.push(` \u2192 ${s.what_worked.slice(0,100)}`),c.push("")}return c.push(`_Full evolution: ${o.map(s=>{try{const d=JSON.parse(s);return d.outcome==="success"?"\u2705":d.outcome==="partial"?"\u26A0\uFE0F":"\u274C"}catch{return"?"}}).join(" \u2192 ")}_`),c.join(`
28
29
  `)}case"trace_dependency":{const{instance_id:a,dependency:t,mark_review:n=!1}=m,r=await y(a),i=`cachly:dep:${t}`,e=await r.get(i);if(!e)return`\u{1F4ED} No lessons found that depend on \`${t}\`.
29
30
 
30
- Add dependencies via: \`learn_from_attempts(..., depends_on=["${t}"])\``;const o=z(e,[]),l=[`\u{1F517} **Causal Chain: \`${t}\`** \u2014 ${o.length} dependent lesson${o.length===1?"":"s"}`,""];let c=0;for(const s of o){const d=await r.get(`cachly:lesson:best:${s}`);if(!d){l.push(` \u2022 \`${s}\` _(lesson deleted)_`);continue}const u=z(d,null);if(!u){l.push(` \u2022 \`${s}\` _(lesson corrupted)_`);continue}if(K(d)===null){c++,n&&await r.set(`cachly:lesson:best:${s}`,JSON.stringify({...u,needs_review:!0}));continue}const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",k=u.needs_review?" \u{1F50D} **needs_review**":"";if(l.push(` ${_} \`${s}\` (${u.severity??"major"})${k}`),n){const b={...u,needs_review:!0};await r.set(`cachly:lesson:best:${s}`,JSON.stringify(b))}}return c>0&&l.push(` \u{1F512} ${c} private or group-only, not named.`),n?l.push("",`\u{1F50D} All ${o.length} lessons marked as **needs_review** \u2014 verify they still work with the changed dependency.`):l.push("","_Run with `mark_review: true` to flag all dependent lessons for re-verification._"),l.join(`
31
+ Add dependencies via: \`learn_from_attempts(..., depends_on=["${t}"])\``;const o=z(e,[]),l=[`\u{1F517} **Causal Chain: \`${t}\`** \u2014 ${o.length} dependent lesson${o.length===1?"":"s"}`,""];let c=0;for(const s of o){const d=await r.get(`cachly:lesson:best:${s}`);if(!d){l.push(` \u2022 \`${s}\` _(lesson deleted)_`);continue}const u=z(d,null);if(!u){l.push(` \u2022 \`${s}\` _(lesson corrupted)_`);continue}if(J(d)===null){c++,n&&await r.set(`cachly:lesson:best:${s}`,JSON.stringify({...u,needs_review:!0}));continue}const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",x=u.needs_review?" \u{1F50D} **needs_review**":"";if(l.push(` ${_} \`${s}\` (${u.severity??"major"})${x}`),n){const b={...u,needs_review:!0};await r.set(`cachly:lesson:best:${s}`,JSON.stringify(b))}}return c>0&&l.push(` \u{1F512} ${c} private or group-only, not named.`),n?l.push("",`\u{1F50D} All ${o.length} lessons marked as **needs_review** \u2014 verify they still work with the changed dependency.`):l.push("","_Run with `mark_review: true` to flag all dependent lessons for re-verification._"),l.join(`
31
32
  `)}case"global_learn":{const{instance_id:a,topic:t,lesson:n,severity:r="minor",tags:i=[]}=m,e=le({topic:t,lesson:n,tags:i}),{topic:o,lesson:l}=e.felder,c=await y(a),s=`cachly:global:lesson:${o}`,d={topic:o,lesson:l,severity:r,tags:Xe(e.felder.tags,e.verdacht),ts:new Date().toISOString(),scope:"global",recall_count:0},u=await c.get(s);if(u){const _=z(u,null);d.recall_count=_?.recall_count??0}return await c.set(s,JSON.stringify(d)),[`\u{1F310} **Global lesson stored**: \`${o}\`
32
33
 
33
34
  ${l}
@@ -42,22 +43,22 @@ Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;f
42
43
  Available: ${d}
43
44
 
44
45
  Or publish your own: \`publish_lesson(framework="${t}", ...)\``}const l=o.slice(0,n);let c=0;for(const d of l){const u=`cachly:lesson:best:${d.topic}`;await r.get(u)||(await r.set(u,JSON.stringify({...d,what_worked:d.lesson,outcome:"success",ts:new Date().toISOString(),recall_count:0,source:"public_brain",version:2})),c++)}return[`\u{1F4E5} **Public Brain imported: ${t}**`,"",`${c} new lessons added (${l.length-c} already existed)`,"","**Imported topics:**",...l.map(d=>` ${d.severity==="critical"?"\u{1F534}":d.severity==="major"?"\u{1F7E1}":"\u{1F4A1}"} \`${d.topic}\``),"","These lessons will now appear in `session_start` when relevant.",`Recall any time: \`recall_best_solution(topic="${e}:...")\``].join(`
45
- `)}case"setup_ai_memory":{const{instance_id:a,project_dir:t,embed_provider:n="openai",project_description:r="a software project"}=m,i=await R(`/api/v1/instances/${a}`),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"}},o=e[n]??e.openai,l=!!i.vector_token,c=JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"your-api-token-from-cachly.dev/settings",[o.key]:n==="ollama"?"http://localhost:11434":"your-key-here",...n!=="openai"?{CACHLY_EMBED_PROVIDER:n}:{}}}}},null,2),s=i.tier.toUpperCase(),d=Je(a),u=["\u{1F9E0} **cachly AI Memory Setup Complete**","",`**Project:** ${r}`,`**Instance:** ${i.name} (${s}) \xB7 ID: \`${a}\``,`**Embedding Provider:** ${n}`,`**Semantic Search:** ${l?"\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",c,"```","",`**Step 2 \u2014 Set your ${n} key:**`,"```bash",`export ${o.key}="your-key-here"`,"```",`_(${o.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",d,"```","","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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:_}=await import("node:fs/promises"),{constants:k}=await import("node:fs"),b=async x=>_(x,k.F_OK).then(()=>!0).catch(()=>!1),j=[{ide:"GitHub Copilot",path:B(t,".github","copilot-instructions.md")}];(await b(B(t,"CLAUDE.md"))||await b(B(t,".claude")))&&j.push({ide:"Claude Code",path:B(t,"CLAUDE.md")}),(await b(B(t,".cursor"))||await b(B(t,".cursorrules")))&&j.push({ide:"Cursor",path:B(t,".cursor","rules","cachly.mdc"),prefix:Ke}),(await b(B(t,".windsurfrules"))||await b(B(t,".windsurf")))&&j.push({ide:"Windsurf",path:B(t,".windsurfrules")});const A=[];for(const x of j){const p=await He(x.path,d,x.prefix),S=p==="written"?"written":p==="unchanged"?"already current, nothing changed":p==="updated"?"cachly block updated, rest of the file unchanged":"cachly block appended, your text kept";A.push(`\u2705 [${x.ide}] \u2192 \`${x.path.replace(t,".")}\` (${S})`)}A.push("\u2139\uFE0F Hooks (session briefing, per-prompt recall) are set up by `npx @cachly-dev/mcp-server@latest init` or `autopilot`."),u.push(...A)}return u.join(`
46
- `)}case"team_assign_role":{const{instance_id:a,handle:t,role:n,assigned_by:r=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, role";const i=["admin","reviewer","contributor","viewer"].includes(n)?n:null;if(!i)return`\u274C Unknown role \`${n}\`. Valid: admin \xB7 reviewer \xB7 contributor \xB7 viewer`;const e=await H(a);if(e)return["\u2139\uFE0F **Roles are no longer set here.** Nothing was changed.","",`The brain owner or an organisation admin sets roles in the dashboard: ${Z}`,`There, \`${t}\` can be made \`${i}\` (the roles admin and owner come from the account and are not assigned).`,"",`Your role: ${F[e.role]} ${pe(e)}. Run \`team_whoami\` to see what it allows.`].join(`
47
- `);const o=await y(a),l=await o.hgetall(G(a)).catch(()=>({})),c=Object.values(l).includes("admin");if(c){const _=r?await V(o,a,r):null;if(!X(_,"admin"))return["\u274C **Permission denied** \u2014 only an `admin` can assign roles.","","Ask an existing admin to run:",`\`team_assign_role(instance_id="${a}", handle="${t}", role="${n}", assigned_by="<their-handle>")\``].join(`
48
- `)}const s=l[t.toLowerCase()]??null;await o.hset(G(a),t.toLowerCase(),i),await o.expire(G(a),365*2*86400),await xe(o,a,{action:"team_assign_role",actor:r||"(bootstrap)",handle:t.toLowerCase(),from:s,to:i});const d=!c;return[`${F[i]} **Role assigned** \u2014 **${t}** is now a \`${i}\``,"",`**Capabilities:** ${te[i]}`,"",d?"_First admin bootstrapped \u2014 governance is now active on this brain._":`_Assigned by ${r||"(bootstrap)"}_`,"","Run `team_roster` to see all current roles."].join(`
49
- `)}case"team_whoami":{const{instance_id:a,handle:t}=m;if(!a||!t)return"\u274C Required: instance_id, handle";const n=await H(a);if(n){const o=n.can,l=s=>s?"yes":"no",c=[`## ${F[n.role]} ${t} \u2014 \`${n.role}\``,"",`**Where the role comes from:** ${de[n.source]??(n.source||"unknown")} (cachly API, not the brain store)`,`**You can:** ${te[n.role]}`,`**Allowed:** store lessons ${l(o.learn)} \xB7 confirm ${l(o.confirm)} \xB7 withdraw ${l(o.withdraw)} \xB7 manage roles ${l(o.manage)}`];return n.review_mode&&c.push("**Review required:** lessons from contributors become proposals until an admin approves them."),c.push("",`Roles are set by the brain owner or an organisation admin: ${Z}`),c.join(`
50
- `)}const r=await y(a),i=await V(r,a,t);if(!i){const o=await r.hgetall(G(a)).catch(()=>({})),l=Object.values(o).includes("admin");return[`\u{1F441}\uFE0F **${t}** has no assigned role on this brain.`,"",l?`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:
46
+ `)}case"setup_ai_memory":{const{instance_id:a,project_dir:t,embed_provider:n="openai",project_description:r="a software project"}=m,i=await L(`/api/v1/instances/${a}`),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"}},o=e[n]??e.openai,l=!!i.vector_token,c=JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"your-api-token-from-cachly.dev/settings",[o.key]:n==="ollama"?"http://localhost:11434":"your-key-here",...n!=="openai"?{CACHLY_EMBED_PROVIDER:n}:{}}}}},null,2),s=i.tier.toUpperCase(),d=Je(a),u=["\u{1F9E0} **cachly AI Memory Setup Complete**","",`**Project:** ${r}`,`**Instance:** ${i.name} (${s}) \xB7 ID: \`${a}\``,`**Embedding Provider:** ${n}`,`**Semantic Search:** ${l?"\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",c,"```","",`**Step 2 \u2014 Set your ${n} key:**`,"```bash",`export ${o.key}="your-key-here"`,"```",`_(${o.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",d,"```","","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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:_}=await import("node:fs/promises"),{constants:x}=await import("node:fs"),b=async S=>_(S,x.F_OK).then(()=>!0).catch(()=>!1),R=[{ide:"GitHub Copilot",path:B(t,".github","copilot-instructions.md")}];(await b(B(t,"CLAUDE.md"))||await b(B(t,".claude")))&&R.push({ide:"Claude Code",path:B(t,"CLAUDE.md")}),(await b(B(t,".cursor"))||await b(B(t,".cursorrules")))&&R.push({ide:"Cursor",path:B(t,".cursor","rules","cachly.mdc"),prefix:Ke}),(await b(B(t,".windsurfrules"))||await b(B(t,".windsurf")))&&R.push({ide:"Windsurf",path:B(t,".windsurfrules")});const A=[];for(const S of R){const p=await Ge(S.path,d,S.prefix),k=p==="written"?"written":p==="unchanged"?"already current, nothing changed":p==="updated"?"cachly block updated, rest of the file unchanged":"cachly block appended, your text kept";A.push(`\u2705 [${S.ide}] \u2192 \`${S.path.replace(t,".")}\` (${k})`)}A.push("\u2139\uFE0F Hooks (session briefing, per-prompt recall) are set up by `npx @cachly-dev/mcp-server@latest init` or `autopilot`."),u.push(...A)}return u.join(`
47
+ `)}case"team_assign_role":{const{instance_id:a,handle:t,role:n,assigned_by:r=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, role";const i=["admin","reviewer","contributor","viewer"].includes(n)?n:null;if(!i)return`\u274C Unknown role \`${n}\`. Valid: admin \xB7 reviewer \xB7 contributor \xB7 viewer`;const e=await U(a);if(e)return["\u2139\uFE0F **Roles are no longer set here.** Nothing was changed.","",`The brain owner or an organisation admin sets roles in the dashboard: ${W}`,`There, \`${t}\` can be made \`${i}\` (the roles admin and owner come from the account and are not assigned).`,"",`Your role: ${F[e.role]} ${pe(e)}. Run \`team_whoami\` to see what it allows.`].join(`
48
+ `);const o=await y(a),l=await o.hgetall(H(a)).catch(()=>({})),c=Object.values(l).includes("admin");if(c){const _=r?await Y(o,a,r):null;if(!X(_,"admin"))return["\u274C **Permission denied** \u2014 only an `admin` can assign roles.","","Ask an existing admin to run:",`\`team_assign_role(instance_id="${a}", handle="${t}", role="${n}", assigned_by="<their-handle>")\``].join(`
49
+ `)}const s=l[t.toLowerCase()]??null;await o.hset(H(a),t.toLowerCase(),i),await o.expire(H(a),365*2*86400),await xe(o,a,{action:"team_assign_role",actor:r||"(bootstrap)",handle:t.toLowerCase(),from:s,to:i});const d=!c;return[`${F[i]} **Role assigned** \u2014 **${t}** is now a \`${i}\``,"",`**Capabilities:** ${te[i]}`,"",d?"_First admin bootstrapped \u2014 governance is now active on this brain._":`_Assigned by ${r||"(bootstrap)"}_`,"","Run `team_roster` to see all current roles."].join(`
50
+ `)}case"team_whoami":{const{instance_id:a,handle:t}=m;if(!a||!t)return"\u274C Required: instance_id, handle";const n=await U(a);if(n){const o=n.can,l=s=>s?"yes":"no",c=[`## ${F[n.role]} ${t} \u2014 \`${n.role}\``,"",`**Where the role comes from:** ${de[n.source]??(n.source||"unknown")} (cachly API, not the brain store)`,`**You can:** ${te[n.role]}`,`**Allowed:** store lessons ${l(o.learn)} \xB7 confirm ${l(o.confirm)} \xB7 withdraw ${l(o.withdraw)} \xB7 manage roles ${l(o.manage)}`];return n.review_mode&&c.push("**Review required:** lessons from contributors become proposals until an admin approves them."),c.push("",`Roles are set by the brain owner or an organisation admin: ${W}`),c.join(`
51
+ `)}const r=await y(a),i=await Y(r,a,t);if(!i){const o=await r.hgetall(H(a)).catch(()=>({})),l=Object.values(o).includes("admin");return[`\u{1F441}\uFE0F **${t}** has no assigned role on this brain.`,"",l?`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:
51
52
  \`team_assign_role(handle="${t}", role="admin")\``].join(`
52
53
  `)}return[`## ${F[i]} ${t} \u2014 \`${i}\``,"",`**You can:** ${te[i]}`,"","Run `team_roster` to see all team members and their roles."].join(`
53
- `)}case"team_roster":{const{instance_id:a}=m;if(!a)return"\u274C Required: instance_id";if(await H(a)){let e=null;try{const c=await R(`/api/v1/instances/${encodeURIComponent(a)}/members`);e=Array.isArray(c?.members)?c.members:null}catch{e=null}if(!e)return`## \u{1F465} Team Roster
54
+ `)}case"team_roster":{const{instance_id:a}=m;if(!a)return"\u274C Required: instance_id";if(await U(a)){let e=null;try{const c=await L(`/api/v1/instances/${encodeURIComponent(a)}/members`);e=Array.isArray(c?.members)?c.members:null}catch{e=null}if(!e)return`## \u{1F465} Team Roster
54
55
 
55
- The member list could not be loaded right now. Roles are managed in the dashboard: ${Z}`;const o=[...e].sort((c,s)=>(W[s.role]??0)-(W[c.role]??0)||String(c.display_name??"").localeCompare(String(s.display_name??"")));return[`## \u{1F465} Team Roster (${o.length} member${o.length!==1?"s":""})`,"","| Role | Member | Source |","|---|---|---|",...o.map(c=>{const s=c.role??"";return`| ${F[s]??"?"} ${c.role??"?"} | **${c.display_name||"(no name)"}** | ${de[c.source??""]??(c.source||"")} |`}),"",`_Roles come from the cachly API. The owner or an organisation admin changes them at ${Z}._`].join(`
56
- `)}const n=await(await y(a)).hgetall(G(a)).catch(()=>({}));if(Object.keys(n).length===0)return["## \u{1F465} Team Roster","","No roles assigned yet. Establish governance with:",`\`team_assign_role(instance_id="${a}", handle="<your-handle>", role="admin")\``].join(`
57
- `);const r=Object.entries(n).map(([e,o])=>({handle:e,role:o})).sort((e,o)=>(W[o.role]??0)-(W[e.role]??0)||e.handle.localeCompare(o.handle)),i=[`## \u{1F465} Team Roster (${r.length} member${r.length!==1?"s":""})`,"","| Role | Handle | Capabilities |","|---|---|---|"];for(const e of r){const o=F[e.role]??"?";i.push(`| ${o} ${e.role} | **${e.handle}** | ${te[e.role].split(" \xB7 ").slice(0,2).join(", ")} |`)}return i.push("","_Manage with `team_assign_role`. Any admin can add or change roles._"),i.join(`
56
+ The member list could not be loaded right now. Roles are managed in the dashboard: ${W}`;const o=[...e].sort((c,s)=>(V[s.role]??0)-(V[c.role]??0)||String(c.display_name??"").localeCompare(String(s.display_name??"")));return[`## \u{1F465} Team Roster (${o.length} member${o.length!==1?"s":""})`,"","| Role | Member | Source |","|---|---|---|",...o.map(c=>{const s=c.role??"";return`| ${F[s]??"?"} ${c.role??"?"} | **${c.display_name||"(no name)"}** | ${de[c.source??""]??(c.source||"")} |`}),"",`_Roles come from the cachly API. The owner or an organisation admin changes them at ${W}._`].join(`
57
+ `)}const n=await(await y(a)).hgetall(H(a)).catch(()=>({}));if(Object.keys(n).length===0)return["## \u{1F465} Team Roster","","No roles assigned yet. Establish governance with:",`\`team_assign_role(instance_id="${a}", handle="<your-handle>", role="admin")\``].join(`
58
+ `);const r=Object.entries(n).map(([e,o])=>({handle:e,role:o})).sort((e,o)=>(V[o.role]??0)-(V[e.role]??0)||e.handle.localeCompare(o.handle)),i=[`## \u{1F465} Team Roster (${r.length} member${r.length!==1?"s":""})`,"","| Role | Handle | Capabilities |","|---|---|---|"];for(const e of r){const o=F[e.role]??"?";i.push(`| ${o} ${e.role} | **${e.handle}** | ${te[e.role].split(" \xB7 ").slice(0,2).join(", ")} |`)}return i.push("","_Manage with `team_assign_role`. Any admin can add or change roles._"),i.join(`
58
59
  `)}case"team_audit":{const{instance_id:a,requester:t="",limit:n=50}=m;if(!a)return"\u274C Required: instance_id";const r=await y(a),i=await me(r,a,t,"admin","view the governance audit log");if(i)return i;const e=Math.min(Math.max(1,Number(n)||50),200),o=await r.lrange(`cachly:team:audit:${a}`,-e,-1).catch(()=>[]);if(o.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(`
59
60
  `);const l=o.map(s=>z(s,null)).filter(s=>s!==null).reverse(),c=s=>{const d=s.ts?new Date(s.ts).toISOString().replace("T"," ").slice(0,16):"?";return s.action==="team_assign_role"?`| ${d} | \u{1F451} role | **${s.actor}** set \`${s.handle}\`: ${s.from??"\u2014"} \u2192 **${s.to}** |`:s.action==="team_confirm"?`| ${d} | \u2705 confirm | **${s.actor}** confirmed \`${s.topic}\` (${s.level}) |`:`| ${d} | ${s.action??"?"} | ${s.actor??"?"} |`};return[`## \u{1F4DC} Governance Audit Log (${l.length} event${l.length!==1?"s":""})`,"","| When (UTC) | Type | Detail |","|---|---|---|",...l.map(c),"",`_Immutable trail \xB7 2-year retention \xB7 last ${e} events. Admin-only._`].join(`
60
- `)}case"team_grant_scope":{const{instance_id:a,handle:t,group:n,action:r="add",assigned_by:i=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, group";const e=String(n).toLowerCase().trim();if(!e)return'\u274C `group` must be a non-empty name (e.g. "backend", "security")';const o=await y(a),l=await H(a);if(l&&l.role!=="admin")return`\u274C **Permission denied** \u2014 only the brain owner or an organisation admin can manage group scopes (your role: ${pe(l)}).`;const c=l?{}:await o.hgetall(G(a)).catch(()=>({}));if(Object.values(c).includes("admin")){const d=i?await V(o,a,i):null;if(!X(d,"admin"))return"\u274C **Permission denied** \u2014 only an `admin` can manage group scopes. Ask an admin to set `assigned_by`."}return r==="remove"?(await o.srem(Q(a,e),t.toLowerCase()),`\u{1F513} **${t}** removed from group \`${e}\`.`):(await o.sadd(se(a),e),await o.sadd(Q(a,e),t.toLowerCase()),await o.expire(se(a),365*2*86400),await o.expire(Q(a,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(`
61
+ `)}case"team_grant_scope":{const{instance_id:a,handle:t,group:n,action:r="add",assigned_by:i=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, group";const e=String(n).toLowerCase().trim();if(!e)return'\u274C `group` must be a non-empty name (e.g. "backend", "security")';const o=await y(a),l=await U(a);if(l?.rooms===!0)return`Gruppen pflegt ein Admin auf der Rollen-Seite: ${W}`;if(l&&l.role!=="admin")return`\u274C **Permission denied** \u2014 only the brain owner or an organisation admin can manage group scopes (your role: ${pe(l)}).`;const c=l?{}:await o.hgetall(H(a)).catch(()=>({}));if(Object.values(c).includes("admin")){const d=i?await Y(o,a,i):null;if(!X(d,"admin"))return"\u274C **Permission denied** \u2014 only an `admin` can manage group scopes. Ask an admin to set `assigned_by`."}return r==="remove"?(await o.srem(Q(a,e),t.toLowerCase()),`\u{1F513} **${t}** removed from group \`${e}\`.`):(await o.sadd(se(a),e),await o.sadd(Q(a,e),t.toLowerCase()),await o.expire(se(a),365*2*86400),await o.expire(Q(a,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(`
61
62
  `))}case"team_scopes":{const{instance_id:a,handle:t}=m;if(!a)return"\u274C Required: instance_id";const n=await y(a);if(t){const e=await Ae(n,a,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(o=>`\`${o}\``).join(", ")}`}const r=await n.smembers(se(a)).catch(()=>[]);if(r.length===0)return["## \u{1F510} Team Scopes","","No groups defined yet. Create one by adding a member:",`\`team_grant_scope(instance_id="${a}", handle="alice", group="backend")\``].join(`
62
63
  `);const i=[`## \u{1F510} Team Scopes (${r.length} group${r.length!==1?"s":""})`,""];for(const e of r.sort()){const o=await n.smembers(Q(a,e)).catch(()=>[]);i.push(`- **\`${e}\`** (${o.length}): ${o.length?o.map(l=>`**${l}**`).join(", "):"_empty_"}`)}return i.push("",'_Scope a lesson to a group with `learn_from_attempts(group="...")`. Members + admins see it; others don\'t._'),i.join(`
63
- `)}default:return null}}export{se as GROUPS_INDEX_KEY,Q as GROUP_KEY,ne as NIEMAND,it as PROPOSED_LESSON_PREFIX,rt as REVIEW_MODE_KEY,G as ROLES_KEY,F as ROLE_BADGE,Lt as TEAM_TOOL_NAMES,xe as auditLog,nt as eigeneRolle,jt as fragenderAusweis,V as getRole,Ae as getScopes,Ot as handleTeamTool,X as hasPermission,Re as lessonVisibleToScope,Nt as namensPruefer,at as rbacActive,me as requireRole,lt as reviewModeEnabled,ot as roleToReviewLevel,ht as sichtbarFuer,ut as storeLessonProposal,K as teamweitLesbar,Le as teamweiteNamen};
64
+ `)}default:return null}}export{se as GROUPS_INDEX_KEY,Q as GROUP_KEY,ne as NIEMAND,it as PROPOSED_LESSON_PREFIX,rt as REVIEW_MODE_KEY,H as ROLES_KEY,F as ROLE_BADGE,Lt as TEAM_TOOL_NAMES,xe as auditLog,nt as eigeneRolle,jt as fragenderAusweis,Y as getRole,Ae as getScopes,Ot as handleTeamTool,X as hasPermission,Re as lessonVisibleToScope,Nt as namensPruefer,at as rbacActive,me as requireRole,lt as reviewModeEnabled,ot as roleToReviewLevel,ht as sichtbarFuer,ut as storeLessonProposal,J as teamweitLesbar,Le as teamweiteNamen};
@@ -0,0 +1 @@
1
+ import{createHash as A}from"node:crypto";import{zugangVon as z}from"./rolle.js";const b="cachly:zone:raeume";function g(t){return A("sha256").update(t).digest("hex")}function j(t){return`cachly:zone:p:${t.replace(/-/g,"").slice(0,16)}:`}function E(t){return`cachly:zone:g:${g(`gruppe:${t.toLowerCase().trim()}`).slice(0,16)}:`}function y(t,e){return`${t}lesson:best:${g(e).slice(0,32)}`}function R(t){return`${t}themen`}function M(t){return["%R~cachly:[^z]*",...t.privat?[`%R~${t.privat}*`]:[],...t.gruppen.map(e=>`%R~${e}*`),"~[^c]*","~c[^a]*","~ca[^c]*","~cac[^h]*","~cach[^l]*","~cachl[^y]*","~cachly[^:]*","~cachly:[^tlciwgfbmpdz]*","~cachly:ctx:*","~cachly:cls:*","~cachly:wirkung:*","~cachly:lock:*","~cachly:mcp:*","~cachly:mcm:*","~cachly:prefs:*","~cachly:dep:*","~cachly:letzter-recall:*","~cachly:liefer:*","+@all","-@admin","-@dangerous","+keys","+info","-client"]}function h(t){return typeof t=="string"&&t?t:void 0}function V(t){if(!t||typeof t!="object")return;const e=t,o=h(e.private),a=[];if(Array.isArray(e.groups))for(const n of e.groups){const c=h(n?.prefix);if(!c)continue;const u=h(n.name);a.push({...u?{name:u}:{},praefix:c})}const r=e.all===!0;if(!(!o&&a.length===0&&!r))return{...o?{privat:o}:{},gruppen:a,...r?{alle:!0}:{}}}function v(t){return z(t)?.raeume}function $(t){return t.startsWith("cachly:zone:p:")?"p":"g"}function x(t){try{const e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}async function w(t){const e=v(t);if(!e)return[];const o=[],a=new Set,r=n=>{a.has(n.praefix)||(a.add(n.praefix),o.push(n))};e.privat&&r({praefix:e.privat});for(const n of e.gruppen)r(n);if(e.alle){let n={};try{n=await t.hgetall(b)}catch{n={}}for(const[c,u]of Object.entries(n)){const l=h(x(u)?.name);r({...l?{name:l}:{},praefix:c})}}return o}function d(t,e,o){const a=x(t);if(!a)return null;const r=$(e.praefix),n=typeof a.topic=="string"&&a.topic?a.topic:o;if(!n)return null;const c=r==="g"?e.name??h(a.group):void 0;return{thema:n,praefix:e.praefix,art:r,...c?{gruppe:c}:{},lektion:a,roh:t}}async function C(t,e){const o=await w(t);if(o.length===0)return null;const a=await t.mget(...o.map(r=>y(r.praefix,e)));for(let r=0;r<o.length;r++){const n=a[r];if(typeof n!="string")continue;const c=d(n,o[r],e);if(c)return c}return null}async function N(t,e=200){const o=await w(t);if(o.length===0)return[];const a=t.pipeline();for(const i of o)a.smembers(R(i.praefix));const r=await a.exec()??[],n=[];o.forEach((i,f)=>{const[s,p]=r[f]??[null,[]];if(!(s||!Array.isArray(p)))for(const m of p.slice().sort())typeof m=="string"&&n.push({ref:i,thema:m})});const c=n.slice(0,Math.max(0,e));if(c.length===0)return[];const u=await t.mget(...c.map(i=>y(i.ref.praefix,i.thema))),l=[];return c.forEach((i,f)=>{const s=u[f];if(typeof s!="string")return;const p=d(s,i.ref,i.thema);p&&l.push(p)}),l}function k(t){return t.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3)}function _(t,e,o=3){const a=new Set(k(e));if(a.size===0)return[];const r=[];for(const n of t){const c=n.lektion,u=Array.isArray(c.tags)?c.tags.filter(s=>typeof s=="string").join(" "):"",l=[n.thema,c.what_worked,c.what_failed,c.context,u].filter(s=>typeof s=="string").join(" "),i=new Set(k(l));let f=0;for(const s of a)i.has(s)&&f++;f>0&&r.push({l:n,n:f})}return r.sort((n,c)=>c.n-n.n),r.slice(0,Math.max(0,o)).map(n=>n.l)}export{b as RAUM_VERZEICHNIS,N as ladeRaumLektionen,y as lektionsSchluessel,C as leseRaumLektion,M as mitgliedMuster,V as raeumeAusAuskunft,v as raeumeVon,E as raumGruppe,j as raumPrivat,_ as raumTreffer,R as themenSchluessel};
@@ -1,6 +1,6 @@
1
1
  const i=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
2
- <rect width="32" height="32" rx="8" fill="#dcf5e8"/>
3
- <path d="M18.8 11.19A6.8 6.8 0 1 0 18.8 20.81" stroke="#061521" stroke-width="4.8" stroke-linecap="round"/>
4
- <circle cx="24" cy="23.6" r="2.4" fill="#14b86e"/>
2
+ <rect width="32" height="32" rx="8" fill="#F59E0B"/>
3
+ <path d="M20.6 10.4A7.6 7.6 0 1 0 20.6 21.6" stroke="#292524" stroke-width="5.2" stroke-linecap="round"/>
4
+ <circle cx="25.4" cy="23.4" r="2.7" fill="#292524"/>
5
5
  </svg>
6
6
  `;function n(t){return{name:"cachly-mcp",version:t,title:"cachly",websiteUrl:"https://cachly.dev",icons:[{src:"https://cachly.dev/favicon.svg",mimeType:"image/svg+xml",sizes:["any"]}]}}function c(t,e,o){return o!=="/favicon.svg"&&o!=="/favicon.ico"?!1:t.method!=="GET"&&t.method!=="HEAD"?(e.writeHead(405,{Allow:"GET, HEAD"}),e.end(),!0):o==="/favicon.ico"?(e.writeHead(301,{Location:"/favicon.svg","Cache-Control":"public, max-age=86400"}),e.end(),!0):(e.writeHead(200,{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}),e.end(t.method==="HEAD"?void 0:i),!0)}export{i as LOGO_SVG,c as beantworteLogo,n as serverInfo};
package/dist/src/rolle.js CHANGED
@@ -1,12 +1,13 @@
1
- import{AsyncLocalStorage as O}from"node:async_hooks";import{mitgliedDarfSchreiben as T}from"./schluessel-klassen.js";const D=new Set(["admin","reviewer","contributor","viewer"]),M=6e4,w="https://cachly.dev/team";let m=null,x=()=>"";const p=new Map,g=new Map;function P(t){m=t.abruf,x=t.bereich??(()=>""),p.clear(),g.clear()}function W(){P({abruf:null}),d.clear()}function z(t){if(!t||typeof t!="object")return null;const e=t;if(typeof e.role!="string"||!D.has(e.role))return null;const n=e.can&&typeof e.can=="object"?e.can:{};return{role:e.role,source:typeof e.source=="string"?e.source:"",can:{learn:n.learn===!0,confirm:n.confirm===!0,withdraw:n.withdraw===!0,manage:n.manage===!0},review_mode:e.review_mode===!0,protection:typeof e.protection=="string"?e.protection:"",...e.knowledge&&typeof e.knowledge=="object"?{knowledge:e.knowledge}:{},...typeof e.min_mcp=="string"?{min_mcp:e.min_mcp}:{}}}function $(t){return`${x()}|${t}`}async function q(t){if(!m||!t)return null;const e=$(t),n=p.get(e);if(n&&Date.now()-n.am<M)return n.auskunft;const r=g.get(e);return n?(r||S(e,t,n),n.auskunft):r||S(e,t,void 0)}function S(t,e,n){if(!m)return Promise.resolve(n?.auskunft??null);const r=m,o=(async()=>{try{const i=z(await r(`/api/v1/instances/${encodeURIComponent(e)}/role`));return p.set(t,{auskunft:i,am:Date.now()}),i}catch(i){return h(i).status===404?(p.set(t,{auskunft:null,am:Date.now()}),null):n?.auskunft??null}})().finally(()=>g.delete(t));return g.set(t,o),o}function C(t){return p.get($(t))?.auskunft??null}function K(t,e,n){if(t&&typeof t=="object"){const r=n&&typeof n=="object"?n:{};Object.assign(t,{apiStatus:e,...typeof r.code=="string"?{apiCode:r.code}:{},...typeof r.role=="string"?{apiRole:r.role}:{},...typeof r.reason=="string"?{apiReason:r.reason}:{}})}return t}function h(t){const e=t&&typeof t=="object"?t:{},n=(c,a)=>typeof c=="string"?c:typeof a=="string"?a:void 0,r={},o=typeof e.apiStatus=="number"?e.apiStatus:typeof e.status=="number"?e.status:void 0;o!==void 0&&(r.status=o);const i=n(e.apiCode,e.code);i!==void 0&&(r.code=i);const s=n(e.apiRole,e.role);s!==void 0&&(r.role=s);const u=n(e.apiReason,e.reason);if(u!==void 0&&(r.reason=u),r.status===void 0){const c=/\((\d{3})\)|error (\d{3})/.exec(String(e.message??""));c&&(r.status=Number(c[1]??c[2]))}return r}const b=new WeakMap;function R(t){return t&&typeof t=="object"?b.get(t):void 0}function I(t){return R(t)?.access==="member"}function L(t){const e=R(t);return(e?.instanceId?C(e.instanceId)?.role:void 0)??e?.role??"contributor"}function Q(t,e){return!I(t)||T(e)}const X="member_access_unavailable";function Y(t,e){const n=e?` (Grund: ${e})`:"";return[`\u{1F512} Der Zugang fuer Mitglieder zu Brain "${t}" geht gerade nicht${n}.`,`Bitte den Besitzer des Brains oder einen Org-Admin fragen. Rollen und Zugang stehen unter ${w}.`,"(Member access to this brain is not available right now; ask the brain owner or an organisation admin.)"].join(`
2
- `)}const v="Das darf nur der Besitzer oder ein Admin.";function A(t){return`${v} Deine Rolle: ${t}.`}class U extends Error{rolle;constructor(e){super(A(e)),this.name="SchreibVerweigert",this.rolle=e}}function _(t){if(!t||typeof t!="object")return!1;const e=t;return/\bNOPERM\b/.test(String(e.message??""))?!0:Array.isArray(e.previousErrors)&&e.previousErrors.some(n=>_(n))}const k=new O;function F(t){const e=k.getStore();e&&(e.abgewiesen++,e.rolle=t)}async function ee(t){const e={abgewiesen:0};return{ergebnis:await k.run(e,t),abgewiesen:e.abgewiesen,rolle:e.rolle}}function te(t,e,n="contributor"){if(e<=0||t.includes(v))return t;const r=e===1?"1 Schreibbefehl":`${e} Schreibbefehle`;return`${t}
1
+ import{AsyncLocalStorage as T}from"node:async_hooks";import{mitgliedDarfSchreiben as O}from"./schluessel-klassen.js";const D=new Set(["admin","reviewer","contributor","viewer"]),M=6e4,m="https://cachly.dev/team";let h=null,$=()=>"";const p=new Map,g=new Map;function z(t){h=t.abruf,$=t.bereich??(()=>""),p.clear(),g.clear()}function W(){z({abruf:null}),d.clear()}function L(t){if(!t||typeof t!="object")return null;const e=t;if(typeof e.role!="string"||!D.has(e.role))return null;const n=e.can&&typeof e.can=="object"?e.can:{};return{role:e.role,source:typeof e.source=="string"?e.source:"",can:{learn:n.learn===!0,confirm:n.confirm===!0,withdraw:n.withdraw===!0,manage:n.manage===!0},review_mode:e.review_mode===!0,protection:typeof e.protection=="string"?e.protection:"",...e.knowledge&&typeof e.knowledge=="object"?{knowledge:e.knowledge}:{},...typeof e.min_mcp=="string"?{min_mcp:e.min_mcp}:{},...e.rooms===!0?{rooms:!0}:{}}}function x(t){return`${$()}|${t}`}async function q(t){if(!h||!t)return null;const e=x(t),n=p.get(e);if(n&&Date.now()-n.am<M)return n.auskunft;const o=g.get(e);return n?(o||S(e,t,n),n.auskunft):o||S(e,t,void 0)}function S(t,e,n){if(!h)return Promise.resolve(n?.auskunft??null);const o=h,r=(async()=>{try{const i=L(await o(`/api/v1/instances/${encodeURIComponent(e)}/role`));return p.set(t,{auskunft:i,am:Date.now()}),i}catch(i){return b(i).status===404?(p.set(t,{auskunft:null,am:Date.now()}),null):n?.auskunft??null}})().finally(()=>g.delete(t));return g.set(t,r),r}function P(t){return p.get(x(t))?.auskunft??null}function K(t,e,n){if(t&&typeof t=="object"){const o=n&&typeof n=="object"?n:{};Object.assign(t,{apiStatus:e,...typeof o.code=="string"?{apiCode:o.code}:{},...typeof o.role=="string"?{apiRole:o.role}:{},...typeof o.reason=="string"?{apiReason:o.reason}:{}})}return t}function b(t){const e=t&&typeof t=="object"?t:{},n=(u,a)=>typeof u=="string"?u:typeof a=="string"?a:void 0,o={},r=typeof e.apiStatus=="number"?e.apiStatus:typeof e.status=="number"?e.status:void 0;r!==void 0&&(o.status=r);const i=n(e.apiCode,e.code);i!==void 0&&(o.code=i);const s=n(e.apiRole,e.role);s!==void 0&&(o.role=s);const c=n(e.apiReason,e.reason);if(c!==void 0&&(o.reason=c),o.status===void 0){const u=/\((\d{3})\)|error (\d{3})/.exec(String(e.message??""));u&&(o.status=Number(u[1]??u[2]))}return o}const w=new WeakMap;function v(t){return t&&typeof t=="object"?w.get(t):void 0}function C(t){return v(t)?.access==="member"}function I(t){const e=v(t);return(e?.instanceId?P(e.instanceId)?.role:void 0)??e?.role??"contributor"}function Q(t,e){return!C(t)||O(e)}const X="member_access_unavailable";function Y(t,e){const n=e?` (Grund: ${e})`:"";return[`\u{1F512} Der Zugang fuer Mitglieder zu Brain "${t}" geht gerade nicht${n}.`,`Bitte den Besitzer des Brains oder einen Org-Admin fragen. Rollen und Zugang stehen unter ${m}.`,"(Member access to this brain is not available right now; ask the brain owner or an organisation admin.)"].join(`
2
+ `)}const A="Das darf nur der Besitzer oder ein Admin.";function R(t){return`${A} Deine Rolle: ${t}.`}class U extends Error{rolle;constructor(e){super(R(e)),this.name="SchreibVerweigert",this.rolle=e}}function _(t){if(!t||typeof t!="object")return!1;const e=t;return/\bNOPERM\b/.test(String(e.message??""))?!0:Array.isArray(e.previousErrors)&&e.previousErrors.some(n=>_(n))}const k=new T;function F(t){const e=k.getStore();e&&(e.abgewiesen++,e.rolle=t)}async function ee(t){const e={abgewiesen:0};return{ergebnis:await k.run(e,t),abgewiesen:e.abgewiesen,rolle:e.rolle}}function te(t,e,n="contributor"){if(e<=0||t.includes(A))return t;const o=e===1?"1 Schreibbefehl":`${e} Schreibbefehle`;return`${t}
3
3
 
4
- \u{1F512} ${A(n)} Nicht gespeichert: ${r} dieses Aufrufs.`}function y(t){return!!t&&typeof t.then=="function"}function V(t){return e=>{if(!_(e))return e;const n=t();return F(n),new U(n)}}function Z(t,e){return Array.isArray(t)?t.map(n=>Array.isArray(n)&&n[0]?[e(n[0]),n[1]]:n):t}function H(t,e){const n=new Map,r=new Proxy(t,{get(o,i){const s=Reflect.get(o,i,o);if(typeof s!="function")return s;if(n.has(i))return n.get(i);const u=(...c)=>{const a=s.apply(o,c);return a===o?r:i==="exec"&&y(a)?a.then(l=>Z(l,e),l=>{throw e(l)}):y(a)?a.then(void 0,l=>{throw e(l)}):a};return n.set(i,u),u}});return r}function ne(t,e){const n={...e,access:"member"},r=V(()=>L(i)),o=new Map,i=new Proxy(t,{get(s,u){const c=Reflect.get(s,u,s);if(typeof c!="function")return c;if(o.has(u))return o.get(u);const a=(...l)=>{const f=c.apply(s,l);return f===s?i:y(f)?f.then(void 0,B=>{throw r(B)}):(u==="pipeline"||u==="multi")&&f&&typeof f=="object"?H(f,r):f};return o.set(u,a),a}});return b.set(i,n),i}function re(t,e={}){b.set(t,{...e,access:"full"})}function N(t,e){const n=h(t);return n.role?n.role:n.code?.startsWith("role_")?n.code.slice(5):e}function E(t){return(t instanceof Error?t.message:String(t)).split(`
5
- `)[0].slice(0,300)}async function oe(t,e,n,r){let o;try{o=await t(`/api/v1/instances/${encodeURIComponent(e)}/learn`,{method:"POST",body:JSON.stringify({source:"mcp",...n})})}catch(s){return h(s).status===403?[`\u{1F512} Deine Rolle (${N(s,r)}) darf in diesem Brain keine Lektionen speichern. Nichts wurde gespeichert.`,`Rollen setzt der Besitzer oder ein Admin unter ${w}.`].join(`
6
- `):`\u26A0\uFE0F Nicht gespeichert: Die API hat \`${n.topic}\` nicht angenommen (${E(s)}). Bitte noch einmal versuchen.`}const i=o?.topic||n.topic;return o?.proposed?[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${i}\` 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(`
7
- `):[`\u2705 Lesson stored: \`${i}\` (${n.outcome}) \u2014 saved through the cachly API as a team member (role: ${r}).`,`\u{1F4A1} ${String(n.what_worked??"").slice(0,120)}`].join(`
8
- `)}async function ie(t,e,n,r){try{const o=await t(`/api/v1/instances/${encodeURIComponent(e)}/lessons/confirm`,{method:"POST",body:JSON.stringify(n)}),i=o?.review_level==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",s=Number(o?.endorsements??0);return`${i} \u2014 \`${o?.topic??n.topic}\` confirmed by **${o?.reviewed_by??"?"}** (role: ${r}, ${s} distinct endorsement${s===1?"":"s"}).
9
- \u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.`}catch(o){const i=h(o);return i.status===403?[`\u{1F512} Bestaetigen duerfen nur reviewer und admin. Deine Rolle: ${N(o,r)}. Nichts wurde geaendert.`,`Rollen setzt der Besitzer oder ein Admin unter ${w}.`].join(`
4
+ \u{1F512} ${R(n)} Nicht gespeichert: ${o} dieses Aufrufs.`}function y(t){return!!t&&typeof t.then=="function"}function G(t){return e=>{if(!_(e))return e;const n=t();return F(n),new U(n)}}function V(t,e){return Array.isArray(t)?t.map(n=>Array.isArray(n)&&n[0]?[e(n[0]),n[1]]:n):t}function Z(t,e){const n=new Map,o=new Proxy(t,{get(r,i){const s=Reflect.get(r,i,r);if(typeof s!="function")return s;if(n.has(i))return n.get(i);const c=(...u)=>{const a=s.apply(r,u);return a===r?o:i==="exec"&&y(a)?a.then(l=>V(l,e),l=>{throw e(l)}):y(a)?a.then(void 0,l=>{throw e(l)}):a};return n.set(i,c),c}});return o}function ne(t,e){const n={...e,access:"member"},o=G(()=>I(i)),r=new Map,i=new Proxy(t,{get(s,c){const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(r.has(c))return r.get(c);const a=(...l)=>{const f=u.apply(s,l);return f===s?i:y(f)?f.then(void 0,j=>{throw o(j)}):(c==="pipeline"||c==="multi")&&f&&typeof f=="object"?Z(f,o):f};return r.set(c,a),a}});return w.set(i,n),i}function re(t,e={}){w.set(t,{...e,access:"full"})}function N(t,e){const n=b(t);return n.role?n.role:n.code?.startsWith("role_")?n.code.slice(5):e}function E(t){return(t instanceof Error?t.message:String(t)).split(`
5
+ `)[0].slice(0,300)}async function oe(t,e,n,o){let r;try{r=await t(`/api/v1/instances/${encodeURIComponent(e)}/learn`,{method:"POST",body:JSON.stringify({source:"mcp",...n})})}catch(c){const u=b(c);return u.status===403&&u.code==="group_forbidden"?[`\u{1F512} Du bist nicht Mitglied der Gruppe \`${n.group??""}\`. Nichts wurde gespeichert.`,`Gruppen setzt der Besitzer oder ein Admin unter ${m}.`].join(`
6
+ `):u.status===409&&u.code==="topic_exists_team"?`\u26A0\uFE0F Nicht gespeichert: Das Thema \`${n.topic}\` gibt es schon als Team-Lektion. Bitte einen anderen Namen waehlen.`:u.status===403?[`\u{1F512} Deine Rolle (${N(c,o)}) darf in diesem Brain keine Lektionen speichern. Nichts wurde gespeichert.`,`Rollen setzt der Besitzer oder ein Admin unter ${m}.`].join(`
7
+ `):`\u26A0\uFE0F Nicht gespeichert: Die API hat \`${n.topic}\` nicht angenommen (${E(c)}). Bitte noch einmal versuchen.`}const i=r?.topic||n.topic;if(r?.proposed)return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${i}\` 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(`
8
+ `);const s=r?.room==="private"?" in your private room":r?.room==="group"?` in the room of group \`${n.group??""}\``:"";return[`\u2705 Lesson stored: \`${i}\` (${n.outcome})${s} \u2014 saved through the cachly API as a team member (role: ${o}).`,`\u{1F4A1} ${String(n.what_worked??"").slice(0,120)}`].join(`
9
+ `)}async function ie(t,e,n,o){try{const r=await t(`/api/v1/instances/${encodeURIComponent(e)}/lessons/confirm`,{method:"POST",body:JSON.stringify(n)}),i=r?.review_level==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",s=Number(r?.endorsements??0);return`${i} \u2014 \`${r?.topic??n.topic}\` confirmed by **${r?.reviewed_by??"?"}** (role: ${o}, ${s} distinct endorsement${s===1?"":"s"}).
10
+ \u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.`}catch(r){const i=b(r);return i.status===403?[`\u{1F512} Bestaetigen duerfen nur reviewer und admin. Deine Rolle: ${N(r,o)}. Nichts wurde geaendert.`,`Rollen setzt der Besitzer oder ein Admin unter ${m}.`].join(`
10
11
  `):i.status===404?`\u{1F4ED} No best-solution lesson found for \`${n.topic}\`.
11
12
 
12
- A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`:`\u26A0\uFE0F Nicht bestaetigt: Die API hat \`${n.topic}\` nicht angenommen (${E(o)}).`}}const j=25,d=new Set;function se(t,e,n){const r=[...new Set(n.map(o=>String(o).trim()).filter(o=>o&&o.length<=200))];for(let o=0;o<r.length;o+=j){const i=r.slice(o,o+j),s=t(`/api/v1/instances/${encodeURIComponent(e)}/lessons/recalled`,{method:"POST",body:JSON.stringify({topics:i})}).then(()=>{},()=>{}).finally(()=>{d.delete(s)});d.add(s)}}async function ue(){for(;d.size>0;)await Promise.all([...d])}export{j as ABRUF_HOECHSTENS,X as CODE_ZUGANG_NICHT_VERFUEGBAR,w as ROLLEN_SEITE,M as ROLLE_FRISCH_MS,v as SCHREIBVERBOT_ANFANG,U as SchreibVerweigert,ue as abrufMeldungenFertig,ne as alsMitgliedsSpeicher,z as alsRollenAuskunft,h as apiFehler,ie as bestaetigeUeberApi,Q as darfDirektSchreiben,q as holeRolle,ee as imWerkzeugLauf,I as istMitglied,_ as istNoPerm,oe as lerneUeberApi,K as markiereApiFehler,se as meldeAbrufe,re as merkeVollenZugang,te as mitAbweisungsHinweis,P as richteRolleEin,L as rolleFuer,C as rolleImSpeicher,A as schreibverbotText,W as setzeRollenZustandZurueck,Y as zugangNichtVerfuegbarText,R as zugangVon};
13
+ A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`:`\u26A0\uFE0F Nicht bestaetigt: Die API hat \`${n.topic}\` nicht angenommen (${E(r)}).`}}const B=25,d=new Set;function se(t,e,n){const o=[...new Set(n.map(r=>String(r).trim()).filter(r=>r&&r.length<=200))];for(let r=0;r<o.length;r+=B){const i=o.slice(r,r+B),s=t(`/api/v1/instances/${encodeURIComponent(e)}/lessons/recalled`,{method:"POST",body:JSON.stringify({topics:i})}).then(()=>{},()=>{}).finally(()=>{d.delete(s)});d.add(s)}}async function ue(){for(;d.size>0;)await Promise.all([...d])}export{B as ABRUF_HOECHSTENS,X as CODE_ZUGANG_NICHT_VERFUEGBAR,m as ROLLEN_SEITE,M as ROLLE_FRISCH_MS,A as SCHREIBVERBOT_ANFANG,U as SchreibVerweigert,ue as abrufMeldungenFertig,ne as alsMitgliedsSpeicher,L as alsRollenAuskunft,b as apiFehler,ie as bestaetigeUeberApi,Q as darfDirektSchreiben,q as holeRolle,ee as imWerkzeugLauf,C as istMitglied,_ as istNoPerm,oe as lerneUeberApi,K as markiereApiFehler,se as meldeAbrufe,re as merkeVollenZugang,te as mitAbweisungsHinweis,z as richteRolleEin,I as rolleFuer,P as rolleImSpeicher,R as schreibverbotText,W as setzeRollenZustandZurueck,Y as zugangNichtVerfuegbarText,v as zugangVon};
@@ -1 +1 @@
1
- const l=Object.freeze({team:"S",lesson:"W",lessons:"W",ckg:"W",crystal:"W",contradictions:"W",idx:"W",index:"W",withdrawn:"W",global:"W",fedbrain:"W",fed:"W",brain:"W",brain_from_git:"W",meta:"W",public:"W",doppel:"W","letzter-recall":"W",liefer:"W",ctx:"B",cls:"B",wirkung:"B",lock:"B",mcp:"B",mcm:"B",prefs:"B",dep:"B",session:"B",stats:"B",sem:"B",roadmap:"B",recall:"B",streak:"B",agents:"B",stream:"B",vek:"B",startwissen:"B",versuch:"B",quota:"B",aussetzer:"B"}),i=Object.freeze(["%R~*","~[^c]*","~c[^a]*","~ca[^c]*","~cac[^h]*","~cach[^l]*","~cachl[^y]*","~cachly[^:]*","~cachly:[^tlciwgfbmpd]*","~cachly:ctx:*","~cachly:cls:*","~cachly:wirkung:*","~cachly:lock:*","~cachly:mcp:*","~cachly:mcm:*","~cachly:prefs:*","~cachly:dep:*","+@all","-@admin","-@dangerous","+keys","+info"]);function o(e){let c="";for(let t=0;t<e.length;t++){const s=e[t];if(s==="*")c+="[\\s\\S]*";else if(s==="?")c+="[\\s\\S]";else if(s==="["){const n=e.indexOf("]",t+1);if(n===-1){c+="\\[";continue}let a=e.slice(t+1,n);const r=a.startsWith("^");r&&(a=a.slice(1)),c+=`[${r?"^":""}${a.replace(/[\\\]]/g,"\\$&")}]`,t=n}else s==="\\"&&t+1<e.length?c+=e[++t].replace(/[.*+?^${}()|[\]\\/]/g,"\\$&"):c+=s.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}return new RegExp(`^${c}$`)}const f=i.filter(e=>e.startsWith("~")).map(e=>o(e.slice(1)));function B(e){return f.some(c=>c.test(e))}function h(e){const c=/^cachly:([A-Za-z0-9_-]+)/.exec(e);return c?c[1]:""}function p(e){return e.startsWith("cachly:")?l[h(e)]:"B"}export{i as MITGLIED_MUSTER,l as SCHLUESSEL_KLASSEN,h as familieVon,o as globAlsRegex,p as klasseVon,B as mitgliedDarfSchreiben};
1
+ import{mitgliedMuster as a}from"./raeume.js";const l=Object.freeze({team:"S",lesson:"W",lessons:"W",ckg:"W",crystal:"W",contradictions:"W",idx:"W",index:"W",withdrawn:"W",global:"W",fedbrain:"W",fed:"W",brain:"W",brain_from_git:"W",meta:"W",public:"W",doppel:"W",zone:"W",ctx:"B",cls:"B",wirkung:"B",lock:"B",mcp:"B",mcm:"B",prefs:"B",dep:"B","letzter-recall":"B",liefer:"B",session:"B",stats:"B",sem:"B",roadmap:"B",recall:"B",streak:"B",agents:"B",stream:"B",vek:"B",startwissen:"B",versuch:"B",quota:"B",aussetzer:"B"}),o=Object.freeze(a({gruppen:[]}));function B(e){let t="";for(let r=0;r<e.length;r++){const s=e[r];if(s==="*")t+="[\\s\\S]*";else if(s==="?")t+="[\\s\\S]";else if(s==="["){const i=e.indexOf("]",r+1);if(i===-1){t+="\\[";continue}let n=e.slice(r+1,i);const c=n.startsWith("^");c&&(n=n.slice(1)),t+=`[${c?"^":""}${n.replace(/[\\\]]/g,"\\$&")}]`,r=i}else s==="\\"&&r+1<e.length?t+=e[++r].replace(/[.*+?^${}()|[\]\\/]/g,"\\$&"):t+=s.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}return new RegExp(`^${t}$`)}const f=o.filter(e=>e.startsWith("~")).map(e=>B(e.slice(1)));function m(e){return f.some(t=>t.test(e))}function p(e){const t=/^cachly:([A-Za-z0-9_-]+)/.exec(e);return t?t[1]:""}function u(e){return e.startsWith("cachly:")?l[p(e)]:"B"}export{o as MITGLIED_MUSTER,l as SCHLUESSEL_KLASSEN,p as familieVon,B as globAlsRegex,u as klasseVon,m as mitgliedDarfSchreiben};
@@ -1 +1 @@
1
- import{ErrorCode as t,McpError as i}from"@modelcontextprotocol/sdk/types.js";import{alsMitgliedsSpeicher as d,apiFehler as a,CODE_ZUGANG_NICHT_VERFUEGBAR as u,zugangNichtVerfuegbarText as p}from"./rolle.js";async function h(e,o){try{return await e()}catch(r){const s=a(r);if(s.status===409&&s.code===u)throw new i(t.InvalidRequest,p(o,s.reason));const n=r instanceof Error?r.message:String(r);if(n.includes("401")||n.includes("403")||n.includes("Unauthorized"))throw new i(t.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.");return}}function w(e){const o=typeof e?.username=="string"&&e.username?e.username:void 0,r=typeof e?.password=="string"&&e.password?e.password:void 0;return{...o?{username:o}:{},...r?{password:r}:{},mitglied:e?.access==="member",...typeof e?.role=="string"?{role:e.role}:{}}}function l(e){return{...e.username?{username:e.username}:{},password:e.password||void 0}}function g(e,o,r,s){const n=new e({...o,...l(r)}),c=r.mitglied?d(n,{role:r.role,username:r.username,instanceId:s}):n;return{roh:n,nutzbar:c}}export{l as anmeldeOptionen,w as anmeldungAus,g as baueSpeicherClient,h as holeVerbindungsAuskunft};
1
+ import{ErrorCode as n,McpError as i}from"@modelcontextprotocol/sdk/types.js";import{alsMitgliedsSpeicher as u,apiFehler as a,CODE_ZUGANG_NICHT_VERFUEGBAR as m,merkeVollenZugang as p,zugangNichtVerfuegbarText as d}from"./rolle.js";import{raeumeAusAuskunft as l}from"./raeume.js";async function y(e,t){try{return await e()}catch(r){const o=a(r);if(o.status===409&&o.code===m)throw new i(n.InvalidRequest,d(t,o.reason));const s=r instanceof Error?r.message:String(r);if(s.includes("401")||s.includes("403")||s.includes("Unauthorized"))throw new i(n.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.");return}}function A(e){const t=typeof e?.username=="string"&&e.username?e.username:void 0,r=typeof e?.password=="string"&&e.password?e.password:void 0,o=l(e?.rooms);return{...o?{raeume:o}:{},...t?{username:t}:{},...r?{password:r}:{},mitglied:e?.access==="member",...typeof e?.role=="string"?{role:e.role}:{}}}function f(e){return{...e.username?{username:e.username}:{},password:e.password||void 0}}function E(e,t,r,o){const s=new e({...t,...f(r)}),c=r.mitglied?u(s,{role:r.role,username:r.username,instanceId:o,...r.raeume?{raeume:r.raeume}:{}}):s;return!r.mitglied&&r.raeume&&p(s,{instanceId:o,username:r.username,raeume:r.raeume}),{roh:s,nutzbar:c}}export{f as anmeldeOptionen,A as anmeldungAus,E as baueSpeicherClient,y as holeVerbindungsAuskunft};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.281",
3
+ "version": "0.10.283",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.281",
3
+ "version": "0.10.283",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Explain it once. Every AI knows it. cachly keeps your project's rules, decisions and fixes for every AI tool, for you, your team and your company.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -17,12 +17,12 @@
17
17
  "url": "https://github.com/cachly-dev/cachly-mcp",
18
18
  "source": "github"
19
19
  },
20
- "version": "0.10.281",
20
+ "version": "0.10.283",
21
21
  "packages": [
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "@cachly-dev/mcp-server",
25
- "version": "0.10.281",
25
+ "version": "0.10.283",
26
26
  "runtimeHint": "npx",
27
27
  "transport": {
28
28
  "type": "stdio"