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