@cachly-dev/mcp-server 0.10.168 → 0.10.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{createHash as s}from"node:crypto";const i=Number(process.env.CACHLY_CONFIDENCE_WARN_DAYS??5),d=Number(process.env.CACHLY_CONFIDENCE_STALE_DAYS??10),o=.7,c=.5;function p(e){const r=e.verified_at??e.ts,t=(Date.now()-new Date(r).getTime())/864e5;return t>=d?c:t>=i?o:1-t/i*(1-o)}function m(e,r,n){if(e>=.9)return"\u2705";const t=a(n);return e>=.7?`\u26A0\uFE0F (${Math.round(r)}d old, confidence ${(e*100).toFixed(0)}% \u2014 verify before applying${t})`:`\u{1F534} STALE (${Math.round(r)}d old, confidence ${(e*100).toFixed(0)}% \u2014 likely outdated!${t})`}function a(e){const r=(e??"").trim();return!r||r.includes(`
2
- `)||r.length>120?"":`, e.g. \`${r}\``}const E={deploy:{required:["commands"],hint:"deploy:* needs commands[]"},bash:{required:["commands"],hint:"bash:* needs commands[]"},infra:{required:["commands"],hint:"infra:* needs commands[] + verified on real system"},pricing:{required:[],hint:'pricing:* \u2014 add context with source (e.g. "Stripe Dashboard Apr 2026")'},stripe:{required:[],hint:"stripe:* \u2014 add context with Stripe API version"}};function f(e){return s("md5").update(e).digest("hex").slice(0,12)}export{d as CONFIDENCE_STALE_DAYS,c as CONFIDENCE_STALE_VALUE,i as CONFIDENCE_WARN_DAYS,o as CONFIDENCE_WARN_VALUE,E as STRUCTURED_TEMPLATES,p as calculateConfidence,m as confidenceBadge,f as simpleHash};
1
+ import{createHash as u}from"node:crypto";const d=Number(process.env.CACHLY_CONFIDENCE_WARN_DAYS??5),p=Number(process.env.CACHLY_CONFIDENCE_STALE_DAYS??10),c=.7,m=.5;function C(e){const t=e.verified_at??e.ts,r=(Date.now()-new Date(t).getTime())/864e5;return r>=p?m:r>=d?c:1-r/d*(1-c)}function A(e,t,n,r){const i=(r?.am??"").slice(0,10);if(i){const s=(r?.befund??"").trim(),a=s?` \u2014 ${s.slice(0,160)}`:"";return`\u274C CHECK FAILED on ${i}${a}`}if(e>=.9)return"\u2705";const o=E(n);return e>=.7?`\u26A0\uFE0F (${Math.round(t)}d old, confidence ${(e*100).toFixed(0)}% \u2014 verify before applying${o})`:`\u{1F534} STALE (${Math.round(t)}d old, confidence ${(e*100).toFixed(0)}% \u2014 likely outdated!${o})`}function E(e){const t=(e??"").trim();return!t||t.includes(`
2
+ `)||t.length>120?"":`, e.g. \`${t}\``}const N={deploy:{required:["commands"],hint:"deploy:* needs commands[]"},bash:{required:["commands"],hint:"bash:* needs commands[]"},infra:{required:["commands"],hint:"infra:* needs commands[] + verified on real system"},pricing:{required:[],hint:'pricing:* \u2014 add context with source (e.g. "Stripe Dashboard Apr 2026")'},stripe:{required:[],hint:"stripe:* \u2014 add context with Stripe API version"}};function h(e){return u("md5").update(e).digest("hex").slice(0,12)}export{p as CONFIDENCE_STALE_DAYS,m as CONFIDENCE_STALE_VALUE,d as CONFIDENCE_WARN_DAYS,c as CONFIDENCE_WARN_VALUE,N as STRUCTURED_TEMPLATES,C as calculateConfidence,A as confidenceBadge,h as simpleHash};
@@ -1,76 +1,76 @@
1
- import{execSync as Qe}from"node:child_process";import{createRequire as et}from"node:module";import{calculateConfidence as Re,confidenceBadge as Mt,STRUCTURED_TEMPLATES as It,CONFIDENCE_WARN_VALUE as tt,CONFIDENCE_STALE_VALUE as Dt,CONFIDENCE_WARN_DAYS as Rt}from"../confidence.js";import{kurzfassenHinweis as Lt}from"../antwort-hinweis.js";import{pruefeMeldung as Bt,wendeAn as zt}from"../pruefung-melden.js";import{ckgSlug as me,extractProblemConcept as We,ckgUpsertNode as xe,ckgUpdateEdge as ge,ckgUpsertPersonNode as Ot,ckgUpsertFileNode as st,ckgRecordCollaboration as Pt,ckgUpsertServiceNode as jt}from"../ckg.js";import{safeJsonParse as O,scanKeys as ve,leseOderNull as Ce,darfHeraus as Te}from"../utils.js";import{ersparteMinuten as nt,istStarterLektion as Le,zaehltAlsErsparnis as ot}from"../wertbeitrag.js";import{lessonPreviewLines as Me,trimTo as Ft}from"../lesson-preview.js";import{normalisiereZeit as Ke,zaehleZeitangaben as Ge}from"../zeit-normalisieren.js";import{abstentionSatz as Wt,alterssatzFuerBelegte as Kt,beurteileTreffer as Gt,istBelegt as Ht}from"../abstention.js";import{meldeEinmal as He,meldeUndVermerke as Be,fehlerText as Je,OHNE_VEKTOREN as Jt,OHNE_DIENST as qt,OHNE_FRAGEVEKTOR as Ut,SINNPFAD_ABBRUCH as Vt,OHNE_SCHREIBVEKTOR as qe}from"../aussetzer.js";import{versuchStart as Yt,neueKennung as Zt,wendeZuteilungAn as Xt,schliesseVersuchAb as Qt}from"../versuch.js";function at(ie,H,U){if(ie.includes("lesson:best:")){const g=O(H,{});if(g&&typeof g=="object"&&(g.what_worked||g.what_failed||g.commands?.length))return Me(g,{maxChars:U,indent:" "})}const ue=Ft(H,U);return ue?[ue]:[]}import{getRole as Ue,ROLE_BADGE as es,getScopes as it,lessonVisibleToScope as rt,reviewModeEnabled as ts,storeLessonProposal as ss}from"./team.js";import{keywordSearch as ze,treffeUeberDateipfad as ns,wortindexEntwerten as ct,tokenize as Ve,splitMultiQuery as os,levenshtein as as,indexVocab as lt}from"../search.js";import{rerankByQuality as is,qualityMultiplier as rs,extractLessonQuality as cs}from"../rerank.js";import{computeEmbedding as $e,hasEmbedProvider as Ne,EMBED_PROVIDER as Se}from"../embeddings.js";import{repariereFelder as ls}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as ut,NAME_VEKTOR_PRAEFIX as ht,ZWEIT_VEKTOR_PRAEFIX as Ie,packe as Ee,textFuerVektor as De,textFuerNamensVektor as us,Vektorbestand as Ye}from"../bedeutung.js";import{schreibeEingaenge as hs,Eingangsbestand as ds}from"../eingaenge.js";import{Seltenheitsbestand as fs}from"../seltenheitsbestand.js";import{spurLegen as ps}from"../spuren.js";import{schlageErsetzungVor as ms}from"../ersetzung-vorschlag.js";const Ae="cachly:vek:nachtrag",gs=365;import{etikettenFuer as ys,lieferJournalSchluessel as dt,JOURNAL_DECKEL as ws}from"../etiketten.js";import{klassifiziereFehlschlag as _s,suchProtokollSchluessel as ft,trichterSchluessel as pt,SUCH_DECKEL as bs}from"../recall-trichter.js";import{leiteEntscheidungAb as $s,entscheidungsZeile as mt}from"../entscheidung-ableiten.js";import{bewerteTopf as vs,spreizeImTopf as gt,reichereAn as ks,inhaltsWoerter as yt,grobStamm as Ss,GEWICHTE as Cs,knapperSiegSatz as xs}from"../rangfolge.js";import{pruefeWirkung as Ts,werteAus as Ns,lehrwert as Es,leiteAb as As}from"../wirkungsspur.js";import{merkeSuchlauf as wt}from"../suchstatistik.js";import{schreibeTopfNotiz as Ms,topfProtokollAktiv as Is}from"../topf-protokoll.js";import{SINN_TOPF as Ds,EINGANG_SCHWELLE as Rs,EINGANG_SORTIER_GEWICHT as Ls,ZWEIT_MODELL as Oe,ZWEIT_GEWICHT as Bs,ZWEIT_MINDESTDECKUNG as _t,NAHDUPLIKAT_SCHWELLE as zs}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as bt,quelleZeile as Os}from"../herkunft.js";import{merkeRecall as Ps,sitzungsKosten as js,vergissSitzungsKosten as Fs,kostenZeilen as Ws}from"../sitzungs-kosten.js";const ye=new Ye,Ze=new Ye(6e4,ht),Pe=new Ye(6e4,Ie),Xe=new ds,je=new fs,$t=Ds,Ks=Rs,Gs=Ls;import{upgradeNudge as Hs}from"../upgrade-nudge.js";import{recallTiefe as vt,TIEFE_VOLL as Js,TIEFE_VOLL_MEHRTHEMIG as qs}from"../recall-tiefe.js";import{nutzungInWorten as Us,nutzungsSchluessel as Vs,verdichte as Ys}from"../werkzeug-nutzung.js";import{inWorten as Zs,lieferBild as Xs,lieferSchluessel as Qs,trefferSchluessel as en}from"../geliefert.js";import{COAUTHOR_PREF_KEY as tn,autorHinweis as sn,coautorAus as nn,echterGitLeser as on,ermittleAutor as an,mitCoautor as rn,nurMensch as kt}from"../autor.js";import{TOOLS as cn}from"../tools.js";import{vorspannHinweis as ln}from"../vorspann.js";import{autorAbzeichen as un,fremdanteil as hn}from"../autor-abzeichen.js";import{cachlyUrl as dn}from"../cachly-url.js";const Fe=(()=>{try{const ie=et(import.meta.url);for(const H of["../../../package.json","../../package.json"])try{const U=ie(H);if(U.name==="@cachly-dev/mcp-server"&&U.version)return U.version}catch{}}catch{}return"0.10.100"})(),fn=()=>{try{return et(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},pn={"0.10.119":["\u{1F50D} **Explainable briefings \u2014 provenance in every warning**"," \u{1F4CE} `/briefing` warnings now carry `outcome`, `author`, `learned_at` and `matched_on` (the context tokens that triggered the warning) \u2014 editors can show WHY a fix hint fired, not just what it claims.",' \u{1F9F0} VS Code 0.12.0 uses this: severity + confidence in the toast, full lesson card with provenance, "Not helpful" per-file suppression, reviewable CLS auto-learns.'," \u{1F9F9} CI docs now describe exactly what ships: scan mode uses the REST `/scan` endpoint, the GitLab template covers learn/scan/confirm."],"0.10.115":["\u{1F527} **`brain_get_pref` + `brain_set_pref` \u2014 persistent Brain preferences**"," \u{1F4D6} `brain_get_pref` reads back any stored preference (omit key to list all)."," \u270F\uFE0F `brain_set_pref` saves a preference to Redis \u2014 survives restarts, scoped per Brain instance.",' \u{1F4A1} Known key: `auto_changelog` \u2014 set to "false" to silence the new-lessons digest at session_start.'," \u{1F4CA} 140 MCP tools"],"0.10.114":["\u{1F4CB} **`brain_changelog` \u2014 weekly knowledge digest in one call**"," \u{1F4C5} Generates a grouped Markdown changelog of lessons learned in the last N days."," \u{1F465} Grouped by topic category, annotated with author, recall count, and confidence \u2014 paste directly into standup or Slack."," \u2699\uFE0F Params: `days` (default 7), `max_lessons` (default 30), `include_failures` (default true)."," \u{1F4CA} 138 MCP tools"],"0.10.113":["\u{1F4C8} **Week-over-week savings trend in `cache_stats`**"," \u{1F4C5} `cache_stats` now shows **7-day hits** + **WoW trend %** (e.g. `+23.0% vs prev week`) so ROI momentum is visible, not just the cumulative total."," \u2B07\uFE0F Goes red (\u{1F4C9}) on drops, green (\u{1F4C8}) on growth \u2014 first week always shows +100% (new)."," \u{1F527} Backed by new `CountHitsInWindow` repo method + `hits_last_7d`, `hits_prev_7d`, `week_over_week_pct` fields in `SavingsEstimate`."," \u{1F4CA} 137 MCP tools"],"0.10.112":["\u2699\uFE0F **Configurable cost_per_call_usd \u2014 accurate ROI for any LLM**"," \u{1F4A1} New `set_cost_per_call` tool: set your real per-call cost (claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001) so savings estimates in `cache_stats` reflect your actual bill."," \u{1F527} New API: `PUT /api/v1/instances/:id/cost-per-call` \u2014 persisted per instance, used by `cache_stats`, org savings, and SSE analytics stream."," \u{1F4CA} 137 MCP tools"],"0.10.111":["\u{1F3E2} **Org-wide ROI + GitLab CI \u2014 the CFO number, aggregated**"," \u{1F4B0} `cache_org_stats` now shows **org-wide Tokenmaxxing ROI**: total savings summed across every instance in your org, monthly projection, top-5 instances by savings. One number for the whole team."," \u{1F50C} Backed by new API endpoint `GET /api/v1/orgs/:id/savings` (org members only)"," \u{1F98A} GitLab CI integration: `brain-from-ci-gitlab.yml` \u2014 two `.post` jobs (on_success/on_failure), same helper script, pipeline never fails because of Brain push"," \u{1F6E0}\uFE0F GitHub Action template fixed: `secrets.*` in job-level `if` is invalid \u2014 guard removed (helper script skips cleanly on missing secrets)"," \u{1F4CA} 136 MCP tools"],"0.10.110":["\u{1F3E2} **Zero friction: ROI-Projektor, Org-Shared-Cache, CI ready-to-paste**"," \u{1F4C8} `cache_stats` \u2014 zero-hit projection calculator: shows expected monthly savings for 5/10/20-dev teams before a single cache hit lands. ROI visible from day 1."," \u{1F3E2} New `cache_org_stats` \u2014 shared org-level cache stats across multiple instances. Convention-based (`org:{id}:sem`), zero API changes needed."," \u{1F517} `cache_set`/`cache_get` now accept optional `org_id` \u2014 write to personal + org namespace, fall back to org on miss. Fully backwards-compatible."," \u{1F4CB} Copy-paste CI integration: `brain-from-ci-action.yml` \u2192 Brain self-calibrates confidence on every GitHub Actions run. No config beyond two repo secrets."," \u{1F4CA} 136 MCP tools"],"0.10.109":["\u{1F4B0} **Tokenmaxxing ROI + Closed-loop CI learning**"," \u{1F4CA} `cache_stats` now shows a **Tokenmaxxing ROI** section \u2014 total tokens saved, monthly cost projection, and top 3 most-cached prompts. Finally a number you can show the CFO."," \u{1F504} New `brain_from_ci` \u2014 bulk-ingest CI history into the Brain (red\u2192green = learned fix, green\u2192red = CKG causal edge). The brain_from_git equivalent for CI. Bootstrap the Brain from your CI logs in one call."," \u{1F4CA} 134 MCP tools"],"0.10.108":["\u{1F9E0} **Focused briefing + trustworthy autopilot**"," \u{1F3AF} New `session_start_summary` \u2014 top-N focused briefing by topic. Scores lessons by relevance \xD7 confidence + recall_count + severity + recency. Use it for a quick pre-brief without loading the full Brain.",' \u{1F91D} Autopilot template now explains the data flow upfront ("your own Brain, EU-hosted, no third parties") \u2014 no more friction with cautious AI assistants during onboarding'," \u{1F4CA} 132 MCP tools"],"0.10.107":["\u{1F3AF} **Recall@3 gap closed \u2014 the moat proof got sharper (the head-to-head that matters)**"," \u{1F50D} External-corpus Recall@3 **82.1% \u2192 98.2%** \xB7 Precision@1 **80.4%** \xB7 MRR **89.0%** \u2014 now ahead of flat-file memory on every metric"," \u{1F9EC} Root-cause fix: documents are no longer indexed with cross-lingual synonyms (the symmetric-expansion bug inflated any doc containing a common word ~28\xD7, burying topic-specific lessons). Queries still expand \u2014 a \u65E5\u672C\u8A9E query still finds English lessons."," \u2696\uFE0F Reranker now compresses BM25 with score^0.3 before applying lesson quality, so a proven success can overtake a text-similar failed attempt even when the distractor scores 5\u20136\xD7 higher in raw BM25"," \u{1F6E1}\uFE0F CI bench gate widened to both home + external corpora with committed floors (`npm run bench:gate`) \u2014 recall quality can never silently regress again"," \u{1F4CA} 121 MCP tools"],"0.10.98":['\u{1F310} **Model-Neutrality as Feature (W9) \u2014 "Bring your own model, keep your brain."**'," \u{1F50C} New `brain_portability()` \u2014 shows your Brain ID, all compatible MCP clients, and ready-to-paste config snippets for each; proves the same Brain works in Claude, Cursor, Copilot, Windsurf, Cline, Zed and more"," \u{1F9E0} Your lessons, crystals, and predictions are model-agnostic \u2014 no vendor lock-in at the memory layer",' \u{1F4D6} New docs: cachly.dev/docs/model-neutral \u2014 "Same Brain, Any Model" guide with live config examples'," \u{1F4CA} 121 MCP tools (new: `brain_portability`)"],"0.10.97":['\u{1F4A0} **Team Crystallize (W8) \u2014 the team-wide, causal counter to per-user "Dreaming"**'," \u{1F9EC} New `team_crystallize()` \u2014 surfaces fixes that 2+ teammates *independently converged on*, the one thing a single-user memory structurally can't build",' \u{1F9E9} Cross-person clustering: groups structurally similar problems across people & namespaces (e.g. "pool exhaustion" solved the same way in payments, auth & db)',' \u{1F465} Each pattern names who converged \u2014 instant "ask @alice and @bob, they both hit this"'," \u{1F48E} Shows up in `crystal_view` alongside your per-brain crystal"," \u{1F4CA} 120 MCP tools (new: `team_crystallize`)"],"0.10.96":["\u{1F510} **Roles & Team-Scopes now ENFORCED (W6) \u2014 the enterprise governance layer**"," \u{1F6E1}\uFE0F `team_confirm` is now reviewer-gated, `team_learn` blocks viewers (recall-only) \u2014 roles stop being cosmetic the moment an admin is assigned"," \u{1F4DC} New `team_audit` tool \u2014 immutable, admin-only trail of every role change & lesson confirmation, for compliance & security reviews"," \u{1F513} Zero impact on open teams: governance activates only once you bootstrap an admin; before that everything works exactly as before"," \u{1F4CA} 119 MCP tools (new: `team_audit`)"],"0.10.95":["\u{1F9E0} **Domain Brain Marketplace (W10) \u2014 bootstrap your Brain with curated community knowledge**"," \u{1F6D2} `brain_marketplace()` \u2014 browse installable packs of high-trust lessons by domain: \u2638\uFE0F Kubernetes, \u{1F510} Auth, \u{1F5C4}\uFE0F Database, \u269B\uFE0F React, \u{1F4B3} Payments & more",' \u{1F4E6} `brain_install(slug="k8s")` \u2014 merges a domain\'s verified lessons into your Brain; live in `smart_recall` instantly, even offline',' \u{1F6E1}\uFE0F Idempotent + non-destructive: installed lessons are tagged `source:"marketplace:<slug>"` and NEVER override your own'," \u{1F50C} New gRPC `Subscribe` RPC \u2014 agents get new lessons streamed live the moment they're learned (completes the M2M loop with `Learn`)"," \u{1F4CA} 118 MCP tools (new: `brain_marketplace`, `brain_install`)"],"0.10.94":['\u{1F91D} **Person\u2194Person Collaboration Graph (W5) \u2014 "Frag X und Y, die haben das zusammen gel\xF6st"**'," \u{1F578}\uFE0F New `brain_collab_pairs()` tool: shows every contributor pair who've touched the same files or recalled each other's lessons \u2014 ideal for onboarding and bus-factor analysis"," \u{1F4E1} `smart_recall` now wires CKG `collaborates` edges live when cross-author reuse fires \u2014 collaboration graph grows with every team recall"," \u26A0\uFE0F Bus-factor section: flags solo contributors whose knowledge no teammate has yet recalled"," \u{1F4CA} 116 MCP tools (new: `brain_collab_pairs`)"],"0.10.93":['\u{1F5FA}\uFE0F **`brain_plan` \u2014 your Brain goes from "what did we learn?" to "what should I do?"**',` \u{1F9ED} Give it a task you're about to start ("upgrade Postgres 14\u219216") and it returns an ordered, grounded action plan: ranked failure modes to avoid, proven fix steps (dependency-aware, with commands), and a pre-flight checklist \u2014 all from your own lessons`,' \u{1F52C} Generative layer on the CKG: where `brain_predict` answers "what might fail?", `brain_plan` answers "what, in what order?"'," \u{1F4CA} 115 MCP tools (new: `brain_plan`)"],"0.10.92":["\u{1F44B} **Welcome-back digest \u2014 re-entry after a week away now leads with what changed**"," \u{1F331} `session_start` detects a gap \u2265 7 days and surfaces how many lessons your Brain gained while you were gone (git, CI & teammates kept it learning), with the freshest topics"," \u{1F9E0} Zero extra latency \u2014 the digest is computed from data session_start already loads"," \u{1F50C} New gRPC `Learn` RPC (M2M write path) \u2014 agents & CI can now teach the Brain directly, byte-compatible with the MCP lesson format"," \u{1F4CA} 115 MCP tools"],"0.10.91":["\u{1F550} **Lesson-anchored time attribution \u2014 every recall shows when it was learned and how much it saves**",` \u{1F4A1} "Brain saved you" banner now includes: when the lesson was learned (e.g. "12 May"), estimated original debug cost by severity (critical=2h, major=1h, minor=20min), and team attribution when a teammate's lesson fires`,' \u{1F4C5} Origin date formatted as "12 May" (same year) or "12 May 2024" (different year) \u2014 no clutter',' \u{1F465} Cross-author recalls now show "@author" on the same banner line \u2014 the "team knowledge reuse" value is front-and-center'," \u{1F4CA} 115 MCP tools"],"0.10.90":["\u{1F4CA} **External benchmark corpus v2 \u2014 the proof is now statistically solid**"," \u{1F9EA} Expanded from 8 queries \u2192 61 lessons / 56 queries across 10 real-world engineering domains (k8s, DB, auth, CI, frontend, API, payments, observability, network, Node.js, security, infra)"," \u2694\uFE0F 10 adversarial distractors added \u2014 failure lessons that share the exact same vocabulary as the query, forcing the quality reranker to earn its lift"," \u{1F4C8} Results on the larger corpus: cachly +2.9% Precision@1 vs flat-file, +12.5% vs raw BM25 baseline \u2014 on a harder dataset, not an easy one"," \u{1F4CA} 115 MCP tools"],"0.10.89":["\u26A1 **One-command onboarding \u2014 `autopilot` is now the single canonical setup**"," \u{1F680} Every surface (README, docs, emails, dashboard, blog) now leads with `npx @cachly-dev/mcp-server@latest autopilot` \u2014 one command signs you in, configures every editor, and bootstraps from git",' \u{1F9F9} Retired the split-brain instructions (legacy `@cachly-dev/init` wrapper + the old "three steps") so there\'s exactly one thing to copy-paste'," \u{1F527} Fixed a build-breaking duplicate `export` on buildClaudeMdBlock that failed CI on v0.10.88"," \u{1F522} Version hygiene \u2014 package.json, server.json, lockfile and MCP_VERSION resynced (server.json/lockfile were stuck at 0.10.85)"," \u{1F4CA} 115 MCP tools"],"0.10.88":["\u2705 **Honest setup + tested config writer (v0.10.88)**",' \u{1F512} setup/autopilot now report the truth: if no editor config could be written it exits non-zero with the exact failures instead of falsely claiming "Brain is ready"'," \u{1F4CA} New setup_config_write_failed telemetry \u2014 permission/path failures that block activation are now visible in reporting"," \u{1F9EA} 24 new unit tests for the config writer (buildServerEnv, buildMcpConfig, mergeMcpConfig, buildClaudeMdBlock) \u2014 the merge logic that must never clobber your other MCP servers is now regression-guarded"," \u{1F4CA} 115 MCP tools"],"0.10.87":["\u{1F310} **Multi-editor auth persistence + full activation telemetry (v0.10.87)**"," \u2705 JWT + instance_id now persisted to Cursor (`~/.cursor/mcp.json`) and Windsurf configs on auth \u2014 no more infinite re-auth for non-Claude-Code users",' \u{1F4E1} `device_flow_failed(reason="timeout")` now fires when sign-in window expires \u2014 blind spot in the funnel is gone'," \u{1F4E1} `auto_provision_failed` now fires on network errors too (was only HTTP non-2xx)"," \u{1F4E1} `brain_from_git_failed` fires with error reason when auto-bootstrap throws \u2014 no more empty brain with no explanation",' \u2728 Git bootstrap shows lesson count in session_start: "Brain bootstrapped \u2014 23 lessons loaded" \u2014 the WOW moment'," \u{1F527} API: McpEvent stores brain quality metrics (fixes/features/refactors/total) \u2014 git learning quality now measurable"," \u{1F4CA} 115 MCP tools"],"0.10.86":["\u{1F6E1}\uFE0F **Zero-friction activation \u2014 your Brain self-heals into existence**"," \u{1F527} Auto-provision now runs on *any* tool call, not just at sign-in \u2014 if instance creation ever fails once, the next call recovers it automatically"," \u{1F91D} Parallel tool calls on startup are coalesced into one resolve (no more duplicate-instance races)",' \u{1F4AC} Clearer "instance still starting" message \u2014 leads with "just retry", no manual config needed'," \u{1F4C8} New activation-funnel telemetry: install \u2192 sign-in \u2192 provision, so silent churn is visible"," \u{1F4CA} 115 MCP tools"],"0.10.85":["\u{1F680} **One-command onboarding \u2014 `npx @cachly-dev/mcp-server@latest autopilot`**"," \u26A1 Single command does it all: auth \u2192 instance \u2192 every editor config \u2192 CLAUDE.md \u2192 Brain bootstrap \u2192 health"," \u{1F331} Seeds the 16-lesson starter corpus when git history is empty \u2014 your first smart_recall hits instantly"," \u{1F916} Fully automatic (zero prompts); `setup` remains for interactive, pick-your-editors onboarding"],"0.10.84":["\u{1F916} **M2M & agent-ecosystem reach \u2014 cachly for every caller, human or machine**"," \u{1F511} OAuth2 `client_credentials` grant \u2014 set CACHLY_CLIENT_ID + CACHLY_CLIENT_SECRET for fully headless auth (CI, agents, AI-to-AI)"," \u{1F5C2}\uFE0F `npx ... tool-specs --format=openai|anthropic|langchain` \u2014 export all 121 tools in any framework's dialect"," \u{1F310} `npx ... openapi` \u2014 OpenAPI 3.1 doc (1 POST path per tool) for Assistants / codegen / Postman"," \u{1F9EA} 14 new tests: client_credentials helpers, all four spec dialects, OpenAPI required-body inference"],"0.10.83":["\u{1F9E0} **Brain Viz \u2014 3D graph export**"," \u{1F310} `brain_graph(instance_id)` \u2014 exports the Causal Knowledge Graph as a render-ready {nodes, links} payload"," \u{1F3A8} Schema `cachly.brain_graph/v1`: node kinds (concept/person/file/service) with color groups + size, edges with confidence"," \u{1F5A5}\uFE0F Consumed verbatim by the 3D frontend (react-force-graph-3d / three.js) \u2014 the visual brain map",' \u{1F50E} Filters: `domain`, `min_confidence`, `max_nodes` (with truncation flag), `format="summary"`'," \u{1F9EA} 10 tests: kind detection, dangling-edge pruning, confidence/domain filters, schema contract"," \u{1F4CA} 115 MCP tools"],"0.10.82":["\u{1F4E1} **Telemetry API contracts \u2014 dashboard ingest pipeline prepared**"," \u{1F5C2}\uFE0F `src/telemetry-types.ts` \u2014 canonical event types + resolved event format (TelemetryEventRaw / TelemetryEventResolved)"," \u{1F510} `user_fingerprint` \u2014 non-reversible JWT sub hash, PII-free user clustering for dashboard"," \u{1F4CA} `metrics` block on key events: smart_recall (hit/topic), brain_from_git (fixes/features/total), brain_seed_starter (seeded_count)"," \u{1F6A6} Internal API contract documented: GET /internal/telemetry/stream \u2192 TelemetryEventResolved[]"],"0.10.81":["\u23F1\uFE0F **Onboarding-Bench \u2014 time-to-first-recall, now measured**"," \u{1F4D0} `npm run bench:onboarding` \u2014 cold (empty) vs seeded (starter) first-query hit rate via the real search engine"," \u{1F4CA} Result: first-query hit@1 **0% \u2192 87.5%**, hit@3 **0% \u2192 100%**, MRR **0% \u2192 93.8%**"," \u{1F6E1}\uFE0F CI-defended in `onboarding-bench.test.ts` (cold must answer 0%, seeded thresholds enforced)"," \u{1F4CB} `PLAN-DASHBOARD.md` \u2014 full build spec for the external Team-Knowledge-Reuse dashboard (separate repo)"],"0.10.80":["\u{1F331} **Starter corpus \u2014 first recall in seconds, not sessions**"," \u{1F4DA} `brain_seed_starter(instance_id)` \u2014 seed 16 curated universal lessons (Docker cache, JWT skew, K8s OOM, N+1, cache stampede\u2026)"," \u{1F680} Auto-seeds on first session when git history is empty/shallow \u2014 your first `smart_recall` returns a real hit",' \u{1F6E1}\uFE0F Tagged `source:"starter"`, idempotent, never overrides your own lessons'," \u23F1\uFE0F Directly attacks time-to-first-recall (<2 min goal); stamps `born_at` on seed"," \u{1F9EA} 18 new tests: seeding, idempotency, topic_filter, force, user-lesson protection"," \u{1F4CA} 113 MCP tools"],"0.10.79":["\u{1F310} **Brain Marketplace \u2014 full shareable Brain lifecycle**"," \u{1F4CB} `brain_share_list(instance_id)` \u2014 see all your public shares with lesson counts + share IDs"," \u{1F5D1}\uFE0F `brain_unshare(share_id)` \u2014 revoke a share; link goes dead immediately"," \u{1F50D} `brain_discover(query, topic)` \u2014 search public Brains in the cachly marketplace"," \u{1F4E4} `publish` CLI \u2014 fancy card + share URL; `--public` for discoverable; `--title` custom name"," \u{1F9EA} stress tests: team_expertise_map with 50 contributors, chain import/unshare, discover fallback"," \u{1F4CA} 112 MCP tools"],"0.10.78":["\u{1F310} **Phase 3: Shareable / Public Brains**",' \u{1F4E4} `brain_share(instance_id="...")` \u2014 export a Brain snapshot as a shareable link (public or unlisted)',' \u{1F4E5} `brain_import(instance_id="...", share_id="...")` \u2014 import any public Brain into yours (1-line)'," \u{1F50D} Optional topic_filter, min_confidence, topic_prefix \u2014 precise control over what gets shared/imported"," \u{1F512} dry_run mode on both tools \u2014 preview before committing"," \u{1F9EA} Regression suite added: share handler, buildServerEnv, stdout cleanness"," \u{1F4CA} 109 MCP tools"],"0.10.77":["\u{1FA79} **Frictionless onboarding + first-class self-hosting/BYOK**"," \u{1F680} Editor-launched server now serves all tools even before sign-in \u2014 zero-credential device flow finally triggers on first tool call"," \u{1F512} No more stdout pollution: stdio JSON-RPC stream stays clean when no JWT is set"," \u{1F3E0} `setup --api-url` / `init --api-url` point at a self-hosted backend; URL baked into config only when non-default",' \u{1F9EC} `health` now shows your BYOK embedding provider + accepts cky_ long-lived keys (was a false "invalid token" failure)'],"0.10.76":["\u{1F4CA} **Agent-trace benchmark + editor matrix + setup timer**"," \u{1F4C2} New `agent-traces-corpus.json` \u2014 22 lessons, 15 queries, realistic AI-agent debug patterns"," \u{1F3C6} Benchmark result: **P@1 +66.7%, MRR +9.5% vs flat-file** (adversarial failure-distractors per category)"," \u{1F4CB} README: first-class editor support matrix (Claude Code, Cursor, Windsurf, VSCode, Cline, Continue.dev, Zed)",' \u23F1\uFE0F setup now shows elapsed time + "Brain is ready" banner at the end'],"0.10.75":["\u{1FA79} **Setup hardened \u2014 works from the VSCode plugin & any non-TTY terminal**"," \u{1F50C} `setup` no longer hangs on a non-interactive stdin (VSCode tasks, CI) \u2014 auto-detects + runs in automatic mode"," \u{1F510} Device-flow now uses the API proxy first (the old direct-Keycloak call returned 403) \u2014 sign-in actually completes"," \u{1F310} When auto sign-in is unavailable, the browser opens with a step-by-step API-key guide instead of a silent paste prompt"," \u{1F4CA} Funnel fix: `device_flow_completed` / `device_flow_failed(reason)` now emitted from setup too"],"0.10.73":["\u{1F510} **Team visibility scopes + one-command init + external bench**",' \u{1F195} `team_grant_scope` / `team_scopes` \u2014 scope lessons to a sub-team (group="security"); only members + admins recall them',' \u{1F3F7}\uFE0F `learn_from_attempts(group="...")` \u2014 orthogonal to private; smart_recall enforces it per requester'," \u26A1 `init` is now zero-arg + idempotent (reuses saved creds, only writes what changed, <60s)"," \u{1F4E6} `npm run bench:external` \u2014 prove recall-lift on a third-party-labeled corpus (portable JSON format)"," \u{1F4CA} 107 MCP tools"],"0.10.72":["\u{1F451} **Role model \u2014 admin \xB7 reviewer \xB7 contributor \xB7 viewer (Phase 3)**"," \u{1F195} `team_assign_role` \u2014 establish governance; first call bootstraps, admins manage the rest"," \u{1F195} `team_whoami` \u2014 see your own role and capabilities"," \u{1F195} `team_roster` \u2014 full team role table (\u{1F451}\u{1F6E1}\uFE0F\u270F\uFE0F\u{1F441}\uFE0F)"," \u{1F6E1}\uFE0F `team_confirm` is now role-aware \u2014 admin/reviewer auto-get senior weight; contributor gets peer; no self-promotion"," \u{1F451} Setup CLI now prompts for governance bootstrap (idempotent). 105 MCP tools"],"0.10.71":['\u{1F6E1}\uFE0F **Self-healing auth** \u2014 no more silent "0 recalls because the token quietly died"'," \u267B\uFE0F Near-expiry tokens auto-refresh into a long-lived key while still valid (zero interaction)"," \u{1F501} A rejected (401) call self-heals once and retries before surfacing an error"," \u{1F4E3} If the credential is truly dead, session_start + get_api_status say so plainly + how to fix"],"0.10.70":["\u{1F6F0}\uFE0F **Service/System nodes in the graph (Phase 3)** \u2014 the brain now models running systems",' \u{1F195} `brain_service_map(service="prometheus")` \u2014 who owns it + every failure/fix known',' \u{1F3F7}\uFE0F Tag lessons with `service="..."` (`service_kind="system"` for infra) \u2014 person\u2192operates, file\u2192runs_in edges',` \u{1F6A8} Incident triage: a restarting pod \u2192 instant "who knows this and what's broken before"`," \u{1F4CA} 102 MCP tools"],"0.10.69":["\u{1F4C1} **Personalized context-aware recall (Phase 3)** \u2014 pass `context_files` to `smart_recall`"," \u{1F3AF} Lessons learned on your current files bubble up \u2014 even when the query doesn't name the file"," \u{1F3F7}\uFE0F `\u{1F4C1} context match` badge on every file-boosted result so you know WHY it ranked up"," \u2705 Works alongside keyword, semantic, CKG, and governance signals \u2014 a 6th ranking dimension"],"0.10.68":["\u{1F91D} **Collaboration graph (Phase 3)** \u2014 person\u2194person edges from shared files"," \u{1F465} `brain_who_knows` now shows who the top expert frequently works with",' \u{1F68C} Bus-factor insight: "ask X and Y together \u2014 they solved this on shared files"'," \u{1F6E1}\uFE0F Stability: every network call in the agent hot path is now timeout-bounded"],"0.10.64":["\u{1F4C8} **The three decisive metrics, now measurable**"," \u23F1\uFE0F `brain_metrics()` \u2014 time-to-first-recall, recall-lift, team-knowledge-reuse in one view"," \u{1F465} Cross-author reuse tracked: recall a teammate's lesson \u2192 counted + surfaced inline"," \u{1F6E1}\uFE0F Stability: scans now capped + timed out (a huge keyspace can't hang the agent)"],"0.10.61":["\u{1F3AF} **Phase 3C: 100 MCP tools milestone \u2014 zero-setup knowledge graph**"," \u{1F504} `brain_from_git` now auto-builds Person+File nodes from git history (zero setup!)"," \u{1F50D} `skill_gaps()` \u2014 find domains with unresolved failures, missing attribution"," \u{1F4CA} `brain_coverage()` \u2014 scored 0-100 health report: lessons \xB7 attribution \xB7 file coverage"],"0.10.60":["\u{1F195} **Phase 3B: File map + team overview + visibility**"," \u{1F4C1} `brain_file_map(file_paths=[...])` \u2014 experts + lessons per file before you touch it"," \u{1F5FA}\uFE0F `team_expertise_map()` \u2014 full team skills matrix in one table",' \u{1F512} `visibility: "private"` on `learn_from_attempts` \u2014 private notes never leak to smart_recall'," \u{1F4CA} 98 MCP tools"],"0.10.59":["\u{1F195} **Phase 3A: Org-wide knowledge graph**",' \u{1F465} `brain_who_knows(topic="...")` \u2014 find your team\'s experts on any topic instantly',' \u{1F578}\uFE0F Person + File nodes auto-built from `learn_from_attempts(author="...", file_paths=[...])`'," \u{1F464} Author attribution now shown inline in `smart_recall` results"," \u{1F4CA} 96 MCP tools \xB7 386 tests green"],"0.10.58":["\u{1F9F9} Zero lint warnings \u2014 all unused imports cleaned across every handler","\u2705 Build: 0 errors, 0 warnings \xB7 379 tests green"],"0.10.57":[`\u{1F195} **What's new in v${Fe}:**`," \u{1F527} **Critical fix** \u2014 corrected the npm bin/main entry path (`dist/src/index.js`); 0.10.50\u20130.10.52 shipped a broken entry point"," \u{1F527} Version hygiene \u2014 synced package.json, server.json, lockfile, MCP_VERSION; `latest` now points forward again"," \u2705 Accurate tool count (95) across README, server.json, CLI banners"," \u2705 Includes all Phase 2/3 work: quality reranking, Cachly-Bench, hybrid + CKG recall, team_confirm governance"],"0.10.52":[" \u2705 `smart_recall` \u2014 CKG traversal as Layer 3: finds lessons that FIXED causal-graph-similar problems (\u{1F578}\uFE0F causal graph badge)"," \u2705 Bench corpus expanded: governance adversarial pair proves review-boost end-to-end (+22% P@1 headline)"," \u{1F527} Import cleanup: unused symbols removed from brain.ts (no functional change)"," \u{1F4A1} `smart_recall` now shows keyword / semantic / CKG / hybrid match type for every result"],"0.10.51":[" \u2705 `team_confirm` \u2014 human review raises lesson recall ranking (\u{1F6E1}\uFE0F senior / \u2714\uFE0F peer)"," \u2705 Governance-aware recall \u2014 confirmed lessons outrank unreviewed auto-learned entries"],"0.10.50":[" \u2705 `smart_recall` \u2014 unified keyword + semantic hybrid list (one ranked result, not two sections)",' \u2705 `smart_recall` \u2014 "Brain saved you here" banner surfaces time saved inline per proven lesson'," \u2705 Quality reranking \u2014 proven successes outrank symptom-dense failures (+11% Precision@1)"," \u2705 Cachly-Bench \u2014 IR benchmark with CI regression guard (see BENCH.md for the proof)"," \u{1F527} Contradiction resolution now persisted to Redis (90-day TTL)"," \u{1F4A1} Run `smart_recall` to see your Brain's recall quality in action"],"0.10.49":[" \u2705 `brain_from_git` \u2014 auto-seed your Brain from git history in seconds"," \u2705 `brain_predict_failures` \u2014 predict CI/build failures before they happen"," \u2705 VS Code extension \u2014 Brain status bar, ambient learning, CodeLens hints"," \u2705 Team Brain \u2014 share lessons across your whole engineering team"," \u{1F527} Stability \u2014 auto-expiring memory keys, longer provisioning wait, robust recall"]},lo=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","lesson_verified","session_start","session_start_summary","session_end","session_ping","session_handoff","auto_learn_session","brain_who_knows","brain_file_map","team_expertise_map","skill_gaps","brain_coverage","brain_metrics","brain_service_map","brain_collab_pairs","brain_portability","brain_changelog","brain_set_pref","brain_get_pref"]),mn=dn("/billing","upgrade"),St=new Map,Ct=new Set,gn=1680*60*60;function yn(ie=new Date){return`cachly:quota:recalls:${ie.toISOString().slice(0,7)}`}async function xt(ie){try{const H=yn();await ie.incr(H)===1&&await ie.expire(H,gn)}catch{}}function Tt(ie){return`cachly:stats:drei-ausgaenge:${ie}`}async function Nt(ie,H,U){try{await ie.hincrby(Tt(H),U,1)}catch{}}async function Et(ie,H){const U=St.get(ie);if(U&&U.expiresAt>Date.now())return U.gate;try{const ue=await H(`/api/v1/instances/${ie}/memory`),g=ue?.recall_limit??-1,t=ue?.total_recall_count??0,s={reached:g>0&&t>=g,limit:g,used:t,goodwillMessage:ue?.goodwill_message,notice:ue?.notice};return St.set(ie,{gate:s,expiresAt:Date.now()+6e4}),s}catch{return{reached:!1,limit:-1,used:0}}}const wn={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function uo(ie,H,U,ue){const g=await _n(ie,H,U,ue),t=wn[ie];if(t&&typeof g=="string")try{Ps(String(H.instance_id??""),String(H[t]??""),g.length)}catch{}return g}async function _n(ie,H,U,ue){switch(ie){case"learn_from_attempts":{const{instance_id:g,topic:t,outcome:s,what_worked:k,what_failed:m="",context:d="",severity:$="major",file_paths:a=[],commands:u=[],tags:M=[],depends_on:o=[],author:_="",visibility:S="team",service:h="",service_kind:i="service",group:x="",grund:b="",ersetzt:w="",gilt_ab:A=""}=H,{what_worked:I,what_failed:e="",context:j=""}=ls({what_worked:k,what_failed:m,context:d}),v=await U(g),oe=new Date,ce=oe.toISOString(),he=A&&!Number.isNaN(Date.parse(String(A)))?new Date(String(A)):oe,R=Ke(I,he),E=Ke(e,he),J=Ke(j,he),se=Ge(I,he)+Ge(e,he)+Ge(j,he),V=an({uebergeben:_,umgebung:process.env.CACHLY_AUTHOR,git:on(process.env.CACHLY_WORKSPACE??process.cwd())});let n="";try{n=nn(await v.get(`cachly:prefs:${tn}:${g}`))}catch{}const r=rn(V.autor,n),p=sn(V);if(S!=="private"&&await ts(v,g))return ss(v,t,{topic:t,outcome:s,what_worked:R,what_failed:E,context:J,severity:$,file_paths:a,commands:u,tags:M,depends_on:o,...r?{author:r}:{},source:bt(),...h?{service:h}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:S,recall_count:0,ts:ce,confidence:1,version:3});const c=t.split(":")[0],l=It[c],T=[];if(l)for(const D of l.required)D==="commands"&&u.length===0&&T.push(`\u{1F4CB} ${l.hint}`);let B=!1,P=0,N,W=[];const ee=await v.get(`cachly:lesson:best:${t}`),le=String(b??"").trim();if(ee&&!le)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
- `);if(ee)try{const D=JSON.parse(ee);P=D.recall_count??0,N=D.last_recalled_at,W=D.audit_trail??[],W.push({ts:ce,action:"updated",prev_outcome:D.outcome,grund:le}),W.length>20&&(W=W.slice(-20)),B=!0;const L=[];if(D.outcome==="success"&&s==="failure"?L.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):D.outcome==="failure"&&s==="success"&&L.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),L.length>0){W[W.length-1].action="contradiction-resolved";try{const ae=me(t),te=me(`resolution:${t}`);await ge(v,ae,"contradicts",te,!1)}catch{}try{const ae=`cachly:contradictions:${t}`,te=D.outcome==="success"&&s==="failure"?"kept-success":"overwrote-failure";await v.rpush(ae,JSON.stringify({ts:ce,prev_outcome:D.outcome,new_outcome:s,direction:te})),await v.ltrim(ae,-50,-1),await v.expire(ae,180*86400)}catch{}L.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else W=[{ts:ce,action:"created"}];const we=[];if(s==="failure"){const D=[],L=v.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((te,Z)=>{L.on("data",X=>D.push(...X)),L.on("end",te),L.on("error",Z)});const ae=t.split(/[:\-_]/).filter(te=>te.length>2);for(const te of D.slice(0,50)){const Z=await v.get(te);if(Z)try{const X=JSON.parse(Z);if(X.outcome!=="success")continue;const z=(X.topic??"").split(/[:\-_]/).filter(pe=>pe.length>2);if(ae.filter(pe=>z.includes(pe)).length>=1&&X.topic!==t){we.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${X.topic}\` (success, ${X.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${X.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${X.topic}", ..., severity="critical")\``);break}}catch{}}}for(const D of o){const L=`cachly:dep:${D}`,ae=await v.get(L),te=O(ae,[]);te.includes(t)||te.push(t),await v.set(L,JSON.stringify(te),"EX",90*86400)}const ne={topic:t,outcome:s,what_worked:R,what_failed:E,context:J,severity:$,file_paths:a,commands:u,tags:M,depends_on:o,...r?{author:r}:{},source:bt(),...h?{service:h}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:S,recall_count:P,...N?{last_recalled_at:N}:{},...A&&!Number.isNaN(Date.parse(String(A)))?{gilt_ab:new Date(String(A)).toISOString()}:{},ts:ce,verified_at:s==="success"||s==="partial"?ce:void 0,confidence:1,audit_trail:W,version:3},fe=String(w??"").trim();let f="",y=null;fe===t&&fe?f="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":fe&&(y=await v.get(`cachly:lesson:best:${fe}`),y?O(y,{}).ersetzt===t?(y=null,f=`\u26A0\uFE0F \`${fe}\` ersetzt bereits \`${t}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${fe}\` entfernen und danach hier setzen.`):ne.ersetzt=fe:f=`\u26A0\uFE0F Die zu ersetzende Lektion \`${fe}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let C="";if(!fe)try{const D=X=>{const z=O(X.content,{});return{topic:z.topic??X.key.slice(19),what_worked:z.what_worked}},[L,ae]=await Promise.all([ze(v,["cachly:lesson:best:*"],`${t} ${R}`.slice(0,300),5),ns(v,["cachly:lesson:best:*"],a??[])]),te=new Set,Z=[...L,...ae].filter(X=>X.key.startsWith("cachly:lesson:best:")).filter(X=>!te.has(X.key)&&te.add(X.key)).map(D);C=ms(t,R,Z)??""}catch{}if(s==="failure")try{const L=(await v.lrange(ft(g),0,199)).map(Z=>O(Z,{ts:"",frage:"",geliefert:[]})).filter(Z=>Z.ts!==""),ae=(await ze(v,["cachly:lesson:best:*"],`${t} ${E||R}`.slice(0,300),5)).filter(Z=>Z.key.startsWith("cachly:lesson:best:")).map(Z=>{const X=O(Z.content,{});return{topic:X.topic??Z.key.slice(19),what_worked:X.what_worked}}),te=_s(t,String(E||""),L,ae);await v.hincrby(pt(g),te,1)}catch{}const Y=$s([R,E,d].filter(Boolean).join(" ").slice(0,2e3));Y&&(ne.entscheidung=Y);const q=JSON.stringify(ne);v.set(`cachly:stats:born_at:${g}`,ce,"EX",365*86400,"NX").catch(()=>{});const F=`cachly:lessons:${t}`;await v.rpush(F,q),await v.ltrim(F,-100,-1),await v.expire(F,gs*86400);let G=!1;if(s==="success"||s==="partial"?(await v.set(`cachly:lesson:best:${t}`,q),G=!0):ee||(await v.set(`cachly:lesson:best:${t}`,q),G=!0),y&&G)try{const D=JSON.parse(y);D.ersetzt_durch=t,D.gilt_bis=ce,D.ersetzt_am=ce,le&&(D.ersetzt_grund=le.slice(0,200)),await v.set(`cachly:lesson:best:${fe}`,JSON.stringify(D))}catch{}G&&ct(),G&&Ne()&&(await v.sadd(Ae,t).catch(()=>{}),(async()=>{const D=O(q,{});try{const L=await $e(De(D),{geduld:"lang"});if(L?.length&&(await v.set(`${ut}${t}`,Ee(L)),await v.srem(Ae,t).catch(()=>{})),Se==="cachly"||Se==="ollama")try{const ae=await $e(De(D),{geduld:"lang",modell:Oe});ae?.length&&await v.set(`${Ie}${t}`,Ee(ae))}catch{}}catch(L){await v.sadd(Ae,t).catch(()=>{}),await Be(v,qe,`Volltext-Vektor nicht geschrieben (${Se}): ${Je(L)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const L=await $e(us(t),{geduld:"lang"});L?.length&&await v.set(`${ht}${t}`,Ee(L))}catch(L){await Be(v,qe,`Namens-Vektor nicht geschrieben (${Se}): ${Je(L)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await hs(v,t,D,L=>$e(L,{geduld:"lang"}))}catch(L){await Be(v,qe,`Eingaenge nicht geschrieben (${Se}): ${Je(L)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await At(v,t,3)})());try{const D="cachly:session:decision-log",L=JSON.stringify({ts:ce,topic:t,outcome:s,what_worked:R.slice(0,120)});await v.rpush(D,L),await v.ltrim(D,-50,-1)}catch{}let Q=null;try{const D=me(t),L=t.split(":")[0]??"unknown";await xe(v,D,L,L);for(const te of M){const Z=me(`tag:${te}`);await xe(v,Z,"tag","tag"),await ge(v,D,"co-occurs",Z,s==="success",s==="partial")}for(const te of o){const Z=me(te);await ge(v,D,"requires",Z,!0)}if((L==="fix"||L==="debug")&&(s==="success"||s==="partial")){const te=E||J||"",Z=te?We(te):null;if(Z){const X=me(`problem:${Z}`);await xe(v,X,"problem","problem"),await ge(v,D,"fixes",X,s==="success",s==="partial")}}if(s==="failure"&&(E||R)){const Z=We(E||R);if(Z){const X=me(`cause:${Z}`);await xe(v,X,"cause","cause"),await ge(v,D,"causes",X,!1)}}if(s==="failure"){const te=await v.smembers(`cachly:ckg:idx:from:${D}`);for(const Z of te){const X=await v.get(Z);if(!X)continue;const z=O(X,null);if(z&&z.edgeType==="fixes"&&z.confidence>.7&&z.trials>=3){Q=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${z.confidence.toFixed(2)}, n=${z.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${D}")\` to review.`;const re=`cachly:ckg:conflict:${D}`;await v.set(re,JSON.stringify({topic:t,concept_id:D,detected_at:new Date().toISOString(),fix_confidence:z.confidence,fix_trials:z.trials,failure_outcome:s,reported_by:r||"unknown",what_failed:E||"",resolved:!1}),"EX",3600*24*90)}}}if(s==="success"&&(L==="fix"||L==="debug")){const te=await v.smembers(`cachly:ckg:idx:from:${D}`);for(const Z of te.slice(0,10)){const X=await v.get(Z);if(!X)continue;const z=O(X,null);if(!z||z.edgeType!=="fixes")continue;const re=await v.smembers(`cachly:ckg:idx:from:${z.to}`);for(const pe of re.slice(0,5)){const _e=await v.get(pe);if(!_e)continue;const be=O(_e,null);be&&be.edgeType==="co-occurs"&&(be.successes=(be.successes||0)+.1,be.trials=(be.trials||0)+.1,be.confidence=(be.successes+1)/(be.trials+2),be.last_updated=new Date().toISOString(),await v.set(pe,JSON.stringify(be)))}}}if(Math.random()<.01){const te=Date.now()-7776e6,Z=await v.smembers(`cachly:ckg:idx:from:${D}`);for(const X of Z){const z=await v.get(X);if(!z)continue;const re=O(z,null);re&&re.trials<3&&re.last_updated&&new Date(re.last_updated).getTime()<te&&(re.confidence=re.confidence*.9,re.last_updated=new Date().toISOString(),await v.set(X,JSON.stringify(re)))}}}catch{}if(r){v.set(`cachly:agents:active:${r}`,JSON.stringify({author:r,last_topic:t,last_outcome:s,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const D=t.split(":")[0]??"unknown",L=await Ot(v,kt(r),D),ae=me(t);await ge(v,L,"authored",ae,s==="success",s==="partial");for(const te of a.slice(0,8)){const Z=await st(v,te);await ge(v,L,"touched",Z,!0),await Pt(v,Z,L)}}catch{}}if(h&&typeof h=="string"&&h.trim())try{const D=t.split(":")[0]??"unknown",L=i==="system"?"system":"service",ae=await jt(v,h.trim(),D,L),te=me(t);if(await ge(v,te,"affects",ae,s==="success",s==="partial"),r){const Z=`person:${me(kt(r))}`;await ge(v,Z,"operates",ae,!0)}for(const Z of a.slice(0,8)){const X=`file:${me(Z)}`;await ge(v,X,"runs_in",ae,!0)}}catch{}if(r&&(s==="success"||s==="partial")){const D={topic:t,outcome:s,what_worked:R,what_failed:E??"",severity:$,author:r,file_paths:a,commands:u,tags:[...new Set([...M,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},L=`cachly:lessons:${t}`;v.rpush(L,JSON.stringify(D)).catch(()=>{})}return[`${s==="success"?"\u2705":s==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${B?"updated":"stored"}:** \`${t}\` (${s}) ${$==="critical"?"\u{1F534}":$==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${$}`,Q??"","",`**What worked:** ${R}`,E?`**What failed:** ${E}`:"",J?`**Context:** ${J}`:"",a.length>0?`**Files:** ${a.map(D=>`\`${D}\``).join(", ")}`:"",u.length>0?`**Commands:** ${u.map(D=>`\`${D}\``).join(", ")}`:"",M.length>0?`**Tags:** ${M.map(D=>`#${D}`).join(" ")}`:"","",B?`\u267B\uFE0F Updated (recall count: ${P} \xB7 audit entries: ${W.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,r&&(s==="success"||s==="partial")?`\u{1F465} Auto-shared with team (by _${r}_${V.quelle!=="uebergeben"?` \xB7 aus ${V.quelle}`:""}) \u2014 visible in \`team_recall\``:"",p??"",o.length>0?`\u{1F517} Depends on: ${o.map(D=>`\`${D}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",C,y&&G?le?`\u21B7 Ersetzt \`${fe}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${fe}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin. Ohne \`grund\` steht dort 'Grund nicht erfasst' \u2014 eine Zeile (warum die alte falsch war) macht den Verweis pruefbar.`:f,...T,...we,se>0?`\u{1F5D3}\uFE0F ${se} relative Zeitangabe${se===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(oe.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",ln(R)??""].filter(D=>D!=="").join(`
3
- `)}case"lesson_verified":{const{instance_id:g}=H,t=await U(g),s=new Date().toISOString(),k=Bt(H,s);if(!k.ok)return[`\u26A0\uFE0F ${k.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
4
- `);const m=k.eintrag,d=`cachly:lesson:best:${m.topic}`,$=await t.get(d);if(!$)return`\u{1F4ED} Keine Lektion \`${m.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const a=O($,{});return await t.set(d,JSON.stringify(zt(a,m))),ct(),m.haelt?[`\u2705 \`${m.topic}\` ist wieder frisch \u2014 geprueft am ${s.slice(0,10)}.`,m.geprueft_mit?` geprueft mit: \`${m.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht."].filter(Boolean).join(`
1
+ import{execSync as Qe}from"node:child_process";import{createRequire as et}from"node:module";import{calculateConfidence as Re,confidenceBadge as Mt,STRUCTURED_TEMPLATES as It,CONFIDENCE_WARN_VALUE as tt,CONFIDENCE_STALE_VALUE as Dt,CONFIDENCE_WARN_DAYS as Rt}from"../confidence.js";import{kurzfassenHinweis as Lt}from"../antwort-hinweis.js";import{pruefeMeldung as Bt,wendeAn as zt}from"../pruefung-melden.js";import{ckgSlug as me,extractProblemConcept as We,ckgUpsertNode as xe,ckgUpdateEdge as ge,ckgUpsertPersonNode as Ot,ckgUpsertFileNode as st,ckgRecordCollaboration as Pt,ckgUpsertServiceNode as jt}from"../ckg.js";import{safeJsonParse as O,scanKeys as ve,leseOderNull as Ce,darfHeraus as Te}from"../utils.js";import{ersparteMinuten as nt,istStarterLektion as Le,zaehltAlsErsparnis as ot}from"../wertbeitrag.js";import{lessonPreviewLines as Me,trimTo as Ft}from"../lesson-preview.js";import{normalisiereZeit as Ge,zaehleZeitangaben as Ke}from"../zeit-normalisieren.js";import{abstentionSatz as Wt,alterssatzFuerBelegte as Gt,beurteileTreffer as Kt,istBelegt as Ht}from"../abstention.js";import{meldeEinmal as He,meldeUndVermerke as Be,fehlerText as Je,OHNE_VEKTOREN as Jt,OHNE_DIENST as qt,OHNE_FRAGEVEKTOR as Ut,SINNPFAD_ABBRUCH as Vt,OHNE_SCHREIBVEKTOR as qe}from"../aussetzer.js";import{versuchStart as Yt,neueKennung as Zt,wendeZuteilungAn as Xt,schliesseVersuchAb as Qt}from"../versuch.js";function at(ie,q,V){if(ie.includes("lesson:best:")){const g=O(q,{});if(g&&typeof g=="object"&&(g.what_worked||g.what_failed||g.commands?.length))return Me(g,{maxChars:V,indent:" "})}const ue=Ft(q,V);return ue?[ue]:[]}import{getRole as Ue,ROLE_BADGE as es,getScopes as it,lessonVisibleToScope as rt,reviewModeEnabled as ts,storeLessonProposal as ss}from"./team.js";import{keywordSearch as ze,treffeUeberDateipfad as ns,wortindexEntwerten as ct,tokenize as Ve,splitMultiQuery as os,levenshtein as as,indexVocab as lt}from"../search.js";import{rerankByQuality as is,qualityMultiplier as rs,extractLessonQuality as cs}from"../rerank.js";import{computeEmbedding as $e,hasEmbedProvider as Ne,EMBED_PROVIDER as Se}from"../embeddings.js";import{repariereFelder as ls}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as ut,NAME_VEKTOR_PRAEFIX as ht,ZWEIT_VEKTOR_PRAEFIX as Ie,packe as Ee,textFuerVektor as De,textFuerNamensVektor as us,Vektorbestand as Ye}from"../bedeutung.js";import{schreibeEingaenge as hs,Eingangsbestand as ds}from"../eingaenge.js";import{Seltenheitsbestand as fs}from"../seltenheitsbestand.js";import{spurLegen as ps}from"../spuren.js";import{schlageErsetzungVor as ms}from"../ersetzung-vorschlag.js";const Ae="cachly:vek:nachtrag",gs=365;import{etikettenFuer as ys,lieferJournalSchluessel as dt,JOURNAL_DECKEL as ws}from"../etiketten.js";import{klassifiziereFehlschlag as _s,suchProtokollSchluessel as ft,trichterSchluessel as pt,SUCH_DECKEL as bs}from"../recall-trichter.js";import{leiteEntscheidungAb as $s,entscheidungsZeile as mt}from"../entscheidung-ableiten.js";import{bewerteTopf as vs,spreizeImTopf as gt,reichereAn as ks,inhaltsWoerter as yt,grobStamm as Ss,GEWICHTE as Cs,knapperSiegSatz as xs}from"../rangfolge.js";import{pruefeWirkung as Ts,werteAus as Ns,lehrwert as Es,leiteAb as As}from"../wirkungsspur.js";import{merkeSuchlauf as wt}from"../suchstatistik.js";import{schreibeTopfNotiz as Ms,topfProtokollAktiv as Is}from"../topf-protokoll.js";import{SINN_TOPF as Ds,EINGANG_SCHWELLE as Rs,EINGANG_SORTIER_GEWICHT as Ls,ZWEIT_MODELL as Oe,ZWEIT_GEWICHT as Bs,ZWEIT_MINDESTDECKUNG as _t,NAHDUPLIKAT_SCHWELLE as zs}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as bt,quelleZeile as Os}from"../herkunft.js";import{merkeRecall as Ps,sitzungsKosten as js,vergissSitzungsKosten as Fs,kostenZeilen as Ws}from"../sitzungs-kosten.js";const ye=new Ye,Ze=new Ye(6e4,ht),Pe=new Ye(6e4,Ie),Xe=new ds,je=new fs,$t=Ds,Gs=Rs,Ks=Ls;import{upgradeNudge as Hs}from"../upgrade-nudge.js";import{recallTiefe as vt,TIEFE_VOLL as Js,TIEFE_VOLL_MEHRTHEMIG as qs}from"../recall-tiefe.js";import{nutzungInWorten as Us,nutzungsSchluessel as Vs,verdichte as Ys}from"../werkzeug-nutzung.js";import{inWorten as Zs,lieferBild as Xs,lieferSchluessel as Qs,trefferSchluessel as en}from"../geliefert.js";import{COAUTHOR_PREF_KEY as tn,autorHinweis as sn,coautorAus as nn,echterGitLeser as on,ermittleAutor as an,mitCoautor as rn,nurMensch as kt}from"../autor.js";import{TOOLS as cn}from"../tools.js";import{vorspannHinweis as ln}from"../vorspann.js";import{autorAbzeichen as un,fremdanteil as hn}from"../autor-abzeichen.js";import{cachlyUrl as dn}from"../cachly-url.js";const Fe=(()=>{try{const ie=et(import.meta.url);for(const q of["../../../package.json","../../package.json"])try{const V=ie(q);if(V.name==="@cachly-dev/mcp-server"&&V.version)return V.version}catch{}}catch{}return"0.10.100"})(),fn=()=>{try{return et(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},pn={"0.10.119":["\u{1F50D} **Explainable briefings \u2014 provenance in every warning**"," \u{1F4CE} `/briefing` warnings now carry `outcome`, `author`, `learned_at` and `matched_on` (the context tokens that triggered the warning) \u2014 editors can show WHY a fix hint fired, not just what it claims.",' \u{1F9F0} VS Code 0.12.0 uses this: severity + confidence in the toast, full lesson card with provenance, "Not helpful" per-file suppression, reviewable CLS auto-learns.'," \u{1F9F9} CI docs now describe exactly what ships: scan mode uses the REST `/scan` endpoint, the GitLab template covers learn/scan/confirm."],"0.10.115":["\u{1F527} **`brain_get_pref` + `brain_set_pref` \u2014 persistent Brain preferences**"," \u{1F4D6} `brain_get_pref` reads back any stored preference (omit key to list all)."," \u270F\uFE0F `brain_set_pref` saves a preference to Redis \u2014 survives restarts, scoped per Brain instance.",' \u{1F4A1} Known key: `auto_changelog` \u2014 set to "false" to silence the new-lessons digest at session_start.'," \u{1F4CA} 140 MCP tools"],"0.10.114":["\u{1F4CB} **`brain_changelog` \u2014 weekly knowledge digest in one call**"," \u{1F4C5} Generates a grouped Markdown changelog of lessons learned in the last N days."," \u{1F465} Grouped by topic category, annotated with author, recall count, and confidence \u2014 paste directly into standup or Slack."," \u2699\uFE0F Params: `days` (default 7), `max_lessons` (default 30), `include_failures` (default true)."," \u{1F4CA} 138 MCP tools"],"0.10.113":["\u{1F4C8} **Week-over-week savings trend in `cache_stats`**"," \u{1F4C5} `cache_stats` now shows **7-day hits** + **WoW trend %** (e.g. `+23.0% vs prev week`) so ROI momentum is visible, not just the cumulative total."," \u2B07\uFE0F Goes red (\u{1F4C9}) on drops, green (\u{1F4C8}) on growth \u2014 first week always shows +100% (new)."," \u{1F527} Backed by new `CountHitsInWindow` repo method + `hits_last_7d`, `hits_prev_7d`, `week_over_week_pct` fields in `SavingsEstimate`."," \u{1F4CA} 137 MCP tools"],"0.10.112":["\u2699\uFE0F **Configurable cost_per_call_usd \u2014 accurate ROI for any LLM**"," \u{1F4A1} New `set_cost_per_call` tool: set your real per-call cost (claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001) so savings estimates in `cache_stats` reflect your actual bill."," \u{1F527} New API: `PUT /api/v1/instances/:id/cost-per-call` \u2014 persisted per instance, used by `cache_stats`, org savings, and SSE analytics stream."," \u{1F4CA} 137 MCP tools"],"0.10.111":["\u{1F3E2} **Org-wide ROI + GitLab CI \u2014 the CFO number, aggregated**"," \u{1F4B0} `cache_org_stats` now shows **org-wide Tokenmaxxing ROI**: total savings summed across every instance in your org, monthly projection, top-5 instances by savings. One number for the whole team."," \u{1F50C} Backed by new API endpoint `GET /api/v1/orgs/:id/savings` (org members only)"," \u{1F98A} GitLab CI integration: `brain-from-ci-gitlab.yml` \u2014 two `.post` jobs (on_success/on_failure), same helper script, pipeline never fails because of Brain push"," \u{1F6E0}\uFE0F GitHub Action template fixed: `secrets.*` in job-level `if` is invalid \u2014 guard removed (helper script skips cleanly on missing secrets)"," \u{1F4CA} 136 MCP tools"],"0.10.110":["\u{1F3E2} **Zero friction: ROI-Projektor, Org-Shared-Cache, CI ready-to-paste**"," \u{1F4C8} `cache_stats` \u2014 zero-hit projection calculator: shows expected monthly savings for 5/10/20-dev teams before a single cache hit lands. ROI visible from day 1."," \u{1F3E2} New `cache_org_stats` \u2014 shared org-level cache stats across multiple instances. Convention-based (`org:{id}:sem`), zero API changes needed."," \u{1F517} `cache_set`/`cache_get` now accept optional `org_id` \u2014 write to personal + org namespace, fall back to org on miss. Fully backwards-compatible."," \u{1F4CB} Copy-paste CI integration: `brain-from-ci-action.yml` \u2192 Brain self-calibrates confidence on every GitHub Actions run. No config beyond two repo secrets."," \u{1F4CA} 136 MCP tools"],"0.10.109":["\u{1F4B0} **Tokenmaxxing ROI + Closed-loop CI learning**"," \u{1F4CA} `cache_stats` now shows a **Tokenmaxxing ROI** section \u2014 total tokens saved, monthly cost projection, and top 3 most-cached prompts. Finally a number you can show the CFO."," \u{1F504} New `brain_from_ci` \u2014 bulk-ingest CI history into the Brain (red\u2192green = learned fix, green\u2192red = CKG causal edge). The brain_from_git equivalent for CI. Bootstrap the Brain from your CI logs in one call."," \u{1F4CA} 134 MCP tools"],"0.10.108":["\u{1F9E0} **Focused briefing + trustworthy autopilot**"," \u{1F3AF} New `session_start_summary` \u2014 top-N focused briefing by topic. Scores lessons by relevance \xD7 confidence + recall_count + severity + recency. Use it for a quick pre-brief without loading the full Brain.",' \u{1F91D} Autopilot template now explains the data flow upfront ("your own Brain, EU-hosted, no third parties") \u2014 no more friction with cautious AI assistants during onboarding'," \u{1F4CA} 132 MCP tools"],"0.10.107":["\u{1F3AF} **Recall@3 gap closed \u2014 the moat proof got sharper (the head-to-head that matters)**"," \u{1F50D} External-corpus Recall@3 **82.1% \u2192 98.2%** \xB7 Precision@1 **80.4%** \xB7 MRR **89.0%** \u2014 now ahead of flat-file memory on every metric"," \u{1F9EC} Root-cause fix: documents are no longer indexed with cross-lingual synonyms (the symmetric-expansion bug inflated any doc containing a common word ~28\xD7, burying topic-specific lessons). Queries still expand \u2014 a \u65E5\u672C\u8A9E query still finds English lessons."," \u2696\uFE0F Reranker now compresses BM25 with score^0.3 before applying lesson quality, so a proven success can overtake a text-similar failed attempt even when the distractor scores 5\u20136\xD7 higher in raw BM25"," \u{1F6E1}\uFE0F CI bench gate widened to both home + external corpora with committed floors (`npm run bench:gate`) \u2014 recall quality can never silently regress again"," \u{1F4CA} 121 MCP tools"],"0.10.98":['\u{1F310} **Model-Neutrality as Feature (W9) \u2014 "Bring your own model, keep your brain."**'," \u{1F50C} New `brain_portability()` \u2014 shows your Brain ID, all compatible MCP clients, and ready-to-paste config snippets for each; proves the same Brain works in Claude, Cursor, Copilot, Windsurf, Cline, Zed and more"," \u{1F9E0} Your lessons, crystals, and predictions are model-agnostic \u2014 no vendor lock-in at the memory layer",' \u{1F4D6} New docs: cachly.dev/docs/model-neutral \u2014 "Same Brain, Any Model" guide with live config examples'," \u{1F4CA} 121 MCP tools (new: `brain_portability`)"],"0.10.97":['\u{1F4A0} **Team Crystallize (W8) \u2014 the team-wide, causal counter to per-user "Dreaming"**'," \u{1F9EC} New `team_crystallize()` \u2014 surfaces fixes that 2+ teammates *independently converged on*, the one thing a single-user memory structurally can't build",' \u{1F9E9} Cross-person clustering: groups structurally similar problems across people & namespaces (e.g. "pool exhaustion" solved the same way in payments, auth & db)',' \u{1F465} Each pattern names who converged \u2014 instant "ask @alice and @bob, they both hit this"'," \u{1F48E} Shows up in `crystal_view` alongside your per-brain crystal"," \u{1F4CA} 120 MCP tools (new: `team_crystallize`)"],"0.10.96":["\u{1F510} **Roles & Team-Scopes now ENFORCED (W6) \u2014 the enterprise governance layer**"," \u{1F6E1}\uFE0F `team_confirm` is now reviewer-gated, `team_learn` blocks viewers (recall-only) \u2014 roles stop being cosmetic the moment an admin is assigned"," \u{1F4DC} New `team_audit` tool \u2014 immutable, admin-only trail of every role change & lesson confirmation, for compliance & security reviews"," \u{1F513} Zero impact on open teams: governance activates only once you bootstrap an admin; before that everything works exactly as before"," \u{1F4CA} 119 MCP tools (new: `team_audit`)"],"0.10.95":["\u{1F9E0} **Domain Brain Marketplace (W10) \u2014 bootstrap your Brain with curated community knowledge**"," \u{1F6D2} `brain_marketplace()` \u2014 browse installable packs of high-trust lessons by domain: \u2638\uFE0F Kubernetes, \u{1F510} Auth, \u{1F5C4}\uFE0F Database, \u269B\uFE0F React, \u{1F4B3} Payments & more",' \u{1F4E6} `brain_install(slug="k8s")` \u2014 merges a domain\'s verified lessons into your Brain; live in `smart_recall` instantly, even offline',' \u{1F6E1}\uFE0F Idempotent + non-destructive: installed lessons are tagged `source:"marketplace:<slug>"` and NEVER override your own'," \u{1F50C} New gRPC `Subscribe` RPC \u2014 agents get new lessons streamed live the moment they're learned (completes the M2M loop with `Learn`)"," \u{1F4CA} 118 MCP tools (new: `brain_marketplace`, `brain_install`)"],"0.10.94":['\u{1F91D} **Person\u2194Person Collaboration Graph (W5) \u2014 "Frag X und Y, die haben das zusammen gel\xF6st"**'," \u{1F578}\uFE0F New `brain_collab_pairs()` tool: shows every contributor pair who've touched the same files or recalled each other's lessons \u2014 ideal for onboarding and bus-factor analysis"," \u{1F4E1} `smart_recall` now wires CKG `collaborates` edges live when cross-author reuse fires \u2014 collaboration graph grows with every team recall"," \u26A0\uFE0F Bus-factor section: flags solo contributors whose knowledge no teammate has yet recalled"," \u{1F4CA} 116 MCP tools (new: `brain_collab_pairs`)"],"0.10.93":['\u{1F5FA}\uFE0F **`brain_plan` \u2014 your Brain goes from "what did we learn?" to "what should I do?"**',` \u{1F9ED} Give it a task you're about to start ("upgrade Postgres 14\u219216") and it returns an ordered, grounded action plan: ranked failure modes to avoid, proven fix steps (dependency-aware, with commands), and a pre-flight checklist \u2014 all from your own lessons`,' \u{1F52C} Generative layer on the CKG: where `brain_predict` answers "what might fail?", `brain_plan` answers "what, in what order?"'," \u{1F4CA} 115 MCP tools (new: `brain_plan`)"],"0.10.92":["\u{1F44B} **Welcome-back digest \u2014 re-entry after a week away now leads with what changed**"," \u{1F331} `session_start` detects a gap \u2265 7 days and surfaces how many lessons your Brain gained while you were gone (git, CI & teammates kept it learning), with the freshest topics"," \u{1F9E0} Zero extra latency \u2014 the digest is computed from data session_start already loads"," \u{1F50C} New gRPC `Learn` RPC (M2M write path) \u2014 agents & CI can now teach the Brain directly, byte-compatible with the MCP lesson format"," \u{1F4CA} 115 MCP tools"],"0.10.91":["\u{1F550} **Lesson-anchored time attribution \u2014 every recall shows when it was learned and how much it saves**",` \u{1F4A1} "Brain saved you" banner now includes: when the lesson was learned (e.g. "12 May"), estimated original debug cost by severity (critical=2h, major=1h, minor=20min), and team attribution when a teammate's lesson fires`,' \u{1F4C5} Origin date formatted as "12 May" (same year) or "12 May 2024" (different year) \u2014 no clutter',' \u{1F465} Cross-author recalls now show "@author" on the same banner line \u2014 the "team knowledge reuse" value is front-and-center'," \u{1F4CA} 115 MCP tools"],"0.10.90":["\u{1F4CA} **External benchmark corpus v2 \u2014 the proof is now statistically solid**"," \u{1F9EA} Expanded from 8 queries \u2192 61 lessons / 56 queries across 10 real-world engineering domains (k8s, DB, auth, CI, frontend, API, payments, observability, network, Node.js, security, infra)"," \u2694\uFE0F 10 adversarial distractors added \u2014 failure lessons that share the exact same vocabulary as the query, forcing the quality reranker to earn its lift"," \u{1F4C8} Results on the larger corpus: cachly +2.9% Precision@1 vs flat-file, +12.5% vs raw BM25 baseline \u2014 on a harder dataset, not an easy one"," \u{1F4CA} 115 MCP tools"],"0.10.89":["\u26A1 **One-command onboarding \u2014 `autopilot` is now the single canonical setup**"," \u{1F680} Every surface (README, docs, emails, dashboard, blog) now leads with `npx @cachly-dev/mcp-server@latest autopilot` \u2014 one command signs you in, configures every editor, and bootstraps from git",' \u{1F9F9} Retired the split-brain instructions (legacy `@cachly-dev/init` wrapper + the old "three steps") so there\'s exactly one thing to copy-paste'," \u{1F527} Fixed a build-breaking duplicate `export` on buildClaudeMdBlock that failed CI on v0.10.88"," \u{1F522} Version hygiene \u2014 package.json, server.json, lockfile and MCP_VERSION resynced (server.json/lockfile were stuck at 0.10.85)"," \u{1F4CA} 115 MCP tools"],"0.10.88":["\u2705 **Honest setup + tested config writer (v0.10.88)**",' \u{1F512} setup/autopilot now report the truth: if no editor config could be written it exits non-zero with the exact failures instead of falsely claiming "Brain is ready"'," \u{1F4CA} New setup_config_write_failed telemetry \u2014 permission/path failures that block activation are now visible in reporting"," \u{1F9EA} 24 new unit tests for the config writer (buildServerEnv, buildMcpConfig, mergeMcpConfig, buildClaudeMdBlock) \u2014 the merge logic that must never clobber your other MCP servers is now regression-guarded"," \u{1F4CA} 115 MCP tools"],"0.10.87":["\u{1F310} **Multi-editor auth persistence + full activation telemetry (v0.10.87)**"," \u2705 JWT + instance_id now persisted to Cursor (`~/.cursor/mcp.json`) and Windsurf configs on auth \u2014 no more infinite re-auth for non-Claude-Code users",' \u{1F4E1} `device_flow_failed(reason="timeout")` now fires when sign-in window expires \u2014 blind spot in the funnel is gone'," \u{1F4E1} `auto_provision_failed` now fires on network errors too (was only HTTP non-2xx)"," \u{1F4E1} `brain_from_git_failed` fires with error reason when auto-bootstrap throws \u2014 no more empty brain with no explanation",' \u2728 Git bootstrap shows lesson count in session_start: "Brain bootstrapped \u2014 23 lessons loaded" \u2014 the WOW moment'," \u{1F527} API: McpEvent stores brain quality metrics (fixes/features/refactors/total) \u2014 git learning quality now measurable"," \u{1F4CA} 115 MCP tools"],"0.10.86":["\u{1F6E1}\uFE0F **Zero-friction activation \u2014 your Brain self-heals into existence**"," \u{1F527} Auto-provision now runs on *any* tool call, not just at sign-in \u2014 if instance creation ever fails once, the next call recovers it automatically"," \u{1F91D} Parallel tool calls on startup are coalesced into one resolve (no more duplicate-instance races)",' \u{1F4AC} Clearer "instance still starting" message \u2014 leads with "just retry", no manual config needed'," \u{1F4C8} New activation-funnel telemetry: install \u2192 sign-in \u2192 provision, so silent churn is visible"," \u{1F4CA} 115 MCP tools"],"0.10.85":["\u{1F680} **One-command onboarding \u2014 `npx @cachly-dev/mcp-server@latest autopilot`**"," \u26A1 Single command does it all: auth \u2192 instance \u2192 every editor config \u2192 CLAUDE.md \u2192 Brain bootstrap \u2192 health"," \u{1F331} Seeds the 16-lesson starter corpus when git history is empty \u2014 your first smart_recall hits instantly"," \u{1F916} Fully automatic (zero prompts); `setup` remains for interactive, pick-your-editors onboarding"],"0.10.84":["\u{1F916} **M2M & agent-ecosystem reach \u2014 cachly for every caller, human or machine**"," \u{1F511} OAuth2 `client_credentials` grant \u2014 set CACHLY_CLIENT_ID + CACHLY_CLIENT_SECRET for fully headless auth (CI, agents, AI-to-AI)"," \u{1F5C2}\uFE0F `npx ... tool-specs --format=openai|anthropic|langchain` \u2014 export all 121 tools in any framework's dialect"," \u{1F310} `npx ... openapi` \u2014 OpenAPI 3.1 doc (1 POST path per tool) for Assistants / codegen / Postman"," \u{1F9EA} 14 new tests: client_credentials helpers, all four spec dialects, OpenAPI required-body inference"],"0.10.83":["\u{1F9E0} **Brain Viz \u2014 3D graph export**"," \u{1F310} `brain_graph(instance_id)` \u2014 exports the Causal Knowledge Graph as a render-ready {nodes, links} payload"," \u{1F3A8} Schema `cachly.brain_graph/v1`: node kinds (concept/person/file/service) with color groups + size, edges with confidence"," \u{1F5A5}\uFE0F Consumed verbatim by the 3D frontend (react-force-graph-3d / three.js) \u2014 the visual brain map",' \u{1F50E} Filters: `domain`, `min_confidence`, `max_nodes` (with truncation flag), `format="summary"`'," \u{1F9EA} 10 tests: kind detection, dangling-edge pruning, confidence/domain filters, schema contract"," \u{1F4CA} 115 MCP tools"],"0.10.82":["\u{1F4E1} **Telemetry API contracts \u2014 dashboard ingest pipeline prepared**"," \u{1F5C2}\uFE0F `src/telemetry-types.ts` \u2014 canonical event types + resolved event format (TelemetryEventRaw / TelemetryEventResolved)"," \u{1F510} `user_fingerprint` \u2014 non-reversible JWT sub hash, PII-free user clustering for dashboard"," \u{1F4CA} `metrics` block on key events: smart_recall (hit/topic), brain_from_git (fixes/features/total), brain_seed_starter (seeded_count)"," \u{1F6A6} Internal API contract documented: GET /internal/telemetry/stream \u2192 TelemetryEventResolved[]"],"0.10.81":["\u23F1\uFE0F **Onboarding-Bench \u2014 time-to-first-recall, now measured**"," \u{1F4D0} `npm run bench:onboarding` \u2014 cold (empty) vs seeded (starter) first-query hit rate via the real search engine"," \u{1F4CA} Result: first-query hit@1 **0% \u2192 87.5%**, hit@3 **0% \u2192 100%**, MRR **0% \u2192 93.8%**"," \u{1F6E1}\uFE0F CI-defended in `onboarding-bench.test.ts` (cold must answer 0%, seeded thresholds enforced)"," \u{1F4CB} `PLAN-DASHBOARD.md` \u2014 full build spec for the external Team-Knowledge-Reuse dashboard (separate repo)"],"0.10.80":["\u{1F331} **Starter corpus \u2014 first recall in seconds, not sessions**"," \u{1F4DA} `brain_seed_starter(instance_id)` \u2014 seed 16 curated universal lessons (Docker cache, JWT skew, K8s OOM, N+1, cache stampede\u2026)"," \u{1F680} Auto-seeds on first session when git history is empty/shallow \u2014 your first `smart_recall` returns a real hit",' \u{1F6E1}\uFE0F Tagged `source:"starter"`, idempotent, never overrides your own lessons'," \u23F1\uFE0F Directly attacks time-to-first-recall (<2 min goal); stamps `born_at` on seed"," \u{1F9EA} 18 new tests: seeding, idempotency, topic_filter, force, user-lesson protection"," \u{1F4CA} 113 MCP tools"],"0.10.79":["\u{1F310} **Brain Marketplace \u2014 full shareable Brain lifecycle**"," \u{1F4CB} `brain_share_list(instance_id)` \u2014 see all your public shares with lesson counts + share IDs"," \u{1F5D1}\uFE0F `brain_unshare(share_id)` \u2014 revoke a share; link goes dead immediately"," \u{1F50D} `brain_discover(query, topic)` \u2014 search public Brains in the cachly marketplace"," \u{1F4E4} `publish` CLI \u2014 fancy card + share URL; `--public` for discoverable; `--title` custom name"," \u{1F9EA} stress tests: team_expertise_map with 50 contributors, chain import/unshare, discover fallback"," \u{1F4CA} 112 MCP tools"],"0.10.78":["\u{1F310} **Phase 3: Shareable / Public Brains**",' \u{1F4E4} `brain_share(instance_id="...")` \u2014 export a Brain snapshot as a shareable link (public or unlisted)',' \u{1F4E5} `brain_import(instance_id="...", share_id="...")` \u2014 import any public Brain into yours (1-line)'," \u{1F50D} Optional topic_filter, min_confidence, topic_prefix \u2014 precise control over what gets shared/imported"," \u{1F512} dry_run mode on both tools \u2014 preview before committing"," \u{1F9EA} Regression suite added: share handler, buildServerEnv, stdout cleanness"," \u{1F4CA} 109 MCP tools"],"0.10.77":["\u{1FA79} **Frictionless onboarding + first-class self-hosting/BYOK**"," \u{1F680} Editor-launched server now serves all tools even before sign-in \u2014 zero-credential device flow finally triggers on first tool call"," \u{1F512} No more stdout pollution: stdio JSON-RPC stream stays clean when no JWT is set"," \u{1F3E0} `setup --api-url` / `init --api-url` point at a self-hosted backend; URL baked into config only when non-default",' \u{1F9EC} `health` now shows your BYOK embedding provider + accepts cky_ long-lived keys (was a false "invalid token" failure)'],"0.10.76":["\u{1F4CA} **Agent-trace benchmark + editor matrix + setup timer**"," \u{1F4C2} New `agent-traces-corpus.json` \u2014 22 lessons, 15 queries, realistic AI-agent debug patterns"," \u{1F3C6} Benchmark result: **P@1 +66.7%, MRR +9.5% vs flat-file** (adversarial failure-distractors per category)"," \u{1F4CB} README: first-class editor support matrix (Claude Code, Cursor, Windsurf, VSCode, Cline, Continue.dev, Zed)",' \u23F1\uFE0F setup now shows elapsed time + "Brain is ready" banner at the end'],"0.10.75":["\u{1FA79} **Setup hardened \u2014 works from the VSCode plugin & any non-TTY terminal**"," \u{1F50C} `setup` no longer hangs on a non-interactive stdin (VSCode tasks, CI) \u2014 auto-detects + runs in automatic mode"," \u{1F510} Device-flow now uses the API proxy first (the old direct-Keycloak call returned 403) \u2014 sign-in actually completes"," \u{1F310} When auto sign-in is unavailable, the browser opens with a step-by-step API-key guide instead of a silent paste prompt"," \u{1F4CA} Funnel fix: `device_flow_completed` / `device_flow_failed(reason)` now emitted from setup too"],"0.10.73":["\u{1F510} **Team visibility scopes + one-command init + external bench**",' \u{1F195} `team_grant_scope` / `team_scopes` \u2014 scope lessons to a sub-team (group="security"); only members + admins recall them',' \u{1F3F7}\uFE0F `learn_from_attempts(group="...")` \u2014 orthogonal to private; smart_recall enforces it per requester'," \u26A1 `init` is now zero-arg + idempotent (reuses saved creds, only writes what changed, <60s)"," \u{1F4E6} `npm run bench:external` \u2014 prove recall-lift on a third-party-labeled corpus (portable JSON format)"," \u{1F4CA} 107 MCP tools"],"0.10.72":["\u{1F451} **Role model \u2014 admin \xB7 reviewer \xB7 contributor \xB7 viewer (Phase 3)**"," \u{1F195} `team_assign_role` \u2014 establish governance; first call bootstraps, admins manage the rest"," \u{1F195} `team_whoami` \u2014 see your own role and capabilities"," \u{1F195} `team_roster` \u2014 full team role table (\u{1F451}\u{1F6E1}\uFE0F\u270F\uFE0F\u{1F441}\uFE0F)"," \u{1F6E1}\uFE0F `team_confirm` is now role-aware \u2014 admin/reviewer auto-get senior weight; contributor gets peer; no self-promotion"," \u{1F451} Setup CLI now prompts for governance bootstrap (idempotent). 105 MCP tools"],"0.10.71":['\u{1F6E1}\uFE0F **Self-healing auth** \u2014 no more silent "0 recalls because the token quietly died"'," \u267B\uFE0F Near-expiry tokens auto-refresh into a long-lived key while still valid (zero interaction)"," \u{1F501} A rejected (401) call self-heals once and retries before surfacing an error"," \u{1F4E3} If the credential is truly dead, session_start + get_api_status say so plainly + how to fix"],"0.10.70":["\u{1F6F0}\uFE0F **Service/System nodes in the graph (Phase 3)** \u2014 the brain now models running systems",' \u{1F195} `brain_service_map(service="prometheus")` \u2014 who owns it + every failure/fix known',' \u{1F3F7}\uFE0F Tag lessons with `service="..."` (`service_kind="system"` for infra) \u2014 person\u2192operates, file\u2192runs_in edges',` \u{1F6A8} Incident triage: a restarting pod \u2192 instant "who knows this and what's broken before"`," \u{1F4CA} 102 MCP tools"],"0.10.69":["\u{1F4C1} **Personalized context-aware recall (Phase 3)** \u2014 pass `context_files` to `smart_recall`"," \u{1F3AF} Lessons learned on your current files bubble up \u2014 even when the query doesn't name the file"," \u{1F3F7}\uFE0F `\u{1F4C1} context match` badge on every file-boosted result so you know WHY it ranked up"," \u2705 Works alongside keyword, semantic, CKG, and governance signals \u2014 a 6th ranking dimension"],"0.10.68":["\u{1F91D} **Collaboration graph (Phase 3)** \u2014 person\u2194person edges from shared files"," \u{1F465} `brain_who_knows` now shows who the top expert frequently works with",' \u{1F68C} Bus-factor insight: "ask X and Y together \u2014 they solved this on shared files"'," \u{1F6E1}\uFE0F Stability: every network call in the agent hot path is now timeout-bounded"],"0.10.64":["\u{1F4C8} **The three decisive metrics, now measurable**"," \u23F1\uFE0F `brain_metrics()` \u2014 time-to-first-recall, recall-lift, team-knowledge-reuse in one view"," \u{1F465} Cross-author reuse tracked: recall a teammate's lesson \u2192 counted + surfaced inline"," \u{1F6E1}\uFE0F Stability: scans now capped + timed out (a huge keyspace can't hang the agent)"],"0.10.61":["\u{1F3AF} **Phase 3C: 100 MCP tools milestone \u2014 zero-setup knowledge graph**"," \u{1F504} `brain_from_git` now auto-builds Person+File nodes from git history (zero setup!)"," \u{1F50D} `skill_gaps()` \u2014 find domains with unresolved failures, missing attribution"," \u{1F4CA} `brain_coverage()` \u2014 scored 0-100 health report: lessons \xB7 attribution \xB7 file coverage"],"0.10.60":["\u{1F195} **Phase 3B: File map + team overview + visibility**"," \u{1F4C1} `brain_file_map(file_paths=[...])` \u2014 experts + lessons per file before you touch it"," \u{1F5FA}\uFE0F `team_expertise_map()` \u2014 full team skills matrix in one table",' \u{1F512} `visibility: "private"` on `learn_from_attempts` \u2014 private notes never leak to smart_recall'," \u{1F4CA} 98 MCP tools"],"0.10.59":["\u{1F195} **Phase 3A: Org-wide knowledge graph**",' \u{1F465} `brain_who_knows(topic="...")` \u2014 find your team\'s experts on any topic instantly',' \u{1F578}\uFE0F Person + File nodes auto-built from `learn_from_attempts(author="...", file_paths=[...])`'," \u{1F464} Author attribution now shown inline in `smart_recall` results"," \u{1F4CA} 96 MCP tools \xB7 386 tests green"],"0.10.58":["\u{1F9F9} Zero lint warnings \u2014 all unused imports cleaned across every handler","\u2705 Build: 0 errors, 0 warnings \xB7 379 tests green"],"0.10.57":[`\u{1F195} **What's new in v${Fe}:**`," \u{1F527} **Critical fix** \u2014 corrected the npm bin/main entry path (`dist/src/index.js`); 0.10.50\u20130.10.52 shipped a broken entry point"," \u{1F527} Version hygiene \u2014 synced package.json, server.json, lockfile, MCP_VERSION; `latest` now points forward again"," \u2705 Accurate tool count (95) across README, server.json, CLI banners"," \u2705 Includes all Phase 2/3 work: quality reranking, Cachly-Bench, hybrid + CKG recall, team_confirm governance"],"0.10.52":[" \u2705 `smart_recall` \u2014 CKG traversal as Layer 3: finds lessons that FIXED causal-graph-similar problems (\u{1F578}\uFE0F causal graph badge)"," \u2705 Bench corpus expanded: governance adversarial pair proves review-boost end-to-end (+22% P@1 headline)"," \u{1F527} Import cleanup: unused symbols removed from brain.ts (no functional change)"," \u{1F4A1} `smart_recall` now shows keyword / semantic / CKG / hybrid match type for every result"],"0.10.51":[" \u2705 `team_confirm` \u2014 human review raises lesson recall ranking (\u{1F6E1}\uFE0F senior / \u2714\uFE0F peer)"," \u2705 Governance-aware recall \u2014 confirmed lessons outrank unreviewed auto-learned entries"],"0.10.50":[" \u2705 `smart_recall` \u2014 unified keyword + semantic hybrid list (one ranked result, not two sections)",' \u2705 `smart_recall` \u2014 "Brain saved you here" banner surfaces time saved inline per proven lesson'," \u2705 Quality reranking \u2014 proven successes outrank symptom-dense failures (+11% Precision@1)"," \u2705 Cachly-Bench \u2014 IR benchmark with CI regression guard (see BENCH.md for the proof)"," \u{1F527} Contradiction resolution now persisted to Redis (90-day TTL)"," \u{1F4A1} Run `smart_recall` to see your Brain's recall quality in action"],"0.10.49":[" \u2705 `brain_from_git` \u2014 auto-seed your Brain from git history in seconds"," \u2705 `brain_predict_failures` \u2014 predict CI/build failures before they happen"," \u2705 VS Code extension \u2014 Brain status bar, ambient learning, CodeLens hints"," \u2705 Team Brain \u2014 share lessons across your whole engineering team"," \u{1F527} Stability \u2014 auto-expiring memory keys, longer provisioning wait, robust recall"]},lo=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","lesson_verified","session_start","session_start_summary","session_end","session_ping","session_handoff","auto_learn_session","brain_who_knows","brain_file_map","team_expertise_map","skill_gaps","brain_coverage","brain_metrics","brain_service_map","brain_collab_pairs","brain_portability","brain_changelog","brain_set_pref","brain_get_pref"]),mn=dn("/billing","upgrade"),St=new Map,Ct=new Set,gn=1680*60*60;function yn(ie=new Date){return`cachly:quota:recalls:${ie.toISOString().slice(0,7)}`}async function xt(ie){try{const q=yn();await ie.incr(q)===1&&await ie.expire(q,gn)}catch{}}function Tt(ie){return`cachly:stats:drei-ausgaenge:${ie}`}async function Nt(ie,q,V){try{await ie.hincrby(Tt(q),V,1)}catch{}}async function Et(ie,q){const V=St.get(ie);if(V&&V.expiresAt>Date.now())return V.gate;try{const ue=await q(`/api/v1/instances/${ie}/memory`),g=ue?.recall_limit??-1,t=ue?.total_recall_count??0,s={reached:g>0&&t>=g,limit:g,used:t,goodwillMessage:ue?.goodwill_message,notice:ue?.notice};return St.set(ie,{gate:s,expiresAt:Date.now()+6e4}),s}catch{return{reached:!1,limit:-1,used:0}}}const wn={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function uo(ie,q,V,ue){const g=await _n(ie,q,V,ue),t=wn[ie];if(t&&typeof g=="string")try{Ps(String(q.instance_id??""),String(q[t]??""),g.length)}catch{}return g}async function _n(ie,q,V,ue){switch(ie){case"learn_from_attempts":{const{instance_id:g,topic:t,outcome:s,what_worked:S,what_failed:m="",context:f="",severity:$="major",file_paths:a=[],commands:u=[],tags:M=[],depends_on:n=[],author:_="",visibility:C="team",service:h="",service_kind:i="service",group:x="",grund:b="",ersetzt:w="",gilt_ab:A=""}=q,{what_worked:I,what_failed:e="",context:F=""}=ls({what_worked:S,what_failed:m,context:f}),k=await V(g),oe=new Date,ce=oe.toISOString(),he=A&&!Number.isNaN(Date.parse(String(A)))?new Date(String(A)):oe,R=Ge(I,he),E=Ge(e,he),H=Ge(F,he),se=Ke(I,he)+Ke(e,he)+Ke(F,he),Y=an({uebergeben:_,umgebung:process.env.CACHLY_AUTHOR,git:on(process.env.CACHLY_WORKSPACE??process.cwd())});let o="";try{o=nn(await k.get(`cachly:prefs:${tn}:${g}`))}catch{}const r=rn(Y.autor,o),p=sn(Y);if(C!=="private"&&await ts(k,g))return ss(k,t,{topic:t,outcome:s,what_worked:R,what_failed:E,context:H,severity:$,file_paths:a,commands:u,tags:M,depends_on:n,...r?{author:r}:{},source:bt(),...h?{service:h}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:C,recall_count:0,ts:ce,confidence:1,version:3});const c=t.split(":")[0],l=It[c],T=[];if(l)for(const D of l.required)D==="commands"&&u.length===0&&T.push(`\u{1F4CB} ${l.hint}`);let B=!1,P=0,N,W=[];const ee=await k.get(`cachly:lesson:best:${t}`),le=String(b??"").trim();if(ee&&!le)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
+ `);if(ee)try{const D=JSON.parse(ee);P=D.recall_count??0,N=D.last_recalled_at,W=D.audit_trail??[],W.push({ts:ce,action:"updated",prev_outcome:D.outcome,grund:le}),W.length>20&&(W=W.slice(-20)),B=!0;const L=[];if(D.outcome==="success"&&s==="failure"?L.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):D.outcome==="failure"&&s==="success"&&L.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),L.length>0){W[W.length-1].action="contradiction-resolved";try{const ae=me(t),te=me(`resolution:${t}`);await ge(k,ae,"contradicts",te,!1)}catch{}try{const ae=`cachly:contradictions:${t}`,te=D.outcome==="success"&&s==="failure"?"kept-success":"overwrote-failure";await k.rpush(ae,JSON.stringify({ts:ce,prev_outcome:D.outcome,new_outcome:s,direction:te})),await k.ltrim(ae,-50,-1),await k.expire(ae,180*86400)}catch{}L.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else W=[{ts:ce,action:"created"}];const we=[];if(s==="failure"){const D=[],L=k.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((te,Z)=>{L.on("data",X=>D.push(...X)),L.on("end",te),L.on("error",Z)});const ae=t.split(/[:\-_]/).filter(te=>te.length>2);for(const te of D.slice(0,50)){const Z=await k.get(te);if(Z)try{const X=JSON.parse(Z);if(X.outcome!=="success")continue;const z=(X.topic??"").split(/[:\-_]/).filter(pe=>pe.length>2);if(ae.filter(pe=>z.includes(pe)).length>=1&&X.topic!==t){we.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${X.topic}\` (success, ${X.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${X.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${X.topic}", ..., severity="critical")\``);break}}catch{}}}for(const D of n){const L=`cachly:dep:${D}`,ae=await k.get(L),te=O(ae,[]);te.includes(t)||te.push(t),await k.set(L,JSON.stringify(te),"EX",90*86400)}const ne={topic:t,outcome:s,what_worked:R,what_failed:E,context:H,severity:$,file_paths:a,commands:u,tags:M,depends_on:n,...r?{author:r}:{},source:bt(),...h?{service:h}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:C,recall_count:P,...N?{last_recalled_at:N}:{},...A&&!Number.isNaN(Date.parse(String(A)))?{gilt_ab:new Date(String(A)).toISOString()}:{},ts:ce,verified_at:s==="success"||s==="partial"?ce:void 0,confidence:1,audit_trail:W,version:3},fe=String(w??"").trim();let d="",y=null;fe===t&&fe?d="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":fe&&(y=await k.get(`cachly:lesson:best:${fe}`),y?O(y,{}).ersetzt===t?(y=null,d=`\u26A0\uFE0F \`${fe}\` ersetzt bereits \`${t}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${fe}\` entfernen und danach hier setzen.`):ne.ersetzt=fe:d=`\u26A0\uFE0F Die zu ersetzende Lektion \`${fe}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let v="";if(!fe)try{const D=X=>{const z=O(X.content,{});return{topic:z.topic??X.key.slice(19),what_worked:z.what_worked}},[L,ae]=await Promise.all([ze(k,["cachly:lesson:best:*"],`${t} ${R}`.slice(0,300),5),ns(k,["cachly:lesson:best:*"],a??[])]),te=new Set,Z=[...L,...ae].filter(X=>X.key.startsWith("cachly:lesson:best:")).filter(X=>!te.has(X.key)&&te.add(X.key)).map(D);v=ms(t,R,Z)??""}catch{}if(s==="failure")try{const L=(await k.lrange(ft(g),0,199)).map(Z=>O(Z,{ts:"",frage:"",geliefert:[]})).filter(Z=>Z.ts!==""),ae=(await ze(k,["cachly:lesson:best:*"],`${t} ${E||R}`.slice(0,300),5)).filter(Z=>Z.key.startsWith("cachly:lesson:best:")).map(Z=>{const X=O(Z.content,{});return{topic:X.topic??Z.key.slice(19),what_worked:X.what_worked}}),te=_s(t,String(E||""),L,ae);await k.hincrby(pt(g),te,1)}catch{}const U=$s([R,E,f].filter(Boolean).join(" ").slice(0,2e3));U&&(ne.entscheidung=U);const K=JSON.stringify(ne);k.set(`cachly:stats:born_at:${g}`,ce,"EX",365*86400,"NX").catch(()=>{});const j=`cachly:lessons:${t}`;await k.rpush(j,K),await k.ltrim(j,-100,-1),await k.expire(j,gs*86400);let J=!1;if(s==="success"||s==="partial"?(await k.set(`cachly:lesson:best:${t}`,K),J=!0):ee||(await k.set(`cachly:lesson:best:${t}`,K),J=!0),y&&J)try{const D=JSON.parse(y);D.ersetzt_durch=t,D.gilt_bis=ce,D.ersetzt_am=ce,le&&(D.ersetzt_grund=le.slice(0,200)),await k.set(`cachly:lesson:best:${fe}`,JSON.stringify(D))}catch{}J&&ct(),J&&Ne()&&(await k.sadd(Ae,t).catch(()=>{}),(async()=>{const D=O(K,{});try{const L=await $e(De(D),{geduld:"lang"});if(L?.length&&(await k.set(`${ut}${t}`,Ee(L)),await k.srem(Ae,t).catch(()=>{})),Se==="cachly"||Se==="ollama")try{const ae=await $e(De(D),{geduld:"lang",modell:Oe});ae?.length&&await k.set(`${Ie}${t}`,Ee(ae))}catch{}}catch(L){await k.sadd(Ae,t).catch(()=>{}),await Be(k,qe,`Volltext-Vektor nicht geschrieben (${Se}): ${Je(L)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const L=await $e(us(t),{geduld:"lang"});L?.length&&await k.set(`${ht}${t}`,Ee(L))}catch(L){await Be(k,qe,`Namens-Vektor nicht geschrieben (${Se}): ${Je(L)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await hs(k,t,D,L=>$e(L,{geduld:"lang"}))}catch(L){await Be(k,qe,`Eingaenge nicht geschrieben (${Se}): ${Je(L)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await At(k,t,3)})());try{const D="cachly:session:decision-log",L=JSON.stringify({ts:ce,topic:t,outcome:s,what_worked:R.slice(0,120)});await k.rpush(D,L),await k.ltrim(D,-50,-1)}catch{}let Q=null;try{const D=me(t),L=t.split(":")[0]??"unknown";await xe(k,D,L,L);for(const te of M){const Z=me(`tag:${te}`);await xe(k,Z,"tag","tag"),await ge(k,D,"co-occurs",Z,s==="success",s==="partial")}for(const te of n){const Z=me(te);await ge(k,D,"requires",Z,!0)}if((L==="fix"||L==="debug")&&(s==="success"||s==="partial")){const te=E||H||"",Z=te?We(te):null;if(Z){const X=me(`problem:${Z}`);await xe(k,X,"problem","problem"),await ge(k,D,"fixes",X,s==="success",s==="partial")}}if(s==="failure"&&(E||R)){const Z=We(E||R);if(Z){const X=me(`cause:${Z}`);await xe(k,X,"cause","cause"),await ge(k,D,"causes",X,!1)}}if(s==="failure"){const te=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const Z of te){const X=await k.get(Z);if(!X)continue;const z=O(X,null);if(z&&z.edgeType==="fixes"&&z.confidence>.7&&z.trials>=3){Q=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${z.confidence.toFixed(2)}, n=${z.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${D}")\` to review.`;const re=`cachly:ckg:conflict:${D}`;await k.set(re,JSON.stringify({topic:t,concept_id:D,detected_at:new Date().toISOString(),fix_confidence:z.confidence,fix_trials:z.trials,failure_outcome:s,reported_by:r||"unknown",what_failed:E||"",resolved:!1}),"EX",3600*24*90)}}}if(s==="success"&&(L==="fix"||L==="debug")){const te=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const Z of te.slice(0,10)){const X=await k.get(Z);if(!X)continue;const z=O(X,null);if(!z||z.edgeType!=="fixes")continue;const re=await k.smembers(`cachly:ckg:idx:from:${z.to}`);for(const pe of re.slice(0,5)){const _e=await k.get(pe);if(!_e)continue;const be=O(_e,null);be&&be.edgeType==="co-occurs"&&(be.successes=(be.successes||0)+.1,be.trials=(be.trials||0)+.1,be.confidence=(be.successes+1)/(be.trials+2),be.last_updated=new Date().toISOString(),await k.set(pe,JSON.stringify(be)))}}}if(Math.random()<.01){const te=Date.now()-7776e6,Z=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const X of Z){const z=await k.get(X);if(!z)continue;const re=O(z,null);re&&re.trials<3&&re.last_updated&&new Date(re.last_updated).getTime()<te&&(re.confidence=re.confidence*.9,re.last_updated=new Date().toISOString(),await k.set(X,JSON.stringify(re)))}}}catch{}if(r){k.set(`cachly:agents:active:${r}`,JSON.stringify({author:r,last_topic:t,last_outcome:s,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const D=t.split(":")[0]??"unknown",L=await Ot(k,kt(r),D),ae=me(t);await ge(k,L,"authored",ae,s==="success",s==="partial");for(const te of a.slice(0,8)){const Z=await st(k,te);await ge(k,L,"touched",Z,!0),await Pt(k,Z,L)}}catch{}}if(h&&typeof h=="string"&&h.trim())try{const D=t.split(":")[0]??"unknown",L=i==="system"?"system":"service",ae=await jt(k,h.trim(),D,L),te=me(t);if(await ge(k,te,"affects",ae,s==="success",s==="partial"),r){const Z=`person:${me(kt(r))}`;await ge(k,Z,"operates",ae,!0)}for(const Z of a.slice(0,8)){const X=`file:${me(Z)}`;await ge(k,X,"runs_in",ae,!0)}}catch{}if(r&&(s==="success"||s==="partial")){const D={topic:t,outcome:s,what_worked:R,what_failed:E??"",severity:$,author:r,file_paths:a,commands:u,tags:[...new Set([...M,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},L=`cachly:lessons:${t}`;k.rpush(L,JSON.stringify(D)).catch(()=>{})}return[`${s==="success"?"\u2705":s==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${B?"updated":"stored"}:** \`${t}\` (${s}) ${$==="critical"?"\u{1F534}":$==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${$}`,Q??"","",`**What worked:** ${R}`,E?`**What failed:** ${E}`:"",H?`**Context:** ${H}`:"",a.length>0?`**Files:** ${a.map(D=>`\`${D}\``).join(", ")}`:"",u.length>0?`**Commands:** ${u.map(D=>`\`${D}\``).join(", ")}`:"",M.length>0?`**Tags:** ${M.map(D=>`#${D}`).join(" ")}`:"","",B?`\u267B\uFE0F Updated (recall count: ${P} \xB7 audit entries: ${W.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,r&&(s==="success"||s==="partial")?`\u{1F465} Auto-shared with team (by _${r}_${Y.quelle!=="uebergeben"?` \xB7 aus ${Y.quelle}`:""}) \u2014 visible in \`team_recall\``:"",p??"",n.length>0?`\u{1F517} Depends on: ${n.map(D=>`\`${D}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",v,y&&J?le?`\u21B7 Ersetzt \`${fe}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${fe}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin. Ohne \`grund\` steht dort 'Grund nicht erfasst' \u2014 eine Zeile (warum die alte falsch war) macht den Verweis pruefbar.`:d,...T,...we,se>0?`\u{1F5D3}\uFE0F ${se} relative Zeitangabe${se===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(oe.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",ln(R)??""].filter(D=>D!=="").join(`
3
+ `)}case"lesson_verified":{const{instance_id:g}=q,t=await V(g),s=new Date().toISOString(),S=Bt(q,s);if(!S.ok)return[`\u26A0\uFE0F ${S.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
4
+ `);const m=S.eintrag,f=`cachly:lesson:best:${m.topic}`,$=await t.get(f);if(!$)return`\u{1F4ED} Keine Lektion \`${m.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const a=O($,{});return await t.set(f,JSON.stringify(zt(a,m))),ct(),m.haelt?[`\u2705 \`${m.topic}\` ist wieder frisch \u2014 geprueft am ${s.slice(0,10)}.`,m.geprueft_mit?` geprueft mit: \`${m.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht."].filter(Boolean).join(`
5
5
  `):[`\u26A0\uFE0F \`${m.topic}\` ist als fraglich markiert.`,` Befund: ${m.befund}`,"","Geloescht wurde nichts \u2014 eine Pruefung kann aus Gruenden fehlschlagen,","die mit der Lektion nichts zu tun haben. Wenn du weisst, was jetzt gilt:",`\`learn_from_attempts(topic="${m.topic}", \u2026, grund="\u2026")\`.`].join(`
6
- `)}case"recall_feedback":{const{instance_id:g}=H,t=await U(g),s=Ts(H,new Date().toISOString());if(!s.ok)return[`\u26A0\uFE0F ${s.grund}`,"","Beispiel:","```",'recall_feedback(instance_id="\u2026", query="warum bricht der Deploy ab",',' topic="ci:zeitgrenze-meldet-cancelled", helped=true, rank=0)',"```","rank=0 heisst: die Lektion stand GAR NICHT in der Antwort.","Das ist die wertvollste Rueckmeldung von allen."].join(`
7
- `);const k=s.eintrag,m=`cachly:wirkung:${g}`;await t.rpush(m,JSON.stringify(k));const $=(await t.lrange(m,0,-1).catch(()=>[])).map(_=>O(_,null)).filter(Boolean),a=Ns($),u=Es(k),M={"fehlender-treffer":"Sie half, stand aber gar nicht in der Antwort \u2014 der Topf hat sie nicht aufgenommen. Das ist der wertvollste Fall.","zu-weit-hinten":`Sie half, stand aber auf Platz ${k.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${k.platz} und half nicht \u2014 die Sortierung war sich sicher und lag falsch.`,bestaetigung:"Sie stand vorn und half. Bestaetigung.",unauffaellig:"Half nicht und stand hinten. Sagt wenig."},o=a.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${(a.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${k.thema}** \u2014 ${k.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${k.platz===0?"\u2014 (stand nicht drin)":k.platz}`,"",M[u],"",`Spur: ${a.gesamt} Rueckmeldungen, ${o}.`,`Davon: ${a.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${a.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${a.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
8
- `)}case"recall_best_solution":{const g=Date.now(),{instance_id:t,topic:s,author:k}=H,m=await U(t);try{const o=await m.get(`cachly:letzter-recall:${t}`),_=o?O(o,null):null,S=As(_,s,new Date().toISOString());S&&(await m.rpush(`cachly:wirkung:${t}`,JSON.stringify(S)),await m.del(`cachly:letzter-recall:${t}`))}catch{}const d=await m.get(`cachly:lesson:best:${s}`);if(d){const o=O(d,null);if(!o)return`\u26A0\uFE0F Lesson data for \`${s}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const _=o.group;if(_){const ne=k?await it(m,t,k).catch(()=>new Set):new Set,fe=k?await Ue(m,t,k).catch(()=>null)==="admin":!1;if(!rt(_,ne,fe))return`\u{1F4ED} No lessons found for \`${s}\`. Use \`learn_from_attempts\` after solving it.`}const S=Re(o),h=o.verified_at??o.ts,i=(Date.now()-new Date(h).getTime())/864e5,x=o.commands,b=Mt(S,i,Array.isArray(x)&&typeof x[0]=="string"?x[0]:void 0),w=new Date().toISOString(),A={...o,recall_count:(o.recall_count??0)+1,last_recalled_at:w};await m.set(`cachly:lesson:best:${s}`,JSON.stringify(A)),xt(m),wt(m,String(s??""),Date.now()-g);const I=ot(o)?nt(o):0;I>0&&m.incrbyfloat(`cachly:stats:time_saved_mins:${t}`,I).catch(()=>{});const e=o.severity==="critical"?"\u{1F534}":o.severity==="major"?"\u{1F7E1}":o.severity?"\u{1F7E2}":"",j=o.audit_trail??[],v=j.filter(ne=>ne&&typeof ne.grund=="string"&&ne.grund.trim().length>0).slice(-3).map(ne=>` \xB7 ${ne.ts?new Date(ne.ts).toLocaleDateString("de-DE"):"?"}: ${ne.grund.trim()}`),oe=j.length>1?[`_Audit: ${j.length} changes \xB7 stored ${new Date(o.ts).toLocaleDateString("de-DE")}_`,...v.length>0?["**Warum zuletzt geaendert:**",...v]:[]].join(`
9
- `):"",ce=(Date.now()-new Date(o.ts).getTime())/864e5,he=ce>60?`\u{1F4AD} _Remember when you solved this ${Math.round(ce/30)} months ago? Still works._`:"",R=A.recall_count===3&&!o.pinned?"\u{1F4CC} **You've looked this up 3 times.** Consider pinning it for instant access: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",E=o.authors??(o.author?[o.author]:[]),J=[...new Set(E.filter(Boolean))],se=A.recall_count;let V="";J.length>=2&&se>=5?V=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7 \xB7 verified by ${J.length} developers. Trust this.`:se>=10?V=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7. This is one of your most-proven solutions.`:J.length>=2?V=`\u2705 **Team-verified** \u2014 confirmed by ${J.length} developers.`:se>=5&&(V=`\u2705 **Proven** \u2014 recalled ${se}\xD7 without contradiction.`);const n=o.ersetzt_durch,r=o.ersetzt_am?` (am ${o.ersetzt_am.slice(0,10)})`:"",p=n?await m.get(`cachly:lesson:best:${n}`):null,c=String(o.ersetzt_grund??"").trim(),l=c?` Grund: ${c}`:" Grund nicht erfasst.",T=p?!Te(Ce(p)):!1,B=n?p?T?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${r} \u2014 die Nachfolge-Lektion ist nicht team-sichtbar (privat). Der Text unten bleibt als Vorgeschichte lesbar; die gueltige Fassung kennt ihr Autor.`:`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${r} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${n}")\`.${l} Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${r} \u2014 der Nachfolger \`${n}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",P=o.gilt_ab,N=o.gilt_bis,W=P?`\u{1F4C5} Gilt seit ${String(P).slice(0,10)}.`:"",ee=o.entscheidung,le=ee?.gegen?mt({gegen:ee.gegen,grund:ee.grund??null}):"",we=N&&Date.parse(String(N))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(N).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[B,we,W,le,he,V,`${b} **Best solution for \`${s}\`** ${e}${o.severity?` (${o.severity})`:""} \xB7 recalled ${A.recall_count}\xD7`,Os(o.author,o.source),"",o.what_worked?`**What worked:** ${o.what_worked}`:"",o.what_failed?`**What failed (avoid this):** ${o.what_failed}`:"",o.context?`**Context:** ${o.context}`:"",(o.file_paths??[]).length>0?`**Files:** ${(o.file_paths??[]).map(ne=>`\`${ne}\``).join(", ")}`:"",(o.commands??[]).length>0?`**Commands:** ${(o.commands??[]).map(ne=>`\`${ne}\``).join(", ")}`:"",(o.tags??[]).length>0?`**Tags:** ${(o.tags??[]).map(ne=>`#${ne}`).join(" ")}`:"",oe,R].filter(ne=>ne!=="").join(`
10
- `)}const $=[],a=m.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((o,_)=>{a.on("data",S=>$.push(...S)),a.on("end",o),a.on("error",_)});const u=$.filter(o=>o.toLowerCase().includes(s.toLowerCase()));if(u.length===0){const o=`cachly:lessons:${s}`,_=await m.lrange(o,-3,-1);if(_.length>0){const h=_.map(i=>O(i,null)).filter(Boolean).map(i=>`- ${i.outcome==="success"?"\u2705":"\u274C"} ${i.what_worked.slice(0,120)} (${new Date(i.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${s}\` yet. Last attempts:
6
+ `)}case"recall_feedback":{const{instance_id:g}=q,t=await V(g),s=Ts(q,new Date().toISOString());if(!s.ok)return[`\u26A0\uFE0F ${s.grund}`,"","Beispiel:","```",'recall_feedback(instance_id="\u2026", query="warum bricht der Deploy ab",',' topic="ci:zeitgrenze-meldet-cancelled", helped=true, rank=0)',"```","rank=0 heisst: die Lektion stand GAR NICHT in der Antwort.","Das ist die wertvollste Rueckmeldung von allen."].join(`
7
+ `);const S=s.eintrag,m=`cachly:wirkung:${g}`;await t.rpush(m,JSON.stringify(S));const $=(await t.lrange(m,0,-1).catch(()=>[])).map(_=>O(_,null)).filter(Boolean),a=Ns($),u=Es(S),M={"fehlender-treffer":"Sie half, stand aber gar nicht in der Antwort \u2014 der Topf hat sie nicht aufgenommen. Das ist der wertvollste Fall.","zu-weit-hinten":`Sie half, stand aber auf Platz ${S.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${S.platz} und half nicht \u2014 die Sortierung war sich sicher und lag falsch.`,bestaetigung:"Sie stand vorn und half. Bestaetigung.",unauffaellig:"Half nicht und stand hinten. Sagt wenig."},n=a.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${(a.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${S.thema}** \u2014 ${S.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${S.platz===0?"\u2014 (stand nicht drin)":S.platz}`,"",M[u],"",`Spur: ${a.gesamt} Rueckmeldungen, ${n}.`,`Davon: ${a.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${a.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${a.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
8
+ `)}case"recall_best_solution":{const g=Date.now(),{instance_id:t,topic:s,author:S}=q,m=await V(t);try{const n=await m.get(`cachly:letzter-recall:${t}`),_=n?O(n,null):null,C=As(_,s,new Date().toISOString());C&&(await m.rpush(`cachly:wirkung:${t}`,JSON.stringify(C)),await m.del(`cachly:letzter-recall:${t}`))}catch{}const f=await m.get(`cachly:lesson:best:${s}`);if(f){const n=O(f,null);if(!n)return`\u26A0\uFE0F Lesson data for \`${s}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const _=n.group;if(_){const ne=S?await it(m,t,S).catch(()=>new Set):new Set,fe=S?await Ue(m,t,S).catch(()=>null)==="admin":!1;if(!rt(_,ne,fe))return`\u{1F4ED} No lessons found for \`${s}\`. Use \`learn_from_attempts\` after solving it.`}const C=Re(n),h=n.verified_at??n.ts,i=(Date.now()-new Date(h).getTime())/864e5,x=n.commands,b=Mt(C,i,Array.isArray(x)&&typeof x[0]=="string"?x[0]:void 0,n.pruefung_gefallen_am?{am:n.pruefung_gefallen_am,befund:n.pruefung_befund}:void 0),w=new Date().toISOString(),A={...n,recall_count:(n.recall_count??0)+1,last_recalled_at:w};await m.set(`cachly:lesson:best:${s}`,JSON.stringify(A)),xt(m),wt(m,String(s??""),Date.now()-g);const I=ot(n)?nt(n):0;I>0&&m.incrbyfloat(`cachly:stats:time_saved_mins:${t}`,I).catch(()=>{});const e=n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":n.severity?"\u{1F7E2}":"",F=n.audit_trail??[],k=F.filter(ne=>ne&&typeof ne.grund=="string"&&ne.grund.trim().length>0).slice(-3).map(ne=>` \xB7 ${ne.ts?new Date(ne.ts).toLocaleDateString("de-DE"):"?"}: ${ne.grund.trim()}`),oe=F.length>1?[`_Audit: ${F.length} changes \xB7 stored ${new Date(n.ts).toLocaleDateString("de-DE")}_`,...k.length>0?["**Warum zuletzt geaendert:**",...k]:[]].join(`
9
+ `):"",ce=(Date.now()-new Date(n.ts).getTime())/864e5,he=ce>60?`\u{1F4AD} _Remember when you solved this ${Math.round(ce/30)} months ago? Still works._`:"",R=A.recall_count===3&&!n.pinned?"\u{1F4CC} **You've looked this up 3 times.** Consider pinning it for instant access: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",E=n.authors??(n.author?[n.author]:[]),H=[...new Set(E.filter(Boolean))],se=A.recall_count;let Y="";H.length>=2&&se>=5?Y=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7 \xB7 verified by ${H.length} developers. Trust this.`:se>=10?Y=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7. This is one of your most-proven solutions.`:H.length>=2?Y=`\u2705 **Team-verified** \u2014 confirmed by ${H.length} developers.`:se>=5&&(Y=`\u2705 **Proven** \u2014 recalled ${se}\xD7 without contradiction.`);const o=n.ersetzt_durch,r=n.ersetzt_am?` (am ${n.ersetzt_am.slice(0,10)})`:"",p=o?await m.get(`cachly:lesson:best:${o}`):null,c=String(n.ersetzt_grund??"").trim(),l=c?` Grund: ${c}`:" Grund nicht erfasst.",T=p?!Te(Ce(p)):!1,B=o?p?T?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${r} \u2014 die Nachfolge-Lektion ist nicht team-sichtbar (privat). Der Text unten bleibt als Vorgeschichte lesbar; die gueltige Fassung kennt ihr Autor.`:`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${r} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${o}")\`.${l} Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${r} \u2014 der Nachfolger \`${o}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",P=n.gilt_ab,N=n.gilt_bis,W=P?`\u{1F4C5} Gilt seit ${String(P).slice(0,10)}.`:"",ee=n.entscheidung,le=ee?.gegen?mt({gegen:ee.gegen,grund:ee.grund??null}):"",we=N&&Date.parse(String(N))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(N).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[B,we,W,le,he,Y,`${b} **Best solution for \`${s}\`** ${e}${n.severity?` (${n.severity})`:""} \xB7 recalled ${A.recall_count}\xD7`,Os(n.author,n.source),"",n.what_worked?`**What worked:** ${n.what_worked}`:"",n.what_failed?`**What failed (avoid this):** ${n.what_failed}`:"",n.context?`**Context:** ${n.context}`:"",(n.file_paths??[]).length>0?`**Files:** ${(n.file_paths??[]).map(ne=>`\`${ne}\``).join(", ")}`:"",(n.commands??[]).length>0?`**Commands:** ${(n.commands??[]).map(ne=>`\`${ne}\``).join(", ")}`:"",(n.tags??[]).length>0?`**Tags:** ${(n.tags??[]).map(ne=>`#${ne}`).join(" ")}`:"",oe,R].filter(ne=>ne!=="").join(`
10
+ `)}const $=[],a=m.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((n,_)=>{a.on("data",C=>$.push(...C)),a.on("end",n),a.on("error",_)});const u=$.filter(n=>n.toLowerCase().includes(s.toLowerCase()));if(u.length===0){const n=`cachly:lessons:${s}`,_=await m.lrange(n,-3,-1);if(_.length>0){const h=_.map(i=>O(i,null)).filter(Boolean).map(i=>`- ${i.outcome==="success"?"\u2705":"\u274C"} ${i.what_worked.slice(0,120)} (${new Date(i.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${s}\` yet. Last attempts:
11
11
 
12
12
  ${h.join(`
13
- `)}`}return`\u{1F4ED} No lessons found for \`${s}\`. Use \`learn_from_attempts\` after solving it.`}const M=[];for(const o of u.slice(0,5)){const _=await m.get(o);if(!_)continue;const S=O(_,null);S&&M.push(`**\`${S.topic}\`** \u2014 ${S.what_worked.slice(0,400)}${S.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${s}\`:**
13
+ `)}`}return`\u{1F4ED} No lessons found for \`${s}\`. Use \`learn_from_attempts\` after solving it.`}const M=[];for(const n of u.slice(0,5)){const _=await m.get(n);if(!_)continue;const C=O(_,null);C&&M.push(`**\`${C.topic}\`** \u2014 ${C.what_worked.slice(0,400)}${C.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${s}\`:**
14
14
 
15
15
  ${M.join(`
16
16
 
17
- `)}`}case"smart_recall":{const g=Date.now(),{instance_id:t,query:s,threshold:k=.78,author:m="",context_files:d=[]}=H,$=Array.isArray(d)?d.filter(f=>typeof f=="string"):[],a=await U(t);At(a,void 0,2);let u=new Set,M=!1;m&&(u=await it(a,t,m).catch(()=>new Set),M=await Ue(a,t,m).catch(()=>null)==="admin");const o=await ze(a,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],s,25),_=is(o);let S=!1,h=null;const i=await(async()=>{if(!Ne())return He(qt,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),_;try{if(await ye.aktualisiere(a),ye.groesse===0)return He(Jt,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),_;const f=await $e(s);if(!f?.length)return He(Ut,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),_;await Ze.aktualisiere(a),await Xe.aktualisiere(a),await je.aktualisiere(a),await Pe.aktualisiere(a);const y=ye.groesse>0?Pe.groesse/ye.groesse:0;y<_t&&ye.groesse>0&&bn(a,3);const C=y>=_t?$e(s,{modell:Oe}).catch(()=>null):null,Y=_.filter(z=>z.key.startsWith("cachly:lesson:best:")).map(z=>z.key.slice(19)),q=z=>Math.max(ye.naehe(f,z),Ze.naehe(f,z)),F=[...je.themen()],G=(F.length>0?F:ye.aehnlichste(f,500).map(z=>z.topic)).map(z=>({t:z,n:q(z)})).sort((z,re)=>re.n-z.n).slice(0,$t).map(z=>z.t),Q=[...new Set([...Y,...G])],K=G.slice(0,3).map(z=>ye.rohvektor(z)).filter(Boolean),de=K.length?ks(f,K):f,ke=yt(s),D=je.statistik,L=Q.map(z=>{const re=new Set([...yt(je.textVon(z))].map(Ss));return{naeheText:ye.naehe(f,z),naeheThema:Ze.naehe(f,z),naeheRueckkopplung:ye.naehe(de,z),seltenheitsDeckung:D?D.deckung(ke,re):0,besterZeuge:D?D.besterZeuge(ke,re):0}});let ae=vs(L,Cs);{const z=[...ae].sort((re,pe)=>pe-re);h=z.length>1?z[0]-z[1]:null}if(Xe.groesse>0){const z=Q.map(pe=>{const _e=Xe.besteNaehe(f,pe);return _e>=Ks?_e:-2}),re=gt(z);ae=ae.map((pe,_e)=>pe+Gs*re[_e])}if(C){const z=await C;if(z?.length){const re=gt(Q.map(pe=>Pe.naehe(z,pe)));ae=ae.map((pe,_e)=>pe+Bs*re[_e])}}const te=Q.map((z,re)=>({t:z,p:ae[re]})).sort((z,re)=>re.p-z.p).map(z=>z.t),Z=new Map(_.map(z=>[z.key,z])),X=[];for(const z of te){const re=`cachly:lesson:best:${z}`,pe=Z.get(re);if(pe){X.push(pe),Z.delete(re);continue}const _e=await a.get(re).catch(()=>null);_e&&X.push({key:re,content:_e,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return X.push(...Z.values()),Is&&Ms({frage:s.slice(0,200),themen:Q,ausWortsuche:Y.length,ausSinnsuche:G.length,obergrenze:$t,gezeigt:te.slice(0,10)}),S=!0,X}catch(f){return await Be(a,Vt,`der Bedeutungspfad brach ab (${f instanceof Error?f.message:String(f)}) \u2014 diese Suche lief nur ueber Woerter`),_}})();xt(a),wt(a,String(s??""),Date.now()-g);{const f=i.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(f.length>0){const y={ts:new Date().toISOString(),themen:f};(async()=>{const C=dt(t);await a.lpush(C,JSON.stringify(y)),await a.ltrim(C,0,ws-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:s.slice(0,200),geliefert:f};(async()=>{const C=ft(t);await a.lpush(C,JSON.stringify(y)),await a.ltrim(C,0,bs-1)})().catch(()=>{})}}if(Ne()){const f=i.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));ps(a,s,f,$e).catch(()=>{})}const x=[],b=i.filter(f=>f.key.startsWith("cachly:lesson:best:"));let w=0,A=0;for(const f of b.slice(0,5)){const y=await a.get(f.key).catch(()=>null);if(y){const C=O(y,null);if(C?.state==="archived")continue;if(C){const Y=new Date().toISOString(),q={...C,recall_count:(C.recall_count??0)+1,last_recalled_at:Y};a.set(f.key,JSON.stringify(q)).catch(()=>{});const F=ot(C)?nt(C):0;if(F>0&&a.incrbyfloat(`cachly:stats:time_saved_mins:${t}`,F).catch(()=>{}),C.author&&m&&C.author!==m){w++,a.sadd(`cachly:stats:reuse_pairs:${t}`,`${m}<-${C.author}`).catch(()=>{});const G=`person:${me(m)}`,Q=`person:${me(C.author)}`;ge(a,G,"collaborates",Q,!0).catch(()=>{}),ge(a,Q,"collaborates",G,!0).catch(()=>{})}C.outcome==="success"&&A++,C.outcome==="success"&&(C.recall_count??0)>=1&&!Le(C)&&x.push({topic:f.key.replace("cachly:lesson:best:",""),severity:C.severity??"major",recall_count:(C.recall_count??0)+1,savedMins:F,ts:C.ts,author:C.author})}}}A>0&&a.set(`cachly:stats:first_recall_at:${t}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),b.length>0&&(a.incr(`cachly:stats:recalls_total:${t}`).catch(()=>{}),w>0&&a.incr(`cachly:stats:cross_author_recalls:${t}`).catch(()=>{}));const I=await ue(`/api/v1/instances/${t}`).catch(()=>null),e=!I?.tier||I.tier.toLowerCase()==="free",j=[];if(!e&&I?.vector_token&&Ne())try{const f=await $e(s),y=`https://api.cachly.dev/v1/sem/${I.vector_token}`,C=await fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:f,namespace:"cachly:ctx",threshold:k,top_k:5}),signal:AbortSignal.timeout(8e3)});if(C.ok){const Y=await C.json();for(const q of Y.filter(F=>F.found&&F.id)){const F=q.id.replace("ctx:","").split(":"),G=F[0],Q=F.slice(1).join(":"),K=`cachly:ctx:${G}:${Q}`,de=await a.get(K).catch(()=>null);j.push({key:K,similarity:q.similarity??0,content:de??"(evicted)"})}}}catch{}const v=i.map(f=>f.score),oe=v.length?Math.min(...v):0,ce=v.length&&Math.max(...v)-oe||1,he=f=>(f-oe)/ce,R=new Map;for(const f of i){const y=he(f.score);R.set(f.key,{key:f.key,content:f.content,bm25Score:y,hybridScore:y*(j.length>0?.7:1),matchedWords:f.matchedWords,matchType:"keyword",subQuery:f.subQuery,wortBelege:f.wortBelege})}for(const f of j){const y=R.get(f.key);y?(y.semScore=f.similarity,y.hybridScore=(y.bm25Score??0)*.6+f.similarity*.4,y.matchType="hybrid"):R.set(f.key,{key:f.key,content:f.content,semScore:f.similarity,hybridScore:f.similarity*.5,matchType:"semantic"})}try{const f=Ve(s).filter(Y=>Y.length>=4).slice(0,4),y=new Set;for(const Y of f){const q=a.scanStream({match:`cachly:ckg:node:*${Y}*`,count:20});await new Promise((F,G)=>{q.on("data",Q=>{for(const K of Q.slice(0,5))y.add(K.replace("cachly:ckg:node:",""))}),q.on("end",F),q.on("error",G)})}const C=new Set;for(const Y of[...y].slice(0,12)){const q=await a.smembers(`cachly:ckg:idx:to:${Y}`);for(const F of q.slice(0,6)){const G=await a.get(F);if(!G)continue;const Q=O(G,null);if(!Q||Q.edgeType!=="fixes"||Q.confidence<.35||C.has(Q.from))continue;C.add(Q.from);const K=`cachly:lesson:best:${Q.from}`,de=R.get(K);if(de)de.ckgScore=Math.max(de.ckgScore??0,Q.confidence),de.hybridScore=de.hybridScore*.88+Q.confidence*.12,de.matchType==="keyword"&&(de.matchType="hybrid");else{const ke=await a.get(K).catch(()=>null);if(!ke)continue;R.set(K,{key:K,content:ke,ckgScore:Q.confidence,hybridScore:Q.confidence*.3,matchType:"ckg"})}}}}catch{}if($.length>0){const f=new Set($.map(y=>y.replace(/\\/g,"/")));for(const y of R.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const C=O(y.content,{});(Array.isArray(C.file_paths)?C.file_paths.filter(q=>typeof q=="string").map(q=>q.replace(/\\/g,"/")):[]).some(q=>f.has(q))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const f of R.values()){if(f.matchType!=="semantic"&&f.matchType!=="ckg")continue;const y=cs({key:f.key,content:f.content});y&&(f.hybridScore*=rs(y))}const E=[...R.values()].filter(f=>{if(!f.key.startsWith("cachly:lesson:best:"))return!0;const y=Ce(f.content);return!(!Te(y)||!rt(y?.group,u,M))}).sort((f,y)=>y.hybridScore-f.hybridScore),J=[];for(const f of E){if(!f.key.startsWith("cachly:lesson:best:"))continue;const y=O(f.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&J.push(`\u23F3 \`${f.key.replace("cachly:lesson:best:","")}\` galt bis ${String(y.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`)}{const f=new Set(E.map(y=>y.key));for(let y=E.length-1;y>=0;y--){const C=E[y];if(!C.key.startsWith("cachly:lesson:best:"))continue;const Y=O(C.content,{});if(!Y.ersetzt_durch)continue;const q=String(Y.ersetzt_grund??"").trim(),F=C.key.replace("cachly:lesson:best:","");if(f.has(`cachly:lesson:best:${Y.ersetzt_durch}`))E.splice(y,1),J.push(`\u21B7 \`${F}\` verdraengt \u2014 ersetzt durch \`${Y.ersetzt_durch}\`${Y.ersetzt_am?` am ${Y.ersetzt_am.slice(0,10)}`:""}${q?` \u2014 Grund: ${q}`:" \u2014 Grund nicht erfasst"}`);else if(await a.get(`cachly:lesson:best:${Y.ersetzt_durch}`)){const G=Ce(await a.get(`cachly:lesson:best:${Y.ersetzt_durch}`));Te(G)?J.push(`\u26A0\uFE0F \`${F}\` ist ersetzt durch \`${Y.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${Y.ersetzt_durch}")\``):J.push(`\u21B7 \`${F}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else J.push(`\u21A9\uFE0F \`${F}\` war ersetzt durch \`${Y.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const se=[];{await ye.aktualisiere(a).catch(()=>{});const f=E.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<f.length;y++)for(let C=y+1;C<f.length;C++){const Y=f[y].key.replace("cachly:lesson:best:",""),q=f[C].key.replace("cachly:lesson:best:",""),F=ye.rohvektor(Y),G=ye.rohvektor(q);if(!F||!G)continue;let Q=0,K=0,de=0;for(let L=0;L<F.length;L++)Q+=F[L]*G[L],K+=F[L]*F[L],de+=G[L]*G[L];if((K>0&&de>0?Q/(Math.sqrt(K)*Math.sqrt(de)):0)<zs)continue;const D=L=>{const ae=O(L??"",{});return String(ae.verified_at??ae.ts??"").slice(0,10)||"ohne Datum"};se.push(`\u26A0\uFE0F \`${Y}\` (${D(f[y].content)}) und \`${q}\` (${D(f[C].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}se.length>3&&(se.length=3)}if(J.push(...se),E.length>=2){const f=E[0].hybridScore,y=E[Math.min(4,E.length-1)].hybridScore,C=Math.max(0,f-y);(async()=>{try{await a.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(C.toFixed(4)),n:E.length})),await a.ltrim("cachly:recall:spread",0,199)}catch{}})()}const V=Yt();let n="",r=null;if(V!==null){n=Zt();const f=E[0]?.hybridScore??0,y=Xt(E.map(C=>({key:C.key,content:C.content,punktzahl:C.hybridScore})),n,V,f);y.weggelassenesThema!==void 0?E.splice(0,1):y.markierungGesetzt&&E[0]&&y.treffer[0]&&(E[0]={...E[0],content:y.treffer[0].content}),r={frage:s,hoechstePunktzahl:f,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}const p=await Et(t,ue),c=p.reached,l=vt({ueberLimit:c,gesamt:E.length,volleTiefe:Js}),T=process.env.CACHLY_RECALL_COMPACT==="1",B=(()=>{const f=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(f)?Math.min(20,Math.max(1,f)):5})(),P=T?Math.min(B,l.sichtbar):l.sichtbar,N=[`\u{1F9E0} **Smart Recall** for: _"${s}"_
17
+ `)}`}case"smart_recall":{const g=Date.now(),{instance_id:t,query:s,threshold:S=.78,author:m="",context_files:f=[]}=q,$=Array.isArray(f)?f.filter(d=>typeof d=="string"):[],a=await V(t);At(a,void 0,2);let u=new Set,M=!1;m&&(u=await it(a,t,m).catch(()=>new Set),M=await Ue(a,t,m).catch(()=>null)==="admin");const n=await ze(a,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],s,25),_=is(n);let C=!1,h=null;const i=await(async()=>{if(!Ne())return He(qt,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),_;try{if(await ye.aktualisiere(a),ye.groesse===0)return He(Jt,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),_;const d=await $e(s);if(!d?.length)return He(Ut,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),_;await Ze.aktualisiere(a),await Xe.aktualisiere(a),await je.aktualisiere(a),await Pe.aktualisiere(a);const y=ye.groesse>0?Pe.groesse/ye.groesse:0;y<_t&&ye.groesse>0&&bn(a,3);const v=y>=_t?$e(s,{modell:Oe}).catch(()=>null):null,U=_.filter(z=>z.key.startsWith("cachly:lesson:best:")).map(z=>z.key.slice(19)),K=z=>Math.max(ye.naehe(d,z),Ze.naehe(d,z)),j=[...je.themen()],J=(j.length>0?j:ye.aehnlichste(d,500).map(z=>z.topic)).map(z=>({t:z,n:K(z)})).sort((z,re)=>re.n-z.n).slice(0,$t).map(z=>z.t),Q=[...new Set([...U,...J])],G=J.slice(0,3).map(z=>ye.rohvektor(z)).filter(Boolean),de=G.length?ks(d,G):d,ke=yt(s),D=je.statistik,L=Q.map(z=>{const re=new Set([...yt(je.textVon(z))].map(Ss));return{naeheText:ye.naehe(d,z),naeheThema:Ze.naehe(d,z),naeheRueckkopplung:ye.naehe(de,z),seltenheitsDeckung:D?D.deckung(ke,re):0,besterZeuge:D?D.besterZeuge(ke,re):0}});let ae=vs(L,Cs);{const z=[...ae].sort((re,pe)=>pe-re);h=z.length>1?z[0]-z[1]:null}if(Xe.groesse>0){const z=Q.map(pe=>{const _e=Xe.besteNaehe(d,pe);return _e>=Gs?_e:-2}),re=gt(z);ae=ae.map((pe,_e)=>pe+Ks*re[_e])}if(v){const z=await v;if(z?.length){const re=gt(Q.map(pe=>Pe.naehe(z,pe)));ae=ae.map((pe,_e)=>pe+Bs*re[_e])}}const te=Q.map((z,re)=>({t:z,p:ae[re]})).sort((z,re)=>re.p-z.p).map(z=>z.t),Z=new Map(_.map(z=>[z.key,z])),X=[];for(const z of te){const re=`cachly:lesson:best:${z}`,pe=Z.get(re);if(pe){X.push(pe),Z.delete(re);continue}const _e=await a.get(re).catch(()=>null);_e&&X.push({key:re,content:_e,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return X.push(...Z.values()),Is&&Ms({frage:s.slice(0,200),themen:Q,ausWortsuche:U.length,ausSinnsuche:J.length,obergrenze:$t,gezeigt:te.slice(0,10)}),C=!0,X}catch(d){return await Be(a,Vt,`der Bedeutungspfad brach ab (${d instanceof Error?d.message:String(d)}) \u2014 diese Suche lief nur ueber Woerter`),_}})();xt(a),wt(a,String(s??""),Date.now()-g);{const d=i.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(d.length>0){const y={ts:new Date().toISOString(),themen:d};(async()=>{const v=dt(t);await a.lpush(v,JSON.stringify(y)),await a.ltrim(v,0,ws-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:s.slice(0,200),geliefert:d};(async()=>{const v=ft(t);await a.lpush(v,JSON.stringify(y)),await a.ltrim(v,0,bs-1)})().catch(()=>{})}}if(Ne()){const d=i.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));ps(a,s,d,$e).catch(()=>{})}const x=[],b=i.filter(d=>d.key.startsWith("cachly:lesson:best:"));let w=0,A=0;for(const d of b.slice(0,5)){const y=await a.get(d.key).catch(()=>null);if(y){const v=O(y,null);if(v?.state==="archived")continue;if(v){const U=new Date().toISOString(),K={...v,recall_count:(v.recall_count??0)+1,last_recalled_at:U};a.set(d.key,JSON.stringify(K)).catch(()=>{});const j=ot(v)?nt(v):0;if(j>0&&a.incrbyfloat(`cachly:stats:time_saved_mins:${t}`,j).catch(()=>{}),v.author&&m&&v.author!==m){w++,a.sadd(`cachly:stats:reuse_pairs:${t}`,`${m}<-${v.author}`).catch(()=>{});const J=`person:${me(m)}`,Q=`person:${me(v.author)}`;ge(a,J,"collaborates",Q,!0).catch(()=>{}),ge(a,Q,"collaborates",J,!0).catch(()=>{})}v.outcome==="success"&&A++,v.outcome==="success"&&(v.recall_count??0)>=1&&!Le(v)&&x.push({topic:d.key.replace("cachly:lesson:best:",""),severity:v.severity??"major",recall_count:(v.recall_count??0)+1,savedMins:j,ts:v.ts,author:v.author})}}}A>0&&a.set(`cachly:stats:first_recall_at:${t}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),b.length>0&&(a.incr(`cachly:stats:recalls_total:${t}`).catch(()=>{}),w>0&&a.incr(`cachly:stats:cross_author_recalls:${t}`).catch(()=>{}));const I=await ue(`/api/v1/instances/${t}`).catch(()=>null),e=!I?.tier||I.tier.toLowerCase()==="free",F=[];if(!e&&I?.vector_token&&Ne())try{const d=await $e(s),y=`https://api.cachly.dev/v1/sem/${I.vector_token}`,v=await fetch(`${y}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:d,namespace:"cachly:ctx",threshold:S,top_k:5}),signal:AbortSignal.timeout(8e3)});if(v.ok){const U=await v.json();for(const K of U.filter(j=>j.found&&j.id)){const j=K.id.replace("ctx:","").split(":"),J=j[0],Q=j.slice(1).join(":"),G=`cachly:ctx:${J}:${Q}`,de=await a.get(G).catch(()=>null);F.push({key:G,similarity:K.similarity??0,content:de??"(evicted)"})}}}catch{}const k=i.map(d=>d.score),oe=k.length?Math.min(...k):0,ce=k.length&&Math.max(...k)-oe||1,he=d=>(d-oe)/ce,R=new Map;for(const d of i){const y=he(d.score);R.set(d.key,{key:d.key,content:d.content,bm25Score:y,hybridScore:y*(F.length>0?.7:1),matchedWords:d.matchedWords,matchType:"keyword",subQuery:d.subQuery,wortBelege:d.wortBelege})}for(const d of F){const y=R.get(d.key);y?(y.semScore=d.similarity,y.hybridScore=(y.bm25Score??0)*.6+d.similarity*.4,y.matchType="hybrid"):R.set(d.key,{key:d.key,content:d.content,semScore:d.similarity,hybridScore:d.similarity*.5,matchType:"semantic"})}try{const d=Ve(s).filter(U=>U.length>=4).slice(0,4),y=new Set;for(const U of d){const K=a.scanStream({match:`cachly:ckg:node:*${U}*`,count:20});await new Promise((j,J)=>{K.on("data",Q=>{for(const G of Q.slice(0,5))y.add(G.replace("cachly:ckg:node:",""))}),K.on("end",j),K.on("error",J)})}const v=new Set;for(const U of[...y].slice(0,12)){const K=await a.smembers(`cachly:ckg:idx:to:${U}`);for(const j of K.slice(0,6)){const J=await a.get(j);if(!J)continue;const Q=O(J,null);if(!Q||Q.edgeType!=="fixes"||Q.confidence<.35||v.has(Q.from))continue;v.add(Q.from);const G=`cachly:lesson:best:${Q.from}`,de=R.get(G);if(de)de.ckgScore=Math.max(de.ckgScore??0,Q.confidence),de.hybridScore=de.hybridScore*.88+Q.confidence*.12,de.matchType==="keyword"&&(de.matchType="hybrid");else{const ke=await a.get(G).catch(()=>null);if(!ke)continue;R.set(G,{key:G,content:ke,ckgScore:Q.confidence,hybridScore:Q.confidence*.3,matchType:"ckg"})}}}}catch{}if($.length>0){const d=new Set($.map(y=>y.replace(/\\/g,"/")));for(const y of R.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const v=O(y.content,{});(Array.isArray(v.file_paths)?v.file_paths.filter(K=>typeof K=="string").map(K=>K.replace(/\\/g,"/")):[]).some(K=>d.has(K))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const d of R.values()){if(d.matchType!=="semantic"&&d.matchType!=="ckg")continue;const y=cs({key:d.key,content:d.content});y&&(d.hybridScore*=rs(y))}const E=[...R.values()].filter(d=>{if(!d.key.startsWith("cachly:lesson:best:"))return!0;const y=Ce(d.content);return!(!Te(y)||!rt(y?.group,u,M))}).sort((d,y)=>y.hybridScore-d.hybridScore),H=[];for(const d of E){if(!d.key.startsWith("cachly:lesson:best:"))continue;const y=O(d.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&H.push(`\u23F3 \`${d.key.replace("cachly:lesson:best:","")}\` galt bis ${String(y.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const v=O(d.content,{});if(v.pruefung_gefallen_am){const U=d.key.replace("cachly:lesson:best:",""),K=String(v.pruefung_gefallen_am).slice(0,10),j=String(v.pruefung_befund??"").trim().slice(0,200);H.push(`\u274C \`${U}\` \u2014 Pruefung am ${K} FEHLGESCHLAGEN`+(j?`: ${j}`:""))}}{const d=new Set(E.map(y=>y.key));for(let y=E.length-1;y>=0;y--){const v=E[y];if(!v.key.startsWith("cachly:lesson:best:"))continue;const U=O(v.content,{});if(!U.ersetzt_durch)continue;const K=String(U.ersetzt_grund??"").trim(),j=v.key.replace("cachly:lesson:best:","");if(d.has(`cachly:lesson:best:${U.ersetzt_durch}`))E.splice(y,1),H.push(`\u21B7 \`${j}\` verdraengt \u2014 ersetzt durch \`${U.ersetzt_durch}\`${U.ersetzt_am?` am ${U.ersetzt_am.slice(0,10)}`:""}${K?` \u2014 Grund: ${K}`:" \u2014 Grund nicht erfasst"}`);else if(await a.get(`cachly:lesson:best:${U.ersetzt_durch}`)){const J=Ce(await a.get(`cachly:lesson:best:${U.ersetzt_durch}`));Te(J)?H.push(`\u26A0\uFE0F \`${j}\` ist ersetzt durch \`${U.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${U.ersetzt_durch}")\``):H.push(`\u21B7 \`${j}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else H.push(`\u21A9\uFE0F \`${j}\` war ersetzt durch \`${U.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const se=[];{await ye.aktualisiere(a).catch(()=>{});const d=E.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<d.length;y++)for(let v=y+1;v<d.length;v++){const U=d[y].key.replace("cachly:lesson:best:",""),K=d[v].key.replace("cachly:lesson:best:",""),j=ye.rohvektor(U),J=ye.rohvektor(K);if(!j||!J)continue;let Q=0,G=0,de=0;for(let L=0;L<j.length;L++)Q+=j[L]*J[L],G+=j[L]*j[L],de+=J[L]*J[L];if((G>0&&de>0?Q/(Math.sqrt(G)*Math.sqrt(de)):0)<zs)continue;const D=L=>{const ae=O(L??"",{});return String(ae.verified_at??ae.ts??"").slice(0,10)||"ohne Datum"};se.push(`\u26A0\uFE0F \`${U}\` (${D(d[y].content)}) und \`${K}\` (${D(d[v].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}se.length>3&&(se.length=3)}if(H.push(...se),E.length>=2){const d=E[0].hybridScore,y=E[Math.min(4,E.length-1)].hybridScore,v=Math.max(0,d-y);(async()=>{try{await a.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(v.toFixed(4)),n:E.length})),await a.ltrim("cachly:recall:spread",0,199)}catch{}})()}const Y=Yt();let o="",r=null;if(Y!==null){o=Zt();const d=E[0]?.hybridScore??0,y=Xt(E.map(v=>({key:v.key,content:v.content,punktzahl:v.hybridScore})),o,Y,d);y.weggelassenesThema!==void 0?E.splice(0,1):y.markierungGesetzt&&E[0]&&y.treffer[0]&&(E[0]={...E[0],content:y.treffer[0].content}),r={frage:s,hoechstePunktzahl:d,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}const p=await Et(t,ue),c=p.reached,l=vt({ueberLimit:c,gesamt:E.length,volleTiefe:Js}),T=process.env.CACHLY_RECALL_COMPACT==="1",B=(()=>{const d=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(d)?Math.min(20,Math.max(1,d)):5})(),P=T?Math.min(B,l.sichtbar):l.sichtbar,N=[`\u{1F9E0} **Smart Recall** for: _"${s}"_
18
18
  `];p.goodwillMessage&&N.push(`${p.goodwillMessage}
19
- `);const W={critical:0,major:1,minor:2},ee=x.sort((f,y)=>(W[f.severity]??1)-(W[y.severity]??1))[0];if(ee){const f=F=>F>=60?`${F/60}h`:`${F}min`,y=(()=>{if(!ee.ts)return null;const F=new Date(ee.ts);if(isNaN(F.getTime()))return null;const G=new Date,Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return F.getFullYear()===G.getFullYear()?`${F.getDate()} ${Q[F.getMonth()]}`:`${F.getDate()} ${Q[F.getMonth()]} ${F.getFullYear()}`})(),C=ee.severity==="critical"?120:ee.severity==="major"?60:20,Y=ee.author&&ee.author!==m?` \xB7 by @${ee.author}`:"",q=y?` \xB7 learned ${y} (was a ${f(C)} debug)`:"";N.push(`> \u{1F4A1} **Brain saved you ~${f(ee.savedMins)} here** \u2014 \`${ee.topic}\`${q} \xB7 recalled ${ee.recall_count}\xD7${Y}
19
+ `);const W={critical:0,major:1,minor:2},ee=x.sort((d,y)=>(W[d.severity]??1)-(W[y.severity]??1))[0];if(ee){const d=j=>j>=60?`${j/60}h`:`${j}min`,y=(()=>{if(!ee.ts)return null;const j=new Date(ee.ts);if(isNaN(j.getTime()))return null;const J=new Date,Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return j.getFullYear()===J.getFullYear()?`${j.getDate()} ${Q[j.getMonth()]}`:`${j.getDate()} ${Q[j.getMonth()]} ${j.getFullYear()}`})(),v=ee.severity==="critical"?120:ee.severity==="major"?60:20,U=ee.author&&ee.author!==m?` \xB7 by @${ee.author}`:"",K=y?` \xB7 learned ${y} (was a ${d(v)} debug)`:"";N.push(`> \u{1F4A1} **Brain saved you ~${d(ee.savedMins)} here** \u2014 \`${ee.topic}\`${K} \xB7 recalled ${ee.recall_count}\xD7${U}
20
20
  `)}w>0&&N.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${w} of these lesson${w!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
21
- `);const le=E.filter(f=>f.contextBoost).length;le>0&&N.push(`> \u{1F4C1} **Personalized** \u2014 ${le} lesson${le!==1?"s":""} boosted because ${le!==1?"they match":"it matches"} your current file context (${$.slice(0,3).join(", ")}${$.length>3?", \u2026":""})
22
- `);const we=os(s);we.length>1&&N.push(`_Detected ${we.length} sub-topics:_ ${we.map((f,y)=>`${y+1}. "${f}"`).join(", ")}
23
- `);const ne=Gt(E.map(f=>({wortBelege:f.wortBelege,semScore:f.semScore,ckgScore:f.ckgScore})));if(ne.schweigen)return Nt(a,t,"schweigen"),N.push(Wt(ne)),N.join(`
24
- `);const fe=xs(h);if(fe&&N.push(fe,""),Nt(a,t,fe?"knapp":"beantwortet"),E.length>0){const f=E.some(C=>C.ckgScore!==void 0),y=j.length>0&&f?"keyword + semantic + CKG hybrid":j.length>0?"keyword + semantic hybrid":f?"keyword + CKG hybrid":"keyword";if(N.push(`### \u{1F50D} Results (${E.length} \u2014 ${y})
25
- `),ne.belegte<E.length){const C=[];for(const q of E){if(!q.key.startsWith("cachly:lesson:best:")||!Ht({wortBelege:q.wortBelege,semScore:q.semScore,ckgScore:q.ckgScore}))continue;const F=O(q.content,{}),G=Date.parse(F.verified_at??F.ts??"");Number.isFinite(G)&&C.push(Math.floor((Date.now()-G)/864e5))}const Y=Kt(C);N.push(`> \u{1F4CA} ${ne.belegte} von ${E.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(Y?` \u23F3 ${Y}`:"")+`
26
- `)}if(J.length>0&&N.push(...J.map(C=>`> ${C}`),""),we.length>1){const C=new Map,Y=vt({ueberLimit:c,gesamt:E.length,volleTiefe:qs});for(const G of E.slice(0,Y.sichtbar)){const Q=G.subQuery??s;C.has(Q)||C.set(Q,[]),C.get(Q).push(G)}for(const[G,Q]of C){N.push(`**Topic: "${G}"** (${Q.length} results)
27
- `);for(const K of Q.slice(0,T?2:4)){const de=K.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),ke=K.matchType==="ckg"?`CKG: ${(K.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:K.ckgScore!==void 0&&K.bm25Score!==void 0?`BM25: ${K.bm25Score.toFixed(2)}, CKG: ${K.ckgScore.toFixed(2)}, \u{1F500} hybrid`:K.matchType==="hybrid"?`BM25: ${(K.bm25Score??0).toFixed(2)}, sem: ${((K.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:K.matchType==="semantic"?`sem: ${((K.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(K.bm25Score??0).toFixed(2)}, matched: ${K.matchedWords?.join(", ")}`,D=at(K.key,K.content,300);if(N.push(T?` **${de}**`:` **${de}** _(${ke})_`),K.key.startsWith("cachly:lesson:best:")){const L=await a.get(K.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(K.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ae=L?O(L,{}):{};ae.title&&N.push(` \u{1F4D6} **${ae.title}** \u2014 ${ae.summary??""}`)}for(const L of D)N.push(` > ${L}`);N.push("")}}const q=[...C.keys()],F=we.filter(G=>!q.includes(G));F.length>0&&N.push(`
28
- \u26A0\uFE0F **No results for:** ${F.map(G=>`"${G}"`).join(", ")}`)}else for(const C of E.slice(0,P)){const Y=C.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let q="";if(C.key.startsWith("cachly:lesson:best:")){const K=O(C.content,{});K.author&&(q=` \xB7 \u{1F464} ${K.author}`)}const F=C.contextBoost?" \xB7 \u{1F4C1} context match":"",G=C.matchType==="hybrid"?`BM25: ${(C.bm25Score??0).toFixed(2)}, sem: ${((C.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:C.matchType==="semantic"?`sem: ${((C.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(C.bm25Score??0).toFixed(2)}, matched: ${C.matchedWords?.join(", ")}`,Q=at(C.key,C.content,400);N.push(T?`**${Y}**`:`**${Y}**${q}${F} _(${G})_`);{const K=O(C.content??"",{});K.entscheidung?.gegen&&N.push(mt({gegen:K.entscheidung.gegen,grund:K.entscheidung.grund??null}))}if(C.key.startsWith("cachly:lesson:best:")){const K=await a.get(C.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(C.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),de=K?O(K,{}):{};de.title&&N.push(`\u{1F4D6} **${de.title}** \u2014 ${de.summary??""}`)}for(const K of Q)N.push(`> ${K}`);N.push("")}if(c&&l.zurueckgehalten>0){const C=l.zurueckgehalten;N.push(`\u{1F512} **Free recall limit reached** (${p.used}/${p.limit} this month). Showing your top match; ${C} further relevant lesson${C!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${mn}
29
- `)}}else{N.push(`\u26A0\uFE0F No matches found for: "${s}"`),J.length>0&&N.push("",...J.map(C=>`> ${C}`));const f=Ve(s),y=[];if(lt.size>0&&f.length>0)for(const C of f.slice(0,3)){if(C.length<4)continue;let Y=3,q="";for(const F of lt){if(F.length<3||Math.abs(F.length-C.length)>4)continue;const G=as(C,F);G>0&&G<Y&&(Y=G,q=F)}q&&y.push(`"${q}" (instead of "${C}")`)}y.length>0?N.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(N.push(`
30
- \u{1F4A1} Tips:`),N.push(" \u2022 Try different keywords"),N.push(" \u2022 Use `list_remembered` to see available context"),N.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!T&&E.length>0){N.push(""),N.push("\u21A9\uFE0E Hat eine davon geholfen? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` \u2014 und wenn die richtige Lektion **nicht** dabei war: dieselbe Meldung mit `rank=0`. Das ist die einzige Zahl, die die Sortierung besser macht.");const f=E.filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));if(f.length>0)try{await a.setex(`cachly:letzter-recall:${t}`,7200,JSON.stringify({frage:s,themen:f}))}catch{}}if(T&&E.length>0){const f=Lt();f&&(N.push(""),N.push(f))}if(V!==null&&r){const f=E.slice(0,P).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return Qt(a,n,{...r,themen:f},N.join(`
21
+ `);const le=E.filter(d=>d.contextBoost).length;le>0&&N.push(`> \u{1F4C1} **Personalized** \u2014 ${le} lesson${le!==1?"s":""} boosted because ${le!==1?"they match":"it matches"} your current file context (${$.slice(0,3).join(", ")}${$.length>3?", \u2026":""})
22
+ `);const we=os(s);we.length>1&&N.push(`_Detected ${we.length} sub-topics:_ ${we.map((d,y)=>`${y+1}. "${d}"`).join(", ")}
23
+ `);const ne=Kt(E.map(d=>({wortBelege:d.wortBelege,semScore:d.semScore,ckgScore:d.ckgScore})));if(ne.schweigen)return Nt(a,t,"schweigen"),N.push(Wt(ne)),N.join(`
24
+ `);const fe=xs(h);if(fe&&N.push(fe,""),Nt(a,t,fe?"knapp":"beantwortet"),E.length>0){const d=E.some(v=>v.ckgScore!==void 0),y=F.length>0&&d?"keyword + semantic + CKG hybrid":F.length>0?"keyword + semantic hybrid":d?"keyword + CKG hybrid":"keyword";if(N.push(`### \u{1F50D} Results (${E.length} \u2014 ${y})
25
+ `),ne.belegte<E.length){const v=[];for(const K of E){if(!K.key.startsWith("cachly:lesson:best:")||!Ht({wortBelege:K.wortBelege,semScore:K.semScore,ckgScore:K.ckgScore}))continue;const j=O(K.content,{}),J=Date.parse(j.verified_at??j.ts??"");Number.isFinite(J)&&v.push(Math.floor((Date.now()-J)/864e5))}const U=Gt(v);N.push(`> \u{1F4CA} ${ne.belegte} von ${E.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(U?` \u23F3 ${U}`:"")+`
26
+ `)}if(H.length>0&&N.push(...H.map(v=>`> ${v}`),""),we.length>1){const v=new Map,U=vt({ueberLimit:c,gesamt:E.length,volleTiefe:qs});for(const J of E.slice(0,U.sichtbar)){const Q=J.subQuery??s;v.has(Q)||v.set(Q,[]),v.get(Q).push(J)}for(const[J,Q]of v){N.push(`**Topic: "${J}"** (${Q.length} results)
27
+ `);for(const G of Q.slice(0,T?2:4)){const de=G.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),ke=G.matchType==="ckg"?`CKG: ${(G.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:G.ckgScore!==void 0&&G.bm25Score!==void 0?`BM25: ${G.bm25Score.toFixed(2)}, CKG: ${G.ckgScore.toFixed(2)}, \u{1F500} hybrid`:G.matchType==="hybrid"?`BM25: ${(G.bm25Score??0).toFixed(2)}, sem: ${((G.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:G.matchType==="semantic"?`sem: ${((G.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(G.bm25Score??0).toFixed(2)}, matched: ${G.matchedWords?.join(", ")}`,D=at(G.key,G.content,300);if(N.push(T?` **${de}**`:` **${de}** _(${ke})_`),G.key.startsWith("cachly:lesson:best:")){const L=await a.get(G.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(G.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ae=L?O(L,{}):{};ae.title&&N.push(` \u{1F4D6} **${ae.title}** \u2014 ${ae.summary??""}`)}for(const L of D)N.push(` > ${L}`);N.push("")}}const K=[...v.keys()],j=we.filter(J=>!K.includes(J));j.length>0&&N.push(`
28
+ \u26A0\uFE0F **No results for:** ${j.map(J=>`"${J}"`).join(", ")}`)}else for(const v of E.slice(0,P)){const U=v.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let K="";if(v.key.startsWith("cachly:lesson:best:")){const G=O(v.content,{});G.author&&(K=` \xB7 \u{1F464} ${G.author}`)}const j=v.contextBoost?" \xB7 \u{1F4C1} context match":"",J=v.matchType==="hybrid"?`BM25: ${(v.bm25Score??0).toFixed(2)}, sem: ${((v.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:v.matchType==="semantic"?`sem: ${((v.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(v.bm25Score??0).toFixed(2)}, matched: ${v.matchedWords?.join(", ")}`,Q=at(v.key,v.content,400);N.push(T?`**${U}**`:`**${U}**${K}${j} _(${J})_`);{const G=O(v.content??"",{});G.entscheidung?.gegen&&N.push(mt({gegen:G.entscheidung.gegen,grund:G.entscheidung.grund??null}))}if(v.key.startsWith("cachly:lesson:best:")){const G=await a.get(v.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(v.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),de=G?O(G,{}):{};de.title&&N.push(`\u{1F4D6} **${de.title}** \u2014 ${de.summary??""}`)}for(const G of Q)N.push(`> ${G}`);N.push("")}if(c&&l.zurueckgehalten>0){const v=l.zurueckgehalten;N.push(`\u{1F512} **Free recall limit reached** (${p.used}/${p.limit} this month). Showing your top match; ${v} further relevant lesson${v!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${mn}
29
+ `)}}else{N.push(`\u26A0\uFE0F No matches found for: "${s}"`),H.length>0&&N.push("",...H.map(v=>`> ${v}`));const d=Ve(s),y=[];if(lt.size>0&&d.length>0)for(const v of d.slice(0,3)){if(v.length<4)continue;let U=3,K="";for(const j of lt){if(j.length<3||Math.abs(j.length-v.length)>4)continue;const J=as(v,j);J>0&&J<U&&(U=J,K=j)}K&&y.push(`"${K}" (instead of "${v}")`)}y.length>0?N.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(N.push(`
30
+ \u{1F4A1} Tips:`),N.push(" \u2022 Try different keywords"),N.push(" \u2022 Use `list_remembered` to see available context"),N.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!T&&E.length>0){N.push(""),N.push("\u21A9\uFE0E Hat eine davon geholfen? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` \u2014 und wenn die richtige Lektion **nicht** dabei war: dieselbe Meldung mit `rank=0`. Das ist die einzige Zahl, die die Sortierung besser macht.");const d=E.filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));if(d.length>0)try{await a.setex(`cachly:letzter-recall:${t}`,7200,JSON.stringify({frage:s,themen:d}))}catch{}}if(T&&E.length>0){const d=Lt();d&&(N.push(""),N.push(d))}if(Y!==null&&r){const d=E.slice(0,P).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return Qt(a,o,{...r,themen:d},N.join(`
31
31
  `))}return N.join(`
32
- `)}case"session_start":{const{instance_id:g,focus:t="",author:s="",provider:k="",workspace_path:m=""}=H,d=await U(g),$=[],a=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((n,r)=>{a.on("data",p=>$.push(...p)),a.on("end",n),a.on("error",r)});const u=[];if($.length>0){const n=await d.mget(...$);for(const r of n){const p=O(r??null,null);p&&u.push(p)}}u.sort((n,r)=>new Date(r.ts).getTime()-new Date(n.ts).getTime());let M=0;const o=d.scanStream({match:"cachly:ctx:*",count:200});await new Promise((n,r)=>{o.on("data",p=>{M+=p.filter(c=>!c.endsWith(":meta")).length}),o.on("end",n),o.on("error",r)});const _=await d.get("cachly:session:last"),S=O(_,null),h=t.toLowerCase().split(/\s+/).filter(Boolean),i=h.length>0?u.filter(n=>h.some(r=>n.topic.toLowerCase().includes(r)||(n.tags??[]).some(p=>p.toLowerCase().includes(r)))):[];let x=0,b=0,w="";try{const n=await d.get("cachly:streak:current"),r=O(n,null),p=new Date().toISOString().slice(0,10);if(r){const c=r.last_date,l=new Date(Date.now()-864e5).toISOString().slice(0,10);c===p?(x=r.days,b=r.record):c===l?(x=r.days+1,b=Math.max(x,r.record),await d.set("cachly:streak:current",JSON.stringify({days:x,last_date:p,record:b}))):(x=1,b=r.record,await d.set("cachly:streak:current",JSON.stringify({days:1,last_date:p,record:b})))}else x=1,b=1,await d.set("cachly:streak:current",JSON.stringify({days:1,last_date:p,record:1}));x>=7?w=`\u{1F525} **${x}-day streak!** ${x===b?" New record!":`Best: ${b}d`}`:x>1&&(w=`\u{1F525} ${x}-day streak`)}catch{}await d.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:t,provider:k}),"EX",86400);let A=0;try{const n=await d.get(`cachly:stats:time_saved_mins:${g}`);A=parseFloat(n??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${k?` \xB7 ${k}`:""}`,""];if(w&&e.push(w,""),A>=30){const n=Math.floor(A/60),r=Math.round(A%60),p=n>0?`${n}h${r>0?` ${r}m`:""}`:`${r}m`,c=u.filter(T=>!Le(T)&&(T.recall_count??0)>0).length,l=c>0?` \u2014 ${c} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${p} total**${l}`,"")}const j=await Et(g,ue),v=Hs({used:j.used,limit:j.limit,savedMins:A});if(v&&e.push(v,""),j.notice&&!Ct.has(g)&&(Ct.add(g),e.push(j.notice,"")),S?.ts){const n=new Date(S.ts).getTime(),r=Math.floor((Date.now()-n)/864e5);if(r>=7&&!Number.isNaN(n)){const p=u.filter(c=>{const l=new Date(c.ts).getTime();return!Number.isNaN(l)&&l>n});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${r} days since your last session.`),p.length>0){const c=p.slice(0,3).map(l=>`\`${l.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${p.length} lesson${p.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${c}${p.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${u.length} lesson${u.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);e.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await d.get("cachly:mcp:version:last_seen")!==Fe){await d.set("cachly:mcp:version:last_seen",Fe,"EX",365*86400);const r=pn[Fe];if(r){e.push(...r,"");const p=fn();p&&e.push(`\u{1F4CA} ${p} MCP tools`,"")}}}catch{}const oe=!S&&u.length===0&&M===0;if(oe&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),m?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${g}")\``),e.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),e.push(""),e.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),e.push("")),s&&!oe)try{const n=`cachly:team:first_briefing:${s}`;if(!await d.get(n)){const p=u.filter(c=>c.author&&c.author!==s);if(p.length>0){await d.set(n,"1","EX",365*86400);const c=new Map;for(const l of p){const T=l.author;c.has(T)||c.set(T,[]),c.get(T).push(l)}e.push(""),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),e.push(""),e.push("Your teammates have already solved problems you're about to hit:"),e.push("");for(const[l,T]of c){e.push(` \u{1F464} **${l}** fixed ${T.length} thing${T.length>1?"s":""}:`);for(const B of T.slice(0,2)){const P=B.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${P} \`${B.topic}\` \u2014 ${B.what_worked.slice(0,90)}`)}T.length>2&&e.push(` \u2026 and ${T.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const ce=await d.get("cachly:session:handoff");if(ce)try{const n=JSON.parse(ce),r=Math.round((Date.now()-new Date(n.ts).getTime())/6e4),p=r<60?`${r}m ago`:r<1440?`${Math.round(r/60)}h ago`:`${Math.round(r/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${p}):`),n.context_summary&&e.push(` ${n.context_summary}`),n.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const l of n.remaining_tasks)e.push(` - ${l}`)}n.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${n.completed_tasks.join(", ")}`);const c=(n.files_changed??[]).filter(l=>l.status==="broken"||l.status==="partial");c.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${c.map(l=>`\`${l.path}\` (${l.status}${l.description?": "+l.description:""})`).join(", ")}`),n.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${n.blocked_on}`),n.instructions&&e.push(` \u{1F4DD} **Instructions:** ${n.instructions}`),e.push("")}catch{}const he=await d.get("cachly:session:checkpoint");if(he)try{const n=JSON.parse(he),r=new Date(n.ts).getTime(),p=S?new Date(S.ts).getTime():0;if(r>p){const c=Math.round((Date.now()-r)/6e4),l=c<60?`${c}m ago`:c<1440?`${Math.round(c/60)}h ago`:`${Math.round(c/1440)}d ago`,T=n.provider?` [${n.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${T} (${l}): ${n.task}`),n.files_touched.length>0&&e.push(` Files: ${n.files_touched.slice(0,5).map(B=>`\`${B}\``).join(", ")}`),n.next_step&&e.push(` \u{1F4CD} Next step was: ${n.next_step}`),(!S||r-p>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(m&&!S)try{const{execSync:n}=await import("node:child_process"),r=n(`git -C "${m}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),p=n(`git -C "${m}" diff --stat HEAD~3 2>/dev/null || git -C "${m}" diff --stat 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim();if(r){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const c of r.split(`
32
+ `)}case"session_start":{const{instance_id:g,focus:t="",author:s="",provider:S="",workspace_path:m=""}=q,f=await V(g),$=[],a=f.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((o,r)=>{a.on("data",p=>$.push(...p)),a.on("end",o),a.on("error",r)});const u=[];if($.length>0){const o=await f.mget(...$);for(const r of o){const p=O(r??null,null);p&&u.push(p)}}u.sort((o,r)=>new Date(r.ts).getTime()-new Date(o.ts).getTime());let M=0;const n=f.scanStream({match:"cachly:ctx:*",count:200});await new Promise((o,r)=>{n.on("data",p=>{M+=p.filter(c=>!c.endsWith(":meta")).length}),n.on("end",o),n.on("error",r)});const _=await f.get("cachly:session:last"),C=O(_,null),h=t.toLowerCase().split(/\s+/).filter(Boolean),i=h.length>0?u.filter(o=>h.some(r=>o.topic.toLowerCase().includes(r)||(o.tags??[]).some(p=>p.toLowerCase().includes(r)))):[];let x=0,b=0,w="";try{const o=await f.get("cachly:streak:current"),r=O(o,null),p=new Date().toISOString().slice(0,10);if(r){const c=r.last_date,l=new Date(Date.now()-864e5).toISOString().slice(0,10);c===p?(x=r.days,b=r.record):c===l?(x=r.days+1,b=Math.max(x,r.record),await f.set("cachly:streak:current",JSON.stringify({days:x,last_date:p,record:b}))):(x=1,b=r.record,await f.set("cachly:streak:current",JSON.stringify({days:1,last_date:p,record:b})))}else x=1,b=1,await f.set("cachly:streak:current",JSON.stringify({days:1,last_date:p,record:1}));x>=7?w=`\u{1F525} **${x}-day streak!** ${x===b?" New record!":`Best: ${b}d`}`:x>1&&(w=`\u{1F525} ${x}-day streak`)}catch{}await f.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:t,provider:S}),"EX",86400);let A=0;try{const o=await f.get(`cachly:stats:time_saved_mins:${g}`);A=parseFloat(o??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${S?` \xB7 ${S}`:""}`,""];if(w&&e.push(w,""),A>=30){const o=Math.floor(A/60),r=Math.round(A%60),p=o>0?`${o}h${r>0?` ${r}m`:""}`:`${r}m`,c=u.filter(T=>!Le(T)&&(T.recall_count??0)>0).length,l=c>0?` \u2014 ${c} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${p} total**${l}`,"")}const F=await Et(g,ue),k=Hs({used:F.used,limit:F.limit,savedMins:A});if(k&&e.push(k,""),F.notice&&!Ct.has(g)&&(Ct.add(g),e.push(F.notice,"")),C?.ts){const o=new Date(C.ts).getTime(),r=Math.floor((Date.now()-o)/864e5);if(r>=7&&!Number.isNaN(o)){const p=u.filter(c=>{const l=new Date(c.ts).getTime();return!Number.isNaN(l)&&l>o});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${r} days since your last session.`),p.length>0){const c=p.slice(0,3).map(l=>`\`${l.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${p.length} lesson${p.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${c}${p.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${u.length} lesson${u.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);e.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await f.get("cachly:mcp:version:last_seen")!==Fe){await f.set("cachly:mcp:version:last_seen",Fe,"EX",365*86400);const r=pn[Fe];if(r){e.push(...r,"");const p=fn();p&&e.push(`\u{1F4CA} ${p} MCP tools`,"")}}}catch{}const oe=!C&&u.length===0&&M===0;if(oe&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),m?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${g}")\``),e.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),e.push(""),e.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),e.push("")),s&&!oe)try{const o=`cachly:team:first_briefing:${s}`;if(!await f.get(o)){const p=u.filter(c=>c.author&&c.author!==s);if(p.length>0){await f.set(o,"1","EX",365*86400);const c=new Map;for(const l of p){const T=l.author;c.has(T)||c.set(T,[]),c.get(T).push(l)}e.push(""),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),e.push(""),e.push("Your teammates have already solved problems you're about to hit:"),e.push("");for(const[l,T]of c){e.push(` \u{1F464} **${l}** fixed ${T.length} thing${T.length>1?"s":""}:`);for(const B of T.slice(0,2)){const P=B.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${P} \`${B.topic}\` \u2014 ${B.what_worked.slice(0,90)}`)}T.length>2&&e.push(` \u2026 and ${T.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const ce=await f.get("cachly:session:handoff");if(ce)try{const o=JSON.parse(ce),r=Math.round((Date.now()-new Date(o.ts).getTime())/6e4),p=r<60?`${r}m ago`:r<1440?`${Math.round(r/60)}h ago`:`${Math.round(r/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${p}):`),o.context_summary&&e.push(` ${o.context_summary}`),o.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const l of o.remaining_tasks)e.push(` - ${l}`)}o.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${o.completed_tasks.join(", ")}`);const c=(o.files_changed??[]).filter(l=>l.status==="broken"||l.status==="partial");c.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${c.map(l=>`\`${l.path}\` (${l.status}${l.description?": "+l.description:""})`).join(", ")}`),o.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${o.blocked_on}`),o.instructions&&e.push(` \u{1F4DD} **Instructions:** ${o.instructions}`),e.push("")}catch{}const he=await f.get("cachly:session:checkpoint");if(he)try{const o=JSON.parse(he),r=new Date(o.ts).getTime(),p=C?new Date(C.ts).getTime():0;if(r>p){const c=Math.round((Date.now()-r)/6e4),l=c<60?`${c}m ago`:c<1440?`${Math.round(c/60)}h ago`:`${Math.round(c/1440)}d ago`,T=o.provider?` [${o.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${T} (${l}): ${o.task}`),o.files_touched.length>0&&e.push(` Files: ${o.files_touched.slice(0,5).map(B=>`\`${B}\``).join(", ")}`),o.next_step&&e.push(` \u{1F4CD} Next step was: ${o.next_step}`),(!C||r-p>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(m&&!C)try{const{execSync:o}=await import("node:child_process"),r=o(`git -C "${m}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),p=o(`git -C "${m}" diff --stat HEAD~3 2>/dev/null || git -C "${m}" diff --stat 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim();if(r){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const c of r.split(`
33
33
  `).slice(0,8))e.push(` ${c}`);if(p){const c=p.split(`
34
- `).filter(l=>l.includes("|")||l.includes("changed"));if(c.length>0){e.push(" **Recent changes:**");for(const l of c.slice(0,5))e.push(` ${l.trim()}`)}}e.push("")}}catch{}if(S){const n=Math.round((Date.now()-new Date(S.ts).getTime())/6e4),r=n<60?`${n}m ago`:n<1440?`${Math.round(n/60)}h ago`:`${Math.round(n/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${r}): ${S.summary}`),S.duration_min&&e.push(` Duration: ${S.duration_min} min`),(S.files_changed??[]).length>0&&e.push(` Files: ${(S.files_changed??[]).slice(0,5).map(p=>`\`${p}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${u.length} lessons \xB7 ${M} context entries`,"");{const r=u.filter(p=>!Le(p)).filter(p=>p.outcome==="success"&&(p.pinned===!0||(p.recall_count??0)>=5)).sort((p,c)=>(c.recall_count??0)-(p.recall_count??0)).slice(0,5);if(r.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const p of r){const c=p.severity==="critical"?"\u{1F534}":p.severity==="major"?"\u{1F7E1}":"",l=p.recall_count??0,T=p.pinned===!0?"pinned":`recalled ${l}\xD7`,B=Me(p);e.push(` \u{1F3C6}${c} \`${p.topic}\` _(${T})_ \u2014 ${B[0]??""}`,...B.slice(1))}e.push("")}}if(u.length>=3){const n=new Map;for(const c of u){const l=c.topic.split(":")[0]??"other";n.has(l)||n.set(l,{total:0,success:0,critical:0});const T=n.get(l);T.total++,c.outcome==="success"&&T.success++,c.severity==="critical"&&T.critical++}const r=[...n.entries()].sort((c,l)=>l[1].total-c[1].total).slice(0,6),p=r.some(([,c])=>c.success<c.total*.4&&c.total>=2);if(r.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[c,l]of r){const T=Math.round(l.success/l.total*100),B=Math.round(T/10),P="\u2588".repeat(B)+"\u2591".repeat(10-B),N=l.critical>0?" \u{1F534}":T<40&&l.total>=2?" \u26A0\uFE0F":"";e.push(` ${P} ${c.padEnd(18)} ${String(T).padStart(3)}% (${l.success}/${l.total} confirmed)${N}`)}p&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}try{const n=[],r=d.scanStream({match:"cachly:ckg:conflict:*",count:50});if(await new Promise((p,c)=>{r.on("data",l=>n.push(...l)),r.on("end",p),r.on("error",c)}),n.length>0){e.push(`\u26A1 **Active belief conflicts (${n.length}):**`);for(const p of n.slice(0,3)){const c=await d.get(p);if(!c)continue;const l=O(c,null);l&&e.push(` \u26A0\uFE0F \`${l.topic}\` \u2014 previously confirmed fix (${(l.fix_confidence*100).toFixed(0)}%, n=${l.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${me(l.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const n=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(p=>p.length>3),r=[];for(const p of n.slice(0,6))if(!await d.exists(`cachly:ckg:node:${p}`)){const l=[],T=d.scanStream({match:`cachly:ckg:node:${p}*`,count:10});await new Promise((B,P)=>{T.on("data",N=>l.push(...N)),T.on("end",B),T.on("error",P)}),l.length===0&&r.push(p)}if(r.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const p of r.slice(0,3))e.push(` \u2B1C \`${p}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${p}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${p}")\` \u2014 search global commons`);e.push("")}}catch{}if(i.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const n of i.slice(0,4)){const r=n.outcome==="success"?"\u2705":n.outcome==="partial"?"\u26A0\uFE0F":"\u274C",p=n.severity==="critical"?"\u{1F534}":n.severity==="major"?"\u{1F7E1}":"",c=Me(n);e.push(` ${r}${p} \`${n.topic}\` \u2014 ${c[0]??""}`,...c.slice(1))}e.push("")}if(u.length>0){const r=[...u].filter(c=>!Le(c)).sort((c,l)=>(l.recall_count??0)-(c.recall_count??0)).filter(c=>(c.recall_count??0)>0).slice(0,3),p=(i.length>0?u.filter(c=>!i.includes(c)):u).filter(c=>!r.includes(c)).slice(0,i.length>0?3:4);if(r.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${r[0].recall_count}\xD7 before):`);for(const c of r){const l=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",T=c.severity==="critical"?"\u{1F534}":c.severity==="major"?"\u{1F7E1}":"",B=c.recall_count??0,P=c.authors??(c.author?[c.author]:[]),N=new Set(P.filter(Boolean)).size,W=N>=2&&B>=5||B>=10?" \u{1F3C6}":N>=2||B>=5?" \u2705":"",ee=B>1?` _(${B}\xD7 recalled)_`:"",le=Me(c);e.push(` ${l}${T}${W} \`${c.topic}\`${ee} \u2014 ${le[0]??""}`,...le.slice(1))}e.push("")}if(p.length>0){const c=r.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(c);for(const l of p){const T=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",B=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",P=Me(l);e.push(` ${T}${B} \`${l.topic}\` \u2014 ${P[0]??""}`,...P.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");u.length>=10&&(u.some(r=>r.author)||(e.push(`\u{1F91D} **Your Brain has ${u.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const R=u.filter(n=>n.outcome==="failure"||n.outcome==="partial");if(R.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${R.length} topic${R.length>1?"s":""} with no success yet):`);for(const n of R.slice(0,3))e.push(` \u274C \`${n.topic}\` \u2014 ${(n.what_failed??n.what_worked).slice(0,80)}`);e.push("")}const E=u.filter(n=>n.outcome!=="success"&&n.outcome!=="partial"?!1:Re(n)<tt);if(E.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Rt}d \u2014 verify before applying):`);for(const n of E.slice(0,4)){const r=Re(n),p=Math.round((Date.now()-new Date(n.verified_at??n.ts).getTime())/864e5),c=r<Dt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${c} \`${n.topic}\` \u2014 ${p}d stale, ${(r*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const J=S;if(J?.decision_log?.length){const n=J.decision_log,r=n.filter(c=>c.outcome==="success"),p=n.filter(c=>c.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${n.length} lessons stored):`),r.length>0&&e.push(` \u2705 Worked: ${r.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),p.length>0&&e.push(` \u274C Failed: ${p.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),e.push("")}{const n=new Set(["src","lib","test","tests","dist","index","main","app","internal","pkg","cmd","node_modules","components","utils","ts","tsx","js","jsx","go","py","rs","java","json","yaml","yml"]),r=T=>{const B=new Set;for(const P of T)for(const N of P.toLowerCase().split(/[/\\._-]/))N.length>3&&!n.has(N)&&B.add(N);return[...B]};let p=h,c=t,l=!1;if(p.length===0&&S){const T=r(S.files_changed??[]),B=(S.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(P=>P.length>3&&!n.has(P));p=[...new Set([...T,...B])],c="where you left off last session",l=!0}if(p.length>0){const T=u.filter(B=>{if(B.outcome==="success")return!1;const P=B.topic.split(":")[0];return p.some(N=>B.topic.toLowerCase().includes(N)||P===N||(B.tags??[]).some(W=>W.toLowerCase()===N))});if(T.length>=1){const P=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",l?` You're likely to continue **${c}** \u2014 ${T.length} known pitfall${T.length>1?"s":""} there:`:` Known pitfalls for **"${c}"** (${T.length} past failure${T.length>1?"s":""}):`,...T.slice(0,3).map(N=>` \u274C \`${N.topic}\` \u2014 ${(N.what_failed??N.what_worked).slice(0,80)}`),""];e.splice(2,0,...P)}}}if(s){const n=Date.now()-6048e5,r=u.filter(p=>p.author&&p.author!==s&&new Date(p.ts).getTime()>n);if(r.length>0){const p=new Map;for(const c of r){const l=c.author;p.has(l)||p.set(l,[]),p.get(l).push(c)}e.push(`\u{1F465} **Team this week** (${r.length} lesson${r.length>1?"s":""} from teammates):`);for(const[c,l]of p){e.push(` \u{1F464} **${c}**:`);for(const T of l.slice(0,3)){const B=T.outcome==="success"?"\u2705":T.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${B} \`${T.topic}\` \u2014 ${T.what_worked.slice(0,80)}`)}l.length>3&&e.push(` \u2026 and ${l.length-3} more`)}e.push("")}}try{const n=await d.get("cachly:crystal:latest");if(n){const r=O(n,null);if(r&&Math.round((Date.now()-new Date(r.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${r.label} \xB7 ${r.session_count} sessions compressed):`);for(const c of r.top_patterns.slice(0,3))e.push(` \u2022 **${c.category}** (${c.count}\xD7): ${c.insight.slice(0,90)}`);e.push("")}}}catch{}try{const n=await d.hgetall(`cachly:roadmap:${g}`);if(n&&Object.keys(n).length>0){const r={critical:0,high:1,medium:2,low:3},p={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},c=new Set(["planned","in-progress","blocked"]),l=Object.values(n).flatMap(P=>{const N=O(P,null);return N?[N]:[]}),T=l.filter(P=>c.has(P.status)).sort((P,N)=>P.status==="in-progress"&&N.status!=="in-progress"?-1:N.status==="in-progress"&&P.status!=="in-progress"?1:(r[P.priority]??99)-(r[N.priority]??99)),B=l.filter(P=>P.status==="done").length;if(T.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${T.length} open \xB7 ${B} done):`);for(const P of T.slice(0,5)){const N=P.status==="in-progress"?"\u26A1":P.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${N} ${p[P.priority]??"\u26AA"} \`${P.id}\` **${P.title}**`)}T.length>5&&e.push(` \u2026 and ${T.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const n=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2).slice(0,5),r=[];for(const l of n){const T=[],B=d.scanStream({match:`cachly:ckg:node:*${l}*`,count:20});await new Promise((P,N)=>{B.on("data",W=>T.push(...W)),B.on("end",P),B.on("error",N)});for(const P of T.slice(0,3)){const N=await d.get(P);if(!N)continue;const W=O(N,null);if(!W)continue;const ee=await d.smembers(`cachly:ckg:idx:from:${W.id}`);for(const le of ee.slice(0,15)){const we=await d.get(le);if(!we)continue;const ne=O(we,null);if(!ne||ne.edgeType!=="causes"&&ne.edgeType!=="co-occurs"&&ne.edgeType!=="fixes"||ne.confidence<.35)continue;const fe=ne.edgeType==="fixes"?`cachly:lesson:best:${ne.from}`:`cachly:lesson:best:${ne.to}`,f=await d.get(fe),y=O(f,null);r.push({concept:W.id,edgeType:ne.edgeType,target:ne.to,confidence:ne.confidence,lesson:y??void 0})}}}const p=new Set,c=r.filter(l=>{const T=`${l.concept}:${l.target}`;return p.has(T)?!1:(p.add(T),!0)}).sort((l,T)=>T.confidence-l.confidence).slice(0,4);if(c.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const l of c){const T=Math.round(l.confidence*100),B=l.edgeType==="causes"?"\u26A1":l.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${B} **${T}%** \`${l.concept}\` ${l.edgeType} \`${l.target}\``),l.lesson?.what_worked&&e.push(` \u2705 ${l.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const n=await d.get("cachly:mcm:calibration:last"),r=O(n,null)?.ts??0;if((Date.now()-r)/864e5>=30&&u.length>=5){const c=u.filter(T=>T.outcome==="success"&&(T.recall_count??0)>0),l=u.filter(T=>(T.recall_count??0)>0);if(l.length>=3){const T=l.length>0?c.length/l.length:1,B=[],P=new Map;for(const N of l){const W=N.topic.split(":")[0]??"other";P.has(W)||P.set(W,{success:0,total:0});const ee=P.get(W);ee.total++,N.outcome==="success"&&ee.success++}for(const[N,W]of P)W.total>=2&&W.success/W.total<.6&&B.push(N);await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:T,recalled:l.length,low_precision_domains:B})),(B.length>0||T<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${l.length} recalled lessons):`),e.push(` Overall precision: **${(T*100).toFixed(0)}%** recalled lessons actually worked`),B.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${B.map(N=>`\`${N}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await d.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const n=await ue("/api/v1/syndication/stats");n.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${n.total_lessons.toLocaleString()} lessons \xB7 ${n.total_confirms.toLocaleString()} confirms \xB7 +${n.added_last_7_days} this week`),e.push(""))}catch{}const se=u.filter(n=>n.outcome==="failure"||n.outcome==="partial").length>0,V=u.some(n=>n.outcome==="success"&&Re(n)<tt);if(u.length===0||se||V){const n=[];u.length===0&&n.push("brain is empty"),se&&n.push("open failures"),V&&n.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${n.join(", ")}._`)}try{if(await d.get(`cachly:prefs:auto_changelog:${g}`).catch(()=>null)!=="false"&&S?.ts&&!oe){const p=new Date(S.ts).getTime();if(!Number.isNaN(p)){const c=u.filter(l=>{const T=new Date(l.ts).getTime();return!Number.isNaN(T)&&T>p});if(c.length>0){const l=Math.round((Date.now()-p)/6e4),T=l<60?`${l}m`:l<1440?`${Math.round(l/60)}h`:`${Math.round(l/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${c.length} new lesson${c.length!==1?"s":""} since your last session** (${T} ago):`);const B=new Map;for(const P of c.slice(0,20)){const N=P.topic.includes(":")?P.topic.split(":")[0]:"general",W=B.get(N)??[];W.push(P),B.set(N,W)}for(const[P,N]of B){e.push(` **${P}**`);for(const W of N){const ee=W.outcome==="failure"?"\u274C":W.severity==="critical"?"\u{1F6A8}":W.severity==="major"?"\u26A0\uFE0F":"\u2705",le=(W.outcome==="failure"?W.what_failed:W.what_worked)??"";e.push(` ${ee} \`${W.topic}\`${le?` \u2014 ${le.slice(0,80)}`:""}`)}}c.length>20&&e.push(` \u2026 and ${c.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${g}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
35
- `)}case"session_start_summary":{const{instance_id:g,focus:t,top_n:s=10,author:k=""}=H;if(!t||!t.trim())throw new Error("focus is required for session_start_summary");const m=Math.min(Math.max(1,Math.floor(Number(s)||10)),25),d=await U(g),$=[],a=d.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,j)=>{a.on("data",v=>$.push(...v)),a.on("end",e),a.on("error",j)});const u=[];if($.length>0){const e=await d.mget(...$);for(const j of e){const v=O(j??null,null);v&&u.push(v)}}if(u.length===0)return["\u{1F9E0} Brain Summary \u2014 no lessons yet","","Your brain is empty. Use `learn_from_attempts` after solving tasks to build it up.",`\u{1F4A1} Tip: \`brain_seed_starter(instance_id="${g}")\` to bootstrap with 16 universal lessons.`].join(`
36
- `);const M=u.length>m,o=t.toLowerCase().split(/\s+/).filter(Boolean),_=Date.now(),S=u.map(e=>{const j=o.filter(n=>e.topic.toLowerCase().includes(n)).length,v=o.filter(n=>(e.tags??[]).some(r=>r.toLowerCase().includes(n))).length,oe=j*2+v,ce=Math.max(0,e.recall_count??0),he=Math.min(1.5,Math.log1p(ce)/10),R=e.severity==="critical"?1:e.severity==="major"?.5:0,E=(_-new Date(e.verified_at??e.ts).getTime())/864e5,J=E<30?.5*(1-E/30):0,se=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,V=oe+he+R+J+se;return{lesson:e,score:V}});S.sort((e,j)=>j.score!==e.score?j.score-e.score:new Date(j.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const h=(M?S.slice(0,m):S).map(e=>e.lesson),i=u.length,x=h.length,A=[M?`\u{1F9E0} Brain Summary \u2014 top ${x} of ${i} lessons for "${t}"`:`\u{1F9E0} Brain Summary \u2014 all ${x} lesson${x!==1?"s":""} for "${t}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(const e of h){const j=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",v=e.severity?`[${e.severity}] `:"[minor] ",oe=e.recall_count??0,ce=oe>0?` (\u2713 recalled ${oe}\xD7)`:"",he=e.what_worked.slice(0,110),R=un(e.author,k);A.push(`${j} ${v}\`${e.topic}\` \u2014 ${he}${ce}${R}`)}A.push("");const I=hn(h,k);return I>0&&A.push(`\u{1F465} ${I} of these ${I===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),M?A.push(`\u{1F4A1} Showing top ${x} of ${i} lessons \xB7 \`session_start\` for full briefing`):A.push(`\u{1F4A1} All ${x} lesson${x!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),A.join(`
37
- `)}case"session_end":{const{instance_id:g,summary:t,files_changed:s=[],lessons_learned:k,workspace_path:m=""}=H,d=await U(g),$=new Date;let a;const u=await d.get("cachly:session:current");if(!u)return"\u26A0\uFE0F No active session found.\n\nRun `session_start` first to begin tracking a session, then call `session_end` when you're done.";const M=O(u,null);M?.started&&(a=Math.round(($.getTime()-new Date(M.started).getTime())/6e4));let o=[];try{o=(await d.lrange("cachly:session:decision-log",0,-1)).flatMap(v=>{const oe=O(v,null);return oe?[oe]:[]}),await d.del("cachly:session:decision-log")}catch{}const _=js(g);Fs(g);const S={ts:$.toISOString(),summary:t,files_changed:s,..._.recalls>0?{memory_cost:_}:{},...k!==void 0?{lessons_learned:k}:{},...a!==void 0?{duration_min:a}:{},...o.length>0?{decision_log:o}:{}};await d.set("cachly:session:last",JSON.stringify(S)),await d.lpush("cachly:session:history",JSON.stringify(S)),await d.ltrim("cachly:session:history",0,49),await d.expire("cachly:session:history",90*86400),await d.del("cachly:session:current");const h=[];try{const j=/\b(fixed|deployed|added|removed|refactored|migrated|updated|resolved|implemented|improved|optimized|configured|created|deleted|disabled|enabled|discovered|found|learned|debugged|patched|upgraded|installed|tested|built|rewrote|moved|renamed|split|merged|extracted)\b/i,v=t.split(/[.!\n]+/).map(oe=>oe.trim()).filter(oe=>oe.length>20&&j.test(oe));for(const oe of v.slice(0,6)){const he=oe.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(V=>V.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(V)).slice(0,4).join("-");if(!he)continue;const R=`auto:${he}`,E=`cachly:lesson:best:${R}`,J=await d.get(E);if(J)try{if(JSON.parse(J).outcome==="success")continue}catch{}const se={topic:R,outcome:"success",what_worked:oe,context:`Auto-learned from session summary. Full summary: ${t.slice(0,300)}`,severity:"minor",ts:$.toISOString(),recall_count:0,auto_learned:!0,session_ts:$.toISOString(),version:2};await d.set(E,JSON.stringify(se)),await d.expire(E,90*86400),h.push(R)}}catch{}const i=[];if(m)try{const j=u?(()=>{try{return JSON.parse(u).started??""}catch{return""}})():"",v=j?`--since="${j}"`:'--since="1 hour ago"',oe=Qe(`git -C "${m}" log ${v} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(oe){const ce=/\b(fix|add|remove|refactor|migrate|update|resolve|implement|improve|optimize|configure|create|delete|disable|enable|debug|patch|upgrade|build|rewrite|deploy|feat|chore|docs|test|perf|ci)\b/i,he=oe.split("|||ENDE").map(R=>R.trim()).filter(Boolean);for(const R of he.slice(0,10)){const[E,J,se,V]=R.split("|||");if(E)try{const B=Qe(`git -C "${m}" diff-tree --no-commit-id --name-only -r --root "${E}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),N=B?B.split(`
38
- `).map(ee=>ee.trim()).filter(Boolean).slice(0,12):[],W=[];for(const ee of N)W.push(await st(d,ee));for(let ee=0;ee<W.length;ee++)for(let le=ee+1;le<W.length;le++)await ge(d,W[ee],"co-occurs",W[le],!0),await ge(d,W[le],"co-occurs",W[ee],!0)}catch{}if(!J||!ce.test(J))continue;const n=(se??"").trim();if(n.length<120)continue;const r=J.toLowerCase().replace(/^(fix|feat|chore|docs|test|ci|perf|refactor|build|revert)[:(\s]/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);if(!r)continue;const p=`git:${r}`,c=`cachly:lesson:best:${p}`;if(await d.get(c))continue;const T={topic:p,outcome:"success",what_worked:`${J}
34
+ `).filter(l=>l.includes("|")||l.includes("changed"));if(c.length>0){e.push(" **Recent changes:**");for(const l of c.slice(0,5))e.push(` ${l.trim()}`)}}e.push("")}}catch{}if(C){const o=Math.round((Date.now()-new Date(C.ts).getTime())/6e4),r=o<60?`${o}m ago`:o<1440?`${Math.round(o/60)}h ago`:`${Math.round(o/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${r}): ${C.summary}`),C.duration_min&&e.push(` Duration: ${C.duration_min} min`),(C.files_changed??[]).length>0&&e.push(` Files: ${(C.files_changed??[]).slice(0,5).map(p=>`\`${p}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${u.length} lessons \xB7 ${M} context entries`,"");{const r=u.filter(p=>!Le(p)).filter(p=>p.outcome==="success"&&(p.pinned===!0||(p.recall_count??0)>=5)).sort((p,c)=>(c.recall_count??0)-(p.recall_count??0)).slice(0,5);if(r.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const p of r){const c=p.severity==="critical"?"\u{1F534}":p.severity==="major"?"\u{1F7E1}":"",l=p.recall_count??0,T=p.pinned===!0?"pinned":`recalled ${l}\xD7`,B=Me(p);e.push(` \u{1F3C6}${c} \`${p.topic}\` _(${T})_ \u2014 ${B[0]??""}`,...B.slice(1))}e.push("")}}if(u.length>=3){const o=new Map;for(const c of u){const l=c.topic.split(":")[0]??"other";o.has(l)||o.set(l,{total:0,success:0,critical:0});const T=o.get(l);T.total++,c.outcome==="success"&&T.success++,c.severity==="critical"&&T.critical++}const r=[...o.entries()].sort((c,l)=>l[1].total-c[1].total).slice(0,6),p=r.some(([,c])=>c.success<c.total*.4&&c.total>=2);if(r.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[c,l]of r){const T=Math.round(l.success/l.total*100),B=Math.round(T/10),P="\u2588".repeat(B)+"\u2591".repeat(10-B),N=l.critical>0?" \u{1F534}":T<40&&l.total>=2?" \u26A0\uFE0F":"";e.push(` ${P} ${c.padEnd(18)} ${String(T).padStart(3)}% (${l.success}/${l.total} confirmed)${N}`)}p&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}try{const o=[],r=f.scanStream({match:"cachly:ckg:conflict:*",count:50});if(await new Promise((p,c)=>{r.on("data",l=>o.push(...l)),r.on("end",p),r.on("error",c)}),o.length>0){e.push(`\u26A1 **Active belief conflicts (${o.length}):**`);for(const p of o.slice(0,3)){const c=await f.get(p);if(!c)continue;const l=O(c,null);l&&e.push(` \u26A0\uFE0F \`${l.topic}\` \u2014 previously confirmed fix (${(l.fix_confidence*100).toFixed(0)}%, n=${l.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${me(l.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const o=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(p=>p.length>3),r=[];for(const p of o.slice(0,6))if(!await f.exists(`cachly:ckg:node:${p}`)){const l=[],T=f.scanStream({match:`cachly:ckg:node:${p}*`,count:10});await new Promise((B,P)=>{T.on("data",N=>l.push(...N)),T.on("end",B),T.on("error",P)}),l.length===0&&r.push(p)}if(r.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const p of r.slice(0,3))e.push(` \u2B1C \`${p}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${p}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${p}")\` \u2014 search global commons`);e.push("")}}catch{}if(i.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const o of i.slice(0,4)){const r=o.outcome==="success"?"\u2705":o.outcome==="partial"?"\u26A0\uFE0F":"\u274C",p=o.severity==="critical"?"\u{1F534}":o.severity==="major"?"\u{1F7E1}":"",c=Me(o);e.push(` ${r}${p} \`${o.topic}\` \u2014 ${c[0]??""}`,...c.slice(1))}e.push("")}if(u.length>0){const r=[...u].filter(c=>!Le(c)).sort((c,l)=>(l.recall_count??0)-(c.recall_count??0)).filter(c=>(c.recall_count??0)>0).slice(0,3),p=(i.length>0?u.filter(c=>!i.includes(c)):u).filter(c=>!r.includes(c)).slice(0,i.length>0?3:4);if(r.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${r[0].recall_count}\xD7 before):`);for(const c of r){const l=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",T=c.severity==="critical"?"\u{1F534}":c.severity==="major"?"\u{1F7E1}":"",B=c.recall_count??0,P=c.authors??(c.author?[c.author]:[]),N=new Set(P.filter(Boolean)).size,W=N>=2&&B>=5||B>=10?" \u{1F3C6}":N>=2||B>=5?" \u2705":"",ee=B>1?` _(${B}\xD7 recalled)_`:"",le=Me(c);e.push(` ${l}${T}${W} \`${c.topic}\`${ee} \u2014 ${le[0]??""}`,...le.slice(1))}e.push("")}if(p.length>0){const c=r.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(c);for(const l of p){const T=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",B=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",P=Me(l);e.push(` ${T}${B} \`${l.topic}\` \u2014 ${P[0]??""}`,...P.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");u.length>=10&&(u.some(r=>r.author)||(e.push(`\u{1F91D} **Your Brain has ${u.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const R=u.filter(o=>o.outcome==="failure"||o.outcome==="partial");if(R.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${R.length} topic${R.length>1?"s":""} with no success yet):`);for(const o of R.slice(0,3))e.push(` \u274C \`${o.topic}\` \u2014 ${(o.what_failed??o.what_worked).slice(0,80)}`);e.push("")}const E=u.filter(o=>o.outcome!=="success"&&o.outcome!=="partial"?!1:Re(o)<tt);if(E.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Rt}d \u2014 verify before applying):`);for(const o of E.slice(0,4)){const r=Re(o),p=Math.round((Date.now()-new Date(o.verified_at??o.ts).getTime())/864e5),c=r<Dt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${c} \`${o.topic}\` \u2014 ${p}d stale, ${(r*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const H=C;if(H?.decision_log?.length){const o=H.decision_log,r=o.filter(c=>c.outcome==="success"),p=o.filter(c=>c.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${o.length} lessons stored):`),r.length>0&&e.push(` \u2705 Worked: ${r.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),p.length>0&&e.push(` \u274C Failed: ${p.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),e.push("")}{const o=new Set(["src","lib","test","tests","dist","index","main","app","internal","pkg","cmd","node_modules","components","utils","ts","tsx","js","jsx","go","py","rs","java","json","yaml","yml"]),r=T=>{const B=new Set;for(const P of T)for(const N of P.toLowerCase().split(/[/\\._-]/))N.length>3&&!o.has(N)&&B.add(N);return[...B]};let p=h,c=t,l=!1;if(p.length===0&&C){const T=r(C.files_changed??[]),B=(C.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(P=>P.length>3&&!o.has(P));p=[...new Set([...T,...B])],c="where you left off last session",l=!0}if(p.length>0){const T=u.filter(B=>{if(B.outcome==="success")return!1;const P=B.topic.split(":")[0];return p.some(N=>B.topic.toLowerCase().includes(N)||P===N||(B.tags??[]).some(W=>W.toLowerCase()===N))});if(T.length>=1){const P=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",l?` You're likely to continue **${c}** \u2014 ${T.length} known pitfall${T.length>1?"s":""} there:`:` Known pitfalls for **"${c}"** (${T.length} past failure${T.length>1?"s":""}):`,...T.slice(0,3).map(N=>` \u274C \`${N.topic}\` \u2014 ${(N.what_failed??N.what_worked).slice(0,80)}`),""];e.splice(2,0,...P)}}}if(s){const o=Date.now()-6048e5,r=u.filter(p=>p.author&&p.author!==s&&new Date(p.ts).getTime()>o);if(r.length>0){const p=new Map;for(const c of r){const l=c.author;p.has(l)||p.set(l,[]),p.get(l).push(c)}e.push(`\u{1F465} **Team this week** (${r.length} lesson${r.length>1?"s":""} from teammates):`);for(const[c,l]of p){e.push(` \u{1F464} **${c}**:`);for(const T of l.slice(0,3)){const B=T.outcome==="success"?"\u2705":T.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${B} \`${T.topic}\` \u2014 ${T.what_worked.slice(0,80)}`)}l.length>3&&e.push(` \u2026 and ${l.length-3} more`)}e.push("")}}try{const o=await f.get("cachly:crystal:latest");if(o){const r=O(o,null);if(r&&Math.round((Date.now()-new Date(r.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${r.label} \xB7 ${r.session_count} sessions compressed):`);for(const c of r.top_patterns.slice(0,3))e.push(` \u2022 **${c.category}** (${c.count}\xD7): ${c.insight.slice(0,90)}`);e.push("")}}}catch{}try{const o=await f.hgetall(`cachly:roadmap:${g}`);if(o&&Object.keys(o).length>0){const r={critical:0,high:1,medium:2,low:3},p={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},c=new Set(["planned","in-progress","blocked"]),l=Object.values(o).flatMap(P=>{const N=O(P,null);return N?[N]:[]}),T=l.filter(P=>c.has(P.status)).sort((P,N)=>P.status==="in-progress"&&N.status!=="in-progress"?-1:N.status==="in-progress"&&P.status!=="in-progress"?1:(r[P.priority]??99)-(r[N.priority]??99)),B=l.filter(P=>P.status==="done").length;if(T.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${T.length} open \xB7 ${B} done):`);for(const P of T.slice(0,5)){const N=P.status==="in-progress"?"\u26A1":P.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${N} ${p[P.priority]??"\u26AA"} \`${P.id}\` **${P.title}**`)}T.length>5&&e.push(` \u2026 and ${T.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const o=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2).slice(0,5),r=[];for(const l of o){const T=[],B=f.scanStream({match:`cachly:ckg:node:*${l}*`,count:20});await new Promise((P,N)=>{B.on("data",W=>T.push(...W)),B.on("end",P),B.on("error",N)});for(const P of T.slice(0,3)){const N=await f.get(P);if(!N)continue;const W=O(N,null);if(!W)continue;const ee=await f.smembers(`cachly:ckg:idx:from:${W.id}`);for(const le of ee.slice(0,15)){const we=await f.get(le);if(!we)continue;const ne=O(we,null);if(!ne||ne.edgeType!=="causes"&&ne.edgeType!=="co-occurs"&&ne.edgeType!=="fixes"||ne.confidence<.35)continue;const fe=ne.edgeType==="fixes"?`cachly:lesson:best:${ne.from}`:`cachly:lesson:best:${ne.to}`,d=await f.get(fe),y=O(d,null);r.push({concept:W.id,edgeType:ne.edgeType,target:ne.to,confidence:ne.confidence,lesson:y??void 0})}}}const p=new Set,c=r.filter(l=>{const T=`${l.concept}:${l.target}`;return p.has(T)?!1:(p.add(T),!0)}).sort((l,T)=>T.confidence-l.confidence).slice(0,4);if(c.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const l of c){const T=Math.round(l.confidence*100),B=l.edgeType==="causes"?"\u26A1":l.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${B} **${T}%** \`${l.concept}\` ${l.edgeType} \`${l.target}\``),l.lesson?.what_worked&&e.push(` \u2705 ${l.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const o=await f.get("cachly:mcm:calibration:last"),r=O(o,null)?.ts??0;if((Date.now()-r)/864e5>=30&&u.length>=5){const c=u.filter(T=>T.outcome==="success"&&(T.recall_count??0)>0),l=u.filter(T=>(T.recall_count??0)>0);if(l.length>=3){const T=l.length>0?c.length/l.length:1,B=[],P=new Map;for(const N of l){const W=N.topic.split(":")[0]??"other";P.has(W)||P.set(W,{success:0,total:0});const ee=P.get(W);ee.total++,N.outcome==="success"&&ee.success++}for(const[N,W]of P)W.total>=2&&W.success/W.total<.6&&B.push(N);await f.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:T,recalled:l.length,low_precision_domains:B})),(B.length>0||T<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${l.length} recalled lessons):`),e.push(` Overall precision: **${(T*100).toFixed(0)}%** recalled lessons actually worked`),B.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${B.map(N=>`\`${N}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await f.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const o=await ue("/api/v1/syndication/stats");o.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${o.total_lessons.toLocaleString()} lessons \xB7 ${o.total_confirms.toLocaleString()} confirms \xB7 +${o.added_last_7_days} this week`),e.push(""))}catch{}const se=u.filter(o=>o.outcome==="failure"||o.outcome==="partial").length>0,Y=u.some(o=>o.outcome==="success"&&Re(o)<tt);if(u.length===0||se||Y){const o=[];u.length===0&&o.push("brain is empty"),se&&o.push("open failures"),Y&&o.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${o.join(", ")}._`)}try{if(await f.get(`cachly:prefs:auto_changelog:${g}`).catch(()=>null)!=="false"&&C?.ts&&!oe){const p=new Date(C.ts).getTime();if(!Number.isNaN(p)){const c=u.filter(l=>{const T=new Date(l.ts).getTime();return!Number.isNaN(T)&&T>p});if(c.length>0){const l=Math.round((Date.now()-p)/6e4),T=l<60?`${l}m`:l<1440?`${Math.round(l/60)}h`:`${Math.round(l/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${c.length} new lesson${c.length!==1?"s":""} since your last session** (${T} ago):`);const B=new Map;for(const P of c.slice(0,20)){const N=P.topic.includes(":")?P.topic.split(":")[0]:"general",W=B.get(N)??[];W.push(P),B.set(N,W)}for(const[P,N]of B){e.push(` **${P}**`);for(const W of N){const ee=W.outcome==="failure"?"\u274C":W.severity==="critical"?"\u{1F6A8}":W.severity==="major"?"\u26A0\uFE0F":"\u2705",le=(W.outcome==="failure"?W.what_failed:W.what_worked)??"";e.push(` ${ee} \`${W.topic}\`${le?` \u2014 ${le.slice(0,80)}`:""}`)}}c.length>20&&e.push(` \u2026 and ${c.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${g}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
35
+ `)}case"session_start_summary":{const{instance_id:g,focus:t,top_n:s=10,author:S=""}=q;if(!t||!t.trim())throw new Error("focus is required for session_start_summary");const m=Math.min(Math.max(1,Math.floor(Number(s)||10)),25),f=await V(g),$=[],a=f.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,F)=>{a.on("data",k=>$.push(...k)),a.on("end",e),a.on("error",F)});const u=[];if($.length>0){const e=await f.mget(...$);for(const F of e){const k=O(F??null,null);k&&u.push(k)}}if(u.length===0)return["\u{1F9E0} Brain Summary \u2014 no lessons yet","","Your brain is empty. Use `learn_from_attempts` after solving tasks to build it up.",`\u{1F4A1} Tip: \`brain_seed_starter(instance_id="${g}")\` to bootstrap with 16 universal lessons.`].join(`
36
+ `);const M=u.length>m,n=t.toLowerCase().split(/\s+/).filter(Boolean),_=Date.now(),C=u.map(e=>{const F=n.filter(o=>e.topic.toLowerCase().includes(o)).length,k=n.filter(o=>(e.tags??[]).some(r=>r.toLowerCase().includes(o))).length,oe=F*2+k,ce=Math.max(0,e.recall_count??0),he=Math.min(1.5,Math.log1p(ce)/10),R=e.severity==="critical"?1:e.severity==="major"?.5:0,E=(_-new Date(e.verified_at??e.ts).getTime())/864e5,H=E<30?.5*(1-E/30):0,se=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,Y=oe+he+R+H+se;return{lesson:e,score:Y}});C.sort((e,F)=>F.score!==e.score?F.score-e.score:new Date(F.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const h=(M?C.slice(0,m):C).map(e=>e.lesson),i=u.length,x=h.length,A=[M?`\u{1F9E0} Brain Summary \u2014 top ${x} of ${i} lessons for "${t}"`:`\u{1F9E0} Brain Summary \u2014 all ${x} lesson${x!==1?"s":""} for "${t}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(const e of h){const F=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",k=e.severity?`[${e.severity}] `:"[minor] ",oe=e.recall_count??0,ce=oe>0?` (\u2713 recalled ${oe}\xD7)`:"",he=e.what_worked.slice(0,110),R=un(e.author,S);A.push(`${F} ${k}\`${e.topic}\` \u2014 ${he}${ce}${R}`)}A.push("");const I=hn(h,S);return I>0&&A.push(`\u{1F465} ${I} of these ${I===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),M?A.push(`\u{1F4A1} Showing top ${x} of ${i} lessons \xB7 \`session_start\` for full briefing`):A.push(`\u{1F4A1} All ${x} lesson${x!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),A.join(`
37
+ `)}case"session_end":{const{instance_id:g,summary:t,files_changed:s=[],lessons_learned:S,workspace_path:m=""}=q,f=await V(g),$=new Date;let a;const u=await f.get("cachly:session:current");if(!u)return"\u26A0\uFE0F No active session found.\n\nRun `session_start` first to begin tracking a session, then call `session_end` when you're done.";const M=O(u,null);M?.started&&(a=Math.round(($.getTime()-new Date(M.started).getTime())/6e4));let n=[];try{n=(await f.lrange("cachly:session:decision-log",0,-1)).flatMap(k=>{const oe=O(k,null);return oe?[oe]:[]}),await f.del("cachly:session:decision-log")}catch{}const _=js(g);Fs(g);const C={ts:$.toISOString(),summary:t,files_changed:s,..._.recalls>0?{memory_cost:_}:{},...S!==void 0?{lessons_learned:S}:{},...a!==void 0?{duration_min:a}:{},...n.length>0?{decision_log:n}:{}};await f.set("cachly:session:last",JSON.stringify(C)),await f.lpush("cachly:session:history",JSON.stringify(C)),await f.ltrim("cachly:session:history",0,49),await f.expire("cachly:session:history",90*86400),await f.del("cachly:session:current");const h=[];try{const F=/\b(fixed|deployed|added|removed|refactored|migrated|updated|resolved|implemented|improved|optimized|configured|created|deleted|disabled|enabled|discovered|found|learned|debugged|patched|upgraded|installed|tested|built|rewrote|moved|renamed|split|merged|extracted)\b/i,k=t.split(/[.!\n]+/).map(oe=>oe.trim()).filter(oe=>oe.length>20&&F.test(oe));for(const oe of k.slice(0,6)){const he=oe.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(Y=>Y.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(Y)).slice(0,4).join("-");if(!he)continue;const R=`auto:${he}`,E=`cachly:lesson:best:${R}`,H=await f.get(E);if(H)try{if(JSON.parse(H).outcome==="success")continue}catch{}const se={topic:R,outcome:"success",what_worked:oe,context:`Auto-learned from session summary. Full summary: ${t.slice(0,300)}`,severity:"minor",ts:$.toISOString(),recall_count:0,auto_learned:!0,session_ts:$.toISOString(),version:2};await f.set(E,JSON.stringify(se)),await f.expire(E,90*86400),h.push(R)}}catch{}const i=[];if(m)try{const F=u?(()=>{try{return JSON.parse(u).started??""}catch{return""}})():"",k=F?`--since="${F}"`:'--since="1 hour ago"',oe=Qe(`git -C "${m}" log ${k} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(oe){const ce=/\b(fix|add|remove|refactor|migrate|update|resolve|implement|improve|optimize|configure|create|delete|disable|enable|debug|patch|upgrade|build|rewrite|deploy|feat|chore|docs|test|perf|ci)\b/i,he=oe.split("|||ENDE").map(R=>R.trim()).filter(Boolean);for(const R of he.slice(0,10)){const[E,H,se,Y]=R.split("|||");if(E)try{const B=Qe(`git -C "${m}" diff-tree --no-commit-id --name-only -r --root "${E}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),N=B?B.split(`
38
+ `).map(ee=>ee.trim()).filter(Boolean).slice(0,12):[],W=[];for(const ee of N)W.push(await st(f,ee));for(let ee=0;ee<W.length;ee++)for(let le=ee+1;le<W.length;le++)await ge(f,W[ee],"co-occurs",W[le],!0),await ge(f,W[le],"co-occurs",W[ee],!0)}catch{}if(!H||!ce.test(H))continue;const o=(se??"").trim();if(o.length<120)continue;const r=H.toLowerCase().replace(/^(fix|feat|chore|docs|test|ci|perf|refactor|build|revert)[:(\s]/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);if(!r)continue;const p=`git:${r}`,c=`cachly:lesson:best:${p}`;if(await f.get(c))continue;const T={topic:p,outcome:"success",what_worked:`${H}
39
39
 
40
- ${n.slice(0,1200)}`,context:`Auto-learned from git commit ${(E??"").slice(0,7)} at ${V??""} in ${m}`,severity:"minor",ts:$.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3};await d.set(c,JSON.stringify(T)),await d.expire(c,60*86400),i.push(p)}}}catch{}const x=a!==void 0?` \xB7 ${a} min`:"",b=h.length+i.length,w=[];a!==void 0&&a>0&&w.push(`\u23F1 ${a} min session`),b>0&&w.push(`\u{1F9E0} ${b} lessons saved to Brain`),s.length>0&&w.push(`\u{1F4C1} ${s.length} file${s.length>1?"s":""} changed`);const A=w.length>0?`${w.join(" \xB7 ")}
40
+ ${o.slice(0,1200)}`,context:`Auto-learned from git commit ${(E??"").slice(0,7)} at ${Y??""} in ${m}`,severity:"minor",ts:$.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3};await f.set(c,JSON.stringify(T)),await f.expire(c,60*86400),i.push(p)}}}catch{}const x=a!==void 0?` \xB7 ${a} min`:"",b=h.length+i.length,w=[];a!==void 0&&a>0&&w.push(`\u23F1 ${a} min session`),b>0&&w.push(`\u{1F9E0} ${b} lessons saved to Brain`),s.length>0&&w.push(`\u{1F4C1} ${s.length} file${s.length>1?"s":""} changed`);const A=w.length>0?`${w.join(" \xB7 ")}
41
41
 
42
42
  My AI Brain remembers this so I never repeat it. @cachlydev
43
43
  cachly.dev`:`Session saved to my AI Brain. No more re-explaining this tomorrow. @cachlydev
44
- cachly.dev`,I=`https://twitter.com/intent/tweet?text=${encodeURIComponent(A)}`,e=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",a!==void 0?`\u2502 \u23F1 Duration : ${(a+" min").padEnd(26)}\u2502`:"",b>0?`\u2502 \u{1F4DA} Learned : ${(b+" lessons").padEnd(26)}\u2502`:"",s.length>0?`\u2502 \u{1F4C1} Changed : ${(s.length+" file"+(s.length>1?"s":"")).padEnd(26)}\u2502`:"","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",`\u2502 \u{1F4E3} Share: ${I.slice(0,34).padEnd(34)}\u2502`,"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"].filter(j=>j!=="").join(`
45
- `);return[`\u2705 **Session saved**${x}`,"",`\u{1F4CB} **Summary:** ${t}`,s.length>0?`\u{1F4C1} **Files changed:** ${s.map(j=>`\`${j}\``).join(", ")}`:"",k!==void 0?`\u{1F9E0} **Lessons stored:** ${k}`:"",...Ws(_),h.length>0?`\u{1F916} **Auto-learned:** ${h.length} lessons extracted from summary (${h.slice(0,3).map(j=>`\`${j}\``).join(", ")}${h.length>3?"\u2026":""})`:"",i.length>0?`\u{1F33F} **Ambient git learning:** ${i.length} commit${i.length>1?"s":""} auto-learned (${i.slice(0,3).map(j=>`\`${j}\``).join(", ")}${i.length>3?"\u2026":""})`:"",e,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(j=>j!=="").join(`
46
- `)}case"session_ping":{const{instance_id:g,task:t,files_touched:s=[],next_step:k="",provider:m=""}=H,d=await U(g),$={ts:new Date().toISOString(),task:t,files_touched:s,next_step:k,provider:m};await d.set("cachly:session:checkpoint",JSON.stringify($),"EX",86400*3),await d.lpush("cachly:session:checkpoint:log",JSON.stringify($)),await d.ltrim("cachly:session:checkpoint:log",0,19);const a=m?` [${m}]`:"",u=s.length>0?` \xB7 ${s.length} file${s.length>1?"s":""} touched`:"",M=k?`
47
- \u{1F4CD} **Next step:** ${k}`:"";return[`\u{1F4CC} **Checkpoint saved**${a} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${t}${u}`,M,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically."].filter(o=>o!=="").join(`
48
- `)}case"session_handoff":{const{instance_id:g,completed_tasks:t=[],remaining_tasks:s=[],files_changed:k=[],instructions:m="",context_summary:d="",blocked_on:$=""}=H,a=await U(g),M={ts:new Date().toISOString(),completed_tasks:t,remaining_tasks:s,files_changed:k,instructions:m,context_summary:d,blocked_on:$};await a.set("cachly:session:handoff",JSON.stringify(M)),await a.lpush("cachly:session:handoff:history",JSON.stringify(M)),await a.ltrim("cachly:session:handoff:history",0,19);const o=t.length+s.length,_=o>0?Math.round(t.length/o*100):0,S=k.filter(h=>h.status==="broken"||h.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${t.length}/${o} tasks done (${_}%)`,"",t.length>0?`\u2705 **Completed:**
44
+ cachly.dev`,I=`https://twitter.com/intent/tweet?text=${encodeURIComponent(A)}`,e=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",a!==void 0?`\u2502 \u23F1 Duration : ${(a+" min").padEnd(26)}\u2502`:"",b>0?`\u2502 \u{1F4DA} Learned : ${(b+" lessons").padEnd(26)}\u2502`:"",s.length>0?`\u2502 \u{1F4C1} Changed : ${(s.length+" file"+(s.length>1?"s":"")).padEnd(26)}\u2502`:"","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",`\u2502 \u{1F4E3} Share: ${I.slice(0,34).padEnd(34)}\u2502`,"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"].filter(F=>F!=="").join(`
45
+ `);return[`\u2705 **Session saved**${x}`,"",`\u{1F4CB} **Summary:** ${t}`,s.length>0?`\u{1F4C1} **Files changed:** ${s.map(F=>`\`${F}\``).join(", ")}`:"",S!==void 0?`\u{1F9E0} **Lessons stored:** ${S}`:"",...Ws(_),h.length>0?`\u{1F916} **Auto-learned:** ${h.length} lessons extracted from summary (${h.slice(0,3).map(F=>`\`${F}\``).join(", ")}${h.length>3?"\u2026":""})`:"",i.length>0?`\u{1F33F} **Ambient git learning:** ${i.length} commit${i.length>1?"s":""} auto-learned (${i.slice(0,3).map(F=>`\`${F}\``).join(", ")}${i.length>3?"\u2026":""})`:"",e,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(F=>F!=="").join(`
46
+ `)}case"session_ping":{const{instance_id:g,task:t,files_touched:s=[],next_step:S="",provider:m=""}=q,f=await V(g),$={ts:new Date().toISOString(),task:t,files_touched:s,next_step:S,provider:m};await f.set("cachly:session:checkpoint",JSON.stringify($),"EX",86400*3),await f.lpush("cachly:session:checkpoint:log",JSON.stringify($)),await f.ltrim("cachly:session:checkpoint:log",0,19);const a=m?` [${m}]`:"",u=s.length>0?` \xB7 ${s.length} file${s.length>1?"s":""} touched`:"",M=S?`
47
+ \u{1F4CD} **Next step:** ${S}`:"";return[`\u{1F4CC} **Checkpoint saved**${a} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${t}${u}`,M,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically."].filter(n=>n!=="").join(`
48
+ `)}case"session_handoff":{const{instance_id:g,completed_tasks:t=[],remaining_tasks:s=[],files_changed:S=[],instructions:m="",context_summary:f="",blocked_on:$=""}=q,a=await V(g),M={ts:new Date().toISOString(),completed_tasks:t,remaining_tasks:s,files_changed:S,instructions:m,context_summary:f,blocked_on:$};await a.set("cachly:session:handoff",JSON.stringify(M)),await a.lpush("cachly:session:handoff:history",JSON.stringify(M)),await a.ltrim("cachly:session:handoff:history",0,19);const n=t.length+s.length,_=n>0?Math.round(t.length/n*100):0,C=S.filter(h=>h.status==="broken"||h.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${t.length}/${n} tasks done (${_}%)`,"",t.length>0?`\u2705 **Completed:**
49
49
  ${t.map(h=>` - ${h}`).join(`
50
50
  `)}`:"",s.length>0?`
51
51
  \u23F3 **Remaining for next window:**
52
52
  ${s.map(h=>` - ${h}`).join(`
53
- `)}`:"",S.length>0?`
54
- \u26A0\uFE0F **Needs attention:** ${S.map(h=>`\`${h.path}\` (${h.status})`).join(", ")}`:"",$?`
53
+ `)}`:"",C.length>0?`
54
+ \u26A0\uFE0F **Needs attention:** ${C.map(h=>`\`${h.path}\` (${h.status})`).join(", ")}`:"",$?`
55
55
  \u{1F6AB} **Blocked on:** ${$}`:"",m?`
56
56
  \u{1F4DD} **Instructions:** ${m}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically."].filter(h=>h!=="").join(`
57
- `)}case"auto_learn_session":{const{instance_id:g,observations:t}=H,s=await U(g),k=[],m=[];for(const $ of t){const a=$.topic??$.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),u=a.includes(":")?a:`auto:${a}`,M=`cachly:lesson:best:${u}`,o=await s.get(M);if(o&&JSON.parse(o).outcome==="success"&&$.outcome!=="success"){m.push(u);continue}const _={topic:u,outcome:$.outcome,what_worked:$.outcome==="success"?$.action:$.details??$.action,what_failed:$.outcome==="failure"?$.action:void 0,context:$.details,severity:$.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2},S=JSON.stringify(_);await s.set(M,S);const h=`cachly:lessons:${u}`;await s.rpush(h,S),await s.ltrim(h,-100,-1),await s.expire(h,90*86400);try{const i=u.split(":")[0]??"auto",x=me(u);if(await xe(s,x,i,i),$.outcome==="success"||$.outcome==="partial"){const b=$.details?We($.details):null;if(b){const w=me(`problem:${b}`);await xe(s,w,"problem","problem"),await ge(s,x,"fixes",w,$.outcome==="success",$.outcome==="partial")}}}catch{}k.push(`${$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${u}\``)}const d=[`\u{1F916} **Auto-learn complete**: ${k.length} stored, ${m.length} skipped`,""];return k.length>0&&d.push("**Stored:**",...k.map($=>" "+$),""),m.length>0&&d.push(`**Skipped** (better lesson already exists): ${m.map($=>`\`${$}\``).join(", ")}`),d.join(`
58
- `)}case"brain_who_knows":{const{instance_id:g,topic:t,limit:s=10}=H;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const k=Math.max(1,Math.min(Number(s)||10,50)),m=await U(g),d=me(t),$=Ve(t).filter(h=>h.length>=3).slice(0,5),a=new Set([d]);for(const h of $.slice(0,3)){const i=m.scanStream({match:`cachly:ckg:node:*${h}*`,count:30});await new Promise((x,b)=>{i.on("data",w=>{for(const A of w.slice(0,10)){const I=A.replace("cachly:ckg:node:","");!I.startsWith("person:")&&!I.startsWith("file:")&&a.add(I)}}),i.on("end",x),i.on("error",b)})}const u=new Map;for(const h of[...a].slice(0,25)){const i=await m.smembers(`cachly:ckg:idx:to:${h}`);for(const x of i){const b=await m.get(x);if(!b)continue;const w=O(b,null);if(!w||w.edgeType!=="authored")continue;const A=await m.get(`cachly:ckg:node:${w.from}`);if(!A)continue;const I=O(A,null);if(!I||I.type!=="person")continue;const e=u.get(w.from);e?(e.lessonCount++,e.totalConfidence+=w.confidence,e.domains.add(I.domain),w.last_updated>e.lastActive&&(e.lastActive=w.last_updated)):u.set(w.from,{handle:I.handle,lessonCount:1,totalConfidence:w.confidence,domains:new Set([I.domain]),lastActive:I.last_active??w.last_updated})}}if(u.size===0)return[`## \u{1F465} Who Knows About \`${t}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${t}", author="your-handle", ...)\``].join(`
59
- `);const M=[...u.entries()].map(([h,i])=>({id:h,handle:i.handle,lessonCount:i.lessonCount,avgConfidence:i.totalConfidence/i.lessonCount,domains:[...i.domains].slice(0,3).join(", "),lastActive:i.lastActive})).sort((h,i)=>i.lessonCount*i.avgConfidence-h.lessonCount*h.avgConfidence).slice(0,k),o=[],_=M[0];if(_)try{const h=await m.smembers(`cachly:ckg:idx:from:${_.id}`),i=[];for(const x of h){const b=await m.get(x);if(!b)continue;const w=O(b,null);if(!w||w.edgeType!=="collaborates")continue;const A=await m.get(`cachly:ckg:node:${w.to}`),I=A?O(A,null):null;I?.handle&&i.push({handle:I.handle,trials:w.trials})}i.sort((x,b)=>b.trials-x.trials);for(const x of i.slice(0,3))o.push(x.handle)}catch{}const S=[`## \u{1F465} Who Knows About \`${t}\`?`,"",`**${M.length}** contributor${M.length!==1?"s":""} with relevant lessons:`,""];for(const[h,i]of M.entries()){const x=h===0?"\u{1F947}":h===1?"\u{1F948}":h===2?"\u{1F949}":`${h+1}.`,b=(i.avgConfidence*100).toFixed(0),w=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),A=w<1?"today":w<7?`${w}d ago`:w<30?`${Math.floor(w/7)}w ago`:`${Math.floor(w/30)}mo ago`,I=await Ue(m,g,i.handle).catch(()=>null),e=I?` ${es[I]}`:"";S.push(`${x} **${i.handle}**${e} \u2014 ${i.lessonCount} lesson${i.lessonCount!==1?"s":""} \xB7 ${b}% confidence \xB7 last active ${A}`,` _domains: ${i.domains}_`,"")}return o.length>0&&_&&S.push(`\u{1F91D} **${_.handle}** frequently works with: ${o.map(h=>`**${h}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),S.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),S.join(`
60
- `)}case"brain_file_map":{const{instance_id:g,file_paths:t=[]}=H,s=(Array.isArray(t)?t:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim());if(!s.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const k=await U(g),m=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const d of s.slice(0,10)){m.push(`### \`${d}\``);const $=`file:${me(d)}`,a=await k.smembers(`cachly:ckg:idx:to:${$}`),u=[];for(const S of a){const h=await k.get(S);if(!h)continue;const i=O(h,null);if(!i||i.edgeType!=="touched")continue;const x=await k.get(`cachly:ckg:node:${i.from}`);if(!x)continue;const b=O(x,null);!b||b.type!=="person"||u.push({handle:b.handle,touches:i.trials,lastSeen:i.last_updated})}if(u.sort((S,h)=>h.touches-S.touches),u.length>0){const S=u.slice(0,5).map((h,i)=>{const x=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}.`,b=Math.floor((Date.now()-new Date(h.lastSeen).getTime())/864e5),w=b<1?"today":b<7?`${b}d ago`:`${Math.floor(b/7)}w ago`;return`${x} **${h.handle}** (${h.touches}\xD7 \xB7 ${w})`}).join(" \xB7 ");m.push(`**Experts:** ${S}`)}else m.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const o=d.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(S=>S.length>=4).slice(0,3).join(" "),_=[];if(o)try{const S=await ze(k,["cachly:lesson:best:*"],o,4);for(const h of S){const i=Ce(h.content);if(!Te(i))continue;const x=i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C",b=i.severity==="critical"?" \u{1F534}":i.severity==="major"?" \u{1F7E1}":"",w=i.author?` \xB7 \u{1F464} ${i.author}`:"",A=h.key.replace("cachly:lesson:best:","");_.push(` - ${x} \`${A}\`${b}${w} \u2014 ${(i.what_worked??"").slice(0,100)}`)}}catch{}if(_.length<2){const S=await ve(k,"cachly:lesson:best:*",{max:1500});for(const h of S.slice(0,300)){const i=await k.get(h);if(!i)continue;const x=Ce(i);if(!Te(x)||!(x.file_paths??[]).includes(d))continue;const b=h.replace("cachly:lesson:best:","");if(_.some(e=>e.includes(`\`${b}\``)))continue;const w=x.outcome==="success"?"\u2705":x.outcome==="partial"?"\u26A0\uFE0F":"\u274C",A=x.severity==="critical"?" \u{1F534}":x.severity==="major"?" \u{1F7E1}":"",I=x.author?` \xB7 \u{1F464} ${x.author}`:"";_.push(` - ${w} \`${b}\`${A}${I} \u2014 ${(x.what_worked??"").slice(0,100)}`)}}_.length>0?(m.push("**Related lessons:**"),m.push(..._.slice(0,5))):m.push("**Related lessons:** _None yet_"),m.push("")}return m.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),m.join(`
61
- `)}case"team_expertise_map":{const{instance_id:g,top_n:t=20}=H,s=await U(g),k=await ve(s,"cachly:ckg:node:person:*",{max:2e3});if(k.length===0)return["## \u{1F5FA}\uFE0F Team Expertise Map","","No contributors yet.","",'Add `author="handle"` to any `learn_from_attempts` call to start building the map.'].join(`
62
- `);const m=[];for(const a of k){const u=await s.get(a);if(!u)continue;const M=O(u,null);if(!M||M.type!=="person")continue;const o=await s.smembers(`cachly:ckg:idx:from:${M.id}`),_=new Map;let S=0;for(const h of o){const i=await s.get(h);if(!i)continue;const x=O(i,null);if(!x||x.edgeType!=="authored")continue;S++;const b=x.to.split(":")[0]??"unknown";_.set(b,(_.get(b)??0)+1)}m.push({handle:M.handle,lessonCount:S,domains:_,lastActive:M.last_active})}m.sort((a,u)=>u.lessonCount-a.lessonCount);const d=m.slice(0,t),$=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${d.length}** contributor${d.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[a,u]of d.entries()){const M=a===0?"\u{1F947}":a===1?"\u{1F948}":a===2?"\u{1F949}":`${a+1}`,o=Math.floor((Date.now()-new Date(u.lastActive).getTime())/864e5),_=o<1?"today":o<7?`${o}d ago`:o<30?`${Math.floor(o/7)}w ago`:`${Math.floor(o/30)}mo ago`,S=[...u.domains.entries()].sort((h,i)=>i[1]-h[1]).slice(0,3).map(([h,i])=>`${h}(${i})`).join(", ")||"\u2014";$.push(`| ${M} | **${u.handle}** | ${u.lessonCount} | ${S} | ${_} |`)}return $.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),$.join(`
63
- `)}case"skill_gaps":{const{instance_id:g,min_failures:t=1}=H,s=await U(g),k=await ve(s,"cachly:lesson:best:*",{max:3e3}),m=new Map;let d=0,$=0;for(const M of k){const o=await s.get(M);if(!o)continue;const _=Ce(o);if(_===null)continue;const S=(_.topic??"").split(":")[0]??"unknown",h=m.get(S)??{successes:0,failures:0,attributed:0,topics:[]};_.outcome==="success"||_.outcome==="partial"?h.successes++:h.failures++,_.author&&(h.attributed++,d++),_.visibility==="private"&&$++,h.topics.push(_.topic??""),m.set(S,h)}const a=[];for(const[M,o]of m)o.failures>=t&&o.successes===0&&a.push({domain:M,type:"unresolved failures",severity:o.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${o.failures} failure${o.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),o.successes+o.failures>=3&&o.attributed===0&&a.push({domain:M,type:"no attribution",severity:"\u{1F535} info",detail:`${o.successes+o.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const u=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${k.length}** lessons scanned \xB7 **${d}** attributed \xB7 **${a.length}** gap${a.length!==1?"s":""} found`,$>0?`_(${$} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(a.length===0)u.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const M=[...a.filter(o=>o.severity.includes("critical")),...a.filter(o=>o.severity.includes("warn")),...a.filter(o=>o.severity.includes("info"))];for(const o of M.slice(0,15))u.push(`${o.severity} **\`${o.domain}\`** \u2014 ${o.type}`),u.push(` ${o.detail}`),u.push("");a.length>15&&u.push(`_\u2026and ${a.length-15} more gaps. Fix critical ones first._`)}return u.push("---",`_Fix gaps with \`learn_from_attempts(topic="${a[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),u.join(`
64
- `)}case"brain_coverage":{const{instance_id:g,repo_path:t="."}=H,s=await U(g),[k,m,d]=await Promise.all([ve(s,"cachly:lesson:best:*",{max:5e3}),ve(s,"cachly:ckg:node:person:*",{max:2e3}),ve(s,"cachly:ckg:node:file:*",{max:5e3})]);let $=0,a="n/a";try{const{execSync:b}=await import("node:child_process"),{resolve:w}=await import("node:path"),A=w(t);$=b("git ls-files",{cwd:A,encoding:"utf-8",stdio:"pipe"}).trim().split(`
65
- `).filter(Boolean).length,a=String($)}catch{}let u=0,M=0,o=0;const _=new Set;for(const b of k){const w=await s.get(b);if(!w)continue;const A=O(w,{});A.outcome==="success"||A.outcome==="partial"?u++:M++,A.author&&o++,_.add((A.topic??"").split(":")[0]??"unknown")}const S=$>0?`${Math.round(d.length/$*100)}% (${d.length}/${$} files)`:`${d.length} files tracked`,h=k.length>0?Math.round(o/k.length*100):0,i=Math.round(Math.min(1,k.length/50)*25+Math.min(1,u/Math.max(1,k.length))*25+Math.min(1,h/100)*25+Math.min(1,m.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${i>=80?"\u{1F7E2}":i>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${i}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${k.length}** (${u} success \xB7 ${M} failure) |`,`| Problem domains | **${_.size}** |`,`| Attribution | **${o}/${k.length}** (${h}%) |`,`| Contributors | **${m.length}** tracked in knowledge graph |`,`| File coverage | **${S}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,k.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,u/Math.max(1,k.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,h/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,m.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
66
- `)}case"brain_metrics":{const{instance_id:g}=H,t=await U(g),[s,k,m,d,$,a]=await Promise.all([t.get(`cachly:stats:born_at:${g}`).catch(()=>null),t.get(`cachly:stats:first_recall_at:${g}`).catch(()=>null),t.get(`cachly:stats:recalls_total:${g}`).catch(()=>null),t.get(`cachly:stats:cross_author_recalls:${g}`).catch(()=>null),t.get(`cachly:stats:time_saved_mins:${g}`).catch(()=>null),t.smembers(`cachly:stats:reuse_pairs:${g}`).catch(()=>[])]);let u={};try{u=await t.hgetall(Tt(g))??{}}catch{u={}}let M={};try{M=await t.hgetall(pt(g))??{}}catch{M={}}const o={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const R=await t.lrange(dt(g),0,499),E=new Map;for(const J of R){const se=O(J,{ts:"",themen:[]});if(!(!se.ts||!Array.isArray(se.themen)))for(const V of se.themen){if(o.lieferungen++,!E.has(V)){const r=await t.get(`cachly:lesson:best:${V}`).catch(()=>null);E.set(V,r?O(r,{}):null)}const n=ys(se.ts,E.get(V)??null);if(n.length===0){o.ohneEreignis++;continue}for(const r of n)o[r]++}}}catch{}let _=0,S=0;try{const R=await t.lrange(`cachly:wirkung:${g}`,0,-1);for(const E of R){const J=O(E,{});S++,J.geholfen===!0&&_++}}catch{}let h={};try{h=await t.hgetall(Vs(g))??{}}catch{h={}}const i=Ys(h,10);let x={token:0,abrufe:0,treffer:0};try{const R=await t.get(Qs(g)),E=await t.hgetall(en(g))??{};x={token:R??0,abrufe:E.abrufe??0,treffer:E.treffer??0}}catch{}const b=Xs(x);let w;if(s&&k){const R=new Date(k).getTime()-new Date(s).getTime(),E=Math.max(0,Math.round(R/6e4)),J=E<1?"<1 min":E<60?`${E} min`:`${(E/60).toFixed(1)} h`,se=R<=2*6e4?"\u{1F7E2} under 2 min target":R<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";w=`**${J}** from first lesson \u2192 first proven recall \xB7 ${se}`}else s&&!k?w="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":w="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const A=["\u26AA **Nicht gemessen** \u2014 diese Zahl erhebt der Server nicht selbst."," Selbst messen: `npm run bench` in `sdk/mcp`."," Achtung, der Pruefstand hat 17 Lektionen und 13 Fragen \u2014 ein Beispielsatz, kein Bestand."," Auf 498 ECHTEN Lektionen gemessen am 19.08.2026: Precision@1 **30 %** (vorher 15 %)."].join(`
67
- `),I=Number(m??0),e=Number(d??0),j=I>0?Math.round(e/I*100):0,v=j>=30?"\u{1F7E2} above 30 % target":I===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",oe=Math.round(Number($??0)),ce=oe<60?`${oe} min`:`${(oe/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",w,"","### 2. Recall-lift _(the moat proof)_",A,"_Reproduce: `npm run bench` \xB7 CI-defended in `rerank.test.ts` \xB7 details in BENCH.md_","","### 3. Team-knowledge-reuse _(the value only a shared brain delivers)_",`**${j}%** of proven recalls used a teammate's lesson (${e}/${I}) \xB7 ${v}`,a.length>0?`**${a.length}** distinct reuse relationship${a.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",Zs(b),"",b.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ce} nicht neu recherchiert \u2014 gerechnet mit 30\u2013240 Min. je Lektion nach Schwere, nicht gemessen. Die Zahl dar\xFCber braucht diese Annahme nicht._`:`_Eine **Sch\xE4tzung** von ${ce} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,I===0?'_Tip: pass `author="your-handle"` to `smart_recall` so cross-author reuse can be tracked._':"_These numbers compound: every learned lesson and every teammate raises all three._","","### \u2696\uFE0F Die drei Ausgaenge der Suche _(gezaehlt, nicht behauptet)_",(()=>{const R=Number(u.beantwortet??0),E=Number(u.knapp??0),J=Number(u.schweigen??0),se=R+E+J;if(se===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const V=n=>`${Math.round(100*n/se)} %`;return`**${se}** Suchen: ${V(R)} beantwortet \xB7 ${V(E)} als knapper Sieg markiert \xB7 ${V(J)} ehrliches Nein. (Ob ein Nein stimmt, zeigt nur die Stichprobe \u2014 die Rate hier zaehlt, sie urteilt nicht.)`})(),"","### \u{1F53D} Recall-Trichter _(je Fehlschlag: WORAN scheiterte der Abruf)_",(()=>{const R=V=>Number(M[V]??0),E=[["nicht-gesucht","nicht gesucht"],["nominierung","Nominierung (gesucht, nichts geliefert)"],["ranking","Ranking (geliefert, das Richtige fehlte)"],["anwendung","Anwendung (das Richtige lag vor)"],["ohne-vorwissen","ohne Vorwissen (es gab nichts zu finden)"]],J=E.reduce((V,[n])=>V+R(n),0);if(J===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const se=E.filter(([V])=>V!=="ohne-vorwissen").sort((V,n)=>R(n[0])-R(V[0]))[0];return`**${J}** klassifizierte Fehlschlaege: `+E.map(([V,n])=>`${R(V)} ${n}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${se[1]}** (${R(se[0])}) \u2014 dorthin gehoert das naechste Investment. (Heuristik je Einzelfall; erst die Verteilung ueber viele Sessions traegt.)`})(),"","### \u{1F3F7}\uFE0F Drei Etiketten ohne Selbstauskunft _(widersprochen \xB7 korrigiert \xB7 veraltet)_",o.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${o.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${o.widersprochen} widersprochen \xB7 ${o.korrigiert} korrigiert \xB7 ${o.veraltet} veraltet \xB7 ${o.ohneEreignis} ohne spaeteres Ereignis. (Kein Etikett heisst: nichts ist passiert \u2014 nicht "benutzt". Das vierte Etikett haette nur eine geschmeichelte Fassung.)`,"","### \u2696\uFE0F Netto-verhinderter-Schaden _(kann negativ werden \u2014 sonst misst es nichts)_",(()=>{const R=Number(o.widersprochen)+Number(o.veraltet);if(S===0&&R===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const E=_-R;return`**${E>=0?"+":""}${E}** = ${_} bestaetigt geholfen (Wirkungsspur, ${S} Eintraege) \u2212 ${R} Schadenslieferungen (${o.widersprochen} spaeter widerlegt + ${o.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",Us(i,cn.length),...i.spitze.length>0?i.spitze.map((R,E)=>` ${String(E+1).padStart(2)}. \`${R.name}\` \u2014 ${R.aufrufe}\xD7 (${Math.round(R.anteil*100)} %)`):[]].filter(Boolean).join(`
68
- `)}case"brain_service_map":{const{instance_id:g,service:t}=H;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const s=await U(g),k=`service:${me(t.trim())}`,m=await s.get(`cachly:ckg:node:${k}`).catch(()=>null),d=m?O(m,null):null,$=await s.smembers(`cachly:ckg:idx:to:${k}`).catch(()=>[]),a=[],u=[],M=[];for(const w of $){const A=await s.get(w).catch(()=>null);if(!A)continue;const I=O(A,null);if(I)if(I.edgeType==="operates"){const e=await s.get(`cachly:ckg:node:${I.from}`).catch(()=>null),j=e?O(e,null):null;j?.handle&&a.push({handle:j.handle,trials:I.trials})}else if(I.edgeType==="runs_in"){const e=await s.get(`cachly:ckg:node:${I.from}`).catch(()=>null),j=e?O(e,null):null;j?.path&&u.push({path:j.path,trials:I.trials})}else I.edgeType==="affects"&&M.push({id:I.from,confidence:I.confidence})}a.sort((w,A)=>A.trials-w.trials),u.sort((w,A)=>A.trials-w.trials),M.sort((w,A)=>A.confidence-w.confidence);const o=[],_=await ve(s,"cachly:lesson:best:*",{max:1500}),S=t.trim().toLowerCase();for(const w of _.slice(0,400)){const A=await s.get(w).catch(()=>null);if(!A)continue;const I=Ce(A);Te(I)&&(I.service??"").toLowerCase()===S&&o.push({...I,topic:w.replace("cachly:lesson:best:","")})}if(!d&&o.length===0&&a.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${t}\``,"","Nothing known about this service yet.","","Tag lessons with the service they concern so the brain can build this map:",`\`learn_from_attempts(topic="...", service="${t}", author="you", file_paths=[...])\``].join(`
69
- `);const h=d?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",i=[`## ${d?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${t}\``,"",d?`_${h} \xB7 ${d.count} lesson${d.count!==1?"s":""} referenced \xB7 domain: ${d.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(a.length>0){const w=a.slice(0,5).map((A,I)=>`${I===0?"\u{1F947}":I===1?"\u{1F948}":I===2?"\u{1F949}":`${I+1}.`} **${A.handle}** (${A.trials}\xD7)`).join(" \xB7 ");i.push(`**Operators:** ${w}`,"")}else i.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const x=o.filter(w=>w.outcome==="failure"),b=o.filter(w=>w.outcome!=="failure");if(x.length>0){i.push(`**\u26A0\uFE0F Known failures (${x.length}):**`);for(const w of x.slice(0,6)){const A=w.severity==="critical"?" \u{1F534}":w.severity==="major"?" \u{1F7E1}":"",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";i.push(` - \u274C \`${w.topic}\`${A}${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}i.push("")}if(b.length>0){i.push(`**\u2705 Proven fixes (${b.length}):**`);for(const w of b.slice(0,6)){const A=w.outcome==="partial"?"\u26A0\uFE0F":"\u2705",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";i.push(` - ${A} \`${w.topic}\`${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}i.push("")}return u.length>0&&i.push(`**Files in this service:** ${u.slice(0,8).map(w=>`\`${w.path}\``).join(", ")}`,""),i.push("---",`_Tag lessons with \`service="${t}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),i.join(`
70
- `)}case"brain_collab_pairs":{const{instance_id:g,min_weight:t=1}=H,s=await U(g),k=typeof t=="number"&&t>=1?Math.floor(t):1,m=await ve(s,"cachly:ckg:node:person:*",{max:500}),d=new Map;for(const _ of m){const S=await s.get(_);if(!S)continue;const h=O(S,null);!h||h.type!=="person"||d.set(h.id,{id:h.id,handle:h.handle,domain:h.domain,count:h.count})}if(d.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
71
- `);const $=new Map;for(const[_,S]of d){const h=await s.smembers(`cachly:ckg:idx:from:${_}`);for(const i of h){const x=await s.get(i);if(!x)continue;const b=O(x,null);if(!b||b.edgeType!=="collaborates")continue;const w=d.get(b.to);if(!w)continue;const[A,I]=_<b.to?[_,b.to]:[b.to,_],e=`${A}||${I}`,j=$.get(e);if(j)j.trials+=b.trials;else{const[v,oe]=_<b.to?[S,w]:[w,S];$.set(e,{a:v,b:oe,trials:b.trials,confidence:b.confidence})}}}const a=[...$.values()].filter(_=>_.trials>=k).sort((_,S)=>S.trials-_.trials),u=new Set;for(const _ of a)u.add(_.a.id),u.add(_.b.id);const M=[...d.values()].filter(_=>!u.has(_.id)),o=["## \u{1F91D} Team Collaboration Graph",""];if(a.length===0)o.push(`No collaboration pairs yet (min weight: ${k}).`,"","Pairs appear when two contributors touch the same file in `learn_from_attempts`",'or when someone recalls a teammate\'s lesson via `smart_recall(requester="...")`.');else{o.push(`**${a.length} collaboration pair${a.length!==1?"s":""}** across ${u.size} contributor${u.size!==1?"s":""}:`,"");for(const _ of a.slice(0,20)){const S=(_.confidence*100).toFixed(0),h=[_.a.domain,_.b.domain].filter((i,x,b)=>i&&b.indexOf(i)===x).map(i=>`\`${i}\``).join(", ");o.push(`### @${_.a.handle} \u2194 @${_.b.handle}`,`- **${_.trials} collaboration event${_.trials!==1?"s":""}** \xB7 ${S}% confidence`,`- Domains: ${h||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${_.a.handle}** und **@${_.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}a.length>20&&o.push(`_...and ${a.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return M.length>0&&o.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${M.length} contributor${M.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...M.slice(0,10).map(_=>`- **@${_.handle}** \u2014 ${_.count} lesson${_.count!==1?"s":""} \xB7 domain: \`${_.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),o.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),o.join(`
72
- `)}case"brain_portability":{const{instance_id:g}=H,t=[{name:"Claude Code",slug:"claude-code",icon:"\u{1F916}",configPath:"~/.claude/settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Cursor",slug:"cursor",icon:"\u{1F5B1}\uFE0F",configPath:"~/.cursor/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Windsurf",slug:"windsurf",icon:"\u{1F3C4}",configPath:"~/.windsurf/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"GitHub Copilot (VS Code)",slug:"copilot",icon:"\u{1F419}",configPath:".vscode/mcp.json (workspace)",configBlock:JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Cline",slug:"cline",icon:"\u26A1",configPath:"~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Zed",slug:"zed",icon:"\u26A1",configPath:"~/.config/zed/settings.json",configBlock:JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["@cachly-dev/mcp-server@latest"]},env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Continue",slug:"continue",icon:"\u25B6\uFE0F",configPath:"~/.continue/config.json",configBlock:JSON.stringify({mcpServers:[{name:"cachly",command:"npx @cachly-dev/mcp-server@latest",env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}]},null,2)}],s=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${g}\``,"","Replace `<cky_live_...>` below with your own API key (get one at https://cachly.dev/setup-ai) \u2014 the Brain ID alone does not authenticate you.","","This Brain ID is model-agnostic. Every lesson you've learned, every Memory Crystal you've distilled,","and every prediction from your Causal Knowledge Graph is accessible from **any MCP-compatible AI client**.","","---","",`### Compatible Clients (${t.length} supported)`,""];for(const k of t)s.push(`#### ${k.icon} ${k.name}`,`Config: \`${k.configPath}\``,"","```json",k.configBlock,"```","");return s.push("---","","### What travels with you","","| Data | Model-neutral? |","|------|---------------|","| Lessons (learn_from_attempts) | \u2705 Full access in all clients |","| Memory Crystals (memory_crystalize) | \u2705 Included in every session_start |","| Causal Knowledge Graph (brain_predict) | \u2705 Same graph, same predictions |","| Team lessons (team_learn, team_confirm) | \u2705 Team is per-Brain, not per-model |","| Domain Brain Marketplace installs | \u2705 Installed once, available everywhere |","| Session handoffs (session_handoff) | \u2705 Cross-client continuity |","","---","","### One-command setup for any new client","","```bash","npx @cachly-dev/mcp-server@latest autopilot","```","",`Autopilot detects all installed editors and writes the config for each \u2014 with your \`${g}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),s.join(`
73
- `)}case"brain_changelog":{const{instance_id:g,days:t=7,max_lessons:s=30,include_failures:k=!0}=H,m=await U(g),d=Date.now()-Number(t)*864e5,$=await ve(m,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),a=[];for(const i of $){const x=await m.get(i).catch(()=>null);if(!x)continue;const b=O(x,{});if((b.ts?new Date(b.ts).getTime():0)<d||!k&&b.outcome==="failure")continue;const A=i.replace("cachly:lesson:best:","");a.push({...b,topic:A})}a.sort((i,x)=>{const b=i.ts?new Date(i.ts).getTime():0;return(x.ts?new Date(x.ts).getTime():0)-b});const u=a.slice(0,Number(s));if(u.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${t} day${Number(t)!==1?"s":""}`,"","_No new lessons learned in this window. Your Brain already knows everything it knows \u2014 add new lessons with `learn_from_attempts`._"].join(`
74
- `);const M=new Map;for(const i of u){const x=i.topic.includes(":")?i.topic.split(":")[0]:"general",b=M.get(x)??[];b.push(i),M.set(x,b)}const o=i=>i==="critical"?"\u{1F6A8}":i==="major"?"\u26A0\uFE0F":i==="minor"?"\u{1F4A1}":"\u2728",_=i=>i==="failure"?"\u274C":i==="partial"?"\u{1F536}":"\u2705",h=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${t} day${Number(t)!==1?"s":""})`,"",`_${u.length} lesson${u.length!==1?"s":""} learned across ${M.size} topic area${M.size!==1?"s":""}_`,""];for(const[i,x]of Array.from(M.entries()).sort((b,w)=>w[1].length-b[1].length)){h.push(`### ${i}`),h.push("");for(const b of x){const w=b.outcome==="failure"?_(b.outcome):o(b.severity),A=b.outcome==="failure"?b.what_failed:b.what_worked,I=[];b.author&&I.push(`by **${b.author}**`),b.recall_count&&I.push(`${b.recall_count} recall${b.recall_count!==1?"s":""}`),b.confidence!==void 0&&I.push(`${Math.round(b.confidence*100)}% confidence`),h.push(`- ${w} **${b.topic}**${A?` \u2014 ${A}`:""}`),I.length&&h.push(` _${I.join(" \xB7 ")}_`)}h.push("")}return h.push("---",`_Generated from Brain \`${g}\` \xB7 Share this in your standup or Slack_`),h.join(`
75
- `)}case"brain_set_pref":{const{instance_id:g,key:t,value:s}=H;if(!t||!t.trim())throw new Error("key is required");const k=await U(g),m=`cachly:prefs:${t.trim()}:${g}`;return await k.set(m,String(s)),`\u2705 Preference \`${t}\` set to \`${s}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:g,key:t}=H,s=await U(g);if(t&&t.trim()){const $=await s.get(`cachly:prefs:${t.trim()}:${g}`).catch(()=>null);return $===null?`\u2139\uFE0F Preference \`${t}\` is not set (using default).`:`\u{1F527} Preference \`${t}\` = \`${$}\``}const k=await ve(s,`cachly:prefs:*:${g}`,{max:200,timeoutMs:2e3});if(k.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const m=await s.mget(...k),d=["\u{1F527} **Brain preferences:**",""];for(let $=0;$<k.length;$++){const a=k[$].replace("cachly:prefs:","").replace(`:${g}`,"");d.push(`- \`${a}\` = \`${m[$]??"(null)"}\``)}return d.join(`
76
- `)}default:return null}}async function bn(ie,H){try{if(!Ne()||Se!=="cachly"&&Se!=="ollama")return 0;let U=0;for(const ue of ye.themen()){if(U>=H)break;if(Pe.hat(ue)||await ie.exists(`${Ie}${ue}`))continue;const g=await ie.get(`cachly:lesson:best:${ue}`);if(!g)continue;const t=O(g,{});try{const s=await $e(De(t),{geduld:"lang",modell:Oe});s?.length&&(await ie.set(`${Ie}${ue}`,Ee(s)),U++)}catch{}}return U}catch{return 0}}async function At(ie,H,U){try{if(!Ne())return;const ue=await ie.srandmember(Ae,U),g=Array.isArray(ue)?ue:ue?[ue]:[];for(const t of g){if(t===H)continue;const s=await ie.get(`cachly:lesson:best:${t}`);if(!s){await ie.srem(Ae,t);continue}const k=O(s,{});try{const m=await $e(De(k),{geduld:"lang"});if(m?.length)await ie.set(`${ut}${t}`,Ee(m)),await ie.srem(Ae,t);else continue;if(Se==="cachly"||Se==="ollama")try{const d=await $e(De(k),{geduld:"lang",modell:Oe});d?.length&&await ie.set(`${Ie}${t}`,Ee(d))}catch{}}catch{}}}catch{}}export{lo as BRAIN_TOOL_NAMES,uo as handleBrainTool,at as recallVorschau};
57
+ `)}case"auto_learn_session":{const{instance_id:g,observations:t}=q,s=await V(g),S=[],m=[];for(const $ of t){const a=$.topic??$.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),u=a.includes(":")?a:`auto:${a}`,M=`cachly:lesson:best:${u}`,n=await s.get(M);if(n&&JSON.parse(n).outcome==="success"&&$.outcome!=="success"){m.push(u);continue}const _={topic:u,outcome:$.outcome,what_worked:$.outcome==="success"?$.action:$.details??$.action,what_failed:$.outcome==="failure"?$.action:void 0,context:$.details,severity:$.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2},C=JSON.stringify(_);await s.set(M,C);const h=`cachly:lessons:${u}`;await s.rpush(h,C),await s.ltrim(h,-100,-1),await s.expire(h,90*86400);try{const i=u.split(":")[0]??"auto",x=me(u);if(await xe(s,x,i,i),$.outcome==="success"||$.outcome==="partial"){const b=$.details?We($.details):null;if(b){const w=me(`problem:${b}`);await xe(s,w,"problem","problem"),await ge(s,x,"fixes",w,$.outcome==="success",$.outcome==="partial")}}}catch{}S.push(`${$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${u}\``)}const f=[`\u{1F916} **Auto-learn complete**: ${S.length} stored, ${m.length} skipped`,""];return S.length>0&&f.push("**Stored:**",...S.map($=>" "+$),""),m.length>0&&f.push(`**Skipped** (better lesson already exists): ${m.map($=>`\`${$}\``).join(", ")}`),f.join(`
58
+ `)}case"brain_who_knows":{const{instance_id:g,topic:t,limit:s=10}=q;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const S=Math.max(1,Math.min(Number(s)||10,50)),m=await V(g),f=me(t),$=Ve(t).filter(h=>h.length>=3).slice(0,5),a=new Set([f]);for(const h of $.slice(0,3)){const i=m.scanStream({match:`cachly:ckg:node:*${h}*`,count:30});await new Promise((x,b)=>{i.on("data",w=>{for(const A of w.slice(0,10)){const I=A.replace("cachly:ckg:node:","");!I.startsWith("person:")&&!I.startsWith("file:")&&a.add(I)}}),i.on("end",x),i.on("error",b)})}const u=new Map;for(const h of[...a].slice(0,25)){const i=await m.smembers(`cachly:ckg:idx:to:${h}`);for(const x of i){const b=await m.get(x);if(!b)continue;const w=O(b,null);if(!w||w.edgeType!=="authored")continue;const A=await m.get(`cachly:ckg:node:${w.from}`);if(!A)continue;const I=O(A,null);if(!I||I.type!=="person")continue;const e=u.get(w.from);e?(e.lessonCount++,e.totalConfidence+=w.confidence,e.domains.add(I.domain),w.last_updated>e.lastActive&&(e.lastActive=w.last_updated)):u.set(w.from,{handle:I.handle,lessonCount:1,totalConfidence:w.confidence,domains:new Set([I.domain]),lastActive:I.last_active??w.last_updated})}}if(u.size===0)return[`## \u{1F465} Who Knows About \`${t}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${t}", author="your-handle", ...)\``].join(`
59
+ `);const M=[...u.entries()].map(([h,i])=>({id:h,handle:i.handle,lessonCount:i.lessonCount,avgConfidence:i.totalConfidence/i.lessonCount,domains:[...i.domains].slice(0,3).join(", "),lastActive:i.lastActive})).sort((h,i)=>i.lessonCount*i.avgConfidence-h.lessonCount*h.avgConfidence).slice(0,S),n=[],_=M[0];if(_)try{const h=await m.smembers(`cachly:ckg:idx:from:${_.id}`),i=[];for(const x of h){const b=await m.get(x);if(!b)continue;const w=O(b,null);if(!w||w.edgeType!=="collaborates")continue;const A=await m.get(`cachly:ckg:node:${w.to}`),I=A?O(A,null):null;I?.handle&&i.push({handle:I.handle,trials:w.trials})}i.sort((x,b)=>b.trials-x.trials);for(const x of i.slice(0,3))n.push(x.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${t}\`?`,"",`**${M.length}** contributor${M.length!==1?"s":""} with relevant lessons:`,""];for(const[h,i]of M.entries()){const x=h===0?"\u{1F947}":h===1?"\u{1F948}":h===2?"\u{1F949}":`${h+1}.`,b=(i.avgConfidence*100).toFixed(0),w=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),A=w<1?"today":w<7?`${w}d ago`:w<30?`${Math.floor(w/7)}w ago`:`${Math.floor(w/30)}mo ago`,I=await Ue(m,g,i.handle).catch(()=>null),e=I?` ${es[I]}`:"";C.push(`${x} **${i.handle}**${e} \u2014 ${i.lessonCount} lesson${i.lessonCount!==1?"s":""} \xB7 ${b}% confidence \xB7 last active ${A}`,` _domains: ${i.domains}_`,"")}return n.length>0&&_&&C.push(`\u{1F91D} **${_.handle}** frequently works with: ${n.map(h=>`**${h}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),C.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),C.join(`
60
+ `)}case"brain_file_map":{const{instance_id:g,file_paths:t=[]}=q,s=(Array.isArray(t)?t:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim());if(!s.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const S=await V(g),m=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const f of s.slice(0,10)){m.push(`### \`${f}\``);const $=`file:${me(f)}`,a=await S.smembers(`cachly:ckg:idx:to:${$}`),u=[];for(const C of a){const h=await S.get(C);if(!h)continue;const i=O(h,null);if(!i||i.edgeType!=="touched")continue;const x=await S.get(`cachly:ckg:node:${i.from}`);if(!x)continue;const b=O(x,null);!b||b.type!=="person"||u.push({handle:b.handle,touches:i.trials,lastSeen:i.last_updated})}if(u.sort((C,h)=>h.touches-C.touches),u.length>0){const C=u.slice(0,5).map((h,i)=>{const x=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}.`,b=Math.floor((Date.now()-new Date(h.lastSeen).getTime())/864e5),w=b<1?"today":b<7?`${b}d ago`:`${Math.floor(b/7)}w ago`;return`${x} **${h.handle}** (${h.touches}\xD7 \xB7 ${w})`}).join(" \xB7 ");m.push(`**Experts:** ${C}`)}else m.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const n=f.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),_=[];if(n)try{const C=await ze(S,["cachly:lesson:best:*"],n,4);for(const h of C){const i=Ce(h.content);if(!Te(i))continue;const x=i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C",b=i.severity==="critical"?" \u{1F534}":i.severity==="major"?" \u{1F7E1}":"",w=i.author?` \xB7 \u{1F464} ${i.author}`:"",A=h.key.replace("cachly:lesson:best:","");_.push(` - ${x} \`${A}\`${b}${w} \u2014 ${(i.what_worked??"").slice(0,100)}`)}}catch{}if(_.length<2){const C=await ve(S,"cachly:lesson:best:*",{max:1500});for(const h of C.slice(0,300)){const i=await S.get(h);if(!i)continue;const x=Ce(i);if(!Te(x)||!(x.file_paths??[]).includes(f))continue;const b=h.replace("cachly:lesson:best:","");if(_.some(e=>e.includes(`\`${b}\``)))continue;const w=x.outcome==="success"?"\u2705":x.outcome==="partial"?"\u26A0\uFE0F":"\u274C",A=x.severity==="critical"?" \u{1F534}":x.severity==="major"?" \u{1F7E1}":"",I=x.author?` \xB7 \u{1F464} ${x.author}`:"";_.push(` - ${w} \`${b}\`${A}${I} \u2014 ${(x.what_worked??"").slice(0,100)}`)}}_.length>0?(m.push("**Related lessons:**"),m.push(..._.slice(0,5))):m.push("**Related lessons:** _None yet_"),m.push("")}return m.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),m.join(`
61
+ `)}case"team_expertise_map":{const{instance_id:g,top_n:t=20}=q,s=await V(g),S=await ve(s,"cachly:ckg:node:person:*",{max:2e3});if(S.length===0)return["## \u{1F5FA}\uFE0F Team Expertise Map","","No contributors yet.","",'Add `author="handle"` to any `learn_from_attempts` call to start building the map.'].join(`
62
+ `);const m=[];for(const a of S){const u=await s.get(a);if(!u)continue;const M=O(u,null);if(!M||M.type!=="person")continue;const n=await s.smembers(`cachly:ckg:idx:from:${M.id}`),_=new Map;let C=0;for(const h of n){const i=await s.get(h);if(!i)continue;const x=O(i,null);if(!x||x.edgeType!=="authored")continue;C++;const b=x.to.split(":")[0]??"unknown";_.set(b,(_.get(b)??0)+1)}m.push({handle:M.handle,lessonCount:C,domains:_,lastActive:M.last_active})}m.sort((a,u)=>u.lessonCount-a.lessonCount);const f=m.slice(0,t),$=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${f.length}** contributor${f.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[a,u]of f.entries()){const M=a===0?"\u{1F947}":a===1?"\u{1F948}":a===2?"\u{1F949}":`${a+1}`,n=Math.floor((Date.now()-new Date(u.lastActive).getTime())/864e5),_=n<1?"today":n<7?`${n}d ago`:n<30?`${Math.floor(n/7)}w ago`:`${Math.floor(n/30)}mo ago`,C=[...u.domains.entries()].sort((h,i)=>i[1]-h[1]).slice(0,3).map(([h,i])=>`${h}(${i})`).join(", ")||"\u2014";$.push(`| ${M} | **${u.handle}** | ${u.lessonCount} | ${C} | ${_} |`)}return $.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),$.join(`
63
+ `)}case"skill_gaps":{const{instance_id:g,min_failures:t=1}=q,s=await V(g),S=await ve(s,"cachly:lesson:best:*",{max:3e3}),m=new Map;let f=0,$=0;for(const M of S){const n=await s.get(M);if(!n)continue;const _=Ce(n);if(_===null)continue;const C=(_.topic??"").split(":")[0]??"unknown",h=m.get(C)??{successes:0,failures:0,attributed:0,topics:[]};_.outcome==="success"||_.outcome==="partial"?h.successes++:h.failures++,_.author&&(h.attributed++,f++),_.visibility==="private"&&$++,h.topics.push(_.topic??""),m.set(C,h)}const a=[];for(const[M,n]of m)n.failures>=t&&n.successes===0&&a.push({domain:M,type:"unresolved failures",severity:n.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${n.failures} failure${n.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),n.successes+n.failures>=3&&n.attributed===0&&a.push({domain:M,type:"no attribution",severity:"\u{1F535} info",detail:`${n.successes+n.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const u=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${S.length}** lessons scanned \xB7 **${f}** attributed \xB7 **${a.length}** gap${a.length!==1?"s":""} found`,$>0?`_(${$} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(a.length===0)u.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const M=[...a.filter(n=>n.severity.includes("critical")),...a.filter(n=>n.severity.includes("warn")),...a.filter(n=>n.severity.includes("info"))];for(const n of M.slice(0,15))u.push(`${n.severity} **\`${n.domain}\`** \u2014 ${n.type}`),u.push(` ${n.detail}`),u.push("");a.length>15&&u.push(`_\u2026and ${a.length-15} more gaps. Fix critical ones first._`)}return u.push("---",`_Fix gaps with \`learn_from_attempts(topic="${a[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),u.join(`
64
+ `)}case"brain_coverage":{const{instance_id:g,repo_path:t="."}=q,s=await V(g),[S,m,f]=await Promise.all([ve(s,"cachly:lesson:best:*",{max:5e3}),ve(s,"cachly:ckg:node:person:*",{max:2e3}),ve(s,"cachly:ckg:node:file:*",{max:5e3})]);let $=0,a="n/a";try{const{execSync:b}=await import("node:child_process"),{resolve:w}=await import("node:path"),A=w(t);$=b("git ls-files",{cwd:A,encoding:"utf-8",stdio:"pipe"}).trim().split(`
65
+ `).filter(Boolean).length,a=String($)}catch{}let u=0,M=0,n=0;const _=new Set;for(const b of S){const w=await s.get(b);if(!w)continue;const A=O(w,{});A.outcome==="success"||A.outcome==="partial"?u++:M++,A.author&&n++,_.add((A.topic??"").split(":")[0]??"unknown")}const C=$>0?`${Math.round(f.length/$*100)}% (${f.length}/${$} files)`:`${f.length} files tracked`,h=S.length>0?Math.round(n/S.length*100):0,i=Math.round(Math.min(1,S.length/50)*25+Math.min(1,u/Math.max(1,S.length))*25+Math.min(1,h/100)*25+Math.min(1,m.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${i>=80?"\u{1F7E2}":i>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${i}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${S.length}** (${u} success \xB7 ${M} failure) |`,`| Problem domains | **${_.size}** |`,`| Attribution | **${n}/${S.length}** (${h}%) |`,`| Contributors | **${m.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,S.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,u/Math.max(1,S.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,h/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,m.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
66
+ `)}case"brain_metrics":{const{instance_id:g}=q,t=await V(g),[s,S,m,f,$,a]=await Promise.all([t.get(`cachly:stats:born_at:${g}`).catch(()=>null),t.get(`cachly:stats:first_recall_at:${g}`).catch(()=>null),t.get(`cachly:stats:recalls_total:${g}`).catch(()=>null),t.get(`cachly:stats:cross_author_recalls:${g}`).catch(()=>null),t.get(`cachly:stats:time_saved_mins:${g}`).catch(()=>null),t.smembers(`cachly:stats:reuse_pairs:${g}`).catch(()=>[])]);let u={};try{u=await t.hgetall(Tt(g))??{}}catch{u={}}let M={};try{M=await t.hgetall(pt(g))??{}}catch{M={}}const n={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const R=await t.lrange(dt(g),0,499),E=new Map;for(const H of R){const se=O(H,{ts:"",themen:[]});if(!(!se.ts||!Array.isArray(se.themen)))for(const Y of se.themen){if(n.lieferungen++,!E.has(Y)){const r=await t.get(`cachly:lesson:best:${Y}`).catch(()=>null);E.set(Y,r?O(r,{}):null)}const o=ys(se.ts,E.get(Y)??null);if(o.length===0){n.ohneEreignis++;continue}for(const r of o)n[r]++}}}catch{}let _=0,C=0;try{const R=await t.lrange(`cachly:wirkung:${g}`,0,-1);for(const E of R){const H=O(E,{});C++,H.geholfen===!0&&_++}}catch{}let h={};try{h=await t.hgetall(Vs(g))??{}}catch{h={}}const i=Ys(h,10);let x={token:0,abrufe:0,treffer:0};try{const R=await t.get(Qs(g)),E=await t.hgetall(en(g))??{};x={token:R??0,abrufe:E.abrufe??0,treffer:E.treffer??0}}catch{}const b=Xs(x);let w;if(s&&S){const R=new Date(S).getTime()-new Date(s).getTime(),E=Math.max(0,Math.round(R/6e4)),H=E<1?"<1 min":E<60?`${E} min`:`${(E/60).toFixed(1)} h`,se=R<=2*6e4?"\u{1F7E2} under 2 min target":R<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";w=`**${H}** from first lesson \u2192 first proven recall \xB7 ${se}`}else s&&!S?w="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":w="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const A=["\u26AA **Nicht gemessen** \u2014 diese Zahl erhebt der Server nicht selbst."," Selbst messen: `npm run bench` in `sdk/mcp`."," Achtung, der Pruefstand hat 17 Lektionen und 13 Fragen \u2014 ein Beispielsatz, kein Bestand."," Auf 498 ECHTEN Lektionen gemessen am 19.08.2026: Precision@1 **30 %** (vorher 15 %)."].join(`
67
+ `),I=Number(m??0),e=Number(f??0),F=I>0?Math.round(e/I*100):0,k=F>=30?"\u{1F7E2} above 30 % target":I===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",oe=Math.round(Number($??0)),ce=oe<60?`${oe} min`:`${(oe/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",w,"","### 2. Recall-lift _(the moat proof)_",A,"_Reproduce: `npm run bench` \xB7 CI-defended in `rerank.test.ts` \xB7 details in BENCH.md_","","### 3. Team-knowledge-reuse _(the value only a shared brain delivers)_",`**${F}%** of proven recalls used a teammate's lesson (${e}/${I}) \xB7 ${k}`,a.length>0?`**${a.length}** distinct reuse relationship${a.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",Zs(b),"",b.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ce} nicht neu recherchiert \u2014 gerechnet mit 30\u2013240 Min. je Lektion nach Schwere, nicht gemessen. Die Zahl dar\xFCber braucht diese Annahme nicht._`:`_Eine **Sch\xE4tzung** von ${ce} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,I===0?'_Tip: pass `author="your-handle"` to `smart_recall` so cross-author reuse can be tracked._':"_These numbers compound: every learned lesson and every teammate raises all three._","","### \u2696\uFE0F Die drei Ausgaenge der Suche _(gezaehlt, nicht behauptet)_",(()=>{const R=Number(u.beantwortet??0),E=Number(u.knapp??0),H=Number(u.schweigen??0),se=R+E+H;if(se===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const Y=o=>`${Math.round(100*o/se)} %`;return`**${se}** Suchen: ${Y(R)} beantwortet \xB7 ${Y(E)} als knapper Sieg markiert \xB7 ${Y(H)} ehrliches Nein. (Ob ein Nein stimmt, zeigt nur die Stichprobe \u2014 die Rate hier zaehlt, sie urteilt nicht.)`})(),"","### \u{1F53D} Recall-Trichter _(je Fehlschlag: WORAN scheiterte der Abruf)_",(()=>{const R=Y=>Number(M[Y]??0),E=[["nicht-gesucht","nicht gesucht"],["nominierung","Nominierung (gesucht, nichts geliefert)"],["ranking","Ranking (geliefert, das Richtige fehlte)"],["anwendung","Anwendung (das Richtige lag vor)"],["ohne-vorwissen","ohne Vorwissen (es gab nichts zu finden)"]],H=E.reduce((Y,[o])=>Y+R(o),0);if(H===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const se=E.filter(([Y])=>Y!=="ohne-vorwissen").sort((Y,o)=>R(o[0])-R(Y[0]))[0];return`**${H}** klassifizierte Fehlschlaege: `+E.map(([Y,o])=>`${R(Y)} ${o}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${se[1]}** (${R(se[0])}) \u2014 dorthin gehoert das naechste Investment. (Heuristik je Einzelfall; erst die Verteilung ueber viele Sessions traegt.)`})(),"","### \u{1F3F7}\uFE0F Drei Etiketten ohne Selbstauskunft _(widersprochen \xB7 korrigiert \xB7 veraltet)_",n.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${n.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${n.widersprochen} widersprochen \xB7 ${n.korrigiert} korrigiert \xB7 ${n.veraltet} veraltet \xB7 ${n.ohneEreignis} ohne spaeteres Ereignis. (Kein Etikett heisst: nichts ist passiert \u2014 nicht "benutzt". Das vierte Etikett haette nur eine geschmeichelte Fassung.)`,"","### \u2696\uFE0F Netto-verhinderter-Schaden _(kann negativ werden \u2014 sonst misst es nichts)_",(()=>{const R=Number(n.widersprochen)+Number(n.veraltet);if(C===0&&R===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const E=_-R;return`**${E>=0?"+":""}${E}** = ${_} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${R} Schadenslieferungen (${n.widersprochen} spaeter widerlegt + ${n.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",Us(i,cn.length),...i.spitze.length>0?i.spitze.map((R,E)=>` ${String(E+1).padStart(2)}. \`${R.name}\` \u2014 ${R.aufrufe}\xD7 (${Math.round(R.anteil*100)} %)`):[]].filter(Boolean).join(`
68
+ `)}case"brain_service_map":{const{instance_id:g,service:t}=q;if(!t||typeof t!="string"||!t.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const s=await V(g),S=`service:${me(t.trim())}`,m=await s.get(`cachly:ckg:node:${S}`).catch(()=>null),f=m?O(m,null):null,$=await s.smembers(`cachly:ckg:idx:to:${S}`).catch(()=>[]),a=[],u=[],M=[];for(const w of $){const A=await s.get(w).catch(()=>null);if(!A)continue;const I=O(A,null);if(I)if(I.edgeType==="operates"){const e=await s.get(`cachly:ckg:node:${I.from}`).catch(()=>null),F=e?O(e,null):null;F?.handle&&a.push({handle:F.handle,trials:I.trials})}else if(I.edgeType==="runs_in"){const e=await s.get(`cachly:ckg:node:${I.from}`).catch(()=>null),F=e?O(e,null):null;F?.path&&u.push({path:F.path,trials:I.trials})}else I.edgeType==="affects"&&M.push({id:I.from,confidence:I.confidence})}a.sort((w,A)=>A.trials-w.trials),u.sort((w,A)=>A.trials-w.trials),M.sort((w,A)=>A.confidence-w.confidence);const n=[],_=await ve(s,"cachly:lesson:best:*",{max:1500}),C=t.trim().toLowerCase();for(const w of _.slice(0,400)){const A=await s.get(w).catch(()=>null);if(!A)continue;const I=Ce(A);Te(I)&&(I.service??"").toLowerCase()===C&&n.push({...I,topic:w.replace("cachly:lesson:best:","")})}if(!f&&n.length===0&&a.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${t}\``,"","Nothing known about this service yet.","","Tag lessons with the service they concern so the brain can build this map:",`\`learn_from_attempts(topic="...", service="${t}", author="you", file_paths=[...])\``].join(`
69
+ `);const h=f?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",i=[`## ${f?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${t}\``,"",f?`_${h} \xB7 ${f.count} lesson${f.count!==1?"s":""} referenced \xB7 domain: ${f.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(a.length>0){const w=a.slice(0,5).map((A,I)=>`${I===0?"\u{1F947}":I===1?"\u{1F948}":I===2?"\u{1F949}":`${I+1}.`} **${A.handle}** (${A.trials}\xD7)`).join(" \xB7 ");i.push(`**Operators:** ${w}`,"")}else i.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const x=n.filter(w=>w.outcome==="failure"),b=n.filter(w=>w.outcome!=="failure");if(x.length>0){i.push(`**\u26A0\uFE0F Known failures (${x.length}):**`);for(const w of x.slice(0,6)){const A=w.severity==="critical"?" \u{1F534}":w.severity==="major"?" \u{1F7E1}":"",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";i.push(` - \u274C \`${w.topic}\`${A}${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}i.push("")}if(b.length>0){i.push(`**\u2705 Proven fixes (${b.length}):**`);for(const w of b.slice(0,6)){const A=w.outcome==="partial"?"\u26A0\uFE0F":"\u2705",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";i.push(` - ${A} \`${w.topic}\`${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}i.push("")}return u.length>0&&i.push(`**Files in this service:** ${u.slice(0,8).map(w=>`\`${w.path}\``).join(", ")}`,""),i.push("---",`_Tag lessons with \`service="${t}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),i.join(`
70
+ `)}case"brain_collab_pairs":{const{instance_id:g,min_weight:t=1}=q,s=await V(g),S=typeof t=="number"&&t>=1?Math.floor(t):1,m=await ve(s,"cachly:ckg:node:person:*",{max:500}),f=new Map;for(const _ of m){const C=await s.get(_);if(!C)continue;const h=O(C,null);!h||h.type!=="person"||f.set(h.id,{id:h.id,handle:h.handle,domain:h.domain,count:h.count})}if(f.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
71
+ `);const $=new Map;for(const[_,C]of f){const h=await s.smembers(`cachly:ckg:idx:from:${_}`);for(const i of h){const x=await s.get(i);if(!x)continue;const b=O(x,null);if(!b||b.edgeType!=="collaborates")continue;const w=f.get(b.to);if(!w)continue;const[A,I]=_<b.to?[_,b.to]:[b.to,_],e=`${A}||${I}`,F=$.get(e);if(F)F.trials+=b.trials;else{const[k,oe]=_<b.to?[C,w]:[w,C];$.set(e,{a:k,b:oe,trials:b.trials,confidence:b.confidence})}}}const a=[...$.values()].filter(_=>_.trials>=S).sort((_,C)=>C.trials-_.trials),u=new Set;for(const _ of a)u.add(_.a.id),u.add(_.b.id);const M=[...f.values()].filter(_=>!u.has(_.id)),n=["## \u{1F91D} Team Collaboration Graph",""];if(a.length===0)n.push(`No collaboration pairs yet (min weight: ${S}).`,"","Pairs appear when two contributors touch the same file in `learn_from_attempts`",'or when someone recalls a teammate\'s lesson via `smart_recall(requester="...")`.');else{n.push(`**${a.length} collaboration pair${a.length!==1?"s":""}** across ${u.size} contributor${u.size!==1?"s":""}:`,"");for(const _ of a.slice(0,20)){const C=(_.confidence*100).toFixed(0),h=[_.a.domain,_.b.domain].filter((i,x,b)=>i&&b.indexOf(i)===x).map(i=>`\`${i}\``).join(", ");n.push(`### @${_.a.handle} \u2194 @${_.b.handle}`,`- **${_.trials} collaboration event${_.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${h||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${_.a.handle}** und **@${_.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}a.length>20&&n.push(`_...and ${a.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return M.length>0&&n.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${M.length} contributor${M.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...M.slice(0,10).map(_=>`- **@${_.handle}** \u2014 ${_.count} lesson${_.count!==1?"s":""} \xB7 domain: \`${_.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),n.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),n.join(`
72
+ `)}case"brain_portability":{const{instance_id:g}=q,t=[{name:"Claude Code",slug:"claude-code",icon:"\u{1F916}",configPath:"~/.claude/settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Cursor",slug:"cursor",icon:"\u{1F5B1}\uFE0F",configPath:"~/.cursor/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Windsurf",slug:"windsurf",icon:"\u{1F3C4}",configPath:"~/.windsurf/mcp.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"GitHub Copilot (VS Code)",slug:"copilot",icon:"\u{1F419}",configPath:".vscode/mcp.json (workspace)",configBlock:JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Cline",slug:"cline",icon:"\u26A1",configPath:"~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Zed",slug:"zed",icon:"\u26A1",configPath:"~/.config/zed/settings.json",configBlock:JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["@cachly-dev/mcp-server@latest"]},env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}}},null,2)},{name:"Continue",slug:"continue",icon:"\u25B6\uFE0F",configPath:"~/.continue/config.json",configBlock:JSON.stringify({mcpServers:[{name:"cachly",command:"npx @cachly-dev/mcp-server@latest",env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:g}}]},null,2)}],s=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${g}\``,"","Replace `<cky_live_...>` below with your own API key (get one at https://cachly.dev/setup-ai) \u2014 the Brain ID alone does not authenticate you.","","This Brain ID is model-agnostic. Every lesson you've learned, every Memory Crystal you've distilled,","and every prediction from your Causal Knowledge Graph is accessible from **any MCP-compatible AI client**.","","---","",`### Compatible Clients (${t.length} supported)`,""];for(const S of t)s.push(`#### ${S.icon} ${S.name}`,`Config: \`${S.configPath}\``,"","```json",S.configBlock,"```","");return s.push("---","","### What travels with you","","| Data | Model-neutral? |","|------|---------------|","| Lessons (learn_from_attempts) | \u2705 Full access in all clients |","| Memory Crystals (memory_crystalize) | \u2705 Included in every session_start |","| Causal Knowledge Graph (brain_predict) | \u2705 Same graph, same predictions |","| Team lessons (team_learn, team_confirm) | \u2705 Team is per-Brain, not per-model |","| Domain Brain Marketplace installs | \u2705 Installed once, available everywhere |","| Session handoffs (session_handoff) | \u2705 Cross-client continuity |","","---","","### One-command setup for any new client","","```bash","npx @cachly-dev/mcp-server@latest autopilot","```","",`Autopilot detects all installed editors and writes the config for each \u2014 with your \`${g}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),s.join(`
73
+ `)}case"brain_changelog":{const{instance_id:g,days:t=7,max_lessons:s=30,include_failures:S=!0}=q,m=await V(g),f=Date.now()-Number(t)*864e5,$=await ve(m,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),a=[];for(const i of $){const x=await m.get(i).catch(()=>null);if(!x)continue;const b=O(x,{});if((b.ts?new Date(b.ts).getTime():0)<f||!S&&b.outcome==="failure")continue;const A=i.replace("cachly:lesson:best:","");a.push({...b,topic:A})}a.sort((i,x)=>{const b=i.ts?new Date(i.ts).getTime():0;return(x.ts?new Date(x.ts).getTime():0)-b});const u=a.slice(0,Number(s));if(u.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${t} day${Number(t)!==1?"s":""}`,"","_No new lessons learned in this window. Your Brain already knows everything it knows \u2014 add new lessons with `learn_from_attempts`._"].join(`
74
+ `);const M=new Map;for(const i of u){const x=i.topic.includes(":")?i.topic.split(":")[0]:"general",b=M.get(x)??[];b.push(i),M.set(x,b)}const n=i=>i==="critical"?"\u{1F6A8}":i==="major"?"\u26A0\uFE0F":i==="minor"?"\u{1F4A1}":"\u2728",_=i=>i==="failure"?"\u274C":i==="partial"?"\u{1F536}":"\u2705",h=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${t} day${Number(t)!==1?"s":""})`,"",`_${u.length} lesson${u.length!==1?"s":""} learned across ${M.size} topic area${M.size!==1?"s":""}_`,""];for(const[i,x]of Array.from(M.entries()).sort((b,w)=>w[1].length-b[1].length)){h.push(`### ${i}`),h.push("");for(const b of x){const w=b.outcome==="failure"?_(b.outcome):n(b.severity),A=b.outcome==="failure"?b.what_failed:b.what_worked,I=[];b.author&&I.push(`by **${b.author}**`),b.recall_count&&I.push(`${b.recall_count} recall${b.recall_count!==1?"s":""}`),b.confidence!==void 0&&I.push(`${Math.round(b.confidence*100)}% confidence`),h.push(`- ${w} **${b.topic}**${A?` \u2014 ${A}`:""}`),I.length&&h.push(` _${I.join(" \xB7 ")}_`)}h.push("")}return h.push("---",`_Generated from Brain \`${g}\` \xB7 Share this in your standup or Slack_`),h.join(`
75
+ `)}case"brain_set_pref":{const{instance_id:g,key:t,value:s}=q;if(!t||!t.trim())throw new Error("key is required");const S=await V(g),m=`cachly:prefs:${t.trim()}:${g}`;return await S.set(m,String(s)),`\u2705 Preference \`${t}\` set to \`${s}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:g,key:t}=q,s=await V(g);if(t&&t.trim()){const $=await s.get(`cachly:prefs:${t.trim()}:${g}`).catch(()=>null);return $===null?`\u2139\uFE0F Preference \`${t}\` is not set (using default).`:`\u{1F527} Preference \`${t}\` = \`${$}\``}const S=await ve(s,`cachly:prefs:*:${g}`,{max:200,timeoutMs:2e3});if(S.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const m=await s.mget(...S),f=["\u{1F527} **Brain preferences:**",""];for(let $=0;$<S.length;$++){const a=S[$].replace("cachly:prefs:","").replace(`:${g}`,"");f.push(`- \`${a}\` = \`${m[$]??"(null)"}\``)}return f.join(`
76
+ `)}default:return null}}async function bn(ie,q){try{if(!Ne()||Se!=="cachly"&&Se!=="ollama")return 0;let V=0;for(const ue of ye.themen()){if(V>=q)break;if(Pe.hat(ue)||await ie.exists(`${Ie}${ue}`))continue;const g=await ie.get(`cachly:lesson:best:${ue}`);if(!g)continue;const t=O(g,{});try{const s=await $e(De(t),{geduld:"lang",modell:Oe});s?.length&&(await ie.set(`${Ie}${ue}`,Ee(s)),V++)}catch{}}return V}catch{return 0}}async function At(ie,q,V){try{if(!Ne())return;const ue=await ie.srandmember(Ae,V),g=Array.isArray(ue)?ue:ue?[ue]:[];for(const t of g){if(t===q)continue;const s=await ie.get(`cachly:lesson:best:${t}`);if(!s){await ie.srem(Ae,t);continue}const S=O(s,{});try{const m=await $e(De(S),{geduld:"lang"});if(m?.length)await ie.set(`${ut}${t}`,Ee(m)),await ie.srem(Ae,t);else continue;if(Se==="cachly"||Se==="ollama")try{const f=await $e(De(S),{geduld:"lang",modell:Oe});f?.length&&await ie.set(`${Ie}${t}`,Ee(f))}catch{}}catch{}}}catch{}}export{lo as BRAIN_TOOL_NAMES,uo as handleBrainTool,at as recallVorschau};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.168",
3
+ "version": "0.10.169",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.168",
3
+ "version": "0.10.169",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Your AI forgets everything between sessions. cachly fixes that permanently: 124 MCP tools for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run. Arrives pre-briefed. Free tier forever, EU servers, GDPR.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -6,13 +6,13 @@
6
6
  "url": "https://github.com/cachly-dev/cachly-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.10.168",
9
+ "version": "0.10.169",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "name": "@cachly-dev/mcp-server",
14
14
  "identifier": "@cachly-dev/mcp-server",
15
- "version": "0.10.168",
15
+ "version": "0.10.169",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }