@cachly-dev/mcp-server 0.10.279 → 0.10.281
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/ambient-cli.js +4 -2
- package/dist/src/cli-argumente.js +1 -1
- package/dist/src/client-kopf.js +1 -0
- package/dist/src/handlers/brain.js +73 -68
- package/dist/src/handlers/share.js +11 -11
- package/dist/src/handlers/team.js +49 -43
- package/dist/src/import-docs.js +11 -0
- package/dist/src/index.js +127 -123
- package/dist/src/rolle.js +12 -0
- package/dist/src/schluessel-klassen.js +1 -0
- package/dist/src/speicher-zugang.js +1 -0
- package/dist/src/suchstatistik.js +1 -1
- package/dist/src/wissenssuche.js +7 -0
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +40 -36
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{safeJsonParse as D}from"../utils.js";import{STARTER_CORPUS as x,STARTER_CORPUS_SIZE as q}from"../starter-corpus.js";import{cachlyUrl as R}from"../cachly-url.js";import{VEKTOR_NACHTRAG as J}from"../bedeutung.js";import{schwaerze as P}from"../geheimnis-filter.js";import{fuerEigenenSpeicher as E,fuerWeitergabe as I,hinweise as U,istMarkiert as z,markiert as L,weitergabeHinweis as C,zaehlHinweise as
|
|
2
|
-
`);if(r){const o=h.slice(0,5).map(
|
|
3
|
-
`)}let j=null,v=null;try{j=(await $("/api/v1/brains/share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_,description:f,visibility:t,lessons:h})})).share_id??null,j&&(v=R(`/brain/share/${j}`,"brain-share"))}catch(o){const
|
|
1
|
+
import{safeJsonParse as D}from"../utils.js";import{STARTER_CORPUS as x,STARTER_CORPUS_SIZE as q}from"../starter-corpus.js";import{cachlyUrl as R}from"../cachly-url.js";import{VEKTOR_NACHTRAG as J}from"../bedeutung.js";import{schwaerze as P}from"../geheimnis-filter.js";import{fuerEigenenSpeicher as E,fuerWeitergabe as I,hinweise as U,istMarkiert as z,markiert as L,weitergabeHinweis as C,zaehlHinweise as M}from"../schreibtor.js";import{teamweitLesbar as K}from"./team.js";import{istMitglied as Y}from"../rolle.js";const te=new Set(["brain_share","brain_import","brain_share_list","brain_unshare","brain_discover","brain_seed_starter"]);async function H(O,y){const g=[],$=O.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((a,d)=>{$.on("data",e=>g.push(...e)),$.on("end",a),$.on("error",d)});const i=[];for(const a of g.slice(0,500)){const d=await O.get(a);if(!d)continue;const e=K(d);!e||!e.topic||y&&y.length>0&&!y.some(s=>e.topic.includes(s))||i.push({topic:e.topic,outcome:e.outcome,...e.what_worked?{what_worked:e.what_worked}:{},...e.what_failed?{what_failed:e.what_failed}:{},...e.ctx?{ctx:e.ctx}:{},...e.tags?.length?{tags:e.tags}:{},...e.author?{author:e.author}:{},...e.service?{service:e.service}:{},confidence:e.confidence??1,ts:e.ts})}return i}async function re(O,y,g,$){switch(O){case"brain_share":{const{instance_id:i,title:a="My Brain Snapshot",description:d="",topic_filter:e,visibility:t="unlisted",max_lessons:s=100,dry_run:r=!1}=y;if(!i)return"\u26A0\uFE0F `brain_share` requires `instance_id`.";const c=I({title:a,description:d},"the share");if(!c.ok)return c.meldung;const l=[...c.geschwaerzt],_=c.felder.title,f=c.felder.description,n=await g(i),p=Array.isArray(e)&&e.length>0?e:void 0,w=await H(n,p),m=[],S=[];for(const o of w){if(S.length>=s)break;const u=P(o.topic).text;if(z(o)){m.push(`${u} (beim Speichern markiert)`);continue}const b=I(o,"the share");if(!b.ok){m.push(`${u} (${b.verdacht.join("; ")})`);continue}l.push(...b.geschwaerzt),S.push(b.felder)}const h=S,T=[C(l),m.length?`\u26D4 Tuersteher (security gate): ${m.length} lesson(s) NOT included in the share (instruction or dangerous command detected): ${m.slice(0,10).join(", ")}${m.length>10?", \u2026":""}. Check them and save them again one by one; the lessons in the Brain stay unchanged.`:""].filter(Boolean);if(h.length===0)return["\u{1F4E4} **brain_share** \u2014 nothing to share yet","",`No lessons found in Brain \`${i}\`${p?` matching topics: ${p.join(", ")}`:""}${m.length?" that can be shared":""}.`,"",'Store lessons first with `learn_from_attempts(topic="...", what_worked="...")`.',...T].join(`
|
|
2
|
+
`);if(r){const o=h.slice(0,5).map(u=>` ${u.outcome==="success"?"\u2705":u.outcome==="failure"?"\u274C":"\u26A0\uFE0F"} \`${u.topic}\` \u2014 ${(u.what_worked??u.what_failed??"").slice(0,80)}`);return[`\u{1F4E4} **brain_share (DRY RUN)** \u2014 would share ${h.length} lesson${h.length!==1?"s":""}`,"",`**Title:** ${_}`,`**Visibility:** ${t}`,p?`**Topic filter:** ${p.join(", ")}`:"","","**Sample lessons (first 5):**",...o,h.length>5?` _...and ${h.length-5} more_`:"","",...T,"_Remove `dry_run=true` to create the public share._"].filter(u=>u!=="").join(`
|
|
3
|
+
`)}let j=null,v=null;try{j=(await $("/api/v1/brains/share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_,description:f,visibility:t,lessons:h})})).share_id??null,j&&(v=R(`/brain/share/${j}`,"brain-share"))}catch(o){const u=o.message??"";if(u.includes("404")||u.includes("not found")||u.includes("ECONNREFUSED")){const b=JSON.stringify({title:_,description:f,visibility:t,lessons:h,exported_at:new Date().toISOString()},null,2);return[`\u{1F4E4} **brain_share** \u2014 exported ${h.length} lesson${h.length!==1?"s":""}`,"","\u26A0\uFE0F The public share API is not yet available. Here is your portable snapshot:","","```json",b.slice(0,3e3)+(b.length>3e3?`
|
|
4
4
|
... (truncated)`:""),"```","","_To import this on another Brain, use `brain_import` with the JSON payload._",...T].join(`
|
|
5
5
|
`)}return`\u274C brain_share failed: ${o.message}`}const k=h.slice(0,5).map(o=>` ${o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F"} \`${o.topic}\``);try{const o=JSON.stringify({share_id:j,title:_,visibility:t,lesson_count:h.length,created_at:new Date().toISOString()});await n.rpush("cachly:brain:shares",o),await n.ltrim("cachly:brain:shares",-20,-1)}catch{}return[`\u{1F4E4} **brain_share** \u2014 ${h.length} lesson${h.length!==1?"s":""} shared`,"",`**Share ID:** \`${j}\``,`**URL:** ${v}`,`**Title:** ${_}`,`**Visible:** ${t}`,"","**Sample lessons:**",...k,h.length>5?` _...and ${h.length-5} more_`:"","","**Anyone can import this Brain with:**",`\`brain_import(instance_id="<their-id>", share_id="${j}")\``,"","_To list all your shares, run `brain_share_list`._",...T.length?["",...T]:[]].filter(o=>o!=="").join(`
|
|
6
|
-
`)}case"brain_import":{const{instance_id:i,share_id:a,topic_prefix:
|
|
7
|
-
`):`\u274C brain_import failed: ${k.message}`}const l=c.lessons??[];if(l.length===0)return`\u26A0\uFE0F Share \`${r}\` exists but contains no lessons.`;const _=await g(i);let f=0,n=0,p=0;const w=[];let m=0,S=0;const h=E({title:c.title??""}),T=h.felder.title||r;for(const k of l){if((k.confidence??1)<e){n++;continue}const o=E(k);o.geschwaerzt.length&&m++,o.verdacht.length&&S++;const
|
|
8
|
-
`)}case"brain_share_list":{const{instance_id:i}=y;if(!i)return"\u26A0\uFE0F `brain_share_list` requires `instance_id`.";const a=await g(i);let
|
|
6
|
+
`)}case"brain_import":{const{instance_id:i,share_id:a,topic_prefix:d="",min_confidence:e=0,dry_run:t=!1,overwrite:s=!1}=y;if(!i)return"\u26A0\uFE0F `brain_import` requires `instance_id`.";if(!a)return"\u26A0\uFE0F `brain_import` requires `share_id`. Get one from `brain_share`.";const r=a.replace(/^.*\/brain\/share\//,"").trim();let c;try{c=await $(`/api/v1/brains/share/${r}`)}catch(k){const o=k.message??"";return o.includes("404")||o.includes("not found")?["\u274C **brain_import** \u2014 share not found","",`Share ID \`${r}\` does not exist or has been removed.`,"","Ask the Brain owner to re-run `brain_share` and share the new ID with you."].join(`
|
|
7
|
+
`):`\u274C brain_import failed: ${k.message}`}const l=c.lessons??[];if(l.length===0)return`\u26A0\uFE0F Share \`${r}\` exists but contains no lessons.`;const _=await g(i);let f=0,n=0,p=0;const w=[];let m=0,S=0;const h=E({title:c.title??""}),T=h.felder.title||r;for(const k of l){if((k.confidence??1)<e){n++;continue}const o=E(k);o.geschwaerzt.length&&m++,o.verdacht.length&&S++;const u=o.verdacht.length?{...o.felder,tags:L(o.felder.tags,o.verdacht)}:o.felder,b=d?`${d}:${u.topic}`:u.topic,B=`cachly:lesson:best:${b}`;if(!s&&await _.get(B)){p++;continue}const A=JSON.stringify({...u,topic:b,imported_from:r,imported_at:new Date().toISOString()});if(!t){await _.set(B,A);const N=`cachly:lessons:${b}`;await _.rpush(N,A),await _.ltrim(N,-100,-1),await _.expire(N,90*86400)}if(f++,w.length<6){const N=u.outcome==="success"?"\u2705":u.outcome==="failure"?"\u274C":"\u26A0\uFE0F";w.push(` ${N} \`${b}\` \u2014 ${(u.what_worked??u.what_failed??"").slice(0,80)}`)}}if(!t&&f>0)try{const k=JSON.stringify({share_id:r,title:h.felder.title||void 0,...h.verdacht.length?{verdacht:h.verdacht}:{},imported:f,skipped:n,conflicts:p,topic_prefix:d,imported_at:new Date().toISOString()});await _.rpush("cachly:brain:imports",k),await _.ltrim("cachly:brain:imports",-20,-1)}catch{}const v=[`\u{1F4E5} **brain_import${t?" (DRY RUN \u2014 no writes)":""}** \u2014 from "${T}"`,"",`**Share ID:** \`${r}\``,`**Lessons imported:** ${f}`,...n>0?[`**Skipped (low confidence):** ${n}`]:[],...p>0?[`**Skipped (already exist):** ${p} _(pass \`overwrite=true\` to replace)_`]:[],...M(m,S,`${l.length} entries`),...U(h,"notiz"),""];return w.length>0&&(v.push("**Sample lessons imported:**",...w),f>6&&v.push(` _...and ${f-6} more_`)),f>0&&!t?v.push("",'\u2705 Brain updated \u2014 use `smart_recall(query="...")` to query the new knowledge.'):t?v.push("","_Remove `dry_run=true` to actually import these lessons._"):f===0&&p>0&&v.push("","\u2139\uFE0F All lessons already exist in your Brain. Pass `overwrite=true` to update them."),v.join(`
|
|
8
|
+
`)}case"brain_share_list":{const{instance_id:i}=y;if(!i)return"\u26A0\uFE0F `brain_share_list` requires `instance_id`.";const a=await g(i);let d=[];try{d=(await a.lrange("cachly:brain:shares",0,-1)).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean)}catch{}let e=[];try{e=(await $("/api/v1/brains/share")).shares??[]}catch{}const t=e.length>0?e:d;if(t.length===0)return["\u{1F4E4} **brain_share_list** \u2014 no shares yet","","You haven't shared any Brain snapshots from this instance.","",`Create one with: \`brain_share(instance_id="${i}", title="My Patterns")\``].join(`
|
|
9
9
|
`);const s=[`\u{1F4E4} **Your Brain Shares** (${t.length})`,"","| # | Title | Lessons | Visibility | Created |","|---|-------|---------|------------|---------|"];for(const[c,l]of t.entries()){const _=new Date(l.created_at),f=isNaN(_.getTime())?l.created_at:_.toISOString().slice(0,10),n=l.visibility==="public"?"\u{1F310} public":"\u{1F517} unlisted";s.push(`| ${c+1} | ${l.title??"\u2014"} | ${l.lesson_count??"?"} | ${n} | ${f} |`)}const r=t[t.length-1];return s.push("",`**Import command:** \`brain_import(instance_id="<their-id>", share_id="${r?.share_id??"..."}")\``,`**Revoke:** \`brain_unshare(instance_id="${i}", share_id="<id>")\``),s.join(`
|
|
10
10
|
`)}case"brain_unshare":{const{instance_id:i,share_id:a}=y;if(!i)return"\u26A0\uFE0F `brain_unshare` requires `instance_id`.";if(!a)return"\u26A0\uFE0F `brain_unshare` requires `share_id`.";try{await $(`/api/v1/brains/share/${a}`,{method:"DELETE"})}catch(e){const t=e.message??"";if(t.includes("404")||t.includes("not found"))return`\u274C Share \`${a}\` not found \u2014 it may have already been removed.`;if(t.includes("ECONNREFUSED")||t.includes("fetch failed")){const s=await g(i);try{const c=(await s.lrange("cachly:brain:shares",0,-1)).filter(l=>{try{return JSON.parse(l).share_id!==a}catch{return!0}});await s.del("cachly:brain:shares");for(const l of c)await s.rpush("cachly:brain:shares",l)}catch{}return["\u26A0\uFE0F **brain_unshare** \u2014 removed from local log","",`API unreachable \u2014 removed \`${a}\` from your local share registry.`,"The public link may still be accessible until the API confirms deletion."].join(`
|
|
11
|
-
`)}return`\u274C brain_unshare failed: ${t}`}const
|
|
12
|
-
`)}case"brain_discover":{const{query:i="",topic:a="",limit:
|
|
11
|
+
`)}return`\u274C brain_unshare failed: ${t}`}const d=await g(i);if(!Y(d))try{const t=(await d.lrange("cachly:brain:shares",0,-1)).filter(s=>{try{return JSON.parse(s).share_id!==a}catch{return!0}});await d.del("cachly:brain:shares");for(const s of t)await d.rpush("cachly:brain:shares",s)}catch{}return["\u{1F5D1}\uFE0F **brain_unshare** \u2014 share revoked","",`Share \`${a}\` has been deleted. The public link is no longer accessible.`,"","_Anyone who already imported this Brain keeps their local copy._"].join(`
|
|
12
|
+
`)}case"brain_discover":{const{query:i="",topic:a="",limit:d=10}=y;let e=[];try{const s=new URLSearchParams;i&&s.set("q",i),a&&s.set("topic",a),s.set("limit",String(d)),e=await $(`/api/v1/brains/discover?${s.toString()}`)}catch(s){const r=s.message??"";return r.includes("404")||r.includes("ECONNREFUSED")||r.includes("fetch failed")?["\u{1F50D} **brain_discover** \u2014 marketplace not yet live","","The public Brain marketplace is coming soon.","","**In the meantime:**",' \u2022 Share your Brain: `brain_share(instance_id="...", visibility="public")`',' \u2022 Import by ID: `brain_import(instance_id="...", share_id="<id>")`',` \u2022 Community index: ${R("/brains","brain-discover")}`].join(`
|
|
13
13
|
`):`\u274C brain_discover failed: ${r}`}if(e.length===0)return[`\u{1F50D} **brain_discover** \u2014 no public Brains found ${i?`matching "${i}"`:a?`in topic "${a}"`:""}`.trim(),"",'Be the first! `brain_share(instance_id="...", visibility="public")`'].join(`
|
|
14
14
|
`);const t=[`\u{1F50D} **brain_discover**${i?` \u2014 "${i}"`:""}${a?` \xB7 topic: ${a}`:""} (${e.length} result${e.length!==1?"s":""})`,""];for(const[s,r]of e.entries()){const c=new Date(r.created_at),l=isNaN(c.getTime())?"":` \xB7 ${c.toISOString().slice(0,10)}`,_=r.imports!=null?` \xB7 ${r.imports} imports`:"",f=r.topics?.length?` \xB7 topics: ${r.topics.slice(0,4).join(", ")}`:"",n=r.author?` by **${r.author}**`:"";t.push(`**${s+1}. ${r.title}**${n}`,` \u{1F4DA} ${r.lesson_count} lessons${f}${_}${l}`,r.description?` _${r.description.slice(0,120)}_`:"",` \`brain_import(instance_id="...", share_id="${r.share_id}")\``,"")}return t.push(`_Browse more at ${R("/brains","brain-discover")}_`),t.filter(s=>s!==" ").join(`
|
|
15
|
-
`)}case"brain_seed_starter":{const{instance_id:i,topic_filter:a,dry_run:
|
|
15
|
+
`)}case"brain_seed_starter":{const{instance_id:i,topic_filter:a,dry_run:d=!1,force:e=!1}=y;if(!i)return"\u26A0\uFE0F `brain_seed_starter` requires `instance_id`.";const t=await g(i),s=await t.get(`cachly:brain:starter_seeded:${i}`);if(s&&!e&&!d)return["\u{1F331} **brain_seed_starter** \u2014 already seeded","",`This Brain was seeded with the starter corpus on ${s}.`,"","Pass `force=true` to re-seed (existing starter lessons will be refreshed)."].join(`
|
|
16
16
|
`);const r=Array.isArray(a)&&a.length>0?a:void 0,c=r?x.filter(n=>r.some(p=>n.topic.includes(p)||n.tags.some(w=>w.includes(p)))):x;if(c.length===0)return["\u{1F331} **brain_seed_starter** \u2014 no matching starter lessons","",`No starter lessons match filter: ${r?.join(", ")}.`,`Available topics: ${x.map(n=>`\`${n.topic}\``).join(", ")}`].join(`
|
|
17
|
-
`);if(
|
|
17
|
+
`);if(d){const n=c.slice(0,8).map(p=>` \u2705 \`${p.topic}\` \u2014 ${p.what_worked.slice(0,70)}\u2026`);return[`\u{1F331} **brain_seed_starter (DRY RUN)** \u2014 would seed ${c.length} lesson${c.length!==1?"s":""}`,"",...n,c.length>8?` _...and ${c.length-8} more_`:"","","_Remove `dry_run=true` to seed these into the Brain._"].filter(p=>p!=="").join(`
|
|
18
18
|
`)}const l=new Date().toISOString();let _=0,f=0;for(const n of c){const p=`cachly:lesson:best:${n.topic}`;if(!e){const S=await t.get(p);if(S){const h=D(S,null);if(h&&h.source!=="starter"){f++;continue}}}const w=JSON.stringify({topic:n.topic,outcome:n.outcome,what_worked:n.what_worked,what_failed:n.what_failed,ctx:n.ctx,tags:n.tags,confidence:n.confidence,recall_count:0,source:"starter",ts:l,verified_at:l,version:3});await t.set(p,w),await t.sadd(J,n.topic).catch(()=>{});const m=`cachly:lessons:${n.topic}`;await t.rpush(m,w),await t.ltrim(m,-100,-1),await t.expire(m,90*86400),_++}return await t.set(`cachly:stats:born_at:${i}`,l,"EX",365*86400,"NX").catch(()=>{}),await t.set(`cachly:brain:starter_seeded:${i}`,l,"EX",365*86400),["\u{1F331} **brain_seed_starter** \u2014 Brain seeded","",`**${_}** universal engineering lesson${_!==1?"s":""} added${f>0?` (${f} skipped \u2014 your own lessons take priority)`:""}.`,"","Your Brain now answers common questions out of the box:",' \u2022 `smart_recall(query="docker build slow")`',' \u2022 `smart_recall(query="pod OOMKilled")`',' \u2022 `smart_recall(query="jwt token rejected")`',"",'_Starter lessons are tagged `source: "starter"` and never override your own._',"_They're replaced as you learn project-specific lessons on the same topics._"].join(`
|
|
19
|
-
`)}default:return null}}export{
|
|
19
|
+
`)}default:return null}}export{te as SHARE_TOOL_NAMES,q as STARTER_CORPUS_SIZE,re as handleShareTool};
|
|
@@ -1,57 +1,63 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`)
|
|
3
|
-
`)}const
|
|
4
|
-
`)}
|
|
5
|
-
\u
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
\u{
|
|
11
|
-
|
|
1
|
+
import{readFileSync as Oe}from"node:fs";import{bauabdruck as Ee,formatiereBauabdruck as Ce}from"../bauabdruck.js";import{beurteileSpeicher as Te,zahlAusInfo as ge}from"../speicherlage.js";import{beurteileDeckung as De}from"../eingaenge.js";import{VEKTOR_NACHTRAG as Me,NAME_VEKTOR_NACHTRAG as ze,ZWEIT_VEKTOR_NACHTRAG as Ie}from"../bedeutung.js";import{join as B}from"node:path";import{calculateConfidence as ee,CONFIDENCE_STALE_VALUE as ce,CONFIDENCE_WARN_VALUE as Pe,CONFIDENCE_WARN_DAYS as we,CONFIDENCE_STALE_DAYS as ye}from"../confidence.js";import{safeJsonParse as z,leseOderNull as _e,darfHeraus as Fe,teamweitLesbar as K}from"../utils.js";import{ersparteMinuten as Be,istStarterLektion as Ue,fmtStunden as $e}from"../wertbeitrag.js";import{CURSOR_MDC_FRONTMATTER as Ke,buildClaudeMdBlock as Je,setzeAnweisungsblock as He}from"../projektdateien.js";import{aussetzerEinzelheit as Ge,aussetzerErklaerung as ve,leseVermerke as qe}from"../aussetzer.js";import{schwaerzeFelder as We}from"../geheimnis-filter.js";import{VERDACHT_TAG as be,pruefeFelder as Ve,verdachtsWarnung as Ye}from"../tuersteher.js";import{fuerEigenenSpeicher as le,fuerWeitergabe as Ze,fuerZusammenfassung as ke,hinweise as ue,markiert as Xe,markierungsWarnung as Qe,weitergabeHinweis as et}from"../schreibtor.js";import{holeRolle as H,istMitglied as he,rolleFuer as Se,lerneUeberApi as tt,bestaetigeUeberApi as st,ROLLEN_SEITE as Z}from"../rolle.js";const Lt=new Set(["sync_file_changes","team_learn","team_confirm","team_recall","team_synthesize","memory_crystalize","team_crystallize","brain_doctor","brain_hygiene","recall_at","trace_dependency","global_learn","global_recall","publish_lesson","import_public_brain","setup_ai_memory","team_assign_role","team_whoami","team_roster","team_grant_scope","team_scopes","team_audit"]),W={admin:4,reviewer:3,contributor:2,viewer:1},F={admin:"\u{1F451}",reviewer:"\u{1F6E1}\uFE0F",contributor:"\u270F\uFE0F",viewer:"\u{1F441}\uFE0F"},te={admin:"assign roles \xB7 delete lessons \xB7 all reviewer + contributor actions",reviewer:"senior-review lessons (\u{1F6E1}\uFE0F) \xB7 all contributor actions",contributor:"store lessons \xB7 peer-review lessons (\u2714\uFE0F) \xB7 recall",viewer:"recall only \u2014 cannot store or review lessons"},G=w=>`cachly:team:roles:${w}`;async function V(w,m,y){return await w.hget(G(m),y.toLowerCase()).catch(()=>null)}async function nt(w,m,y){const R=await H(m);return R?R.role:y?V(w,m,y):null}const de={owner:"owner of this brain",org_admin:"organisation admin",assigned:"assigned by an admin",default:"default for members"};function pe(w){const m=de[w.source]??w.source;return m?`${w.role} (${m})`:w.role}function X(w,m){return w?(W[w]??0)>=(W[m]??0):!1}function ot(w){return w==="admin"||w==="reviewer"?"senior":"peer"}async function at(w,m){if(await H(m))return!0;const y=await w.hgetall(G(m)).catch(()=>({}));return Object.values(y).includes("admin")}async function me(w,m,y,R,a){const t=await H(m);if(t)return X(t.role,R)?null:[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${R}\` ${F[R]} (your role: ${F[t.role]} ${pe(t)}).`,"",`Roles are set by the brain owner or an organisation admin in the dashboard: ${Z}`,"_Run `team_whoami` to check your role._"].join(`
|
|
2
|
+
`);if(!await at(w,m))return null;const n=y?await V(w,m,y):null;if(X(n,R))return null;const r=n?`${F[n]} ${n}`:"no role";return[`\u{1F512} **Permission denied** \u2014 to ${a} you need at least \`${R}\` ${F[R]} (you have: ${r}).`,"","Ask an admin to grant it:",`\`team_assign_role(instance_id="${m}", handle="${y||"<your-handle>"}", role="${R}", assigned_by="<admin>")\``,"_Governance is active on this brain. Run `team_whoami` to check your role._"].join(`
|
|
3
|
+
`)}async function xe(w,m,y){const R=`cachly:team:audit:${m}`,a=JSON.stringify({...y,ts:new Date().toISOString()});await w.rpush(R,a).catch(()=>{}),await w.ltrim(R,-500,-1).catch(()=>{}),await w.expire(R,365*2*86400).catch(()=>{})}const rt="cachly:team:review_mode",it="cachly:lesson:proposed:",ct=90*86400;async function lt(w,m){const y=await w.get(rt).catch(()=>null);return y==="1"||y==="true"||y==="on"}async function ut(w,m,y){const R={...y,proposed_at:new Date().toISOString(),status:"pending"};await w.set(`${it}${m}`,JSON.stringify(R),"EX",ct).catch(()=>{});const a=typeof y.author=="string"&&y.author?` by **${y.author}**`:"";return[`\u{1F4DD} **Lesson submitted for review** \u2014 \`${m}\`${a} is now a pending proposal.`,"","This team requires review before knowledge enters the Team Brain (org setting).","An org owner/admin can approve or reject it in the dashboard under **Team \u2192 Review**.","Until approved it will NOT surface in `smart_recall` / `team_recall`."].join(`
|
|
4
|
+
`)}const se=w=>`cachly:team:groups:${w}`,Q=(w,m)=>`cachly:team:group:${w}:${m.toLowerCase()}`;async function Ae(w,m,y){const R=await w.smembers(se(m)).catch(()=>[]),a=new Set;for(const t of R)await w.sismember(Q(m,t),y.toLowerCase()).catch(()=>0)&&a.add(t.toLowerCase());return a}function Re(w,m,y){return!w||y?!0:m.has(w.toLowerCase())}const ne=Object.freeze({scopes:new Set,isAdmin:!1});async function jt(w,m,y){const R=await H(m),a=(y??"").trim();if(!a)return R?.role==="admin"?{scopes:new Set,isAdmin:!0}:ne;const t=await Ae(w,m,a).catch(()=>new Set),n=R?R.role==="admin":await V(w,m,a).catch(()=>null)==="admin";return{scopes:t,isAdmin:n}}function ht(w,m){if(!Fe(w))return!1;const y=typeof w.group=="string"?w.group.trim():w.group?String(w.group):"";return Re(y||null,m.scopes,m.isAdmin)}function Nt(w,m=ne){const y=new Map;return async R=>{const a=y.get(R);if(a!==void 0)return a;const t=await w.get(`cachly:lesson:best:${R}`).catch(()=>null),n=t===null||ht(_e(t),m);return y.set(R,n),n}}function Le(w,m,y){const R=w.filter(t=>!m.has(t)),a=R.slice(0,y);return{namen:a,rest:w.length-a.length,davonVerborgen:w.length-R.length}}async function Ot(w,m,y,R){switch(w){case"sync_file_changes":{const{instance_id:a,changed_files:t,git_diff_stat:n,commit_msg:r}=m,i=le({changed_files:t,git_diff_stat:n,commit_msg:r}),{changed_files:e,git_diff_stat:o,commit_msg:l}=i.felder,c=await y(a),s={ts:new Date().toISOString(),files:e,commit_msg:l,diff_stat:o?.slice(0,500),...i.verdacht.length?{verdacht:i.verdacht}:{}};await c.lpush("cachly:session:file_changes",JSON.stringify(s)),await c.ltrim("cachly:session:file_changes",0,99),await c.expire("cachly:session:file_changes",30*86400);const d=[],u=c.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((j,A)=>{u.on("data",x=>d.push(...x)),u.on("end",j),u.on("error",A)});const _=[],k=d.length>0?await c.mget(...d):[];for(const j of k){const A=K(j);if(!A)continue;const x=A.topic.toLowerCase().split(/[:\-_]/);if(e.some(S=>{const g=S.split("/").pop()?.replace(/\.[^.]+$/,"").toLowerCase()??"";return x.some(h=>h.length>3&&g.includes(h))||(A.file_paths??[]).some(h=>S.includes(h)||h.includes(S))})){const S=A.outcome==="success"?"\u2705":"\u26A0\uFE0F";_.push(` ${S} \`${A.topic}\` \u2014 ${A.what_worked.slice(0,80)}`)}}const b=[`\u{1F4C1} **File sync recorded**: ${e.length} files`,l?`\u{1F4DD} Commit: "${l}"`:"","",`**Changed:** ${e.slice(0,8).map(j=>`\`${j}\``).join(", ")}${e.length>8?` +${e.length-8} more`:""}`,"",...ue(i,"notiz")];return _.length>0?b.push(`\u{1F9E0} **Relevant brain lessons (${_.length}):**`,..._):b.push("\u{1F4A1} No existing lessons match these files yet. Add them with `learn_from_attempts`."),b.filter(Boolean).join(`
|
|
5
|
+
`)}case"team_learn":{const a=We(m).felder,t=Ve(a),{instance_id:n,author:r,topic:i,outcome:e,what_worked:o,what_failed:l,severity:c,file_paths:s,commands:d,tags:u}=a;if(!r||!i||!e||!o)return"\u274C Required: author, topic, outcome, what_worked";if(!["success","failure","partial"].includes(e))return"\u274C outcome must be one of: success, failure, partial";if(!r.trim())return"\u274C Required: author (a name or handle, not blank)";const _=n;if(!_)return"\u274C instance_id required";const k=await y(_),b=await me(k,_,r,"contributor","store team lessons");if(b)return b;if(he(k))return tt(R,_,{topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],author:r},Se(k));const j={topic:i,outcome:e,what_worked:o,what_failed:l??"",severity:c??"minor",author:r,file_paths:s??[],commands:d??[],tags:[...u??[],"team",...t.length?[be]:[]],timestamp:new Date().toISOString(),ts:new Date().toISOString(),recall_count:0,version:2};if(await lt(k,_))return ut(k,i,j);const A=`cachly:lessons:${i}`;return await k.rpush(A,JSON.stringify(j)),e==="success"&&await k.set(`cachly:lesson:best:${i}`,JSON.stringify(j)),`\u2705 Team lesson stored by **${r}**: \`${i}\` (${e})
|
|
6
|
+
\u{1F4A1} ${o.slice(0,120)}${t.length?`
|
|
7
|
+
${Ye(t)}`:""}`}case"team_confirm":{const{instance_id:a,topic:t,reviewer:n,level:r,note:i=""}=m,e=le({note:i}),o=e.felder.note;if(!a)return"\u274C instance_id required";if(!t||!n)return"\u274C Required: topic, reviewer";const l=await y(a),c=await me(l,a,n,"reviewer","confirm team lessons");if(c)return c;if(he(l))return st(R,a,{topic:t,...r?{tier:r}:{},...o?{note:o.slice(0,280)}:{}},Se(l));const s=await nt(l,a,n),d=ot(s),u=r==="peer"?"peer":r==="senior"&&X(s,"reviewer")?"senior":d,_=s?` (role: ${F[s]} ${s})`:" (no role assigned \u2014 peer weight applied)",k=`cachly:lesson:best:${t}`,b=await l.get(k),j=z(b,null);if(!j)return`\u{1F4ED} No best-solution lesson found for \`${t}\`.
|
|
8
|
+
|
|
9
|
+
A lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;const A=`cachly:lesson:endorsers:${t}`,x=await l.sadd(A,n)===1;await l.expire(A,365*86400);const p=await l.scard(A),g=(j.review_level??"")==="senior"?"senior":u,h={...j,reviewed_by:n,review_level:g,endorsements:p,reviewed_at:new Date().toISOString()};await l.set(k,JSON.stringify(h));const $={reviewer:n,level:u,note:o.slice(0,280),ts:new Date().toISOString(),...e.verdacht.length?{verdacht:e.verdacht}:{}},N=`cachly:lesson:reviews:${t}`;await l.rpush(N,JSON.stringify($)),await l.ltrim(N,-50,-1),await l.expire(N,365*86400),await xe(l,a,{action:"team_confirm",actor:n,topic:t,level:g});const T=g==="senior"?"\u{1F6E1}\uFE0F senior-reviewed":"\u2714\uFE0F peer-reviewed",O=x?"":` (already endorsed by ${n} \u2014 no change to rank)`;return`${T} \u2014 \`${t}\` confirmed by **${n}**${_} (${p} distinct endorsement${p===1?"":"s"})${O}.
|
|
10
|
+
\u{1F4C8} This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.${o?`
|
|
11
|
+
\u{1F4DD} ${o.slice(0,200)}`:""}${ue(e,"notiz").map(E=>`
|
|
12
|
+
${E}`).join("")}`}case"team_recall":{const{instance_id:a,author:t,limit:n=10}=m,r=m.topic??(typeof m.query=="string"?m.query:void 0),i=Number.isFinite(Number(n))&&Number(n)>=1?Math.floor(Number(n)):10,e=await y(a),o=[],l=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((u,_)=>{l.on("data",k=>o.push(...k)),l.on("end",u),l.on("error",_)});let c=[];if(o.length>0){const u=await e.mget(...o);for(const _ of u){const k=K(_);k&&c.push(k)}}if(r){const u=r.toLowerCase();c=c.filter(_=>_.topic.toLowerCase().includes(u)||(_.tags??[]).some(k=>k.toLowerCase().includes(u)))}if(t){const u=t.toLowerCase();c=c.filter(_=>_.author?.toLowerCase().includes(u))}const s=u=>u.reviewed_by?u.review_level==="senior"?2:1:0;if(c.sort((u,_)=>s(_)-s(u)||(_.recall_count??0)-(u.recall_count??0)),c=c.slice(0,i),c.length===0)return r||t?`\u{1F4ED} No team lessons found for ${[r&&`topic \`${r}\``,t&&`author \`${t}\``].filter(Boolean).join(" and ")}.
|
|
12
13
|
|
|
13
14
|
Add lessons with \`team_learn\` (requires an \`author\`).`:`\u{1F4ED} No lessons in this brain yet.
|
|
14
15
|
|
|
15
|
-
All team members sharing this instance will see lessons here.`;const d=[`\u{1F465} **Team Brain** \u2014 ${
|
|
16
|
-
`)}case"team_synthesize":{const{instance_id:
|
|
16
|
+
All team members sharing this instance will see lessons here.`;const d=[`\u{1F465} **Team Brain** \u2014 ${c.length} lesson${c.length>1?"s":""}`,""];for(const u of c){const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",k=u.severity==="critical"?"\u{1F534} ":u.severity==="major"?"\u{1F7E1} ":"",b=u.reviewed_by?u.review_level==="senior"?" \u{1F6E1}\uFE0F":" \u2714\uFE0F":"",j=u.author?` \xB7 _by ${u.author}_`:"",A=u.reviewed_by?` \xB7 reviewed by ${u.reviewed_by}${(u.endorsements??0)>1?` +${(u.endorsements??0)-1}`:""}`:"",x=(u.recall_count??0)>0?` \xB7 in ${u.recall_count} answers`:"",p=new Date(u.ts??u.timestamp??"").getTime(),S=Math.max(0,Math.round((Date.now()-p)/864e5)),g=Number.isNaN(p)?"":S===0?" \xB7 today":S===1?" \xB7 yesterday":` \xB7 ${S}d ago`;d.push(`${_} ${k}**\`${u.topic}\`**${b}${j}${A}${x}${g}`);const h=Qe(u);h&&d.push(` ${h}`),d.push(` ${u.what_worked.slice(0,120)}`),d.push("")}return d.join(`
|
|
17
|
+
`)}case"team_synthesize":{const{instance_id:a,topic:t}=m,n=await y(a),r=`cachly:lessons:${t}`,i=(await n.lrange(r,0,-1)).filter(p=>K(p)!==null);if(i.length<2)return`\u{1F4ED} Need at least 2 entries for topic \`${t}\` to synthesize.
|
|
17
18
|
|
|
18
|
-
Currently: ${
|
|
19
|
+
Currently: ${i.length} entr${i.length===1?"y":"ies"}.
|
|
19
20
|
|
|
20
|
-
Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=
|
|
21
|
-
`)}case"memory_crystalize":{const{instance_id:
|
|
22
|
-
`)}case"team_crystallize":{const{instance_id:
|
|
23
|
-
`);const S=[`\u{1F4A0} **Team Crystal created: ${x}**`,"",`\u{1F9EC} **${A.length} cross-person pattern${A.length!==1?"s":""}** \u2014 fixes that ${e}+ teammates independently converged on.`,`_Compressed from ${
|
|
24
|
-
`)}case"brain_doctor":{const{instance_id:
|
|
25
|
-
`)}case"brain_hygiene":{const{instance_id:
|
|
26
|
-
`)}case"recall_at":{const{instance_id:
|
|
27
|
-
`)}case"trace_dependency":{const{instance_id:
|
|
21
|
+
Have team members store lessons via \`learn_from_attempts(topic="${t}", ...)\`.`;const e=i.map(p=>{try{return JSON.parse(p)}catch{return null}}).filter(p=>p!==null),o=e.filter(p=>p.outcome==="success"),l=e.filter(p=>p.outcome==="failure"),c=e.filter(p=>p.outcome==="partial"),s=[...new Set(e.map(p=>p.author).filter(Boolean))],d=s.length>1,u=o.sort((p,S)=>new Date(S.ts).getTime()-new Date(p.ts).getTime())[0],k=o.map(p=>p.what_worked).filter(p=>p&&p.length>10).sort((p,S)=>S.length-p.length)[0]??u?.what_worked??"",b=[...new Set([...l,...c].map(p=>p.what_failed).filter(p=>!!p&&p.length>5))],j=e.map(p=>p.severity).filter(Boolean),A=j.includes("critical")?"critical":j.includes("major")?"major":"minor";return[`\u{1F9EC} **Team Brain Synthesis: \`${t}\`**`,`_${e.length} entries from ${s.length} author${s.length===1?"":"s"}${d?` (${s.join(", ")})`:""} \xB7 ${o.length} success \xB7 ${l.length} failure \xB7 ${c.length} partial_`,"",'**Canonical "what worked":**',`> ${k}`,"",b.length>0?"**Avoid (combined failures):**":"",...b.map(p=>`> \u274C ${p}`),(b.length>0,""),"**Suggested canonical lesson:**","```","learn_from_attempts(",` topic = "${t}",`,' outcome = "success",',` what_worked = "${k.replace(/"/g,"'")}",`,b.length>0?` what_failed = "${b[0].replace(/"/g,"'")}",`:"",` severity = "${A}",`,")","```","",d?`\u{1F4A1} _${s.length} team members contributed to this synthesis. Store the canonical version to replace individual entries._`:"\u{1F4A1} _Single author \u2014 more value when multiple team members contribute to the same topic._"].filter(p=>p!==void 0).join(`
|
|
22
|
+
`)}case"memory_crystalize":{const{instance_id:a,label:t=""}=m,n=await y(a),r=new Date,i=`${r.getFullYear()}-W${String(Math.ceil((r.getDate()-r.getDay()+10)/7)).padStart(2,"0")}`,e=t||`${r.toISOString().slice(0,7)} Crystal`,o=await n.lrange("cachly:session:history",0,49),l=[],c=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((x,p)=>{c.on("data",S=>l.push(...S)),c.on("end",x),c.on("error",p)});const s=[];let d=0,u=0;if(l.length>0){const x=await n.mget(...l);for(const p of x){const S=K(p);if(!S)continue;const g=ke(S);if(!g){d++;continue}g.geschwaerzt&&u++,s.push(g.lektion)}}const _=new Map;for(const x of s){const p=x.topic.split(":")[0]||"misc";_.has(p)||_.set(p,[]),_.get(p).push(x)}const k=[];for(const[x,p]of[..._.entries()].sort((S,g)=>g[1].length-S[1].length).slice(0,8)){const g=p.filter(h=>h.outcome==="success")[0]??p[0];g&&k.push({category:x,insight:g.what_worked.slice(0,120),count:p.length})}const b={label:e,ts:r.toISOString(),session_count:o.length,lesson_count:s.length,top_patterns:k,categories:[..._.keys()],created_from:`${o.length} sessions, ${s.length} lessons`,...d>0?{ausgelassen:d}:{}},j=JSON.stringify(b);return await n.set("cachly:crystal:latest",j),await n.expire("cachly:crystal:latest",90*86400),await n.set(`cachly:crystal:${i}`,j),await n.expire(`cachly:crystal:${i}`,365*86400),[`\u{1F48E} **Memory Crystal created: ${e}**`,"",`\u{1F4CA} Compressed: **${o.length} sessions** + **${s.length} lessons** \u2192 ${k.length} top patterns`,"","**Top patterns by category:**",...k.slice(0,6).map(x=>` \u2022 **${x.category}** (${x.count}\xD7): ${x.insight.slice(0,90)}`),"","\u{1F4A1} This crystal will appear in every future `session_start` briefing.","\u{1F4A1} Re-run `memory_crystalize` monthly to keep it fresh.",...d>0?["",`\u26A0 ${d} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...u>0?[`\u{1F512} ${u} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]].join(`
|
|
23
|
+
`)}case"team_crystallize":{const{instance_id:a,min_authors:t=2,label:n=""}=m,r=await y(a),i=new Date,e=Math.max(2,Number(t)||2),o=[],l=r.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((g,h)=>{l.on("data",$=>o.push(...$)),l.on("end",g),l.on("error",h)});const c=[];let s=0,d=0;if(o.length>0){const g=await r.mget(...o);for(const h of g){const $=K(h);if(!$||$.outcome!=="success"||!$.author)continue;const N=ke($);if(!N){s++;continue}N.geschwaerzt&&d++,c.push(N.lektion)}}const u=[...s>0?[`\u26A0 ${s} lesson(s) not summarized: flagged as suspicious when saved, or detected today by the Tuersteher (security gate) as an instruction/dangerous command. Check them or save them again.`]:[],...d>0?[`\u{1F512} ${d} lesson(s) contained secrets \u2014 redacted before summarizing (the lessons themselves stay unchanged).`]:[]],_=new Set(["the","and","for","with","from","that","this","fix","bug","error","issue","use","via","add","set","team"]),k=g=>{const[h,...$]=g.topic.split(":"),N=(g.tags??[]).map(E=>E.toLowerCase().trim()).filter(E=>E.length>3&&!_.has(E)).sort();return N.length>0?N[0]:$.join("-").toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/[\s-]+/).filter(E=>E.length>3&&!_.has(E)).sort((E,M)=>M.length-E.length||E.localeCompare(M))[0]??h},b=new Map;for(const g of c){const h=k(g);let $=b.get(h);$||($={concept:h,authors:new Set,lessons:[],namespaces:new Set,bestFix:g},b.set(h,$)),$.authors.add(g.author.toLowerCase()),$.lessons.push(g),$.namespaces.add(g.topic.split(":")[0]||"misc");const N=T=>(T.endorsements??0)*10+(T.confirm_count??0)+(T.review_level==="senior"?5:0);N(g)>N($.bestFix)&&($.bestFix=g)}const A=[...b.values()].filter(g=>g.authors.size>=e).sort((g,h)=>h.authors.size-g.authors.size||h.lessons.length-g.lessons.length).slice(0,10).map(g=>({concept:g.concept,author_count:g.authors.size,authors:[...g.authors],lesson_count:g.lessons.length,spans:[...g.namespaces],convergent_fix:g.bestFix.what_worked.slice(0,200),fix_topic:g.bestFix.topic})),x=n||`${i.toISOString().slice(0,7)} Team Crystal`,p={label:x,ts:i.toISOString(),kind:"team",contributors:new Set(c.map(g=>g.author.toLowerCase())).size,analysed:c.length,patterns:A,...s>0?{ausgelassen:s}:{}};if(await r.set("cachly:crystal:team:latest",JSON.stringify(p)),await r.expire("cachly:crystal:team:latest",180*86400),A.length===0)return["\u{1F4A0} **Team Crystal \u2014 not enough cross-person convergence yet**","",`Analysed **${c.length}** attributed success lessons from **${p.contributors}** contributor${p.contributors!==1?"s":""}, but no concept had **${e}+ distinct authors** converge on it yet.`,"","This is the one thing a per-user memory can't build \u2014 it needs your team to accumulate shared, attributed lessons.",'Keep using `learn_from_attempts(author="...")` / `team_learn`; re-run as the team grows.',...u.length?["",...u]:[]].join(`
|
|
24
|
+
`);const S=[`\u{1F4A0} **Team Crystal created: ${x}**`,"",`\u{1F9EC} **${A.length} cross-person pattern${A.length!==1?"s":""}** \u2014 fixes that ${e}+ teammates independently converged on.`,`_Compressed from ${c.length} attributed lessons across ${p.contributors} contributors. This is the team-wide, causal layer a per-user "Dreaming" process structurally cannot produce._`,""];for(const g of A.slice(0,6)){const h=g.spans.length>1?` \xB7 spans ${g.spans.map($=>`\`${$}\``).join(", ")}`:"";S.push(`### \u{1F9E9} \`${g.concept}\` \u2014 ${g.author_count} people converged${h}`,`**Convergent fix** (from \`${g.fix_topic}\`): ${g.convergent_fix}`,`**Who solved it together:** ${g.authors.map($=>`@${$}`).join(", ")} _(ask them \u2014 they've each hit this)_`,"")}return S.push("---","\u{1F4A1} Surfaces in `crystal_view` and onboarding. Re-run `team_crystallize` monthly.",...u.length?["",...u]:[]),S.join(`
|
|
25
|
+
`)}case"brain_doctor":{const{instance_id:a,workspace_path:t=""}=m,n=await y(a),r=[],i=[],e=[],o=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((f,v)=>{o.on("data",L=>e.push(...L)),o.on("end",f),o.on("error",v)});let l=0;const c=n.scanStream({match:"cachly:ctx:*",count:200});await new Promise((f,v)=>{c.on("data",L=>{l+=L.filter(C=>!C.endsWith(":meta")).length}),c.on("end",f),c.on("error",v)});const s=[],d=new Set;if(e.length>0){const f=await n.mget(...e);for(const v of f){const L=z(v??null,null);L&&(s.push(L),K(v)||d.add(L.topic))}}const u=f=>{const{namen:v,davonVerborgen:L}=Le(f.map(I=>I.topic),d,3),C=v.map(I=>`\`${I}\``);return L>0&&C.push(`${L} private or group-only, not named`),C.join(", ")},_=await n.get("cachly:session:last"),k=z(_,null),b=s.filter(f=>f.outcome==="failure"||f.outcome==="partial"),j=s.filter(f=>(f.recall_count??0)===0),A=s.filter(f=>f.severity==="critical"),x=s.filter(f=>f.outcome==="success"&&ee(f)<=ce),p=s.filter(f=>f.outcome==="success"&&ee(f)>ce&&ee(f)<=Pe),S=s.filter(f=>(f.audit_trail??[]).length>1),g=s.filter(f=>f.author),h=new Set(s.map(f=>f.author).filter(Boolean)),$=s.reduce((f,v)=>f+(v.recall_count??0),0),N=s.length>0?Math.min(100,Math.round($/s.length*10)):0,T=async f=>{let v=0;const L=n.scanStream({match:f,count:200});return await new Promise((C,I)=>{L.on("data",P=>{v+=P.length}),L.on("end",C),L.on("error",I)}),v},O=await T("cachly:lesson:vec:*"),E=await T("cachly:lesson:vecname:*"),M=await T("cachly:lesson:eing:*"),U=await T("cachly:lesson:pfad:*"),oe=await T("cachly:lesson:vec2:*"),ae=O>0?Math.round(oe/O*100):0;O>0&&i.push(ae>=80?`\u2705 **Second-model coverage: ${ae}%** \u2014 ${oe} of ${O} embedded lessons also carry the second-model vector; the second ranking feature is ON`:`\u{1F7E1} **Second-model coverage: ${ae}%** \u2014 ${O-oe} lessons still lack the second-model vector; the second ranking feature stays OFF below 80% and backfills three lessons per recall`);const q=await Promise.all([Me,ze,Ie].map(f=>n.smembers(f).then(v=>v.length).catch(()=>0)));if(q.some(f=>f>0)&&i.push(`\u{1F7E1} **Vector backfill pending:** ${q[0]} full-text, ${q[1]} topic-name, ${q[2]} second-model \u2014 retried on the next write or recall`),O>0){const f=Math.max(0,O-E),v=Math.max(0,f-q[1]);f===0?i.push(`\u2705 **Topic-name coverage: 100%** \u2014 all ${O} embedded lessons carry a topic-name vector`):i.push(`\u{1F7E1} **Topic-name coverage: ${Math.round(E/O*100)}%** \u2014 ${f} of ${O} embedded lessons lack a topic-name vector (${Math.min(f,q[1])} queued and healed on the next write or recall`+(v>0?`, ${v} older ones not queued and not healed automatically`:"")+")")}const re=e.length>0?Math.round(O/e.length*100):100,ie=De(e.length,O);e.length>0&&(ie==="aus"?(r.push(`semantic search is OFF: not a single lesson has an embedding (0 of ${e.length}). Recall falls back to keyword matching only. Fix: run the backfill (sdk/mcp/src/eingaenge-nachruesten.ts).`),i.push(`\u{1F534} **Semantic search: OFF** \u2014 0 of ${e.length} lessons have an embedding`)):ie==="luecke"?(r.push(`only ${re}% of lessons have an embedding (${O} of ${e.length}) \u2014 the rest can never be found by meaning.`),i.push(`\u{1F7E1} **Semantic coverage: ${re}%** \u2014 ${e.length-O} lessons without an embedding`)):(i.push(`\u2705 **Semantic coverage: ${re}%** \u2014 ${O} full-text, ${E} topic-name, ${M} with error-text entries`+(U>0?`, ${U} with learned question paths`:"")),U===0&&e.length>=20&&i.push("\u{1F4A4} **No learned question paths yet** \u2014 a question that finds the same lesson twice becomes its own entry. Needs repeated real use.")));try{const f=await qe(n);for(const v of f??[]){const L=Ge(v.text);i.push(`\u26A0\uFE0F **Failure noted:** ${ve(v.grund)} \u2014 ${v.anzahl}\xD7 (last: ${v.zuletzt})`+(L?` \xB7 ${L}`:"")),r.push(`failures recorded (${v.anzahl}\xD7): ${ve(v.grund)} \u2014 see the check above.`)}}catch{}let D=50;e.length>=5&&(D+=10),e.length>=20&&(D+=10),l>=3&&(D+=10),l>=10&&(D+=5),k&&(D+=10),b.length===0&&(D+=5);const fe=s.length>0?j.length/s.length:0;fe<.5&&(D+=10),x.length===0&&(D+=5),h.size>=2&&(D+=5),ie!=="gut"&&(D-=20),D=Math.max(0,Math.min(100,D));const je=D>=80?"\u{1F7E2}":D>=50?"\u{1F7E1}":"\u{1F534}",Ne=N>=50?"\u{1F680}":N>=20?"\u{1F4C8}":"\u{1F4A4}";i.push(`${je} **Brain Quality Score: ${D}/100**`),i.push(`${Ne} **Effective IQ Boost: ${N}%** (${$} recalls across ${s.length} lessons)`);try{const v=(await n.lrange("cachly:recall:spread",0,199)).map(L=>z(L,null)?.spread).filter(L=>typeof L=="number"&&Number.isFinite(L));if(v.length===0)i.push("\u{1F4CF} **Rank spread:** not measured yet \u2014 recorded from the next `smart_recall` on (score gap rank 1 \u2192 rank 5).");else{const L=v.reduce((P,Y)=>P+Y,0)/v.length,C=v.filter(P=>P<.05).length,I=`mean ${L.toFixed(3)} over ${v.length} recall${v.length===1?"":"s"} (${C} flat, < 0.05)`;v.length>=20&&L<.05?(i.push(`\u{1F7E1} **Rank spread: ${I}** \u2014 ranking has stopped separating hits; provisional threshold, see card 0u9s8qoopwhr`),r.push("Rank spread is flat: the top hits score alike. Check whether the store has grown past what the ranking separates (near-duplicates, one embedding for everything).")):i.push(`\u{1F4CF} **Rank spread:** ${I}`)}}catch{}i.push(`\u{1F4DA} **Lessons:** ${e.length} (${A.length} critical \xB7 ${S.length} with audit trail \xB7 ${g.length} from team)`),i.push(`\u{1F4BE} **Context entries:** ${l}`),i.push(`\u{1F3AF} **Confidence:** ${s.length-x.length-p.length} fresh \xB7 ${p.length} warn \xB7 ${x.length} stale`),i.push(`\u23F1\uFE0F **Decay config:** warn after ${we}d \xB7 stale after ${ye}d`),i.push(Ce(Ee));try{const f=await n.info("memory");let v=null;if(he(n))v=/^maxmemory_policy:(\S+)/m.exec(String(f))?.[1]??null;else try{const C=await n.config("GET","maxmemory-policy");v=Array.isArray(C)&&C.length>1?String(C[1]):null}catch{v=null}const L={benutzt:ge(f,"used_memory"),grenze:ge(f,"maxmemory"),richtlinie:v};for(const C of Te(L)){const P=`${C.art==="fehler"?"\u{1F534}":C.art==="hinweis"?"\u{1F7E1}":C.art==="ungemessen"?"\u26AA":"\u{1F7E2}"} **Storage:** ${C.text}`;C.art==="fehler"||C.art==="ungemessen"?r.push(P):i.push(P)}}catch{r.push("\u26AA **Storage:** state could not be read \u2014 unknown whether this store silently deletes when it is full.")}h.size>=2&&i.push(`\u{1F465} **Team:** ${h.size} contributors (${[...h].join(", ")})`);try{const f=await n.get("cachly:index:last_run");if(f){const v=Math.round((Date.now()-new Date(f).getTime())/864e5);v>7?r.push(`\u{1F504} Index is ${v}d stale \u2014 run \`index_project\` to re-sync semantic search`):i.push(`\u{1F5C2}\uFE0F **Semantic index:** ${v}d old (fresh)`)}else r.push('\u{1F4A1} No semantic index \u2014 run `index_project(dir="<your-src>")` to enable semantic search')}catch{}try{const f=await n.get("cachly:crystal:latest");if(f){const v=JSON.parse(f),L=Math.round((Date.now()-new Date(v.ts).getTime())/864e5);i.push(`\u{1F48E} **Memory Crystal:** ${v.label} (${L}d ago)`),L>30&&r.push(`\u{1F4A1} Memory Crystal is ${L}d old \u2014 re-run \`memory_crystalize\` to compress new sessions`)}else e.length>=10&&r.push(`\u{1F4A1} ${e.length} lessons but no Memory Crystal \u2014 run \`memory_crystalize\` to compress wisdom`)}catch{}if(t)try{const f=t.replace(/\/$/,"")+"/package.json",v=Oe(f,"utf-8"),L=JSON.parse(v),C={...L.dependencies,...L.devDependencies},I=["openai","@anthropic-ai/sdk","@google/generative-ai","mistralai","cohere-ai"].some(Y=>Y in C),P="@cachly-dev/openclaw"in C;I&&!P?(r.push(`\u{1F4A1} **openclaw missing:** you use LLM APIs (${Object.keys(C).filter(Y=>["openai","@anthropic-ai/sdk"].includes(Y)).join(", ")}) but not \`@cachly-dev/openclaw\``),r.push(" \u2192 `npm install @cachly-dev/openclaw` cuts LLM costs 60\u201390% with 3 lines of code")):P&&i.push("\u2705 **@cachly-dev/openclaw installed** (LLM cost caching active)")}catch{}if(k){const f=Math.round((Date.now()-new Date(k.ts).getTime())/6e4),v=f<60?`${f}m`:f<1440?`${Math.round(f/60)}h`:`${Math.round(f/1440)}d`;i.push(`\u{1F550} **Last session:** ${v} ago`)}else r.push("\u274C No session history \u2014 call `session_start` + `session_end` to start tracking");e.length===0?r.push("\u274C No lessons \u2014 call `learn_from_attempts` after solving bugs"):e.length<5&&r.push(`\u{1F4A1} Only ${e.length} lessons \u2014 add more after each problem solved`),N===0&&s.length>=5&&r.push("\u{1F4A4} **IQ Boost is 0%** \u2014 lessons exist but are never recalled. Use `recall_best_solution` BEFORE tasks."),l===0&&r.push("\u{1F4A1} No context \u2014 use `remember_context` to cache architecture docs, ADRs, etc."),b.length>0&&r.push(`\u26A0\uFE0F ${b.length} unresolved failure${b.length>1?"s":""}: ${u(b)}`),x.length>0&&(r.push(`\u{1F534} ${x.length} STALE lesson${x.length>1?"s":""} (${ye}d+ since written or checked, confidence ${ce*100}%): ${u(x)}`),r.push(" \u2192 Re-run each check, then confirm with `lesson_verified` (recalling does not reset the clock)")),p.length>0&&r.push(`\u26A0\uFE0F ${p.length} lesson${p.length>1?"s":""} aging (${we}d+): ${u(p)}`),fe>.7&&s.length>5&&r.push(`\u{1F4A1} ${j.length} lessons never recalled \u2014 verify topics match your workflow`);const J=["\u{1FA7A} **Brain Doctor**",`\`${"\u2500".repeat(48)}\``,"","**\u{1F4CA} Health Checks**",...i.map(f=>" "+f),""];return r.length>0?(J.push(`**\u{1F527} Action Items** (${r.length} issue${r.length>1?"s":""})`),r.forEach((f,v)=>J.push(` ${v+1}. ${f}`)),J.push(""),J.push("_brain_doctor only reports and changes nothing. Act on the items above, then run it again to check._")):(J.push("**\u2705 All checks passed** \u2014 Brain is healthy!"),J.push(""),J.push("_Keep the brain sharp: `session_start` \u2192 work \u2192 `learn_from_attempts` \u2192 `session_end`_")),J.join(`
|
|
26
|
+
`)}case"brain_hygiene":{const{instance_id:a,dry_run:t=!1,provisional_threshold:n=.5,archive_days:r=30}=m,i=await y(a),e=[],o=i.scanStream({match:"cachly:lesson:best:*",count:200});if(await new Promise((h,$)=>{o.on("data",N=>e.push(...N)),o.on("end",h),o.on("error",$)}),e.length===0)return"\u{1F9F9} **Brain Hygiene** \u2014 no lessons found. Nothing to sweep.";const l=await i.mget(...e),c=[],s=new Set;for(let h=0;h<e.length;h++){const $=l[h],N=z($??null,null);N&&(c.push({...N,_key:e[h]}),K($)||s.add(N.topic))}const d=Date.now(),u=[],_=[],k=[],b=new Map;for(const h of c){const $=h.state??"active";if($==="archived")continue;const N=ee(h),T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(N<=n){const E=h.recall_count??0;if($==="provisional"&&E<2&&O>r){if(_.push(h.topic),!t){const U={...h,state:"archived",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"archived",prev_state:"provisional"}]};b.set(h._key,U)}}else if($==="active"&&(u.push(h.topic),!t)){const U={...h,state:"provisional",audit_trail:[...h.audit_trail??[],{ts:new Date().toISOString(),action:"flagged_provisional",prev_state:"active"}]};b.set(h._key,U)}}}for(const h of c){const $=h.state??"active";if($==="archived"||b.has(h._key)&&b.get(h._key).state==="archived"||h.outcome!=="failure"||(h.recall_count??0)>0)continue;const T=new Date(h.verified_at??h.ts).getTime(),O=(d-T)/864e5;if(O<=r)continue;const E=u.indexOf(h.topic);if(E!==-1&&u.splice(E,1),k.push({topic:h.topic,text:`${h.topic} (failure, never recalled, ${Math.round(O)}d old)`}),!t){const M=b.get(h._key)??h,U={...M,state:"archived",audit_trail:[...M.audit_trail??[],{ts:new Date().toISOString(),action:"orphan_failure_archived",prev_state:$}]};b.set(h._key,U)}}let j=0,A=0;const x=parseFloat(await i.get(`cachly:stats:time_saved_mins:${a}`)??"0")||0;for(const h of c){if(Ue(h)){if((h.recall_count??0)>0){j++;const $=b.get(h._key)??h;b.set(h._key,{...$,recall_count:0})}continue}(h.recall_count??0)>0&&(A+=Be(h))}if(t||await i.set(`cachly:stats:time_saved_mins:${a}`,String(A)).catch(()=>{}),!t&&b.size>0){const h=i.pipeline();for(const[$,N]of b){const{_key:T,...O}=N;h.set($,JSON.stringify(O))}await h.exec()}const S=[`${t?"\u{1F50D} **Brain Hygiene (dry run)**":"\u{1F9F9} **Brain Hygiene**"} \u2014 scanned **${c.length}** lessons`,"","| Action | Count |","|---|---|",`| Flagged provisional (confidence < ${n}) | ${u.length} |`,`| Archived (stale + low-recall + age > ${r}d) | ${_.length} |`,`| Contradictions auto-resolved | ${k.length} |`,`| Startvorrat entwertet (Z\xE4hler auf 0) | ${j} |`,""];Math.round(x)!==Math.round(A)&&S.push(`**\u23F1\uFE0F Zeitersparnis neu gerechnet:** ${$e(x)} \u2192 **${$e(A)}**`,"_Nur eigene Lektionen, und jede genau einmal. Der mitgelieferte Startvorrat ist Allgemeinwissen, kein gelerntes; und wer dieselbe Lektion zum zweiten Mal liest, spart keine zweite Recherche._","");const g=(h,$,N)=>{const{namen:T,rest:O,davonVerborgen:E}=Le(h,s,$);if(T.forEach(M=>S.push(` - ${N(M)}`)),O>0){const M=E>0?` (${E} of them private or group-only, not named)`:"";S.push(` - _\u2026and ${O} more${M}_`)}};if(u.length>0&&(S.push("**\u26A0\uFE0F Provisional (verify or re-learn):**"),g(u,10,h=>`\`${h}\``),S.push("")),_.length>0&&(S.push("**\u{1F4E6} Archived (excluded from recall):**"),g(_,5,h=>`\`${h}\``),S.push("")),k.length>0){S.push("**\u2694\uFE0F Contradictions resolved (failure archived, success kept):**");const h=new Map(k.map($=>[$.topic,$.text]));g(k.map($=>$.topic),5,$=>h.get($)??`\`${$}\``),S.push("")}return t?S.push("_Run `brain_hygiene(dry_run=false)` to apply these changes._"):u.length+_.length+k.length===0?S.push("\u2705 Brain is clean \u2014 no hygiene actions needed."):S.push("_Changes applied. Run `brain_doctor` to verify the updated health score._"),S.join(`
|
|
27
|
+
`)}case"recall_at":{const{instance_id:a,topic:t,date:n}=m,r=await y(a),i=new Date(n).getTime();if(isNaN(i))return`\u274C Invalid date "${n}". Use ISO format: "2026-01-15"`;const e=`cachly:lessons:${t}`,o=(await r.lrange(e,0,-1)).filter(s=>{const d=_e(s);return d!==null&&Re(d.group,ne.scopes,ne.isAdmin)});if(o.length===0)return`\u{1F4ED} No history found for \`${t}\`. Lessons are stored via \`learn_from_attempts\`.`;const l=o.map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null&&new Date(s.ts).getTime()<=i).sort((s,d)=>new Date(s.ts).getTime()-new Date(d.ts).getTime());if(l.length===0){const s=z(o[0]??null,null),d=s?.ts?new Date(s.ts).toLocaleDateString("de-DE"):"unknown";return`\u{1F4ED} No entries for \`${t}\` found before **${n}**. Earliest entry: ${d}.`}const c=[`\u{1F3FA} **Brain Archaeology: \`${t}\` before ${n}**`,`_${l.length} of ${o.length} total entries shown_`,""];for(const s of l.slice(-10)){const d=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",u=new Date(s.ts).toLocaleDateString("de-DE");c.push(`**${u}** ${d} ${s.outcome}`),s.what_worked&&c.push(` \u2192 ${s.what_worked.slice(0,100)}`),c.push("")}return c.push(`_Full evolution: ${o.map(s=>{try{const d=JSON.parse(s);return d.outcome==="success"?"\u2705":d.outcome==="partial"?"\u26A0\uFE0F":"\u274C"}catch{return"?"}}).join(" \u2192 ")}_`),c.join(`
|
|
28
|
+
`)}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}\`.
|
|
28
29
|
|
|
29
|
-
Add dependencies via: \`learn_from_attempts(..., depends_on=["${t}"])\``;const
|
|
30
|
-
`)}case"global_learn":{const{instance_id:
|
|
30
|
+
Add dependencies via: \`learn_from_attempts(..., depends_on=["${t}"])\``;const o=z(e,[]),l=[`\u{1F517} **Causal Chain: \`${t}\`** \u2014 ${o.length} dependent lesson${o.length===1?"":"s"}`,""];let c=0;for(const s of o){const d=await r.get(`cachly:lesson:best:${s}`);if(!d){l.push(` \u2022 \`${s}\` _(lesson deleted)_`);continue}const u=z(d,null);if(!u){l.push(` \u2022 \`${s}\` _(lesson corrupted)_`);continue}if(K(d)===null){c++,n&&await r.set(`cachly:lesson:best:${s}`,JSON.stringify({...u,needs_review:!0}));continue}const _=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",k=u.needs_review?" \u{1F50D} **needs_review**":"";if(l.push(` ${_} \`${s}\` (${u.severity??"major"})${k}`),n){const b={...u,needs_review:!0};await r.set(`cachly:lesson:best:${s}`,JSON.stringify(b))}}return c>0&&l.push(` \u{1F512} ${c} private or group-only, not named.`),n?l.push("",`\u{1F50D} All ${o.length} lessons marked as **needs_review** \u2014 verify they still work with the changed dependency.`):l.push("","_Run with `mark_review: true` to flag all dependent lessons for re-verification._"),l.join(`
|
|
31
|
+
`)}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
32
|
|
|
32
33
|
${l}
|
|
33
34
|
|
|
34
|
-
Recallable from any project via \`global_recall(topic="${
|
|
35
|
-
`)}case"global_recall":{const{instance_id:
|
|
35
|
+
Recallable from any project via \`global_recall(topic="${o}")\`.`,...ue(e)].join(`
|
|
36
|
+
`)}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
37
|
|
|
37
|
-
Add cross-project knowledge with \`global_learn(topic="...", lesson="...")\`.`;for(const l of e){const
|
|
38
|
-
`)}case"publish_lesson":{const{instance_id:
|
|
39
|
-
`)}case"import_public_brain":{const{instance_id:
|
|
38
|
+
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(`
|
|
39
|
+
`)}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(`
|
|
40
|
+
`)}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}\`.
|
|
40
41
|
|
|
41
42
|
Available: ${d}
|
|
42
43
|
|
|
43
|
-
Or publish your own: \`publish_lesson(framework="${t}", ...)\``}const l=
|
|
44
|
-
`)}case"setup_ai_memory":{const{instance_id:
|
|
45
|
-
`)}case"team_assign_role":{const{instance_id:
|
|
46
|
-
`)
|
|
47
|
-
`)}
|
|
44
|
+
Or publish your own: \`publish_lesson(framework="${t}", ...)\``}const l=o.slice(0,n);let c=0;for(const d of l){const u=`cachly:lesson:best:${d.topic}`;await r.get(u)||(await r.set(u,JSON.stringify({...d,what_worked:d.lesson,outcome:"success",ts:new Date().toISOString(),recall_count:0,source:"public_brain",version:2})),c++)}return[`\u{1F4E5} **Public Brain imported: ${t}**`,"",`${c} new lessons added (${l.length-c} already existed)`,"","**Imported topics:**",...l.map(d=>` ${d.severity==="critical"?"\u{1F534}":d.severity==="major"?"\u{1F7E1}":"\u{1F4A1}"} \`${d.topic}\``),"","These lessons will now appear in `session_start` when relevant.",`Recall any time: \`recall_best_solution(topic="${e}:...")\``].join(`
|
|
45
|
+
`)}case"setup_ai_memory":{const{instance_id:a,project_dir:t,embed_provider:n="openai",project_description:r="a software project"}=m,i=await R(`/api/v1/instances/${a}`),e={openai:{key:"OPENAI_API_KEY",hint:"Get at: https://platform.openai.com/api-keys"},mistral:{key:"MISTRAL_API_KEY",hint:"Get at: https://console.mistral.ai/api-keys"},cohere:{key:"COHERE_API_KEY",hint:"Get at: https://dashboard.cohere.com/api-keys"},ollama:{key:"OLLAMA_BASE_URL",hint:"Run: brew install ollama && ollama serve (free, local, no key needed)"},gemini:{key:"GEMINI_API_KEY",hint:"Get at: https://aistudio.google.com/app/apikey"}},o=e[n]??e.openai,l=!!i.vector_token,c=JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"your-api-token-from-cachly.dev/settings",[o.key]:n==="ollama"?"http://localhost:11434":"your-key-here",...n!=="openai"?{CACHLY_EMBED_PROVIDER:n}:{}}}}},null,2),s=i.tier.toUpperCase(),d=Je(a),u=["\u{1F9E0} **cachly AI Memory Setup Complete**","",`**Project:** ${r}`,`**Instance:** ${i.name} (${s}) \xB7 ID: \`${a}\``,`**Embedding Provider:** ${n}`,`**Semantic Search:** ${l?"\u2705 pgvector HNSW available":"\u26A0\uFE0F needs a vector token \u2014 rotate it in the dashboard (every tier includes one)"}`,"","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**Step 1 \u2014 Add to .mcp.json:**","```json",c,"```","",`**Step 2 \u2014 Set your ${n} key:**`,"```bash",`export ${o.key}="your-key-here"`,"```",`_(${o.hint})_`,"","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**Step 3 \u2014 Brain rules (Layer 3 Autopilot):**","",...t?[`\u{1F50D} Detecting IDEs in \`${t}\`\u2026`]:["Copy this to `.github/copilot-instructions.md` (Copilot), `CLAUDE.md` (Claude Code), or `.cursor/rules` (Cursor) in your project:"],"","```markdown",d,"```","","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","**How the 3 layers work together:**"," Layer 1 \u2192 Your Valkey instance stores all lessons + context (persists forever)"," Layer 2 \u2192 MCP tools (learn_from_attempts, recall_best_solution, smart_recall) read/write it"," Layer 3 \u2192 copilot-instructions.md makes your AI run them automatically","","Result: Your AI never solves the same problem twice. \u{1F680}"];if(t){const{access:_}=await import("node:fs/promises"),{constants:k}=await import("node:fs"),b=async x=>_(x,k.F_OK).then(()=>!0).catch(()=>!1),j=[{ide:"GitHub Copilot",path:B(t,".github","copilot-instructions.md")}];(await b(B(t,"CLAUDE.md"))||await b(B(t,".claude")))&&j.push({ide:"Claude Code",path:B(t,"CLAUDE.md")}),(await b(B(t,".cursor"))||await b(B(t,".cursorrules")))&&j.push({ide:"Cursor",path:B(t,".cursor","rules","cachly.mdc"),prefix:Ke}),(await b(B(t,".windsurfrules"))||await b(B(t,".windsurf")))&&j.push({ide:"Windsurf",path:B(t,".windsurfrules")});const A=[];for(const x of j){const p=await He(x.path,d,x.prefix),S=p==="written"?"written":p==="unchanged"?"already current, nothing changed":p==="updated"?"cachly block updated, rest of the file unchanged":"cachly block appended, your text kept";A.push(`\u2705 [${x.ide}] \u2192 \`${x.path.replace(t,".")}\` (${S})`)}A.push("\u2139\uFE0F Hooks (session briefing, per-prompt recall) are set up by `npx @cachly-dev/mcp-server@latest init` or `autopilot`."),u.push(...A)}return u.join(`
|
|
46
|
+
`)}case"team_assign_role":{const{instance_id:a,handle:t,role:n,assigned_by:r=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, role";const i=["admin","reviewer","contributor","viewer"].includes(n)?n:null;if(!i)return`\u274C Unknown role \`${n}\`. Valid: admin \xB7 reviewer \xB7 contributor \xB7 viewer`;const e=await H(a);if(e)return["\u2139\uFE0F **Roles are no longer set here.** Nothing was changed.","",`The brain owner or an organisation admin sets roles in the dashboard: ${Z}`,`There, \`${t}\` can be made \`${i}\` (the roles admin and owner come from the account and are not assigned).`,"",`Your role: ${F[e.role]} ${pe(e)}. Run \`team_whoami\` to see what it allows.`].join(`
|
|
47
|
+
`);const o=await y(a),l=await o.hgetall(G(a)).catch(()=>({})),c=Object.values(l).includes("admin");if(c){const _=r?await V(o,a,r):null;if(!X(_,"admin"))return["\u274C **Permission denied** \u2014 only an `admin` can assign roles.","","Ask an existing admin to run:",`\`team_assign_role(instance_id="${a}", handle="${t}", role="${n}", assigned_by="<their-handle>")\``].join(`
|
|
48
|
+
`)}const s=l[t.toLowerCase()]??null;await o.hset(G(a),t.toLowerCase(),i),await o.expire(G(a),365*2*86400),await xe(o,a,{action:"team_assign_role",actor:r||"(bootstrap)",handle:t.toLowerCase(),from:s,to:i});const d=!c;return[`${F[i]} **Role assigned** \u2014 **${t}** is now a \`${i}\``,"",`**Capabilities:** ${te[i]}`,"",d?"_First admin bootstrapped \u2014 governance is now active on this brain._":`_Assigned by ${r||"(bootstrap)"}_`,"","Run `team_roster` to see all current roles."].join(`
|
|
49
|
+
`)}case"team_whoami":{const{instance_id:a,handle:t}=m;if(!a||!t)return"\u274C Required: instance_id, handle";const n=await H(a);if(n){const o=n.can,l=s=>s?"yes":"no",c=[`## ${F[n.role]} ${t} \u2014 \`${n.role}\``,"",`**Where the role comes from:** ${de[n.source]??(n.source||"unknown")} (cachly API, not the brain store)`,`**You can:** ${te[n.role]}`,`**Allowed:** store lessons ${l(o.learn)} \xB7 confirm ${l(o.confirm)} \xB7 withdraw ${l(o.withdraw)} \xB7 manage roles ${l(o.manage)}`];return n.review_mode&&c.push("**Review required:** lessons from contributors become proposals until an admin approves them."),c.push("",`Roles are set by the brain owner or an organisation admin: ${Z}`),c.join(`
|
|
50
|
+
`)}const r=await y(a),i=await V(r,a,t);if(!i){const o=await r.hgetall(G(a)).catch(()=>({})),l=Object.values(o).includes("admin");return[`\u{1F441}\uFE0F **${t}** has no assigned role on this brain.`,"",l?`Ask an admin to run \`team_assign_role(handle="${t}", role="contributor")\` to add you.`:`This brain has no roles set up yet. Establish governance:
|
|
48
51
|
\`team_assign_role(handle="${t}", role="admin")\``].join(`
|
|
49
|
-
`)}return[`## ${
|
|
50
|
-
`)}case"team_roster":{const{instance_id:
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
`)
|
|
54
|
-
`)
|
|
55
|
-
`)
|
|
56
|
-
`);const o=
|
|
57
|
-
`)}
|
|
52
|
+
`)}return[`## ${F[i]} ${t} \u2014 \`${i}\``,"",`**You can:** ${te[i]}`,"","Run `team_roster` to see all team members and their roles."].join(`
|
|
53
|
+
`)}case"team_roster":{const{instance_id:a}=m;if(!a)return"\u274C Required: instance_id";if(await H(a)){let e=null;try{const c=await R(`/api/v1/instances/${encodeURIComponent(a)}/members`);e=Array.isArray(c?.members)?c.members:null}catch{e=null}if(!e)return`## \u{1F465} Team Roster
|
|
54
|
+
|
|
55
|
+
The member list could not be loaded right now. Roles are managed in the dashboard: ${Z}`;const o=[...e].sort((c,s)=>(W[s.role]??0)-(W[c.role]??0)||String(c.display_name??"").localeCompare(String(s.display_name??"")));return[`## \u{1F465} Team Roster (${o.length} member${o.length!==1?"s":""})`,"","| Role | Member | Source |","|---|---|---|",...o.map(c=>{const s=c.role??"";return`| ${F[s]??"?"} ${c.role??"?"} | **${c.display_name||"(no name)"}** | ${de[c.source??""]??(c.source||"")} |`}),"",`_Roles come from the cachly API. The owner or an organisation admin changes them at ${Z}._`].join(`
|
|
56
|
+
`)}const n=await(await y(a)).hgetall(G(a)).catch(()=>({}));if(Object.keys(n).length===0)return["## \u{1F465} Team Roster","","No roles assigned yet. Establish governance with:",`\`team_assign_role(instance_id="${a}", handle="<your-handle>", role="admin")\``].join(`
|
|
57
|
+
`);const r=Object.entries(n).map(([e,o])=>({handle:e,role:o})).sort((e,o)=>(W[o.role]??0)-(W[e.role]??0)||e.handle.localeCompare(o.handle)),i=[`## \u{1F465} Team Roster (${r.length} member${r.length!==1?"s":""})`,"","| Role | Handle | Capabilities |","|---|---|---|"];for(const e of r){const o=F[e.role]??"?";i.push(`| ${o} ${e.role} | **${e.handle}** | ${te[e.role].split(" \xB7 ").slice(0,2).join(", ")} |`)}return i.push("","_Manage with `team_assign_role`. Any admin can add or change roles._"),i.join(`
|
|
58
|
+
`)}case"team_audit":{const{instance_id:a,requester:t="",limit:n=50}=m;if(!a)return"\u274C Required: instance_id";const r=await y(a),i=await me(r,a,t,"admin","view the governance audit log");if(i)return i;const e=Math.min(Math.max(1,Number(n)||50),200),o=await r.lrange(`cachly:team:audit:${a}`,-e,-1).catch(()=>[]);if(o.length===0)return["## \u{1F4DC} Governance Audit Log","","No governance events recorded yet.","Events are logged automatically on `team_assign_role` and `team_confirm`."].join(`
|
|
59
|
+
`);const l=o.map(s=>z(s,null)).filter(s=>s!==null).reverse(),c=s=>{const d=s.ts?new Date(s.ts).toISOString().replace("T"," ").slice(0,16):"?";return s.action==="team_assign_role"?`| ${d} | \u{1F451} role | **${s.actor}** set \`${s.handle}\`: ${s.from??"\u2014"} \u2192 **${s.to}** |`:s.action==="team_confirm"?`| ${d} | \u2705 confirm | **${s.actor}** confirmed \`${s.topic}\` (${s.level}) |`:`| ${d} | ${s.action??"?"} | ${s.actor??"?"} |`};return[`## \u{1F4DC} Governance Audit Log (${l.length} event${l.length!==1?"s":""})`,"","| When (UTC) | Type | Detail |","|---|---|---|",...l.map(c),"",`_Immutable trail \xB7 2-year retention \xB7 last ${e} events. Admin-only._`].join(`
|
|
60
|
+
`)}case"team_grant_scope":{const{instance_id:a,handle:t,group:n,action:r="add",assigned_by:i=""}=m;if(!a||!t||!n)return"\u274C Required: instance_id, handle, group";const e=String(n).toLowerCase().trim();if(!e)return'\u274C `group` must be a non-empty name (e.g. "backend", "security")';const o=await y(a),l=await H(a);if(l&&l.role!=="admin")return`\u274C **Permission denied** \u2014 only the brain owner or an organisation admin can manage group scopes (your role: ${pe(l)}).`;const c=l?{}:await o.hgetall(G(a)).catch(()=>({}));if(Object.values(c).includes("admin")){const d=i?await V(o,a,i):null;if(!X(d,"admin"))return"\u274C **Permission denied** \u2014 only an `admin` can manage group scopes. Ask an admin to set `assigned_by`."}return r==="remove"?(await o.srem(Q(a,e),t.toLowerCase()),`\u{1F513} **${t}** removed from group \`${e}\`.`):(await o.sadd(se(a),e),await o.sadd(Q(a,e),t.toLowerCase()),await o.expire(se(a),365*2*86400),await o.expire(Q(a,e),365*2*86400),[`\u{1F510} **Scope granted** \u2014 **${t}** is now in group \`${e}\`.`,"",`Lessons stored with \`group="${e}"\` will surface in recall for ${t} (and other \`${e}\` members + admins) only.`,"",`Store a scoped lesson: \`learn_from_attempts(topic="...", group="${e}", ...)\``].join(`
|
|
61
|
+
`))}case"team_scopes":{const{instance_id:a,handle:t}=m;if(!a)return"\u274C Required: instance_id";const n=await y(a);if(t){const e=await Ae(n,a,t);return e.size===0?`\u{1F441}\uFE0F **${t}** is in no groups \u2014 sees only team-wide + public lessons.`:`\u{1F510} **${t}** belongs to: ${[...e].map(o=>`\`${o}\``).join(", ")}`}const r=await n.smembers(se(a)).catch(()=>[]);if(r.length===0)return["## \u{1F510} Team Scopes","","No groups defined yet. Create one by adding a member:",`\`team_grant_scope(instance_id="${a}", handle="alice", group="backend")\``].join(`
|
|
62
|
+
`);const i=[`## \u{1F510} Team Scopes (${r.length} group${r.length!==1?"s":""})`,""];for(const e of r.sort()){const o=await n.smembers(Q(a,e)).catch(()=>[]);i.push(`- **\`${e}\`** (${o.length}): ${o.length?o.map(l=>`**${l}**`).join(", "):"_empty_"}`)}return i.push("",'_Scope a lesson to a group with `learn_from_attempts(group="...")`. Members + admins see it; others don\'t._'),i.join(`
|
|
63
|
+
`)}default:return null}}export{se as GROUPS_INDEX_KEY,Q as GROUP_KEY,ne as NIEMAND,it as PROPOSED_LESSON_PREFIX,rt as REVIEW_MODE_KEY,G as ROLES_KEY,F as ROLE_BADGE,Lt as TEAM_TOOL_NAMES,xe as auditLog,nt as eigeneRolle,jt as fragenderAusweis,V as getRole,Ae as getScopes,Ot as handleTeamTool,X as hasPermission,Re as lessonVisibleToScope,Nt as namensPruefer,at as rbacActive,me as requireRole,lt as reviewModeEnabled,ot as roleToReviewLevel,ht as sichtbarFuer,ut as storeLessonProposal,K as teamweitLesbar,Le as teamweiteNamen};
|