@cachly-dev/mcp-server 0.10.247 → 0.10.249

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,73 +1,73 @@
1
- import{gitLesen as Fe,istCommitHash as $s,pruefeOrdner as ht}from"../git-ohne-shell.js";import{createRequire as It}from"node:module";import{calculateConfidence as Mt,confidenceBadge as ks,STRUCTURED_TEMPLATES as vs,CONFIDENCE_WARN_VALUE as Ss}from"../confidence.js";import{kurzfassenHinweis as Cs}from"../antwort-hinweis.js";import{pruefeMeldung as xs,wendeAn as Ts}from"../pruefung-melden.js";import{ckgSlug as me,extractProblemConcept as ut,ckgUpsertNode as He,ckgUpdateEdge as ve,ckgUpsertPersonNode as Ns,ckgUpsertFileNode as Rt,ckgRecordCollaboration as Es,ckgUpsertServiceNode as As}from"../ckg.js";import{safeJsonParse as W,scanKeys as Me,leseOderNull as De,darfHeraus as Ge}from"../utils.js";import{ersparteMinuten as Lt,istStarterLektion as Is,zaehltAlsErsparnis as Bt}from"../wertbeitrag.js";import{lessonPreviewLines as st,trimTo as Ms}from"../lesson-preview.js";import{normalisiereZeit as dt,zaehleZeitangaben as ft}from"../zeit-normalisieren.js";import{abstentionSatz as Rs,alterssatzFuerBelegte as Ls,beurteileTreffer as Bs,istBelegt as Ot}from"../abstention.js";import{meldeEinmal as pt,meldeUndVermerke as Ze,fehlerText as nt,OHNE_VEKTOREN as Os,OHNE_DIENST as Ds,OHNE_FRAGEVEKTOR as zs,SINNPFAD_ABBRUCH as Ps,OHNE_SCHREIBVEKTOR as ot}from"../aussetzer.js";import{versuchStart as js,neueKennung as Ws,wendeZuteilungAn as Fs,schliesseVersuchAb as Hs}from"../versuch.js";function gt(R,N,L,X=L){if(R.includes("lesson:best:")){const o=W(N,{});if(o&&typeof o=="object"&&(o.what_worked||o.what_failed||o.commands?.length))return st(o,{maxChars:L,indent:" "})}const h=Ms(N,X);return h?[h]:[]}const Dt=2e3,zt=400;function Pt(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as Gs,holeKantenVorrat as Ks,SPEICHER_SCAN_SCHRITT as jt}from"../kanten-vorrat.js";import{getRole as at,ROLE_BADGE as Vs,getScopes as mt,lessonVisibleToScope as rt,reviewModeEnabled as Js,storeLessonProposal as qs}from"./team.js";import{keywordSearch as it,treffeUeberDateipfad as Us,wortindexEntwerten as Wt,tokenize as wt,splitMultiQuery as Ys,levenshtein as Zs,indexVocab as Ft,bestandHolen as Xs}from"../search.js";import{startetNochLeer as Ht,leeresBrainAntwort as Gt,startLageMitCommits as yt,sofortAntwortNeuesBrain as Qs,neuesBrainBriefing as en}from"../leeres-brain.js";import{rerankByQuality as tn,qualityMultiplier as sn,extractLessonQuality as nn}from"../rerank.js";import{computeEmbedding as Te,hasEmbedProvider as Be,EMBED_PROVIDER as Ce}from"../embeddings.js";import{leserAktiv as on,leserPunkte as an,mischeMitLeser as rn}from"../leser.js";import{repariereFelder as cn}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as _t,NAME_VEKTOR_PRAEFIX as ct,ZWEIT_VEKTOR_PRAEFIX as Ke,packe as ze,textFuerVektor as Ve,textFuerNamensVektor as bt,Vektorbestand as $t,VEKTOR_NACHTRAG as ln,NAME_VEKTOR_NACHTRAG as Xe,ZWEIT_VEKTOR_NACHTRAG as lt}from"../bedeutung.js";import{schreibeEingaenge as hn,Eingangsbestand as un}from"../eingaenge.js";import{ordneNachHausordnung as dn,rangWerte as fn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as pn}from"../seltenheitsbestand.js";import{spurLegen as gn}from"../spuren.js";import{schlageErsetzungVor as mn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as Kt,stufeSucheNachProjektversion as wn,versionsNotizen as yn,versionsBanner as _n}from"../gueltigkeit-version.js";const Je=ln,bn=365;import{etikettenFuer as $n,lieferJournalSchluessel as Vt,JOURNAL_DECKEL as kn}from"../etiketten.js";import{klassifiziereFehlschlag as vn,suchProtokollSchluessel as kt,trichterSchluessel as Jt,SUCH_DECKEL as qt}from"../recall-trichter.js";import{leiteEntscheidungAb as Sn,entscheidungsZeile as Ut}from"../entscheidung-ableiten.js";import{bewerteTopf as Cn,spreizeImTopf as Yt,reichereAn as xn,inhaltsWoerter as Zt,grobStamm as Tn,GEWICHTE as Nn,knapperSiegSatz as En}from"../rangfolge.js";import{fehlendeLernfelder as An,hatFrage as In,kappeAnfrage as Mn,ungueltigerAusgang as Rn}from"../pflichtfelder.js";import{pruefeWirkung as Ln,wirkungsEingabeAus as Bn,werteAus as On,lehrwert as Dn,leiteAb as zn,belegeJeThema as Pn}from"../wirkungsspur.js";import{merkeSuchlauf as vt}from"../suchstatistik.js";import{schreibeTopfNotiz as jn,topfProtokollAktiv as Wn}from"../topf-protokoll.js";import{SINN_TOPF as Fn,EINGANG_SCHWELLE as Hn,EINGANG_SORTIER_GEWICHT as Gn,ZWEIT_MODELL as qe,ZWEIT_GEWICHT as Kn,ZWEIT_MINDESTDECKUNG as Xt,NAHDUPLIKAT_SCHWELLE as Vn,LESER_TIEFE as Qt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as es,quelleZeile as Jn}from"../herkunft.js";import{doppelHinweis as qn,leseDoppelKandidaten as Un,mitFrist as Yn,pruefeDoppelung as Zn}from"../doppel-kandidat.js";import{merkeRecall as Xn,sitzungsKosten as Qn,vergissSitzungsKosten as eo,kostenZeilen as to}from"../sitzungs-kosten.js";const ts=new WeakMap;function St(R){let N=ts.get(R);return N||(N={vektor:new $t,namen:new $t(6e4,ct),zweit:new $t(6e4,Ke),eingang:new un,seltenheit:new pn},ts.set(R,N)),N}const ss=Fn,so=Hn,no=Gn;import{upgradeNudge as oo}from"../upgrade-nudge.js";import{recallTiefe as ns,verlangteTiefe as ao,TIEFE_VOLL as ro,TIEFE_VOLL_MEHRTHEMIG as io}from"../recall-tiefe.js";import{nutzungInWorten as co,nutzungsSchluessel as lo,verdichte as ho}from"../werkzeug-nutzung.js";import{inWorten as uo,lieferBild as fo,lieferSchluessel as po,trefferSchluessel as go}from"../geliefert.js";import{COAUTHOR_PREF_KEY as mo,autorHinweis as wo,coautorAus as yo,echterGitLeser as _o,ermittleAutor as bo,mitCoautor as $o,nurMensch as os}from"../autor.js";import{TOOLS as ko}from"../tools.js";import{vorspannHinweis as vo}from"../vorspann.js";import{autorAbzeichen as So,fremdanteil as Co}from"../autor-abzeichen.js";import{cachlyUrl as xo}from"../cachly-url.js";import{belegFuer as To}from"../schreibbeleg.js";import{rueckfallHinweis as No,dazuHinweis as Eo}from"../rueckfall.js";import{schwaerzeFelder as Ao}from"../geheimnis-filter.js";import{VERDACHT_TAG as Ct,mitVerdachtTag as Io,pruefeFelder as Mo,verdachtsWarnung as Ro}from"../tuersteher.js";import{fuerEigenenSpeicher as Pe,hinweise as je,istMarkiert as as,markiert as Lo,markierungsWarnung as rs,markierungsWarnungAusRohwert as is,zaehlHinweise as cs}from"../schreibtor.js";import{istBlossesThema as ls}from"../blosses-thema.js";import{zeitpunkt as ye}from"../zeitmessung.js";import{wartetAufFrischenBestand as Bo}from"../bestand-frische.js";const Qe=(()=>{try{const R=It(import.meta.url);for(const N of["../../../package.json","../../package.json"])try{const L=R(N);if(L.name==="@cachly-dev/mcp-server"&&L.version)return L.version}catch{}}catch{}return"0.10.100"})(),Oo=()=>{try{return It(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Do={"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${Qe}:**`," \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"]},Ya=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"]),zo=xo("/billing","upgrade"),hs=new Map,us=new Set,Po=1680*60*60;function jo(R=new Date){return`cachly:quota:recalls:${R.toISOString().slice(0,7)}`}async function xt(R){try{const N=jo();await R.incr(N)===1&&await R.expire(N,Po)}catch{}}function ds(R){return`cachly:stats:drei-ausgaenge:${R}`}async function Tt(R,N,L){try{await R.hincrby(ds(N),L,1)}catch{}}function fs(R,N,L,X){xt(R),vt(R,L,X);const h={ts:new Date().toISOString(),frage:L.slice(0,200),geliefert:[]};(async()=>{const o=kt(N);await R.lpush(o,JSON.stringify(h)),await R.ltrim(o,0,qt-1)})().catch(()=>{}),Tt(R,N,"schweigen")}async function ps(R){const N={tage:0,rekord:0};try{const L=await R.get("cachly:streak:current"),X=W(L,null),h=new Date().toISOString().slice(0,10);if(X){const o=X.last_date,u=new Date(Date.now()-864e5).toISOString().slice(0,10);o===h?(N.tage=X.days,N.rekord=X.record):o===u?(N.tage=X.days+1,N.rekord=Math.max(N.tage,X.record),await R.set("cachly:streak:current",JSON.stringify({days:N.tage,last_date:h,record:N.rekord}))):(N.tage=1,N.rekord=X.record,await R.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:N.rekord})))}else N.tage=1,N.rekord=1,await R.set("cachly:streak:current",JSON.stringify({days:1,last_date:h,record:1}))}catch{}return N}async function gs(R,N,L){await R.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:N,provider:L}),"EX",86400)}const Nt=new Map;async function ms(R,N){const L=hs.get(R);if(L&&L.expiresAt>Date.now())return L.gate;let X=Nt.get(R);return X||(X=Wo(R,N).finally(()=>{Nt.delete(R)}),Nt.set(R,X)),L&&!Bo()?L.gate:X}async function Wo(R,N){try{const L=await N(`/api/v1/instances/${R}/memory`),X=L?.recall_limit??-1,h=L?.total_recall_count??0,o={reached:X>0&&h>=X,limit:X,used:h,goodwillMessage:L?.goodwill_message,notice:L?.notice};return hs.set(R,{gate:o,expiresAt:Date.now()+6e4}),o}catch{return{reached:!1,limit:-1,used:0}}}const Fo={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function Za(R,N,L,X){const h=await Ho(R,N,L,X),o=Fo[R];if(o&&typeof h=="string")try{Xn(String(N.instance_id??""),String(N[o]??""),h.length)}catch{}return h}async function Ho(R,N,L,X){switch(R){case"learn_from_attempts":{{const b=An(N);if(b.length)return`\u26A0\uFE0F learn_from_attempts needs ${b.join(" and ")}. Nothing was stored.`;const j=Rn(N);if(j)return j}const h=Ao(N),o=Mo(h.felder),u=o.length?{...h.felder,tags:Io(h.felder.tags)}:h.felder,{instance_id:p,topic:a,outcome:n,what_worked:v,what_failed:d="",context:i="",severity:S="major",file_paths:t=[],commands:s=[],tags:C=[],depends_on:r=[],author:c="",visibility:$="team",service:m="",service_kind:w="service",group:M="",grund:I="",ersetzt:e="",gilt_ab:Z="",gilt_fuer:ce}=u,{what_worked:ie,what_failed:he="",context:ne=""}=cn({what_worked:v,what_failed:d,context:i}),g=await L(p),K=new Date,Q=K.toISOString();let Y=Kt(ce,void 0);const ee=Z&&!Number.isNaN(Date.parse(String(Z)))?new Date(String(Z)):K,V=dt(ie,ee),te=dt(he,ee),l=dt(ne,ee),k=ft(ie,ee)+ft(he,ee)+ft(ne,ee),E=bo({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:_o(process.env.CACHLY_WORKSPACE??process.cwd())});let A="";try{A=yo(await g.get(`cachly:prefs:${mo}:${p}`))}catch{}const _=$o(E.autor,A),x=wo(E);if($!=="private"&&await Js(g,p))return qs(g,a,{topic:a,outcome:n,what_worked:V,what_failed:te,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:r,...Y.angaben.length?{gilt_fuer:Y.angaben}:{},..._?{author:_}:{},source:es(),...m?{service:m}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:0,ts:Q,confidence:1,version:3});const H=a.split(":")[0],F=vs[H],J=[];if(F)for(const b of F.required)b==="commands"&&s.length===0&&J.push(`\u{1F4CB} ${F.hint}`);let z=!1,le=0,ge,ue=[];const se=await g.get(`cachly:lesson:best:${a}`),we=String(I||u.reason||"").trim();if(se&&!we)return[`\u270B **Update rejected:** \`${a}\` already exists \u2014 an update needs the field \`grund\` (the reason; \`reason\` works too).`,"","One line is enough: WHY was the previous version wrong or incomplete?",'Example: grund="The deploy target moved from port 3000 to 8080"',"","The diff says WHAT changes. The grund line says why the old version was wrong \u2014","and that is the line someone reads two months from now (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
- `);if(se)try{const b=JSON.parse(se);Y=Kt(ce,b.gilt_fuer),le=b.recall_count??0,ge=b.last_recalled_at,ue=b.audit_trail??[],ue.push({ts:Q,action:"updated",prev_outcome:b.outcome,grund:we}),ue.length>20&&(ue=ue.slice(-20)),z=!0;const j=[];if(b.outcome==="success"&&n==="failure"?j.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."):b.outcome==="failure"&&n==="success"&&j.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),j.length>0){ue[ue.length-1].action="contradiction-resolved";try{const U=me(a),P=me(`resolution:${a}`);await ve(g,U,"contradicts",P,!1)}catch{}try{const U=`cachly:contradictions:${a}`,P=b.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await g.rpush(U,JSON.stringify({ts:Q,prev_outcome:b.outcome,new_outcome:n,direction:P})),await g.ltrim(U,-50,-1),await g.expire(U,180*86400)}catch{}j.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${a}")\` to resolve via expert agent voting.`)}}catch{}else ue=[{ts:Q,action:"created"}];const We=[];if(n==="failure"){const b=[],j=g.scanStream({match:"cachly:lesson:best:*",count:jt});await new Promise((P,T)=>{j.on("data",D=>b.push(...D)),j.on("end",P),j.on("error",T)});const U=a.split(/[:\-_]/).filter(P=>P.length>2);for(const P of b.slice(0,50)){const T=await g.get(P);if(T)try{const D=JSON.parse(T);if(D.outcome!=="success")continue;const re=(D.topic??"").split(/[:\-_]/).filter(pe=>pe.length>2);if(U.filter(pe=>re.includes(pe)).length>=1&&D.topic!==a){We.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${D.topic}\` (success, ${D.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${D.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${D.topic}", ..., severity="critical")\``);break}}catch{}}}for(const b of r){const j=`cachly:dep:${b}`,U=await g.get(j),P=W(U,[]);P.includes(a)||P.push(a),await g.set(j,JSON.stringify(P),"EX",90*86400)}const Ee={topic:a,outcome:n,what_worked:V,what_failed:te,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:r,..._?{author:_}:{},source:es(),...m?{service:m}:{},...M?{group:String(M).toLowerCase().trim()}:{},visibility:$,recall_count:le,...ge?{last_recalled_at:ge}:{},...Z&&!Number.isNaN(Date.parse(String(Z)))?{gilt_ab:new Date(String(Z)).toISOString()}:{},...Y.angaben.length?{gilt_fuer:Y.angaben}:{},ts:Q,verified_at:n==="success"||n==="partial"?Q:void 0,confidence:1,audit_trail:ue,version:3},_e=String(e??"").trim();let Re="",be=null;_e===a&&_e?Re="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":_e&&(be=await g.get(`cachly:lesson:best:${_e}`),be?W(be,{}).ersetzt===a?(be=null,Re=`\u26A0\uFE0F \`${_e}\` already replaces \`${a}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${_e}\` first, then set it here.`):Ee.ersetzt=_e:Re=`\u26A0\uFE0F The lesson to replace, \`${_e}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Ue="";if(!_e)try{const b=D=>{const re=W(D.content,{});return{topic:re.topic??D.key.slice(19),what_worked:re.what_worked}},[j,U]=await Promise.all([it(g,["cachly:lesson:best:*"],`${a} ${V}`.slice(0,300),5),Us(g,["cachly:lesson:best:*"],t??[])]),P=new Set,T=[...j,...U].filter(D=>D.key.startsWith("cachly:lesson:best:")).filter(D=>!P.has(D.key)&&P.add(D.key)).map(b);Ue=mn(a,V,T)??""}catch{}if(n==="failure")try{const j=(await g.lrange(kt(p),0,199)).map(T=>W(T,{ts:"",frage:"",geliefert:[]})).filter(T=>T.ts!==""),U=(await it(g,["cachly:lesson:best:*"],`${a} ${te||V}`.slice(0,300),5)).filter(T=>T.key.startsWith("cachly:lesson:best:")).map(T=>{const D=W(T.content,{});return{topic:D.topic??T.key.slice(19),what_worked:D.what_worked}}),P=vn(a,String(te||""),j,U);await g.hincrby(Jt(p),P,1)}catch{}const Oe=Sn([V,te,i].filter(Boolean).join(" ").slice(0,2e3));Oe&&(Ee.entscheidung=Oe);const oe=To(a,Q,V);Ee.beleg=oe;const Le=JSON.stringify(Ee);g.set(`cachly:stats:born_at:${p}`,Q,"EX",365*86400,"NX").catch(()=>{});const Ae=`cachly:lessons:${a}`;await g.rpush(Ae,Le),await g.ltrim(Ae,-100,-1),await g.expire(Ae,bn*86400);let Se=!1;if(n==="success"||n==="partial"?(await g.set(`cachly:lesson:best:${a}`,Le),Se=!0):se||(await g.set(`cachly:lesson:best:${a}`,Le),Se=!0),be&&Se)try{const b=JSON.parse(be);b.ersetzt_durch=a,b.gilt_bis=Q,b.ersetzt_am=Q,we&&(b.ersetzt_grund=we.slice(0,200)),await g.set(`cachly:lesson:best:${_e}`,JSON.stringify(b))}catch{}Se&&Wt();let Ie=()=>{};const f=new Promise(b=>{Ie=b});if(Se&&Be()||Ie(null),Se&&Be()){await g.sadd(Je,a).catch(()=>{}),await g.sadd(Xe,a).catch(()=>{}),(Ce==="cachly"||Ce==="ollama")&&await g.sadd(lt,a).catch(()=>{});const b=Et(g);b.add(a),(async()=>{const j=W(Le,{});let U=Promise.resolve();try{const T=await Te(Ve(j),{geduld:"lang"});T?.length?(await g.set(`${_t}${a}`,ze(T)),await g.srem(Je,a).catch(()=>{}),Ie(await Zn(g,{...j,topic:a},T,St(g).vektor))):Ie(null),(Ce==="cachly"||Ce==="ollama")&&(U=(async()=>{try{const D=await Te(Ve(j),{geduld:"lang",modell:qe});D?.length&&(await g.set(`${Ke}${a}`,ze(D)),await g.srem(lt,a).catch(()=>{}))}catch(D){await Ze(g,ot,`Zweit-Vektor nicht geschrieben (${Ce}, ${qe}): ${nt(D)} \u2014 die Lektion ist gespeichert, der Nachtrag holt ihn spaeter.`)}})())}catch(T){Ie(null),await g.sadd(Je,a).catch(()=>{}),await Ze(g,ot,`Volltext-Vektor nicht geschrieben (${Ce}): ${nt(T)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}const P=bt(a);try{if(!P)await g.srem(Xe,a).catch(()=>{});else{const T=await Te(P,{geduld:"lang"});T?.length&&(await g.set(`${ct}${a}`,ze(T)),await g.srem(Xe,a).catch(()=>{}))}}catch(T){await Ze(g,ot,`Namens-Vektor nicht geschrieben (${Ce}): ${nt(T)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await hn(g,a,j,T=>Te(T,{geduld:"lang"}))}catch(T){await Ze(g,ot,`Eingaenge nicht geschrieben (${Ce}): ${nt(T)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await U,await ws(g,a,3),Ie(null)})().finally(()=>b.delete(a))}try{const b="cachly:session:decision-log",j=JSON.stringify({ts:Q,topic:a,outcome:n,what_worked:V.slice(0,120)});await g.rpush(b,j),await g.ltrim(b,-50,-1)}catch{}let y=null;try{const b=me(a),j=a.split(":")[0]??"unknown";await He(g,b,j,j);for(const P of C){const T=me(`tag:${P}`);await He(g,T,"tag","tag"),await ve(g,b,"co-occurs",T,n==="success",n==="partial")}for(const P of r){const T=me(P);await ve(g,b,"requires",T,!0)}if((j==="fix"||j==="debug")&&(n==="success"||n==="partial")){const P=te||l||"",T=P?ut(P):null;if(T){const D=me(`problem:${T}`);await He(g,D,"problem","problem"),await ve(g,b,"fixes",D,n==="success",n==="partial")}}if(n==="failure"&&(te||V)){const T=ut(te||V);if(T){const D=me(`cause:${T}`);await He(g,D,"cause","cause"),await ve(g,b,"causes",D,!1)}}if(n==="failure"){const P=await g.smembers(`cachly:ckg:idx:from:${b}`);for(const T of P){const D=await g.get(T);if(!D)continue;const re=W(D,null);if(re&&re.edgeType==="fixes"&&re.confidence>.7&&re.trials>=3){y=`\u26A0\uFE0F **belief_conflict** on \`${a}\`: previously confirmed fix (confidence ${re.confidence.toFixed(2)}, n=${re.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${a}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${b}")\` to review.`;const de=`cachly:ckg:conflict:${b}`;await g.set(de,JSON.stringify({topic:a,concept_id:b,detected_at:new Date().toISOString(),fix_confidence:re.confidence,fix_trials:re.trials,failure_outcome:n,reported_by:_||"unknown",what_failed:te||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(j==="fix"||j==="debug")){const P=await g.smembers(`cachly:ckg:idx:from:${b}`);for(const T of P.slice(0,10)){const D=await g.get(T);if(!D)continue;const re=W(D,null);if(!re||re.edgeType!=="fixes")continue;const de=await g.smembers(`cachly:ckg:idx:from:${re.to}`);for(const pe of de.slice(0,5)){const Ne=await g.get(pe);if(!Ne)continue;const ke=W(Ne,null);ke&&ke.edgeType==="co-occurs"&&(ke.successes=(ke.successes||0)+.1,ke.trials=(ke.trials||0)+.1,ke.confidence=(ke.successes+1)/(ke.trials+2),ke.last_updated=new Date().toISOString(),await g.set(pe,JSON.stringify(ke)))}}}if(Math.random()<.01){const P=Date.now()-7776e6,T=await g.smembers(`cachly:ckg:idx:from:${b}`);for(const D of T){const re=await g.get(D);if(!re)continue;const de=W(re,null);de&&de.trials<3&&de.last_updated&&new Date(de.last_updated).getTime()<P&&(de.confidence=de.confidence*.9,de.last_updated=new Date().toISOString(),await g.set(D,JSON.stringify(de)))}}}catch{}if(_){g.set(`cachly:agents:active:${_}`,JSON.stringify({author:_,last_topic:a,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const b=a.split(":")[0]??"unknown",j=await Ns(g,os(_),b),U=me(a);await ve(g,j,"authored",U,n==="success",n==="partial");for(const P of t.slice(0,8)){const T=await Rt(g,P);await ve(g,j,"touched",T,!0),await Es(g,T,j)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const b=a.split(":")[0]??"unknown",j=w==="system"?"system":"service",U=await As(g,m.trim(),b,j),P=me(a);if(await ve(g,P,"affects",U,n==="success",n==="partial"),_){const T=`person:${me(os(_))}`;await ve(g,T,"operates",U,!0)}for(const T of t.slice(0,8)){const D=`file:${me(T)}`;await ve(g,D,"runs_in",U,!0)}}catch{}if(_&&(n==="success"||n==="partial")){const b={topic:a,outcome:n,what_worked:V,what_failed:te??"",severity:S,author:_,file_paths:t,commands:s,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},j=`cachly:lessons:${a}`;g.rpush(j,JSON.stringify(b)).catch(()=>{})}const B=n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C",ae=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",O=z?"updated":"stored",q=await Yn(f);return[`${B} **Lesson ${O}:** \`${a}\` (${n}) ${ae} ${S} \xB7 receipt: \`${oe}\``,h.funde.length?`\u{1F512} **${h.funde.length} secret(s) redacted** before saving (${h.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",Ro(o),y??"","",`**What worked:** ${V}`,te?`**What failed:** ${te}`:"",l?`**Context:** ${l}`:"",t.length>0?`**Files:** ${t.map(b=>`\`${b}\``).join(", ")}`:"",s.length>0?`**Commands:** ${s.map(b=>`\`${b}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(b=>`#${b}`).join(" ")}`:"","",z?`\u267B\uFE0F Updated (recall count: ${le} \xB7 audit entries: ${ue.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${a}")\``,_&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${_}_${E.quelle!=="uebergeben"?` \xB7 from ${E.quelle}`:""}) \u2014 visible in \`team_recall\``:"",x??"",r.length>0?`\u{1F517} Depends on: ${r.map(b=>`\`${b}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Ue,qn(q,Ue),Y.angaben.length?`\u{1F4E6} Applies to ${Y.angaben.map(b=>`\`${b}\``).join(", ")}${Y.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...Y.fehler.map(b=>`\u26A0\uFE0F gilt_fuer not stored, ${b}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),be&&Se?we?`\u21B7 Replaces \`${_e}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${_e}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:Re,...J,...We,k>0?`\u{1F5D3}\uFE0F ${k} relative time reference${k===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(K.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",vo(V)??"",No({outcome:n,topic:a,what_worked:V,what_failed:te,file_paths:t}),Eo({outcome:n,topic:a,what_worked:V,what_failed:te,file_paths:t})].filter(b=>b!=="").join(`
3
- `)}case"lesson_verified":{const{instance_id:h}=N,o=await L(h),u=new Date().toISOString(),p=N,a=Pe({geprueft_mit:p.geprueft_mit,befund:p.befund}),n=xs({...p,...a.felder},u);if(!n.ok)return[`\u26A0\uFE0F ${n.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 v=n.eintrag,d=`cachly:lesson:best:${v.topic}`,i=await o.get(d);if(!i)return`\u{1F4ED} Keine Lektion \`${v.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const S=W(i,{}),t=Ts(S,v);return await o.set(d,JSON.stringify(a.verdacht.length?{...t,tags:Lo(t.tags,a.verdacht)}:t)),Wt(),!v.haelt&&v.ursache==="umgebung"?[`\u2139\uFE0F \`${v.topic}\`: Pruefung an der Umgebung gescheitert \u2014 die Lektion bleibt, wie sie war.`,` Befund: ${v.befund}`,"","Nicht als fraglich markiert, `verified_at` unveraendert. Das sagt etwas ueber","den Tag, nicht ueber die Lektion. Pruefe noch einmal, wenn die Umgebung wieder steht.",...je(a)].join(`
5
- `):v.haelt?[`\u2705 \`${v.topic}\` ist wieder frisch \u2014 geprueft am ${u.slice(0,10)}.`,v.geprueft_mit?` geprueft mit: \`${v.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...je(a)].filter(Boolean).join(`
6
- `):[`\u26A0\uFE0F \`${v.topic}\` ist als fraglich markiert.`,` Befund: ${v.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="${v.topic}", \u2026, grund="\u2026")\`.`,...je(a)].join(`
7
- `)}case"recall_feedback":{const{instance_id:h}=N,o=await L(h),u=Ln(Bn(N),new Date().toISOString());if(!u.ok)return[`\u26A0\uFE0F ${u.grund}`,"","Example:","```",'recall_feedback(instance_id="\u2026", query="why does the deploy abort",',' topic="ci:timeout-reports-cancelled", helped=true, rank=0)',"```","rank=0 means: the lesson was NOT in the answer at all.","That is the most valuable feedback there is."].join(`
8
- `);const p=u.eintrag,a=`cachly:wirkung:${h}`;await o.rpush(a,JSON.stringify(p));const v=(await o.lrange(a,0,-1).catch(()=>[])).map(s=>W(s,null)).filter(Boolean),d=On(v),i=Dn(p),S={"fehlender-treffer":"It helped but was not in the answer at all \u2014 the search never picked it up. That is the most valuable case.","zu-weit-hinten":`It helped but was only at rank ${p.platz} \u2014 the ranking was too weak.`,"falsch-und-sicher":`It was at rank ${p.platz} and did not help \u2014 the ranking was confident and wrong.`,bestaetigung:"It was near the top and helped. Confirmed.",unauffaellig:"It did not help and was far down. Says little."},t=d.trefferquote===null?"no helpful feedback yet":`${(d.trefferquote*100).toFixed(0)} % of the helpful lessons were in the top three`;return[`\u2705 Noted: **${p.thema}** \u2014 ${p.geholfen?"helped":"did not help"}, rank ${p.platz===0?"\u2014 (not in the answer)":p.platz}`,"",S[i],"",`Feedback so far: ${d.gesamt}, ${t}.`,`Of these: ${d.nachLehrwert["fehlender-treffer"]} not found \xB7 ${d.nachLehrwert["zu-weit-hinten"]} too far down \xB7 ${d.nachLehrwert["falsch-und-sicher"]} confident and wrong.`].join(`
9
- `)}case"recall_best_solution":{const h=Date.now(),{instance_id:o,topic:u,author:p}=N,a=await Qs(o,X,`\u{1F4ED} No lessons found for \`${u}\`.`);if(a)return a;const n=await L(o);try{const s=await n.get(`cachly:letzter-recall:${o}`),C=s?W(s,null):null,r=zn(C,u,new Date().toISOString());r&&(await n.rpush(`cachly:wirkung:${o}`,JSON.stringify(r)),await n.del(`cachly:letzter-recall:${o}`))}catch{}const v=await n.get(`cachly:lesson:best:${u}`);if(v){const s=W(v,null);if(!s)return`\u26A0\uFE0F Lesson data for \`${u}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const C=s.group;if(C){const se=p?await mt(n,o,p).catch(()=>new Set):new Set,we=p?await at(n,o,p).catch(()=>null)==="admin":!1;if(!rt(C,se,we))return`\u{1F4ED} No lessons found for \`${u}\`. Use \`learn_from_attempts\` after solving it.`}const r=Mt(s),c=s.verified_at??s.ts,$=(Date.now()-new Date(c).getTime())/864e5,m=s.commands,w=ks(r,$,Array.isArray(m)&&typeof m[0]=="string"?m[0]:void 0,s.pruefung_gefallen_am?{am:s.pruefung_gefallen_am,befund:s.pruefung_befund}:void 0,s.pruefung_umgebung_am?{am:s.pruefung_umgebung_am,befund:s.pruefung_umgebung_befund}:void 0),M=new Date().toISOString(),I={...s,recall_count:(s.recall_count??0)+1,last_recalled_at:M};await n.set(`cachly:lesson:best:${u}`,JSON.stringify(I)),xt(n),vt(n,String(u??""),Date.now()-h);const e=Bt(s)?Lt(s):0;e>0&&n.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,e).catch(()=>{});const Z=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":s.severity?"\u{1F7E2}":"",ce=s.audit_trail??[],ie=ce.filter(se=>se&&typeof se.grund=="string"&&se.grund.trim().length>0).slice(-3).map(se=>` \xB7 ${se.ts?new Date(se.ts).toLocaleDateString("de-DE"):"?"}: ${se.grund.trim()}`),he=ce.length>1?[`_Audit: ${ce.length} changes \xB7 stored ${new Date(s.ts).toLocaleDateString("de-DE")}_`,...ie.length>0?["**Warum zuletzt geaendert:**",...ie]:[]].join(`
10
- `):"",ne=(Date.now()-new Date(s.ts).getTime())/864e5,g=ne>60?`\u{1F4AD} _Remember when you solved this ${Math.round(ne/30)} months ago? Still works._`:"",K=I.recall_count===3&&!s.pinned?"\u{1F4CC} **This lesson came up in 3 answers so far.** If you need it often, pin it: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",Q=s.authors??(s.author?[s.author]:[]),Y=[...new Set(Q.filter(Boolean))];let ee="";Y.length>=2&&(ee=`\u2705 **Team-verified** \u2014 confirmed by ${Y.length} developers.`);const V=s.ersetzt_durch,te=s.ersetzt_am?` (on ${s.ersetzt_am.slice(0,10)})`:"",l=V?await n.get(`cachly:lesson:best:${V}`):null,k=String(s.ersetzt_grund??"").trim(),E=k?` Reason: ${k}`:" No reason recorded.",A=l?De(l):null,_=l?!Ge(A):!1;let x=!1;if(l&&!_&&A?.group){const se=p?await mt(n,o,p).catch(()=>new Set):new Set,we=p?await at(n,o,p).catch(()=>null)==="admin":!1;x=!rt(A.group,se,we)}const H=V?l?_?`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the successor lesson is private, not visible to the team. The text below stays readable as history; its author knows the current version.`:x?`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the successor lesson is not visible to you. The text below stays readable as history.`:`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the current answer is in \`recall_best_solution(topic="${V}")\`.${E} The text below stays readable as history.`:`\u26A0\uFE0F **REPLACEMENT POINTS NOWHERE**${te} \u2014 the successor \`${V}\` has been deleted. This version applies again as the best EXISTING answer; confirm it when you can (learn_from_attempts with grund).`:"",F=s.gilt_ab,J=s.gilt_bis,z=F?`\u{1F4C5} Valid since ${String(F).slice(0,10)}.`:"",le=s.entscheidung,ge=le?.gegen?Ut({gegen:le.gegen,grund:le.grund??null}):"",ue=J&&Date.parse(String(J))<Date.now()?`\u23F3 **THIS FACT WAS VALID UNTIL ${String(J).slice(0,10)}** \u2014 it is history, not current information.`:"";return[rs(s),H,ue,_n(s.gilt_fuer),z,ge,g,ee,`${w} **Best solution for \`${u}\`** ${Z}${s.severity?` (${s.severity})`:""} \xB7 in ${I.recall_count} answer${I.recall_count===1?"":"s"} so far`,Jn(s.author,s.source),"",s.what_worked?`**What worked:** ${s.what_worked}`:"",s.what_failed?`**What failed (avoid this):** ${s.what_failed}`:"",s.context?`**Context:** ${s.context}`:"",(s.file_paths??[]).length>0?`**Files:** ${(s.file_paths??[]).map(se=>`\`${se}\``).join(", ")}`:"",(s.commands??[]).length>0?`**Commands:** ${(s.commands??[]).map(se=>`\`${se}\``).join(", ")}`:"",(s.tags??[]).length>0?`**Tags:** ${(s.tags??[]).map(se=>`#${se}`).join(" ")}`:"",he,K].filter(se=>se!=="").join(`
11
- `)}const d=[],i=n.scanStream({match:"cachly:lesson:best:*",count:jt});await new Promise((s,C)=>{i.on("data",r=>d.push(...r)),i.on("end",s),i.on("error",C)});const S=d.filter(s=>s.toLowerCase().includes(u.toLowerCase()));if(S.length===0){const s=`cachly:lessons:${u}`,C=await n.lrange(s,-3,-1);if(C.length>0){const c=C.map($=>W($,null)).filter(Boolean).map($=>`- ${$.outcome==="success"?"\u2705":"\u274C"} ${$.what_worked.slice(0,120)} (${new Date($.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${u}\` yet. Last attempts:
1
+ import{gitLesen as Ge,istCommitHash as vs,pruefeOrdner as dt}from"../git-ohne-shell.js";import{createRequire as Mt}from"node:module";import{calculateConfidence as Rt,confidenceBadge as Ss,STRUCTURED_TEMPLATES as Cs,CONFIDENCE_WARN_VALUE as xs}from"../confidence.js";import{kurzfassenHinweis as Ts}from"../antwort-hinweis.js";import{pruefeMeldung as Ns,wendeAn as Es}from"../pruefung-melden.js";import{ckgSlug as we,extractProblemConcept as ft,ckgUpsertNode as Ke,ckgUpdateEdge as ve,ckgUpsertPersonNode as As,ckgUpsertFileNode as Lt,ckgRecordCollaboration as Is,ckgUpsertServiceNode as Ms}from"../ckg.js";import{safeJsonParse as j,scanKeys as Re,leseOderNull as je,darfHeraus as Ve}from"../utils.js";import{ersparteMinuten as Bt,istStarterLektion as Rs,zaehltAlsErsparnis as Ot}from"../wertbeitrag.js";import{lessonPreviewLines as ot,trimTo as Ls}from"../lesson-preview.js";import{normalisiereZeit as pt,zaehleZeitangaben as gt}from"../zeit-normalisieren.js";import{abstentionSatz as Bs,alterssatzFuerBelegte as Os,beurteileTreffer as Ds,istBelegt as Dt}from"../abstention.js";import{meldeEinmal as mt,meldeUndVermerke as Qe,fehlerText as at,OHNE_VEKTOREN as zs,OHNE_DIENST as Ps,OHNE_FRAGEVEKTOR as js,SINNPFAD_ABBRUCH as Ws,OHNE_SCHREIBVEKTOR as rt}from"../aussetzer.js";import{versuchStart as Fs,neueKennung as Hs,wendeZuteilungAn as Gs,schliesseVersuchAb as Ks}from"../versuch.js";function wt(M,T,L,X=L){if(M.includes("lesson:best:")){const o=j(T,{});if(o&&typeof o=="object"&&(o.what_worked||o.what_failed||o.commands?.length))return ot(o,{maxChars:L,indent:" "})}const u=Ls(T,X);return u?[u]:[]}const zt=2e3,Pt=400;function jt(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as Vs,holeKantenVorrat as Js,SPEICHER_SCAN_SCHRITT as Wt}from"../kanten-vorrat.js";import{getRole as it,ROLE_BADGE as qs,getScopes as yt,lessonVisibleToScope as ct,reviewModeEnabled as Us,storeLessonProposal as Ys}from"./team.js";import{keywordSearch as lt,treffeUeberDateipfad as Zs,wortindexEntwerten as Ft,tokenize as _t,splitMultiQuery as Xs,levenshtein as Qs,indexVocab as Ht,bestandHolen as en}from"../search.js";import{startetNochLeer as Gt,leeresBrainAntwort as Kt,startLageMitCommits as bt,sofortAntwortNeuesBrain as tn,neuesBrainBriefing as sn}from"../leeres-brain.js";import{rerankByQuality as nn,qualityMultiplier as on,extractLessonQuality as an}from"../rerank.js";import{computeEmbedding as Te,hasEmbedProvider as ze,EMBED_PROVIDER as Se}from"../embeddings.js";import{leserAktiv as rn,leserPunkte as cn,mischeMitLeser as ln}from"../leser.js";import{repariereFelder as hn}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as $t,NAME_VEKTOR_PRAEFIX as ht,ZWEIT_VEKTOR_PRAEFIX as Je,packe as We,textFuerVektor as qe,textFuerNamensVektor as kt,Vektorbestand as vt,VEKTOR_NACHTRAG as un,NAME_VEKTOR_NACHTRAG as et,ZWEIT_VEKTOR_NACHTRAG as ut}from"../bedeutung.js";import{schreibeEingaenge as dn,Eingangsbestand as fn}from"../eingaenge.js";import{ordneNachHausordnung as pn,rangWerte as gn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as mn}from"../seltenheitsbestand.js";import{spurLegen as wn}from"../spuren.js";import{schlageErsetzungVor as yn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as Vt,stufeSucheNachProjektversion as _n,versionsNotizen as bn,versionsBanner as $n}from"../gueltigkeit-version.js";const Ue=un,kn=365;import{etikettenFuer as vn,lieferJournalSchluessel as Jt,JOURNAL_DECKEL as Sn}from"../etiketten.js";import{klassifiziereFehlschlag as Cn,suchProtokollSchluessel as St,trichterSchluessel as qt,SUCH_DECKEL as Ut}from"../recall-trichter.js";import{leiteEntscheidungAb as xn,entscheidungsZeile as Yt}from"../entscheidung-ableiten.js";import{bewerteTopf as Tn,spreizeImTopf as Zt,reichereAn as Nn,inhaltsWoerter as Xt,grobStamm as En,GEWICHTE as An,knapperSiegSatz as In}from"../rangfolge.js";import{fehlendeLernfelder as Mn,hatFrage as Rn,kappeAnfrage as Ln,ungueltigerAusgang as Bn}from"../pflichtfelder.js";import{pruefeWirkung as On,wirkungsEingabeAus as Dn,werteAus as zn,lehrwert as Pn,leiteAb as jn,belegeJeThema as Wn}from"../wirkungsspur.js";import{merkeSuchlauf as Ct}from"../suchstatistik.js";import{schreibeTopfNotiz as Fn,topfProtokollAktiv as Hn}from"../topf-protokoll.js";import{SINN_TOPF as Gn,EINGANG_SCHWELLE as Kn,EINGANG_SORTIER_GEWICHT as Vn,ZWEIT_MODELL as Ye,ZWEIT_GEWICHT as Jn,ZWEIT_MINDESTDECKUNG as Qt,NAHDUPLIKAT_SCHWELLE as qn,LESER_TIEFE as es}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as ts,quelleZeile as Un}from"../herkunft.js";import{doppelHinweis as ss,KEINE_NACHBARN as tt,leseDoppelKandidaten as Yn,mitFrist as Zn,nahHinweis as Xn,pruefeNachbarn as Qn}from"../doppel-kandidat.js";import{merkeRecall as eo,sitzungsKosten as to,vergissSitzungsKosten as so,kostenZeilen as no}from"../sitzungs-kosten.js";const ns=new WeakMap;function xt(M){let T=ns.get(M);return T||(T={vektor:new vt,namen:new vt(6e4,ht),zweit:new vt(6e4,Je),eingang:new fn,seltenheit:new mn},ns.set(M,T)),T}const os=Gn,oo=Kn,ao=Vn;import{upgradeNudge as ro}from"../upgrade-nudge.js";import{recallTiefe as as,verlangteTiefe as io,TIEFE_VOLL as co,TIEFE_VOLL_MEHRTHEMIG as lo}from"../recall-tiefe.js";import{nutzungInWorten as ho,nutzungsSchluessel as uo,verdichte as fo}from"../werkzeug-nutzung.js";import{inWorten as po,lieferBild as go,lieferSchluessel as mo,trefferSchluessel as wo}from"../geliefert.js";import{COAUTHOR_PREF_KEY as yo,autorHinweis as _o,coautorAus as bo,echterGitLeser as $o,ermittleAutor as ko,mitCoautor as vo,nurMensch as rs}from"../autor.js";import{TOOLS as So}from"../tools.js";import{vorspannHinweis as Co}from"../vorspann.js";import{autorAbzeichen as xo,fremdanteil as To}from"../autor-abzeichen.js";import{cachlyUrl as No}from"../cachly-url.js";import{belegFuer as Eo}from"../schreibbeleg.js";import{rueckfallHinweis as Ao,dazuHinweis as Io}from"../rueckfall.js";import{schwaerzeFelder as Mo}from"../geheimnis-filter.js";import{VERDACHT_TAG as Tt,mitVerdachtTag as Ro,pruefeFelder as Lo,verdachtsWarnung as Bo}from"../tuersteher.js";import{fuerEigenenSpeicher as Fe,hinweise as He,istMarkiert as is,markiert as Oo,markierungsWarnung as cs,markierungsWarnungAusRohwert as ls,zaehlHinweise as hs}from"../schreibtor.js";import{istBlossesThema as us}from"../blosses-thema.js";import{zeitpunkt as be}from"../zeitmessung.js";import{wartetAufFrischenBestand as Do}from"../bestand-frische.js";const st=(()=>{try{const M=Mt(import.meta.url);for(const T of["../../../package.json","../../package.json"])try{const L=M(T);if(L.name==="@cachly-dev/mcp-server"&&L.version)return L.version}catch{}}catch{}return"0.10.100"})(),zo=()=>{try{return Mt(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Po={"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${st}:**`," \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"]},Xa=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"]),jo=No("/billing","upgrade"),ds=new Map,fs=new Set,Wo=1680*60*60;function Fo(M=new Date){return`cachly:quota:recalls:${M.toISOString().slice(0,7)}`}async function Nt(M){try{const T=Fo();await M.incr(T)===1&&await M.expire(T,Wo)}catch{}}function ps(M){return`cachly:stats:drei-ausgaenge:${M}`}async function Et(M,T,L){try{await M.hincrby(ps(T),L,1)}catch{}}function gs(M,T,L,X){Nt(M),Ct(M,L,X);const u={ts:new Date().toISOString(),frage:L.slice(0,200),geliefert:[]};(async()=>{const o=St(T);await M.lpush(o,JSON.stringify(u)),await M.ltrim(o,0,Ut-1)})().catch(()=>{}),Et(M,T,"schweigen")}async function ms(M){const T={tage:0,rekord:0};try{const L=await M.get("cachly:streak:current"),X=j(L,null),u=new Date().toISOString().slice(0,10);if(X){const o=X.last_date,d=new Date(Date.now()-864e5).toISOString().slice(0,10);o===u?(T.tage=X.days,T.rekord=X.record):o===d?(T.tage=X.days+1,T.rekord=Math.max(T.tage,X.record),await M.set("cachly:streak:current",JSON.stringify({days:T.tage,last_date:u,record:T.rekord}))):(T.tage=1,T.rekord=X.record,await M.set("cachly:streak:current",JSON.stringify({days:1,last_date:u,record:T.rekord})))}else T.tage=1,T.rekord=1,await M.set("cachly:streak:current",JSON.stringify({days:1,last_date:u,record:1}))}catch{}return T}async function ws(M,T,L){await M.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:T,provider:L}),"EX",86400)}const At=new Map;async function ys(M,T){const L=ds.get(M);if(L&&L.expiresAt>Date.now())return L.gate;let X=At.get(M);return X||(X=Ho(M,T).finally(()=>{At.delete(M)}),At.set(M,X)),L&&!Do()?L.gate:X}async function Ho(M,T){try{const L=await T(`/api/v1/instances/${M}/memory`),X=L?.recall_limit??-1,u=L?.total_recall_count??0,o={reached:X>0&&u>=X,limit:X,used:u,goodwillMessage:L?.goodwill_message,notice:L?.notice};return ds.set(M,{gate:o,expiresAt:Date.now()+6e4}),o}catch{return{reached:!1,limit:-1,used:0}}}const Go={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function Qa(M,T,L,X){const u=await Ko(M,T,L,X),o=Go[M];if(o&&typeof u=="string")try{eo(String(T.instance_id??""),String(T[o]??""),u.length)}catch{}return u}async function Ko(M,T,L,X){switch(M){case"learn_from_attempts":{{const k=Mn(T);if(k.length)return`\u26A0\uFE0F learn_from_attempts needs ${k.join(" and ")}. Nothing was stored.`;const z=Bn(T);if(z)return z}const u=Mo(T),o=Lo(u.felder),d=o.length?{...u.felder,tags:Ro(u.felder.tags)}:u.felder,{instance_id:p,topic:a,outcome:n,what_worked:v,what_failed:f="",context:i="",severity:S="major",file_paths:t=[],commands:s=[],tags:C=[],depends_on:r=[],author:c="",visibility:b="team",service:m="",service_kind:w="service",group:I="",grund:A="",ersetzt:e="",gilt_ab:Z="",gilt_fuer:le}=d,{what_worked:re,what_failed:ue="",context:ne=""}=hn({what_worked:v,what_failed:f,context:i}),g=await L(p),V=new Date,Q=V.toISOString();let Y=Vt(le,void 0);const ee=Z&&!Number.isNaN(Date.parse(String(Z)))?new Date(String(Z)):V,J=pt(re,ee),te=pt(ue,ee),l=pt(ne,ee),$=gt(re,ee)+gt(ue,ee)+gt(ne,ee),N=ko({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:$o(process.env.CACHLY_WORKSPACE??process.cwd())});let E="";try{E=bo(await g.get(`cachly:prefs:${yo}:${p}`))}catch{}const _=vo(N.autor,E),x=_o(N);if(b!=="private"&&await Us(g,p))return Ys(g,a,{topic:a,outcome:n,what_worked:J,what_failed:te,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:r,...Y.angaben.length?{gilt_fuer:Y.angaben}:{},..._?{author:_}:{},source:ts(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:b,recall_count:0,ts:Q,confidence:1,version:3});const H=a.split(":")[0],W=Cs[H],q=[];if(W)for(const k of W.required)k==="commands"&&s.length===0&&q.push(`\u{1F4CB} ${W.hint}`);let D=!1,he=0,me,de=[];const se=await g.get(`cachly:lesson:best:${a}`),ye=String(A||d.reason||"").trim();if(se&&!ye)return[`\u270B **Update rejected:** \`${a}\` already exists \u2014 an update needs the field \`grund\` (the reason; \`reason\` works too).`,"","One line is enough: WHY was the previous version wrong or incomplete?",'Example: grund="The deploy target moved from port 3000 to 8080"',"","The diff says WHAT changes. The grund line says why the old version was wrong \u2014","and that is the line someone reads two months from now (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
+ `);const Le=[];if(se)try{const k=JSON.parse(se);if(Y=Vt(le,k.gilt_fuer),he=k.recall_count??0,me=k.last_recalled_at,de=k.audit_trail??[],de.push({ts:Q,action:"updated",prev_outcome:k.outcome,grund:ye}),de.length>20&&(de=de.slice(-20)),D=!0,k.outcome==="success"&&n==="failure"?Le.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."):k.outcome==="failure"&&n==="success"&&Le.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),Le.length>0){de[de.length-1].action="contradiction-resolved";try{const z=we(a),F=we(`resolution:${a}`);await ve(g,z,"contradicts",F,!1)}catch{}try{const z=`cachly:contradictions:${a}`,F=k.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await g.rpush(z,JSON.stringify({ts:Q,prev_outcome:k.outcome,new_outcome:n,direction:F})),await g.ltrim(z,-50,-1),await g.expire(z,180*86400)}catch{}Le.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${a}")\` to resolve via expert agent voting.`)}}catch{}else de=[{ts:Q,action:"created"}];const Oe=[];if(n==="failure"){const k=[],z=g.scanStream({match:"cachly:lesson:best:*",count:Wt});await new Promise((P,R)=>{z.on("data",G=>k.push(...G)),z.on("end",P),z.on("error",R)});const F=a.split(/[:\-_]/).filter(P=>P.length>2);for(const P of k.slice(0,50)){const R=await g.get(P);if(R)try{const G=JSON.parse(R);if(G.outcome!=="success")continue;const ie=(G.topic??"").split(/[:\-_]/).filter(Me=>Me.length>2);if(F.filter(Me=>ie.includes(Me)).length>=1&&G.topic!==a){Oe.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${G.topic}\` (success, ${G.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${G.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${G.topic}", ..., severity="critical")\``);break}}catch{}}}for(const k of r){const z=`cachly:dep:${k}`,F=await g.get(z),P=j(F,[]);P.includes(a)||P.push(a),await g.set(z,JSON.stringify(P),"EX",90*86400)}const De={topic:a,outcome:n,what_worked:J,what_failed:te,context:l,severity:S,file_paths:t,commands:s,tags:C,depends_on:r,..._?{author:_}:{},source:ts(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:b,recall_count:he,...me?{last_recalled_at:me}:{},...Z&&!Number.isNaN(Date.parse(String(Z)))?{gilt_ab:new Date(String(Z)).toISOString()}:{},...Y.angaben.length?{gilt_fuer:Y.angaben}:{},ts:Q,verified_at:n==="success"||n==="partial"?Q:void 0,confidence:1,audit_trail:de,version:3},_e=String(e??"").trim();let Ce="",Be=null;_e===a&&_e?Ce="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":_e&&(Be=await g.get(`cachly:lesson:best:${_e}`),Be?j(Be,{}).ersetzt===a?(Be=null,Ce=`\u26A0\uFE0F \`${_e}\` already replaces \`${a}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${_e}\` first, then set it here.`):De.ersetzt=_e:Ce=`\u26A0\uFE0F The lesson to replace, \`${_e}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Ae="";if(!_e)try{const k=G=>{const ie=j(G.content,{});return{topic:ie.topic??G.key.slice(19),what_worked:ie.what_worked}},[z,F]=await Promise.all([lt(g,["cachly:lesson:best:*"],`${a} ${J}`.slice(0,300),5),Zs(g,["cachly:lesson:best:*"],t??[])]),P=new Set,R=[...z,...F].filter(G=>G.key.startsWith("cachly:lesson:best:")).filter(G=>!P.has(G.key)&&P.add(G.key)).map(k);Ae=yn(a,J,R)??""}catch{}if(n==="failure")try{const z=(await g.lrange(St(p),0,199)).map(R=>j(R,{ts:"",frage:"",geliefert:[]})).filter(R=>R.ts!==""),F=(await lt(g,["cachly:lesson:best:*"],`${a} ${te||J}`.slice(0,300),5)).filter(R=>R.key.startsWith("cachly:lesson:best:")).map(R=>{const G=j(R.content,{});return{topic:G.topic??R.key.slice(19),what_worked:G.what_worked}}),P=Cn(a,String(te||""),z,F);await g.hincrby(qt(p),P,1)}catch{}const oe=xn([J,te,i].filter(Boolean).join(" ").slice(0,2e3));oe&&(De.entscheidung=oe);const Pe=Eo(a,Q,J);De.beleg=Pe;const Ne=JSON.stringify(De);g.set(`cachly:stats:born_at:${p}`,Q,"EX",365*86400,"NX").catch(()=>{});const Ie=`cachly:lessons:${a}`;await g.rpush(Ie,Ne),await g.ltrim(Ie,-100,-1),await g.expire(Ie,kn*86400);let Ee=!1;if(n==="success"||n==="partial"?(await g.set(`cachly:lesson:best:${a}`,Ne),Ee=!0):se||(await g.set(`cachly:lesson:best:${a}`,Ne),Ee=!0),Be&&Ee)try{const k=JSON.parse(Be);k.ersetzt_durch=a,k.gilt_bis=Q,k.ersetzt_am=Q,ye&&(k.ersetzt_grund=ye.slice(0,200)),await g.set(`cachly:lesson:best:${_e}`,JSON.stringify(k))}catch{}Ee&&Ft();let h=()=>{};const y=new Promise(k=>{h=k});if(Ee&&ze()||h(tt),Ee&&ze()){await g.sadd(Ue,a).catch(()=>{}),await g.sadd(et,a).catch(()=>{}),(Se==="cachly"||Se==="ollama")&&await g.sadd(ut,a).catch(()=>{});const k=It(g);k.add(a),(async()=>{const z=j(Ne,{});let F=Promise.resolve();try{const R=await Te(qe(z),{geduld:"lang"});R?.length?(await g.set(`${$t}${a}`,We(R)),await g.srem(Ue,a).catch(()=>{}),h(await Qn(g,{...z,topic:a},R,xt(g).vektor))):h(tt),(Se==="cachly"||Se==="ollama")&&(F=(async()=>{try{const G=await Te(qe(z),{geduld:"lang",modell:Ye});G?.length&&(await g.set(`${Je}${a}`,We(G)),await g.srem(ut,a).catch(()=>{}))}catch(G){await Qe(g,rt,`Zweit-Vektor nicht geschrieben (${Se}, ${Ye}): ${at(G)} \u2014 die Lektion ist gespeichert, der Nachtrag holt ihn spaeter.`)}})())}catch(R){h(tt),await g.sadd(Ue,a).catch(()=>{}),await Qe(g,rt,`Volltext-Vektor nicht geschrieben (${Se}): ${at(R)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}const P=kt(a);try{if(!P)await g.srem(et,a).catch(()=>{});else{const R=await Te(P,{geduld:"lang"});R?.length&&(await g.set(`${ht}${a}`,We(R)),await g.srem(et,a).catch(()=>{}))}}catch(R){await Qe(g,rt,`Namens-Vektor nicht geschrieben (${Se}): ${at(R)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await dn(g,a,z,R=>Te(R,{geduld:"lang"}))}catch(R){await Qe(g,rt,`Eingaenge nicht geschrieben (${Se}): ${at(R)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await F,await _s(g,a,3),h(tt)})().finally(()=>k.delete(a))}try{const k="cachly:session:decision-log",z=JSON.stringify({ts:Q,topic:a,outcome:n,what_worked:J.slice(0,120)});await g.rpush(k,z),await g.ltrim(k,-50,-1)}catch{}let B=null;try{const k=we(a),z=a.split(":")[0]??"unknown";await Ke(g,k,z,z);for(const P of C){const R=we(`tag:${P}`);await Ke(g,R,"tag","tag"),await ve(g,k,"co-occurs",R,n==="success",n==="partial")}for(const P of r){const R=we(P);await ve(g,k,"requires",R,!0)}if((z==="fix"||z==="debug")&&(n==="success"||n==="partial")){const P=te||l||"",R=P?ft(P):null;if(R){const G=we(`problem:${R}`);await Ke(g,G,"problem","problem"),await ve(g,k,"fixes",G,n==="success",n==="partial")}}if(n==="failure"&&(te||J)){const R=ft(te||J);if(R){const G=we(`cause:${R}`);await Ke(g,G,"cause","cause"),await ve(g,k,"causes",G,!1)}}if(n==="failure"){const P=await g.smembers(`cachly:ckg:idx:from:${k}`);for(const R of P){const G=await g.get(R);if(!G)continue;const ie=j(G,null);if(ie&&ie.edgeType==="fixes"&&ie.confidence>.7&&ie.trials>=3){B=`\u26A0\uFE0F **belief_conflict** on \`${a}\`: previously confirmed fix (confidence ${ie.confidence.toFixed(2)}, n=${ie.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${a}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${k}")\` to review.`;const ge=`cachly:ckg:conflict:${k}`;await g.set(ge,JSON.stringify({topic:a,concept_id:k,detected_at:new Date().toISOString(),fix_confidence:ie.confidence,fix_trials:ie.trials,failure_outcome:n,reported_by:_||"unknown",what_failed:te||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(z==="fix"||z==="debug")){const P=await g.smembers(`cachly:ckg:idx:from:${k}`);for(const R of P.slice(0,10)){const G=await g.get(R);if(!G)continue;const ie=j(G,null);if(!ie||ie.edgeType!=="fixes")continue;const ge=await g.smembers(`cachly:ckg:idx:from:${ie.to}`);for(const Me of ge.slice(0,5)){const Ze=await g.get(Me);if(!Ze)continue;const $e=j(Ze,null);$e&&$e.edgeType==="co-occurs"&&($e.successes=($e.successes||0)+.1,$e.trials=($e.trials||0)+.1,$e.confidence=($e.successes+1)/($e.trials+2),$e.last_updated=new Date().toISOString(),await g.set(Me,JSON.stringify($e)))}}}if(Math.random()<.01){const P=Date.now()-7776e6,R=await g.smembers(`cachly:ckg:idx:from:${k}`);for(const G of R){const ie=await g.get(G);if(!ie)continue;const ge=j(ie,null);ge&&ge.trials<3&&ge.last_updated&&new Date(ge.last_updated).getTime()<P&&(ge.confidence=ge.confidence*.9,ge.last_updated=new Date().toISOString(),await g.set(G,JSON.stringify(ge)))}}}catch{}if(_){g.set(`cachly:agents:active:${_}`,JSON.stringify({author:_,last_topic:a,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const k=a.split(":")[0]??"unknown",z=await As(g,rs(_),k),F=we(a);await ve(g,z,"authored",F,n==="success",n==="partial");for(const P of t.slice(0,8)){const R=await Lt(g,P);await ve(g,z,"touched",R,!0),await Is(g,R,z)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const k=a.split(":")[0]??"unknown",z=w==="system"?"system":"service",F=await Ms(g,m.trim(),k,z),P=we(a);if(await ve(g,P,"affects",F,n==="success",n==="partial"),_){const R=`person:${we(rs(_))}`;await ve(g,R,"operates",F,!0)}for(const R of t.slice(0,8)){const G=`file:${we(R)}`;await ve(g,G,"runs_in",F,!0)}}catch{}if(_&&(n==="success"||n==="partial")){const k={topic:a,outcome:n,what_worked:J,what_failed:te??"",severity:S,author:_,file_paths:t,commands:s,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},z=`cachly:lessons:${a}`;g.rpush(z,JSON.stringify(k)).catch(()=>{})}const ae=n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C",O=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",U=D?"updated":"stored",ce=await Zn(y)??tt,fe=ce.doppel;return[`${ae} **Lesson ${U}:** \`${a}\` (${n}) ${O} ${S} \xB7 receipt: \`${Pe}\``,u.funde.length?`\u{1F512} **${u.funde.length} secret(s) redacted** before saving (${u.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",Bo(o),B??"","",`**What worked:** ${J}`,te?`**What failed:** ${te}`:"",l?`**Context:** ${l}`:"",t.length>0?`**Files:** ${t.map(k=>`\`${k}\``).join(", ")}`:"",s.length>0?`**Commands:** ${s.map(k=>`\`${k}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(k=>`#${k}`).join(" ")}`:"","",D?`\u267B\uFE0F Updated (recall count: ${he} \xB7 audit entries: ${de.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${a}")\``,_&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${_}_${N.quelle!=="uebergeben"?` \xB7 from ${N.quelle}`:""}) \u2014 visible in \`team_recall\``:"",x??"",r.length>0?`\u{1F517} Depends on: ${r.map(k=>`\`${k}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Ae,ss(fe,Ae),_e?"":Xn(ce.nahe,Ae+ss(fe,Ae)),Y.angaben.length?`\u{1F4E6} Applies to ${Y.angaben.map(k=>`\`${k}\``).join(", ")}${Y.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...Y.fehler.map(k=>`\u26A0\uFE0F gilt_fuer not stored, ${k}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),Be&&Ee?ye?`\u21B7 Replaces \`${_e}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${_e}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:Ce,...q,...Le,...Oe,$>0?`\u{1F5D3}\uFE0F ${$} relative time reference${$===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(V.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",Co(J)??"",Ao({outcome:n,topic:a,what_worked:J,what_failed:te,file_paths:t}),Io({outcome:n,topic:a,what_worked:J,what_failed:te,file_paths:t})].filter(k=>k!=="").join(`
3
+ `)}case"lesson_verified":{const{instance_id:u}=T,o=await L(u),d=new Date().toISOString(),p=T,a=Fe({geprueft_mit:p.geprueft_mit,befund:p.befund}),n=Ns({...p,...a.felder},d);if(!n.ok)return[`\u26A0\uFE0F ${n.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 v=n.eintrag,f=`cachly:lesson:best:${v.topic}`,i=await o.get(f);if(!i)return`\u{1F4ED} Keine Lektion \`${v.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const S=j(i,{}),t=Es(S,v);return await o.set(f,JSON.stringify(a.verdacht.length?{...t,tags:Oo(t.tags,a.verdacht)}:t)),Ft(),!v.haelt&&v.ursache==="umgebung"?[`\u2139\uFE0F \`${v.topic}\`: Pruefung an der Umgebung gescheitert \u2014 die Lektion bleibt, wie sie war.`,` Befund: ${v.befund}`,"","Nicht als fraglich markiert, `verified_at` unveraendert. Das sagt etwas ueber","den Tag, nicht ueber die Lektion. Pruefe noch einmal, wenn die Umgebung wieder steht.",...He(a)].join(`
5
+ `):v.haelt?[`\u2705 \`${v.topic}\` ist wieder frisch \u2014 geprueft am ${d.slice(0,10)}.`,v.geprueft_mit?` geprueft mit: \`${v.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...He(a)].filter(Boolean).join(`
6
+ `):[`\u26A0\uFE0F \`${v.topic}\` ist als fraglich markiert.`,` Befund: ${v.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="${v.topic}", \u2026, grund="\u2026")\`.`,...He(a)].join(`
7
+ `)}case"recall_feedback":{const{instance_id:u}=T,o=await L(u),d=On(Dn(T),new Date().toISOString());if(!d.ok)return[`\u26A0\uFE0F ${d.grund}`,"","Example:","```",'recall_feedback(instance_id="\u2026", query="why does the deploy abort",',' topic="ci:timeout-reports-cancelled", helped=true, rank=0)',"```","rank=0 means: the lesson was NOT in the answer at all.","That is the most valuable feedback there is."].join(`
8
+ `);const p=d.eintrag,a=`cachly:wirkung:${u}`;await o.rpush(a,JSON.stringify(p));const v=(await o.lrange(a,0,-1).catch(()=>[])).map(s=>j(s,null)).filter(Boolean),f=zn(v),i=Pn(p),S={"fehlender-treffer":"It helped but was not in the answer at all \u2014 the search never picked it up. That is the most valuable case.","zu-weit-hinten":`It helped but was only at rank ${p.platz} \u2014 the ranking was too weak.`,"falsch-und-sicher":`It was at rank ${p.platz} and did not help \u2014 the ranking was confident and wrong.`,bestaetigung:"It was near the top and helped. Confirmed.",unauffaellig:"It did not help and was far down. Says little."},t=f.trefferquote===null?"no helpful feedback yet":`${(f.trefferquote*100).toFixed(0)} % of the helpful lessons were in the top three`;return[`\u2705 Noted: **${p.thema}** \u2014 ${p.geholfen?"helped":"did not help"}, rank ${p.platz===0?"\u2014 (not in the answer)":p.platz}`,"",S[i],"",`Feedback so far: ${f.gesamt}, ${t}.`,`Of these: ${f.nachLehrwert["fehlender-treffer"]} not found \xB7 ${f.nachLehrwert["zu-weit-hinten"]} too far down \xB7 ${f.nachLehrwert["falsch-und-sicher"]} confident and wrong.`].join(`
9
+ `)}case"recall_best_solution":{const u=Date.now(),{instance_id:o,topic:d,author:p}=T,a=await tn(o,X,`\u{1F4ED} No lessons found for \`${d}\`.`);if(a)return a;const n=await L(o);try{const s=await n.get(`cachly:letzter-recall:${o}`),C=s?j(s,null):null,r=jn(C,d,new Date().toISOString());r&&(await n.rpush(`cachly:wirkung:${o}`,JSON.stringify(r)),await n.del(`cachly:letzter-recall:${o}`))}catch{}const v=await n.get(`cachly:lesson:best:${d}`);if(v){const s=j(v,null);if(!s)return`\u26A0\uFE0F Lesson data for \`${d}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const C=s.group;if(C){const se=p?await yt(n,o,p).catch(()=>new Set):new Set,ye=p?await it(n,o,p).catch(()=>null)==="admin":!1;if(!ct(C,se,ye))return`\u{1F4ED} No lessons found for \`${d}\`. Use \`learn_from_attempts\` after solving it.`}const r=Rt(s),c=s.verified_at??s.ts,b=(Date.now()-new Date(c).getTime())/864e5,m=s.commands,w=Ss(r,b,Array.isArray(m)&&typeof m[0]=="string"?m[0]:void 0,s.pruefung_gefallen_am?{am:s.pruefung_gefallen_am,befund:s.pruefung_befund}:void 0,s.pruefung_umgebung_am?{am:s.pruefung_umgebung_am,befund:s.pruefung_umgebung_befund}:void 0),I=new Date().toISOString(),A={...s,recall_count:(s.recall_count??0)+1,last_recalled_at:I};await n.set(`cachly:lesson:best:${d}`,JSON.stringify(A)),Nt(n),Ct(n,String(d??""),Date.now()-u);const e=Ot(s)?Bt(s):0;e>0&&n.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,e).catch(()=>{});const Z=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":s.severity?"\u{1F7E2}":"",le=s.audit_trail??[],re=le.filter(se=>se&&typeof se.grund=="string"&&se.grund.trim().length>0).slice(-3).map(se=>` \xB7 ${se.ts?new Date(se.ts).toLocaleDateString("de-DE"):"?"}: ${se.grund.trim()}`),ue=le.length>1?[`_Audit: ${le.length} changes \xB7 stored ${new Date(s.ts).toLocaleDateString("de-DE")}_`,...re.length>0?["**Warum zuletzt geaendert:**",...re]:[]].join(`
10
+ `):"",ne=(Date.now()-new Date(s.ts).getTime())/864e5,g=ne>60?`\u{1F4AD} _Remember when you solved this ${Math.round(ne/30)} months ago? Still works._`:"",V=A.recall_count===3&&!s.pinned?"\u{1F4CC} **This lesson came up in 3 answers so far.** If you need it often, pin it: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",Q=s.authors??(s.author?[s.author]:[]),Y=[...new Set(Q.filter(Boolean))];let ee="";Y.length>=2&&(ee=`\u2705 **Team-verified** \u2014 confirmed by ${Y.length} developers.`);const J=s.ersetzt_durch,te=s.ersetzt_am?` (on ${s.ersetzt_am.slice(0,10)})`:"",l=J?await n.get(`cachly:lesson:best:${J}`):null,$=String(s.ersetzt_grund??"").trim(),N=$?` Reason: ${$}`:" No reason recorded.",E=l?je(l):null,_=l?!Ve(E):!1;let x=!1;if(l&&!_&&E?.group){const se=p?await yt(n,o,p).catch(()=>new Set):new Set,ye=p?await it(n,o,p).catch(()=>null)==="admin":!1;x=!ct(E.group,se,ye)}const H=J?l?_?`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the successor lesson is private, not visible to the team. The text below stays readable as history; its author knows the current version.`:x?`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the successor lesson is not visible to you. The text below stays readable as history.`:`\u{1F6AB} **THIS VERSION IS REPLACED**${te} \u2014 the current answer is in \`recall_best_solution(topic="${J}")\`.${N} The text below stays readable as history.`:`\u26A0\uFE0F **REPLACEMENT POINTS NOWHERE**${te} \u2014 the successor \`${J}\` has been deleted. This version applies again as the best EXISTING answer; confirm it when you can (learn_from_attempts with grund).`:"",W=s.gilt_ab,q=s.gilt_bis,D=W?`\u{1F4C5} Valid since ${String(W).slice(0,10)}.`:"",he=s.entscheidung,me=he?.gegen?Yt({gegen:he.gegen,grund:he.grund??null}):"",de=q&&Date.parse(String(q))<Date.now()?`\u23F3 **THIS FACT WAS VALID UNTIL ${String(q).slice(0,10)}** \u2014 it is history, not current information.`:"";return[cs(s),H,de,$n(s.gilt_fuer),D,me,g,ee,`${w} **Best solution for \`${d}\`** ${Z}${s.severity?` (${s.severity})`:""} \xB7 in ${A.recall_count} answer${A.recall_count===1?"":"s"} so far`,Un(s.author,s.source),"",s.what_worked?`**What worked:** ${s.what_worked}`:"",s.what_failed?`**What failed (avoid this):** ${s.what_failed}`:"",s.context?`**Context:** ${s.context}`:"",(s.file_paths??[]).length>0?`**Files:** ${(s.file_paths??[]).map(se=>`\`${se}\``).join(", ")}`:"",(s.commands??[]).length>0?`**Commands:** ${(s.commands??[]).map(se=>`\`${se}\``).join(", ")}`:"",(s.tags??[]).length>0?`**Tags:** ${(s.tags??[]).map(se=>`#${se}`).join(" ")}`:"",ue,V].filter(se=>se!=="").join(`
11
+ `)}const f=[],i=n.scanStream({match:"cachly:lesson:best:*",count:Wt});await new Promise((s,C)=>{i.on("data",r=>f.push(...r)),i.on("end",s),i.on("error",C)});const S=f.filter(s=>s.toLowerCase().includes(d.toLowerCase()));if(S.length===0){const s=`cachly:lessons:${d}`,C=await n.lrange(s,-3,-1);if(C.length>0){const c=C.map(b=>j(b,null)).filter(Boolean).map(b=>`- ${b.outcome==="success"?"\u2705":"\u274C"} ${b.what_worked.slice(0,120)} (${new Date(b.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${d}\` yet. Last attempts:
12
12
 
13
13
  ${c.join(`
14
- `)}`}return`\u{1F4ED} No lessons found for \`${u}\`. Use \`learn_from_attempts\` after solving it.`}const t=[];for(const s of S.slice(0,5)){const C=await n.get(s);if(!C)continue;const r=W(C,null);if(!r)continue;const c=rs(r);t.push(`${c?`${c}
15
- `:""}**\`${r.topic}\`** \u2014 ${r.what_worked.slice(0,400)}${r.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${u}\`:**
14
+ `)}`}return`\u{1F4ED} No lessons found for \`${d}\`. Use \`learn_from_attempts\` after solving it.`}const t=[];for(const s of S.slice(0,5)){const C=await n.get(s);if(!C)continue;const r=j(C,null);if(!r)continue;const c=cs(r);t.push(`${c?`${c}
15
+ `:""}**\`${r.topic}\`** \u2014 ${r.what_worked.slice(0,400)}${r.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${d}\`:**
16
16
 
17
17
  ${t.join(`
18
18
 
19
- `)}`}case"smart_recall":{const h=Date.now(),{instance_id:o,query:u,threshold:p=.78,author:a="",context_files:n=[],limit:v}=N,d=Mn(u),i=ao(v),S=Array.isArray(n)?n.filter(f=>typeof f=="string"):[];if(ye("smart_recall: Anfang"),!In(d))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await Ht(o,X)){const f=Date.now()-h;return L(o).then(y=>fs(y,o,String(d??""),f)).catch(()=>{}),ye("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),Gt(String(d??""),{startet:!0,...await yt(o)})}const t=await L(o);ye("smart_recall: Verbindung steht");const{vektor:s,namen:C,zweit:r,eingang:c,seltenheit:$}=St(t);Be()&&Promise.allSettled([s.aktualisiere(t),C.aktualisiere(t),c.aktualisiere(t),$.aktualisiere(t),r.aktualisiere(t)]),ws(t,void 0,2);let m=new Set,w=!1;a&&(m=await mt(t,o,a).catch(()=>new Set),w=await at(t,o,a).catch(()=>null)==="admin");const M=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],I=await Xs(t,M);if(ye(`smart_recall: Wortbestand da (${I?.docs.length??0} Eintraege)`),!I)return fs(t,o,String(d??""),Date.now()-h),ye("smart_recall: Brain leer \u2014 sofort geantwortet"),Gt(String(d??""),{startet:!1,...await yt(o)});const e=I.docs.reduce((f,y)=>f+(y.key.startsWith("cachly:lesson:best:")?1:0),0),Z=Ks(t,wt(d).filter(f=>f.length>=4).slice(0,4)).catch(()=>null),ce=(async()=>{const f=await Gs(o,()=>X(`/api/v1/instances/${o}`)),y=[];if(!(!f?.tier||f.tier.toLowerCase()==="free")&&f?.vector_token&&Be())try{const ae=await Te(d),O=`https://api.cachly.dev/v1/sem/${f.vector_token}`,q=await fetch(`${O}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:ae,namespace:"cachly:ctx",threshold:p,top_k:5}),signal:AbortSignal.timeout(8e3)});if(q.ok){const j=(await q.json()).filter(P=>P.found&&P.id).map(P=>{const T=P.id.replace("ctx:","").split(":");return{hit:P,redisKey:`cachly:ctx:${T[0]}:${T.slice(1).join(":")}`}}),U=await Promise.all(j.map(P=>t.get(P.redisKey).catch(()=>null)));j.forEach((P,T)=>{y.push({key:P.redisKey,similarity:P.hit.similarity??0,content:U[T]??"(evicted)"})})}}catch{}return{inst:f,semHits:y}})().catch(()=>({inst:null,semHits:[]})),ie=await it(t,M,d,25);ye(`smart_recall: Wortsuche fertig (${ie.length} Treffer)`);const he=tn(ie);let ne=!1,g=null;const K=await(async()=>{if(!Be())return pt(Ds,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),he;try{if(await s.aktualisiere(t),ye(`smart_recall: Vektorbestand geladen (${s.groesse})`),s.groesse===0)return e>0&&pt(Os,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),he;const f=await Te(d);if(ye("smart_recall: Frage eingebettet"),!f?.length)return pt(zs,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),he;await C.aktualisiere(t),await c.aktualisiere(t),await $.aktualisiere(t),await r.aktualisiere(t),ye(`smart_recall: Bestaende geladen (Namen ${C.groesse}, Eingaenge ${c.groesse}, Seltenheit ${$.groesse}, Zweit ${r.groesse})`);const y=s.groesse>0?r.groesse/s.groesse:0;y<Xt&&s.groesse>0&&Go(t,3);const B=y>=Xt?Te(d,{modell:qe}).catch(()=>null):null,ae=he.filter(G=>G.key.startsWith("cachly:lesson:best:")).map(G=>G.key.slice(19)),O=G=>Math.max(s.naehe(f,G),C.naehe(f,G)),q=[...$.themen()],b=(q.length>0?q:s.aehnlichste(f,500).map(G=>G.topic)).map(G=>({t:G,n:O(G)})).sort((G,fe)=>fe.n-G.n||(G.t<fe.t?-1:G.t>fe.t?1:0)).slice(0,ss).map(G=>G.t),j=[...new Set([...ae,...b])],U=b.slice(0,3).map(G=>s.rohvektor(G)).filter(Boolean),P=U.length?xn(f,U):f,T=Zt(d),D=$.statistik,re=j.map(G=>{const fe=new Set([...Zt($.textVon(G))].map(Tn));return{naeheText:s.naehe(f,G),naeheThema:C.naehe(f,G),naeheRueckkopplung:s.naehe(P,G),seltenheitsDeckung:D?D.deckung(T,fe):0,besterZeuge:D?D.besterZeuge(T,fe):0}});let de=Cn(re,Nn);{const G=[...de].sort((fe,$e)=>$e-fe);g=G.length>1?G[0]-G[1]:null}if(c.groesse>0){const G=j.map($e=>{const xe=c.besteNaehe(f,$e);return xe>=so?xe:-2}),fe=Yt(G);de=de.map(($e,xe)=>$e+no*fe[xe])}if(B){const G=await B;if(G?.length){const fe=Yt(j.map($e=>r.naehe(G,$e)));de=de.map(($e,xe)=>$e+Kn*fe[xe])}}let pe=j.map((G,fe)=>({t:G,p:de[fe]})).sort((G,fe)=>fe.p-G.p).map(G=>G.t);if(on(o)&&pe.length>1){const G=pe.slice(0,Qt),fe=pe.slice(Qt),$e=new Map(j.map((tt,Ye)=>[tt,de[Ye]]));ye("smart_recall: Leser Anfang");const xe=await an(d,G.map(tt=>$.leserTextVon(tt)),{instanceId:o});ye(`smart_recall: Leser ${xe?"fertig":"ohne Ergebnis"}`),xe&&(pe=[...rn(G.map(Ye=>$e.get(Ye)??0),xe).map(Ye=>G[Ye]),...fe])}const Ne=new Map(he.map(G=>[G.key,G])),ke=pe.map(G=>`cachly:lesson:best:${G}`).filter(G=>!Ne.has(G)),At=new Map;if(ke.length>0){const G=await t.mget(...ke).catch(()=>[]);ke.forEach((fe,$e)=>At.set(fe,G[$e]??null))}const et=[];for(const G of pe){const fe=`cachly:lesson:best:${G}`,$e=Ne.get(fe);if($e){et.push($e),Ne.delete(fe);continue}const xe=At.get(fe)??null;xe&&et.push({key:fe,content:xe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return et.push(...Ne.values()),Wn&&jn({frage:d.slice(0,200),themen:j,ausWortsuche:ae.length,ausSinnsuche:b.length,obergrenze:ss,gezeigt:pe.slice(0,10)}),ne=!0,et}catch(f){return await Ze(t,Ps,`der Bedeutungspfad brach ab (${f instanceof Error?f.message:String(f)}) \u2014 diese Suche lief nur ueber Woerter`),he}})();ye("smart_recall: Bedeutungspfad fertig"),xt(t),vt(t,String(d??""),Date.now()-h);{const f=K.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 B=Vt(o);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,kn-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:d.slice(0,200),geliefert:f};(async()=>{const B=kt(o);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,qt-1)})().catch(()=>{})}}if(Be()&&!Pt()){const f=K.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));gn(t,d,f,Te).catch(()=>{})}const Q=K.filter(f=>f.key.startsWith("cachly:lesson:best:"));let Y=0,ee=0;for(const f of Q.slice(0,5)){const y=await t.get(f.key).catch(()=>null);if(y){const B=W(y,null);if(B?.state==="archived")continue;if(B){const ae=new Date().toISOString(),O={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:ae};Pt()||t.set(f.key,JSON.stringify(O)).catch(()=>{});const q=Bt(B)?Lt(B):0;if(q>0&&t.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,q).catch(()=>{}),B.author&&a&&B.author!==a){Y++,t.sadd(`cachly:stats:reuse_pairs:${o}`,`${a}<-${B.author}`).catch(()=>{});const b=`person:${me(a)}`,j=`person:${me(B.author)}`;ve(t,b,"collaborates",j,!0).catch(()=>{}),ve(t,j,"collaborates",b,!0).catch(()=>{})}B.outcome==="success"&&ee++}}}ee>0&&t.set(`cachly:stats:first_recall_at:${o}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),Q.length>0&&(t.incr(`cachly:stats:recalls_total:${o}`).catch(()=>{}),Y>0&&t.incr(`cachly:stats:cross_author_recalls:${o}`).catch(()=>{})),ye("smart_recall: Treffer gezaehlt");const{inst:V,semHits:te}=await ce;ye("smart_recall: Tarif abgefragt");const l=!V?.tier||V.tier.toLowerCase()==="free",k=K.map(f=>f.score),E=k.length?Math.min(...k):0,A=k.length&&Math.max(...k)-E||1,_=f=>(f-E)/A,x=new Map,H=ne?fn(K.map(f=>_(f.score))):null,F=new Map;for(const[f,y]of K.entries()){const B=_(y.score),ae=H?H[f]:B;H&&x.set(y.key,f),F.set(y.key,{key:y.key,content:y.content,bm25Score:B,hausWert:ae,hybridScore:ae*(te.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const f of te){const y=F.get(f.key);y?(y.semScore=f.similarity,y.hybridScore=(y.hausWert??0)*.6+f.similarity*.4,y.matchType="hybrid"):F.set(f.key,{key:f.key,content:f.content,semScore:f.similarity,hybridScore:f.similarity*.5,matchType:"semantic"})}try{const f=await Z,y=new Set;for(const{kante:B,inhalt:ae}of f??[]){if(B.edgeType!=="fixes"||B.confidence<.35||y.has(B.from))continue;y.add(B.from);const O=`cachly:lesson:best:${B.from}`,q=F.get(O);if(q)q.ckgScore=Math.max(q.ckgScore??0,B.confidence),q.hybridScore=q.hybridScore*.88+B.confidence*.12,q.matchType==="keyword"&&(q.matchType="hybrid");else{if(!ae)continue;F.set(O,{key:O,content:ae,ckgScore:B.confidence,hybridScore:B.confidence*.3,matchType:"ckg"})}}}catch{}if(ye("smart_recall: Sinn-Dienst und CKG fertig"),S.length>0){const f=new Set(S.map(y=>y.replace(/\\/g,"/")));for(const y of F.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const B=W(y.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(O=>typeof O=="string").map(O=>O.replace(/\\/g,"/")):[]).some(O=>f.has(O))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const f of F.values()){if(f.matchType!=="semantic"&&f.matchType!=="ckg")continue;const y=nn({key:f.key,content:f.content});y&&(f.hybridScore*=sn(y))}const J=[...F.values()].filter(f=>{if(!f.key.startsWith("cachly:lesson:best:"))return!0;const y=De(f.content);return!(!Ge(y)||!rt(y?.group,m,w))}),z=H?dn(J,x):J.sort((f,y)=>y.hybridScore-f.hybridScore),le=[];for(const f of z){if(!f.key.startsWith("cachly:lesson:best:"))continue;const y=W(f.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&le.push(`\u23F3 \`${f.key.replace("cachly:lesson:best:","")}\` was valid until ${String(y.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const B=W(f.content,{});if(B.pruefung_gefallen_am){const ae=f.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_gefallen_am).slice(0,10),q=String(B.pruefung_befund??"").trim().slice(0,200);le.push(`\u274C \`${ae}\` \u2014 Pruefung am ${O} FEHLGESCHLAGEN`+(q?`: ${q}`:""))}else if(B.pruefung_umgebung_am){const ae=f.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_umgebung_am).slice(0,10),q=String(B.pruefung_umgebung_befund??"").trim().slice(0,120);le.push(`\u2139\uFE0F \`${ae}\` \u2014 Pruefung am ${O} an der Umgebung gescheitert, sagt nichts ueber die Lektion`+(q?`: ${q}`:""))}}{const f=new Set(z.map(y=>y.key));for(let y=z.length-1;y>=0;y--){const B=z[y];if(!B.key.startsWith("cachly:lesson:best:"))continue;const ae=W(B.content,{});if(!ae.ersetzt_durch)continue;const O=String(ae.ersetzt_grund??"").trim(),q=B.key.replace("cachly:lesson:best:","");if(f.has(`cachly:lesson:best:${ae.ersetzt_durch}`))z.splice(y,1),le.push(`\u21B7 \`${q}\` hidden \u2014 replaced by \`${ae.ersetzt_durch}\`${ae.ersetzt_am?` on ${ae.ersetzt_am.slice(0,10)}`:""}${O?` \u2014 reason: ${O}`:" \u2014 no reason recorded"}`);else if(await t.get(`cachly:lesson:best:${ae.ersetzt_durch}`)){const b=De(await t.get(`cachly:lesson:best:${ae.ersetzt_durch}`));!Ge(b)||!rt(b.group,m,w)?le.push(`\u21B7 \`${q}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`):le.push(`\u26A0\uFE0F \`${q}\` is replaced by \`${ae.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${ae.ersetzt_durch}")\``)}else le.push(`\u21A9\uFE0F \`${q}\` was replaced by \`${ae.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const ge=wn(z,S),ue=[];{await s.aktualisiere(t).catch(()=>{});const f=z.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<f.length;y++)for(let B=y+1;B<f.length;B++){const ae=f[y].key.replace("cachly:lesson:best:",""),O=f[B].key.replace("cachly:lesson:best:",""),q=s.rohvektor(ae),b=s.rohvektor(O);if(!q||!b)continue;let j=0,U=0,P=0;for(let re=0;re<q.length;re++)j+=q[re]*b[re],U+=q[re]*q[re],P+=b[re]*b[re];if((U>0&&P>0?j/(Math.sqrt(U)*Math.sqrt(P)):0)<Vn)continue;const D=re=>{const de=W(re??"",{});return String(de.verified_at??de.ts??"").slice(0,10)||"no date"};ue.push(`\u26A0\uFE0F \`${ae}\` (${D(f[y].content)}) und \`${O}\` (${D(f[B].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}ue.length>3&&(ue.length=3)}if(le.push(...ue),z.length>=2){const f=z[0].hybridScore,y=z[Math.min(4,z.length-1)].hybridScore,B=Math.max(0,f-y);(async()=>{try{await t.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:z.length})),await t.ltrim("cachly:recall:spread",0,199)}catch{}})()}const se=js();let we="",We=null;if(se!==null){we=Ws();const f=z[0]?.hybridScore??0,y=Fs(z.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),we,se,f);y.weggelassenesThema!==void 0?z.splice(0,1):y.markierungGesetzt&&z[0]&&y.treffer[0]&&(z[0]={...z[0],content:y.treffer[0].content}),We={frage:d,hoechstePunktzahl:f,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}ye("smart_recall: Notizen und Duplikate fertig");const Ee=await ms(o,X);ye("smart_recall: Abruf-Grenze abgefragt");const _e=Ee.reached,Re=ns({ueberLimit:_e,gesamt:z.length,volleTiefe:i??ro}),be=process.env.CACHLY_RECALL_COMPACT==="1",Ue=(()=>{const f=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(f)?Math.min(20,Math.max(1,f)):5})(),Oe=be?Math.min(Ue,Re.sichtbar):Re.sichtbar,oe=[`\u{1F9E0} **Smart Recall** for: _"${d}"_
20
- `];Ee.goodwillMessage&&oe.push(`${Ee.goodwillMessage}
19
+ `)}`}case"smart_recall":{const u=Date.now(),{instance_id:o,query:d,threshold:p=.78,author:a="",context_files:n=[],limit:v}=T,f=Ln(d),i=io(v),S=Array.isArray(n)?n.filter(h=>typeof h=="string"):[];if(be("smart_recall: Anfang"),!Rn(f))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await Gt(o,X)){const h=Date.now()-u;return L(o).then(y=>gs(y,o,String(f??""),h)).catch(()=>{}),be("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),Kt(String(f??""),{startet:!0,...await bt(o)})}const t=await L(o);be("smart_recall: Verbindung steht");const{vektor:s,namen:C,zweit:r,eingang:c,seltenheit:b}=xt(t);ze()&&Promise.allSettled([s.aktualisiere(t),C.aktualisiere(t),c.aktualisiere(t),b.aktualisiere(t),r.aktualisiere(t)]),_s(t,void 0,2);let m=new Set,w=!1;a&&(m=await yt(t,o,a).catch(()=>new Set),w=await it(t,o,a).catch(()=>null)==="admin");const I=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],A=await en(t,I);if(be(`smart_recall: Wortbestand da (${A?.docs.length??0} Eintraege)`),!A)return gs(t,o,String(f??""),Date.now()-u),be("smart_recall: Brain leer \u2014 sofort geantwortet"),Kt(String(f??""),{startet:!1,...await bt(o)});const e=A.docs.reduce((h,y)=>h+(y.key.startsWith("cachly:lesson:best:")?1:0),0),Z=Js(t,_t(f).filter(h=>h.length>=4).slice(0,4)).catch(()=>null),le=(async()=>{const h=await Vs(o,()=>X(`/api/v1/instances/${o}`)),y=[];if(!(!h?.tier||h.tier.toLowerCase()==="free")&&h?.vector_token&&ze())try{const ae=await Te(f),O=`https://api.cachly.dev/v1/sem/${h.vector_token}`,U=await fetch(`${O}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:ae,namespace:"cachly:ctx",threshold:p,top_k:5}),signal:AbortSignal.timeout(8e3)});if(U.ok){const fe=(await U.json()).filter(z=>z.found&&z.id).map(z=>{const F=z.id.replace("ctx:","").split(":");return{hit:z,redisKey:`cachly:ctx:${F[0]}:${F.slice(1).join(":")}`}}),k=await Promise.all(fe.map(z=>t.get(z.redisKey).catch(()=>null)));fe.forEach((z,F)=>{y.push({key:z.redisKey,similarity:z.hit.similarity??0,content:k[F]??"(evicted)"})})}}catch{}return{inst:h,semHits:y}})().catch(()=>({inst:null,semHits:[]})),re=await lt(t,I,f,25);be(`smart_recall: Wortsuche fertig (${re.length} Treffer)`);const ue=nn(re);let ne=!1,g=null;const V=await(async()=>{if(!ze())return mt(Ps,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),ue;try{if(await s.aktualisiere(t),be(`smart_recall: Vektorbestand geladen (${s.groesse})`),s.groesse===0)return e>0&&mt(zs,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),ue;const h=await Te(f);if(be("smart_recall: Frage eingebettet"),!h?.length)return mt(js,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),ue;await C.aktualisiere(t),await c.aktualisiere(t),await b.aktualisiere(t),await r.aktualisiere(t),be(`smart_recall: Bestaende geladen (Namen ${C.groesse}, Eingaenge ${c.groesse}, Seltenheit ${b.groesse}, Zweit ${r.groesse})`);const y=s.groesse>0?r.groesse/s.groesse:0;y<Qt&&s.groesse>0&&Vo(t,3);const B=y>=Qt?Te(f,{modell:Ye}).catch(()=>null):null,ae=ue.filter(K=>K.key.startsWith("cachly:lesson:best:")).map(K=>K.key.slice(19)),O=K=>Math.max(s.naehe(h,K),C.naehe(h,K)),U=[...b.themen()],ce=(U.length>0?U:s.aehnlichste(h,500).map(K=>K.topic)).map(K=>({t:K,n:O(K)})).sort((K,pe)=>pe.n-K.n||(K.t<pe.t?-1:K.t>pe.t?1:0)).slice(0,os).map(K=>K.t),fe=[...new Set([...ae,...ce])],k=ce.slice(0,3).map(K=>s.rohvektor(K)).filter(Boolean),z=k.length?Nn(h,k):h,F=Xt(f),P=b.statistik,R=fe.map(K=>{const pe=new Set([...Xt(b.textVon(K))].map(En));return{naeheText:s.naehe(h,K),naeheThema:C.naehe(h,K),naeheRueckkopplung:s.naehe(z,K),seltenheitsDeckung:P?P.deckung(F,pe):0,besterZeuge:P?P.besterZeuge(F,pe):0}});let G=Tn(R,An);{const K=[...G].sort((pe,ke)=>ke-pe);g=K.length>1?K[0]-K[1]:null}if(c.groesse>0){const K=fe.map(ke=>{const xe=c.besteNaehe(h,ke);return xe>=oo?xe:-2}),pe=Zt(K);G=G.map((ke,xe)=>ke+ao*pe[xe])}if(B){const K=await B;if(K?.length){const pe=Zt(fe.map(ke=>r.naehe(K,ke)));G=G.map((ke,xe)=>ke+Jn*pe[xe])}}let ie=fe.map((K,pe)=>({t:K,p:G[pe]})).sort((K,pe)=>pe.p-K.p).map(K=>K.t);if(rn(o)&&ie.length>1){const K=ie.slice(0,es),pe=ie.slice(es),ke=new Map(fe.map((nt,Xe)=>[nt,G[Xe]]));be("smart_recall: Leser Anfang");const xe=await cn(f,K.map(nt=>b.leserTextVon(nt)),{instanceId:o});be(`smart_recall: Leser ${xe?"fertig":"ohne Ergebnis"}`),xe&&(ie=[...ln(K.map(Xe=>ke.get(Xe)??0),xe).map(Xe=>K[Xe]),...pe])}const ge=new Map(ue.map(K=>[K.key,K])),Me=ie.map(K=>`cachly:lesson:best:${K}`).filter(K=>!ge.has(K)),Ze=new Map;if(Me.length>0){const K=await t.mget(...Me).catch(()=>[]);Me.forEach((pe,ke)=>Ze.set(pe,K[ke]??null))}const $e=[];for(const K of ie){const pe=`cachly:lesson:best:${K}`,ke=ge.get(pe);if(ke){$e.push(ke),ge.delete(pe);continue}const xe=Ze.get(pe)??null;xe&&$e.push({key:pe,content:xe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return $e.push(...ge.values()),Hn&&Fn({frage:f.slice(0,200),themen:fe,ausWortsuche:ae.length,ausSinnsuche:ce.length,obergrenze:os,gezeigt:ie.slice(0,10)}),ne=!0,$e}catch(h){return await Qe(t,Ws,`der Bedeutungspfad brach ab (${h instanceof Error?h.message:String(h)}) \u2014 diese Suche lief nur ueber Woerter`),ue}})();be("smart_recall: Bedeutungspfad fertig"),Nt(t),Ct(t,String(f??""),Date.now()-u);{const h=V.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(h.length>0){const y={ts:new Date().toISOString(),themen:h};(async()=>{const B=Jt(o);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,Sn-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:f.slice(0,200),geliefert:h};(async()=>{const B=St(o);await t.lpush(B,JSON.stringify(y)),await t.ltrim(B,0,Ut-1)})().catch(()=>{})}}if(ze()&&!jt()){const h=V.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));wn(t,f,h,Te).catch(()=>{})}const Q=V.filter(h=>h.key.startsWith("cachly:lesson:best:"));let Y=0,ee=0;for(const h of Q.slice(0,5)){const y=await t.get(h.key).catch(()=>null);if(y){const B=j(y,null);if(B?.state==="archived")continue;if(B){const ae=new Date().toISOString(),O={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:ae};jt()||t.set(h.key,JSON.stringify(O)).catch(()=>{});const U=Ot(B)?Bt(B):0;if(U>0&&t.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,U).catch(()=>{}),B.author&&a&&B.author!==a){Y++,t.sadd(`cachly:stats:reuse_pairs:${o}`,`${a}<-${B.author}`).catch(()=>{});const ce=`person:${we(a)}`,fe=`person:${we(B.author)}`;ve(t,ce,"collaborates",fe,!0).catch(()=>{}),ve(t,fe,"collaborates",ce,!0).catch(()=>{})}B.outcome==="success"&&ee++}}}ee>0&&t.set(`cachly:stats:first_recall_at:${o}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),Q.length>0&&(t.incr(`cachly:stats:recalls_total:${o}`).catch(()=>{}),Y>0&&t.incr(`cachly:stats:cross_author_recalls:${o}`).catch(()=>{})),be("smart_recall: Treffer gezaehlt");const{inst:J,semHits:te}=await le;be("smart_recall: Tarif abgefragt");const l=!J?.tier||J.tier.toLowerCase()==="free",$=V.map(h=>h.score),N=$.length?Math.min(...$):0,E=$.length&&Math.max(...$)-N||1,_=h=>(h-N)/E,x=new Map,H=ne?gn(V.map(h=>_(h.score))):null,W=new Map;for(const[h,y]of V.entries()){const B=_(y.score),ae=H?H[h]:B;H&&x.set(y.key,h),W.set(y.key,{key:y.key,content:y.content,bm25Score:B,hausWert:ae,hybridScore:ae*(te.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const h of te){const y=W.get(h.key);y?(y.semScore=h.similarity,y.hybridScore=(y.hausWert??0)*.6+h.similarity*.4,y.matchType="hybrid"):W.set(h.key,{key:h.key,content:h.content,semScore:h.similarity,hybridScore:h.similarity*.5,matchType:"semantic"})}try{const h=await Z,y=new Set;for(const{kante:B,inhalt:ae}of h??[]){if(B.edgeType!=="fixes"||B.confidence<.35||y.has(B.from))continue;y.add(B.from);const O=`cachly:lesson:best:${B.from}`,U=W.get(O);if(U)U.ckgScore=Math.max(U.ckgScore??0,B.confidence),U.hybridScore=U.hybridScore*.88+B.confidence*.12,U.matchType==="keyword"&&(U.matchType="hybrid");else{if(!ae)continue;W.set(O,{key:O,content:ae,ckgScore:B.confidence,hybridScore:B.confidence*.3,matchType:"ckg"})}}}catch{}if(be("smart_recall: Sinn-Dienst und CKG fertig"),S.length>0){const h=new Set(S.map(y=>y.replace(/\\/g,"/")));for(const y of W.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const B=j(y.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(O=>typeof O=="string").map(O=>O.replace(/\\/g,"/")):[]).some(O=>h.has(O))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const h of W.values()){if(h.matchType!=="semantic"&&h.matchType!=="ckg")continue;const y=an({key:h.key,content:h.content});y&&(h.hybridScore*=on(y))}const q=[...W.values()].filter(h=>{if(!h.key.startsWith("cachly:lesson:best:"))return!0;const y=je(h.content);return!(!Ve(y)||!ct(y?.group,m,w))}),D=H?pn(q,x):q.sort((h,y)=>y.hybridScore-h.hybridScore),he=[];for(const h of D){if(!h.key.startsWith("cachly:lesson:best:"))continue;const y=j(h.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&he.push(`\u23F3 \`${h.key.replace("cachly:lesson:best:","")}\` was valid until ${String(y.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const B=j(h.content,{});if(B.pruefung_gefallen_am){const ae=h.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_gefallen_am).slice(0,10),U=String(B.pruefung_befund??"").trim().slice(0,200);he.push(`\u274C \`${ae}\` \u2014 Pruefung am ${O} FEHLGESCHLAGEN`+(U?`: ${U}`:""))}else if(B.pruefung_umgebung_am){const ae=h.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_umgebung_am).slice(0,10),U=String(B.pruefung_umgebung_befund??"").trim().slice(0,120);he.push(`\u2139\uFE0F \`${ae}\` \u2014 Pruefung am ${O} an der Umgebung gescheitert, sagt nichts ueber die Lektion`+(U?`: ${U}`:""))}}{const h=new Set(D.map(y=>y.key));for(let y=D.length-1;y>=0;y--){const B=D[y];if(!B.key.startsWith("cachly:lesson:best:"))continue;const ae=j(B.content,{});if(!ae.ersetzt_durch)continue;const O=String(ae.ersetzt_grund??"").trim(),U=B.key.replace("cachly:lesson:best:","");if(h.has(`cachly:lesson:best:${ae.ersetzt_durch}`))D.splice(y,1),he.push(`\u21B7 \`${U}\` hidden \u2014 replaced by \`${ae.ersetzt_durch}\`${ae.ersetzt_am?` on ${ae.ersetzt_am.slice(0,10)}`:""}${O?` \u2014 reason: ${O}`:" \u2014 no reason recorded"}`);else if(await t.get(`cachly:lesson:best:${ae.ersetzt_durch}`)){const ce=je(await t.get(`cachly:lesson:best:${ae.ersetzt_durch}`));!Ve(ce)||!ct(ce.group,m,w)?he.push(`\u21B7 \`${U}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`):he.push(`\u26A0\uFE0F \`${U}\` is replaced by \`${ae.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${ae.ersetzt_durch}")\``)}else he.push(`\u21A9\uFE0F \`${U}\` was replaced by \`${ae.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const me=_n(D,S),de=[];{await s.aktualisiere(t).catch(()=>{});const h=D.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<h.length;y++)for(let B=y+1;B<h.length;B++){const ae=h[y].key.replace("cachly:lesson:best:",""),O=h[B].key.replace("cachly:lesson:best:",""),U=s.rohvektor(ae),ce=s.rohvektor(O);if(!U||!ce)continue;let fe=0,k=0,z=0;for(let R=0;R<U.length;R++)fe+=U[R]*ce[R],k+=U[R]*U[R],z+=ce[R]*ce[R];if((k>0&&z>0?fe/(Math.sqrt(k)*Math.sqrt(z)):0)<qn)continue;const P=R=>{const G=j(R??"",{});return String(G.verified_at??G.ts??"").slice(0,10)||"no date"};de.push(`\u26A0\uFE0F \`${ae}\` (${P(h[y].content)}) und \`${O}\` (${P(h[B].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}de.length>3&&(de.length=3)}if(he.push(...de),D.length>=2){const h=D[0].hybridScore,y=D[Math.min(4,D.length-1)].hybridScore,B=Math.max(0,h-y);(async()=>{try{await t.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:D.length})),await t.ltrim("cachly:recall:spread",0,199)}catch{}})()}const se=Fs();let ye="",Le=null;if(se!==null){ye=Hs();const h=D[0]?.hybridScore??0,y=Gs(D.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),ye,se,h);y.weggelassenesThema!==void 0?D.splice(0,1):y.markierungGesetzt&&D[0]&&y.treffer[0]&&(D[0]={...D[0],content:y.treffer[0].content}),Le={frage:f,hoechstePunktzahl:h,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}be("smart_recall: Notizen und Duplikate fertig");const Oe=await ys(o,X);be("smart_recall: Abruf-Grenze abgefragt");const De=Oe.reached,_e=as({ueberLimit:De,gesamt:D.length,volleTiefe:i??co}),Ce=process.env.CACHLY_RECALL_COMPACT==="1",Be=(()=>{const h=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(h)?Math.min(20,Math.max(1,h)):5})(),Ae=Ce?Math.min(Be,_e.sichtbar):_e.sichtbar,oe=[`\u{1F9E0} **Smart Recall** for: _"${f}"_
20
+ `];Oe.goodwillMessage&&oe.push(`${Oe.goodwillMessage}
21
21
  `),Y>0&&oe.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${Y} of these lesson${Y!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
22
- `);const Le=z.filter(f=>f.contextBoost).length;Le>0&&oe.push(`> \u{1F4C1} **Personalized** \u2014 ${Le} lesson${Le!==1?"s":""} boosted because ${Le!==1?"they match":"it matches"} your current file context (${S.slice(0,3).join(", ")}${S.length>3?", \u2026":""})
23
- `);const Ae=Ys(d);Ae.length>1&&oe.push(`_Detected ${Ae.length} sub-topics:_ ${Ae.map((f,y)=>`${y+1}. "${f}"`).join(", ")}
24
- `);const Se=Bs(z.map(f=>({wortBelege:f.wortBelege,semScore:f.semScore,ckgScore:f.ckgScore})));if(Se.schweigen)return Tt(t,o,"schweigen"),oe.push(Rs(Se)),oe.join(`
25
- `);const Ie=En(g);if(Ie&&oe.push(Ie,""),Tt(t,o,Ie?"knapp":"beantwortet"),z.length>0){const f=z.some(O=>O.ckgScore!==void 0),y=ne||te.length>0,B=y&&f?"keyword + semantic + CKG hybrid":y?"keyword + semantic hybrid":f?"keyword + CKG hybrid":"keyword",ae=Math.min(Oe,z.length);if(oe.push(`### \u{1F50D} Results (${ae<z.length&&Ae.length<=1?`showing ${ae} of ${z.length}`:z.length} \u2014 ${B})
26
- `),Se.belegte<z.length){const O=[];for(const b of z){if(!b.key.startsWith("cachly:lesson:best:")||!Ot({wortBelege:b.wortBelege,semScore:b.semScore,ckgScore:b.ckgScore}))continue;const j=W(b.content,{}),U=Date.parse(j.verified_at??j.ts??"");Number.isFinite(U)&&O.push(Math.floor((Date.now()-U)/864e5))}const q=Ls(O);oe.push(`> \u{1F4CA} ${Se.belegte} of ${z.length} backed by evidence (at least one matching word, close meaning or a graph link). The rest are only the nearest entries, not evidence.`+(q?` \u23F3 ${q}`:"")+`
27
- `)}if(le.push(...yn(z.slice(0,Oe),ge)),le.length>0&&oe.push(...le.map(O=>`> ${O}`),""),Ae.length>1){const O=new Map,q=ns({ueberLimit:_e,gesamt:z.length,volleTiefe:i??io});for(const U of z.slice(0,q.sichtbar)){const P=U.subQuery??d;O.has(P)||O.set(P,[]),O.get(P).push(U)}for(const[U,P]of O){oe.push(`**Topic: "${U}"** (${P.length} results)
28
- `);for(const T of P.slice(0,be?2:i??4)){const D=T.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),re=T.matchType==="ckg"?`CKG: ${(T.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:T.ckgScore!==void 0&&T.bm25Score!==void 0?`BM25: ${T.bm25Score.toFixed(2)}, CKG: ${T.ckgScore.toFixed(2)}, \u{1F500} hybrid`:T.matchType==="hybrid"?`BM25: ${(T.bm25Score??0).toFixed(2)}, sem: ${((T.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:T.matchType==="semantic"?`sem: ${((T.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(T.bm25Score??0).toFixed(2)}, matched: ${T.matchedWords?.join(", ")}`,de=be?gt(T.key,T.content,300):gt(T.key,T.content,Dt,300);if(oe.push(be?` **${D}**`:` **${D}** _(${re})_`),T.key.startsWith("cachly:lesson:best:")){const pe=await t.get(T.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(T.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),Ne=pe?W(pe,{}):{};Ne.title&&oe.push(` \u{1F4D6} **${Ne.title}** \u2014 ${Ne.summary??""}`)}{const pe=T.key.startsWith("cachly:lesson:best:")?is(T.content):"";pe&&oe.push(` ${pe}`)}for(const pe of de)oe.push(` > ${pe}`);oe.push("")}}const b=[...O.keys()],j=Ae.filter(U=>!b.includes(U));j.length>0&&oe.push(`
29
- \u26A0\uFE0F **No results for:** ${j.map(U=>`"${U}"`).join(", ")}`)}else for(const O of z.slice(0,Oe)){const q=O.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let b="";if(O.key.startsWith("cachly:lesson:best:")){const D=W(O.content,{});D.author&&(b=` \xB7 \u{1F464} ${D.author}`)}const j=O.contextBoost?" \xB7 \u{1F4C1} context match":"",U=O.matchType==="hybrid"?`BM25: ${(O.bm25Score??0).toFixed(2)}, sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:O.matchType==="semantic"?`sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(O.bm25Score??0).toFixed(2)}, matched: ${O.matchedWords?.join(", ")}`,P=gt(O.key,O.content,be?zt:Dt,zt),T=Se.belegte>0&&Se.belegte<z.length&&!Ot({wortBelege:O.wortBelege,semScore:O.semScore,ckgScore:O.ckgScore})?" \xB7 \u26A0\uFE0F no evidence":"";oe.push(be?`**${q}**${T}`:`**${q}**${b}${j} _(${U})_${T}`);{const D=W(O.content??"",{});D.entscheidung?.gegen&&oe.push(Ut({gegen:D.entscheidung.gegen,grund:D.entscheidung.grund??null}))}if(O.key.startsWith("cachly:lesson:best:")){const D=await t.get(O.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(O.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),re=D?W(D,{}):{};re.title&&oe.push(`\u{1F4D6} **${re.title}** \u2014 ${re.summary??""}`)}{const D=O.key.startsWith("cachly:lesson:best:")?is(O.content):"";D&&oe.push(D)}for(const D of P)oe.push(`> ${D}`);oe.push("")}if(_e&&Re.zurueckgehalten>0){const O=Re.zurueckgehalten;oe.push(`\u{1F512} **Free recall limit reached** (${Ee.used}/${Ee.limit} this month). Showing your top match; ${O} further relevant lesson${O!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${zo}
30
- `)}}else{oe.push(`\u26A0\uFE0F No matches found for: "${d}"`),le.length>0&&oe.push("",...le.map(B=>`> ${B}`));const f=wt(d),y=[];if(Ft.size>0&&f.length>0)for(const B of f.slice(0,3)){if(B.length<4)continue;let ae=3,O="";for(const q of Ft){if(q.length<3||Math.abs(q.length-B.length)>4)continue;const b=Zs(B,q);b>0&&b<ae&&(ae=b,O=q)}O&&y.push(`"${O}" (instead of "${B}")`)}y.length>0?oe.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(oe.push(`
31
- \u{1F4A1} Tips:`),oe.push(" \u2022 Try different keywords"),oe.push(" \u2022 Use `list_remembered` to see available context"),oe.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!be&&z.length>0){oe.push(""),oe.push('\u21A9\uFE0E Did one of these help? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` (not in your tool list? use `cachly_tool(tool="recall_feedback", arguments={\u2026})`) \u2014 and if the right lesson was **not** in the list: the same call with `rank=0`. That is the only number that improves the ranking.');const f=z.filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));if(f.length>0)try{await t.setex(`cachly:letzter-recall:${o}`,7200,JSON.stringify({frage:d,themen:f}))}catch{}}if(be&&z.length>0){const f=Cs();f&&(oe.push(""),oe.push(f))}if(se!==null&&We){const f=z.slice(0,Oe).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return Hs(t,we,{...We,themen:f},oe.join(`
22
+ `);const Pe=D.filter(h=>h.contextBoost).length;Pe>0&&oe.push(`> \u{1F4C1} **Personalized** \u2014 ${Pe} lesson${Pe!==1?"s":""} boosted because ${Pe!==1?"they match":"it matches"} your current file context (${S.slice(0,3).join(", ")}${S.length>3?", \u2026":""})
23
+ `);const Ne=Xs(f);Ne.length>1&&oe.push(`_Detected ${Ne.length} sub-topics:_ ${Ne.map((h,y)=>`${y+1}. "${h}"`).join(", ")}
24
+ `);const Ie=Ds(D.map(h=>({wortBelege:h.wortBelege,semScore:h.semScore,ckgScore:h.ckgScore})));if(Ie.schweigen)return Et(t,o,"schweigen"),oe.push(Bs(Ie)),oe.join(`
25
+ `);const Ee=In(g);if(Ee&&oe.push(Ee,""),Et(t,o,Ee?"knapp":"beantwortet"),D.length>0){const h=D.some(O=>O.ckgScore!==void 0),y=ne||te.length>0,B=y&&h?"keyword + semantic + CKG hybrid":y?"keyword + semantic hybrid":h?"keyword + CKG hybrid":"keyword",ae=Math.min(Ae,D.length);if(oe.push(`### \u{1F50D} Results (${ae<D.length&&Ne.length<=1?`showing ${ae} of ${D.length}`:D.length} \u2014 ${B})
26
+ `),Ie.belegte<D.length){const O=[];for(const ce of D){if(!ce.key.startsWith("cachly:lesson:best:")||!Dt({wortBelege:ce.wortBelege,semScore:ce.semScore,ckgScore:ce.ckgScore}))continue;const fe=j(ce.content,{}),k=Date.parse(fe.verified_at??fe.ts??"");Number.isFinite(k)&&O.push(Math.floor((Date.now()-k)/864e5))}const U=Os(O);oe.push(`> \u{1F4CA} ${Ie.belegte} of ${D.length} backed by evidence (at least one matching word, close meaning or a graph link). The rest are only the nearest entries, not evidence.`+(U?` \u23F3 ${U}`:"")+`
27
+ `)}if(he.push(...bn(D.slice(0,Ae),me)),he.length>0&&oe.push(...he.map(O=>`> ${O}`),""),Ne.length>1){const O=new Map,U=as({ueberLimit:De,gesamt:D.length,volleTiefe:i??lo});for(const k of D.slice(0,U.sichtbar)){const z=k.subQuery??f;O.has(z)||O.set(z,[]),O.get(z).push(k)}for(const[k,z]of O){oe.push(`**Topic: "${k}"** (${z.length} results)
28
+ `);for(const F of z.slice(0,Ce?2:i??4)){const P=F.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),R=F.matchType==="ckg"?`CKG: ${(F.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:F.ckgScore!==void 0&&F.bm25Score!==void 0?`BM25: ${F.bm25Score.toFixed(2)}, CKG: ${F.ckgScore.toFixed(2)}, \u{1F500} hybrid`:F.matchType==="hybrid"?`BM25: ${(F.bm25Score??0).toFixed(2)}, sem: ${((F.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:F.matchType==="semantic"?`sem: ${((F.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(F.bm25Score??0).toFixed(2)}, matched: ${F.matchedWords?.join(", ")}`,G=Ce?wt(F.key,F.content,300):wt(F.key,F.content,zt,300);if(oe.push(Ce?` **${P}**`:` **${P}** _(${R})_`),F.key.startsWith("cachly:lesson:best:")){const ie=await t.get(F.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(F.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ge=ie?j(ie,{}):{};ge.title&&oe.push(` \u{1F4D6} **${ge.title}** \u2014 ${ge.summary??""}`)}{const ie=F.key.startsWith("cachly:lesson:best:")?ls(F.content):"";ie&&oe.push(` ${ie}`)}for(const ie of G)oe.push(` > ${ie}`);oe.push("")}}const ce=[...O.keys()],fe=Ne.filter(k=>!ce.includes(k));fe.length>0&&oe.push(`
29
+ \u26A0\uFE0F **No results for:** ${fe.map(k=>`"${k}"`).join(", ")}`)}else for(const O of D.slice(0,Ae)){const U=O.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let ce="";if(O.key.startsWith("cachly:lesson:best:")){const P=j(O.content,{});P.author&&(ce=` \xB7 \u{1F464} ${P.author}`)}const fe=O.contextBoost?" \xB7 \u{1F4C1} context match":"",k=O.matchType==="hybrid"?`BM25: ${(O.bm25Score??0).toFixed(2)}, sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:O.matchType==="semantic"?`sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(O.bm25Score??0).toFixed(2)}, matched: ${O.matchedWords?.join(", ")}`,z=wt(O.key,O.content,Ce?Pt:zt,Pt),F=Ie.belegte>0&&Ie.belegte<D.length&&!Dt({wortBelege:O.wortBelege,semScore:O.semScore,ckgScore:O.ckgScore})?" \xB7 \u26A0\uFE0F no evidence":"";oe.push(Ce?`**${U}**${F}`:`**${U}**${ce}${fe} _(${k})_${F}`);{const P=j(O.content??"",{});P.entscheidung?.gegen&&oe.push(Yt({gegen:P.entscheidung.gegen,grund:P.entscheidung.grund??null}))}if(O.key.startsWith("cachly:lesson:best:")){const P=await t.get(O.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await t.get(O.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),R=P?j(P,{}):{};R.title&&oe.push(`\u{1F4D6} **${R.title}** \u2014 ${R.summary??""}`)}{const P=O.key.startsWith("cachly:lesson:best:")?ls(O.content):"";P&&oe.push(P)}for(const P of z)oe.push(`> ${P}`);oe.push("")}if(De&&_e.zurueckgehalten>0){const O=_e.zurueckgehalten;oe.push(`\u{1F512} **Free recall limit reached** (${Oe.used}/${Oe.limit} this month). Showing your top match; ${O} further relevant lesson${O!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${jo}
30
+ `)}}else{oe.push(`\u26A0\uFE0F No matches found for: "${f}"`),he.length>0&&oe.push("",...he.map(B=>`> ${B}`));const h=_t(f),y=[];if(Ht.size>0&&h.length>0)for(const B of h.slice(0,3)){if(B.length<4)continue;let ae=3,O="";for(const U of Ht){if(U.length<3||Math.abs(U.length-B.length)>4)continue;const ce=Qs(B,U);ce>0&&ce<ae&&(ae=ce,O=U)}O&&y.push(`"${O}" (instead of "${B}")`)}y.length>0?oe.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(oe.push(`
31
+ \u{1F4A1} Tips:`),oe.push(" \u2022 Try different keywords"),oe.push(" \u2022 Use `list_remembered` to see available context"),oe.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!Ce&&D.length>0){oe.push(""),oe.push('\u21A9\uFE0E Did one of these help? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` (not in your tool list? use `cachly_tool(tool="recall_feedback", arguments={\u2026})`) \u2014 and if the right lesson was **not** in the list: the same call with `rank=0`. That is the only number that improves the ranking.');const h=D.filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));if(h.length>0)try{await t.setex(`cachly:letzter-recall:${o}`,7200,JSON.stringify({frage:f,themen:h}))}catch{}}if(Ce&&D.length>0){const h=Ts();h&&(oe.push(""),oe.push(h))}if(se!==null&&Le){const h=D.slice(0,Ae).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return Ks(t,ye,{...Le,themen:h},oe.join(`
32
32
  `))}return oe.join(`
33
- `)}case"session_start":{const{instance_id:h,focus:o="",author:u="",provider:p="",workspace_path:a=""}=N;if(await Ht(h,X))return L(h).then(async l=>{await ps(l),await gs(l,o,p),await l.set("cachly:mcp:version:last_seen",Qe,"EX",365*86400)}).catch(()=>{}),ye("session_start: neues Brain startet noch \u2014 sofort geantwortet"),en({instanzId:h,provider:p,...await yt(h)});const n=await L(h),v=[],d=n.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((l,k)=>{d.on("data",E=>v.push(...E)),d.on("end",l),d.on("error",k)});const i=[];let S=0;if(v.length>0){const l=await n.mget(...v);for(const k of l){const E=W(k??null,null);if(E){if(as(E)){S++;continue}ls(E.topic)||i.push(E)}}}i.sort((l,k)=>new Date(k.ts).getTime()-new Date(l.ts).getTime());let t=0;const s=n.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((l,k)=>{s.on("data",E=>{t+=E.filter(A=>!A.endsWith(":meta")).length}),s.on("end",l),s.on("error",k)});const C=await n.get("cachly:session:last"),r=W(C,null),c=o.toLowerCase().split(/\s+/).filter(Boolean),$=c.length>0?i.filter(l=>c.some(k=>l.topic.toLowerCase().includes(k)||(l.tags??[]).some(E=>E.toLowerCase().includes(k)))):[],{tage:m,rekord:w}=await ps(n);let M="";m>=7?M=`\u{1F525} **${m}-day streak!** ${m===w?" New record!":`Best: ${w}d`}`:m>1&&(M=`\u{1F525} ${m}-day streak`),await gs(n,o,p);const e=[`\u{1F9E0} **Session Briefing**${p?` \xB7 ${p}`:""}`,""];M&&e.push(M,"");const Z=await ms(h,X),ce=oo({used:Z.used,limit:Z.limit});if(ce&&e.push(ce,""),Z.notice&&!us.has(h)&&(us.add(h),e.push(Z.notice,"")),r?.ts){const l=new Date(r.ts).getTime(),k=Math.floor((Date.now()-l)/864e5);if(k>=7&&!Number.isNaN(l)){const E=i.filter(A=>{const _=new Date(A.ts).getTime();return!Number.isNaN(_)&&_>l});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${k} days since your last session.`),E.length>0){const A=E.slice(0,3).map(_=>`\`${_.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${E.length} lesson${E.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${A}${E.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${i.length} lesson${i.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 n.get("cachly:mcp:version:last_seen")!==Qe){await n.set("cachly:mcp:version:last_seen",Qe,"EX",365*86400);const k=Do[Qe];if(k){e.push(...k,"");const E=Oo();E&&e.push(`\u{1F4CA} ${E} MCP tools`,"")}}}catch{}const ie=!r&&i.length===0&&S===0&&t===0;ie&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),a?(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="${h}")\``),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(""));const he=$.slice(0,4),ne=new Set(he.map(l=>l.topic));if(u&&!ie)try{const l=`cachly:team:first_briefing:${u}`;if(!await n.get(l)){const E=i.filter(A=>A.author&&A.author!==u&&!ne.has(A.topic));if(E.length>0){await n.set(l,"1","EX",365*86400);const A=new Map;for(const _ of E){const x=_.author;A.has(x)||A.set(x,[]),A.get(x).push(_)}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[_,x]of A){e.push(` \u{1F464} **${_}** fixed ${x.length} thing${x.length>1?"s":""}:`);for(const H of x.slice(0,2)){const F=H.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${F} \`${H.topic}\` \u2014 ${H.what_worked.slice(0,90)}`),ne.add(H.topic)}x.length>2&&e.push(` \u2026 and ${x.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 g=await n.get("cachly:session:handoff");if(g)try{const l=JSON.parse(g),k=Math.round((Date.now()-new Date(l.ts).getTime())/6e4),E=k<60?`${k}m ago`:k<1440?`${Math.round(k/60)}h ago`:`${Math.round(k/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${E}):`),l.context_summary&&e.push(` ${l.context_summary}`),l.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const _ of l.remaining_tasks)e.push(` - ${_}`)}l.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${l.completed_tasks.join(", ")}`);const A=(l.files_changed??[]).filter(_=>_.status==="broken"||_.status==="partial");A.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${A.map(_=>`\`${_.path}\` (${_.status}${_.description?": "+_.description:""})`).join(", ")}`),l.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${l.blocked_on}`),l.instructions&&e.push(` \u{1F4DD} **Instructions:** ${l.instructions}`),e.push("")}catch{}const K=await n.get("cachly:session:checkpoint");if(K)try{const l=JSON.parse(K),k=new Date(l.ts).getTime(),E=r?new Date(r.ts).getTime():0;if(k>E){const A=Math.round((Date.now()-k)/6e4),_=A<60?`${A}m ago`:A<1440?`${Math.round(A/60)}h ago`:`${Math.round(A/1440)}d ago`,x=l.provider?` [${l.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${x} (${_}): ${l.task}`),l.files_touched.length>0&&e.push(` Files: ${l.files_touched.slice(0,5).map(H=>`\`${H}\``).join(", ")}`),l.next_step&&e.push(` \u{1F4CD} Next step was: ${l.next_step}`),(!r||k-E>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}const Q=r?null:ht(a);if(Q)try{const l=Fe(Q,["log","--oneline","--format=%h %s","-15"]).trim();let k;try{k=Fe(Q,["diff","--stat","HEAD~3"]).trim()}catch{k=Fe(Q,["diff","--stat"]).trim()}if(l){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const E of l.split(`
34
- `).slice(0,8))e.push(` ${E}`);if(k){const E=k.split(`
35
- `).filter(A=>A.includes("|")||A.includes("changed"));if(E.length>0){e.push(" **Recent changes:**");for(const A of E.slice(0,5))e.push(` ${A.trim()}`)}}e.push("")}}catch{}if(r){const l=Math.round((Date.now()-new Date(r.ts).getTime())/6e4),k=l<60?`${l}m ago`:l<1440?`${Math.round(l/60)}h ago`:`${Math.round(l/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${k}): ${r.summary}`),r.duration_min&&e.push(` Duration: ${r.duration_min} min`),(r.files_changed??[]).length>0&&e.push(` Files: ${(r.files_changed??[]).slice(0,5).map(E=>`\`${E}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${t} context entries`,""),S>0&&e.push(`\u26A0 ${S} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const k=await n.lrange(`cachly:wirkung:${h}`,0,-1).catch(()=>[]),E=Pn(k.map(x=>W(x,null)).filter(Boolean)),A=x=>E.get(x)??{geholfen:0,geoeffnet:0},_=i.filter(x=>!Is(x)).filter(x=>{if(x.outcome!=="success")return!1;const H=A(x.topic);return x.pinned===!0||H.geholfen>=1||H.geoeffnet>=2}).filter(x=>!ne.has(x.topic)).sort((x,H)=>{const F=A(x.topic),J=A(H.topic);return J.geholfen-F.geholfen||J.geoeffnet-F.geoeffnet||(H.recall_count??0)-(x.recall_count??0)}).slice(0,5);if(_.length>0){e.push("\u{1F4CC} **Confirmed lessons** (pinned, reported helpful, or opened after a search \u2014 being shown does not count):");for(const x of _){ne.add(x.topic);const H=x.severity==="critical"?"\u{1F534}":x.severity==="major"?"\u{1F7E1}":"",F=A(x.topic),J=[x.pinned===!0?"pinned":"",F.geholfen>0?`reported helpful ${F.geholfen}\xD7`:"",F.geoeffnet>0?`opened ${F.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),z=st(x);e.push(` \u2705${H} \`${x.topic}\` _(${J})_ \u2014 ${z[0]??""}`,...z.slice(1))}e.push("")}}try{const l=[],k=n.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((E,A)=>{k.on("data",_=>l.push(..._)),k.on("end",E),k.on("error",A)}),l.length>0){e.push(`\u26A1 **Active belief conflicts (${l.length}):**`);for(const E of l.slice(0,3)){const A=await n.get(E);if(!A)continue;const _=W(A,null);_&&e.push(` \u26A0\uFE0F \`${_.topic}\` \u2014 previously confirmed fix (${(_.fix_confidence*100).toFixed(0)}%, n=${_.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${me(_.topic)}")\``)}e.push("")}}catch{}if(he.length>0){e.push(`\u{1F3AF} **Relevant for "${o}":**`);for(const l of he){const k=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",E=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",A=st(l);e.push(` ${k}${E} \`${l.topic}\` \u2014 ${A[0]??""}`,...A.slice(1))}e.push("")}if(i.length>0){const l=($.length>0?i.filter(k=>!$.includes(k)):i).filter(k=>!ne.has(k.topic)).slice(0,$.length>0?3:4);if(l.length>0){e.push("\u{1F550} **Recent lessons:**");for(const k of l){ne.add(k.topic);const E=k.outcome==="success"?"\u2705":k.outcome==="partial"?"\u26A0\uFE0F":"\u274C",A=k.severity==="critical"?"\u{1F534}":k.severity==="major"?"\u{1F7E1}":"",_=st(k);e.push(` ${E}${A} \`${k.topic}\` \u2014 ${_[0]??""}`,..._.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some(k=>k.author)||(e.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Y=await Un(n,i);if(Y.length>0){e.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const l of Y.slice(0,3))e.push(` \`${l.neu}\` \u2248 \`${l.alt}\` (${l.naehe.toFixed(2)})`);e.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),e.push("")}const ee=r;if(ee?.decision_log?.length){const l=ee.decision_log,k=l.filter((_,x)=>!ne.has(_.topic)&&l.findIndex(H=>H.topic===_.topic)===x),E=k.filter(_=>_.outcome==="success"),A=k.filter(_=>_.outcome==="failure");if(E.length>0||A.length>0){e.push(`\u{1F3AC} **Last session decisions** (${l.length} lessons stored):`),E.length>0&&e.push(` \u2705 Worked: ${E.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),A.length>0&&e.push(` \u274C Failed: ${A.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),e.push("");for(const _ of[...E.slice(0,3),...A.slice(0,3)])ne.add(_.topic)}}{const l=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"]),k=x=>{const H=new Set;for(const F of x)for(const J of F.toLowerCase().split(/[/\\._-]/))J.length>3&&!l.has(J)&&H.add(J);return[...H]};let E=c,A=o,_=!1;if(E.length===0&&r){const x=k(r.files_changed??[]),H=(r.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(F=>F.length>3&&!l.has(F));E=[...new Set([...x,...H])],A="where you left off last session",_=!0}if(E.length>0){const x=i.filter(H=>{if(H.outcome==="success")return!1;const F=H.topic.split(":")[0];return E.some(J=>H.topic.toLowerCase().includes(J)||F===J||(H.tags??[]).some(z=>z.toLowerCase()===J))});if(x.length>=1){const F=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",_?` You're likely to continue **${A}** \u2014 ${x.length} known pitfall${x.length>1?"s":""} there:`:` Known pitfalls for **"${A}"** (${x.length} past failure${x.length>1?"s":""}):`,...x.slice(0,3).map(J=>` \u274C \`${J.topic}\` \u2014 ${(J.what_failed??J.what_worked).slice(0,80)}`),""];e.splice(2,0,...F)}}}if(u){const l=Date.now()-6048e5,k=i.filter(E=>E.author&&E.author!==u&&new Date(E.ts).getTime()>l&&!ne.has(E.topic));if(k.length>0){const E=new Map;for(const A of k){const _=A.author;E.has(_)||E.set(_,[]),E.get(_).push(A)}e.push(`\u{1F465} **Team this week** (${k.length} lesson${k.length>1?"s":""} from teammates):`);for(const[A,_]of E){e.push(` \u{1F464} **${A}**:`);for(const x of _.slice(0,3)){const H=x.outcome==="success"?"\u2705":x.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${H} \`${x.topic}\` \u2014 ${x.what_worked.slice(0,80)}`),ne.add(x.topic)}_.length>3&&e.push(` \u2026 and ${_.length-3} more`)}e.push("")}}try{const l=await n.get("cachly:crystal:latest");if(l){const k=W(l,null);if(k&&Math.round((Date.now()-new Date(k.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${k.label} \xB7 ${k.session_count} sessions compressed):`);for(const A of k.top_patterns.slice(0,3))e.push(` \u2022 **${A.category}** (${A.count}\xD7): ${A.insight.slice(0,90)}`);e.push("")}}}catch{}try{const l=await n.hgetall(`cachly:roadmap:${h}`);if(l&&Object.keys(l).length>0){const k={critical:0,high:1,medium:2,low:3},E={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},A=new Set(["planned","in-progress","blocked"]),_=Object.values(l).flatMap(F=>{const J=W(F,null);return J?[J]:[]}),x=_.filter(F=>A.has(F.status)).sort((F,J)=>F.status==="in-progress"&&J.status!=="in-progress"?-1:J.status==="in-progress"&&F.status!=="in-progress"?1:(k[F.priority]??99)-(k[J.priority]??99)),H=_.filter(F=>F.status==="done").length;if(x.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${x.length} open \xB7 ${H} done):`);for(const F of x.slice(0,5)){const J=F.status==="in-progress"?"\u26A1":F.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${J} ${E[F.priority]??"\u26AA"} \`${F.id}\` **${F.title}**`)}x.length>5&&e.push(` \u2026 and ${x.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}try{const l=await n.get("cachly:mcm:calibration:last"),k=W(l,null)?.ts??0;if((Date.now()-k)/864e5>=30&&i.length>=5){const A=i.filter(x=>x.outcome==="success"&&(x.recall_count??0)>0),_=i.filter(x=>(x.recall_count??0)>0);if(_.length>=3){const x=_.length>0?A.length/_.length:1,H=[],F=new Map;for(const J of _){const z=J.topic.split(":")[0]??"other";F.has(z)||F.set(z,{success:0,total:0});const le=F.get(z);le.total++,J.outcome==="success"&&le.success++}for(const[J,z]of F)z.total>=2&&z.success/z.total<.6&&H.push(J);await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:x,recalled:_.length,low_precision_domains:H})),(H.length>0||x<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${_.length} recalled lessons):`),e.push(` Overall precision: **${(x*100).toFixed(0)}%** recalled lessons actually worked`),H.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${H.map(J=>`\`${J}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const V=i.filter(l=>l.outcome==="failure"||l.outcome==="partial").length,te=i.filter(l=>l.outcome==="success"&&Mt(l)<Ss).length;if(i.length===0||V>0||te>0){const l=[];i.length===0&&l.push("brain is empty"),V>0&&l.push(`${V} open failure${V>1?"s":""}`),te>0&&l.push(`${te} stale lesson${te>1?"s":""}`),e.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${l.join(", ")}._`)}try{if(await n.get(`cachly:prefs:auto_changelog:${h}`).catch(()=>null)!=="false"&&r?.ts&&!ie){const E=new Date(r.ts).getTime();if(!Number.isNaN(E)){const A=i.filter(x=>{const H=new Date(x.ts).getTime();return!Number.isNaN(H)&&H>E}),_=A.filter(x=>!ne.has(x.topic));if(_.length>0){const x=Math.round((Date.now()-E)/6e4),H=x<60?`${x}m`:x<1440?`${Math.round(x/60)}h`:`${Math.round(x/1440)}d`,F=A.length-_.length;e.push(""),e.push(`\u{1F4CB} **${A.length} new lesson${A.length!==1?"s":""} since your last session** (${H} ago${F>0?`, ${F} already listed above`:""}):`);const J=new Map;for(const z of _.slice(0,20)){const le=z.topic.includes(":")?z.topic.split(":")[0]:"general",ge=J.get(le)??[];ge.push(z),J.set(le,ge)}for(const[z,le]of J){e.push(` **${z}**`);for(const ge of le){const ue=ge.outcome==="failure"?"\u274C":ge.severity==="critical"?"\u{1F6A8}":ge.severity==="major"?"\u26A0\uFE0F":"\u2705",se=(ge.outcome==="failure"?ge.what_failed:ge.what_worked)??"";e.push(` ${ue} \`${ge.topic}\`${se?` \u2014 ${se.slice(0,80)}`:""}`)}}_.length>20&&e.push(` \u2026 and ${_.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${h}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
36
- `)}case"session_start_summary":{const{instance_id:h,focus:o,top_n:u=10,author:p=""}=N;if(!o||!o.trim())throw new Error("focus is required for session_start_summary");const a=Math.min(Math.max(1,Math.floor(Number(u)||10)),25),n=await L(h),v=[],d=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,Z)=>{d.on("data",ce=>v.push(...ce)),d.on("end",e),d.on("error",Z)});const i=[];if(v.length>0){const e=await n.mget(...v);for(const Z of e){const ce=W(Z??null,null);ce&&!as(ce)&&!ls(ce.topic)&&i.push(ce)}}if(i.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="${h}")\` to bootstrap with 16 universal lessons.`].join(`
37
- `);const S=i.length>a,t=o.toLowerCase().split(/\s+/).filter(Boolean),s=Date.now(),C=i.map(e=>{const Z=t.filter(V=>e.topic.toLowerCase().includes(V)).length,ce=t.filter(V=>(e.tags??[]).some(te=>te.toLowerCase().includes(V))).length,ie=Z*2+ce,he=Math.max(0,e.recall_count??0),ne=Math.min(1.5,Math.log1p(he)/10),g=e.severity==="critical"?1:e.severity==="major"?.5:0,K=(s-new Date(e.verified_at??e.ts).getTime())/864e5,Q=K<30?.5*(1-K/30):0,Y=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,ee=ie+ne+g+Q+Y;return{lesson:e,score:ee}});C.sort((e,Z)=>Z.score!==e.score?Z.score-e.score:new Date(Z.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const r=(S?C.slice(0,a):C).map(e=>e.lesson),c=i.length,$=r.length,M=[S?`\u{1F9E0} Brain Summary \u2014 top ${$} of ${c} lessons for "${o}"`:`\u{1F9E0} Brain Summary \u2014 all ${$} lesson${$!==1?"s":""} for "${o}"`,"\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 r){const Z=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",ce=e.severity?`[${e.severity}] `:"[minor] ",ie=e.recall_count??0,he=ie>0?` (in ${ie} answer${ie===1?"":"s"})`:"",ne=e.what_worked.slice(0,110),g=So(e.author,p);M.push(`${Z} ${ce}\`${e.topic}\` \u2014 ${ne}${he}${g}`)}M.push("");const I=Co(r,p);return I>0&&M.push(`\u{1F465} ${I} of these ${I===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),S?M.push(`\u{1F4A1} Showing top ${$} of ${c} lessons \xB7 \`session_start\` for full briefing`):M.push(`\u{1F4A1} All ${$} lesson${$!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),M.join(`
38
- `)}case"session_end":{const{instance_id:h,summary:o,files_changed:u=[],lessons_learned:p,workspace_path:a=""}=N,n=Pe({summary:o,files_changed:u}),v=n.felder.summary,d=n.felder.files_changed,i=await L(h),S=new Date;let t;const s=await i.get("cachly:session:current");if(!s)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 C=W(s,null);C?.started&&(t=Math.round((S.getTime()-new Date(C.started).getTime())/6e4));let r=[];try{r=(await i.lrange("cachly:session:decision-log",0,-1)).flatMap(he=>{const ne=W(he,null);return ne?[ne]:[]}),await i.del("cachly:session:decision-log")}catch{}const c=Qn(h);eo(h);const $={ts:S.toISOString(),summary:v,files_changed:d,...c.recalls>0?{memory_cost:c}:{},...n.verdacht.length?{verdacht:n.verdacht}:{},...p!==void 0?{lessons_learned:p}:{},...t!==void 0?{duration_min:t}:{},...r.length>0?{decision_log:r}:{}};await i.set("cachly:session:last",JSON.stringify($)),await i.lpush("cachly:session:history",JSON.stringify($)),await i.ltrim("cachly:session:history",0,49),await i.expire("cachly:session:history",90*86400),await i.del("cachly:session:current");const m=[];try{const ie=/\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,he=v.split(/[.!\n]+/).map(ne=>ne.trim()).filter(ne=>ne.length>20&&ie.test(ne));for(const ne of he.slice(0,6)){const K=ne.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(te=>te.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(te)).slice(0,4).join("-");if(!K)continue;const Q=`auto:${K}`,Y=`cachly:lesson:best:${Q}`,ee=await i.get(Y);if(ee)try{if(JSON.parse(ee).outcome==="success")continue}catch{}const V={topic:Q,outcome:"success",what_worked:ne,context:`Auto-learned from session summary. Full summary: ${v.slice(0,300)}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,session_ts:S.toISOString(),version:2,...n.verdacht.length?{tags:[Ct]}:{}};await i.set(Y,JSON.stringify(V)),await i.expire(Y,90*86400),m.push(Q)}}catch{}const w=[],M=ht(a);let I=0,e=0;if(M)try{const he=`--since=${(s?(()=>{try{return JSON.parse(s).started??""}catch{return""}})():"")||"1 hour ago"}`,ne=Fe(M,["log",he,"--oneline","--format=%H|||%s|||%b|||%ai|||ENDE"]).trim();if(ne){const g=/\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,K=ne.split("|||ENDE").map(Q=>Q.trim()).filter(Boolean);for(const Q of K.slice(0,10)){const[Y,ee,V,te]=Q.split("|||"),l=Pe({msg:ee??"",body:V??""}),k=l.felder.msg,E=l.felder.body;if($s(Y))try{const z=Fe(M,["diff-tree","--no-commit-id","--name-only","-r","--root",Y]).trim(),ge=z?z.split(`
39
- `).map(se=>se.trim()).filter(Boolean).slice(0,12):[],ue=[];for(const se of ge)ue.push(await Rt(i,se));for(let se=0;se<ue.length;se++)for(let we=se+1;we<ue.length;we++)await ve(i,ue[se],"co-occurs",ue[we],!0),await ve(i,ue[we],"co-occurs",ue[se],!0)}catch{}if(!k||!g.test(k))continue;const A=(E??"").trim();if(A.length<120)continue;const _=k.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(!_)continue;const x=`git:${_}`,H=`cachly:lesson:best:${x}`;if(await i.get(H))continue;const J={topic:x,outcome:"success",what_worked:`${k}
33
+ `)}case"session_start":{const{instance_id:u,focus:o="",author:d="",provider:p="",workspace_path:a=""}=T;if(await Gt(u,X))return L(u).then(async l=>{await ms(l),await ws(l,o,p),await l.set("cachly:mcp:version:last_seen",st,"EX",365*86400)}).catch(()=>{}),be("session_start: neues Brain startet noch \u2014 sofort geantwortet"),sn({instanzId:u,provider:p,...await bt(u)});const n=await L(u),v=[],f=n.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((l,$)=>{f.on("data",N=>v.push(...N)),f.on("end",l),f.on("error",$)});const i=[];let S=0;if(v.length>0){const l=await n.mget(...v);for(const $ of l){const N=j($??null,null);if(N){if(is(N)){S++;continue}us(N.topic)||i.push(N)}}}i.sort((l,$)=>new Date($.ts).getTime()-new Date(l.ts).getTime());let t=0;const s=n.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((l,$)=>{s.on("data",N=>{t+=N.filter(E=>!E.endsWith(":meta")).length}),s.on("end",l),s.on("error",$)});const C=await n.get("cachly:session:last"),r=j(C,null),c=o.toLowerCase().split(/\s+/).filter(Boolean),b=c.length>0?i.filter(l=>c.some($=>l.topic.toLowerCase().includes($)||(l.tags??[]).some(N=>N.toLowerCase().includes($)))):[],{tage:m,rekord:w}=await ms(n);let I="";m>=7?I=`\u{1F525} **${m}-day streak!** ${m===w?" New record!":`Best: ${w}d`}`:m>1&&(I=`\u{1F525} ${m}-day streak`),await ws(n,o,p);const e=[`\u{1F9E0} **Session Briefing**${p?` \xB7 ${p}`:""}`,""];I&&e.push(I,"");const Z=await ys(u,X),le=ro({used:Z.used,limit:Z.limit});if(le&&e.push(le,""),Z.notice&&!fs.has(u)&&(fs.add(u),e.push(Z.notice,"")),r?.ts){const l=new Date(r.ts).getTime(),$=Math.floor((Date.now()-l)/864e5);if($>=7&&!Number.isNaN(l)){const N=i.filter(E=>{const _=new Date(E.ts).getTime();return!Number.isNaN(_)&&_>l});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${$} days since your last session.`),N.length>0){const E=N.slice(0,3).map(_=>`\`${_.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${N.length} lesson${N.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${E}${N.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${i.length} lesson${i.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 n.get("cachly:mcp:version:last_seen")!==st){await n.set("cachly:mcp:version:last_seen",st,"EX",365*86400);const $=Po[st];if($){e.push(...$,"");const N=zo();N&&e.push(`\u{1F4CA} ${N} MCP tools`,"")}}}catch{}const re=!r&&i.length===0&&S===0&&t===0;re&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),a?(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="${u}")\``),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(""));const ue=b.slice(0,4),ne=new Set(ue.map(l=>l.topic));if(d&&!re)try{const l=`cachly:team:first_briefing:${d}`;if(!await n.get(l)){const N=i.filter(E=>E.author&&E.author!==d&&!ne.has(E.topic));if(N.length>0){await n.set(l,"1","EX",365*86400);const E=new Map;for(const _ of N){const x=_.author;E.has(x)||E.set(x,[]),E.get(x).push(_)}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[_,x]of E){e.push(` \u{1F464} **${_}** fixed ${x.length} thing${x.length>1?"s":""}:`);for(const H of x.slice(0,2)){const W=H.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${W} \`${H.topic}\` \u2014 ${H.what_worked.slice(0,90)}`),ne.add(H.topic)}x.length>2&&e.push(` \u2026 and ${x.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 g=await n.get("cachly:session:handoff");if(g)try{const l=JSON.parse(g),$=Math.round((Date.now()-new Date(l.ts).getTime())/6e4),N=$<60?`${$}m ago`:$<1440?`${Math.round($/60)}h ago`:`${Math.round($/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${N}):`),l.context_summary&&e.push(` ${l.context_summary}`),l.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const _ of l.remaining_tasks)e.push(` - ${_}`)}l.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${l.completed_tasks.join(", ")}`);const E=(l.files_changed??[]).filter(_=>_.status==="broken"||_.status==="partial");E.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${E.map(_=>`\`${_.path}\` (${_.status}${_.description?": "+_.description:""})`).join(", ")}`),l.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${l.blocked_on}`),l.instructions&&e.push(` \u{1F4DD} **Instructions:** ${l.instructions}`),e.push("")}catch{}const V=await n.get("cachly:session:checkpoint");if(V)try{const l=JSON.parse(V),$=new Date(l.ts).getTime(),N=r?new Date(r.ts).getTime():0;if($>N){const E=Math.round((Date.now()-$)/6e4),_=E<60?`${E}m ago`:E<1440?`${Math.round(E/60)}h ago`:`${Math.round(E/1440)}d ago`,x=l.provider?` [${l.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${x} (${_}): ${l.task}`),l.files_touched.length>0&&e.push(` Files: ${l.files_touched.slice(0,5).map(H=>`\`${H}\``).join(", ")}`),l.next_step&&e.push(` \u{1F4CD} Next step was: ${l.next_step}`),(!r||$-N>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}const Q=r?null:dt(a);if(Q)try{const l=Ge(Q,["log","--oneline","--format=%h %s","-15"]).trim();let $;try{$=Ge(Q,["diff","--stat","HEAD~3"]).trim()}catch{$=Ge(Q,["diff","--stat"]).trim()}if(l){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const N of l.split(`
34
+ `).slice(0,8))e.push(` ${N}`);if($){const N=$.split(`
35
+ `).filter(E=>E.includes("|")||E.includes("changed"));if(N.length>0){e.push(" **Recent changes:**");for(const E of N.slice(0,5))e.push(` ${E.trim()}`)}}e.push("")}}catch{}if(r){const l=Math.round((Date.now()-new Date(r.ts).getTime())/6e4),$=l<60?`${l}m ago`:l<1440?`${Math.round(l/60)}h ago`:`${Math.round(l/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${$}): ${r.summary}`),r.duration_min&&e.push(` Duration: ${r.duration_min} min`),(r.files_changed??[]).length>0&&e.push(` Files: ${(r.files_changed??[]).slice(0,5).map(N=>`\`${N}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${t} context entries`,""),S>0&&e.push(`\u26A0 ${S} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const $=await n.lrange(`cachly:wirkung:${u}`,0,-1).catch(()=>[]),N=Wn($.map(x=>j(x,null)).filter(Boolean)),E=x=>N.get(x)??{geholfen:0,geoeffnet:0},_=i.filter(x=>!Rs(x)).filter(x=>{if(x.outcome!=="success")return!1;const H=E(x.topic);return x.pinned===!0||H.geholfen>=1||H.geoeffnet>=2}).filter(x=>!ne.has(x.topic)).sort((x,H)=>{const W=E(x.topic),q=E(H.topic);return q.geholfen-W.geholfen||q.geoeffnet-W.geoeffnet||(H.recall_count??0)-(x.recall_count??0)}).slice(0,5);if(_.length>0){e.push("\u{1F4CC} **Confirmed lessons** (pinned, reported helpful, or opened after a search \u2014 being shown does not count):");for(const x of _){ne.add(x.topic);const H=x.severity==="critical"?"\u{1F534}":x.severity==="major"?"\u{1F7E1}":"",W=E(x.topic),q=[x.pinned===!0?"pinned":"",W.geholfen>0?`reported helpful ${W.geholfen}\xD7`:"",W.geoeffnet>0?`opened ${W.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),D=ot(x);e.push(` \u2705${H} \`${x.topic}\` _(${q})_ \u2014 ${D[0]??""}`,...D.slice(1))}e.push("")}}try{const l=[],$=n.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((N,E)=>{$.on("data",_=>l.push(..._)),$.on("end",N),$.on("error",E)}),l.length>0){e.push(`\u26A1 **Active belief conflicts (${l.length}):**`);for(const N of l.slice(0,3)){const E=await n.get(N);if(!E)continue;const _=j(E,null);_&&e.push(` \u26A0\uFE0F \`${_.topic}\` \u2014 previously confirmed fix (${(_.fix_confidence*100).toFixed(0)}%, n=${_.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${we(_.topic)}")\``)}e.push("")}}catch{}if(ue.length>0){e.push(`\u{1F3AF} **Relevant for "${o}":**`);for(const l of ue){const $=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",N=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",E=ot(l);e.push(` ${$}${N} \`${l.topic}\` \u2014 ${E[0]??""}`,...E.slice(1))}e.push("")}if(i.length>0){const l=(b.length>0?i.filter($=>!b.includes($)):i).filter($=>!ne.has($.topic)).slice(0,b.length>0?3:4);if(l.length>0){e.push("\u{1F550} **Recent lessons:**");for(const $ of l){ne.add($.topic);const N=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C",E=$.severity==="critical"?"\u{1F534}":$.severity==="major"?"\u{1F7E1}":"",_=ot($);e.push(` ${N}${E} \`${$.topic}\` \u2014 ${_[0]??""}`,..._.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some($=>$.author)||(e.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Y=await Yn(n,i);if(Y.length>0){e.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const l of Y.slice(0,3))e.push(` \`${l.neu}\` \u2248 \`${l.alt}\` (${l.naehe.toFixed(2)})`);e.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),e.push("")}const ee=r;if(ee?.decision_log?.length){const l=ee.decision_log,$=l.filter((_,x)=>!ne.has(_.topic)&&l.findIndex(H=>H.topic===_.topic)===x),N=$.filter(_=>_.outcome==="success"),E=$.filter(_=>_.outcome==="failure");if(N.length>0||E.length>0){e.push(`\u{1F3AC} **Last session decisions** (${l.length} lessons stored):`),N.length>0&&e.push(` \u2705 Worked: ${N.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),E.length>0&&e.push(` \u274C Failed: ${E.slice(0,3).map(_=>`\`${_.topic}\``).join(", ")}`),e.push("");for(const _ of[...N.slice(0,3),...E.slice(0,3)])ne.add(_.topic)}}{const l=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"]),$=x=>{const H=new Set;for(const W of x)for(const q of W.toLowerCase().split(/[/\\._-]/))q.length>3&&!l.has(q)&&H.add(q);return[...H]};let N=c,E=o,_=!1;if(N.length===0&&r){const x=$(r.files_changed??[]),H=(r.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(W=>W.length>3&&!l.has(W));N=[...new Set([...x,...H])],E="where you left off last session",_=!0}if(N.length>0){const x=i.filter(H=>{if(H.outcome==="success")return!1;const W=H.topic.split(":")[0];return N.some(q=>H.topic.toLowerCase().includes(q)||W===q||(H.tags??[]).some(D=>D.toLowerCase()===q))});if(x.length>=1){const W=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",_?` You're likely to continue **${E}** \u2014 ${x.length} known pitfall${x.length>1?"s":""} there:`:` Known pitfalls for **"${E}"** (${x.length} past failure${x.length>1?"s":""}):`,...x.slice(0,3).map(q=>` \u274C \`${q.topic}\` \u2014 ${(q.what_failed??q.what_worked).slice(0,80)}`),""];e.splice(2,0,...W)}}}if(d){const l=Date.now()-6048e5,$=i.filter(N=>N.author&&N.author!==d&&new Date(N.ts).getTime()>l&&!ne.has(N.topic));if($.length>0){const N=new Map;for(const E of $){const _=E.author;N.has(_)||N.set(_,[]),N.get(_).push(E)}e.push(`\u{1F465} **Team this week** (${$.length} lesson${$.length>1?"s":""} from teammates):`);for(const[E,_]of N){e.push(` \u{1F464} **${E}**:`);for(const x of _.slice(0,3)){const H=x.outcome==="success"?"\u2705":x.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${H} \`${x.topic}\` \u2014 ${x.what_worked.slice(0,80)}`),ne.add(x.topic)}_.length>3&&e.push(` \u2026 and ${_.length-3} more`)}e.push("")}}try{const l=await n.get("cachly:crystal:latest");if(l){const $=j(l,null);if($&&Math.round((Date.now()-new Date($.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${$.label} \xB7 ${$.session_count} sessions compressed):`);for(const E of $.top_patterns.slice(0,3))e.push(` \u2022 **${E.category}** (${E.count}\xD7): ${E.insight.slice(0,90)}`);e.push("")}}}catch{}try{const l=await n.hgetall(`cachly:roadmap:${u}`);if(l&&Object.keys(l).length>0){const $={critical:0,high:1,medium:2,low:3},N={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},E=new Set(["planned","in-progress","blocked"]),_=Object.values(l).flatMap(W=>{const q=j(W,null);return q?[q]:[]}),x=_.filter(W=>E.has(W.status)).sort((W,q)=>W.status==="in-progress"&&q.status!=="in-progress"?-1:q.status==="in-progress"&&W.status!=="in-progress"?1:($[W.priority]??99)-($[q.priority]??99)),H=_.filter(W=>W.status==="done").length;if(x.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${x.length} open \xB7 ${H} done):`);for(const W of x.slice(0,5)){const q=W.status==="in-progress"?"\u26A1":W.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${q} ${N[W.priority]??"\u26AA"} \`${W.id}\` **${W.title}**`)}x.length>5&&e.push(` \u2026 and ${x.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}try{const l=await n.get("cachly:mcm:calibration:last"),$=j(l,null)?.ts??0;if((Date.now()-$)/864e5>=30&&i.length>=5){const E=i.filter(x=>x.outcome==="success"&&(x.recall_count??0)>0),_=i.filter(x=>(x.recall_count??0)>0);if(_.length>=3){const x=_.length>0?E.length/_.length:1,H=[],W=new Map;for(const q of _){const D=q.topic.split(":")[0]??"other";W.has(D)||W.set(D,{success:0,total:0});const he=W.get(D);he.total++,q.outcome==="success"&&he.success++}for(const[q,D]of W)D.total>=2&&D.success/D.total<.6&&H.push(q);await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:x,recalled:_.length,low_precision_domains:H})),(H.length>0||x<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${_.length} recalled lessons):`),e.push(` Overall precision: **${(x*100).toFixed(0)}%** recalled lessons actually worked`),H.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${H.map(q=>`\`${q}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const J=i.filter(l=>l.outcome==="failure"||l.outcome==="partial").length,te=i.filter(l=>l.outcome==="success"&&Rt(l)<xs).length;if(i.length===0||J>0||te>0){const l=[];i.length===0&&l.push("brain is empty"),J>0&&l.push(`${J} open failure${J>1?"s":""}`),te>0&&l.push(`${te} stale lesson${te>1?"s":""}`),e.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${l.join(", ")}._`)}try{if(await n.get(`cachly:prefs:auto_changelog:${u}`).catch(()=>null)!=="false"&&r?.ts&&!re){const N=new Date(r.ts).getTime();if(!Number.isNaN(N)){const E=i.filter(x=>{const H=new Date(x.ts).getTime();return!Number.isNaN(H)&&H>N}),_=E.filter(x=>!ne.has(x.topic));if(_.length>0){const x=Math.round((Date.now()-N)/6e4),H=x<60?`${x}m`:x<1440?`${Math.round(x/60)}h`:`${Math.round(x/1440)}d`,W=E.length-_.length;e.push(""),e.push(`\u{1F4CB} **${E.length} new lesson${E.length!==1?"s":""} since your last session** (${H} ago${W>0?`, ${W} already listed above`:""}):`);const q=new Map;for(const D of _.slice(0,20)){const he=D.topic.includes(":")?D.topic.split(":")[0]:"general",me=q.get(he)??[];me.push(D),q.set(he,me)}for(const[D,he]of q){e.push(` **${D}**`);for(const me of he){const de=me.outcome==="failure"?"\u274C":me.severity==="critical"?"\u{1F6A8}":me.severity==="major"?"\u26A0\uFE0F":"\u2705",se=(me.outcome==="failure"?me.what_failed:me.what_worked)??"";e.push(` ${de} \`${me.topic}\`${se?` \u2014 ${se.slice(0,80)}`:""}`)}}_.length>20&&e.push(` \u2026 and ${_.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${u}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
36
+ `)}case"session_start_summary":{const{instance_id:u,focus:o,top_n:d=10,author:p=""}=T;if(!o||!o.trim())throw new Error("focus is required for session_start_summary");const a=Math.min(Math.max(1,Math.floor(Number(d)||10)),25),n=await L(u),v=[],f=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,Z)=>{f.on("data",le=>v.push(...le)),f.on("end",e),f.on("error",Z)});const i=[];if(v.length>0){const e=await n.mget(...v);for(const Z of e){const le=j(Z??null,null);le&&!is(le)&&!us(le.topic)&&i.push(le)}}if(i.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="${u}")\` to bootstrap with 16 universal lessons.`].join(`
37
+ `);const S=i.length>a,t=o.toLowerCase().split(/\s+/).filter(Boolean),s=Date.now(),C=i.map(e=>{const Z=t.filter(J=>e.topic.toLowerCase().includes(J)).length,le=t.filter(J=>(e.tags??[]).some(te=>te.toLowerCase().includes(J))).length,re=Z*2+le,ue=Math.max(0,e.recall_count??0),ne=Math.min(1.5,Math.log1p(ue)/10),g=e.severity==="critical"?1:e.severity==="major"?.5:0,V=(s-new Date(e.verified_at??e.ts).getTime())/864e5,Q=V<30?.5*(1-V/30):0,Y=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,ee=re+ne+g+Q+Y;return{lesson:e,score:ee}});C.sort((e,Z)=>Z.score!==e.score?Z.score-e.score:new Date(Z.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const r=(S?C.slice(0,a):C).map(e=>e.lesson),c=i.length,b=r.length,I=[S?`\u{1F9E0} Brain Summary \u2014 top ${b} of ${c} lessons for "${o}"`:`\u{1F9E0} Brain Summary \u2014 all ${b} lesson${b!==1?"s":""} for "${o}"`,"\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 r){const Z=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",le=e.severity?`[${e.severity}] `:"[minor] ",re=e.recall_count??0,ue=re>0?` (in ${re} answer${re===1?"":"s"})`:"",ne=e.what_worked.slice(0,110),g=xo(e.author,p);I.push(`${Z} ${le}\`${e.topic}\` \u2014 ${ne}${ue}${g}`)}I.push("");const A=To(r,p);return A>0&&I.push(`\u{1F465} ${A} of these ${A===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),S?I.push(`\u{1F4A1} Showing top ${b} of ${c} lessons \xB7 \`session_start\` for full briefing`):I.push(`\u{1F4A1} All ${b} lesson${b!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),I.join(`
38
+ `)}case"session_end":{const{instance_id:u,summary:o,files_changed:d=[],lessons_learned:p,workspace_path:a=""}=T,n=Fe({summary:o,files_changed:d}),v=n.felder.summary,f=n.felder.files_changed,i=await L(u),S=new Date;let t;const s=await i.get("cachly:session:current");if(!s)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 C=j(s,null);C?.started&&(t=Math.round((S.getTime()-new Date(C.started).getTime())/6e4));let r=[];try{r=(await i.lrange("cachly:session:decision-log",0,-1)).flatMap(ue=>{const ne=j(ue,null);return ne?[ne]:[]}),await i.del("cachly:session:decision-log")}catch{}const c=to(u);so(u);const b={ts:S.toISOString(),summary:v,files_changed:f,...c.recalls>0?{memory_cost:c}:{},...n.verdacht.length?{verdacht:n.verdacht}:{},...p!==void 0?{lessons_learned:p}:{},...t!==void 0?{duration_min:t}:{},...r.length>0?{decision_log:r}:{}};await i.set("cachly:session:last",JSON.stringify(b)),await i.lpush("cachly:session:history",JSON.stringify(b)),await i.ltrim("cachly:session:history",0,49),await i.expire("cachly:session:history",90*86400),await i.del("cachly:session:current");const m=[];try{const re=/\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,ue=v.split(/[.!\n]+/).map(ne=>ne.trim()).filter(ne=>ne.length>20&&re.test(ne));for(const ne of ue.slice(0,6)){const V=ne.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(te=>te.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(te)).slice(0,4).join("-");if(!V)continue;const Q=`auto:${V}`,Y=`cachly:lesson:best:${Q}`,ee=await i.get(Y);if(ee)try{if(JSON.parse(ee).outcome==="success")continue}catch{}const J={topic:Q,outcome:"success",what_worked:ne,context:`Auto-learned from session summary. Full summary: ${v.slice(0,300)}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,session_ts:S.toISOString(),version:2,...n.verdacht.length?{tags:[Tt]}:{}};await i.set(Y,JSON.stringify(J)),await i.expire(Y,90*86400),m.push(Q)}}catch{}const w=[],I=dt(a);let A=0,e=0;if(I)try{const ue=`--since=${(s?(()=>{try{return JSON.parse(s).started??""}catch{return""}})():"")||"1 hour ago"}`,ne=Ge(I,["log",ue,"--oneline","--format=%H|||%s|||%b|||%ai|||ENDE"]).trim();if(ne){const g=/\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,V=ne.split("|||ENDE").map(Q=>Q.trim()).filter(Boolean);for(const Q of V.slice(0,10)){const[Y,ee,J,te]=Q.split("|||"),l=Fe({msg:ee??"",body:J??""}),$=l.felder.msg,N=l.felder.body;if(vs(Y))try{const D=Ge(I,["diff-tree","--no-commit-id","--name-only","-r","--root",Y]).trim(),me=D?D.split(`
39
+ `).map(se=>se.trim()).filter(Boolean).slice(0,12):[],de=[];for(const se of me)de.push(await Lt(i,se));for(let se=0;se<de.length;se++)for(let ye=se+1;ye<de.length;ye++)await ve(i,de[se],"co-occurs",de[ye],!0),await ve(i,de[ye],"co-occurs",de[se],!0)}catch{}if(!$||!g.test($))continue;const E=(N??"").trim();if(E.length<120)continue;const _=$.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(!_)continue;const x=`git:${_}`,H=`cachly:lesson:best:${x}`;if(await i.get(H))continue;const q={topic:x,outcome:"success",what_worked:`${$}
40
40
 
41
- ${A.slice(0,1200)}`,context:`Auto-learned from git commit ${(Y??"").slice(0,7)} at ${te??""} in ${M}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3,...l.verdacht.length?{tags:[Ct]}:{}};await i.set(H,JSON.stringify(J)),await i.expire(H,60*86400),w.push(x),l.geschwaerzt.length&&I++,l.verdacht.length&&e++}}}catch{}const Z=t!==void 0?` \xB7 ${t} min`:"",ce=m.length+w.length;return[`\u2705 **Session saved**${Z}`,"",`\u{1F4CB} **Summary:** ${v}`,d.length>0?`\u{1F4C1} **Files changed:** ${d.map(ie=>`\`${ie}\``).join(", ")}`:"",p!==void 0?`\u{1F9E0} **Lessons stored:** ${p}`:"",...to(c),m.length>0?`\u{1F916} **Auto-learned:** ${m.length} lessons extracted from summary (${m.slice(0,3).map(ie=>`\`${ie}\``).join(", ")}${m.length>3?"\u2026":""})`:"",w.length>0?`\u{1F33F} **Ambient git learning:** ${w.length} commit${w.length>1?"s":""} auto-learned (${w.slice(0,3).map(ie=>`\`${ie}\``).join(", ")}${w.length>3?"\u2026":""})`:"",...je(n,"notiz"),...cs(I,e,`${w.length} git lessons`),ce>0?`\u{1F4DA} **Learned this session:** ${ce} lesson${ce>1?"s":""}`:"","",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(ie=>ie!=="").join(`
42
- `)}case"session_ping":{const{instance_id:h,task:o,files_touched:u=[],next_step:p="",provider:a=""}=N,n=Pe({task:o,files_touched:u,next_step:p,provider:a}),{task:v,files_touched:d,next_step:i,provider:S}=n.felder,t=await L(h),s={ts:new Date().toISOString(),task:v,files_touched:d,next_step:i,provider:S,...n.verdacht.length?{verdacht:n.verdacht}:{}};await t.set("cachly:session:checkpoint",JSON.stringify(s),"EX",86400*3),await t.lpush("cachly:session:checkpoint:log",JSON.stringify(s)),await t.ltrim("cachly:session:checkpoint:log",0,19);const C=S?` [${S}]`:"",r=d.length>0?` \xB7 ${d.length} file${d.length>1?"s":""} touched`:"",c=i?`
43
- \u{1F4CD} **Next step:** ${i}`:"";return[`\u{1F4CC} **Checkpoint saved**${C} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${v}${r}`,c,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...je(n,"notiz")].filter($=>$!=="").join(`
44
- `)}case"session_handoff":{const{instance_id:h,completed_tasks:o=[],remaining_tasks:u=[],files_changed:p=[],instructions:a="",context_summary:n="",blocked_on:v=""}=N,d=Pe({completed_tasks:o,remaining_tasks:u,files_changed:p,instructions:a,context_summary:n,blocked_on:v}),{completed_tasks:i,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:r}=d.felder,c=await L(h),m={ts:new Date().toISOString(),completed_tasks:i,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:r,...d.verdacht.length?{verdacht:d.verdacht}:{}};await c.set("cachly:session:handoff",JSON.stringify(m)),await c.lpush("cachly:session:handoff:history",JSON.stringify(m)),await c.ltrim("cachly:session:handoff:history",0,19);const w=i.length+S.length,M=w>0?Math.round(i.length/w*100):0,I=t.filter(e=>e.status==="broken"||e.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${i.length}/${w} tasks done (${M}%)`,"",i.length>0?`\u2705 **Completed:**
41
+ ${E.slice(0,1200)}`,context:`Auto-learned from git commit ${(Y??"").slice(0,7)} at ${te??""} in ${I}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3,...l.verdacht.length?{tags:[Tt]}:{}};await i.set(H,JSON.stringify(q)),await i.expire(H,60*86400),w.push(x),l.geschwaerzt.length&&A++,l.verdacht.length&&e++}}}catch{}const Z=t!==void 0?` \xB7 ${t} min`:"",le=m.length+w.length;return[`\u2705 **Session saved**${Z}`,"",`\u{1F4CB} **Summary:** ${v}`,f.length>0?`\u{1F4C1} **Files changed:** ${f.map(re=>`\`${re}\``).join(", ")}`:"",p!==void 0?`\u{1F9E0} **Lessons stored:** ${p}`:"",...no(c),m.length>0?`\u{1F916} **Auto-learned:** ${m.length} lessons extracted from summary (${m.slice(0,3).map(re=>`\`${re}\``).join(", ")}${m.length>3?"\u2026":""})`:"",w.length>0?`\u{1F33F} **Ambient git learning:** ${w.length} commit${w.length>1?"s":""} auto-learned (${w.slice(0,3).map(re=>`\`${re}\``).join(", ")}${w.length>3?"\u2026":""})`:"",...He(n,"notiz"),...hs(A,e,`${w.length} git lessons`),le>0?`\u{1F4DA} **Learned this session:** ${le} lesson${le>1?"s":""}`:"","",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(re=>re!=="").join(`
42
+ `)}case"session_ping":{const{instance_id:u,task:o,files_touched:d=[],next_step:p="",provider:a=""}=T,n=Fe({task:o,files_touched:d,next_step:p,provider:a}),{task:v,files_touched:f,next_step:i,provider:S}=n.felder,t=await L(u),s={ts:new Date().toISOString(),task:v,files_touched:f,next_step:i,provider:S,...n.verdacht.length?{verdacht:n.verdacht}:{}};await t.set("cachly:session:checkpoint",JSON.stringify(s),"EX",86400*3),await t.lpush("cachly:session:checkpoint:log",JSON.stringify(s)),await t.ltrim("cachly:session:checkpoint:log",0,19);const C=S?` [${S}]`:"",r=f.length>0?` \xB7 ${f.length} file${f.length>1?"s":""} touched`:"",c=i?`
43
+ \u{1F4CD} **Next step:** ${i}`:"";return[`\u{1F4CC} **Checkpoint saved**${C} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${v}${r}`,c,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...He(n,"notiz")].filter(b=>b!=="").join(`
44
+ `)}case"session_handoff":{const{instance_id:u,completed_tasks:o=[],remaining_tasks:d=[],files_changed:p=[],instructions:a="",context_summary:n="",blocked_on:v=""}=T,f=Fe({completed_tasks:o,remaining_tasks:d,files_changed:p,instructions:a,context_summary:n,blocked_on:v}),{completed_tasks:i,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:r}=f.felder,c=await L(u),m={ts:new Date().toISOString(),completed_tasks:i,remaining_tasks:S,files_changed:t,instructions:s,context_summary:C,blocked_on:r,...f.verdacht.length?{verdacht:f.verdacht}:{}};await c.set("cachly:session:handoff",JSON.stringify(m)),await c.lpush("cachly:session:handoff:history",JSON.stringify(m)),await c.ltrim("cachly:session:handoff:history",0,19);const w=i.length+S.length,I=w>0?Math.round(i.length/w*100):0,A=t.filter(e=>e.status==="broken"||e.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${i.length}/${w} tasks done (${I}%)`,"",i.length>0?`\u2705 **Completed:**
45
45
  ${i.map(e=>` - ${e}`).join(`
46
46
  `)}`:"",S.length>0?`
47
47
  \u23F3 **Remaining for next window:**
48
48
  ${S.map(e=>` - ${e}`).join(`
49
- `)}`:"",I.length>0?`
50
- \u26A0\uFE0F **Needs attention:** ${I.map(e=>`\`${e.path}\` (${e.status})`).join(", ")}`:"",r?`
49
+ `)}`:"",A.length>0?`
50
+ \u26A0\uFE0F **Needs attention:** ${A.map(e=>`\`${e.path}\` (${e.status})`).join(", ")}`:"",r?`
51
51
  \u{1F6AB} **Blocked on:** ${r}`:"",s?`
52
- \u{1F4DD} **Instructions:** ${s}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically.",...je(d,"notiz")].filter(e=>e!=="").join(`
53
- `)}case"auto_learn_session":{const{instance_id:h,observations:o}=N,u=await L(h),p=[],a=[];let n=0,v=0;for(const i of o){const S=Pe(i),t=S.felder,s=t.topic??t.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),C=s.includes(":")?s:`auto:${s}`,r=`cachly:lesson:best:${C}`,c=await u.get(r);if(c&&JSON.parse(c).outcome==="success"&&t.outcome!=="success"){a.push(C);continue}const $={topic:C,outcome:t.outcome,what_worked:t.outcome==="success"?t.action:t.details??t.action,what_failed:t.outcome==="failure"?t.action:void 0,context:t.details,severity:t.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2,...S.verdacht.length?{tags:[Ct]}:{}},m=JSON.stringify($);S.geschwaerzt.length&&n++,S.verdacht.length&&v++,await u.set(r,m);const w=`cachly:lessons:${C}`;await u.rpush(w,m),await u.ltrim(w,-100,-1),await u.expire(w,90*86400);try{const M=C.split(":")[0]??"auto",I=me(C);if(await He(u,I,M,M),t.outcome==="success"||t.outcome==="partial"){const e=t.details?ut(t.details):null;if(e){const Z=me(`problem:${e}`);await He(u,Z,"problem","problem"),await ve(u,I,"fixes",Z,t.outcome==="success",t.outcome==="partial")}}}catch{}p.push(`${t.outcome==="success"?"\u2705":t.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${C}\``)}const d=[`\u{1F916} **Auto-learn complete**: ${p.length} stored, ${a.length} skipped`,""];return p.length>0&&d.push("**Stored:**",...p.map(i=>" "+i),""),a.length>0&&d.push(`**Skipped** (better lesson already exists): ${a.map(i=>`\`${i}\``).join(", ")}`),d.push(...cs(n,v,`${p.length} observations`)),d.join(`
54
- `)}case"brain_who_knows":{const{instance_id:h,topic:o,limit:u=10}=N;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const p=Math.max(1,Math.min(Number(u)||10,50)),a=await L(h),n=me(o),v=wt(o).filter(r=>r.length>=3).slice(0,5),d=new Set([n]);for(const r of v.slice(0,3)){const c=a.scanStream({match:`cachly:ckg:node:*${r}*`,count:30});await new Promise(($,m)=>{c.on("data",w=>{for(const M of w.slice(0,10)){const I=M.replace("cachly:ckg:node:","");!I.startsWith("person:")&&!I.startsWith("file:")&&d.add(I)}}),c.on("end",$),c.on("error",m)})}const i=new Map;for(const r of[...d].slice(0,25)){const c=await a.smembers(`cachly:ckg:idx:to:${r}`);for(const $ of c){const m=await a.get($);if(!m)continue;const w=W(m,null);if(!w||w.edgeType!=="authored")continue;const M=await a.get(`cachly:ckg:node:${w.from}`);if(!M)continue;const I=W(M,null);if(!I||I.type!=="person")continue;const e=i.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)):i.set(w.from,{handle:I.handle,lessonCount:1,totalConfidence:w.confidence,domains:new Set([I.domain]),lastActive:I.last_active??w.last_updated})}}if(i.size===0)return[`## \u{1F465} Who Knows About \`${o}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${o}", author="your-handle", ...)\``].join(`
55
- `);const S=[...i.entries()].map(([r,c])=>({id:r,handle:c.handle,lessonCount:c.lessonCount,avgConfidence:c.totalConfidence/c.lessonCount,domains:[...c.domains].slice(0,3).join(", "),lastActive:c.lastActive})).sort((r,c)=>c.lessonCount*c.avgConfidence-r.lessonCount*r.avgConfidence).slice(0,p),t=[],s=S[0];if(s)try{const r=await a.smembers(`cachly:ckg:idx:from:${s.id}`),c=[];for(const $ of r){const m=await a.get($);if(!m)continue;const w=W(m,null);if(!w||w.edgeType!=="collaborates")continue;const M=await a.get(`cachly:ckg:node:${w.to}`),I=M?W(M,null):null;I?.handle&&c.push({handle:I.handle,trials:w.trials})}c.sort(($,m)=>m.trials-$.trials);for(const $ of c.slice(0,3))t.push($.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${o}\`?`,"",`**${S.length}** contributor${S.length!==1?"s":""} with relevant lessons:`,""];for(const[r,c]of S.entries()){const $=r===0?"\u{1F947}":r===1?"\u{1F948}":r===2?"\u{1F949}":`${r+1}.`,m=(c.avgConfidence*100).toFixed(0),w=Math.floor((Date.now()-new Date(c.lastActive).getTime())/864e5),M=w<1?"today":w<7?`${w}d ago`:w<30?`${Math.floor(w/7)}w ago`:`${Math.floor(w/30)}mo ago`,I=await at(a,h,c.handle).catch(()=>null),e=I?` ${Vs[I]}`:"";C.push(`${$} **${c.handle}**${e} \u2014 ${c.lessonCount} lesson${c.lessonCount!==1?"s":""} \xB7 ${m}% confidence \xB7 last active ${M}`,` _domains: ${c.domains}_`,"")}return t.length>0&&s&&C.push(`\u{1F91D} **${s.handle}** frequently works with: ${t.map(r=>`**${r}**`).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(`
56
- `)}case"brain_file_map":{const{instance_id:h,file_paths:o=[]}=N,u=(Array.isArray(o)?o:[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());if(!u.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const p=await L(h),a=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const n of u.slice(0,10)){a.push(`### \`${n}\``);const v=`file:${me(n)}`,d=await p.smembers(`cachly:ckg:idx:to:${v}`),i=[];for(const C of d){const r=await p.get(C);if(!r)continue;const c=W(r,null);if(!c||c.edgeType!=="touched")continue;const $=await p.get(`cachly:ckg:node:${c.from}`);if(!$)continue;const m=W($,null);!m||m.type!=="person"||i.push({handle:m.handle,touches:c.trials,lastSeen:c.last_updated})}if(i.sort((C,r)=>r.touches-C.touches),i.length>0){const C=i.slice(0,5).map((r,c)=>{const $=c===0?"\u{1F947}":c===1?"\u{1F948}":c===2?"\u{1F949}":`${c+1}.`,m=Math.floor((Date.now()-new Date(r.lastSeen).getTime())/864e5),w=m<1?"today":m<7?`${m}d ago`:`${Math.floor(m/7)}w ago`;return`${$} **${r.handle}** (${r.touches}\xD7 \xB7 ${w})`}).join(" \xB7 ");a.push(`**Experts:** ${C}`)}else a.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const t=n.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),s=[];if(t)try{const C=await it(p,["cachly:lesson:best:*"],t,4);for(const r of C){const c=De(r.content);if(!Ge(c))continue;const $=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=c.severity==="critical"?" \u{1F534}":c.severity==="major"?" \u{1F7E1}":"",w=c.author?` \xB7 \u{1F464} ${c.author}`:"",M=r.key.replace("cachly:lesson:best:","");s.push(` - ${$} \`${M}\`${m}${w} \u2014 ${(c.what_worked??"").slice(0,100)}`)}}catch{}if(s.length<2){const C=await Me(p,"cachly:lesson:best:*",{max:1500});for(const r of C.slice(0,300)){const c=await p.get(r);if(!c)continue;const $=De(c);if(!Ge($)||!($.file_paths??[]).includes(n))continue;const m=r.replace("cachly:lesson:best:","");if(s.some(e=>e.includes(`\`${m}\``)))continue;const w=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C",M=$.severity==="critical"?" \u{1F534}":$.severity==="major"?" \u{1F7E1}":"",I=$.author?` \xB7 \u{1F464} ${$.author}`:"";s.push(` - ${w} \`${m}\`${M}${I} \u2014 ${($.what_worked??"").slice(0,100)}`)}}s.length>0?(a.push("**Related lessons:**"),a.push(...s.slice(0,5))):a.push("**Related lessons:** _None yet_"),a.push("")}return a.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),a.join(`
57
- `)}case"team_expertise_map":{const{instance_id:h,top_n:o=20}=N,u=await L(h),p=await Me(u,"cachly:ckg:node:person:*",{max:2e3});if(p.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(`
58
- `);const a=[];for(const d of p){const i=await u.get(d);if(!i)continue;const S=W(i,null);if(!S||S.type!=="person")continue;const t=await u.smembers(`cachly:ckg:idx:from:${S.id}`),s=new Map;let C=0;for(const r of t){const c=await u.get(r);if(!c)continue;const $=W(c,null);if(!$||$.edgeType!=="authored")continue;C++;const m=$.to.split(":")[0]??"unknown";s.set(m,(s.get(m)??0)+1)}a.push({handle:S.handle,lessonCount:C,domains:s,lastActive:S.last_active})}a.sort((d,i)=>i.lessonCount-d.lessonCount);const n=a.slice(0,o),v=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${n.length}** contributor${n.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[d,i]of n.entries()){const S=d===0?"\u{1F947}":d===1?"\u{1F948}":d===2?"\u{1F949}":`${d+1}`,t=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),s=t<1?"today":t<7?`${t}d ago`:t<30?`${Math.floor(t/7)}w ago`:`${Math.floor(t/30)}mo ago`,C=[...i.domains.entries()].sort((r,c)=>c[1]-r[1]).slice(0,3).map(([r,c])=>`${r}(${c})`).join(", ")||"\u2014";v.push(`| ${S} | **${i.handle}** | ${i.lessonCount} | ${C} | ${s} |`)}return v.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),v.join(`
59
- `)}case"skill_gaps":{const{instance_id:h,min_failures:o=1}=N,u=await L(h),p=await Me(u,"cachly:lesson:best:*",{max:3e3}),a=new Map;let n=0,v=0;for(const S of p){const t=await u.get(S);if(!t)continue;const s=De(t);if(s===null)continue;const C=(s.topic??"").split(":")[0]??"unknown",r=a.get(C)??{successes:0,failures:0,attributed:0,topics:[]};s.outcome==="success"||s.outcome==="partial"?r.successes++:r.failures++,s.author&&(r.attributed++,n++),s.visibility==="private"&&v++,r.topics.push(s.topic??""),a.set(C,r)}const d=[];for(const[S,t]of a)t.failures>=o&&t.successes===0&&d.push({domain:S,type:"unresolved failures",severity:t.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${t.failures} failure${t.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),t.successes+t.failures>=3&&t.attributed===0&&d.push({domain:S,type:"no attribution",severity:"\u{1F535} info",detail:`${t.successes+t.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const i=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${p.length}** lessons scanned \xB7 **${n}** attributed \xB7 **${d.length}** gap${d.length!==1?"s":""} found`,v>0?`_(${v} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(d.length===0)i.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const S=[...d.filter(t=>t.severity.includes("critical")),...d.filter(t=>t.severity.includes("warn")),...d.filter(t=>t.severity.includes("info"))];for(const t of S.slice(0,15))i.push(`${t.severity} **\`${t.domain}\`** \u2014 ${t.type}`),i.push(` ${t.detail}`),i.push("");d.length>15&&i.push(`_\u2026and ${d.length-15} more gaps. Fix critical ones first._`)}return i.push("---",`_Fix gaps with \`learn_from_attempts(topic="${d[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),i.join(`
60
- `)}case"brain_coverage":{const{instance_id:h,repo_path:o="."}=N,u=await L(h),[p,a,n]=await Promise.all([Me(u,"cachly:lesson:best:*",{max:5e3}),Me(u,"cachly:ckg:node:person:*",{max:2e3}),Me(u,"cachly:ckg:node:file:*",{max:5e3})]);let v=0,d="n/a";try{const m=ht(o);if(!m)throw new Error("repo_path ist kein Ordner");v=Fe(m,["ls-files"],{timeoutMs:3e4}).trim().split(`
61
- `).filter(Boolean).length,d=String(v)}catch{}let i=0,S=0,t=0;const s=new Set;for(const m of p){const w=await u.get(m);if(!w)continue;const M=W(w,{});M.outcome==="success"||M.outcome==="partial"?i++:S++,M.author&&t++,s.add((M.topic??"").split(":")[0]??"unknown")}const C=v>0?`${Math.round(n.length/v*100)}% (${n.length}/${v} files)`:`${n.length} files tracked`,r=p.length>0?Math.round(t/p.length*100):0,c=Math.round(Math.min(1,p.length/50)*25+Math.min(1,i/Math.max(1,p.length))*25+Math.min(1,r/100)*25+Math.min(1,a.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${c>=80?"\u{1F7E2}":c>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${c}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${p.length}** (${i} success \xB7 ${S} failure) |`,`| Problem domains | **${s.size}** |`,`| Attribution | **${t}/${p.length}** (${r}%) |`,`| Contributors | **${a.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,p.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,i/Math.max(1,p.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,r/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,a.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(`
62
- `)}case"brain_metrics":{const{instance_id:h}=N,o=await L(h),[u,p,a,n,v,d]=await Promise.all([o.get(`cachly:stats:born_at:${h}`).catch(()=>null),o.get(`cachly:stats:first_recall_at:${h}`).catch(()=>null),o.get(`cachly:stats:recalls_total:${h}`).catch(()=>null),o.get(`cachly:stats:cross_author_recalls:${h}`).catch(()=>null),o.get(`cachly:stats:time_saved_mins:${h}`).catch(()=>null),o.smembers(`cachly:stats:reuse_pairs:${h}`).catch(()=>[])]);let i={};try{i=await o.hgetall(ds(h))??{}}catch{i={}}let S={};try{S=await o.hgetall(Jt(h))??{}}catch{S={}}const t={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const g=await o.lrange(Vt(h),0,499),K=new Map;for(const Q of g){const Y=W(Q,{ts:"",themen:[]});if(!(!Y.ts||!Array.isArray(Y.themen)))for(const ee of Y.themen){if(t.lieferungen++,!K.has(ee)){const te=await o.get(`cachly:lesson:best:${ee}`).catch(()=>null);K.set(ee,te?W(te,{}):null)}const V=$n(Y.ts,K.get(ee)??null);if(V.length===0){t.ohneEreignis++;continue}for(const te of V)t[te]++}}}catch{}let s=0,C=0;try{const g=await o.lrange(`cachly:wirkung:${h}`,0,-1);for(const K of g){const Q=W(K,{});C++,Q.geholfen===!0&&s++}}catch{}let r={};try{r=await o.hgetall(lo(h))??{}}catch{r={}}const c=ho(r,10);let $={token:0,abrufe:0,treffer:0};try{const g=await o.get(po(h)),K=await o.hgetall(go(h))??{};$={token:g??0,abrufe:K.abrufe??0,treffer:K.treffer??0}}catch{}const m=fo($);let w;if(u&&p){const g=new Date(p).getTime()-new Date(u).getTime(),K=Math.max(0,Math.round(g/6e4)),Q=K<1?"<1 min":K<60?`${K} min`:`${(K/60).toFixed(1)} h`,Y=g<=2*6e4?"\u{1F7E2} under 2 min target":g<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";w=`**${Q}** from first lesson \u2192 first proven recall \xB7 ${Y}`}else u&&!p?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 M=["\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(`
63
- `),I=Number(a??0),e=Number(n??0),Z=I>0?Math.round(e/I*100):0,ce=Z>=30?"\u{1F7E2} above 30 % target":I===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",ie=Math.round(Number(v??0)),he=ie<60?`${ie} min`:`${(ie/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)_",M,"_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)_",`**${Z}%** of proven recalls used a teammate's lesson (${e}/${I}) \xB7 ${ce}`,d.length>0?`**${d.length}** distinct reuse relationship${d.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",uo(m),"",m.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${he} 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 ${he} \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 g=Number(i.beantwortet??0),K=Number(i.knapp??0),Q=Number(i.schweigen??0),Y=g+K+Q;if(Y===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const ee=V=>`${Math.round(100*V/Y)} %`;return`**${Y}** Suchen: ${ee(g)} beantwortet \xB7 ${ee(K)} als knapper Sieg markiert \xB7 ${ee(Q)} 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 g=ee=>Number(S[ee]??0),K=[["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)"]],Q=K.reduce((ee,[V])=>ee+g(V),0);if(Q===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const Y=K.filter(([ee])=>ee!=="ohne-vorwissen").sort((ee,V)=>g(V[0])-g(ee[0]))[0];return`**${Q}** klassifizierte Fehlschlaege: `+K.map(([ee,V])=>`${g(ee)} ${V}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${Y[1]}** (${g(Y[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)_",t.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${t.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${t.widersprochen} widersprochen \xB7 ${t.korrigiert} korrigiert \xB7 ${t.veraltet} veraltet \xB7 ${t.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 g=Number(t.widersprochen)+Number(t.veraltet);if(C===0&&g===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const K=s-g;return`**${K>=0?"+":""}${K}** = ${s} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${g} Schadenslieferungen (${t.widersprochen} spaeter widerlegt + ${t.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",co(c,ko.length),...c.spitze.length>0?c.spitze.map((g,K)=>` ${String(K+1).padStart(2)}. \`${g.name}\` \u2014 ${g.aufrufe}\xD7 (${Math.round(g.anteil*100)} %)`):[]].filter(Boolean).join(`
64
- `)}case"brain_service_map":{const{instance_id:h,service:o}=N;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const u=await L(h),p=`service:${me(o.trim())}`,a=await u.get(`cachly:ckg:node:${p}`).catch(()=>null),n=a?W(a,null):null,v=await u.smembers(`cachly:ckg:idx:to:${p}`).catch(()=>[]),d=[],i=[],S=[];for(const w of v){const M=await u.get(w).catch(()=>null);if(!M)continue;const I=W(M,null);if(I)if(I.edgeType==="operates"){const e=await u.get(`cachly:ckg:node:${I.from}`).catch(()=>null),Z=e?W(e,null):null;Z?.handle&&d.push({handle:Z.handle,trials:I.trials})}else if(I.edgeType==="runs_in"){const e=await u.get(`cachly:ckg:node:${I.from}`).catch(()=>null),Z=e?W(e,null):null;Z?.path&&i.push({path:Z.path,trials:I.trials})}else I.edgeType==="affects"&&S.push({id:I.from,confidence:I.confidence})}d.sort((w,M)=>M.trials-w.trials),i.sort((w,M)=>M.trials-w.trials),S.sort((w,M)=>M.confidence-w.confidence);const t=[],s=await Me(u,"cachly:lesson:best:*",{max:1500}),C=o.trim().toLowerCase();for(const w of s.slice(0,400)){const M=await u.get(w).catch(()=>null);if(!M)continue;const I=De(M);Ge(I)&&(I.service??"").toLowerCase()===C&&t.push({...I,topic:w.replace("cachly:lesson:best:","")})}if(!n&&t.length===0&&d.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${o}\``,"","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="${o}", author="you", file_paths=[...])\``].join(`
65
- `);const r=n?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${n?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${o}\``,"",n?`_${r} \xB7 ${n.count} lesson${n.count!==1?"s":""} referenced \xB7 domain: ${n.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(d.length>0){const w=d.slice(0,5).map((M,I)=>`${I===0?"\u{1F947}":I===1?"\u{1F948}":I===2?"\u{1F949}":`${I+1}.`} **${M.handle}** (${M.trials}\xD7)`).join(" \xB7 ");c.push(`**Operators:** ${w}`,"")}else c.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const $=t.filter(w=>w.outcome==="failure"),m=t.filter(w=>w.outcome!=="failure");if($.length>0){c.push(`**\u26A0\uFE0F Known failures (${$.length}):**`);for(const w of $.slice(0,6)){const M=w.severity==="critical"?" \u{1F534}":w.severity==="major"?" \u{1F7E1}":"",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";c.push(` - \u274C \`${w.topic}\`${M}${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}c.push("")}if(m.length>0){c.push(`**\u2705 Proven fixes (${m.length}):**`);for(const w of m.slice(0,6)){const M=w.outcome==="partial"?"\u26A0\uFE0F":"\u2705",I=w.author?` \xB7 \u{1F464} ${w.author}`:"";c.push(` - ${M} \`${w.topic}\`${I} \u2014 ${(w.what_worked??"").slice(0,100)}`)}c.push("")}return i.length>0&&c.push(`**Files in this service:** ${i.slice(0,8).map(w=>`\`${w.path}\``).join(", ")}`,""),c.push("---",`_Tag lessons with \`service="${o}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),c.join(`
66
- `)}case"brain_collab_pairs":{const{instance_id:h,min_weight:o=1}=N,u=await L(h),p=typeof o=="number"&&o>=1?Math.floor(o):1,a=await Me(u,"cachly:ckg:node:person:*",{max:500}),n=new Map;for(const s of a){const C=await u.get(s);if(!C)continue;const r=W(C,null);!r||r.type!=="person"||n.set(r.id,{id:r.id,handle:r.handle,domain:r.domain,count:r.count})}if(n.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(`
67
- `);const v=new Map;for(const[s,C]of n){const r=await u.smembers(`cachly:ckg:idx:from:${s}`);for(const c of r){const $=await u.get(c);if(!$)continue;const m=W($,null);if(!m||m.edgeType!=="collaborates")continue;const w=n.get(m.to);if(!w)continue;const[M,I]=s<m.to?[s,m.to]:[m.to,s],e=`${M}||${I}`,Z=v.get(e);if(Z)Z.trials+=m.trials;else{const[ce,ie]=s<m.to?[C,w]:[w,C];v.set(e,{a:ce,b:ie,trials:m.trials,confidence:m.confidence})}}}const d=[...v.values()].filter(s=>s.trials>=p).sort((s,C)=>C.trials-s.trials),i=new Set;for(const s of d)i.add(s.a.id),i.add(s.b.id);const S=[...n.values()].filter(s=>!i.has(s.id)),t=["## \u{1F91D} Team Collaboration Graph",""];if(d.length===0)t.push(`No collaboration pairs yet (min weight: ${p}).`,"","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{t.push(`**${d.length} collaboration pair${d.length!==1?"s":""}** across ${i.size} contributor${i.size!==1?"s":""}:`,"");for(const s of d.slice(0,20)){const C=(s.confidence*100).toFixed(0),r=[s.a.domain,s.b.domain].filter((c,$,m)=>c&&m.indexOf(c)===$).map(c=>`\`${c}\``).join(", ");t.push(`### @${s.a.handle} \u2194 @${s.b.handle}`,`- **${s.trials} collaboration event${s.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${r||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${s.a.handle}** und **@${s.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}d.length>20&&t.push(`_...and ${d.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return S.length>0&&t.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${S.length} contributor${S.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...S.slice(0,10).map(s=>`- **@${s.handle}** \u2014 ${s.count} lesson${s.count!==1?"s":""} \xB7 domain: \`${s.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),t.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),t.join(`
68
- `)}case"brain_portability":{const{instance_id:h}=N,o=[{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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}}},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:h}}]},null,2)}],u=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${h}\``,"","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 (${o.length} supported)`,""];for(const p of o)u.push(`#### ${p.icon} ${p.name}`,`Config: \`${p.configPath}\``,"","```json",p.configBlock,"```","");return u.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 \`${h}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),u.join(`
69
- `)}case"brain_changelog":{const{instance_id:h,days:o=7,max_lessons:u=30,include_failures:p=!0}=N,a=await L(h),n=Date.now()-Number(o)*864e5,v=await Me(a,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),d=[];for(const c of v){const $=await a.get(c).catch(()=>null);if(!$)continue;const m=W($,{});if((m.ts?new Date(m.ts).getTime():0)<n||!p&&m.outcome==="failure")continue;const M=c.replace("cachly:lesson:best:","");d.push({...m,topic:M})}d.sort((c,$)=>{const m=c.ts?new Date(c.ts).getTime():0;return($.ts?new Date($.ts).getTime():0)-m});const i=d.slice(0,Number(u));if(i.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${o} day${Number(o)!==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(`
70
- `);const S=new Map;for(const c of i){const $=c.topic.includes(":")?c.topic.split(":")[0]:"general",m=S.get($)??[];m.push(c),S.set($,m)}const t=c=>c==="critical"?"\u{1F6A8}":c==="major"?"\u26A0\uFE0F":c==="minor"?"\u{1F4A1}":"\u2728",s=c=>c==="failure"?"\u274C":c==="partial"?"\u{1F536}":"\u2705",r=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${o} day${Number(o)!==1?"s":""})`,"",`_${i.length} lesson${i.length!==1?"s":""} learned across ${S.size} topic area${S.size!==1?"s":""}_`,""];for(const[c,$]of Array.from(S.entries()).sort((m,w)=>w[1].length-m[1].length)){r.push(`### ${c}`),r.push("");for(const m of $){const w=m.outcome==="failure"?s(m.outcome):t(m.severity),M=m.outcome==="failure"?m.what_failed:m.what_worked,I=[];m.author&&I.push(`by **${m.author}**`),m.recall_count&&I.push(`${m.recall_count} recall${m.recall_count!==1?"s":""}`),m.confidence!==void 0&&I.push(`${Math.round(m.confidence*100)}% confidence`),r.push(`- ${w} **${m.topic}**${M?` \u2014 ${M}`:""}`),I.length&&r.push(` _${I.join(" \xB7 ")}_`)}r.push("")}return r.push("---",`_Generated from Brain \`${h}\` \xB7 Share this in your standup or Slack_`),r.join(`
71
- `)}case"brain_set_pref":{const{instance_id:h,key:o,value:u}=N;if(!o||!o.trim())throw new Error("key is required");const p=Pe({value:String(u)}),a=p.felder.value,n=await L(h),v=`cachly:prefs:${o.trim()}:${h}`;return await n.set(v,a),[`\u2705 Preference \`${o}\` set to \`${a}\` for this Brain instance.`,...je(p,"wert")].join(`
72
- `)}case"brain_get_pref":{const{instance_id:h,key:o}=N,u=await L(h);if(o&&o.trim()){const v=await u.get(`cachly:prefs:${o.trim()}:${h}`).catch(()=>null);return v===null?`\u2139\uFE0F Preference \`${o}\` is not set (using default).`:`\u{1F527} Preference \`${o}\` = \`${v}\``}const p=await Me(u,`cachly:prefs:*:${h}`,{max:200,timeoutMs:2e3});if(p.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const a=await u.mget(...p),n=["\u{1F527} **Brain preferences:**",""];for(let v=0;v<p.length;v++){const d=p[v].replace("cachly:prefs:","").replace(`:${h}`,"");n.push(`- \`${d}\` = \`${a[v]??"(null)"}\``)}return n.join(`
73
- `)}default:return null}}async function Go(R,N){try{if(!Be()||Ce!=="cachly"&&Ce!=="ollama")return 0;const{vektor:L,zweit:X}=St(R);let h=0;for(const o of L.themen()){if(h>=N)break;if(X.hat(o)||await R.exists(`${Ke}${o}`))continue;const u=await R.get(`cachly:lesson:best:${o}`);if(!u)continue;const p=W(u,{});try{const a=await Te(Ve(p),{geduld:"lang",modell:qe});a?.length&&(await R.set(`${Ke}${o}`,ze(a)),h++)}catch{}}return h}catch{return 0}}async function ws(R,N,L){try{if(!Be())return;const X=await R.srandmember(Je,L),h=Array.isArray(X)?X:X?[X]:[],o=Et(R);for(const u of h){if(u===N||o.has(u))continue;const p=await R.get(`cachly:lesson:best:${u}`);if(!p){await R.srem(Je,u);continue}const a=W(p,{});try{const n=await Te(Ve(a),{geduld:"lang"});if(n?.length)await R.set(`${_t}${u}`,ze(n)),await R.srem(Je,u);else continue;if(Ce==="cachly"||Ce==="ollama")try{const v=await Te(Ve(a),{geduld:"lang",modell:qe});v?.length&&(await R.set(`${Ke}${u}`,ze(v)),await R.srem(lt,u))}catch{}}catch{}}await Vo(R,L),await _s(R,Xe,ct,N,L,u=>{const p=bt(u);return p?Te(p,{geduld:"lang"}):Promise.resolve(null)}),(Ce==="cachly"||Ce==="ollama")&&await _s(R,lt,Ke,N,L,(u,p)=>Te(Ve(p),{geduld:"lang",modell:qe}))}catch{}}const Ko=5*6e4,ys=new WeakMap;async function Vo(R,N){const L=ys.get(R)??{liste:[],geprueft:0};if(ys.set(R,L),L.liste.length===0){if(Date.now()-L.geprueft<Ko)return;L.geprueft=Date.now();const X=async u=>{const p=new Set;let a="0";do{const[n,v]=await R.scan(a,"MATCH",`${u}*`,"COUNT",500);a=n;for(const d of v)p.add(d.slice(u.length))}while(a!=="0");return p},h=await X(_t),o=await X(ct);L.liste=[...h].filter(u=>!o.has(u)&&bt(u))}for(const X of L.liste.splice(0,N))await R.sadd(Xe,X).catch(()=>{})}async function _s(R,N,L,X,h,o){const u=await R.srandmember(N,h),p=Array.isArray(u)?u:u?[u]:[],a=Et(R);for(const n of p){if(n===X||a.has(n))continue;const v=await R.get(`cachly:lesson:best:${n}`);if(!v){await R.srem(N,n);continue}if(await R.exists(`${L}${n}`)){await R.srem(N,n);continue}try{const d=await o(n,W(v,{}));d===null?await R.srem(N,n):d?.length&&(await R.set(`${L}${n}`,ze(d)),await R.srem(N,n))}catch{}}}const bs=new WeakMap;function Et(R){let N=bs.get(R);return N||(N=new Set,bs.set(R,N)),N}export{Ya as BRAIN_TOOL_NAMES,zt as RECALL_ROH_ZEICHEN,Dt as RECALL_VOLLTEXT_ZEICHEN,St as bestaendeFuer,ms as getRecallGate,Za as handleBrainTool,Pt as recallNurLesen,gt as recallVorschau};
52
+ \u{1F4DD} **Instructions:** ${s}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically.",...He(f,"notiz")].filter(e=>e!=="").join(`
53
+ `)}case"auto_learn_session":{const{instance_id:u,observations:o}=T,d=await L(u),p=[],a=[];let n=0,v=0;for(const i of o){const S=Fe(i),t=S.felder,s=t.topic??t.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),C=s.includes(":")?s:`auto:${s}`,r=`cachly:lesson:best:${C}`,c=await d.get(r);if(c&&JSON.parse(c).outcome==="success"&&t.outcome!=="success"){a.push(C);continue}const b={topic:C,outcome:t.outcome,what_worked:t.outcome==="success"?t.action:t.details??t.action,what_failed:t.outcome==="failure"?t.action:void 0,context:t.details,severity:t.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2,...S.verdacht.length?{tags:[Tt]}:{}},m=JSON.stringify(b);S.geschwaerzt.length&&n++,S.verdacht.length&&v++,await d.set(r,m);const w=`cachly:lessons:${C}`;await d.rpush(w,m),await d.ltrim(w,-100,-1),await d.expire(w,90*86400);try{const I=C.split(":")[0]??"auto",A=we(C);if(await Ke(d,A,I,I),t.outcome==="success"||t.outcome==="partial"){const e=t.details?ft(t.details):null;if(e){const Z=we(`problem:${e}`);await Ke(d,Z,"problem","problem"),await ve(d,A,"fixes",Z,t.outcome==="success",t.outcome==="partial")}}}catch{}p.push(`${t.outcome==="success"?"\u2705":t.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${C}\``)}const f=[`\u{1F916} **Auto-learn complete**: ${p.length} stored, ${a.length} skipped`,""];return p.length>0&&f.push("**Stored:**",...p.map(i=>" "+i),""),a.length>0&&f.push(`**Skipped** (better lesson already exists): ${a.map(i=>`\`${i}\``).join(", ")}`),f.push(...hs(n,v,`${p.length} observations`)),f.join(`
54
+ `)}case"brain_who_knows":{const{instance_id:u,topic:o,limit:d=10}=T;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const p=Math.max(1,Math.min(Number(d)||10,50)),a=await L(u),n=we(o),v=_t(o).filter(r=>r.length>=3).slice(0,5),f=new Set([n]);for(const r of v.slice(0,3)){const c=a.scanStream({match:`cachly:ckg:node:*${r}*`,count:30});await new Promise((b,m)=>{c.on("data",w=>{for(const I of w.slice(0,10)){const A=I.replace("cachly:ckg:node:","");!A.startsWith("person:")&&!A.startsWith("file:")&&f.add(A)}}),c.on("end",b),c.on("error",m)})}const i=new Map;for(const r of[...f].slice(0,25)){const c=await a.smembers(`cachly:ckg:idx:to:${r}`);for(const b of c){const m=await a.get(b);if(!m)continue;const w=j(m,null);if(!w||w.edgeType!=="authored")continue;const I=await a.get(`cachly:ckg:node:${w.from}`);if(!I)continue;const A=j(I,null);if(!A||A.type!=="person")continue;const e=i.get(w.from);e?(e.lessonCount++,e.totalConfidence+=w.confidence,e.domains.add(A.domain),w.last_updated>e.lastActive&&(e.lastActive=w.last_updated)):i.set(w.from,{handle:A.handle,lessonCount:1,totalConfidence:w.confidence,domains:new Set([A.domain]),lastActive:A.last_active??w.last_updated})}}if(i.size===0)return[`## \u{1F465} Who Knows About \`${o}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${o}", author="your-handle", ...)\``].join(`
55
+ `);const S=[...i.entries()].map(([r,c])=>({id:r,handle:c.handle,lessonCount:c.lessonCount,avgConfidence:c.totalConfidence/c.lessonCount,domains:[...c.domains].slice(0,3).join(", "),lastActive:c.lastActive})).sort((r,c)=>c.lessonCount*c.avgConfidence-r.lessonCount*r.avgConfidence).slice(0,p),t=[],s=S[0];if(s)try{const r=await a.smembers(`cachly:ckg:idx:from:${s.id}`),c=[];for(const b of r){const m=await a.get(b);if(!m)continue;const w=j(m,null);if(!w||w.edgeType!=="collaborates")continue;const I=await a.get(`cachly:ckg:node:${w.to}`),A=I?j(I,null):null;A?.handle&&c.push({handle:A.handle,trials:w.trials})}c.sort((b,m)=>m.trials-b.trials);for(const b of c.slice(0,3))t.push(b.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${o}\`?`,"",`**${S.length}** contributor${S.length!==1?"s":""} with relevant lessons:`,""];for(const[r,c]of S.entries()){const b=r===0?"\u{1F947}":r===1?"\u{1F948}":r===2?"\u{1F949}":`${r+1}.`,m=(c.avgConfidence*100).toFixed(0),w=Math.floor((Date.now()-new Date(c.lastActive).getTime())/864e5),I=w<1?"today":w<7?`${w}d ago`:w<30?`${Math.floor(w/7)}w ago`:`${Math.floor(w/30)}mo ago`,A=await it(a,u,c.handle).catch(()=>null),e=A?` ${qs[A]}`:"";C.push(`${b} **${c.handle}**${e} \u2014 ${c.lessonCount} lesson${c.lessonCount!==1?"s":""} \xB7 ${m}% confidence \xB7 last active ${I}`,` _domains: ${c.domains}_`,"")}return t.length>0&&s&&C.push(`\u{1F91D} **${s.handle}** frequently works with: ${t.map(r=>`**${r}**`).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(`
56
+ `)}case"brain_file_map":{const{instance_id:u,file_paths:o=[]}=T,d=(Array.isArray(o)?o:[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());if(!d.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const p=await L(u),a=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const n of d.slice(0,10)){a.push(`### \`${n}\``);const v=`file:${we(n)}`,f=await p.smembers(`cachly:ckg:idx:to:${v}`),i=[];for(const C of f){const r=await p.get(C);if(!r)continue;const c=j(r,null);if(!c||c.edgeType!=="touched")continue;const b=await p.get(`cachly:ckg:node:${c.from}`);if(!b)continue;const m=j(b,null);!m||m.type!=="person"||i.push({handle:m.handle,touches:c.trials,lastSeen:c.last_updated})}if(i.sort((C,r)=>r.touches-C.touches),i.length>0){const C=i.slice(0,5).map((r,c)=>{const b=c===0?"\u{1F947}":c===1?"\u{1F948}":c===2?"\u{1F949}":`${c+1}.`,m=Math.floor((Date.now()-new Date(r.lastSeen).getTime())/864e5),w=m<1?"today":m<7?`${m}d ago`:`${Math.floor(m/7)}w ago`;return`${b} **${r.handle}** (${r.touches}\xD7 \xB7 ${w})`}).join(" \xB7 ");a.push(`**Experts:** ${C}`)}else a.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const t=n.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),s=[];if(t)try{const C=await lt(p,["cachly:lesson:best:*"],t,4);for(const r of C){const c=je(r.content);if(!Ve(c))continue;const b=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=c.severity==="critical"?" \u{1F534}":c.severity==="major"?" \u{1F7E1}":"",w=c.author?` \xB7 \u{1F464} ${c.author}`:"",I=r.key.replace("cachly:lesson:best:","");s.push(` - ${b} \`${I}\`${m}${w} \u2014 ${(c.what_worked??"").slice(0,100)}`)}}catch{}if(s.length<2){const C=await Re(p,"cachly:lesson:best:*",{max:1500});for(const r of C.slice(0,300)){const c=await p.get(r);if(!c)continue;const b=je(c);if(!Ve(b)||!(b.file_paths??[]).includes(n))continue;const m=r.replace("cachly:lesson:best:","");if(s.some(e=>e.includes(`\`${m}\``)))continue;const w=b.outcome==="success"?"\u2705":b.outcome==="partial"?"\u26A0\uFE0F":"\u274C",I=b.severity==="critical"?" \u{1F534}":b.severity==="major"?" \u{1F7E1}":"",A=b.author?` \xB7 \u{1F464} ${b.author}`:"";s.push(` - ${w} \`${m}\`${I}${A} \u2014 ${(b.what_worked??"").slice(0,100)}`)}}s.length>0?(a.push("**Related lessons:**"),a.push(...s.slice(0,5))):a.push("**Related lessons:** _None yet_"),a.push("")}return a.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),a.join(`
57
+ `)}case"team_expertise_map":{const{instance_id:u,top_n:o=20}=T,d=await L(u),p=await Re(d,"cachly:ckg:node:person:*",{max:2e3});if(p.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(`
58
+ `);const a=[];for(const f of p){const i=await d.get(f);if(!i)continue;const S=j(i,null);if(!S||S.type!=="person")continue;const t=await d.smembers(`cachly:ckg:idx:from:${S.id}`),s=new Map;let C=0;for(const r of t){const c=await d.get(r);if(!c)continue;const b=j(c,null);if(!b||b.edgeType!=="authored")continue;C++;const m=b.to.split(":")[0]??"unknown";s.set(m,(s.get(m)??0)+1)}a.push({handle:S.handle,lessonCount:C,domains:s,lastActive:S.last_active})}a.sort((f,i)=>i.lessonCount-f.lessonCount);const n=a.slice(0,o),v=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${n.length}** contributor${n.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[f,i]of n.entries()){const S=f===0?"\u{1F947}":f===1?"\u{1F948}":f===2?"\u{1F949}":`${f+1}`,t=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),s=t<1?"today":t<7?`${t}d ago`:t<30?`${Math.floor(t/7)}w ago`:`${Math.floor(t/30)}mo ago`,C=[...i.domains.entries()].sort((r,c)=>c[1]-r[1]).slice(0,3).map(([r,c])=>`${r}(${c})`).join(", ")||"\u2014";v.push(`| ${S} | **${i.handle}** | ${i.lessonCount} | ${C} | ${s} |`)}return v.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),v.join(`
59
+ `)}case"skill_gaps":{const{instance_id:u,min_failures:o=1}=T,d=await L(u),p=await Re(d,"cachly:lesson:best:*",{max:3e3}),a=new Map;let n=0,v=0;for(const S of p){const t=await d.get(S);if(!t)continue;const s=je(t);if(s===null)continue;const C=(s.topic??"").split(":")[0]??"unknown",r=a.get(C)??{successes:0,failures:0,attributed:0,topics:[]};s.outcome==="success"||s.outcome==="partial"?r.successes++:r.failures++,s.author&&(r.attributed++,n++),s.visibility==="private"&&v++,r.topics.push(s.topic??""),a.set(C,r)}const f=[];for(const[S,t]of a)t.failures>=o&&t.successes===0&&f.push({domain:S,type:"unresolved failures",severity:t.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${t.failures} failure${t.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),t.successes+t.failures>=3&&t.attributed===0&&f.push({domain:S,type:"no attribution",severity:"\u{1F535} info",detail:`${t.successes+t.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const i=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${p.length}** lessons scanned \xB7 **${n}** attributed \xB7 **${f.length}** gap${f.length!==1?"s":""} found`,v>0?`_(${v} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(f.length===0)i.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const S=[...f.filter(t=>t.severity.includes("critical")),...f.filter(t=>t.severity.includes("warn")),...f.filter(t=>t.severity.includes("info"))];for(const t of S.slice(0,15))i.push(`${t.severity} **\`${t.domain}\`** \u2014 ${t.type}`),i.push(` ${t.detail}`),i.push("");f.length>15&&i.push(`_\u2026and ${f.length-15} more gaps. Fix critical ones first._`)}return i.push("---",`_Fix gaps with \`learn_from_attempts(topic="${f[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),i.join(`
60
+ `)}case"brain_coverage":{const{instance_id:u,repo_path:o="."}=T,d=await L(u),[p,a,n]=await Promise.all([Re(d,"cachly:lesson:best:*",{max:5e3}),Re(d,"cachly:ckg:node:person:*",{max:2e3}),Re(d,"cachly:ckg:node:file:*",{max:5e3})]);let v=0,f="n/a";try{const m=dt(o);if(!m)throw new Error("repo_path ist kein Ordner");v=Ge(m,["ls-files"],{timeoutMs:3e4}).trim().split(`
61
+ `).filter(Boolean).length,f=String(v)}catch{}let i=0,S=0,t=0;const s=new Set;for(const m of p){const w=await d.get(m);if(!w)continue;const I=j(w,{});I.outcome==="success"||I.outcome==="partial"?i++:S++,I.author&&t++,s.add((I.topic??"").split(":")[0]??"unknown")}const C=v>0?`${Math.round(n.length/v*100)}% (${n.length}/${v} files)`:`${n.length} files tracked`,r=p.length>0?Math.round(t/p.length*100):0,c=Math.round(Math.min(1,p.length/50)*25+Math.min(1,i/Math.max(1,p.length))*25+Math.min(1,r/100)*25+Math.min(1,a.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${c>=80?"\u{1F7E2}":c>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${c}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${p.length}** (${i} success \xB7 ${S} failure) |`,`| Problem domains | **${s.size}** |`,`| Attribution | **${t}/${p.length}** (${r}%) |`,`| Contributors | **${a.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,p.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,i/Math.max(1,p.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,r/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,a.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(`
62
+ `)}case"brain_metrics":{const{instance_id:u}=T,o=await L(u),[d,p,a,n,v,f]=await Promise.all([o.get(`cachly:stats:born_at:${u}`).catch(()=>null),o.get(`cachly:stats:first_recall_at:${u}`).catch(()=>null),o.get(`cachly:stats:recalls_total:${u}`).catch(()=>null),o.get(`cachly:stats:cross_author_recalls:${u}`).catch(()=>null),o.get(`cachly:stats:time_saved_mins:${u}`).catch(()=>null),o.smembers(`cachly:stats:reuse_pairs:${u}`).catch(()=>[])]);let i={};try{i=await o.hgetall(ps(u))??{}}catch{i={}}let S={};try{S=await o.hgetall(qt(u))??{}}catch{S={}}const t={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const g=await o.lrange(Jt(u),0,499),V=new Map;for(const Q of g){const Y=j(Q,{ts:"",themen:[]});if(!(!Y.ts||!Array.isArray(Y.themen)))for(const ee of Y.themen){if(t.lieferungen++,!V.has(ee)){const te=await o.get(`cachly:lesson:best:${ee}`).catch(()=>null);V.set(ee,te?j(te,{}):null)}const J=vn(Y.ts,V.get(ee)??null);if(J.length===0){t.ohneEreignis++;continue}for(const te of J)t[te]++}}}catch{}let s=0,C=0;try{const g=await o.lrange(`cachly:wirkung:${u}`,0,-1);for(const V of g){const Q=j(V,{});C++,Q.geholfen===!0&&s++}}catch{}let r={};try{r=await o.hgetall(uo(u))??{}}catch{r={}}const c=fo(r,10);let b={token:0,abrufe:0,treffer:0};try{const g=await o.get(mo(u)),V=await o.hgetall(wo(u))??{};b={token:g??0,abrufe:V.abrufe??0,treffer:V.treffer??0}}catch{}const m=go(b);let w;if(d&&p){const g=new Date(p).getTime()-new Date(d).getTime(),V=Math.max(0,Math.round(g/6e4)),Q=V<1?"<1 min":V<60?`${V} min`:`${(V/60).toFixed(1)} h`,Y=g<=2*6e4?"\u{1F7E2} under 2 min target":g<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";w=`**${Q}** from first lesson \u2192 first proven recall \xB7 ${Y}`}else d&&!p?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 I=["\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(`
63
+ `),A=Number(a??0),e=Number(n??0),Z=A>0?Math.round(e/A*100):0,le=Z>=30?"\u{1F7E2} above 30 % target":A===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",re=Math.round(Number(v??0)),ue=re<60?`${re} min`:`${(re/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)_",I,"_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)_",`**${Z}%** of proven recalls used a teammate's lesson (${e}/${A}) \xB7 ${le}`,f.length>0?`**${f.length}** distinct reuse relationship${f.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",po(m),"",m.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ue} 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 ${ue} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,A===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 g=Number(i.beantwortet??0),V=Number(i.knapp??0),Q=Number(i.schweigen??0),Y=g+V+Q;if(Y===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const ee=J=>`${Math.round(100*J/Y)} %`;return`**${Y}** Suchen: ${ee(g)} beantwortet \xB7 ${ee(V)} als knapper Sieg markiert \xB7 ${ee(Q)} 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 g=ee=>Number(S[ee]??0),V=[["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)"]],Q=V.reduce((ee,[J])=>ee+g(J),0);if(Q===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const Y=V.filter(([ee])=>ee!=="ohne-vorwissen").sort((ee,J)=>g(J[0])-g(ee[0]))[0];return`**${Q}** klassifizierte Fehlschlaege: `+V.map(([ee,J])=>`${g(ee)} ${J}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${Y[1]}** (${g(Y[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)_",t.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${t.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${t.widersprochen} widersprochen \xB7 ${t.korrigiert} korrigiert \xB7 ${t.veraltet} veraltet \xB7 ${t.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 g=Number(t.widersprochen)+Number(t.veraltet);if(C===0&&g===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const V=s-g;return`**${V>=0?"+":""}${V}** = ${s} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${g} Schadenslieferungen (${t.widersprochen} spaeter widerlegt + ${t.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",ho(c,So.length),...c.spitze.length>0?c.spitze.map((g,V)=>` ${String(V+1).padStart(2)}. \`${g.name}\` \u2014 ${g.aufrufe}\xD7 (${Math.round(g.anteil*100)} %)`):[]].filter(Boolean).join(`
64
+ `)}case"brain_service_map":{const{instance_id:u,service:o}=T;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const d=await L(u),p=`service:${we(o.trim())}`,a=await d.get(`cachly:ckg:node:${p}`).catch(()=>null),n=a?j(a,null):null,v=await d.smembers(`cachly:ckg:idx:to:${p}`).catch(()=>[]),f=[],i=[],S=[];for(const w of v){const I=await d.get(w).catch(()=>null);if(!I)continue;const A=j(I,null);if(A)if(A.edgeType==="operates"){const e=await d.get(`cachly:ckg:node:${A.from}`).catch(()=>null),Z=e?j(e,null):null;Z?.handle&&f.push({handle:Z.handle,trials:A.trials})}else if(A.edgeType==="runs_in"){const e=await d.get(`cachly:ckg:node:${A.from}`).catch(()=>null),Z=e?j(e,null):null;Z?.path&&i.push({path:Z.path,trials:A.trials})}else A.edgeType==="affects"&&S.push({id:A.from,confidence:A.confidence})}f.sort((w,I)=>I.trials-w.trials),i.sort((w,I)=>I.trials-w.trials),S.sort((w,I)=>I.confidence-w.confidence);const t=[],s=await Re(d,"cachly:lesson:best:*",{max:1500}),C=o.trim().toLowerCase();for(const w of s.slice(0,400)){const I=await d.get(w).catch(()=>null);if(!I)continue;const A=je(I);Ve(A)&&(A.service??"").toLowerCase()===C&&t.push({...A,topic:w.replace("cachly:lesson:best:","")})}if(!n&&t.length===0&&f.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${o}\``,"","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="${o}", author="you", file_paths=[...])\``].join(`
65
+ `);const r=n?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${n?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${o}\``,"",n?`_${r} \xB7 ${n.count} lesson${n.count!==1?"s":""} referenced \xB7 domain: ${n.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(f.length>0){const w=f.slice(0,5).map((I,A)=>`${A===0?"\u{1F947}":A===1?"\u{1F948}":A===2?"\u{1F949}":`${A+1}.`} **${I.handle}** (${I.trials}\xD7)`).join(" \xB7 ");c.push(`**Operators:** ${w}`,"")}else c.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const b=t.filter(w=>w.outcome==="failure"),m=t.filter(w=>w.outcome!=="failure");if(b.length>0){c.push(`**\u26A0\uFE0F Known failures (${b.length}):**`);for(const w of b.slice(0,6)){const I=w.severity==="critical"?" \u{1F534}":w.severity==="major"?" \u{1F7E1}":"",A=w.author?` \xB7 \u{1F464} ${w.author}`:"";c.push(` - \u274C \`${w.topic}\`${I}${A} \u2014 ${(w.what_worked??"").slice(0,100)}`)}c.push("")}if(m.length>0){c.push(`**\u2705 Proven fixes (${m.length}):**`);for(const w of m.slice(0,6)){const I=w.outcome==="partial"?"\u26A0\uFE0F":"\u2705",A=w.author?` \xB7 \u{1F464} ${w.author}`:"";c.push(` - ${I} \`${w.topic}\`${A} \u2014 ${(w.what_worked??"").slice(0,100)}`)}c.push("")}return i.length>0&&c.push(`**Files in this service:** ${i.slice(0,8).map(w=>`\`${w.path}\``).join(", ")}`,""),c.push("---",`_Tag lessons with \`service="${o}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),c.join(`
66
+ `)}case"brain_collab_pairs":{const{instance_id:u,min_weight:o=1}=T,d=await L(u),p=typeof o=="number"&&o>=1?Math.floor(o):1,a=await Re(d,"cachly:ckg:node:person:*",{max:500}),n=new Map;for(const s of a){const C=await d.get(s);if(!C)continue;const r=j(C,null);!r||r.type!=="person"||n.set(r.id,{id:r.id,handle:r.handle,domain:r.domain,count:r.count})}if(n.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(`
67
+ `);const v=new Map;for(const[s,C]of n){const r=await d.smembers(`cachly:ckg:idx:from:${s}`);for(const c of r){const b=await d.get(c);if(!b)continue;const m=j(b,null);if(!m||m.edgeType!=="collaborates")continue;const w=n.get(m.to);if(!w)continue;const[I,A]=s<m.to?[s,m.to]:[m.to,s],e=`${I}||${A}`,Z=v.get(e);if(Z)Z.trials+=m.trials;else{const[le,re]=s<m.to?[C,w]:[w,C];v.set(e,{a:le,b:re,trials:m.trials,confidence:m.confidence})}}}const f=[...v.values()].filter(s=>s.trials>=p).sort((s,C)=>C.trials-s.trials),i=new Set;for(const s of f)i.add(s.a.id),i.add(s.b.id);const S=[...n.values()].filter(s=>!i.has(s.id)),t=["## \u{1F91D} Team Collaboration Graph",""];if(f.length===0)t.push(`No collaboration pairs yet (min weight: ${p}).`,"","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{t.push(`**${f.length} collaboration pair${f.length!==1?"s":""}** across ${i.size} contributor${i.size!==1?"s":""}:`,"");for(const s of f.slice(0,20)){const C=(s.confidence*100).toFixed(0),r=[s.a.domain,s.b.domain].filter((c,b,m)=>c&&m.indexOf(c)===b).map(c=>`\`${c}\``).join(", ");t.push(`### @${s.a.handle} \u2194 @${s.b.handle}`,`- **${s.trials} collaboration event${s.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${r||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${s.a.handle}** und **@${s.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}f.length>20&&t.push(`_...and ${f.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return S.length>0&&t.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${S.length} contributor${S.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...S.slice(0,10).map(s=>`- **@${s.handle}** \u2014 ${s.count} lesson${s.count!==1?"s":""} \xB7 domain: \`${s.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),t.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),t.join(`
68
+ `)}case"brain_portability":{const{instance_id:u}=T,o=[{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:u}}}},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:u}}}},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:u}}}},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:u}}}},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:u}}}},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:u}}}},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:u}}]},null,2)}],d=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${u}\``,"","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 (${o.length} supported)`,""];for(const p of o)d.push(`#### ${p.icon} ${p.name}`,`Config: \`${p.configPath}\``,"","```json",p.configBlock,"```","");return d.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 \`${u}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),d.join(`
69
+ `)}case"brain_changelog":{const{instance_id:u,days:o=7,max_lessons:d=30,include_failures:p=!0}=T,a=await L(u),n=Date.now()-Number(o)*864e5,v=await Re(a,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),f=[];for(const c of v){const b=await a.get(c).catch(()=>null);if(!b)continue;const m=j(b,{});if((m.ts?new Date(m.ts).getTime():0)<n||!p&&m.outcome==="failure")continue;const I=c.replace("cachly:lesson:best:","");f.push({...m,topic:I})}f.sort((c,b)=>{const m=c.ts?new Date(c.ts).getTime():0;return(b.ts?new Date(b.ts).getTime():0)-m});const i=f.slice(0,Number(d));if(i.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${o} day${Number(o)!==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(`
70
+ `);const S=new Map;for(const c of i){const b=c.topic.includes(":")?c.topic.split(":")[0]:"general",m=S.get(b)??[];m.push(c),S.set(b,m)}const t=c=>c==="critical"?"\u{1F6A8}":c==="major"?"\u26A0\uFE0F":c==="minor"?"\u{1F4A1}":"\u2728",s=c=>c==="failure"?"\u274C":c==="partial"?"\u{1F536}":"\u2705",r=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${o} day${Number(o)!==1?"s":""})`,"",`_${i.length} lesson${i.length!==1?"s":""} learned across ${S.size} topic area${S.size!==1?"s":""}_`,""];for(const[c,b]of Array.from(S.entries()).sort((m,w)=>w[1].length-m[1].length)){r.push(`### ${c}`),r.push("");for(const m of b){const w=m.outcome==="failure"?s(m.outcome):t(m.severity),I=m.outcome==="failure"?m.what_failed:m.what_worked,A=[];m.author&&A.push(`by **${m.author}**`),m.recall_count&&A.push(`${m.recall_count} recall${m.recall_count!==1?"s":""}`),m.confidence!==void 0&&A.push(`${Math.round(m.confidence*100)}% confidence`),r.push(`- ${w} **${m.topic}**${I?` \u2014 ${I}`:""}`),A.length&&r.push(` _${A.join(" \xB7 ")}_`)}r.push("")}return r.push("---",`_Generated from Brain \`${u}\` \xB7 Share this in your standup or Slack_`),r.join(`
71
+ `)}case"brain_set_pref":{const{instance_id:u,key:o,value:d}=T;if(!o||!o.trim())throw new Error("key is required");const p=Fe({value:String(d)}),a=p.felder.value,n=await L(u),v=`cachly:prefs:${o.trim()}:${u}`;return await n.set(v,a),[`\u2705 Preference \`${o}\` set to \`${a}\` for this Brain instance.`,...He(p,"wert")].join(`
72
+ `)}case"brain_get_pref":{const{instance_id:u,key:o}=T,d=await L(u);if(o&&o.trim()){const v=await d.get(`cachly:prefs:${o.trim()}:${u}`).catch(()=>null);return v===null?`\u2139\uFE0F Preference \`${o}\` is not set (using default).`:`\u{1F527} Preference \`${o}\` = \`${v}\``}const p=await Re(d,`cachly:prefs:*:${u}`,{max:200,timeoutMs:2e3});if(p.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const a=await d.mget(...p),n=["\u{1F527} **Brain preferences:**",""];for(let v=0;v<p.length;v++){const f=p[v].replace("cachly:prefs:","").replace(`:${u}`,"");n.push(`- \`${f}\` = \`${a[v]??"(null)"}\``)}return n.join(`
73
+ `)}default:return null}}async function Vo(M,T){try{if(!ze()||Se!=="cachly"&&Se!=="ollama")return 0;const{vektor:L,zweit:X}=xt(M);let u=0;for(const o of L.themen()){if(u>=T)break;if(X.hat(o)||await M.exists(`${Je}${o}`))continue;const d=await M.get(`cachly:lesson:best:${o}`);if(!d)continue;const p=j(d,{});try{const a=await Te(qe(p),{geduld:"lang",modell:Ye});a?.length&&(await M.set(`${Je}${o}`,We(a)),u++)}catch{}}return u}catch{return 0}}async function _s(M,T,L){try{if(!ze())return;const X=await M.srandmember(Ue,L),u=Array.isArray(X)?X:X?[X]:[],o=It(M);for(const d of u){if(d===T||o.has(d))continue;const p=await M.get(`cachly:lesson:best:${d}`);if(!p){await M.srem(Ue,d);continue}const a=j(p,{});try{const n=await Te(qe(a),{geduld:"lang"});if(n?.length)await M.set(`${$t}${d}`,We(n)),await M.srem(Ue,d);else continue;if(Se==="cachly"||Se==="ollama")try{const v=await Te(qe(a),{geduld:"lang",modell:Ye});v?.length&&(await M.set(`${Je}${d}`,We(v)),await M.srem(ut,d))}catch{}}catch{}}await qo(M,L),await $s(M,et,ht,T,L,d=>{const p=kt(d);return p?Te(p,{geduld:"lang"}):Promise.resolve(null)}),(Se==="cachly"||Se==="ollama")&&await $s(M,ut,Je,T,L,(d,p)=>Te(qe(p),{geduld:"lang",modell:Ye}))}catch{}}const Jo=5*6e4,bs=new WeakMap;async function qo(M,T){const L=bs.get(M)??{liste:[],geprueft:0};if(bs.set(M,L),L.liste.length===0){if(Date.now()-L.geprueft<Jo)return;L.geprueft=Date.now();const X=async d=>{const p=new Set;let a="0";do{const[n,v]=await M.scan(a,"MATCH",`${d}*`,"COUNT",500);a=n;for(const f of v)p.add(f.slice(d.length))}while(a!=="0");return p},u=await X($t),o=await X(ht);L.liste=[...u].filter(d=>!o.has(d)&&kt(d))}for(const X of L.liste.splice(0,T))await M.sadd(et,X).catch(()=>{})}async function $s(M,T,L,X,u,o){const d=await M.srandmember(T,u),p=Array.isArray(d)?d:d?[d]:[],a=It(M);for(const n of p){if(n===X||a.has(n))continue;const v=await M.get(`cachly:lesson:best:${n}`);if(!v){await M.srem(T,n);continue}if(await M.exists(`${L}${n}`)){await M.srem(T,n);continue}try{const f=await o(n,j(v,{}));f===null?await M.srem(T,n):f?.length&&(await M.set(`${L}${n}`,We(f)),await M.srem(T,n))}catch{}}}const ks=new WeakMap;function It(M){let T=ks.get(M);return T||(T=new Set,ks.set(M,T)),T}export{Xa as BRAIN_TOOL_NAMES,Pt as RECALL_ROH_ZEICHEN,zt as RECALL_VOLLTEXT_ZEICHEN,xt as bestaendeFuer,ys as getRecallGate,Qa as handleBrainTool,jt as recallNurLesen,wt as recallVorschau};