@cachly-dev/mcp-server 0.10.188 → 0.10.191
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/README.md +3 -0
- package/dist/src/ambient-cli.js +2 -2
- package/dist/src/ambient-hook.js +2 -2
- package/dist/src/einblendung-kern.js +1 -1
- package/dist/src/einblendung.js +7 -7
- package/dist/src/handlers/advanced.js +11 -11
- package/dist/src/handlers/brain.js +69 -67
- package/dist/src/handlers/fedbrain.js +40 -39
- package/dist/src/handlers/roadmap.js +10 -10
- package/dist/src/handlers/share.js +19 -19
- package/dist/src/handlers/syndicate.js +35 -35
- package/dist/src/handlers/team.js +58 -56
- package/dist/src/lernen.js +6 -0
- package/dist/src/schreibbeleg.js +7 -5
- package/dist/src/schreibtor.js +1 -0
- package/dist/src/tuersteher.js +1 -1
- package/dist/src/verdacht-marke.js +1 -0
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +28 -21
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
import{McpError as
|
|
2
|
-
`)}const
|
|
3
|
-
> \u267B\uFE0F Duplicate detected \u2014 trust score incremented for the existing lesson.`:"";return[`${p==="org"?"\u{1F3E2}":"\u{1F310}"} **Lesson syndicated to the ${p==="org"?"org Knowledge Commons":"global Knowledge Commons"}**${
|
|
4
|
-
`)}case"syndicate_search":{const{q:a="",limit:o=20,category:
|
|
1
|
+
import{McpError as I,ErrorCode as P}from"@modelcontextprotocol/sdk/types.js";import{calculateConfidence as M}from"../confidence.js";import{ckgSlug as B}from"../ckg.js";import{keywordSearch as O}from"../search.js";import{safeJsonParse as S}from"../utils.js";import{sofortAntwortNeuesBrain as K}from"../leeres-brain.js";import{fuerEigenenSpeicher as R,fuerWeitergabe as L,markiert as D,weitergabeHinweis as E,zaehlHinweise as A}from"../schreibtor.js";async function q(T,y,k,$,a){const e=(await a(`/api/v1/instances/${T}`).catch(()=>null))?.org_id;if(!e)return null;let r=null;try{r=await a(`/api/v1/orgs/${e}/brain/predict`,{method:"POST",body:JSON.stringify({context:y,top_k:k})})}catch{return null}return!r||!r.warnings||r.warnings.length===0?null:await z(y,r,$,a)}async function W(T,y,k){const $=y.warnings[0]?.problem||T;if(!$)return[];try{const a=await k(`/api/v1/syndication/search?q=${encodeURIComponent($)}&limit=3`),o=new Set(y.warnings.map(e=>e.problem));return(a.results??[]).filter(e=>!!e.topic&&!!e.what_worked&&!o.has(e.topic)).slice(0,3).map(e=>({topic:e.topic,what_worked:e.what_worked.slice(0,160)}))}catch{return[]}}async function z(T,y,k,$){const a=[`\u{1F52E} **Org Brain Predict: "${T}"**`,""];for(const o of y.warnings){const e=Math.max(0,o.team_span-1),r=o.recurrence.reduce((p,t)=>p+(t.count??0),0),c=o.severity==="critical"?"\u{1F534}":o.severity==="major"?"\u{1F7E0}":"\u{1F7E1}";o.team_span>=2?a.push(`\u26A0\uFE0F **CROSS-TEAM RISK** \u2014 this pattern failed ${r}\xD7 across ${e} other team${e===1?"":"s"}:`):a.push(`\u26A0\uFE0F **RISK** \u2014 this pattern failed ${r}\xD7 before:`),a.push(` ${c} problem: \`${o.problem}\``);for(const p of o.recurrence.slice(0,6)){const t=p.last_seen?` (last: ${p.last_seen.slice(0,10)})`:"";a.push(` \u2022 ${p.team} \xD7${p.count}${t}`)}const d=o.fixes[0];if(d){const p=Math.round((d.confidence??0)*100),t=d.source_team?` (${d.source_team})`:"";a.push(` \u2705 Proven fix \u2014 ${p}% confidence, confirmed ${d.confirm_count}\xD7${t}:`),a.push(` ${d.summary}`)}a.push("")}if(k==="org+commons"){const o=await W(T,y,$);if(o.length>0){a.push("\u{1F310} **From the public Knowledge Commons** (cross-org, lower-signal):");for(const e of o)a.push(` \u2022 \`${e.topic}\` \u2014 ${e.what_worked}`);a.push("")}}return a.push('\u{1F4A1} Heeded the warning? `learn_from_attempts(..., tags=["prevented-by-org-graph"])` \u2192 counts as a prevented cross-team mistake.'),a.join(`
|
|
2
|
+
`)}const V=new Set(["syndicate","syndicate_search","syndicate_stats","syndicate_trending","brain_search","ckg_inspect","brain_predict","brain_plan","brain_marketplace","brain_install","brain_conflicts","brain_resolve_conflict","brain_confirm_ci","brain_briefing"]);async function Q(T,y,k,$){switch(T){case"syndicate":{const{topic:a,outcome:o="success",what_worked:e,what_failed:r="",severity:c="minor",tags:d=[],scope:p="public"}=y;if(!a||!e)throw new I(P.InvalidParams,"topic and what_worked are required");const t=L({topic:a,what_worked:e,what_failed:r,tags:d},p==="org"?"die Org":"die Commons");if(!t.ok)return t.meldung;const s={...t.felder,outcome:o,severity:c,scope:p},f=await $("/api/v1/syndication/contribute",{method:"POST",body:JSON.stringify(s)}),h=p==="org"?"\u{1F3E2} org-private":"\u{1F310} global commons",u=f.deduped?`
|
|
3
|
+
> \u267B\uFE0F Duplicate detected \u2014 trust score incremented for the existing lesson.`:"";return[`${p==="org"?"\u{1F3E2}":"\u{1F310}"} **Lesson syndicated to the ${p==="org"?"org Knowledge Commons":"global Knowledge Commons"}**${u}`,"",`**ID:** \`${f.id}\``,`**Topic:** \`${f.topic}\` \xB7 **Outcome:** ${f.outcome} \xB7 **Scope:** ${h}`,"",p==="org"?'This lesson is visible only within your organisation. Use `syndicate_search(scope="org")` to find it.':"Your lesson is now searchable by every AI brain in the network.","When another instance confirms it works, its trust score rises \u2014 and so does your contributor reputation.","",`**Tip:** Use \`syndicate_search(q="${t.felder.topic}")\` to see all community lessons on this topic.`,...t.geschwaerzt.length?["",E(t.geschwaerzt)]:[]].join(`
|
|
4
|
+
`)}case"syndicate_search":{const{q:a="",limit:o=20,category:e="",scope:r=""}=y,c=new URLSearchParams;a&&c.set("q",a),e&&c.set("category",e),r&&c.set("scope",r),c.set("limit",String(Math.min(Math.max(1,o),50)));const d=await $(`/api/v1/syndication/search?${c}`);if(!d.results||d.results.length===0)return a?`No lessons found for "${a}" in the global Knowledge Commons yet.
|
|
5
5
|
|
|
6
|
-
Be the first to contribute: \`syndicate(topic="...", what_worked="...")\``:'The global Knowledge Commons is empty. Be the first contributor:\n`syndicate(topic="deploy:api", what_worked="...")`';const p=u=>u==="success"?"\u2705":u==="failure"?"\u274C":"\u26A0\uFE0F",
|
|
7
|
-
`)}case"syndicate_stats":{const a=await
|
|
8
|
-
`)}case"syndicate_trending":{const{limit:a=10}=y,o=new URLSearchParams({limit:String(Math.min(Math.max(1,a),50))}),
|
|
9
|
-
`);const
|
|
10
|
-
`)}case"brain_search":{const{instance_id:a,query:o,limit:
|
|
6
|
+
Be the first to contribute: \`syndicate(topic="...", what_worked="...")\``:'The global Knowledge Commons is empty. Be the first contributor:\n`syndicate(topic="deploy:api", what_worked="...")`';const p=u=>u==="success"?"\u2705":u==="failure"?"\u274C":"\u26A0\uFE0F",t=u=>u==="critical"?"\u{1F534}":u==="major"?"\u{1F7E1}":"\u{1F7E2}",s=u=>{const l=Math.min(10,Math.round(u/5));return"\u2588".repeat(l)+"\u2591".repeat(10-l)+` \xD7${u}`},f=[a,e].filter(Boolean).join(" \xB7 "),h=[`## \u{1F310} Global Knowledge Commons${f?` \u2014 ${f}`:" \u2014 Recent"}`,`*${d.count} lesson${d.count===1?"":"s"} found*`,""];for(const u of d.results)h.push(`### ${p(u.outcome)} \`${u.topic}\` ${t(u.severity)}`,`**Trust:** ${s(u.confirm_count)}`,u.what_worked?`**What worked:** ${u.what_worked}`:"",u.what_failed?`**What failed:** ${u.what_failed}`:"",`*Contributed ${new Date(u.created_at).toLocaleDateString("de-DE")} \xB7 ID: \`${u.id}\`*`,"");return h.push("---",`**Confirm** (this helped you): \`syndicate(topic="${d.results[0]?.topic??"..."}", what_worked="...")\` \u2192 auto-deduped, trust +1`,'**Contribute your own:** `syndicate(topic="fix:...", what_worked="...")`','**Filter by category:** `syndicate_search(category="fix")`'),h.filter(u=>u!=="").join(`
|
|
7
|
+
`)}case"syndicate_stats":{const a=await $("/api/v1/syndication/stats"),o=r=>{const c=Math.min(10,Math.round(r/5));return"\u2588".repeat(c)+"\u2591".repeat(10-c)+` \xD7${r}`},e=["## \u{1F310} Global Knowledge Commons \u2014 Stats","","| Metric | Value |","|---|---|",`| Total lessons | **${a.total_lessons.toLocaleString()}** |`,`| Total confirms | **${a.total_confirms.toLocaleString()}** |`,`| Added last 7 days | **${a.added_last_7_days}** |`,"","### Top Categories"];for(const r of a.top_categories??[])e.push(`- \`${r.category}\` \u2014 ${r.count} lesson${r.count===1?"":"s"}`);e.push("","### Most Trusted Lessons");for(const r of a.most_trusted??[])e.push(`**\`${r.topic}\`** ${o(r.confirm_count)}`,`> ${r.what_worked.slice(0,120)}${r.what_worked.length>120?"\u2026":""}`,"");if(e.push("---",'**Contribute:** `syndicate(topic="...", what_worked="...")` | **Search:** `syndicate_search(q="your problem")`'),a.top_contributors?.length){e.push("","### \u{1F3C5} Top Contributors (anonymous)");for(const r of a.top_contributors)e.push(`- Trust **${r.trust_score}** \xB7 ${r.lessons_count} lesson${r.lessons_count===1?"":"s"} \xB7 ${r.confirms_received} confirms received`)}return e.join(`
|
|
8
|
+
`)}case"syndicate_trending":{const{limit:a=10}=y,o=new URLSearchParams({limit:String(Math.min(Math.max(1,a),50))}),e=await $(`/api/v1/syndication/trending?${o}`);if(!e.results||e.results.length===0)return["## \u{1F4C8} Trending in the Knowledge Commons","","No trending lessons yet (need at least 2 confirms in the last 7 days).","",'Contribute and confirm lessons to see them trend: `syndicate(topic="...", what_worked="...")`'].join(`
|
|
9
|
+
`);const r=s=>s==="success"?"\u2705":s==="failure"?"\u274C":"\u26A0\uFE0F",c=s=>s==="critical"?"\u{1F534}":s==="major"?"\u{1F7E1}":"\u{1F7E2}",d=s=>{const f=Math.min(10,Math.round(s/5));return"\u2588".repeat(f)+"\u2591".repeat(10-f)+` \xD7${s}`},p=s=>{const f=Math.min(10,Math.round(s*2));return"\u25B2".repeat(f)+"\u25B3".repeat(10-f)+` ${s.toFixed(2)}/day`},t=["## \u{1F4C8} Trending in the Knowledge Commons","*Lessons with the fastest confirmation velocity in the last 7 days*",""];for(const s of e.results)t.push(`### ${r(s.outcome)} \`${s.topic}\` ${c(s.severity)}`,`**Trend:** ${p(s.trend_score)} | **Trust:** ${d(s.confirm_count)}`,s.what_worked?`**What worked:** ${s.what_worked.slice(0,200)}${s.what_worked.length>200?"\u2026":""}`:"",`*ID: \`${s.id}\` \xB7 ${new Date(s.created_at).toLocaleDateString("de-DE")}*`,"");return t.push("---",`**Confirm** (if this helped you): \`syndicate(topic="${e.results[0]?.topic??"..."}", what_worked="...")\` \u2192 auto-deduped, trust +1`,'**All trending:** `syndicate_trending(limit=50)` | **Search:** `syndicate_search(q="...")`'),t.filter(s=>s!=="").join(`
|
|
10
|
+
`)}case"brain_search":{const{instance_id:a,query:o,limit:e=15}=y,r=await K(a,$,`\u{1F50E} **Brain Search: "${o}"**
|
|
11
11
|
|
|
12
|
-
No results found across all brain data.`);if(
|
|
12
|
+
No results found across all brain data.`);if(r)return r;const c=await k(a),d=await O(c,["cachly:lesson:best:*","cachly:ctx:*","cachly:idx:*","cachly:session:last","cachly:session:handoff","cachly:roadmap:*","cachly:ckg:node:*"],o,e);if(d.length===0)return[`\u{1F50E} **Brain Search: "${o}"**`,"","No results found across all brain data.","","\u{1F4A1} Try `smart_recall` or check `list_remembered`."].join(`
|
|
13
13
|
`);const p=[`\u{1F50E} **Brain Search: "${o}"** \u2014 ${d.length} result${d.length!==1?"s":""} across all brain data
|
|
14
|
-
`];for(const
|
|
14
|
+
`];for(const t of d.slice(0,e)){const s=t.key.startsWith("cachly:lesson:")?"\u{1F4A1} lesson":t.key.startsWith("cachly:ctx:")?"\u{1F4DD} context":t.key.startsWith("cachly:idx:")?"\u{1F4C2} index":t.key.startsWith("cachly:session:")?"\u{1F550} session":t.key.startsWith("cachly:roadmap:")?"\u{1F5FA}\uFE0F roadmap":t.key.startsWith("cachly:ckg:node:")?"\u{1F578}\uFE0F ckg-node":"\u{1F5C4}\uFE0F data",f=t.content.slice(0,280).replace(/\n/g," ");p.push(`**${s}** \`${t.key.split(":").slice(2).join(":")}\` _(BM25: ${t.score.toFixed(2)})_`),p.push(`> ${f}${t.content.length>280?"\u2026":""}
|
|
15
15
|
`)}return p.join(`
|
|
16
|
-
`)}case"ckg_inspect":{const{instance_id:a,concept:o,max_hops:
|
|
17
|
-
`);const
|
|
18
|
-
`);return[`\u{1F578}\uFE0F **CKG Inspect: "${o}"**`,"",`No edges found for \`${c}\`, but found similar nodes:`,
|
|
19
|
-
`)}const
|
|
20
|
-
`],l=new Map;for(const
|
|
21
|
-
`)}case"brain_predict":{const{instance_id:a,context:o,top_k:
|
|
16
|
+
`)}case"ckg_inspect":{const{instance_id:a,concept:o,max_hops:e=2}=y,r=await k(a),c=B(o),d=new Set,p=[],t=[{id:c,hop:0}];for(;t.length>0;){const{id:n,hop:i}=t.shift();if(d.has(n)||i>e)continue;d.add(n);const w=await r.smembers(`cachly:ckg:idx:from:${n}`),g=await r.smembers(`cachly:ckg:idx:to:${n}`);for(const m of[...w,...g].slice(0,50)){const _=await r.get(m);if(!_)continue;const b=S(_,null);b&&(p.push(b),i<e&&(d.has(b.from)||t.push({id:b.from,hop:i+1}),d.has(b.to)||t.push({id:b.to,hop:i+1})))}}if(p.length===0){const n=[],i=r.scanStream({match:`cachly:ckg:node:*${c}*`,count:100});if(await new Promise((g,m)=>{i.on("data",_=>n.push(..._)),i.on("end",g),i.on("error",m)}),n.length===0)return[`\u{1F578}\uFE0F **CKG Inspect: "${o}"**`,"","No CKG nodes found. The graph builds automatically as you call `learn_from_attempts`.","","\u{1F4A1} Once you have lessons stored, CKG edges will appear here."].join(`
|
|
17
|
+
`);const w=n.slice(0,10).map(g=>` \u2022 \`${g.replace("cachly:ckg:node:","")}\``).join(`
|
|
18
|
+
`);return[`\u{1F578}\uFE0F **CKG Inspect: "${o}"**`,"",`No edges found for \`${c}\`, but found similar nodes:`,w,"",'Try: `ckg_inspect(concept="<exact-node-id>")`'].join(`
|
|
19
|
+
`)}const s=new Set,f=p.filter(n=>{const i=`${n.from}:${n.edgeType}:${n.to}`;return s.has(i)?!1:(s.add(i),!0)}).sort((n,i)=>i.confidence-n.confidence),h={fixes:"\u{1F527}",requires:"\u{1F517}","co-occurs":"\u{1F504}",causes:"\u26A1",contradicts:"\u26A0\uFE0F",degrades_under:"\u{1F4C9}"},u=[`\u{1F578}\uFE0F **CKG Inspect: "${o}"** (${f.length} edge${f.length!==1?"s":""}, ${d.size} node${d.size!==1?"s":""} traversed)
|
|
20
|
+
`],l=new Map;for(const n of f)l.has(n.edgeType)||l.set(n.edgeType,[]),l.get(n.edgeType).push(n);for(const[n,i]of l){const w=h[n]??"\u2192";u.push(`**${w} ${n}** (${i.length})`);for(const g of i.slice(0,8)){const m=Math.round(g.confidence*100),_="\u2593".repeat(Math.round(m/10))+"\u2591".repeat(10-Math.round(m/10));u.push(` \`${g.from}\` \u2192 \`${g.to}\` ${_} ${m}% (${g.successes.toFixed(1)}/${g.trials} trials)`)}u.push("")}return u.push(`\u{1F4A1} Expand: \`ckg_inspect(concept="${o}", max_hops=3)\` | Predict: \`brain_predict(context="${o}")\``),u.join(`
|
|
21
|
+
`)}case"brain_predict":{const{instance_id:a,context:o,top_k:e=5,scope:r="instance"}=y;if(r==="org"||r==="org+commons"){const l=await q(a,o,e,r,$);if(l!==null)return l}const c=await K(a,$,`\u{1F52E} **Brain Predict: "${o}"**
|
|
22
22
|
|
|
23
|
-
No predictions yet \u2014 the brain hasn't seen this domain.`);if(c)return c;const d=await k(a),p=o.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2),
|
|
23
|
+
No predictions yet \u2014 the brain hasn't seen this domain.`);if(c)return c;const d=await k(a),p=o.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2),t=[];for(const l of p.slice(0,6)){const n=[],i=d.scanStream({match:`cachly:ckg:node:*${l}*`,count:50});await new Promise((w,g)=>{i.on("data",m=>n.push(...m)),i.on("end",w),i.on("error",g)});for(const w of n.slice(0,5)){const g=await d.get(w);if(!g)continue;const m=S(g,null);if(!m)continue;const _=await d.smembers(`cachly:ckg:idx:from:${m.id}`);for(const b of _.slice(0,20)){const x=await d.get(b);if(!x)continue;const v=S(x,null);if(!v||v.edgeType!=="fixes"&&v.edgeType!=="co-occurs"&&v.edgeType!=="causes")continue;const j=await d.get(`cachly:lesson:best:${v.from}`),C=j?S(j,null)??void 0:void 0;t.push({concept:m.id,edgeType:v.edgeType,target:v.to,confidence:v.confidence,lesson:C})}}}const s=[],f=[],h=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((l,n)=>{h.on("data",i=>f.push(...i)),h.on("end",l),h.on("error",n)});for(const l of f){const n=await d.get(l);if(n){const i=S(n,null);if(!i)continue;const w=[i.topic,i.what_failed??"",i.what_worked??""].join(" ").toLowerCase();if(p.reduce((m,_)=>m+(w.includes(_)?1:0),0)>=1&&i.outcome!=="failure"){const m=M(i);s.push({...i,confidence:m})}}}if(s.sort((l,n)=>n.confidence-l.confidence),t.length===0&&s.length===0)return[`\u{1F52E} **Brain Predict: "${o}"**`,"","No predictions yet \u2014 the brain hasn't seen this domain.","","\u{1F4A1} As you solve problems in this area and call `learn_from_attempts`, the CKG builds up and predictions become available."].join(`
|
|
24
24
|
`);const u=[`\u{1F52E} **Brain Predict: "${o}"**
|
|
25
|
-
`];if(
|
|
26
|
-
`)}case"brain_plan":{const{instance_id:a,task:o,top_k:
|
|
27
|
-
`);
|
|
28
|
-
${
|
|
25
|
+
`];if(t.length>0){const l=new Set,n=t.filter(i=>{const w=`${i.concept}:${i.edgeType}:${i.target}`;return l.has(w)?!1:(l.add(w),!0)}).sort((i,w)=>w.confidence-i.confidence).slice(0,e);u.push(`### \u{1F578}\uFE0F CKG Predictions (based on ${n.length} known edges)`);for(const i of n){const w=Math.round(i.confidence*100),g=i.edgeType==="fixes"?"\u{1F527}":i.edgeType==="co-occurs"?"\u{1F504}":"\u26A1";u.push(`${g} **${w}%** \`${i.concept}\` _${i.edgeType}_ \`${i.target}\``),i.lesson?.what_worked&&u.push(` \u2705 ${i.lesson.what_worked.slice(0,120)}`)}u.push("")}if(s.length>0){u.push(`### \u{1F4DA} Relevant Lessons (${Math.min(s.length,e)} pre-loaded)`);for(const l of s.slice(0,e)){const n=Math.round(l.confidence*100);u.push(` \u2705 **${n}%** \`${l.topic}\` \u2014 ${(l.what_worked??"").slice(0,120)}`)}u.push("")}return u.push('\u{1F4A1} Outcome confirmed? `learn_from_attempts(topic="fix:...", outcome="success", ...)` \u2192 improves future predictions'),u.join(`
|
|
26
|
+
`)}case"brain_plan":{const{instance_id:a,task:o,top_k:e=5}=y;if(!o||!o.trim())throw new I(P.InvalidParams,"task is required");const r=await k(a),c=o.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2),d=[],p=r.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((l,n)=>{p.on("data",i=>d.push(...i)),p.on("end",l),p.on("error",n)});const t=[];for(const l of d){const n=await r.get(l);if(!n)continue;const i=S(n,null);if(!i)continue;const w=[i.topic,i.what_worked??"",i.what_failed??""].join(" ").toLowerCase(),g=c.reduce((m,_)=>m+(w.includes(_)?1:0),0);g>=1&&t.push({l:i,score:g,confidence:M(i)})}if(t.length===0)return[`\u{1F5FA}\uFE0F **Brain Plan: "${o}"**`,"","No grounded plan yet \u2014 the brain hasn't seen this area.","","\u{1F4A1} As you work here and call `learn_from_attempts`, brain_plan will assemble"," an ordered, proven plan from your own history. For now, proceed carefully"," and capture what works."].join(`
|
|
27
|
+
`);t.sort((l,n)=>n.score-l.score||n.confidence-l.confidence);const s=t.filter(l=>l.l.outcome==="failure"||(l.l.what_failed??"").trim().length>0),f=t.filter(l=>l.l.outcome==="success"||l.l.outcome==="partial"),h=[`\u{1F5FA}\uFE0F **Brain Plan: "${o}"**`,"",`_Grounded in ${t.length} relevant lesson${t.length!==1?"s":""} from your own Brain._`,""];if(s.length>0){h.push("### \u26A0\uFE0F Likely failure modes (avoid these)");const l={critical:0,major:1,minor:2};s.slice().sort((n,i)=>(l[n.l.severity??"minor"]??1)-(l[i.l.severity??"minor"]??1)||i.confidence-n.confidence).slice(0,e).forEach(({l:n,confidence:i})=>{const w=n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":"\u{1F7E2}",g=(n.what_failed??n.what_worked??"").slice(0,120);h.push(`${w} **${Math.round(i*100)}%** \`${n.topic}\`${g?` \u2014 ${g}`:""}`)}),h.push("")}if(f.length>0){const l=f.slice(0,e),n=new Map(l.map(m=>[m.l.topic,m])),i=[],w=new Set,g=(m,_)=>{if(!(w.has(m.l.topic)||_>10)){for(const b of m.l.depends_on??[]){const x=n.get(b);x&&!w.has(b)&&g(x,_+1)}w.has(m.l.topic)||(w.add(m.l.topic),i.push(m))}};for(const m of l)g(m,0);h.push("### \u{1F527} Recommended steps (proven fixes, in order)"),i.forEach(({l:m,confidence:_},b)=>{h.push(`${b+1}. **${Math.round(_*100)}%** \`${m.topic}\` \u2014 ${(m.what_worked??"").slice(0,140)}`);const x=(m.commands??[]).slice(0,2);x.length>0&&h.push(` \`\`\`
|
|
28
|
+
${x.join(`
|
|
29
29
|
`)}
|
|
30
|
-
\`\`\``),(m.depends_on??[]).length>0&&
|
|
31
|
-
`)}case"brain_marketplace":{const{min_confirms:a=1}=y,o=new URLSearchParams;a&&a>1&&o.set("min_confirms",String(a));const
|
|
32
|
-
`);const
|
|
33
|
-
`)}case"brain_install":{const{instance_id:a,slug:o,min_confirms:
|
|
34
|
-
`);const
|
|
35
|
-
`)}case"brain_conflicts":{const{instance_id:a}=y,o=await k(a),
|
|
36
|
-
`);
|
|
37
|
-
`)}case"brain_resolve_conflict":{const{instance_id:a,topic:o,winner:
|
|
38
|
-
`)}case"brain_confirm_ci":{const{instance_id:a,job_status:o,topics:
|
|
39
|
-
`);const p=[`\u{1F916} **brain_confirm_ci** \u2014 CI ${o==="success"?"\u2705":"\u274C"} \xB7 ${d.updated} lesson${d.updated!==1?"s":""} updated`,"","| Topic | Old | New | \u0394 | Reason |","|---|---|---|---|---|"];for(const
|
|
40
|
-
`)}case"brain_briefing":{const{instance_id:a,event_type:o,context:
|
|
41
|
-
`);const p=c.risk_level==="high"?"\u{1F534}":c.risk_level==="medium"?"\u{1F7E1}":"\u{1F7E2}",
|
|
42
|
-
`)}default:return null}}export{
|
|
30
|
+
\`\`\``),(m.depends_on??[]).length>0&&h.push(` \u21B3 depends on: ${(m.depends_on??[]).map(v=>`\`${v}\``).join(", ")}`)}),h.push("")}const u=t.filter(l=>(l.l.file_paths??[]).length>0||(l.l.commands??[]).length>0).slice(0,4);if(u.length>0){h.push("### \u2705 Pre-flight checklist");const l=[...new Set(u.flatMap(n=>n.l.file_paths??[]))].slice(0,6);l.length>0&&h.push(` \u2022 Review files that were involved before: ${l.map(n=>`\`${n}\``).join(", ")}`),h.push(" \u2022 Confirm the top failure mode above can't recur in your change"),h.push(" \u2022 Have a rollback ready for any `critical`/`major` step"),h.push("")}return h.push('\u{1F4A1} After you ship: `learn_from_attempts(topic="...", outcome="success", ...)` \u2192 the next plan gets sharper.'),h.join(`
|
|
31
|
+
`)}case"brain_marketplace":{const{min_confirms:a=1}=y,o=new URLSearchParams;a&&a>1&&o.set("min_confirms",String(a));const e=await $(`/api/v1/syndication/brains${o.toString()?`?${o}`:""}`);if(!e.brains||e.brains.length===0)return["## \u{1F9E0} Domain Brain Marketplace","","No domain brains are available yet \u2014 the marketplace fills as the community","contributes verified lessons. Be an early contributor:",'`syndicate(topic="k8s:oom-kill", what_worked="raise memory limit + add probe")`'].join(`
|
|
32
|
+
`);const r=["## \u{1F9E0} Domain Brain Marketplace",`*${e.count} installable brain${e.count===1?"":"s"} \xB7 curated from the global Knowledge Commons*`,""];for(const c of e.brains){const d=c.curated?"\u2B50 curated":"community";r.push(`### ${c.icon} ${c.name} \`${c.slug}\``,`${c.description}`,`**${c.lesson_count}** lesson${c.lesson_count===1?"":"s"} \xB7 \u{1F91D} ${c.total_confirms} community confirm${c.total_confirms===1?"":"s"} \xB7 ${d}`,`Install: \`brain_install(slug="${c.slug}")\``,"")}return r.push("---","_Installed brains merge into your local Brain and surface in `smart_recall` \u2014 they never override your own lessons._"),r.join(`
|
|
33
|
+
`)}case"brain_install":{const{instance_id:a,slug:o,min_confirms:e=1,limit:r=200,dry_run:c=!1}=y,d=typeof o=="string"?o.trim():"";if(!d)throw new I(P.InvalidParams,"slug is required \u2014 run brain_marketplace() to see available domain brains");const p=new URLSearchParams;e&&e>1&&p.set("min_confirms",String(e)),r&&r!==200&&p.set("limit",String(Math.min(Math.max(1,r),500)));const t=await $(`/api/v1/syndication/brains/${encodeURIComponent(d)}${p.toString()?`?${p}`:""}`);if(!t.lessons||t.lessons.length===0)return`No installable lessons found for domain brain \`${d}\`. Run \`brain_marketplace()\` to see what's available.`;if(c)return[`## \u{1F4E6} ${t.name} (DRY RUN)`,`Would install **${t.lessons.length}** lesson${t.lessons.length===1?"":"s"} into your Brain.`,"",...t.lessons.slice(0,15).map(w=>` \u2022 \`${w.topic}\` \xB7 \u{1F91D} ${w.confirm_count}`),t.lessons.length>15?` \u2026and ${t.lessons.length-15} more`:"","",`Run without \`dry_run\` to install: \`brain_install(slug="${d}")\``].filter(Boolean).join(`
|
|
34
|
+
`);const s=await k(a),f=`marketplace:${d}`,h=new Date().toISOString();let u=0,l=0,n=0,i=0;for(const w of t.lessons){if(!w.topic||!w.what_worked){l++;continue}const g=(()=>{const C=S(w.tags,[]);return Array.isArray(C)?C.filter(N=>typeof N=="string"):[]})(),m=R({topic:w.topic,what_worked:w.what_worked,what_failed:w.what_failed??"",tags:g});m.geschwaerzt.length&&n++,m.verdacht.length&&i++;const _={...w,...m.felder},b=`cachly:lesson:best:${_.topic}`,x=await s.get(b);if(x){const C=S(x,null);if(C&&C.source!==f){l++;continue}}const v=JSON.stringify({topic:_.topic,outcome:_.outcome||"success",what_worked:_.what_worked,what_failed:_.what_failed||"",severity:_.severity||"minor",tags:D(m.felder.tags,m.verdacht),visibility:"team",confidence:M({ts:h,verified_at:h,recall_count:_.confirm_count}),recall_count:0,source:f,ts:h,verified_at:h,version:3});await s.set(b,v);const j=`cachly:lessons:${_.topic}`;await s.rpush(j,v),await s.ltrim(j,-100,-1),await s.expire(j,90*86400),u++}return await s.set(`cachly:stats:born_at:${a}`,h,"EX",365*86400,"NX").catch(()=>{}),[`## \u{1F4E6} Installed: ${t.name}`,"",`**${u}** lesson${u===1?"":"s"} merged into your Brain${l>0?` \xB7 ${l} skipped (your own lessons take priority)`:""}.`,"","They're live in `smart_recall` now \u2014 try a query in this domain:",` \u2022 \`smart_recall(query="${t.lessons[0]?.topic.split(":").pop()??"your problem"}")\``,"",`_Installed lessons are tagged \`source: "${f}"\` and never override your own. Re-run anytime to pull updates._`,...n+i>0?["",...A(n,i,`${t.lessons.length} Lektionen`)]:[]].join(`
|
|
35
|
+
`)}case"brain_conflicts":{const{instance_id:a}=y,o=await k(a),e=[],r=o.scanStream({match:"cachly:ckg:conflict:*",count:100});await new Promise((f,h)=>{r.on("data",u=>e.push(...u)),r.on("end",f),r.on("error",h)});const c=[];if(e.length>0){const f=await o.mget(...e);for(const h of f){const u=S(h??null,null);u&&!u.resolved&&c.push(u)}}const d=[],p=o.scanStream({match:"cachly:agents:active:*",count:100});await new Promise((f,h)=>{p.on("data",u=>d.push(...u)),p.on("end",f),p.on("error",h)});const t=[];if(d.length>0){const f=await o.mget(...d);for(const h of f){const u=S(h??null,null);u&&t.push(u)}}const s=["## \u2694\uFE0F Brain Conflicts & Live Agents",""];if(s.push(`**\u{1F916} Active agents (last 1h):** ${t.length}`),t.length>0)for(const f of t.sort((h,u)=>u.ts.localeCompare(h.ts)).slice(0,10)){const h=Math.round((Date.now()-new Date(f.ts).getTime())/6e4);s.push(` - **${f.author}** \u2014 last: \`${f.last_topic??"?"}\` (${f.last_outcome??"?"}, ${h}m ago)`)}if(s.push(""),c.length===0)return s.push("**\u2705 No unresolved belief conflicts.** The Brain is in consensus."),s.join(`
|
|
36
|
+
`);s.push(`**\u26A0\uFE0F Unresolved belief conflicts:** ${c.length}`),s.push(""),s.push("| Topic | Confirmed fix | Contradicted by | Detected |"),s.push("|---|---|---|---|");for(const f of c.sort((h,u)=>u.detected_at.localeCompare(h.detected_at)).slice(0,20)){const h=Math.round((Date.now()-new Date(f.detected_at).getTime())/36e5);s.push(`| \`${f.topic}\` | ${(f.fix_confidence*100).toFixed(0)}% (n=${f.fix_trials}) | ${f.reported_by??"unknown"} | ${h}h ago |`)}return s.push(""),s.push(`_Arbitrate with \`brain_resolve_conflict(instance_id="${a}", topic="<topic>", winner="success"|"failure")\`._`),s.join(`
|
|
37
|
+
`)}case"brain_resolve_conflict":{const{instance_id:a,topic:o,winner:e,resolved_by:r="human"}=y;if(!o||!o.trim())throw new I(P.InvalidParams,"topic is required");if(e!=="success"&&e!=="failure")throw new I(P.InvalidParams,'winner must be "success" or "failure"');const c=await k(a),d=B(o),p=`cachly:ckg:conflict:${d}`,t=await c.get(p);if(!t)return`\u{1F4ED} No active conflict found for \`${o}\`. Run \`brain_conflicts(instance_id="${a}")\` to list open conflicts.`;let s=0;if(e==="failure"){const n=await c.smembers(`cachly:ckg:idx:from:${d}`);for(const i of n){const w=await c.get(i);if(!w)continue;const g=S(w,null);!g||g.edgeType!=="fixes"||(g.confidence=.1,await c.set(i,JSON.stringify(g)),s++)}}let f=!1;const h=`cachly:lesson:best:${o}`,u=await c.get(h);if(u){const n=S(u,null);n&&n.outcome===e?n.state==="provisional"&&(n.state="active",n.verified_at=new Date().toISOString(),await c.set(h,JSON.stringify(n))):n&&n.outcome&&n.outcome!==e&&(n.state="archived",n.audit_trail=[...Array.isArray(n.audit_trail)?n.audit_trail:[],{ts:new Date().toISOString(),action:"conflict_loser_archived",resolved_by:r}],await c.set(h,JSON.stringify(n)),f=!0)}const l=S(t,null)??{};return l.resolved=!0,l.winner=e,l.resolved_by=r,l.resolved_at=new Date().toISOString(),await c.set(p,JSON.stringify(l),"EX",3600*24*30),[`## \u2705 Conflict resolved \u2014 \`${o}\``,"",`**Winner:** ${e==="success"?"\u2705 success (fix is valid)":"\u274C failure (fix retired)"}`,`**Resolved by:** ${r}`,"",`- CKG \`fixes\` edges decayed: **${s}**`,`- Losing lesson archived: **${f?"yes":"no"}**`,"",e==="failure"?"_The contradicted fix is retired. smart_recall will stop surfacing it; future attempts start fresh._":"_The fix is reaffirmed. The contradicting failure no longer blocks recall._"].join(`
|
|
38
|
+
`)}case"brain_confirm_ci":{const{instance_id:a,job_status:o,topics:e,scan_topics:r=[],source:c="manual"}=y;if(!o||!["success","failure","cancelled"].includes(o))throw new Error("job_status must be success, failure, or cancelled");if(!e?.length)throw new Error("topics is required");if(o==="cancelled")return"\u23ED\uFE0F CI was cancelled \u2014 no confidence changes applied.";let d;try{d=await $(`/api/v1/instances/${a}/ci-outcome`,{method:"POST",body:JSON.stringify({job_status:o,topics:e,scan_topics:r,source:c})})}catch{return"\u26A0\uFE0F Could not reach Brain API \u2014 CI outcome not recorded. Will retry on next call."}if(d.updated===0)return[`\u{1F916} **brain_confirm_ci** \u2014 CI ${o}`,"","No confidence changes (no matching predictions for these topics).",`Topics checked: ${e.slice(0,5).map(t=>`\`${t}\``).join(", ")}${e.length>5?` +${e.length-5} more`:""}`].join(`
|
|
39
|
+
`);const p=[`\u{1F916} **brain_confirm_ci** \u2014 CI ${o==="success"?"\u2705":"\u274C"} \xB7 ${d.updated} lesson${d.updated!==1?"s":""} updated`,"","| Topic | Old | New | \u0394 | Reason |","|---|---|---|---|---|"];for(const t of d.confidence_deltas){const s=t.delta>0?"+":"",f=t.reason==="confirmed_failure"?"\u{1F534}":"\u{1F7E1}";p.push(`| \`${t.topic}\` | ${(t.old*100).toFixed(0)}% | ${(t.new*100).toFixed(0)}% | ${s}${(t.delta*100).toFixed(0)}% | ${f} ${t.reason} |`)}return p.push("","_Brain self-calibrated from real CI signal. No manual `learn_from_attempts` needed._"),p.join(`
|
|
40
|
+
`)}case"brain_briefing":{const{instance_id:a,event_type:o,context:e,threshold:r}=y;if(!["file_open","pr_open","deploy","manual"].includes(o))throw new Error("event_type must be file_open, pr_open, deploy, or manual");if(!e?.trim())throw new Error("context is required");let c;try{c=await $(`/api/v1/instances/${a}/briefing`,{method:"POST",body:JSON.stringify({event_type:o,context:e,...r!==void 0?{threshold:r}:{}})})}catch{return"\u26A0\uFE0F Could not reach Brain API \u2014 no proactive briefing available right now."}const d=o==="file_open"?"\u{1F4C2}":o==="pr_open"?"\u{1F500}":o==="deploy"?"\u{1F680}":"\u{1F50D}";if(c.warnings.length===0)return[`${d} **brain_briefing** \u2014 ${o} \xB7 \u2705 no known risk patterns matched`,"",`Checked against ${c.matched_lessons} related lesson${c.matched_lessons!==1?"s":""}. You're clear to proceed.`].join(`
|
|
41
|
+
`);const p=c.risk_level==="high"?"\u{1F534}":c.risk_level==="medium"?"\u{1F7E1}":"\u{1F7E2}",t=[`${d} **brain_briefing** \u2014 ${o} \xB7 ${p} risk: ${c.risk_level.toUpperCase()}`,"",`The Brain proactively found ${c.warnings.length} known pattern${c.warnings.length!==1?"s":""} that may apply here:`,"","| Topic | Confidence | Severity | What to watch | Known fix |","|---|---|---|---|---|"];for(const s of c.warnings){const f=s.fix?s.fix.length>80?s.fix.slice(0,80)+"\u2026":s.fix:"\u2014";t.push(`| \`${s.topic}\` | ${(s.confidence*100).toFixed(0)}% | ${s.severity} | ${s.message} | ${f} |`)}return t.push("","_Surfaced proactively \u2014 no `smart_recall` needed. Address the highest-confidence items first._"),t.join(`
|
|
42
|
+
`)}default:return null}}export{V as SYNDICATE_TOOL_NAMES,Q as handleSyndicateTool};
|