@cachly-dev/mcp-server 0.10.194 → 0.10.195
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-hook-start.js +1 -1
- package/dist/src/ambient-hook.js +3 -3
- package/dist/src/einblendung.js +4 -4
- package/dist/src/git-lektionen.js +2 -0
- package/dist/src/handlers/fedbrain.js +39 -40
- package/dist/src/index.js +75 -75
- package/dist/src/konto-anlegen.js +1 -1
- package/dist/src/startwissen-hook.js +1 -0
- package/dist/src/startwissen.js +19 -17
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +29 -28
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileURLToPath as
|
|
1
|
+
import{fileURLToPath as t}from"node:url";import{AUFFRISCHEN as r,auffrischenHauptlauf as i,hookHauptlauf as o,startwissenImportHauptlauf as f}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as s}from"./startwissen-hook.js";const a=process.argv.slice(2);a[0]===r?await i():a[0]===s?await f(a[1]??""):await o(a,t(import.meta.url));
|
package/dist/src/ambient-hook.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as x}from"node:fs";import{tmpdir as z}from"node:os";import{parseHookPayload as H,runEinblendung as C,stopLernanfrage as K,stopObservation as N}from"./ambient-cli.js";import{stopAntwort as j}from"./schreibbeleg.js";import{holeBestand as R,hookAusgabe as M,starteNebenlauf as G}from"./einblendung.js";import{STARTWISSEN_IMPORT as y,hookImportFuerAuftrag as B,importiereStartwissen as Y}from"./startwissen-hook.js";import{belohnungMelden as $}from"./lernen.js";import{appendLedgerEntry as D,reportLedgerEntry as J}from"./ambient-ledger.js";import{copilotHatHook as V,cursorHatHook as Q,findeInstanz as g,findeSchluessel as h,hookUmfeld as S,pluginVersion as W,projektHatHook as X}from"./hook-zugang.js";import{ABKUEHLUNG_HOOK_MS as q,schreibeAuftrag as O,sichereKonto as Z,startwissenEingeschaltet as tt}from"./konto-anlegen.js";import{istInstanzKennung as U,sofortTestHinweis as et}from"./zugang.js";import{CURSOR_FLAG as p,cursorEreignis as L,cursorHookAntwort as nt,cursorLeer as rt,istCursorNutzlast as P}from"./cursor-hook.js";import{COPILOT_FLAG as w,copilotEreignis as ot,copilotHookAntwort as it,istFremdeLaufzeit as T}from"./copilot-hook.js";import{CODEX_FLAG as v,codexHookAntwort as st}from"./codex-hook.js";import{GEMINI_FLAG as _,geminiEreignis as ct,geminiHookAntwort as ut}from"./gemini-hook.js";const at="https://api.cachly.dev",E=5e3,ft="ambient-auffrischen",F=new Set(["SessionStart","UserPromptSubmit","PreToolUse","Stop"]);async function lt(t,e){if(!t.args.includes(p)&&(L(e,t.args)!=="sessionStart"||Q(t.umfeld)))return"";const o=t.args.filter(r=>r==="--plugin");return nt({payload:e,args:t.args,claudeLauf:(r,u)=>I({...t,raw:r,args:[u,...o]}),ablageOrdner:t.cursorAblage})}function pt(t,e){const n=(o,r)=>I({...t,raw:o,args:[r]});return t.args.includes(w)?it({payload:e,args:t.args,claudeLauf:n,ablageOrdner:t.copilotAblage}):t.args.includes(v)?st({payload:e,args:t.args,claudeLauf:n}):t.args.includes(_)?ut({payload:e,args:t.args,claudeLauf:n}):null}function dt(t,e){return t.includes(p)||P(e)?"cursor":t.includes(w)?"copilot":t.includes(v)?"codex":t.includes(_)?"gemini":T(e)?"vscode":"claude"}async function mt(t){const e=await Z({apiUrl:t.apiUrl,version:W(t.umfeld),home:t.umfeld.heim,env:{...t.umfeld.env,CACHLY_QUELLE:"claude-code-plugin"},fristMs:E,anfrageMs:E,abkuehlungMs:q,holen:t.fetchFn});if(e.art==="vorhanden")return{apiKey:e.apiKey,instanzId:e.instanzId,hinweis:""};if(e.art!=="angelegt")return null;if(tt(t.umfeld.env)){const n={apiUrl:t.apiUrl,jwt:e.test.apiKey,instanceId:e.test.instanzId};t.selbst&&(t.nebenlauf??G)(n,[t.selbst,y,t.umfeld.projekt],{zweck:y,ordner:z()})||O({instanzId:e.test.instanzId,projekt:t.umfeld.projekt},{home:t.umfeld.heim})}return{apiKey:e.test.apiKey,instanzId:e.test.instanzId,hinweis:et(e.test)}}function gt(t,e){const n=e.replace(/^\s+/,"");if(!t)return M("SessionStart",n);try{const o=JSON.parse(t),r=o.hookSpecificOutput?.additionalContext;return!o.hookSpecificOutput||typeof r!="string"?t:(o.hookSpecificOutput.additionalContext=`${n}
|
|
2
2
|
|
|
3
|
-
${r}`,JSON.stringify(
|
|
4
|
-
`);const
|
|
3
|
+
${r}`,JSON.stringify(o))}catch{return t}}async function I(t){try{const e=H(t.raw),n={...t,editor:t.editor??dt(t.args,e)};if(n.args.includes(p)||P(e))return await lt(n,e);const o=pt(n,e);if(o)return await o;const r=e?.hook_event_name??n.args.find(i=>F.has(i))??n.umfeld.env.CACHLY_HOOK_EVENT??"";if(T(e)&&(r!=="SessionStart"&&r!=="UserPromptSubmit"||V(n.umfeld))||n.args.includes("--plugin")&&r&&X(r,n.umfeld))return"";let u=null;if(r==="Stop"&&e?.transcript_path)try{u=x(e.transcript_path,"utf-8").split(`
|
|
4
|
+
`);const i=j(u,e.stop_hook_active===!0);if(i)return i}catch{}let a=h(n.umfeld),c=g(n.umfeld),s="";if(!a&&r==="SessionStart"&&n.args.includes("--plugin")&&!U(c)){const i=await mt(n);i&&(a=i.apiKey,c=i.instanzId??c,s=i.hinweis)}if(!a||!c)return"";const f={apiUrl:n.apiUrl,jwt:a,instanceId:c};if(r==="Stop"){const i=e?N(e):null,m=i?(n.fetchFn??fetch)(`${f.apiUrl}/api/v1/instances/${f.instanceId}/learn`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.jwt}`},body:JSON.stringify(K(i)),signal:AbortSignal.timeout(8e3)}).catch(()=>{}):void 0,l=$(f,e?.session_id??null,u,{fetchFn:n.fetchFn});return await Promise.all([m,l]),""}let d;const A=await(n.einblenden??C)(n.raw,{cfg:f,nebenlauf:n.selbst?[n.selbst,ft]:void 0,editor:n.editor,fetchFn:n.fetchFn,onInject:(i,m)=>{const l={ts:new Date().toISOString(),event:m,injected:i,prevented:0};D(l),d=J(f,l,n.fetchFn)}});return d&&await Promise.race([d,new Promise(i=>setTimeout(i,500))]),s?gt(A,s):A}catch{return""}}async function ht(){if(process.stdin.isTTY)return"";const t=[];for await(const e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}function b(){return process.env.CACHLY_API_URL||at}const k={SessionStart:25e3,UserPromptSubmit:8e3,PreToolUse:8e3,Stop:5e4,sessionStart:25e3,beforeSubmitPrompt:8e3,postToolUse:3e3,userPromptSubmitted:8e3,PostToolUse:3e3,BeforeAgent:8e3};function St(t,e){return t.includes(p)?rt(L(e,t)):t.includes(w)?ot(e,t)?"{}":"":t.includes(_)&&ct(e,t)?"{}":""}async function Ft(t,e){try{const n=await ht(),o=H(n),r=o?.hook_event_name??t.find(s=>F.has(s)||Object.hasOwn(k,s))??"",u=Number(process.env.CACHLY_HOOK_FRIST_MS)||k[r]||k.UserPromptSubmit,a=St(t,o),c=await Promise.race([I({args:t,raw:n,umfeld:S(),apiUrl:b(),selbst:e}),new Promise(s=>setTimeout(()=>s(a),u))]);c&&await new Promise(s=>process.stdout.write(c,()=>s()))}catch{}process.exit(0)}async function xt(){try{const t=S(),e=h(t),n=g(t);e&&n&&await R({apiUrl:b(),jwt:e,instanceId:n},{force:!0,lernen:!0})}catch{}process.exit(0)}async function zt(t){try{const e=S(),n=h(e),o=g(e);if(n&&U(o)){const r=await Y({cfg:{apiUrl:b(),jwt:n,instanceId:o},projekt:t,env:e.env});r.art!=="aus"&&O({instanzId:o,projekt:t,vomHook:B(r)},{home:e.heim})}}catch{}process.exit(0)}export{ft as AUFFRISCHEN,k as HOOK_FRIST_MS,E as KONTO_FRIST_MS,at as STANDARD_API_URL,xt as auffrischenHauptlauf,dt as editorVon,I as hookAntwort,Ft as hookHauptlauf,zt as startwissenImportHauptlauf};
|
package/dist/src/einblendung.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{readFileSync as T,existsSync as C,writeFileSync as R,mkdirSync as Y,statSync as Z,appendFileSync as G}from"node:fs";import{dirname as j,join as _}from"node:path";import{tmpdir as S}from"node:os";import{createHash as F}from"node:crypto";import{spawn as W}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U}from"./einblendung-rahmen.js";import{istMarkiert as V}from"./verdacht-marke.js";import{leserText as X}from"./seltenheitsbestand.js";import{mischeMitLeser as z}from"./leser.js";import{LeserSicherung as Q,dateiSpeicher as ee,frageLeser as te}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as ne,LESER_ZEITLIMIT_MS as re}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as se}from"./gueltigkeit-version.js";import{ARME as H,BASIS_MIN_BELEGE as oe,MERKMAL_KANDIDATEN as ie,OHNE_LERNEN as le,entscheide as ae,leseArmZaehlung as ce,lernEinstellungen as ue,lernenAuffrischen as pe,merkeEntscheidung as fe,neuerSatz as he,sitzungsKennung as me,zugKennung as de}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as it,lernenAuffrischen as lt,lernEinstellungen as at,ARME as ct}from"./lernen.js";const ge=600*1e3,Ee=300*1e3,_e=10*1e3,Se=2e3,Ae=50,ke=60*1e3;function Ie(e,t){return t<Ee?{ttlMs:_e,sofort:!0}:e<Ae?{ttlMs:ke,sofort:!1}:{ttlMs:ge,sofort:!1}}const O=8e3,Ne=60*1e3,P=120,D=ne,ye=1500,I=re,be=_(S(),"cachly-ambient-netlog.jsonl");function We(e=process.cwd()){const t={apiUrl:process.env.CACHLY_API_URL||"https://api.cachly.dev",jwt:process.env.CACHLY_JWT||"",instanceId:process.env.CACHLY_BRAIN_INSTANCE_ID||""};if(t.jwt&&t.instanceId)return t;let n=e;for(let s=0;s<8;s++){const
|
|
1
|
+
import{readFileSync as T,existsSync as C,writeFileSync as R,mkdirSync as Y,statSync as Z,appendFileSync as G}from"node:fs";import{dirname as j,join as _}from"node:path";import{tmpdir as S}from"node:os";import{createHash as F}from"node:crypto";import{spawn as W}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U}from"./einblendung-rahmen.js";import{istMarkiert as V}from"./verdacht-marke.js";import{leserText as X}from"./seltenheitsbestand.js";import{mischeMitLeser as z}from"./leser.js";import{LeserSicherung as Q,dateiSpeicher as ee,frageLeser as te}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as ne,LESER_ZEITLIMIT_MS as re}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as se}from"./gueltigkeit-version.js";import{ARME as H,BASIS_MIN_BELEGE as oe,MERKMAL_KANDIDATEN as ie,OHNE_LERNEN as le,entscheide as ae,leseArmZaehlung as ce,lernEinstellungen as ue,lernenAuffrischen as pe,merkeEntscheidung as fe,neuerSatz as he,sitzungsKennung as me,zugKennung as de}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as it,lernenAuffrischen as lt,lernEinstellungen as at,ARME as ct}from"./lernen.js";const ge=600*1e3,Ee=300*1e3,_e=10*1e3,Se=2e3,Ae=50,ke=60*1e3;function Ie(e,t){return t<Ee?{ttlMs:_e,sofort:!0}:e<Ae?{ttlMs:ke,sofort:!1}:{ttlMs:ge,sofort:!1}}const O=8e3,Ne=60*1e3,P=120,D=ne,ye=1500,I=re,be=_(S(),"cachly-ambient-netlog.jsonl");function We(e=process.cwd()){const t={apiUrl:process.env.CACHLY_API_URL||"https://api.cachly.dev",jwt:process.env.CACHLY_JWT||"",instanceId:process.env.CACHLY_BRAIN_INSTANCE_ID||""};if(t.jwt&&t.instanceId)return t;let n=e;for(let s=0;s<8;s++){const r=_(n,".mcp.json");if(C(r))try{const i=JSON.parse(T(r,"utf8"))?.mcpServers?.cachly?.env??{};if(t.apiUrl=t.apiUrl||i.CACHLY_API_URL||"https://api.cachly.dev",t.jwt=t.jwt||i.CACHLY_JWT||"",t.instanceId=t.instanceId||i.CACHLY_BRAIN_INSTANCE_ID||"",t.jwt&&t.instanceId)return t}catch{}const o=j(n);if(o===n)break;n=o}return t}function N(e){return F("sha1").update(e).digest("hex").slice(0,12)}function we(e){return _(S(),`cachly-ambient-bestand-${N(e)}.json`)}function Me(e){return _(S(),`cachly-leser-sicherung-${N(e)}.json`)}function Le(e,t="ambient-auffrischen"){return _(S(),`cachly-${t}-${N(e)}.lock`)}async function y(e,{fetchFn:t=fetch,zeitlimitMs:n=O}={}){try{const s=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(n)});if(!s.ok)return null;const r=await s.json();return Array.isArray(r?.lessons)?r.lessons.map(o=>typeof o=="string"?ve(o):o).filter(o=>!!o&&typeof o=="object"):null}catch{return null}}function ve(e){try{return JSON.parse(e)}catch{return null}}function b(e,t){try{const n=Date.now(),s=w(e)?.seit??n;Y(j(e),{recursive:!0}),R(e,JSON.stringify({at:n,seit:s,lessons:t}),{mode:384})}catch{}}function w(e){try{const t=JSON.parse(T(e,"utf8"));if(Array.isArray(t?.lessons)){const n=Number(t.at)||0;return{at:n,seit:Number(t.seit)||n,lessons:t.lessons}}}catch{}return null}function xe(e,t,{zweck:n,ordner:s}={}){const r=Le(e.instanceId,n);try{if(C(r)&&Date.now()-Z(r).mtimeMs<Ne)return!1;R(r,String(Date.now()),{mode:384})}catch{return!1}try{return W(process.execPath,t,{detached:!0,stdio:"ignore",...s?{cwd:s}:{},env:{...process.env,CACHLY_API_URL:e.apiUrl,CACHLY_JWT:e.jwt,CACHLY_BRAIN_INSTANCE_ID:e.instanceId}}).unref(),!0}catch{return!1}}async function Te(e,{force:t=!1,nebenlauf:n,abrufMs:s=O,lernen:r=!1,fetchFn:o}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const i=we(e.instanceId);if(t){const[a]=await Promise.all([y(e,{fetchFn:o,zeitlimitMs:s}),r?pe(e,{fetchFn:o}):void 0]);if(a)return b(i,a),{lessons:a,quelle:"server"};const f=w(i);return f?{lessons:f.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const l=w(i);if(l){const a=Date.now(),f=Ie(l.lessons.length,a-l.seit);if(a-l.at<f.ttlMs)return{lessons:l.lessons,quelle:"platte"};if(f.sofort){const m=await y(e,{fetchFn:o,zeitlimitMs:Math.min(s,Se)});return m?(b(i,m),{lessons:m,quelle:"server"}):{lessons:l.lessons,quelle:"platte-alt"}}return n&&xe(e,n),{lessons:l.lessons,quelle:"platte-alt"}}const u=await y(e,{fetchFn:o,zeitlimitMs:s});return u?(b(i,u),{lessons:u,quelle:"server"}):{lessons:[],quelle:"server-nicht-erreichbar"}}function M(e){return Math.ceil(String(e).length/4)}function L(e){const t=e.severity?`[${e.severity}] `:"",n=String(e.what_worked??"").replace(/\s+/g," ").trim(),s=n.length>P?`${n.slice(0,P)}\u2026`:n,r=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${r}: ${s}`}const A={lessons:[],tokens:0,topScore:0,belege:0};function v(e,t,n){if(e.length===0)return{...A};const s=[];let r=0;e=se(e);for(const{lektion:o}of e.slice(0,t)){const i=M(L(o));if(r+i>n)break;s.push(o),r+=i}return{lessons:s,tokens:r,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function Ve(e,t,{minBelege:n=2,topK:s=3,tokenBudget:r=600}={}){if(!Array.isArray(t)||t.length===0)return{...A};if(B(e).length===0)return{...A};const o=new $(t).sortiere(e).filter(i=>i.belege>=n);return o.length===0?{...A}:v(o,s,r)}function Ce(e){return X(e,ye)}async function J(e,t,n,{zeitlimitMs:s=I,fetchFn:r}={}){if(!e?.jwt||!e?.instanceId||n.length===0)return{art:"ohne"};if(["0","off","aus","false"].includes(String(process.env.CACHLY_LESER||"").toLowerCase()))return{art:"ohne"};const o=new Q(ee(Me(e.instanceId)));return te({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:n,instanceId:e.instanceId,zeitlimitMs:s,fetchFn:r},o)}async function Xe(e,t,n,s={}){const r=await J(e,t,n,s);return r.art==="punkte"?{scores:r.scores,provider:r.provider,ms:r.ms}:null}async function K(e,t,n,{minBelege:s,tiefe:r,zeitlimitMs:o,fetchFn:i}){const l={sortiert:[],leser:"aus",leserMs:0};if(!Array.isArray(t)||t.length===0||B(e).length===0)return l;let u=new $(t).sortiere(e).filter(h=>h.belege>=s);if(u.length===0)return l;let a="aus",f=0;if(u.length>1&&r>0){const h=u.slice(0,r),m=u.slice(r),d=await J(n,e,h.map(E=>Ce(E.lektion)),{zeitlimitMs:o,fetchFn:i});d.art==="punkte"?(u=[...z(h.map(p=>p.punkte),d.scores,1).map(p=>({...h[p],leser:d.scores[p]})),...m],a=d.provider,f=d.ms):d.art==="uebersprungen"&&(a="uebersprungen")}return{sortiert:u,leser:a,leserMs:f}}async function Qe(e,t,n,{minBelege:s=2,topK:r=3,tokenBudget:o=600,tiefe:i=D,zeitlimitMs:l=I,fetchFn:u}={}){const a=await K(e,t,n,{minBelege:s,tiefe:i,zeitlimitMs:l,fetchFn:u});return{...v(a.sortiert,r,o),leser:a.leser,leserMs:a.leserMs}}function Re(e){if(!e.lessons.length)return"";const t=e.lessons.map(L).join(`
|
|
2
2
|
`);return`\u{1F9E0} Cachly Brain \u2014 relevant lessons for this task (auto-recall, ${e.lessons.length}):
|
|
3
3
|
${U(t)}
|
|
4
|
-
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const je=5;function et(e){const t=e.filter(
|
|
4
|
+
(ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const je=5;function et(e){const t=e.filter(o=>!V(o));if(!t.length)return"";const n=t.filter(o=>{const i=String(o.topic??"");return!(/^auto:/.test(i)||/^[a-z]+:?$/.test(i))}),r=[...n.length?n:t].sort((o,i)=>(Number(i.recall_count)||0)-(Number(o.recall_count)||0)).slice(0,je).map(L).join(`
|
|
5
5
|
`);return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${t.length} lessons). Top by proven reuse:
|
|
6
|
-
${U(
|
|
7
|
-
(Relevant lessons for each task are auto-injected per prompt. ~${M(
|
|
6
|
+
${U(r)}
|
|
7
|
+
(Relevant lessons for each task are auto-injected per prompt. ~${M(r)} tokens.)`}function tt(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}function $e(e,t){return e.map((n,s)=>({x:n,rang:s,gezeigt:t.includes(n.lektion)})).filter(({rang:n,gezeigt:s})=>n<ie||s).map(({x:n,rang:s,gezeigt:r})=>({thema:String(n.lektion.topic??""),rang:s,punkte:Math.round(n.punkte*1e3)/1e3,belege:n.belege,leser:typeof n.leser=="number"&&Number.isFinite(n.leser)?Math.round(n.leser*1e3)/1e3:null,gezeigt:r}))}async function nt(e,t,{nebenlauf:n,abrufMs:s,leser:r=!0,session:o=null,protokoll:i=!0,ereignis:l="UserPromptSubmit",editor:u="",lernen:a=!0,fetchFn:f}={}){const{lessons:h,quelle:m}=await Te(t,{nebenlauf:n,abrufMs:s,fetchFn:f}),d=ue(),E=a&&d.aktiv&&l==="UserPromptSubmit"&&!!t.instanceId,p=E?ae({instanceId:t.instanceId,sitzung:o,prompt:e,zaehlung:ce(t.instanceId),einstellungen:d}):le,x=H[p.arm]??H[0],g=await K(e,h,t,{minBelege:oe,tiefe:r?D:0,zeitlimitMs:I,fetchFn:f}),c={...v(g.sortiert.filter(q=>q.belege>=x.minBelege),x.topK,600),leser:g.leser,leserMs:g.leserMs},k=p.kontrolle?"":Re(c);if(E&&g.sortiert.length>0&&fe(t.instanceId,o,he({sitzung:me(o),zug:de(e),ereignis:l,editor:u,arm:p.arm,kontrolle:p.kontrolle,erkundet:p.erkundet,ausgewaehlt:c.lessons.length,kandidatenZahl:g.sortiert.length,belege:c.belege,topScore:c.topScore,leser:c.leser,leserMs:c.leserMs,quelle:m,bestand:h.length,kandidaten:$e(g.sortiert,c.lessons)})),i)try{G(be,JSON.stringify({at:Date.now(),session:o,prompt_tokens:M(e),injected_tokens:k?c.tokens:0,matches:k?c.lessons.length:0,arm:p.arm,kontrolle:p.kontrolle,ausgewaehlt:c.lessons.length,top_score:c.topScore,belege:c.belege,leser:c.leser,leser_ms:c.leserMs,quelle:m,bestand:h.length})+`
|
|
8
8
|
`)}catch{}return{kontext:k,auswahl:c,quelle:m,bestand:h.length,entscheidung:p}}export{O as ABRUF_TIMEOUT_MS,P as ANZEIGE_ZEICHEN,ct as ARME,_e as BESTAND_TTL_JUNG_MS,ke as BESTAND_TTL_KLEIN_MS,ge as BESTAND_TTL_MS,Se as JUNG_ABRUF_MS,Ee as JUNG_FENSTER_MS,Ae as KLEIN_LEKTIONEN,I as LESER_HOOK_ZEITLIMIT_MS,ye as LESER_MAX_ZEICHEN,D as LESER_TIEFE,be as NETZ_PROTOKOLL,je as SITZUNG_TOP_N,it as belohnungMelden,Ie as bestandFrist,we as bestandPfad,M as estimateTokens,Te as holeBestand,tt as hookAusgabe,at as lernEinstellungen,lt as lernenAuffrischen,J as leserAnfrageApi,Xe as leserPunkteApi,Ce as leserText,z as mischeMitLeser,nt as promptEinblendung,Re as promptKontext,L as renderLesson,We as resolveConfig,Ve as selectRelevant,Qe as selectRelevantMitLeser,Me as sicherungsPfad,et as sitzungsKontext,xe as starteNebenlauf};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{normalizeGitPath as u}from"./utils.js";import{classifyCommit as m,extractDomain as f}from"./commit-art.js";import{fuerEigenenSpeicher as h,markiert as p}from"./schreibtor.js";const l=12;function w(o,e,t=""){return["log",o,...t?[`--since=${t}`]:[],"--pretty=format:COMMIT|||%H|||%s|||%ad|||%an","--date=short","--no-merges","--name-only","-n",String(e)]}function k(o){const e=[];let t=null;for(const i of o.split(`
|
|
2
|
+
`)){const r=i.trim();if(r.startsWith("COMMIT|||")){t&&e.push(t);const[,s,c,n,a]=r.split("|||");t={sha:(s??"").trim(),subject:(c??"").trim(),date:(n??"").trim(),author:(a??"").trim(),files:[]}}else if(r&&t){const s=u(r);s&&t.files.push(s)}}return t&&e.push(t),e}function g(o){const e=h({subject:o.subject,author:o.author,files:o.files.slice(0,l)}),t={...o,...e.felder},i={commit:t,geschwaerzt:e.geschwaerzt.length>0,verdacht:e.verdacht.length>0};if(!t.subject)return{...i,lektion:null};const{category:r,outcome:s,severity:c}=m(t.subject),n=t.sha.slice(0,8);return{...i,lektion:{topic:`${r}:${f(t.subject)}`,category:r,outcome:s,severity:c,what_worked:t.subject.slice(0,200),what_failed:"",context:`git:${n} by ${t.author} on ${t.date}`,author:t.author||void 0,file_paths:t.files.filter(a=>a.length>0).slice(0,l),commands:[`git show ${n}`],tags:p(["brain_from_git",r,"git-history"],e.verdacht)}}}function x(o){const e=new Map;for(const t of o){const{lektion:i}=g(t);i&&!e.has(i.topic)&&e.set(i.topic,i)}return[...e.values()]}export{l as DATEIEN_JE_COMMIT,g as commitAlsLektion,w as gitLogArgumente,x as lektionenJeThema,k as leseCommits};
|
|
@@ -1,41 +1,40 @@
|
|
|
1
|
-
import{createHmac as
|
|
2
|
-
`);const
|
|
3
|
-
`);const
|
|
4
|
-
`)}case"cls_ingest":{const{instance_id:w,source:c,payload:
|
|
5
|
-
`)}if(c==="ci_outcome"){const f=String(e.status??""),l=String(e.prev_status??""),a=String(e.job??"unknown"),t=String(e.context??""),
|
|
6
|
-
`)}if(c==="ide_diagnostic"){const f=String(e.error??""),l=String(e.fix??""),a=String(e.file??""),t=
|
|
7
|
-
`)}return`\u274C Unknown CLS source: "${c}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:w,repo_path:c=".",hooks:
|
|
8
|
-
`];if(
|
|
9
|
-
`)}case"fedbrain_contribute":{const{instance_id:w,lesson_key:c,visibility:
|
|
10
|
-
`)}case"fedbrain_search":{const{instance_id:w,query:c,context_hints:
|
|
11
|
-
`);const a=r.map(
|
|
12
|
-
`];for(const
|
|
13
|
-
`)}case"fedbrain_confirm":{const{instance_id:w,id:c,topic:
|
|
14
|
-
`);const e=await
|
|
15
|
-
`)}case"fedbrain_status":{const{instance_id:w}=
|
|
16
|
-
`,`### \u{1F4E4} Contributed Lessons: ${
|
|
17
|
-
`)}case"brain_federate":{const{instance_id:w,source:c,domain:
|
|
18
|
-
`);let a=0,t=0,
|
|
19
|
-
`)}case"crystal_view":{const{instance_id:w,show_raw:c=!1}=
|
|
20
|
-
`);const e=R(
|
|
21
|
-
`)}case"compact_recover":{const{instance_id:w,focus:c=""}=
|
|
22
|
-
`];
|
|
23
|
-
`);const e=await
|
|
24
|
-
`)}case"brain_from_git":{const w=Date.now(),{instance_id:c,repo_path:
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
`)
|
|
28
|
-
`),W=N),!I.subject){S++;continue}const{category:B,outcome:H,severity:V}=Ie(I.subject),fe=Ae(I.subject),T=`${B}:${fe}`;C.set(B,(C.get(B)??0)+1),x.set(V,(x.get(V)??0)+1),O.push(T),(!$||B==="fix"&&!$.topic.startsWith("fix:"))&&($={topic:T,subject:I.subject});const oe=I.files.filter(F=>F.length>0).slice(0,12),ne={topic:T,outcome:H,severity:V,what_worked:I.subject.slice(0,200),what_failed:"",context:`git:${I.sha.slice(0,8)} by ${I.author} on ${I.date}`,author:I.author||void 0,file_paths:oe,commands:[`git show ${I.sha.slice(0,8)}`],tags:K(["brain_from_git",B,"git-history"],P.verdacht),visibility:"team",depends_on:[],recall_count:0,ts:j,verified_at:j,confidence:.55,audit_trail:[{ts:j,action:"brain_from_git",sha:I.sha.slice(0,8)}],version:3};await r.get(`cachly:lesson:best:${T}`)||(await r.set(`cachly:lesson:best:${T}`,JSON.stringify(ne),"EX",90*86400),await r.rpush(`cachly:lessons:${T}`,JSON.stringify(ne)),await r.ltrim(`cachly:lessons:${T}`,-100,-1),await r.expire(`cachly:lessons:${T}`,90*86400),await r.sadd(Le,T).catch(()=>{})),await r.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:T,sha:I.sha.slice(0,8),subject:I.subject.slice(0,60)})),await r.ltrim("cachly:lessons:brain_from_git:all",-500,-1),await r.expire("cachly:lessons:brain_from_git:all",90*86400);const ie=b(T);if(await M(r,ie,B,"git-derived"),I.author)try{const F=await ge(r,I.author,B);await J(r,F,"authored",ie,H==="success",H==="partial");for(const he of oe.slice(0,8)){const ae=await _e(r,he);await J(r,F,"touched",ae,!0),await we(r,ae,F)}}catch{}g++}process.stderr.write(` \u2705 brain_from_git complete: ${g}/${v} commits ingested
|
|
1
|
+
import{createHmac as he}from"node:crypto";import{ckgSlug as b,extractProblemConcept as me,ckgUpsertNode as T,ckgUpdateEdge as M,ckgUpsertPersonNode as pe,ckgUpsertFileNode as ge,ckgRecordCollaboration as _e}from"../ckg.js";import{safeJsonParse as R}from"../utils.js";import{buildClsPostCommitHook as we}from"../cls-hook.js";import{alsShellWort as ye,beginntMitBindestrich as $e,gitLesen as ie,instanzIdFuerSkript as be,istCommitHash as ke,pruefeOrdner as Se}from"../git-ohne-shell.js";import{installBrainWatchHook as Ce}from"../brain-watch-hook.js";import{keywordSearch as xe,wortindexEntwerten as ve}from"../search.js";import{buildFirstContactReport as ae,suggestRecallQueries as Oe}from"../first-contact.js";import{commitAlsLektion as Ne,gitLogArgumente as je,leseCommits as Ie}from"../git-lektionen.js";import{VEKTOR_NACHTRAG as Ae}from"../bedeutung.js";import{VERDACHT_TAG as Le,fuerEigenenSpeicher as G,fuerWeitergabe as re,hinweise as W,istMarkiert as Re,markiert as K,weitergabeHinweis as ce,zaehlHinweise as F}from"../schreibtor.js";let De=null,Te=null,Y=0;const Me=10,le=[];function Je(){return Y<Me?(Y++,Promise.resolve()):new Promise(B=>le.push(B))}function Pe(){const B=le.shift();B?B():Y--}const Qe=new Set(["madc_deliberate","cls_ingest","cls_install_hooks","fedbrain_contribute","fedbrain_search","fedbrain_confirm","fedbrain_status","brain_federate","crystal_view","compact_recover","brain_from_git","brain_from_ci","brain_predict_failures","brain_contribute_signal","brain_import_meta","brain_watch"]);async function Xe(B,j,A,z){switch(B){case"madc_deliberate":{const{instance_id:w,topic:c}=j,d=await A(w),e=(await d.lrange(`cachly:lessons:${c}`,0,-1)).map(_=>{try{return JSON.parse(_)}catch{return null}}).filter(Boolean);if(e.length<2)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`Not enough history for deliberation (need \u2265 2 entries, found ${e.length}).`,"","Call `learn_from_attempts` with conflicting outcomes to trigger deliberation."].join(`
|
|
2
|
+
`);const i=[{name:"InfraAgent",domains:["infra","k8s","docker","server","wireguard","helm"]},{name:"AuthAgent",domains:["auth","jwt","keycloak","oauth","oidc","token"]},{name:"DeployAgent",domains:["deploy","ci","pipeline","rsync","release"]},{name:"DatabaseAgent",domains:["db","gorm","migration","postgres","clickhouse","redis"]},{name:"DebugAgent",domains:["debug","panic","race","nil","fix","error"]},{name:"APIAgent",domains:["api","http","grpc","rest","fiber","web"]}],u=c.split(":")[0]??"",r=i.filter(_=>_.domains.some($=>u===$||c.includes($))),f=r.length>0?r:i,l=new Map;for(const _ of f){let $=0;for(const v of _.domains){const O=[],S=d.scanStream({match:`cachly:ckg:node:${v}*`,count:50});await new Promise((k,N)=>{S.on("data",J=>O.push(...J)),S.on("end",k),S.on("error",N)}),$+=O.length}l.set(_.name,$)}const a=e.filter(_=>_.outcome==="success"||_.outcome==="partial"),t=e.filter(_=>_.outcome==="failure");if(t.length===0)return[`\u{1F5F3}\uFE0F **MADC: "${c}"**`,"",`No contradictions found \u2014 all ${a.length} entries have non-failure outcomes.`,"",`Use \`ckg_inspect(concept="${b(c)}")\` to explore the confidence graph.`].join(`
|
|
3
|
+
`);const o=[];for(const _ of f){const $=l.get(_.name)??0;let v,O;$<2?(v="abstain",O="insufficient domain coverage"):a.length>=t.length*2?(v="success",O=`${a.length}/${e.length} entries confirm success`):t.length>=a.length*2?(v="failure",O=`${t.length}/${e.length} entries confirm failure`):(v="abstain",O=`contested (${a.length} success vs ${t.length} failure)`),o.push({agent:_.name,vote:v,coverage:$,reason:O})}const n=o.filter(_=>_.vote==="success").length,h=o.filter(_=>_.vote==="failure").length,m=o.filter(_=>_.vote==="abstain").length;let p,y;n>0&&h===0?(p="unanimous_success",y=`\u2705 **Unanimous: SUCCESS** \u2014 ${n} agent(s) confirm, ${m} abstain`):h>0&&n===0?(p="unanimous_failure",y=`\u274C **Unanimous: FAILURE** \u2014 ${h} agent(s) confirm, ${m} abstain`):(p="contested",y=`\u26A0\uFE0F **CONTESTED** \u2014 ${n} success votes, ${h} failure votes, ${m} abstain`);const g=b(`resolution:${c}`),x={id:g,domain:"resolution",type:"resolution",count:1,ts:new Date().toISOString(),resolution:p,topic:c,votes:{success:n,failure:h,abstain:m}};if(await d.set(`cachly:ckg:node:${g}`,JSON.stringify(x)),p==="contested")await M(d,b(c),"contradicts",g,!1);else{if(((p==="unanimous_success"?"failure":"success")==="failure"?t:a).length>0){const v=await d.smembers(`cachly:ckg:idx:from:${b(c)}`);for(const O of v){const S=await d.get(O);if(S)try{const k=JSON.parse(S);k.edgeType==="fixes"&&k.confidence>.15&&p==="unanimous_failure"&&(k.confidence=.1,k.last_updated=new Date().toISOString(),await d.set(O,JSON.stringify(k)))}catch{}}}await d.del(`cachly:ckg:conflict:${b(c)}`)}const C=[`\u{1F5F3}\uFE0F **MADC Deliberation: "${c}"**`,"",`\u{1F4CA} Evidence: ${a.length} success/partial vs ${t.length} failure entries (${e.length} total)`,"",`**Voting agents (${f.length}):**`,...o.map(_=>{const $=_.vote==="success"?"\u2705":_.vote==="failure"?"\u274C":"\u2B1C",v="\u2593".repeat(Math.min(_.coverage,5))+"\u2591".repeat(Math.max(0,5-_.coverage));return` ${$} **${_.agent}** [${v}] ${_.coverage} CKG edges \u2014 ${_.reason}`}),"",y,""];return p==="unanimous_success"?C.push(`\u{1F527} Failure entries superseded \u2014 store confirmed lesson: \`learn_from_attempts(topic="${c}", outcome="success", ...)\``):p==="unanimous_failure"?C.push(`\u{1F6AB} Success claims unconfirmed \u2014 re-verify: \`recall_best_solution(topic="${c}")\``):C.push(`\u26A0\uFE0F Contested \u2014 run \`causal_trace\` before acting. Explore: \`ckg_inspect(concept="${b(c)}")\``),C.push("",`\u{1F4DD} Resolution node: \`cachly:ckg:node:${g}\``),C.join(`
|
|
4
|
+
`)}case"cls_ingest":{const{instance_id:w,source:c,payload:d}=j,s=G(d),e=s.felder,i=await A(w),u=new Date().toISOString(),r="cachly:cls:events";if(c==="git_commit"){const f=String(e.message??""),l=String(e.sha??""),a=Array.isArray(e.files)?e.files:[],t=/^fix/i.test(f)?"fix":/^feat/i.test(f)?"feat":/^refactor/i.test(f)?"refactor":/^test/i.test(f)?"test":"commit",o=`${t}:${b(f.slice(0,60))}`,n=b(o);await T(i,n,t,"commit");for(const p of a.slice(0,10)){const y=p.includes("auth")?"auth":p.includes("api")?"api":p.includes("infra")?"infra":p.includes("web")?"web":"code",g=b(`file:${y}`);await T(i,g,"file",y),await M(i,n,"co-occurs",g,!0)}const h={topic:o,outcome:"success",what_worked:f,what_failed:"",context:`CLS/git: sha=${l}`,severity:"minor",file_paths:a.slice(0,10),commands:l?[`git show ${l}`]:[],tags:K(["cls","git"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.6,audit_trail:[{ts:u,action:"cls_git_commit"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(h)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(h)),await i.rpush(r,JSON.stringify({source:c,payload:{message:f,sha:l},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: git_commit**","",`Commit \`${l.slice(0,8)||"?"}\`: ${f.slice(0,80)}`,`Concept: \`${n}\` (${t}) \xB7 Files: ${a.length}`,"",`\u{1F578}\uFE0F CKG: \`${n}\` + ${a.length} file edges \xB7 Lesson: \`${o}\``,`\u{1F4A1} Inspect: \`ckg_inspect(concept="${t}")\``,...W(s)].join(`
|
|
5
|
+
`)}if(c==="ci_outcome"){const f=String(e.status??""),l=String(e.prev_status??""),a=String(e.job??"unknown"),t=String(e.context??""),o=["failure","red","error"].includes(l)&&["success","green","passed"].includes(f),n=["success","green","passed"].includes(l)&&["failure","red","error"].includes(f),h=`ci:${b(a)}`,m=b(h);if(await T(i,m,"ci","job"),o){const y=b(`problem:${b(a)}`);await T(i,y,"problem","ci-failure"),await M(i,m,"fixes",y,!0);const g={topic:h,outcome:"success",what_worked:`CI job "${a}" went ${l} \u2192 ${f}`,what_failed:`Job "${a}" was failing`,context:`CLS/ci: ${t}`,severity:"major",file_paths:[],commands:[],tags:K(["cls","ci"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.75,audit_trail:[{ts:u,action:"cls_ci_fixed"}],version:3};await i.rpush(`cachly:lessons:${h}`,JSON.stringify(g)),await i.set(`cachly:lesson:best:${h}`,JSON.stringify(g))}else if(n){const y=b(`cause:${b(a)}`);await T(i,y,"cause","ci-break"),await M(i,m,"causes",y,!1)}return await i.rpush(r,JSON.stringify({source:c,payload:{status:f,prev_status:l,job:a},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ci_outcome**","",`${o?"\u2705 Fixed":n?"\u{1F534} Broken":"\u{1F4CA} Recorded"}: \`${a}\` \u2014 ${l||"?"} \u2192 ${f}`,o?"\u{1F527} CKG `fixes` edge added (75% confidence)":n?"\u26A1 CKG `causes` edge added":"\u{1F4CA} State recorded",`\u{1F4A1} Lesson: \`${h}\` | Predict: \`brain_predict(context="${a}")\``,...W(o?s:{geschwaerzt:s.geschwaerzt,verdacht:[]})].join(`
|
|
6
|
+
`)}if(c==="ide_diagnostic"){const f=String(e.error??""),l=String(e.fix??""),a=String(e.file??""),t=me(f)??"unknown-error",o=`debug:${b(t)}`,n=b(o),h=b(`problem:${t}`);await T(i,n,"debug","diagnostic"),await T(i,h,"problem","compiler-error"),await M(i,n,"fixes",h,!0);const m={topic:o,outcome:"success",what_worked:l,what_failed:f,context:`CLS/ide: ${a}`,severity:"minor",file_paths:a?[a]:[],commands:[],tags:K(["cls","ide-diagnostic"],s.verdacht),depends_on:[],recall_count:0,ts:u,verified_at:u,confidence:.65,audit_trail:[{ts:u,action:"cls_ide_diagnostic"}],version:3};return await i.rpush(`cachly:lessons:${o}`,JSON.stringify(m)),await i.get(`cachly:lesson:best:${o}`)||await i.set(`cachly:lesson:best:${o}`,JSON.stringify(m)),await i.rpush(r,JSON.stringify({source:c,payload:{error:f.slice(0,60),fix:l.slice(0,60),file:a},ts:u})),await i.ltrim(r,-200,-1),["\u{1F4E8} **CLS Ingested: ide_diagnostic**","",`Error: \`${f.slice(0,80)}\``,`Fix: ${l.slice(0,100)}`,a?`File: \`${a}\``:"","",`\u{1F578}\uFE0F CKG: \`${n}\` \u2192 fixes \u2192 \`${h}\` | Lesson: \`${o}\``,...W(s)].filter(y=>y!=="").join(`
|
|
7
|
+
`)}return`\u274C Unknown CLS source: "${c}". Valid: git_commit, ci_outcome, ide_diagnostic`}case"cls_install_hooks":{const{instance_id:w,repo_path:c=".",hooks:d=["git","ci"]}=j,s=Array.isArray(d)?d:["git","ci"],e=[`\u{1F50C} **CLS Hook Installation Guide**
|
|
8
|
+
`];if(be(w),s.includes("git")){const i=we(w),u=ye(`${c}/.git/hooks/post-commit`);e.push("### Git post-commit hook"),e.push("**Quick install (run once per repo):**"),e.push("```sh"),e.push(`touch ${u}`),e.push(`grep -q 'cachly CLS' ${u} || cat >> ${u} << 'HOOK'`),e.push(i),e.push("HOOK"),e.push(`chmod +x ${u}`),e.push("```"),e.push("After install: every `git commit` automatically updates your brain's CKG."),e.push("")}return s.includes("ci")&&(e.push("### GitHub Actions CI outcome hook"),e.push("**Add at the end of each job** (after build/test steps):"),e.push("```yaml"),e.push("- name: cachly CLS \u2014 record CI outcome"),e.push(" if: always()"),e.push(" run: |"),e.push(' node -e "'),e.push(" const r=require('https');"),e.push(` const d=JSON.stringify({instance_id:'${w}',source:'ci_outcome',payload:{`),e.push(" status:'${{ job.status }}',prev_status:'unknown',job:'${{ github.job }}',"),e.push(" context:'github-actions run ${{ github.run_number }}'}});"),e.push(" r.request({hostname:'api.cachly.dev',path:'/api/v1/cls/ingest',method:'POST',"),e.push(" headers:{'Content-Type':'application/json','Authorization':'Bearer $CACHLY_JWT',"),e.push(" 'Content-Length':d.length}},()=>{}).end(d);"),e.push(' " 2>/dev/null || true'),e.push(" env:"),e.push(" CACHLY_JWT: ${{ secrets.CACHLY_JWT }}"),e.push("```"),e.push("")),e.push('\u{1F4A1} Once installed: `brain_search(query="cls")` to verify events are arriving.'),e.push('\u{1F4CA} Monitor CKG growth: `ckg_inspect(concept="ci")` or `ckg_inspect(concept="fix")`'),e.join(`
|
|
9
|
+
`)}case"fedbrain_contribute":{const{instance_id:w,lesson_key:c,visibility:d="public"}=j,s=await A(w),e=await s.get(`cachly:lesson:best:${c}`);if(!e)return`\u274C Lesson \`${c}\` not found. Store it first with \`learn_from_attempts\`.`;const i=R(e,null);if(!i)return`\u274C Lesson \`${c}\` data is corrupted. Re-store with \`learn_from_attempts\`.`;const u=re({topic:i.topic,what_worked:i.what_worked,what_failed:i.what_failed??"",tags:i.tags??[]},"die Commons");if(!u.ok)return u.meldung;if(Re(i))return`\u26D4 Tuersteher: Die Lektion \`${c}\` ist beim Speichern als verdaechtig markiert worden \u2014 NICHT an die Commons weitergegeben. Nichts wurde gesendet. Inhalt pruefen, dann mit \`learn_from_attempts\` ohne die Anweisung neu speichern.`;const r={...i,...u.felder},f=[r.topic.split(":")[0],...r.tags??[]].filter(Boolean),l=[...new Set(f)].sort().join(","),a=`${r.topic}:${r.outcome}:${r.what_worked}`,t=he("sha256",`cachly-fedbrain:${w}`).update(a).digest("hex").slice(0,16),o={cert_id:t,lesson_key:c,visibility:d,domain_fingerprint:l,contributed_at:new Date().toISOString(),confirm_count:0,trust_score:r.outcome==="success"?.85:.5};await s.set(`cachly:fedbrain:cert:${t}`,JSON.stringify(o)),await s.sadd("cachly:fedbrain:contributed",t);let n;try{await z("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify({topic:r.topic,outcome:r.outcome,what_worked:r.what_worked,what_failed:r.what_failed??"",severity:r.severity??"major",cert_id:t,domain_fingerprint:l,visibility:d})}),n="\u2705 Contributed to global commons"}catch{n="\u{1F4E6} Stored locally (commons API unavailable \u2014 will sync when online)"}return[`\u{1F310} **FedBrain Contribute: "${c}"**`,"",`\u{1F4DC} Certificate: \`${t}\``,`\u{1F3F7}\uFE0F Domain fingerprint: ${f.slice(0,6).map(h=>`\`${h}\``).join(", ")}`,`\u{1F512} Visibility: ${d}`,"",n,...u.geschwaerzt.length?[ce(u.geschwaerzt)]:[],"","\u{1F4A1} At 10 independent confirms \u2192 \u{1F3C6} Gold Standard",`\u{1F50D} Search: \`fedbrain_search(query="${r.topic.split(":").slice(-1)[0]}")\``].join(`
|
|
10
|
+
`)}case"fedbrain_search":{const{instance_id:w,query:c,context_hints:d=[],limit:s=10}=j,e=await A(w),i=await e.smembers("cachly:fedbrain:contributed"),u=new Map;for(const o of i.slice(0,30)){const n=await e.get(`cachly:fedbrain:cert:${o}`);if(n)try{const h=JSON.parse(n);for(const m of(h.domain_fingerprint??"").split(",").filter(Boolean))u.set(m,(u.get(m)??0)+1)}catch{}}for(const o of Array.isArray(d)?d:[])u.set(o.toLowerCase(),(u.get(o.toLowerCase())??0)+2);let r=[],f=!1;try{const o=new URLSearchParams({q:c,limit:String(Math.min(s*2,50))});r=(await z(`/api/v1/syndication/search?${o}`)).results??[]}catch{f=!0;const o=[],n=e.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{n.on("data",p=>o.push(...p)),n.on("end",h),n.on("error",m)});for(const h of o.slice(0,60)){const m=await e.get(h);if(m)try{const p=JSON.parse(m),y=`${p.topic} ${p.what_worked??""} ${p.what_failed??""}`.toLowerCase();c.toLowerCase().split(/\s+/).some(g=>g.length>2&&y.includes(g))&&r.push({id:h.split(":").pop()??h,topic:p.topic,category:p.topic.split(":")[0],outcome:p.outcome,what_worked:p.what_worked??"",severity:p.severity??"major",confirm_count:0,created_at:p.ts??new Date().toISOString()})}catch{}}}const l=f?" \u2014 \u26A0\uFE0F Commons unreachable, local fallback (this machine only, not confirmed by the network)":"";if(r.length===0)return[`\u{1F310} **FedBrain Search: "${c}"**${l}`,"",'No results. Contribute: `fedbrain_contribute(lesson_key="fix:...")`'].join(`
|
|
11
|
+
`);const a=r.map(o=>{const n=(o.domain_fingerprint??o.category??"").split(",").filter(Boolean),h=n.reduce((g,x)=>g+(u.get(x)??0),0),m=u.size>0?h/Math.max(1,u.size+n.length):0,p=Math.min(1,o.confirm_count/10),y=m*.4+p*.4+(o.outcome==="success"?.2:0);return{...o,weightedScore:y,isGoldStandard:!f&&o.confirm_count>=10}}).sort((o,n)=>n.weightedScore-o.weightedScore).slice(0,s),t=[`\u{1F310} **FedBrain Search: "${c}"** \u2014 ${a.length} result${a.length!==1?"s":""} (context-weighted)${l}
|
|
12
|
+
`];for(const o of a){const n=o.outcome==="success"?"\u2705":o.outcome==="failure"?"\u274C":"\u26A0\uFE0F",h=o.isGoldStandard?" \u{1F3C6} _Gold Standard_":!f&&o.confirm_count>=3?` \u2713${o.confirm_count}`:"",m=Math.round(o.weightedScore*100);t.push(`${n}${h} **\`${o.topic}\`** [ctx: ${m}%]`),o.what_worked&&t.push(` \u2705 ${o.what_worked.slice(0,150)}`),o.what_failed&&t.push(` \u274C ${o.what_failed.slice(0,80)}`),t.push(` _${o.confirm_count} confirm${o.confirm_count!==1?"s":""} | id: \`${o.id}\`_`,"")}if(u.size>0){const o=[...u.entries()].sort((n,h)=>h[1]-n[1]).slice(0,5).map(([n,h])=>`\`${n}\`(${h})`).join(", ");t.push(`\u{1F3AF} Your context: ${o}`)}return t.push('\u{1F4A1} Confirm a result: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`'),t.join(`
|
|
13
|
+
`)}case"fedbrain_confirm":{const{instance_id:w,id:c,topic:d,outcome:s}=j;if(!c)return["\u274C **FedBrain Confirm** needs the lesson `id` from `fedbrain_search` results.",'Run `fedbrain_search(query="...")`, copy the id shown next to a result,','then: `fedbrain_confirm(id="<id>", topic="<topic>", outcome="worked")`.'].join(`
|
|
14
|
+
`);const e=await A(w),i=new Date().toISOString(),u=JSON.stringify({id:c,topic:d,outcome:s,ts:i});await e.rpush("cachly:fedbrain:confirmations",u),await e.ltrim("cachly:fedbrain:confirmations",-200,-1);const r=s==="worked",f=s==="partially_worked";d&&await M(e,b(d),"fixes",b(`syndicated:${d}`),r,f);let l;try{await z(`/api/v1/syndication/${encodeURIComponent(c)}/confirm`,{method:"POST"}),l="\u2705 Confirmation propagated to global commons"}catch{await e.rpush("cachly:fedbrain:pending_confirms",u),await e.ltrim("cachly:fedbrain:pending_confirms",-50,-1),l="\u{1F4E6} Queued locally (API unavailable \u2014 will propagate on next online session)"}return[`${r?"\u2705":f?"\u26A0\uFE0F":"\u274C"} **FedBrain Confirm: "${d??c}"** \u2192 ${s}`,"",l,"",d?`\u{1F578}\uFE0F CKG confidence ${r||f?"boosted":"reduced"} for \`${b(d)}\``:"\u{1F578}\uFE0F Local CKG unchanged (pass `topic` to also update your own confidence graph)","\u{1F4A1} Your confirmation helps other brains worldwide.",'\u{1F4CA} Status: `fedbrain_status(instance_id="...")`'].join(`
|
|
15
|
+
`)}case"fedbrain_status":{const{instance_id:w}=j,c=await A(w),d=await c.smembers("cachly:fedbrain:contributed"),s=await c.lrange("cachly:fedbrain:confirmations",-10,-1),e=await c.llen("cachly:fedbrain:pending_confirms"),i=s.map(f=>{try{return JSON.parse(f)}catch{return null}}).filter(Boolean),u=[];for(const f of d.slice(0,15)){const l=await c.get(`cachly:fedbrain:cert:${f}`);if(l)try{const a=JSON.parse(l);u.push({cert_id:a.cert_id,lesson_key:a.lesson_key,confirm_count:a.confirm_count??0,trust_score:a.trust_score??.5,isGold:(a.confirm_count??0)>=10})}catch{}}const r=[`\u{1F310} **FedBrain Status**
|
|
16
|
+
`,`### \u{1F4E4} Contributed Lessons: ${d.length}`];if(u.length>0)for(const f of u){const l=f.isGold?" \u{1F3C6} Gold Standard":"",a="\u2588".repeat(Math.min(10,f.confirm_count))+"\u2591".repeat(Math.max(0,10-f.confirm_count));r.push(` \`${f.lesson_key}\` [${a}] \xD7${f.confirm_count}${l}`)}else r.push(' _None yet. Contribute with `fedbrain_contribute(lesson_key="fix:...")`_');if(r.push("",`### \u{1F4E5} Recent Confirmations: ${i.length}`),i.length>0)for(const f of i.slice(-5)){const l=f.outcome==="worked"?"\u2705":f.outcome==="partially_worked"?"\u26A0\uFE0F":"\u274C";r.push(` ${l} \`${f.topic}\` \u2014 ${f.outcome} (${new Date(f.ts).toLocaleDateString("de-DE")})`)}else r.push(" _None yet. Confirm syndicated lessons with `fedbrain_confirm`_");return e>0&&r.push("",`\u26A0\uFE0F ${e} confirmation${e!==1?"s":""} pending propagation`),r.push("","---",'**Contribute:** `fedbrain_contribute(lesson_key="fix:...")`','**Search:** `fedbrain_search(query="...")`','**Confirm:** `fedbrain_confirm(id="...", topic="...", outcome="worked")`'),r.join(`
|
|
17
|
+
`)}case"brain_federate":{const{instance_id:w,source:c,domain:d,min_confidence:s=.6,dry_run:e=!1}=j;if(w===c)return"\u274C Source and destination cannot be the same brain.";const i=await A(w),u=await A(c),r=d==="*"?"cachly:ckg:node:*":`cachly:ckg:node:${d}*`,f=[],l=u.scanStream({match:r,count:100});if(await new Promise((x,C)=>{l.on("data",_=>f.push(..._)),l.on("end",x),l.on("error",C)}),f.length===0)return[`\u{1F9E0} **brain_federate: "${d}"**`,"",`No CKG nodes found in source brain for domain \`${d}\`.`,"The source brain may not have knowledge in this area yet.",`Try: \`fedbrain_search(query="${d}")\` to find global commons knowledge instead.`].join(`
|
|
18
|
+
`);let a=0,t=0,o=0,n=0,h=0,m=0;const p=[];for(const x of f){const C=await u.get(x);if(!C)continue;let _;try{_=JSON.parse(C)}catch{continue}e||await i.set(x,C),a++;const $=await u.smembers(`cachly:ckg:idx:from:${_.id}`);for(const S of $){const k=await u.get(S);if(!k)continue;let N;try{N=JSON.parse(k)}catch{continue}if(N.confidence<s){n++;continue}e||(await i.set(S,k),await i.sadd(`cachly:ckg:idx:from:${N.from}`,S),await i.sadd(`cachly:ckg:idx:to:${N.to}`,S)),t++}const v=`cachly:lesson:best:${_.id}`,O=await u.get(v);if(O){const S=R(O,null);if(!S||typeof S!="object")continue;const k=G(S);k.geschwaerzt.length&&h++,k.verdacht.length&&m++;const N=k.verdacht.length?{...k.felder,tags:K(k.felder.tags,k.verdacht)}:k.felder;if(e||await i.set(v,JSON.stringify(N)),o++,p.length<8){const J=N.outcome==="success"?"\u2705":N.outcome==="failure"?"\u274C":"\u26A0\uFE0F";p.push(` ${J} \`${N.topic}\` \u2014 ${(N.what_worked??"").slice(0,80)}`)}}}if(!e){const x=JSON.stringify({source:c,domain:d,transferred_at:new Date().toISOString(),nodes:a,edges:t,lessons:o});await i.rpush("cachly:fedbrain:federations",x),await i.ltrim("cachly:fedbrain:federations",-50,-1)}const g=[`\u{1F9E0} **brain_federate: "${d}"**${e?" (DRY RUN \u2014 no writes)":""}`,"",`\u{1F4E4} Source: \`${c}\``,`\u{1F4E5} Destination: \`${w}\``,`\u{1F50D} Domain filter: \`${d}\` | min_confidence: ${s}`,"","### Transfer Summary",` \u{1F578}\uFE0F CKG nodes: ${a}`,` \u{1F517} CKG edges: ${t} (${n} skipped, confidence < ${s})`,` \u{1F4DA} Lessons: ${o}`,...F(h,m,`${o} kopierten Lektionen`),""];return p.length>0&&(g.push("### Sample lessons transferred:",...p),o>p.length&&g.push(` _... and ${o-p.length} more_`),g.push("")),e?g.push("\u{1F4A1} Run without `dry_run: true` to apply the transfer."):(g.push(`\u2705 Transfer complete. Your brain now has the \`${d}\` knowledge from \`${c}\`.`),g.push(`\u{1F50D} Explore: \`ckg_inspect(concept="${d}")\` | \`recall_best_solution(topic="${d}:...")\``)),g.join(`
|
|
19
|
+
`)}case"crystal_view":{const{instance_id:w,show_raw:c=!1}=j,d=await A(w),s=await d.get("cachly:crystal:latest");if(!s)return["\u{1F48E} **Memory Crystal: not yet created**","","No crystal found. Create one with `memory_crystalize()` to compress your accumulated wisdom.","","\u{1F4A1} Tip: run `memory_crystalize` monthly for best results."].join(`
|
|
20
|
+
`);const e=R(s,null);if(!e)return"\u274C Memory Crystal data is corrupted. Re-create with `memory_crystalize()`.";const i=Math.floor((Date.now()-new Date(e.ts).getTime())/864e5),u=i<=7?"\u{1F7E2}":i<=30?"\u{1F7E1}":"\u{1F534}",r=[`\u{1F48E} **Memory Crystal: ${e.label}**`,"",`\u{1F4C5} Created: ${new Date(e.ts).toLocaleDateString("de-DE")} (${i}d ago ${u})`,`\u{1F4CA} Compressed from: ${e.created_from}`,`\u{1F5C2}\uFE0F Categories: ${e.categories.slice(0,10).map(l=>`\`${l}\``).join(", ")}${e.categories.length>10?` +${e.categories.length-10} more`:""}`,"",`**\u{1F511} Top patterns (${e.top_patterns.length}):**`];for(const l of e.top_patterns)r.push(` \u2022 **${l.category}** (${l.count}\xD7): ${l.insight.slice(0,110)}`);i>30&&r.push("",`\u26A0\uFE0F Crystal is ${i}d old \u2014 run \`memory_crystalize()\` to refresh it.`),c&&r.push("","```json",JSON.stringify(e,null,2),"```");const f=await d.get("cachly:crystal:team:latest").catch(()=>null);if(f){const l=R(f,null);if(l&&l.patterns?.length){const a=Math.floor((Date.now()-new Date(l.ts).getTime())/864e5);r.push("","---",`\u{1F4A0} **Team Crystal: ${l.label}** _(${a}d ago \xB7 ${l.contributors} contributors)_`,"_Fixes multiple teammates independently converged on \u2014 the team-wide layer:_");for(const t of l.patterns.slice(0,5))r.push(` \u2022 \u{1F9E9} **${t.concept}** \u2014 ${t.author_count} people (${t.authors.map(o=>`@${o}`).join(", ")}): ${t.convergent_fix.slice(0,90)}`)}}return r.push("",'\u{1F4A1} Refresh: `memory_crystalize()` \xB7 `team_crystallize()` | Recover: `compact_recover(instance_id="...")`'),r.join(`
|
|
21
|
+
`)}case"compact_recover":{const{instance_id:w,focus:c=""}=j,d=await A(w),s=[`\u{1F501} **Compact Recovery Briefing**
|
|
22
|
+
`];s.push(`> *Call this first after any context limit hit. Reconstructs where you left off.*
|
|
23
|
+
`);const e=await d.get("cachly:crystal:latest");if(e){const t=R(e,null);if(t){s.push(`### \u{1F48E} Memory Crystal: ${t.label}`),s.push(`Compressed from ${t.session_count} sessions, ${t.lesson_count} lessons.`);const o=c?t.top_patterns.filter(n=>n.category.toLowerCase().includes(c.toLowerCase())||n.insight.toLowerCase().includes(c.toLowerCase())).slice(0,4):t.top_patterns.slice(0,4);for(const n of o)s.push(` \u2022 **${n.category}**: ${n.insight.slice(0,100)}`);s.push("")}}const i=await d.get("cachly:session:last");if(i){const t=R(i,null);t&&(s.push("### \u{1F550} Last Session"),t.focus&&s.push(`Focus: _${t.focus}_`),t.summary&&s.push(`Summary: ${t.summary.slice(0,300)}`),s.push(""))}const u=await d.get("cachly:session:handoff");if(u){const t=R(u,null);if(t){if(s.push("### \u{1F4CB} Handoff (from last window)"),t.context_summary&&s.push(`Context: ${t.context_summary.slice(0,200)}`),t.remaining_tasks?.length){s.push("Remaining tasks:");for(const o of t.remaining_tasks.slice(0,5))s.push(` \u2022 ${o}`)}t.instructions&&s.push(`\u26A0\uFE0F Instructions: ${t.instructions.slice(0,200)}`),t.blocked_on&&s.push(`\u{1F6A7} Blocked on: ${t.blocked_on}`),s.push("")}}const r=await d.get("cachly:ctx:wip-registry");if(r){const t=R(r,null);t?.content&&(s.push("### \u{1F527} WIP Registry"),s.push(t.content.slice(0,400)),s.push(""))}const f=[],l=d.scanStream({match:"cachly:roadmap:*",count:100});await new Promise((t,o)=>{l.on("data",n=>f.push(...n)),l.on("end",t),l.on("error",o)});const a=[];for(const t of f.slice(0,30)){const o=await d.get(t);if(o)try{const n=JSON.parse(o);(n.status==="in_progress"||n.status==="blocked")&&a.push({title:n.title??t,status:n.status,priority:n.priority})}catch{}}if(a.length>0){s.push("### \u{1F6A7} Open Items");for(const t of a.slice(0,5))s.push(` \u2022 [${t.status}] ${t.title}`);s.push("")}if(c){const t=[],o=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((h,m)=>{o.on("data",p=>t.push(...p)),o.on("end",h),o.on("error",m)});const n=[];for(const h of t){const m=await d.get(h);if(m)try{const p=JSON.parse(m);p.topic.toLowerCase().includes(c.toLowerCase())&&p.what_worked&&n.push({topic:p.topic,what_worked:p.what_worked})}catch{}}if(n.length>0){s.push(`### \u{1F4A1} Relevant Lessons for "${c}"`);for(const h of n.slice(0,4))s.push(` \u2022 **${h.topic}**: ${h.what_worked.slice(0,100)}`);s.push("")}}return s.length<=3&&s.push("_No brain data found. Start accumulating knowledge with `learn_from_attempts` and `session_start`._"),s.push("---","\u{1F9E0} Brain is ready. Continue your work \u2014 full context restored."),s.join(`
|
|
24
|
+
`)}case"brain_from_git":{const w=Date.now(),{instance_id:c,repo_path:d=".",limit:s=100,branch:e="HEAD",since:i="",incremental:u=!0}=j,r=await A(c),{resolve:f}=await import("node:path"),l=f(d),a=Math.max(1,Math.floor(Math.min(Number(s)||100,500)));if(typeof e!="string"||$e(e))return'\u274C Ungueltiger `branch`: darf nicht mit "-" beginnen.';await Je();try{try{if(!Se(l))throw new Error("kein Ordner");ie(l,["rev-parse","--git-dir"],{stderr:"pipe"})}catch{return`\u274C Not a git repository: \`${l}\`. Pass \`repo_path\` pointing to a git checkout.`}const t=`cachly:brain_from_git:last_sha:${Buffer.from(l).toString("base64").slice(0,32)}`;let o="",n=!1;u!==!1&&!i&&(o=await r.get(t)??"",ke(o)||(o=""),n=!!o);const m=(n?`${o}..HEAD`:"")||e||"HEAD",p=je(m,a,i);let y="";try{y=ie(l,p,{stderr:"pipe",timeoutMs:6e4})}catch(I){return`\u274C git log failed: ${I.message}. Check \`repo_path\` and \`branch\`.`}const g=Ie(y);if(g.length===0)return n?`\u2705 brain_from_git: Brain is up to date \u2014 no new commits since last run (last SHA: \`${o.slice(0,8)}\`).`:ae({repoDir:l,revRange:m,processed:0,ingested:0,skipped:0,durationMs:Date.now()-w,isIncremental:!1,instanceId:c,categories:[],suggestedQueries:[],emptyReason:`No commits found in \`${l}\` on branch \`${e}\`${i?` since ${i}`:""}.`});const x=new Date().toISOString();let C=0,_=0;const $=new Map,v=new Map,O=[];let S=null;const k=g.length,N=Math.max(1,Math.floor(k/10));let J=0;process.stderr.write(`
|
|
25
|
+
\u{1F9E0} brain_from_git: processing ${k} commits from ${l}...
|
|
26
|
+
`);let H=0,Q=0;for(let I=0;I<g.length;I++){const{commit:L,geschwaerzt:de,verdacht:ue,lektion:P}=Ne(g[I]);if(de&&H++,ue&&Q++,I-J>=N&&(process.stderr.write(` \u23F3 Processing ${I}/${k} commits (${C} lessons so far)...
|
|
27
|
+
`),J=I),!P){_++;continue}const{topic:D,category:E,outcome:q,severity:U}=P;$.set(E,($.get(E)??0)+1),v.set(U,(v.get(U)??0)+1),O.push(D),(!S||E==="fix"&&!S.topic.startsWith("fix:"))&&(S={topic:D,subject:L.subject});const te=P.file_paths,oe={topic:D,outcome:q,severity:U,what_worked:P.what_worked,what_failed:P.what_failed,context:P.context,author:P.author,file_paths:te,commands:P.commands,tags:P.tags,visibility:"team",depends_on:[],recall_count:0,ts:x,verified_at:x,confidence:.55,audit_trail:[{ts:x,action:"brain_from_git",sha:L.sha.slice(0,8)}],version:3};await r.get(`cachly:lesson:best:${D}`)||(await r.set(`cachly:lesson:best:${D}`,JSON.stringify(oe),"EX",90*86400),await r.rpush(`cachly:lessons:${D}`,JSON.stringify(oe)),await r.ltrim(`cachly:lessons:${D}`,-100,-1),await r.expire(`cachly:lessons:${D}`,90*86400),await r.sadd(Ae,D).catch(()=>{})),await r.rpush("cachly:lessons:brain_from_git:all",JSON.stringify({topic:D,sha:L.sha.slice(0,8),subject:L.subject.slice(0,60)})),await r.ltrim("cachly:lessons:brain_from_git:all",-500,-1),await r.expire("cachly:lessons:brain_from_git:all",90*86400);const se=b(D);if(await T(r,se,E,"git-derived"),L.author)try{const V=await pe(r,L.author,E);await M(r,V,"authored",se,q==="success",q==="partial");for(const fe of te.slice(0,8)){const ne=await ge(r,fe);await M(r,V,"touched",ne,!0),await _e(r,ne,V)}}catch{}C++}process.stderr.write(` \u2705 brain_from_git complete: ${C}/${k} commits ingested
|
|
29
28
|
|
|
30
|
-
`),
|
|
31
|
-
`):
|
|
32
|
-
`)}case"brain_predict_failures":{const{instance_id:w,context:c,top_k:
|
|
33
|
-
`);const l=new Set,a=
|
|
34
|
-
`];t.push(`> Pre-deploy failure analysis based on ${
|
|
35
|
-
`);for(let
|
|
36
|
-
`)}case"brain_contribute_signal":{const{instance_id:w,topic_category:c,outcome:
|
|
37
|
-
`)}case"brain_import_meta":{const{instance_id:w,category:c,limit:
|
|
38
|
-
`);let
|
|
39
|
-
`)}case"brain_watch":{const{instance_id:w="",project_dir:c=".",api_key:
|
|
40
|
-
`):[`\u{1F9E0} **brain_watch ${{written:"\u2705 Hook installed (new)",upgraded:"\u{1F504} Hook upgraded to latest version",appended:"\u{1F4CE} Hook appended to existing post-commit script",unchanged:"\u2713 Hook already up to date \u2014 nothing changed"}[
|
|
41
|
-
`)}default:return null}}export{
|
|
29
|
+
`),C>0&&ve(),g.length>0&&g[0]?.sha&&await r.set(t,g[0].sha,"EX",2160*3600),De={fixes:$.get("fix")??0,features:$.get("feat")??0,refactors:$.get("refactor")??0,total:C};let X=null;if(S&&C>0)try{const I=await xe(r,["cachly:lesson:best:*"],S.subject,1);if(I.length>0){const L=R(I[0].content,{});X={query:S.subject.slice(0,80),topic:L.topic??I[0].key.replace("cachly:lesson:best:",""),snippet:(L.what_worked??"").slice(0,120)||S.subject.slice(0,120)}}}catch{}const Z=ae({repoDir:l,revRange:m,processed:g.length,ingested:C,skipped:_,durationMs:Date.now()-w,isIncremental:n,lastSha:o,instanceId:c,categories:[...$.entries()].sort((I,L)=>L[1]-I[1]),severities:[...v.entries()].sort((I,L)=>L[1]-I[1]),proof:X,suggestedQueries:Oe(O,c)}),ee=F(H,Q,`${g.length} Commits`);return ee.length?[Z,"",...ee].join(`
|
|
30
|
+
`):Z}finally{Pe()}}case"brain_from_ci":{const{instance_id:w,outcomes:c}=j,d=await A(w),s=Date.now();let e=0,i=0,u=0,r=0,f=0;const l=c.length;for(const a of c){const t=G({job:String(a.job??"unknown"),context:String(a.context??"")});t.geschwaerzt.length&&r++;const o=String(a.status??""),n=String(a.prev_status??""),h=t.felder.job,m=t.felder.context,p=["failure","red","error"].includes(n)&&["success","green","passed"].includes(o),y=["success","green","passed"].includes(n)&&["failure","red","error"].includes(o),g=`ci:${b(h)}`,x=b(g);if(await T(d,x,"ci","job"),p){const _=b(`problem:${b(h)}`);await T(d,_,"problem","ci-failure"),await M(d,x,"fixes",_,!0);const $={topic:g,outcome:"success",what_worked:`CI job "${h}" went ${n} \u2192 ${o}`,what_failed:`Job "${h}" was failing`,context:`brain_from_ci: ${m}`,severity:"major",file_paths:[],commands:[],tags:K(["brain_from_ci","ci"],t.verdacht),depends_on:[],recall_count:0,ts:s,verified_at:s,confidence:.65,audit_trail:[{ts:s,action:"brain_from_ci_fixed"}],version:3};await d.rpush(`cachly:lessons:${g}`,JSON.stringify($)),await d.ltrim(`cachly:lessons:${g}`,-100,-1),await d.set(`cachly:lesson:best:${g}`,JSON.stringify($)),t.verdacht.length&&f++,e++}else if(y){const _=b(`cause:${b(h)}`);await T(d,_,"cause","ci-break"),await M(d,x,"causes",_,!1),i++}else u++;const C=`cachly:cls:${w}`;await d.rpush(C,JSON.stringify({source:"ci_outcome",payload:{status:o,prev_status:n,job:h},ts:s})),await d.ltrim(C,-200,-1)}return Te={fixes:e,breaks:i,stable:u,total:l},[`\u{1F4E5} **brain_from_ci**: Ingested ${l} outcomes \u2014 ${e} fixes learned, ${i} breaks noted, ${u} stable`,"",e>0?`\u2705 ${e} fix lesson${e!==1?"s":""} written (confidence 0.65) \u2014 CKG \`fixes\` edges added`:"",i>0?`\u{1F534} ${i} break${i!==1?"s":""} noted \u2014 CKG \`causes\` edges added`:"",u>0?`\u{1F4CA} ${u} stable outcome${u!==1?"s":""} recorded`:"","",'\u{1F4A1} Explore: `brain_search(query="ci")` | `brain_predict(context="<job-name>")`',...F(r,f,`${l} CI-Ergebnissen`)].filter(Boolean).join(`
|
|
31
|
+
`)}case"brain_predict_failures":{const{instance_id:w,context:c,top_k:d=5,format:s="detailed"}=j,e=await A(w),i=c.toLowerCase().replace(/[^a-z0-9\s\-_:.]/g," ").split(/\s+/).filter(n=>n.length>2),u=[];for(const n of i.slice(0,8)){const h=[],m=e.scanStream({match:`cachly:ckg:node:*${n}*`,count:50});await new Promise((p,y)=>{m.on("data",g=>h.push(...g)),m.on("end",p),m.on("error",y)});for(const p of h.slice(0,5)){const y=await e.get(p);if(!y)continue;const g=R(y,null);if(!g)continue;const x=await e.smembers(`cachly:ckg:idx:from:${g.id}`);for(const C of x.slice(0,20)){const _=await e.get(C);if(!_)continue;const $=R(_,null);if(!$||$.edgeType!=="causes"&&$.edgeType!=="degrades_under")continue;const v=await e.smembers(`cachly:ckg:idx:from:${$.to}`);let O;for(const S of v.slice(0,10)){const k=await e.get(S);if(!k)continue;const N=R(k,null);if(N&&N.edgeType==="fixes"){const J=await e.get(`cachly:lesson:best:${N.from}`);if(J){O=R(J,null)?.what_worked?.slice(0,120);break}}}u.push({concept:g.id,failure:$.to.replace(/-/g," "),probability:$.confidence,fix:O,source:"ckg"})}}}const r=[],f=e.scanStream({match:"cachly:lesson:best:*",count:300});await new Promise((n,h)=>{f.on("data",m=>r.push(...m)),f.on("end",n),f.on("error",h)});for(const n of r.slice(0,100)){const h=await e.get(n);if(h)try{const m=JSON.parse(h);if(m.outcome!=="failure"&&m.outcome!=="partial"||!m.what_failed)continue;const p=`${m.topic} ${m.what_failed}`.toLowerCase(),y=i.filter(x=>p.includes(x)).length/Math.max(1,i.length);if(y<.15)continue;const g=m.severity==="critical"?.15:m.severity==="major"?.05:0;u.push({concept:m.topic,failure:m.what_failed.slice(0,80),probability:Math.min(.97,(m.confidence??.5)*y*1.5+g),fix:m.what_worked?.slice(0,120),topic:m.topic,source:"lesson"})}catch{}}if(u.length===0)return[`\u{1F52E} **Failure Prediction: "${c}"**`,"","No known failure patterns found for this context.",'\u{1F4A1} The brain learns from every `learn_from_attempts(outcome="failure")` call.',`\u{1F50D} Try: \`brain_predict(context="${c}")\` for broader predictions.`].join(`
|
|
32
|
+
`);const l=new Set,a=u.filter(n=>{const h=n.failure.slice(0,40);return l.has(h)?!1:(l.add(h),!0)}).sort((n,h)=>h.probability-n.probability).slice(0,Number(d)),t=[`\u{1F52E} **Failure Prediction for: "${c}"**
|
|
33
|
+
`];t.push(`> Pre-deploy failure analysis based on ${u.length} patterns. Ranked by probability.
|
|
34
|
+
`);for(let n=0;n<a.length;n++){const h=a[n],m=Math.round(h.probability*100),p="\u2588".repeat(Math.round(m/10))+"\u2591".repeat(10-Math.round(m/10)),y=m>=70?"\u{1F534}":m>=40?"\u{1F7E1}":"\u{1F7E2}";t.push(`${y} **${n+1}. ${h.failure}**`),t.push(` Probability: ${p} **${m}%** (${h.source==="ckg"?"CKG causal edge":"lesson history"})`),s==="detailed"&&h.fix&&t.push(` \u2705 Pre-loaded fix: _${h.fix}_`),s==="detailed"&&h.topic&&t.push(` \u{1F4DA} Lesson: \`${h.topic}\``),t.push("")}const o=a.filter(n=>n.probability>=.6);return o.length>0?t.push(`\u26A0\uFE0F **${o.length} high-risk failure${o.length>1?"s":""} detected** (\u226560% probability). Review fixes before proceeding.`):t.push("\u2705 No high-risk failures detected. Proceed with caution and monitor closely."),t.push("",'\u{1F4A1} After deploy: `learn_from_attempts(topic="deploy:...", outcome="success|failure")` to improve future predictions.'),t.join(`
|
|
35
|
+
`)}case"brain_contribute_signal":{const{instance_id:w,topic_category:c,outcome:d,confidence:s=.5}=j;if(!c?.trim())throw new Error("topic_category is required");if(!["success","failure","partial"].includes(d))throw new Error("outcome must be success, failure, or partial");const e=re({topic_category:c.trim()},"die Commons");if(!e.ok)return e.meldung;const i=e.felder.topic_category,u=s>=.75?"high":s>=.5?"medium":"low";let r="\u{1F4E6} Signal stored locally (commons API unavailable)";try{await z("/api/v1/federation/signals",{method:"POST",body:JSON.stringify({topic_category:i.toLowerCase(),outcome:d,confidence:s})}),r="\u2705 Signal contributed to the global commons (no raw data shared)"}catch{const f=await A(w),l=`cachly:fed:outbox:${Date.now()}`;await f.set(l,JSON.stringify({topic_category:i,outcome:d,bucket:u,ts:new Date().toISOString()}),"EX",3600*24*7).catch(()=>{})}return[`\u{1F512} **Brain Contribute Signal: \`${i}\`**`,"",`\u{1F4CA} Outcome: **${d}** \xB7 Confidence bucket: **${u}**`,"\u{1F6E1}\uFE0F Privacy: topic category only \u2014 no lesson text, no org identity","",r,...e.geschwaerzt.length?[ce(e.geschwaerzt)]:[],"","\u{1F4A1} When \u2265 k orgs contribute the same pattern, a meta-lesson appears in `brain_import_meta`."].join(`
|
|
36
|
+
`)}case"brain_import_meta":{const{instance_id:w,category:c,limit:d=20}=j;let s=[],e=3;try{const a=new URLSearchParams;c&&a.set("category",c),a.set("limit",String(Math.min(d,200)));const t=await z(`/api/v1/federation/meta?${a.toString()}`);s=t.meta_lessons??[],e=t.k_threshold??3}catch{return"\u274C Could not reach the global commons API. Try again later."}if(s.length===0)return["\u{1F310} **Brain Import Meta-Lessons**","",`No meta-lessons available yet (k-threshold: ${e} signals required).`,"","\u{1F4A1} Contribute signals with `brain_contribute_signal` to help build the commons."].join(`
|
|
37
|
+
`);let i=0;const u=new Set;s=s.map(a=>{const t=G({topic_category:a.topic_category,dominant_outcome:a.dominant_outcome});return t.geschwaerzt.length&&i++,t.verdacht.length&&u.add(t.felder.topic_category),{...a,...t.felder}});const r=await A(w);let f=0;for(const a of s){const t=`cachly:lesson:best:meta:${a.topic_category}`;await r.get(t)||(await r.set(t,JSON.stringify({topic:`meta:${a.topic_category}`,outcome:a.dominant_outcome,what_worked:a.contributor_count!=null?`Meta-pattern from ${a.contributor_count} independent orgs`:`Meta-pattern from ${a.signal_count} signals`,what_failed:"",recall_count:0,ts:a.derived_at,state:"meta",...u.has(a.topic_category)?{tags:[Le]}:{},avg_confidence:a.avg_confidence,signal_count:a.signal_count,audit_trail:[{ts:new Date().toISOString(),action:"imported_meta"}]})),f++)}const l=[`\u{1F310} **Brain Import Meta-Lessons** (k \u2265 ${e})`,"","| Topic Category | Outcome | Confidence | Signals |","|---|---|---|---|"];for(const a of s.slice(0,15)){const t=(a.avg_confidence*100).toFixed(0)+"%";l.push(`| \`${a.topic_category}\` | ${a.dominant_outcome} | ${t} | ${a.signal_count} |`)}return s.length>15&&l.push(`| _\u2026${s.length-15} more_ | | | |`),l.push("",`\u2705 **${f}** new meta-lessons imported into local Brain.`),f<s.length&&l.push(`_(${s.length-f} already present \u2014 not overwritten)_`),l.push(...F(i,u.size,`${s.length} Kategorienamen`)),l.join(`
|
|
38
|
+
`)}case"brain_watch":{const{instance_id:w="",project_dir:c=".",api_key:d}=j,{resolve:s}=await import("node:path"),e=s(c),{result:i,hookPath:u}=await Ce(e,w,d);return i==="skipped-no-git"?["\u26A0\uFE0F **brain_watch: no git repository found**","",`No \`.git\` directory in \`${e}\`.`,"Pass `project_dir` pointing to a git checkout."].join(`
|
|
39
|
+
`):[`\u{1F9E0} **brain_watch ${{written:"\u2705 Hook installed (new)",upgraded:"\u{1F504} Hook upgraded to latest version",appended:"\u{1F4CE} Hook appended to existing post-commit script",unchanged:"\u2713 Hook already up to date \u2014 nothing changed"}[i]??i}**`,"",`Hook path: \`${u}\``,`Instance: \`${w||"(none \u2014 set CACHLY_BRAIN_INSTANCE_ID or pass instance_id)"}\``,"","Every future commit will automatically teach your Brain.","No manual `brain_from_git` needed \u2014 the hook runs silently in the background.","",'\u{1F4A1} Verify: `git commit --allow-empty -m "test brain_watch"` then `smart_recall(query="test")`'].join(`
|
|
40
|
+
`)}default:return null}}export{Qe as FEDBRAIN_TOOL_NAMES,Te as _lastBrainFromCiCounts,De as _lastBrainFromGitCounts,Xe as handleFedbrainTool};
|