@cachly-dev/mcp-server 0.10.285 → 0.10.287

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,64 +1,64 @@
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})
1
+ import{readFileSync as Ee}from"node:fs";import{bauabdruck as Ce,formatiereBauabdruck as Te}from"../bauabdruck.js";import{beurteileSpeicher as De,zahlAusInfo as we}from"../speicherlage.js";import{beurteileDeckung as Me}from"../eingaenge.js";import{VEKTOR_NACHTRAG as ze,NAME_VEKTOR_NACHTRAG as Ie,ZWEIT_VEKTOR_NACHTRAG as Pe}from"../bedeutung.js";import{join as B}from"node:path";import{calculateConfidence as te,CONFIDENCE_STALE_VALUE as le,CONFIDENCE_WARN_VALUE as Fe,CONFIDENCE_WARN_DAYS as ye,CONFIDENCE_STALE_DAYS as _e}from"../confidence.js";import{safeJsonParse as z,leseOderNull as $e,darfHeraus as Be,teamweitLesbar as J}from"../utils.js";import{ersparteMinuten as Ue,istStarterLektion as Ke,fmtStunden as ve}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Je,buildClaudeMdBlock as Ge,setzeAnweisungsblock as He}from"../projektdateien.js";import{aussetzerEinzelheit as qe,aussetzerErklaerung as be,leseVermerke as We}from"../aussetzer.js";import{schwaerzeFelder as Ve}from"../geheimnis-filter.js";import{VERDACHT_TAG as ke,pruefeFelder as Ye,verdachtsWarnung as Ze}from"../tuersteher.js";import{fuerEigenenSpeicher as ue,fuerWeitergabe as Xe,fuerZusammenfassung as Se,hinweise as he,markiert as Qe,markierungsWarnung as et,weitergabeHinweis as tt}from"../schreibtor.js";import{holeRolle as U,istMitglied as de,rolleFuer as xe,lerneUeberApi as st,bestaetigeUeberApi as nt,ROLLEN_SEITE as W}from"../rolle.js";import{kontoSchluessel as V}from"../konto-bereich.js";const Nt=new Set(["sync_file_changes","team_learn","team_confirm","team_recall","team_synthesize","memory_crystalize","team_crystallize","brain_doctor","brain_hygiene","recall_at","trace_dependency","global_learn","global_recall","publish_lesson","import_public_brain","setup_ai_memory","team_assign_role","team_whoami","team_roster","team_grant_scope","team_scopes","team_audit"]),Y={admin:4,reviewer:3,contributor:2,viewer:1},F={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},se={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 Z(w,m,y){return await w.hget(H(m),y.toLowerCase()).catch(()=>null)}async function ot(w,m,y){const L=await U(m);return L?L.role:y?Z(w,m,y):null}const pe={owner:"owner of this brain",org_admin:"organisation admin",assigned:"assigned by an admin",default:"default for members"};function me(w){const m=pe[w.source]??w.source;return m?`${w.role} (${m})`:w.role}function Q(w,m){return w?(Y[w]??0)>=(Y[m]??0):!1}function at(w){return w==="admin"||w==="reviewer"?"senior":"peer"}async function rt(w,m){if(await U(m))return!0;const y=await w.hgetall(H(m)).catch(()=>({}));return Object.values(y).includes("admin")}async function fe(w,m,y,L,r){const t=await U(m);if(t)return Q(t.role,L)?null:[`\u{1F512} **Permission denied** \u2014 to ${r} you need at least \`${L}\` ${F[L]} (your role: ${F[t.role]} ${me(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 rt(w,m))return null;const n=y?await Z(w,m,y):null;if(Q(n,L))return null;const i=n?`${F[n]} ${n}`:"no role";return[`\u{1F512} **Permission denied** \u2014 to ${r} you need at least \`${L}\` ${F[L]} (you have: ${i}).`,"","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 Ae(w,m,y){const L=`cachly:team:audit:${m}`,r=JSON.stringify({...y,ts:new Date().toISOString()});await w.rpush(L,r).catch(()=>{}),await w.ltrim(L,-500,-1).catch(()=>{}),await w.expire(L,365*2*86400).catch(()=>{})}const it="cachly:team:review_mode",ct="cachly:lesson:proposed:",lt=90*86400;async function ut(w,m){const y=await w.get(it).catch(()=>null);return y==="1"||y==="true"||y==="on"}async function ht(w,m,y){const L={...y,proposed_at:new Date().toISOString(),status:"pending"};await w.set(`${ct}${m}`,JSON.stringify(L),"EX",lt).catch(()=>{});const r=typeof y.author=="string"&&y.author?` by **${y.author}**`:"";return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${m}\`${r} 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 ne=w=>`cachly:team:groups:${w}`,ee=(w,m)=>`cachly:team:group:${w}:${m.toLowerCase()}`;async function Re(w,m,y){const L=await w.smembers(ne(m)).catch(()=>[]),r=new Set;for(const t of L)await w.sismember(ee(m,t),y.toLowerCase()).catch(()=>0)&&r.add(t.toLowerCase());return r}function Le(w,m,y){return!w||y?!0:m.has(w.toLowerCase())}const oe=Object.freeze({scopes:new Set,isAdmin:!1});async function Ot(w,m,y){const L=await U(m),r=(y??"").trim();if(!r)return L?.role==="admin"?{scopes:new Set,isAdmin:!0}:oe;const t=await Re(w,m,r).catch(()=>new Set),n=L?L.role==="admin":await Z(w,m,r).catch(()=>null)==="admin";return{scopes:t,isAdmin:n}}function dt(w,m){if(!Be(w))return!1;const y=typeof w.group=="string"?w.group.trim():w.group?String(w.group):"";return Le(y||null,m.scopes,m.isAdmin)}function Et(w,m=oe){const y=new Map;return async L=>{const r=y.get(L);if(r!==void 0)return r;const t=await w.get(`cachly:lesson:best:${L}`).catch(()=>null),n=t===null||dt($e(t),m);return y.set(L,n),n}}function je(w,m,y){const L=w.filter(t=>!m.has(t)),r=L.slice(0,y);return{namen:r,rest:w.length-r.length,davonVerborgen:w.length-L.length}}async function Ct(w,m,y,L){switch(w){case"sync_file_changes":{const{instance_id:r,changed_files:t,git_diff_stat:n,commit_msg:i}=m,c=ue({changed_files:t,git_diff_stat:n,commit_msg:i}),{changed_files:e,git_diff_stat:o,commit_msg:l}=c.felder,a=await y(r),s={ts:new Date().toISOString(),files:e,commit_msg:l,diff_stat:o?.slice(0,500),...c.verdacht.length?{verdacht:c.verdacht}:{}};await a.lpush(V(a,"cachly:session:file_changes"),JSON.stringify(s)),await a.ltrim(V(a,"cachly:session:file_changes"),0,99),await a.expire(V(a,"cachly:session:file_changes"),30*86400);const d=[],u=a.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 a.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`:""}`,"",...he(c,"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 r=Ve(m).felder,t=Ye(r),{instance_id:n,author:i,topic:c,outcome:e,what_worked:o,what_failed:l,severity:a,file_paths:s,commands:d,tags:u}=r,_=m.visibility==="private"?"private":void 0,x=String(m.group??"").trim().toLowerCase(),b=_!=="private"&&!x;if(!i||!c||!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(!i.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 fe(A,R,i,"contributor","store team lessons");if(S)return S;if(de(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
+ `):st(L,R,{topic:c,outcome:e,what_worked:o,what_failed:l??"",severity:a??"minor",file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[ke]:[]],author:i,...b?{}:{visibility:_??"team",...x?{group:x}:{}}},xe(A));const k={topic:c,outcome:e,what_worked:o,what_failed:l??"",severity:a??"minor",author:i,file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[ke]:[]],timestamp:new Date().toISOString(),ts:new Date().toISOString(),recall_count:0,version:2};if(await ut(A,R))return ht(A,c,k);const g=`cachly:lessons:${c}`;return await A.rpush(g,JSON.stringify(k)),e==="success"&&await A.set(`cachly:lesson:best:${c}`,JSON.stringify(k)),`\u2705 Team lesson stored by **${i}**: \`${c}\` (${e})
7
7
  \u{1F4A1} ${o.slice(0,120)}${t.length?`
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
+ ${Ze(t)}`:""}`}case"team_confirm":{const{instance_id:r,topic:t,reviewer:n,level:i,note:c=""}=m,e=ue({note:c}),o=e.felder.note;if(!r)return"\u274C instance_id required";if(!t||!n)return"\u274C Required: topic, reviewer";const l=await y(r),a=await fe(l,r,n,"reviewer","confirm team lessons");if(a)return a;if(de(l))return nt(L,r,{topic:t,...i?{tier:i}:{},...o?{note:o.slice(0,280)}:{}},xe(l));const s=await ot(l,r,n),d=at(s),u=i==="peer"?"peer":i==="senior"&&Q(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}\`.
9
9
 
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
+ 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 Ae(l,r,{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}.
11
11
  \u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.${o?`
12
- \u{1F4DD} ${o.slice(0,200)}`:""}${ue(e,"notiz").map(E=>`
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 ")}.
12
+ \u{1F4DD} ${o.slice(0,200)}`:""}${he(e,"notiz").map(E=>`
13
+ ${E}`).join("")}`}case"team_recall":{const{instance_id:r,author:t,limit:n=10}=m,i=m.topic??(typeof m.query=="string"?m.query:void 0),c=Number.isFinite(Number(n))&&Number(n)>=1?Math.floor(Number(n)):10,e=await y(r),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 a=[];if(o.length>0){const u=await e.mget(...o);for(const _ of u){const x=J(_);x&&a.push(x)}}if(i){const u=i.toLowerCase();a=a.filter(_=>_.topic.toLowerCase().includes(u)||(_.tags??[]).some(x=>x.toLowerCase().includes(u)))}if(t){const u=t.toLowerCase();a=a.filter(_=>_.author?.toLowerCase().includes(u))}const s=u=>u.reviewed_by?u.review_level==="senior"?2:1:0;if(a.sort((u,_)=>s(_)-s(u)||(_.recall_count??0)-(u.recall_count??0)),a=a.slice(0,c),a.length===0)return i||t?`\u{1F4ED} No team lessons found for ${[i&&`topic \`${i}\``,t&&`author \`${t}\``].filter(Boolean).join(" and ")}.
14
14
 
15
15
  Add lessons with \`team_learn\` (requires an \`author\`).`:`\u{1F4ED} No lessons in this brain yet.
16
16
 
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.
17
+ All team members sharing this instance will see lessons here.`;const d=[`\u{1F465} **Team Brain** \u2014 ${a.length} lesson${a.length>1?"s":""}`,""];for(const u of a){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=et(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:r,topic:t}=m,n=await y(r),i=`cachly:lessons:${t}`,c=(await n.lrange(i,0,-1)).filter(p=>J(p)!==null);if(c.length<2)return`\u{1F4ED} Need at least 2 entries for topic \`${t}\` to synthesize.
19
19
 
20
- Currently: ${i.length} entr${i.length===1?"y":"ies"}.
20
+ Currently: ${c.length} entr${c.length===1?"y":"ies"}.
21
21
 
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(`
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(`
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}\`.
22
+ Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=c.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"),a=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,...a].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 ${a.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:r,label:t=""}=m,n=await y(r),i=new Date,c=`${i.getFullYear()}-W${String(Math.ceil((i.getDate()-i.getDay()+10)/7)).padStart(2,"0")}`,e=t||`${i.toISOString().slice(0,7)} Crystal`,o=await n.lrange(V(n,"cachly:session:history"),0,49),l=[],a=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((S,p)=>{a.on("data",k=>l.push(...k)),a.on("end",S),a.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=Se(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:i.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:${c}`,R),await n.expire(`cachly:crystal:${c}`,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:r,min_authors:t=2,label:n=""}=m,i=await y(r),c=new Date,e=Math.max(2,Number(t)||2),o=[],l=i.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 a=[];let s=0,d=0;if(o.length>0){const g=await i.mget(...o);for(const h of g){const $=J(h);if(!$||$.outcome!=="success"||!$.author)continue;const N=Se($);if(!N){s++;continue}N.geschwaerzt&&d++,a.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 a){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||`${c.toISOString().slice(0,7)} Team Crystal`,p={label:S,ts:c.toISOString(),kind:"team",contributors:new Set(a.map(g=>g.author.toLowerCase())).size,analysed:a.length,patterns:A,...s>0?{ausgelassen:s}:{}};if(await i.set("cachly:crystal:team:latest",JSON.stringify(p)),await i.expire("cachly:crystal:team:latest",180*86400),A.length===0)return["\u{1F4A0} **Team Crystal \u2014 not enough cross-person convergence yet**","",`Analysed **${a.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 ${a.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:r,workspace_path:t=""}=m,n=await y(r),i=[],c=[],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 a=n.scanStream({match:V(n,"cachly:ctx:*"),count:200});await new Promise((f,v)=>{a.on("data",j=>{l+=j.filter(C=>!C.endsWith(":meta")).length}),a.on("end",f),a.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}=je(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(V(n,"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"&&te(f)<=le),p=s.filter(f=>f.outcome==="success"&&te(f)>le&&te(f)<=Fe),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:*"),ae=await T("cachly:lesson:vec2:*"),re=O>0?Math.round(ae/O*100):0;O>0&&c.push(re>=80?`\u2705 **Second-model coverage: ${re}%** \u2014 ${ae} of ${O} embedded lessons also carry the second-model vector; the second ranking feature is ON`:`\u{1F7E1} **Second-model coverage: ${re}%** \u2014 ${O-ae} 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([ze,Ie,Pe].map(f=>n.smembers(f).then(v=>v.length).catch(()=>0)));if(q.some(f=>f>0)&&c.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?c.push(`\u2705 **Topic-name coverage: 100%** \u2014 all ${O} embedded lessons carry a topic-name vector`):c.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 ie=e.length>0?Math.round(O/e.length*100):100,ce=Me(e.length,O);e.length>0&&(ce==="aus"?(i.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).`),c.push(`\u{1F534} **Semantic search: OFF** \u2014 0 of ${e.length} lessons have an embedding`)):ce==="luecke"?(i.push(`only ${ie}% of lessons have an embedding (${O} of ${e.length}) \u2014 the rest can never be found by meaning.`),c.push(`\u{1F7E1} **Semantic coverage: ${ie}%** \u2014 ${e.length-O} lessons without an embedding`)):(c.push(`\u2705 **Semantic coverage: ${ie}%** \u2014 ${O} full-text, ${E} topic-name, ${M} with error-text entries`+(K>0?`, ${K} with learned question paths`:"")),K===0&&e.length>=20&&c.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 We(n);for(const v of f??[]){const j=qe(v.text);c.push(`\u26A0\uFE0F **Failure noted:** ${be(v.grund)} \u2014 ${v.anzahl}\xD7 (last: ${v.zuletzt})`+(j?` \xB7 ${j}`:"")),i.push(`failures recorded (${v.anzahl}\xD7): ${be(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 ge=s.length>0?R.length/s.length:0;ge<.5&&(D+=10),S.length===0&&(D+=5),h.size>=2&&(D+=5),ce!=="gut"&&(D-=20),D=Math.max(0,Math.min(100,D));const Ne=D>=80?"\u{1F7E2}":D>=50?"\u{1F7E1}":"\u{1F534}",Oe=N>=50?"\u{1F680}":N>=20?"\u{1F4C8}":"\u{1F4A4}";c.push(`${Ne} **Brain Quality Score: ${D}/100**`),c.push(`${Oe} **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)c.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,X)=>P+X,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?(c.push(`\u{1F7E1} **Rank spread: ${I}** \u2014 ranking has stopped separating hits; provisional threshold, see card 0u9s8qoopwhr`),i.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).")):c.push(`\u{1F4CF} **Rank spread:** ${I}`)}}catch{}c.push(`\u{1F4DA} **Lessons:** ${e.length} (${A.length} critical \xB7 ${k.length} with audit trail \xB7 ${g.length} from team)`),c.push(`\u{1F4BE} **Context entries:** ${l}`),c.push(`\u{1F3AF} **Confidence:** ${s.length-S.length-p.length} fresh \xB7 ${p.length} warn \xB7 ${S.length} stale`),c.push(`\u23F1\uFE0F **Decay config:** warn after ${ye}d \xB7 stale after ${_e}d`),c.push(Te(Ce));try{const f=await n.info("memory");let v=null;if(de(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:we(f,"used_memory"),grenze:we(f,"maxmemory"),richtlinie:v};for(const C of De(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"?i.push(P):c.push(P)}}catch{i.push("\u26AA **Storage:** state could not be read \u2014 unknown whether this store silently deletes when it is full.")}h.size>=2&&c.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?i.push(`\u{1F504} Index is ${v}d stale \u2014 run \`index_project\` to re-sync semantic search`):c.push(`\u{1F5C2}\uFE0F **Semantic index:** ${v}d old (fresh)`)}else i.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);c.push(`\u{1F48E} **Memory Crystal:** ${v.label} (${j}d ago)`),j>30&&i.push(`\u{1F4A1} Memory Crystal is ${j}d old \u2014 re-run \`memory_crystalize\` to compress new sessions`)}else e.length>=10&&i.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=Ee(f,"utf-8"),j=JSON.parse(v),C={...j.dependencies,...j.devDependencies},I=["openai","@anthropic-ai/sdk","@google/generative-ai","mistralai","cohere-ai"].some(X=>X in C),P="@cachly-dev/openclaw"in C;I&&!P?(i.push(`\u{1F4A1} **openclaw missing:** you use LLM APIs (${Object.keys(C).filter(X=>["openai","@anthropic-ai/sdk"].includes(X)).join(", ")}) but not \`@cachly-dev/openclaw\``),i.push(" \u2192 `npm install @cachly-dev/openclaw` cuts LLM costs 60\u201390% with 3 lines of code")):P&&c.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`;c.push(`\u{1F550} **Last session:** ${v} ago`)}else i.push("\u274C No session history \u2014 call `session_start` + `session_end` to start tracking");e.length===0?i.push("\u274C No lessons \u2014 call `learn_from_attempts` after solving bugs"):e.length<5&&i.push(`\u{1F4A1} Only ${e.length} lessons \u2014 add more after each problem solved`),N===0&&s.length>=5&&i.push("\u{1F4A4} **IQ Boost is 0%** \u2014 lessons exist but are never recalled. Use `recall_best_solution` BEFORE tasks."),l===0&&i.push("\u{1F4A1} No context \u2014 use `remember_context` to cache architecture docs, ADRs, etc."),b.length>0&&i.push(`\u26A0\uFE0F ${b.length} unresolved failure${b.length>1?"s":""}: ${u(b)}`),S.length>0&&(i.push(`\u{1F534} ${S.length} STALE lesson${S.length>1?"s":""} (${_e}d+ since written or checked, confidence ${le*100}%): ${u(S)}`),i.push(" \u2192 Re-run each check, then confirm with `lesson_verified` (recalling does not reset the clock)")),p.length>0&&i.push(`\u26A0\uFE0F ${p.length} lesson${p.length>1?"s":""} aging (${ye}d+): ${u(p)}`),ge>.7&&s.length>5&&i.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**",...c.map(f=>" "+f),""];return i.length>0?(G.push(`**\u{1F527} Action Items** (${i.length} issue${i.length>1?"s":""})`),i.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:r,dry_run:t=!1,provisional_threshold:n=.5,archive_days:i=30}=m,c=await y(r),e=[],o=c.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 c.mget(...e),a=[],s=new Set;for(let h=0;h<e.length;h++){const $=l[h],N=z($??null,null);N&&(a.push({...N,_key:e[h]}),J($)||s.add(N.topic))}const d=Date.now(),u=[],_=[],x=[],b=new Map;for(const h of a){const $=h.state??"active";if($==="archived")continue;const N=te(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>i){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 a){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<=i)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 c.get(`cachly:stats:time_saved_mins:${r}`)??"0")||0;for(const h of a){if(Ke(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+=Ue(h))}if(t||await c.set(`cachly:stats:time_saved_mins:${r}`,String(A)).catch(()=>{}),!t&&b.size>0){const h=c.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 **${a.length}** lessons`,"","| Action | Count |","|---|---|",`| Flagged provisional (confidence < ${n}) | ${u.length} |`,`| Archived (stale + low-recall + age > ${i}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:** ${ve(S)} \u2192 **${ve(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}=je(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(`
28
+ `)}case"recall_at":{const{instance_id:r,topic:t,date:n}=m,i=await y(r),c=new Date(n).getTime();if(isNaN(c))return`\u274C Invalid date "${n}". Use ISO format: "2026-01-15"`;const e=`cachly:lessons:${t}`,o=(await i.lrange(e,0,-1)).filter(s=>{const d=$e(s);return d!==null&&Le(d.group,oe.scopes,oe.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()<=c).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 a=[`\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");a.push(`**${u}** ${d} ${s.outcome}`),s.what_worked&&a.push(` \u2192 ${s.what_worked.slice(0,100)}`),a.push("")}return a.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 ")}_`),a.join(`
29
+ `)}case"trace_dependency":{const{instance_id:r,dependency:t,mark_review:n=!1}=m,i=await y(r),c=`cachly:dep:${t}`,e=await i.get(c);if(!e)return`\u{1F4ED} No lessons found that depend on \`${t}\`.
30
30
 
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(`
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}\`
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 a=0;for(const s of o){const d=await i.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){a++,n&&await i.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 i.set(`cachly:lesson:best:${s}`,JSON.stringify(b))}}return a>0&&l.push(` \u{1F512} ${a} 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(`
32
+ `)}case"global_learn":{const{instance_id:r,topic:t,lesson:n,severity:i="minor",tags:c=[]}=m,e=ue({topic:t,lesson:n,tags:c}),{topic:o,lesson:l}=e.felder,a=await y(r),s=`cachly:global:lesson:${o}`,d={topic:o,lesson:l,severity:i,tags:Qe(e.felder.tags,e.verdacht),ts:new Date().toISOString(),scope:"global",recall_count:0},u=await a.get(s);if(u){const _=z(u,null);d.recall_count=_?.recall_count??0}return await a.set(s,JSON.stringify(d)),[`\u{1F310} **Global lesson stored**: \`${o}\`
33
33
 
34
34
  ${l}
35
35
 
36
- Recallable from any project via \`global_recall(topic="${o}")\`.`,...ue(e)].join(`
37
- `)}case"global_recall":{const{instance_id:a,topic:t}=m,n=await y(a),r=[],i=n.scanStream({match:"cachly:global:lesson:*",count:200});await new Promise((l,c)=>{i.on("data",s=>r.push(...s)),i.on("end",l),i.on("error",c)});let e=[];if(r.length>0){const l=await n.mget(...r);for(const c of l){const s=z(c??null,null);s&&e.push(s)}}if(t){const l=t.toLowerCase();e=e.filter(c=>c.topic.toLowerCase().includes(l))}if(e.length===0)return`\u{1F4ED} No global lessons${t?` for \`${t}\``:""}.
36
+ Recallable from any project via \`global_recall(topic="${o}")\`.`,...he(e)].join(`
37
+ `)}case"global_recall":{const{instance_id:r,topic:t}=m,n=await y(r),i=[],c=n.scanStream({match:"cachly:global:lesson:*",count:200});await new Promise((l,a)=>{c.on("data",s=>i.push(...s)),c.on("end",l),c.on("error",a)});let e=[];if(i.length>0){const l=await n.mget(...i);for(const a of l){const s=z(a??null,null);s&&e.push(s)}}if(t){const l=t.toLowerCase();e=e.filter(a=>a.topic.toLowerCase().includes(l))}if(e.length===0)return`\u{1F4ED} No global lessons${t?` for \`${t}\``:""}.
38
38
 
39
- Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;for(const l of e){const c=`cachly:global:lesson:${l.topic}`,s=await n.get(c);if(s){const d=z(s,null);if(!d)continue;d.recall_count=(d.recall_count??0)+1,d.last_recalled_at=new Date().toISOString(),await n.set(c,JSON.stringify(d))}}const o=[`\u{1F310} **Global Brain** \u2014 ${e.length} lesson${e.length>1?"s":""}`,""];for(const l of e){const c=l.severity==="critical"?"\u{1F534} ":l.severity==="major"?"\u{1F7E1} ":"";o.push(`${c}**\`${l.topic}\`**`),o.push(l.lesson.slice(0,200)),o.push("")}return o.join(`
40
- `)}case"publish_lesson":{const{instance_id:a,topic:t,lesson:n,framework:r="general",severity:i="minor"}=m,e=Ze({topic:t,lesson:n,framework:r},"the public library");if(!e.ok)return e.meldung;const{topic:o,lesson:l,framework:c}=e.felder,s=await y(a),d=l.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,"[email]").replace(/\b(sk-|cky_live_|Bearer\s)[A-Za-z0-9_-]{8,}/g,"[token]").replace(/\/Users\/[^\s/]+/g,"/Users/[user]").replace(/\/home\/[^\s/]+/g,"/home/[user]"),u={topic:o,lesson:d,framework:c,severity:i,ts:new Date().toISOString(),published:!0,votes:0},_=`cachly:public:lesson:${c}:${o}`;return await s.set(_,JSON.stringify(u),"EX",365*86400),["\u{1F4E2} **Lesson published!**","",`**Topic:** \`${o}\``,`**Framework:** ${c}`,`**Content:** ${d.slice(0,200)}${d.length>200?"\u2026":""}`,"","This lesson is now available in the Public Brain for other developers.",`Import it anywhere: \`import_public_brain(framework="${c}")\``,...e.geschwaerzt.length?["",et(e.geschwaerzt)]:[]].join(`
41
- `)}case"import_public_brain":{const{instance_id:a,framework:t,limit:n=20}=m,r=await y(a),i={nextjs:[{topic:"nextjs:image-layout",lesson:'Use fill + relative parent instead of layout="fill" (deprecated since Next.js 13)',severity:"major"},{topic:"nextjs:app-router-fetch",lesson:'fetch() in Server Components is cached by default \u2014 add {cache:"no-store"} for dynamic data',severity:"major"},{topic:"nextjs:metadata-export",lesson:"Export metadata const or generateMetadata() \u2014 never both in same file",severity:"minor"},{topic:"nextjs:client-boundary",lesson:'"use client" propagates down \u2014 keep it at the lowest component, not at page level',severity:"major"},{topic:"nextjs:env-prefix",lesson:"Only NEXT_PUBLIC_* env vars are exposed to client \u2014 others are server-only",severity:"critical"},{topic:"nextjs:revalidate",lesson:"export const revalidate = 0 disables caching for entire route; use revalidatePath() for on-demand",severity:"minor"}],fastapi:[{topic:"fastapi:async-db",lesson:"Use async session with asyncpg \u2014 sync SQLAlchemy blocks the event loop",severity:"critical"},{topic:"fastapi:pydantic-v2",lesson:"Pydantic v2: use model_validate() instead of parse_obj(), .dict() \u2192 .model_dump()",severity:"major"},{topic:"fastapi:lifespan",lesson:"Use lifespan context manager instead of deprecated on_event startup/shutdown",severity:"minor"},{topic:"fastapi:background-tasks",lesson:"BackgroundTasks run after response is sent \u2014 not in a separate thread pool",severity:"major"},{topic:"fastapi:cors-order",lesson:"CORSMiddleware must be added before other middleware to work correctly",severity:"critical"}],go:[{topic:"go:context-cancel",lesson:"Always call cancel() from context.WithCancel \u2014 leak goroutines if not cancelled",severity:"critical"},{topic:"go:defer-in-loop",lesson:"defer in a loop runs at function return, not loop iteration \u2014 use IIFE or explicit close",severity:"major"},{topic:"go:nil-interface",lesson:"nil interface != interface containing nil pointer \u2014 use explicit nil checks",severity:"major"},{topic:"go:goroutine-leak",lesson:"Goroutines with channel sends block forever if receiver is gone \u2014 use select with done chan",severity:"critical"},{topic:"go:embed-path",lesson:"//go:embed path must be relative and known at compile time \u2014 no os.Getenv",severity:"minor"}],docker:[{topic:"docker:layer-cache",lesson:"Copy package.json before source code \u2014 Docker caches layers, npm install only reruns on dep changes",severity:"major"},{topic:"docker:non-root",lesson:"Run as non-root user (USER 1001) \u2014 some k8s clusters reject root containers by policy",severity:"critical"},{topic:"docker:build-arg-secret",lesson:"Never use ARG for secrets \u2014 visible in image history. Use --secret mount instead",severity:"critical"},{topic:"docker:entrypoint-exec",lesson:'Use exec form ["cmd","arg"] not shell form "cmd arg" \u2014 shell form ignores SIGTERM',severity:"major"},{topic:"docker:multi-stage",lesson:"Multi-stage builds: copy only built artifacts to final stage \u2014 keep image small",severity:"minor"}],kubernetes:[{topic:"k8s:resource-limits",lesson:"Always set resource limits \u2014 unbounded pods cause node evictions and OOMKill",severity:"critical"},{topic:"k8s:liveness-vs-readiness",lesson:"Liveness failures restart pod; Readiness failures remove from LB. Use different endpoints",severity:"major"},{topic:"k8s:imagepullpolicy",lesson:"imagePullPolicy: Always in production \u2014 IfNotPresent can serve stale images",severity:"major"},{topic:"k8s:configmap-env",lesson:"ConfigMap changes don't restart pods \u2014 use rollout restart or mount as volume",severity:"critical"},{topic:"k8s:pdb",lesson:"Set PodDisruptionBudget for stateful apps \u2014 node drains kill all pods without it",severity:"major"}],react:[{topic:"react:useeffect-deps",lesson:"Omitting dependencies from useEffect deps array causes stale closure bugs \u2014 use exhaustive-deps ESLint rule",severity:"critical"},{topic:"react:key-index",lesson:"Never use array index as key in lists \u2014 causes subtle re-render bugs on reorder/delete",severity:"major"},{topic:"react:setState-in-render",lesson:"setState() during render causes infinite loop \u2014 move to useEffect or event handler",severity:"critical"},{topic:"react:memo-reference",lesson:"Object/array literals in JSX recreate on every render \u2014 useMemo for expensive derived values",severity:"minor"}],typescript:[{topic:"ts:type-guard",lesson:'Use "x is Type" return type for type guard functions \u2014 not "boolean"',severity:"minor"},{topic:"ts:strict-null",lesson:"Enable strictNullChecks in tsconfig \u2014 catches 90% of runtime null errors at compile time",severity:"critical"},{topic:"ts:enum-avoid",lesson:'Prefer union types ("a"|"b") over enum \u2014 enums have surprising runtime behavior',severity:"minor"},{topic:"ts:satisfies",lesson:'Use "satisfies" operator to validate type without widening \u2014 more precise than explicit annotation',severity:"minor"}],python:[{topic:"python:mutable-default",lesson:"Never use mutable default arguments (def f(x=[])) \u2014 shared across all calls. Use None + guard",severity:"critical"},{topic:"python:walrus-operator",lesson:":= (walrus) assigns and returns \u2014 useful in while/comprehensions but hard to read in complex expr",severity:"minor"},{topic:"python:asyncio-run",lesson:"asyncio.run() creates new event loop \u2014 calling it inside an existing loop raises RuntimeError",severity:"major"},{topic:"python:typing-optional",lesson:"Optional[X] == Union[X, None] \u2014 in Python 3.10+ use X | None syntax",severity:"minor"}]},e=t.toLowerCase(),o=i[e];if(!o){const d=Object.keys(i).join(", ");return`\u274C No public brain available for \`${t}\`.
39
+ Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;for(const l of e){const a=`cachly:global:lesson:${l.topic}`,s=await n.get(a);if(s){const d=z(s,null);if(!d)continue;d.recall_count=(d.recall_count??0)+1,d.last_recalled_at=new Date().toISOString(),await n.set(a,JSON.stringify(d))}}const o=[`\u{1F310} **Global Brain** \u2014 ${e.length} lesson${e.length>1?"s":""}`,""];for(const l of e){const a=l.severity==="critical"?"\u{1F534} ":l.severity==="major"?"\u{1F7E1} ":"";o.push(`${a}**\`${l.topic}\`**`),o.push(l.lesson.slice(0,200)),o.push("")}return o.join(`
40
+ `)}case"publish_lesson":{const{instance_id:r,topic:t,lesson:n,framework:i="general",severity:c="minor"}=m,e=Xe({topic:t,lesson:n,framework:i},"the public library");if(!e.ok)return e.meldung;const{topic:o,lesson:l,framework:a}=e.felder,s=await y(r),d=l.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,"[email]").replace(/\b(sk-|cky_live_|Bearer\s)[A-Za-z0-9_-]{8,}/g,"[token]").replace(/\/Users\/[^\s/]+/g,"/Users/[user]").replace(/\/home\/[^\s/]+/g,"/home/[user]"),u={topic:o,lesson:d,framework:a,severity:c,ts:new Date().toISOString(),published:!0,votes:0},_=`cachly:public:lesson:${a}:${o}`;return await s.set(_,JSON.stringify(u),"EX",365*86400),["\u{1F4E2} **Lesson published!**","",`**Topic:** \`${o}\``,`**Framework:** ${a}`,`**Content:** ${d.slice(0,200)}${d.length>200?"\u2026":""}`,"","This lesson is now available in the Public Brain for other developers.",`Import it anywhere: \`import_public_brain(framework="${a}")\``,...e.geschwaerzt.length?["",tt(e.geschwaerzt)]:[]].join(`
41
+ `)}case"import_public_brain":{const{instance_id:r,framework:t,limit:n=20}=m,i=await y(r),c={nextjs:[{topic:"nextjs:image-layout",lesson:'Use fill + relative parent instead of layout="fill" (deprecated since Next.js 13)',severity:"major"},{topic:"nextjs:app-router-fetch",lesson:'fetch() in Server Components is cached by default \u2014 add {cache:"no-store"} for dynamic data',severity:"major"},{topic:"nextjs:metadata-export",lesson:"Export metadata const or generateMetadata() \u2014 never both in same file",severity:"minor"},{topic:"nextjs:client-boundary",lesson:'"use client" propagates down \u2014 keep it at the lowest component, not at page level',severity:"major"},{topic:"nextjs:env-prefix",lesson:"Only NEXT_PUBLIC_* env vars are exposed to client \u2014 others are server-only",severity:"critical"},{topic:"nextjs:revalidate",lesson:"export const revalidate = 0 disables caching for entire route; use revalidatePath() for on-demand",severity:"minor"}],fastapi:[{topic:"fastapi:async-db",lesson:"Use async session with asyncpg \u2014 sync SQLAlchemy blocks the event loop",severity:"critical"},{topic:"fastapi:pydantic-v2",lesson:"Pydantic v2: use model_validate() instead of parse_obj(), .dict() \u2192 .model_dump()",severity:"major"},{topic:"fastapi:lifespan",lesson:"Use lifespan context manager instead of deprecated on_event startup/shutdown",severity:"minor"},{topic:"fastapi:background-tasks",lesson:"BackgroundTasks run after response is sent \u2014 not in a separate thread pool",severity:"major"},{topic:"fastapi:cors-order",lesson:"CORSMiddleware must be added before other middleware to work correctly",severity:"critical"}],go:[{topic:"go:context-cancel",lesson:"Always call cancel() from context.WithCancel \u2014 leak goroutines if not cancelled",severity:"critical"},{topic:"go:defer-in-loop",lesson:"defer in a loop runs at function return, not loop iteration \u2014 use IIFE or explicit close",severity:"major"},{topic:"go:nil-interface",lesson:"nil interface != interface containing nil pointer \u2014 use explicit nil checks",severity:"major"},{topic:"go:goroutine-leak",lesson:"Goroutines with channel sends block forever if receiver is gone \u2014 use select with done chan",severity:"critical"},{topic:"go:embed-path",lesson:"//go:embed path must be relative and known at compile time \u2014 no os.Getenv",severity:"minor"}],docker:[{topic:"docker:layer-cache",lesson:"Copy package.json before source code \u2014 Docker caches layers, npm install only reruns on dep changes",severity:"major"},{topic:"docker:non-root",lesson:"Run as non-root user (USER 1001) \u2014 some k8s clusters reject root containers by policy",severity:"critical"},{topic:"docker:build-arg-secret",lesson:"Never use ARG for secrets \u2014 visible in image history. Use --secret mount instead",severity:"critical"},{topic:"docker:entrypoint-exec",lesson:'Use exec form ["cmd","arg"] not shell form "cmd arg" \u2014 shell form ignores SIGTERM',severity:"major"},{topic:"docker:multi-stage",lesson:"Multi-stage builds: copy only built artifacts to final stage \u2014 keep image small",severity:"minor"}],kubernetes:[{topic:"k8s:resource-limits",lesson:"Always set resource limits \u2014 unbounded pods cause node evictions and OOMKill",severity:"critical"},{topic:"k8s:liveness-vs-readiness",lesson:"Liveness failures restart pod; Readiness failures remove from LB. Use different endpoints",severity:"major"},{topic:"k8s:imagepullpolicy",lesson:"imagePullPolicy: Always in production \u2014 IfNotPresent can serve stale images",severity:"major"},{topic:"k8s:configmap-env",lesson:"ConfigMap changes don't restart pods \u2014 use rollout restart or mount as volume",severity:"critical"},{topic:"k8s:pdb",lesson:"Set PodDisruptionBudget for stateful apps \u2014 node drains kill all pods without it",severity:"major"}],react:[{topic:"react:useeffect-deps",lesson:"Omitting dependencies from useEffect deps array causes stale closure bugs \u2014 use exhaustive-deps ESLint rule",severity:"critical"},{topic:"react:key-index",lesson:"Never use array index as key in lists \u2014 causes subtle re-render bugs on reorder/delete",severity:"major"},{topic:"react:setState-in-render",lesson:"setState() during render causes infinite loop \u2014 move to useEffect or event handler",severity:"critical"},{topic:"react:memo-reference",lesson:"Object/array literals in JSX recreate on every render \u2014 useMemo for expensive derived values",severity:"minor"}],typescript:[{topic:"ts:type-guard",lesson:'Use "x is Type" return type for type guard functions \u2014 not "boolean"',severity:"minor"},{topic:"ts:strict-null",lesson:"Enable strictNullChecks in tsconfig \u2014 catches 90% of runtime null errors at compile time",severity:"critical"},{topic:"ts:enum-avoid",lesson:'Prefer union types ("a"|"b") over enum \u2014 enums have surprising runtime behavior',severity:"minor"},{topic:"ts:satisfies",lesson:'Use "satisfies" operator to validate type without widening \u2014 more precise than explicit annotation',severity:"minor"}],python:[{topic:"python:mutable-default",lesson:"Never use mutable default arguments (def f(x=[])) \u2014 shared across all calls. Use None + guard",severity:"critical"},{topic:"python:walrus-operator",lesson:":= (walrus) assigns and returns \u2014 useful in while/comprehensions but hard to read in complex expr",severity:"minor"},{topic:"python:asyncio-run",lesson:"asyncio.run() creates new event loop \u2014 calling it inside an existing loop raises RuntimeError",severity:"major"},{topic:"python:typing-optional",lesson:"Optional[X] == Union[X, None] \u2014 in Python 3.10+ use X | None syntax",severity:"minor"}]},e=t.toLowerCase(),o=c[e];if(!o){const d=Object.keys(c).join(", ");return`\u274C No public brain available for \`${t}\`.
42
42
 
43
43
  Available: ${d}
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(`
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:
45
+ Or publish your own: \`publish_lesson(framework="${t}", ...)\``}const l=o.slice(0,n);let a=0;for(const d of l){const u=`cachly:lesson:best:${d.topic}`;await i.get(u)||(await i.set(u,JSON.stringify({...d,what_worked:d.lesson,outcome:"success",ts:new Date().toISOString(),recall_count:0,source:"public_brain",version:2})),a++)}return[`\u{1F4E5} **Public Brain imported: ${t}**`,"",`${a} new lessons added (${l.length-a} 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(`
46
+ `)}case"setup_ai_memory":{const{instance_id:r,project_dir:t,embed_provider:n="openai",project_description:i="a software project"}=m,c=await L(`/api/v1/instances/${r}`),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=!!c.vector_token,a=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=c.tier.toUpperCase(),d=Ge(r),u=["\u{1F9E0} **cachly AI Memory Setup Complete**","",`**Project:** ${i}`,`**Instance:** ${c.name} (${s}) \xB7 ID: \`${r}\``,`**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",a,"```","",`**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:Je}),(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 He(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:r,handle:t,role:n,assigned_by:i=""}=m;if(!r||!t||!n)return"\u274C Required: instance_id, handle, role";const c=["admin","reviewer","contributor","viewer"].includes(n)?n:null;if(!c)return`\u274C Unknown role \`${n}\`. Valid: admin \xB7 reviewer \xB7 contributor \xB7 viewer`;const e=await U(r);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 \`${c}\` (the roles admin and owner come from the account and are not assigned).`,"",`Your role: ${F[e.role]} ${me(e)}. Run \`team_whoami\` to see what it allows.`].join(`
48
+ `);const o=await y(r),l=await o.hgetall(H(r)).catch(()=>({})),a=Object.values(l).includes("admin");if(a){const _=i?await Z(o,r,i):null;if(!Q(_,"admin"))return["\u274C **Permission denied** \u2014 only an `admin` can assign roles.","","Ask an existing admin to run:",`\`team_assign_role(instance_id="${r}", handle="${t}", role="${n}", assigned_by="<their-handle>")\``].join(`
49
+ `)}const s=l[t.toLowerCase()]??null;await o.hset(H(r),t.toLowerCase(),c),await o.expire(H(r),365*2*86400),await Ae(o,r,{action:"team_assign_role",actor:i||"(bootstrap)",handle:t.toLowerCase(),from:s,to:c});const d=!a;return[`${F[c]} **Role assigned** \u2014 **${t}** is now a \`${c}\``,"",`**Capabilities:** ${se[c]}`,"",d?"_First admin bootstrapped \u2014 governance is now active on this brain._":`_Assigned by ${i||"(bootstrap)"}_`,"","Run `team_roster` to see all current roles."].join(`
50
+ `)}case"team_whoami":{const{instance_id:r,handle:t}=m;if(!r||!t)return"\u274C Required: instance_id, handle";const n=await U(r);if(n){const o=n.can,l=s=>s?"yes":"no",a=[`## ${F[n.role]} ${t} \u2014 \`${n.role}\``,"",`**Where the role comes from:** ${pe[n.source]??(n.source||"unknown")} (cachly API, not the brain store)`,`**You can:** ${se[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&&a.push("**Review required:** lessons from contributors become proposals until an admin approves them."),a.push("",`Roles are set by the brain owner or an organisation admin: ${W}`),a.join(`
51
+ `)}const i=await y(r),c=await Z(i,r,t);if(!c){const o=await i.hgetall(H(r)).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:
52
52
  \`team_assign_role(handle="${t}", role="admin")\``].join(`
53
- `)}return[`## ${F[i]} ${t} \u2014 \`${i}\``,"",`**You can:** ${te[i]}`,"","Run `team_roster` to see all team members and their roles."].join(`
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
53
+ `)}return[`## ${F[c]} ${t} \u2014 \`${c}\``,"",`**You can:** ${se[c]}`,"","Run `team_roster` to see all team members and their roles."].join(`
54
+ `)}case"team_roster":{const{instance_id:r}=m;if(!r)return"\u274C Required: instance_id";if(await U(r)){let e=null;try{const a=await L(`/api/v1/instances/${encodeURIComponent(r)}/members`);e=Array.isArray(a?.members)?a.members:null}catch{e=null}if(!e)return`## \u{1F465} Team Roster
55
55
 
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(`
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(`
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(`
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(`
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(`
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(`
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};
56
+ The member list could not be loaded right now. Roles are managed in the dashboard: ${W}`;const o=[...e].sort((a,s)=>(Y[s.role]??0)-(Y[a.role]??0)||String(a.display_name??"").localeCompare(String(s.display_name??"")));return[`## \u{1F465} Team Roster (${o.length} member${o.length!==1?"s":""})`,"","| Role | Member | Source |","|---|---|---|",...o.map(a=>{const s=a.role??"";return`| ${F[s]??"?"} ${a.role??"?"} | **${a.display_name||"(no name)"}** | ${pe[a.source??""]??(a.source||"")} |`}),"",`_Roles come from the cachly API. The owner or an organisation admin changes them at ${W}._`].join(`
57
+ `)}const n=await(await y(r)).hgetall(H(r)).catch(()=>({}));if(Object.keys(n).length===0)return["## \u{1F465} Team Roster","","No roles assigned yet. Establish governance with:",`\`team_assign_role(instance_id="${r}", handle="<your-handle>", role="admin")\``].join(`
58
+ `);const i=Object.entries(n).map(([e,o])=>({handle:e,role:o})).sort((e,o)=>(Y[o.role]??0)-(Y[e.role]??0)||e.handle.localeCompare(o.handle)),c=[`## \u{1F465} Team Roster (${i.length} member${i.length!==1?"s":""})`,"","| Role | Handle | Capabilities |","|---|---|---|"];for(const e of i){const o=F[e.role]??"?";c.push(`| ${o} ${e.role} | **${e.handle}** | ${se[e.role].split(" \xB7 ").slice(0,2).join(", ")} |`)}return c.push("","_Manage with `team_assign_role`. Any admin can add or change roles._"),c.join(`
59
+ `)}case"team_audit":{const{instance_id:r,requester:t="",limit:n=50}=m;if(!r)return"\u274C Required: instance_id";const i=await y(r),c=await fe(i,r,t,"admin","view the governance audit log");if(c)return c;const e=Math.min(Math.max(1,Number(n)||50),200),o=await i.lrange(`cachly:team:audit:${r}`,-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(`
60
+ `);const l=o.map(s=>z(s,null)).filter(s=>s!==null).reverse(),a=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(a),"",`_Immutable trail \xB7 2-year retention \xB7 last ${e} events. Admin-only._`].join(`
61
+ `)}case"team_grant_scope":{const{instance_id:r,handle:t,group:n,action:i="add",assigned_by:c=""}=m;if(!r||!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(r),l=await U(r);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: ${me(l)}).`;const a=l?{}:await o.hgetall(H(r)).catch(()=>({}));if(Object.values(a).includes("admin")){const d=c?await Z(o,r,c):null;if(!Q(d,"admin"))return"\u274C **Permission denied** \u2014 only an `admin` can manage group scopes. Ask an admin to set `assigned_by`."}return i==="remove"?(await o.srem(ee(r,e),t.toLowerCase()),`\u{1F513} **${t}** removed from group \`${e}\`.`):(await o.sadd(ne(r),e),await o.sadd(ee(r,e),t.toLowerCase()),await o.expire(ne(r),365*2*86400),await o.expire(ee(r,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(`
62
+ `))}case"team_scopes":{const{instance_id:r,handle:t}=m;if(!r)return"\u274C Required: instance_id";const n=await y(r);if(t){const e=await Re(n,r,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 i=await n.smembers(ne(r)).catch(()=>[]);if(i.length===0)return["## \u{1F510} Team Scopes","","No groups defined yet. Create one by adding a member:",`\`team_grant_scope(instance_id="${r}", handle="alice", group="backend")\``].join(`
63
+ `);const c=[`## \u{1F510} Team Scopes (${i.length} group${i.length!==1?"s":""})`,""];for(const e of i.sort()){const o=await n.smembers(ee(r,e)).catch(()=>[]);c.push(`- **\`${e}\`** (${o.length}): ${o.length?o.map(l=>`**${l}**`).join(", "):"_empty_"}`)}return c.push("",'_Scope a lesson to a group with `learn_from_attempts(group="...")`. Members + admins see it; others don\'t._'),c.join(`
64
+ `)}default:return null}}export{ne as GROUPS_INDEX_KEY,ee as GROUP_KEY,oe as NIEMAND,ct as PROPOSED_LESSON_PREFIX,it as REVIEW_MODE_KEY,H as ROLES_KEY,F as ROLE_BADGE,Nt as TEAM_TOOL_NAMES,Ae as auditLog,ot as eigeneRolle,Ot as fragenderAusweis,Z as getRole,Re as getScopes,Ct as handleTeamTool,Q as hasPermission,Le as lessonVisibleToScope,Et as namensPruefer,rt as rbacActive,fe as requireRole,ut as reviewModeEnabled,at as roleToReviewLevel,dt as sichtbarFuer,ht as storeLessonProposal,J as teamweitLesbar,je as teamweiteNamen};
@@ -0,0 +1 @@
1
+ import{zugangVon as a}from"./rolle.js";const i=["cachly:ctx:","cachly:session:","cachly:wirkung:","cachly:letzter-recall:","cachly:liefer:","cachly:agents:","cachly:stats:suchprotokoll:","cachly:stats:reuse_pairs:"];function n(r){return i.some(t=>r.startsWith(t))}function h(r){return`${r}k:`}function o(r){return a(r)?.raeume?.konto}function u(r,t){const c=o(r);return!c||!n(t)?t:c+t.slice(7)}function s(r,t){const c=o(r);if(!c||!t.startsWith(c))return t;const e=`cachly:${t.slice(c.length)}`;return n(e)?e:t}export{i as KONTO_FAMILIEN,s as alterSchluessel,n as istKontoSchluessel,h as kontoBereich,o as kontoBereichVon,u as kontoSchluessel};
@@ -1 +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
+ import{createHash as k}from"node:crypto";import{zugangVon as A}from"./rolle.js";const v="cachly:zone:raeume";function m(t){return k("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:${m(`gruppe:${t.toLowerCase().trim()}`).slice(0,16)}:`}function g(t,e){return`${t}lesson:best:${m(e).slice(0,32)}`}function $(t){return`${t}themen`}function M(t){return["%R~cachly:[^zcslmwa]*","%R~cachly:c[^t]*","%R~cachly:l[^ei]*","%R~cachly:le[^t]*","%R~cachly:m[^e]*","%R~cachly:w[^i]*","%R~cachly:wi[^r]*",...t.privat?[`%R~${t.privat}*`]:[],...t.gruppen.map(e=>`%R~${e}*`),...t.privat?[`~${t.privat}k:*`]:[],"~[^c]*","~c[^a]*","~ca[^c]*","~cac[^h]*","~cach[^l]*","~cachl[^y]*","~cachly[^:]*","~cachly:[^tlciwgfbmpdzsa]*","~cachly:a[^g]*","~cachly:se[^s]*","~cachly:st[^a]*","~cachly:sta[^t]*","~cachly:stats:[^sr]*","~cachly:stats:re[^u]*","~cachly:cls:*","~cachly:lock:*","~cachly:mcp:*","~cachly:mcm:*","~cachly:prefs:*","~cachly:dep:*","+@all","-@admin","-@dangerous","+keys","+info","-client"]}function p(t){return typeof t=="string"&&t?t:void 0}function V(t){if(!t||typeof t!="object")return;const e=t,a=p(e.private),o=[];if(Array.isArray(e.groups))for(const l of e.groups){const s=p(l?.prefix);if(!s)continue;const i=p(l.name);o.push({...i?{name:i}:{},praefix:s})}const r=e.all===!0,n=p(e.account),c=a&&n===`${a}k:`?n:void 0;if(!(!a&&o.length===0&&!r))return{...a?{privat:a}:{},gruppen:o,...r?{alle:!0}:{},...c?{konto:c}:{}}}function b(t){return A(t)?.raeume}function z(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=b(t);if(!e)return[];const a=[],o=new Set,r=n=>{o.has(n.praefix)||(o.add(n.praefix),a.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(v)}catch{n={}}for(const[c,l]of Object.entries(n)){const s=p(x(l)?.name);r({...s?{name:s}:{},praefix:c})}}return a}function d(t,e,a){const o=x(t);if(!o)return null;const r=z(e.praefix),n=typeof o.topic=="string"&&o.topic?o.topic:a;if(!n)return null;const c=r==="g"?e.name??p(o.group):void 0;return{thema:n,praefix:e.praefix,art:r,...c?{gruppe:c}:{},lektion:o,roh:t}}async function C(t,e){const a=await w(t);if(a.length===0)return null;const o=await t.mget(...a.map(r=>g(r.praefix,e)));for(let r=0;r<a.length;r++){const n=o[r];if(typeof n!="string")continue;const c=d(n,a[r],e);if(c)return c}return null}async function N(t,e=200){const a=await w(t);if(a.length===0)return[];const o=t.pipeline();for(const i of a)o.smembers($(i.praefix));const r=await o.exec()??[],n=[];a.forEach((i,f)=>{const[u,h]=r[f]??[null,[]];if(!(u||!Array.isArray(h)))for(const y of h.slice().sort())typeof y=="string"&&n.push({ref:i,thema:y})});const c=n.slice(0,Math.max(0,e));if(c.length===0)return[];const l=await t.mget(...c.map(i=>g(i.ref.praefix,i.thema))),s=[];return c.forEach((i,f)=>{const u=l[f];if(typeof u!="string")return;const h=d(u,i.ref,i.thema);h&&s.push(h)}),s}function R(t){return t.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3)}function _(t,e,a=3){const o=new Set(R(e));if(o.size===0)return[];const r=[];for(const n of t){const c=n.lektion,l=Array.isArray(c.tags)?c.tags.filter(u=>typeof u=="string").join(" "):"",s=[n.thema,c.what_worked,c.what_failed,c.context,l].filter(u=>typeof u=="string").join(" "),i=new Set(R(s));let f=0;for(const u of o)i.has(u)&&f++;f>0&&r.push({l:n,n:f})}return r.sort((n,c)=>c.n-n.n),r.slice(0,Math.max(0,a)).map(n=>n.l)}export{v as RAUM_VERZEICHNIS,N as ladeRaumLektionen,g as lektionsSchluessel,C as leseRaumLektion,M as mitgliedMuster,V as raeumeAusAuskunft,b as raeumeVon,E as raumGruppe,j as raumPrivat,_ as raumTreffer,$ as themenSchluessel};
package/dist/src/rolle.js CHANGED
@@ -1,7 +1,7 @@
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 g=null,$=()=>"";const p=new Map,h=new Map;function z(t){g=t.abruf,$=t.bereich??(()=>""),p.clear(),h.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(!g||!t)return null;const e=x(t),n=p.get(e);if(n&&Date.now()-n.am<M)return n.auskunft;const r=h.get(e);return n?(r||S(e,t,n),n.auskunft):r||S(e,t,void 0)}function S(t,e,n){if(!g)return Promise.resolve(n?.auskunft??null);const r=g,o=(async()=>{try{const i=L(await r(`/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(()=>h.delete(t));return h.set(t,o),o}function P(t){return p.get(x(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}:{},...typeof r.grund=="string"?{apiGrund:r.grund}:{}})}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,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 c=n(e.apiReason,e.reason);if(c!==void 0&&(r.reason=c),typeof e.apiGrund=="string"&&(r.grund=e.apiGrund),r.status===void 0){const u=/\((\d{3})\)|error (\d{3})/.exec(String(e.message??""));u&&(r.status=Number(u[1]??u[2]))}return r}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(`
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 g=null,x=()=>"";const p=new Map,h=new Map;function z(t){g=t.abruf,x=t.bereich??(()=>""),p.clear(),h.clear()}function J(){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 S(t){return`${x()}|${t}`}async function q(t){if(!g||!t)return null;const e=S(t),n=p.get(e);if(n&&Date.now()-n.am<M)return n.auskunft;const r=h.get(e);return n?(r||v(e,t,n),n.auskunft):r||v(e,t,void 0)}function v(t,e,n){if(!g)return Promise.resolve(n?.auskunft??null);const r=g,o=(async()=>{try{const i=L(await r(`/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(()=>h.delete(t));return h.set(t,o),o}function P(t){return p.get(S(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}:{},...typeof r.grund=="string"?{apiGrund:r.grund}:{}})}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,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 c=n(e.apiReason,e.reason);if(c!==void 0&&(r.reason=c),typeof e.apiGrund=="string"&&(r.grund=e.apiGrund),r.status===void 0){const u=/\((\d{3})\)|error (\d{3})/.exec(String(e.message??""));u&&(r.status=Number(u[1]??u[2]))}return r}const w=new WeakMap;function y(t){return t&&typeof t=="object"?w.get(t):void 0}function C(t){return y(t)?.access==="member"}function I(t){const e=y(t);return(e?.instanceId?P(e.instanceId)?.role:void 0)??e?.role??"contributor"}function Q(t,e){if(!C(t))return!0;const n=y(t)?.raeume?.konto;return n&&e.startsWith(n)?!0: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
2
  `)}const A="Das darf nur der Besitzer oder ein Admin.";function R(t){return`${A} Deine Rolle: ${t}.`}class G 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 U(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 r=e===1?"1 Schreibbefehl":`${e} Schreibbefehle`;return`${t}
3
3
 
4
- \u{1F512} ${R(n)} Nicht gespeichert: ${r} dieses Aufrufs.`}function y(t){return!!t&&typeof t.then=="function"}function F(t){return e=>{if(!_(e))return e;const n=t();return U(n),new G(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,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 c=(...u)=>{const a=s.apply(o,u);return a===o?r: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 r}function ne(t,e){const n={...e,access:"member"},r=F(()=>I(i)),o=new Map,i=new Proxy(t,{get(s,c){const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(o.has(c))return o.get(c);const a=(...l)=>{const f=u.apply(s,l);return f===s?i:y(f)?f.then(void 0,j=>{throw r(j)}):(c==="pipeline"||c==="multi")&&f&&typeof f=="object"?Z(f,r):f};return o.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(`
4
+ \u{1F512} ${R(n)} Nicht gespeichert: ${r} dieses Aufrufs.`}function $(t){return!!t&&typeof t.then=="function"}function F(t){return e=>{if(!_(e))return e;const n=t();return U(n),new G(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,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 c=(...u)=>{const a=s.apply(o,u);return a===o?r:i==="exec"&&$(a)?a.then(l=>V(l,e),l=>{throw e(l)}):$(a)?a.then(void 0,l=>{throw e(l)}):a};return n.set(i,c),c}});return r}function ne(t,e){const n={...e,access:"member"},r=F(()=>I(i)),o=new Map,i=new Proxy(t,{get(s,c){const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(o.has(c))return o.get(c);const a=(...l)=>{const f=u.apply(s,l);return f===s?i:$(f)?f.then(void 0,j=>{throw r(j)}):(c==="pipeline"||c==="multi")&&f&&typeof f=="object"?Z(f,r):f};return o.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
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(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
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,r)}) darf in diesem Brain keine Lektionen speichern. Nichts wurde gespeichert.`,`Rollen setzt der Besitzer oder ein Admin unter ${m}.`].join(`
7
7
  `):`\u26A0\uFE0F Nicht gespeichert: Die API hat \`${n.topic}\` nicht angenommen (${E(c)}). Bitte noch einmal versuchen.`}const i=o?.topic||n.topic;if(o?.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(`
@@ -10,4 +10,4 @@ import{AsyncLocalStorage as T}from"node:async_hooks";import{mitgliedDarfSchreibe
10
10
  \u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.`}catch(o){const i=b(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 ${m}.`].join(`
11
11
  `):i.status===404?`\u{1F4ED} No best-solution lesson found for \`${n.topic}\`.
12
12
 
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(o)}).`}}const B=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+=B){const i=r.slice(o,o+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,G 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};
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(o)}).`}}const B=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+=B){const i=r.slice(o,o+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,G 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,J as setzeRollenZustandZurueck,Y as zugangNichtVerfuegbarText,y as zugangVon};
@@ -1 +1 @@
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
+ 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:"K",session:"K",wirkung:"K","letzter-recall":"K",liefer:"K",agents:"K",cls:"B",lock:"B",mcp:"B",mcm:"B",prefs:"B",dep:"B",stats:"B",sem:"B",roadmap:"B",recall:"B",streak:"B",stream:"B",vek:"B",startwissen:"B",versuch:"B",quota:"B",aussetzer:"B"}),o=Object.freeze(a({gruppen:[]}));function f(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 p=o.filter(e=>e.startsWith("~")).map(e=>f(e.slice(1)));function m(e){return p.some(t=>t.test(e))}function W(e){const t=/^cachly:([A-Za-z0-9_-]+)/.exec(e);return t?t[1]:""}function u(e){return e.startsWith("cachly:")?l[W(e)]:"B"}export{o as MITGLIED_MUSTER,l as SCHLUESSEL_KLASSEN,W as familieVon,f as globAlsRegex,u as klasseVon,m as mitgliedDarfSchreiben};
@@ -0,0 +1 @@
1
+ import{randomUUID as r}from"node:crypto";let n=r();function u(){return n}function s(t){n=t}function i(t=n){return`cachly:session:start:${t}`}function c(t,e=n){return typeof t!="string"||t===""||t===e}export{c as gehoertDieserSitzung,s as setzeSitzungsKennung,u as sitzungsKennung,i as startmarkenSchluessel};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.285",
3
+ "version": "0.10.287",
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.285",
3
+ "version": "0.10.287",
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.285",
20
+ "version": "0.10.287",
21
21
  "packages": [
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "@cachly-dev/mcp-server",
25
- "version": "0.10.285",
25
+ "version": "0.10.287",
26
26
  "runtimeHint": "npx",
27
27
  "transport": {
28
28
  "type": "stdio"