@cachly-dev/mcp-server 0.10.213 → 0.10.214
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/bedeutung.js +2 -2
- package/dist/src/handlers/brain.js +68 -68
- package/dist/src/handlers/team.js +41 -41
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +9 -9
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,78 +1,78 @@
|
|
|
1
|
-
import{gitLesen as Oe,istCommitHash as is,pruefeOrdner as Qe}from"../git-ohne-shell.js";import{createRequire as _t}from"node:module";import{calculateConfidence as bt,confidenceBadge as rs,STRUCTURED_TEMPLATES as cs,CONFIDENCE_WARN_VALUE as ls}from"../confidence.js";import{kurzfassenHinweis as hs}from"../antwort-hinweis.js";import{pruefeMeldung as us,wendeAn as ds}from"../pruefung-melden.js";import{ckgSlug as pe,extractProblemConcept as et,ckgUpsertNode as Pe,ckgUpdateEdge as Se,ckgUpsertPersonNode as fs,ckgUpsertFileNode as $t,ckgRecordCollaboration as gs,ckgUpsertServiceNode as ms}from"../ckg.js";import{safeJsonParse as z,scanKeys as Me,leseOderNull as Le,darfHeraus as je}from"../utils.js";import{ersparteMinuten as kt,istStarterLektion as tt,zaehltAlsErsparnis as vt}from"../wertbeitrag.js";import{lessonPreviewLines as qe,trimTo as ps}from"../lesson-preview.js";import{normalisiereZeit as st,zaehleZeitangaben as nt}from"../zeit-normalisieren.js";import{abstentionSatz as ws,alterssatzFuerBelegte as ys,beurteileTreffer as _s,istBelegt as bs}from"../abstention.js";import{meldeEinmal as ot,meldeUndVermerke as Ue,fehlerText as at,OHNE_VEKTOREN as $s,OHNE_DIENST as ks,OHNE_FRAGEVEKTOR as vs,SINNPFAD_ABBRUCH as Ss,OHNE_SCHREIBVEKTOR as it}from"../aussetzer.js";import{versuchStart as Cs,neueKennung as xs,wendeZuteilungAn as Ts,schliesseVersuchAb as Ns}from"../versuch.js";function rt(U,R,G,ie=G){if(U.includes("lesson:best:")){const s=z(R,{});if(s&&typeof s=="object"&&(s.what_worked||s.what_failed||s.commands?.length))return qe(s,{maxChars:G,indent:" "})}const f=ps(R,ie);return f?[f]:[]}const St=2e3,Ct=400;import{getRole as ct,ROLE_BADGE as As,getScopes as xt,lessonVisibleToScope as Tt,reviewModeEnabled as Es,storeLessonProposal as Is}from"./team.js";import{keywordSearch as Ye,treffeUeberDateipfad as Ms,wortindexEntwerten as Nt,tokenize as lt,splitMultiQuery as Ds,levenshtein as Bs,indexVocab as At,bestandHolen as Ls}from"../search.js";import{startetNochLeer as Et,leeresBrainAntwort as It,startLage as ht,sofortAntwortNeuesBrain as Rs,neuesBrainBriefing as zs}from"../leeres-brain.js";import{rerankByQuality as Os,qualityMultiplier as Ps,extractLessonQuality as js}from"../rerank.js";import{computeEmbedding as Ie,hasEmbedProvider as Re,EMBED_PROVIDER as De}from"../embeddings.js";import{leserAktiv as Ws,leserPunkte as Fs,mischeMitLeser as Gs}from"../leser.js";import{repariereFelder as Ks}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Mt,NAME_VEKTOR_PRAEFIX as Dt,ZWEIT_VEKTOR_PRAEFIX as Ke,packe as We,textFuerVektor as He,textFuerNamensVektor as Hs,Vektorbestand as ut,VEKTOR_NACHTRAG as Js}from"../bedeutung.js";import{schreibeEingaenge as Vs,Eingangsbestand as qs}from"../eingaenge.js";import{ordneNachHausordnung as Us,rangWerte as Ys}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as Zs}from"../seltenheitsbestand.js";import{spurLegen as Xs}from"../spuren.js";import{schlageErsetzungVor as Qs}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as Bt,stufeSucheNachProjektversion as en,versionsNotizen as tn,versionsBanner as sn}from"../gueltigkeit-version.js";const Fe=Js,nn=365;import{etikettenFuer as on,lieferJournalSchluessel as Lt,JOURNAL_DECKEL as an}from"../etiketten.js";import{klassifiziereFehlschlag as rn,suchProtokollSchluessel as dt,trichterSchluessel as Rt,SUCH_DECKEL as zt}from"../recall-trichter.js";import{leiteEntscheidungAb as cn,entscheidungsZeile as Ot}from"../entscheidung-ableiten.js";import{bewerteTopf as ln,spreizeImTopf as Pt,reichereAn as hn,inhaltsWoerter as jt,grobStamm as un,GEWICHTE as dn,knapperSiegSatz as fn}from"../rangfolge.js";import{pruefeWirkung as gn,werteAus as mn,lehrwert as pn,leiteAb as wn}from"../wirkungsspur.js";import{merkeSuchlauf as ft}from"../suchstatistik.js";import{schreibeTopfNotiz as yn,topfProtokollAktiv as _n}from"../topf-protokoll.js";import{SINN_TOPF as bn,EINGANG_SCHWELLE as $n,EINGANG_SORTIER_GEWICHT as kn,ZWEIT_MODELL as Ze,ZWEIT_GEWICHT as vn,ZWEIT_MINDESTDECKUNG as Wt,NAHDUPLIKAT_SCHWELLE as Sn,LESER_TIEFE as Ft}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Gt,quelleZeile as Cn}from"../herkunft.js";import{doppelHinweis as xn,leseDoppelKandidaten as Tn,mitFrist as Nn,pruefeDoppelung as An}from"../doppel-kandidat.js";import{merkeRecall as En,sitzungsKosten as In,vergissSitzungsKosten as Mn,kostenZeilen as Dn}from"../sitzungs-kosten.js";const $e=new ut,gt=new ut(6e4,Dt),Xe=new ut(6e4,Ke),mt=new qs,Je=new Zs,Kt=bn,Bn=$n,Ln=kn;import{upgradeNudge as Rn}from"../upgrade-nudge.js";import{recallTiefe as Ht,TIEFE_VOLL as zn,TIEFE_VOLL_MEHRTHEMIG as On}from"../recall-tiefe.js";import{nutzungInWorten as Pn,nutzungsSchluessel as jn,verdichte as Wn}from"../werkzeug-nutzung.js";import{inWorten as Fn,lieferBild as Gn,lieferSchluessel as Kn,trefferSchluessel as Hn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Jn,autorHinweis as Vn,coautorAus as qn,echterGitLeser as Un,ermittleAutor as Yn,mitCoautor as Zn,nurMensch as Jt}from"../autor.js";import{TOOLS as Xn}from"../tools.js";import{vorspannHinweis as Qn}from"../vorspann.js";import{autorAbzeichen as eo,fremdanteil as to}from"../autor-abzeichen.js";import{cachlyUrl as so}from"../cachly-url.js";import{belegFuer as no}from"../schreibbeleg.js";import{schwaerzeFelder as oo}from"../geheimnis-filter.js";import{VERDACHT_TAG as pt,mitVerdachtTag as ao,pruefeFelder as io,verdachtsWarnung as ro}from"../tuersteher.js";import{fuerEigenenSpeicher as ze,hinweise as Ge,istMarkiert as Vt,markiert as co,markierungsWarnung as qt,markierungsWarnungAusRohwert as Ut,zaehlHinweise as Yt}from"../schreibtor.js";import{istBlossesThema as Zt}from"../blosses-thema.js";import{zeitpunkt as ke}from"../zeitmessung.js";const Ve=(()=>{try{const U=_t(import.meta.url);for(const R of["../../../package.json","../../package.json"])try{const G=U(R);if(G.name==="@cachly-dev/mcp-server"&&G.version)return G.version}catch{}}catch{}return"0.10.100"})(),lo=()=>{try{return _t(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},ho={"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${Ve}:**`," \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"]},wa=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"]),uo=so("/billing","upgrade"),Xt=new Map,Qt=new Set,fo=1680*60*60;function go(U=new Date){return`cachly:quota:recalls:${U.toISOString().slice(0,7)}`}async function wt(U){try{const R=go();await U.incr(R)===1&&await U.expire(R,fo)}catch{}}function es(U){return`cachly:stats:drei-ausgaenge:${U}`}async function yt(U,R,G){try{await U.hincrby(es(R),G,1)}catch{}}function ts(U,R,G,ie){wt(U),ft(U,G,ie);const f={ts:new Date().toISOString(),frage:G.slice(0,200),geliefert:[]};(async()=>{const s=dt(R);await U.lpush(s,JSON.stringify(f)),await U.ltrim(s,0,zt-1)})().catch(()=>{}),yt(U,R,"schweigen")}async function ss(U){const R={tage:0,rekord:0};try{const G=await U.get("cachly:streak:current"),ie=z(G,null),f=new Date().toISOString().slice(0,10);if(ie){const s=ie.last_date,u=new Date(Date.now()-864e5).toISOString().slice(0,10);s===f?(R.tage=ie.days,R.rekord=ie.record):s===u?(R.tage=ie.days+1,R.rekord=Math.max(R.tage,ie.record),await U.set("cachly:streak:current",JSON.stringify({days:R.tage,last_date:f,record:R.rekord}))):(R.tage=1,R.rekord=ie.record,await U.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:R.rekord})))}else R.tage=1,R.rekord=1,await U.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:1}))}catch{}return R}async function ns(U,R,G){await U.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:R,provider:G}),"EX",86400)}async function os(U,R){const G=Xt.get(U);if(G&&G.expiresAt>Date.now())return G.gate;try{const ie=await R(`/api/v1/instances/${U}/memory`),f=ie?.recall_limit??-1,s=ie?.total_recall_count??0,u={reached:f>0&&s>=f,limit:f,used:s,goodwillMessage:ie?.goodwill_message,notice:ie?.notice};return Xt.set(U,{gate:u,expiresAt:Date.now()+6e4}),u}catch{return{reached:!1,limit:-1,used:0}}}const mo={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function ya(U,R,G,ie){const f=await po(U,R,G,ie),s=mo[U];if(s&&typeof f=="string")try{En(String(R.instance_id??""),String(R[s]??""),f.length)}catch{}return f}async function po(U,R,G,ie){switch(U){case"learn_from_attempts":{const f=oo(R),s=io(f.felder),u=s.length?{...f.felder,tags:ao(f.felder.tags)}:f.felder,{instance_id:_,topic:c,outcome:n,what_worked:E,what_failed:o="",context:i="",severity:S="major",file_paths:a=[],commands:e=[],tags:C=[],depends_on:l=[],author:r="",visibility:k="team",service:m="",service_kind:p="service",group:I="",grund:N="",ersetzt:A="",gilt_ab:t="",gilt_fuer:ae}=u,{what_worked:ue,what_failed:ge="",context:me=""}=Ks({what_worked:E,what_failed:o,context:i}),g=await G(_),K=new Date,oe=K.toISOString();let H=Bt(ae,void 0);const X=t&&!Number.isNaN(Date.parse(String(t)))?new Date(String(t)):K,J=st(ue,X),te=st(ge,X),P=st(me,X),h=nt(ue,X)+nt(ge,X)+nt(me,X),$=Yn({uebergeben:r,umgebung:process.env.CACHLY_AUTHOR,git:Un(process.env.CACHLY_WORKSPACE??process.cwd())});let y="";try{y=qn(await g.get(`cachly:prefs:${Jn}:${_}`))}catch{}const b=Zn($.autor,y),v=Vn($);if(k!=="private"&&await Es(g,_))return Is(g,c,{topic:c,outcome:n,what_worked:J,what_failed:te,context:P,severity:S,file_paths:a,commands:e,tags:C,depends_on:l,...H.angaben.length?{gilt_fuer:H.angaben}:{},...b?{author:b}:{},source:Gt(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:k,recall_count:0,ts:oe,confidence:1,version:3});const B=c.split(":")[0],F=cs[B],Y=[];if(F)for(const x of F.required)x==="commands"&&e.length===0&&Y.push(`\u{1F4CB} ${F.hint}`);let q=!1,ce=0,ye,Q=[];const V=await g.get(`cachly:lesson:best:${c}`),xe=String(N??"").trim();if(V&&!xe)return[`\u270B **Update abgewiesen:** \`${c}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
-
`);if(V)try{const x=JSON.parse(V);H=Bt(ae,x.gilt_fuer),ce=x.recall_count??0,ye=x.last_recalled_at,Q=x.audit_trail??[],Q.push({ts:oe,action:"updated",prev_outcome:x.outcome,grund:xe}),Q.length>20&&(Q=Q.slice(-20)),q=!0;const j=[];if(x.outcome==="success"&&n==="failure"?j.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):x.outcome==="failure"&&n==="success"&&j.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),j.length>0){Q[Q.length-1].action="contradiction-resolved";try{const de=pe(c),ne=pe(`resolution:${c}`);await Se(g,de,"contradicts",ne,!1)}catch{}try{const de=`cachly:contradictions:${c}`,ne=x.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await g.rpush(de,JSON.stringify({ts:oe,prev_outcome:x.outcome,new_outcome:n,direction:ne})),await g.ltrim(de,-50,-1),await g.expire(de,180*86400)}catch{}j.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${c}")\` to resolve via expert agent voting.`)}}catch{}else Q=[{ts:oe,action:"created"}];const _e=[];if(n==="failure"){const x=[],j=g.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((ne,T)=>{j.on("data",O=>x.push(...O)),j.on("end",ne),j.on("error",T)});const de=c.split(/[:\-_]/).filter(ne=>ne.length>2);for(const ne of x.slice(0,50)){const T=await g.get(ne);if(T)try{const O=JSON.parse(T);if(O.outcome!=="success")continue;const re=(O.topic??"").split(/[:\-_]/).filter(Ae=>Ae.length>2);if(de.filter(Ae=>re.includes(Ae)).length>=1&&O.topic!==c){_e.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${O.topic}\` (success, ${O.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${O.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${O.topic}", ..., severity="critical")\``);break}}catch{}}}for(const x of l){const j=`cachly:dep:${x}`,de=await g.get(j),ne=z(de,[]);ne.includes(c)||ne.push(c),await g.set(j,JSON.stringify(ne),"EX",90*86400)}const we={topic:c,outcome:n,what_worked:J,what_failed:te,context:P,severity:S,file_paths:a,commands:e,tags:C,depends_on:l,...b?{author:b}:{},source:Gt(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:k,recall_count:ce,...ye?{last_recalled_at:ye}:{},...t&&!Number.isNaN(Date.parse(String(t)))?{gilt_ab:new Date(String(t)).toISOString()}:{},...H.angaben.length?{gilt_fuer:H.angaben}:{},ts:oe,verified_at:n==="success"||n==="partial"?oe:void 0,confidence:1,audit_trail:Q,version:3},he=String(A??"").trim();let Ce="",Te=null;he===c&&he?Ce="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":he&&(Te=await g.get(`cachly:lesson:best:${he}`),Te?z(Te,{}).ersetzt===c?(Te=null,Ce=`\u26A0\uFE0F \`${he}\` ersetzt bereits \`${c}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${he}\` entfernen und danach hier setzen.`):we.ersetzt=he:Ce=`\u26A0\uFE0F Die zu ersetzende Lektion \`${he}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let d="";if(!he)try{const x=O=>{const re=z(O.content,{});return{topic:re.topic??O.key.slice(19),what_worked:re.what_worked}},[j,de]=await Promise.all([Ye(g,["cachly:lesson:best:*"],`${c} ${J}`.slice(0,300),5),Ms(g,["cachly:lesson:best:*"],a??[])]),ne=new Set,T=[...j,...de].filter(O=>O.key.startsWith("cachly:lesson:best:")).filter(O=>!ne.has(O.key)&&ne.add(O.key)).map(x);d=Qs(c,J,T)??""}catch{}if(n==="failure")try{const j=(await g.lrange(dt(_),0,199)).map(T=>z(T,{ts:"",frage:"",geliefert:[]})).filter(T=>T.ts!==""),de=(await Ye(g,["cachly:lesson:best:*"],`${c} ${te||J}`.slice(0,300),5)).filter(T=>T.key.startsWith("cachly:lesson:best:")).map(T=>{const O=z(T.content,{});return{topic:O.topic??T.key.slice(19),what_worked:O.what_worked}}),ne=rn(c,String(te||""),j,de);await g.hincrby(Rt(_),ne,1)}catch{}const w=cn([J,te,i].filter(Boolean).join(" ").slice(0,2e3));w&&(we.entscheidung=w);const D=no(c,oe,J);we.beleg=D;const M=JSON.stringify(we);g.set(`cachly:stats:born_at:${_}`,oe,"EX",365*86400,"NX").catch(()=>{});const ee=`cachly:lessons:${c}`;await g.rpush(ee,M),await g.ltrim(ee,-100,-1),await g.expire(ee,nn*86400);let L=!1;if(n==="success"||n==="partial"?(await g.set(`cachly:lesson:best:${c}`,M),L=!0):V||(await g.set(`cachly:lesson:best:${c}`,M),L=!0),Te&&L)try{const x=JSON.parse(Te);x.ersetzt_durch=c,x.gilt_bis=oe,x.ersetzt_am=oe,xe&&(x.ersetzt_grund=xe.slice(0,200)),await g.set(`cachly:lesson:best:${he}`,JSON.stringify(x))}catch{}L&&Nt();let se=()=>{};const Z=new Promise(x=>{se=x});L&&Re()||se(null),L&&Re()&&(await g.sadd(Fe,c).catch(()=>{}),(async()=>{const x=z(M,{});try{const j=await Ie(He(x),{geduld:"lang"});if(j?.length?(await g.set(`${Mt}${c}`,We(j)),await g.srem(Fe,c).catch(()=>{}),se(await An(g,{...x,topic:c},j,$e))):se(null),De==="cachly"||De==="ollama")try{const de=await Ie(He(x),{geduld:"lang",modell:Ze});de?.length&&await g.set(`${Ke}${c}`,We(de))}catch{}}catch(j){se(null),await g.sadd(Fe,c).catch(()=>{}),await Ue(g,it,`Volltext-Vektor nicht geschrieben (${De}): ${at(j)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const j=await Ie(Hs(c),{geduld:"lang"});j?.length&&await g.set(`${Dt}${c}`,We(j))}catch(j){await Ue(g,it,`Namens-Vektor nicht geschrieben (${De}): ${at(j)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await Vs(g,c,x,j=>Ie(j,{geduld:"lang"}))}catch(j){await Ue(g,it,`Eingaenge nicht geschrieben (${De}): ${at(j)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await as(g,c,3),se(null)})());try{const x="cachly:session:decision-log",j=JSON.stringify({ts:oe,topic:c,outcome:n,what_worked:J.slice(0,120)});await g.rpush(x,j),await g.ltrim(x,-50,-1)}catch{}let le=null;try{const x=pe(c),j=c.split(":")[0]??"unknown";await Pe(g,x,j,j);for(const ne of C){const T=pe(`tag:${ne}`);await Pe(g,T,"tag","tag"),await Se(g,x,"co-occurs",T,n==="success",n==="partial")}for(const ne of l){const T=pe(ne);await Se(g,x,"requires",T,!0)}if((j==="fix"||j==="debug")&&(n==="success"||n==="partial")){const ne=te||P||"",T=ne?et(ne):null;if(T){const O=pe(`problem:${T}`);await Pe(g,O,"problem","problem"),await Se(g,x,"fixes",O,n==="success",n==="partial")}}if(n==="failure"&&(te||J)){const T=et(te||J);if(T){const O=pe(`cause:${T}`);await Pe(g,O,"cause","cause"),await Se(g,x,"causes",O,!1)}}if(n==="failure"){const ne=await g.smembers(`cachly:ckg:idx:from:${x}`);for(const T of ne){const O=await g.get(T);if(!O)continue;const re=z(O,null);if(re&&re.edgeType==="fixes"&&re.confidence>.7&&re.trials>=3){le=`\u26A0\uFE0F **belief_conflict** on \`${c}\`: 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="${c}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${x}")\` to review.`;const fe=`cachly:ckg:conflict:${x}`;await g.set(fe,JSON.stringify({topic:c,concept_id:x,detected_at:new Date().toISOString(),fix_confidence:re.confidence,fix_trials:re.trials,failure_outcome:n,reported_by:b||"unknown",what_failed:te||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(j==="fix"||j==="debug")){const ne=await g.smembers(`cachly:ckg:idx:from:${x}`);for(const T of ne.slice(0,10)){const O=await g.get(T);if(!O)continue;const re=z(O,null);if(!re||re.edgeType!=="fixes")continue;const fe=await g.smembers(`cachly:ckg:idx:from:${re.to}`);for(const Ae of fe.slice(0,5)){const Be=await g.get(Ae);if(!Be)continue;const Ee=z(Be,null);Ee&&Ee.edgeType==="co-occurs"&&(Ee.successes=(Ee.successes||0)+.1,Ee.trials=(Ee.trials||0)+.1,Ee.confidence=(Ee.successes+1)/(Ee.trials+2),Ee.last_updated=new Date().toISOString(),await g.set(Ae,JSON.stringify(Ee)))}}}if(Math.random()<.01){const ne=Date.now()-7776e6,T=await g.smembers(`cachly:ckg:idx:from:${x}`);for(const O of T){const re=await g.get(O);if(!re)continue;const fe=z(re,null);fe&&fe.trials<3&&fe.last_updated&&new Date(fe.last_updated).getTime()<ne&&(fe.confidence=fe.confidence*.9,fe.last_updated=new Date().toISOString(),await g.set(O,JSON.stringify(fe)))}}}catch{}if(b){g.set(`cachly:agents:active:${b}`,JSON.stringify({author:b,last_topic:c,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const x=c.split(":")[0]??"unknown",j=await fs(g,Jt(b),x),de=pe(c);await Se(g,j,"authored",de,n==="success",n==="partial");for(const ne of a.slice(0,8)){const T=await $t(g,ne);await Se(g,j,"touched",T,!0),await gs(g,T,j)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const x=c.split(":")[0]??"unknown",j=p==="system"?"system":"service",de=await ms(g,m.trim(),x,j),ne=pe(c);if(await Se(g,ne,"affects",de,n==="success",n==="partial"),b){const T=`person:${pe(Jt(b))}`;await Se(g,T,"operates",de,!0)}for(const T of a.slice(0,8)){const O=`file:${pe(T)}`;await Se(g,O,"runs_in",de,!0)}}catch{}if(b&&(n==="success"||n==="partial")){const x={topic:c,outcome:n,what_worked:J,what_failed:te??"",severity:S,author:b,file_paths:a,commands:e,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},j=`cachly:lessons:${c}`;g.rpush(j,JSON.stringify(x)).catch(()=>{})}const W=n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C",ve=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",Ne=q?"updated":"stored",be=await Nn(Z);return[`${W} **Lesson ${Ne}:** \`${c}\` (${n}) ${ve} ${S} \xB7 Beleg: \`${D}\``,f.funde.length?`\u{1F512} **${f.funde.length} Geheimnis(se) geschwaerzt** vor dem Speichern (${f.funde.join("; ")}). Der Wert ist nicht im Brain \u2014 verweise kuenftig auf den Ort (z. B. Infisical-Pfad oder Variablenname).`:"",ro(s),le??"","",`**What worked:** ${J}`,te?`**What failed:** ${te}`:"",P?`**Context:** ${P}`:"",a.length>0?`**Files:** ${a.map(x=>`\`${x}\``).join(", ")}`:"",e.length>0?`**Commands:** ${e.map(x=>`\`${x}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(x=>`#${x}`).join(" ")}`:"","",q?`\u267B\uFE0F Updated (recall count: ${ce} \xB7 audit entries: ${Q.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${c}")\``,b&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${b}_${$.quelle!=="uebergeben"?` \xB7 aus ${$.quelle}`:""}) \u2014 visible in \`team_recall\``:"",v??"",l.length>0?`\u{1F517} Depends on: ${l.map(x=>`\`${x}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",d,xn(be,d),H.angaben.length?`\u{1F4E6} Gilt fuer ${H.angaben.map(x=>`\`${x}\``).join(", ")}${H.uebernommen?" (aus der Vorfassung uebernommen)":""} \u2014 passt das Projekt nicht, steht die Lektion im Abruf hinten und ist markiert.`:"",...H.fehler.map(x=>`\u26A0\uFE0F gilt_fuer nicht gespeichert, ${x}. Form: paket@bereich, zum Beispiel next@<15 oder python:fastapi@>=0.100 <0.110.`),Te&&L?xe?`\u21B7 Ersetzt \`${he}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${he}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin. Ohne \`grund\` steht dort 'Grund nicht erfasst' \u2014 eine Zeile (warum die alte falsch war) macht den Verweis pruefbar.`:Ce,...Y,..._e,h>0?`\u{1F5D3}\uFE0F ${h} relative Zeitangabe${h===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(K.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",Qn(J)??""].filter(x=>x!=="").join(`
|
|
3
|
-
`)}case"lesson_verified":{const{instance_id:f}=
|
|
4
|
-
`);const
|
|
5
|
-
`):[`\u26A0\uFE0F \`${
|
|
6
|
-
`)}case"recall_feedback":{const{instance_id:f}=
|
|
7
|
-
`);const _=u.eintrag,
|
|
8
|
-
`)}case"recall_best_solution":{const f=Date.now(),{instance_id:
|
|
9
|
-
`):"",me=(Date.now()-new Date(
|
|
10
|
-
`)}const
|
|
1
|
+
import{gitLesen as Pe,istCommitHash as hs,pruefeOrdner as et}from"../git-ohne-shell.js";import{createRequire as kt}from"node:module";import{calculateConfidence as vt,confidenceBadge as us,STRUCTURED_TEMPLATES as ds,CONFIDENCE_WARN_VALUE as fs}from"../confidence.js";import{kurzfassenHinweis as gs}from"../antwort-hinweis.js";import{pruefeMeldung as ms,wendeAn as ps}from"../pruefung-melden.js";import{ckgSlug as pe,extractProblemConcept as tt,ckgUpsertNode as je,ckgUpdateEdge as Se,ckgUpsertPersonNode as ws,ckgUpsertFileNode as St,ckgRecordCollaboration as ys,ckgUpsertServiceNode as _s}from"../ckg.js";import{safeJsonParse as z,scanKeys as De,leseOderNull as Re,darfHeraus as We}from"../utils.js";import{ersparteMinuten as Ct,istStarterLektion as st,zaehltAlsErsparnis as xt}from"../wertbeitrag.js";import{lessonPreviewLines as Ue,trimTo as bs}from"../lesson-preview.js";import{normalisiereZeit as nt,zaehleZeitangaben as ot}from"../zeit-normalisieren.js";import{abstentionSatz as $s,alterssatzFuerBelegte as ks,beurteileTreffer as vs,istBelegt as Ss}from"../abstention.js";import{meldeEinmal as at,meldeUndVermerke as Ye,fehlerText as it,OHNE_VEKTOREN as Cs,OHNE_DIENST as xs,OHNE_FRAGEVEKTOR as Ts,SINNPFAD_ABBRUCH as Ns,OHNE_SCHREIBVEKTOR as rt}from"../aussetzer.js";import{versuchStart as As,neueKennung as Es,wendeZuteilungAn as Is,schliesseVersuchAb as Ms}from"../versuch.js";function ct(F,D,P,ae=P){if(F.includes("lesson:best:")){const e=z(D,{});if(e&&typeof e=="object"&&(e.what_worked||e.what_failed||e.commands?.length))return Ue(e,{maxChars:P,indent:" "})}const f=bs(D,ae);return f?[f]:[]}const Tt=2e3,Nt=400;import{getRole as lt,ROLE_BADGE as Ds,getScopes as At,lessonVisibleToScope as Et,reviewModeEnabled as Bs,storeLessonProposal as Rs}from"./team.js";import{keywordSearch as Ze,treffeUeberDateipfad as Ls,wortindexEntwerten as It,tokenize as ht,splitMultiQuery as zs,levenshtein as Os,indexVocab as Mt,bestandHolen as Ps}from"../search.js";import{startetNochLeer as Dt,leeresBrainAntwort as Bt,startLage as ut,sofortAntwortNeuesBrain as js,neuesBrainBriefing as Ws}from"../leeres-brain.js";import{rerankByQuality as Fs,qualityMultiplier as Gs,extractLessonQuality as Ks}from"../rerank.js";import{computeEmbedding as xe,hasEmbedProvider as Le,EMBED_PROVIDER as Te}from"../embeddings.js";import{leserAktiv as Hs,leserPunkte as Vs,mischeMitLeser as Js}from"../leser.js";import{repariereFelder as qs}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Rt,NAME_VEKTOR_PRAEFIX as dt,ZWEIT_VEKTOR_PRAEFIX as Fe,packe as ze,textFuerVektor as Ge,textFuerNamensVektor as Lt,Vektorbestand as ft,VEKTOR_NACHTRAG as Us,NAME_VEKTOR_NACHTRAG as gt,ZWEIT_VEKTOR_NACHTRAG as Xe}from"../bedeutung.js";import{schreibeEingaenge as Ys,Eingangsbestand as Zs}from"../eingaenge.js";import{ordneNachHausordnung as Xs,rangWerte as Qs}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as en}from"../seltenheitsbestand.js";import{spurLegen as tn}from"../spuren.js";import{schlageErsetzungVor as sn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as zt,stufeSucheNachProjektversion as nn,versionsNotizen as on,versionsBanner as an}from"../gueltigkeit-version.js";const Ke=Us,rn=365;import{etikettenFuer as cn,lieferJournalSchluessel as Ot,JOURNAL_DECKEL as ln}from"../etiketten.js";import{klassifiziereFehlschlag as hn,suchProtokollSchluessel as mt,trichterSchluessel as Pt,SUCH_DECKEL as jt}from"../recall-trichter.js";import{leiteEntscheidungAb as un,entscheidungsZeile as Wt}from"../entscheidung-ableiten.js";import{bewerteTopf as dn,spreizeImTopf as Ft,reichereAn as fn,inhaltsWoerter as Gt,grobStamm as gn,GEWICHTE as mn,knapperSiegSatz as pn}from"../rangfolge.js";import{pruefeWirkung as wn,werteAus as yn,lehrwert as _n,leiteAb as bn}from"../wirkungsspur.js";import{merkeSuchlauf as pt}from"../suchstatistik.js";import{schreibeTopfNotiz as $n,topfProtokollAktiv as kn}from"../topf-protokoll.js";import{SINN_TOPF as vn,EINGANG_SCHWELLE as Sn,EINGANG_SORTIER_GEWICHT as Cn,ZWEIT_MODELL as Ve,ZWEIT_GEWICHT as xn,ZWEIT_MINDESTDECKUNG as Kt,NAHDUPLIKAT_SCHWELLE as Tn,LESER_TIEFE as Ht}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Vt,quelleZeile as Nn}from"../herkunft.js";import{doppelHinweis as An,leseDoppelKandidaten as En,mitFrist as In,pruefeDoppelung as Mn}from"../doppel-kandidat.js";import{merkeRecall as Dn,sitzungsKosten as Bn,vergissSitzungsKosten as Rn,kostenZeilen as Ln}from"../sitzungs-kosten.js";const $e=new ft,wt=new ft(6e4,dt),Qe=new ft(6e4,Fe),yt=new Zs,Je=new en,Jt=vn,zn=Sn,On=Cn;import{upgradeNudge as Pn}from"../upgrade-nudge.js";import{recallTiefe as qt,TIEFE_VOLL as jn,TIEFE_VOLL_MEHRTHEMIG as Wn}from"../recall-tiefe.js";import{nutzungInWorten as Fn,nutzungsSchluessel as Gn,verdichte as Kn}from"../werkzeug-nutzung.js";import{inWorten as Hn,lieferBild as Vn,lieferSchluessel as Jn,trefferSchluessel as qn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Un,autorHinweis as Yn,coautorAus as Zn,echterGitLeser as Xn,ermittleAutor as Qn,mitCoautor as eo,nurMensch as Ut}from"../autor.js";import{TOOLS as to}from"../tools.js";import{vorspannHinweis as so}from"../vorspann.js";import{autorAbzeichen as no,fremdanteil as oo}from"../autor-abzeichen.js";import{cachlyUrl as ao}from"../cachly-url.js";import{belegFuer as io}from"../schreibbeleg.js";import{schwaerzeFelder as ro}from"../geheimnis-filter.js";import{VERDACHT_TAG as _t,mitVerdachtTag as co,pruefeFelder as lo,verdachtsWarnung as ho}from"../tuersteher.js";import{fuerEigenenSpeicher as Oe,hinweise as He,istMarkiert as Yt,markiert as uo,markierungsWarnung as Zt,markierungsWarnungAusRohwert as Xt,zaehlHinweise as Qt}from"../schreibtor.js";import{istBlossesThema as es}from"../blosses-thema.js";import{zeitpunkt as ke}from"../zeitmessung.js";const qe=(()=>{try{const F=kt(import.meta.url);for(const D of["../../../package.json","../../package.json"])try{const P=F(D);if(P.name==="@cachly-dev/mcp-server"&&P.version)return P.version}catch{}}catch{}return"0.10.100"})(),fo=()=>{try{return kt(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},go={"0.10.119":["\u{1F50D} **Explainable briefings \u2014 provenance in every warning**"," \u{1F4CE} `/briefing` warnings now carry `outcome`, `author`, `learned_at` and `matched_on` (the context tokens that triggered the warning) \u2014 editors can show WHY a fix hint fired, not just what it claims.",' \u{1F9F0} VS Code 0.12.0 uses this: severity + confidence in the toast, full lesson card with provenance, "Not helpful" per-file suppression, reviewable CLS auto-learns.'," \u{1F9F9} CI docs now describe exactly what ships: scan mode uses the REST `/scan` endpoint, the GitLab template covers learn/scan/confirm."],"0.10.115":["\u{1F527} **`brain_get_pref` + `brain_set_pref` \u2014 persistent Brain preferences**"," \u{1F4D6} `brain_get_pref` reads back any stored preference (omit key to list all)."," \u270F\uFE0F `brain_set_pref` saves a preference to Redis \u2014 survives restarts, scoped per Brain instance.",' \u{1F4A1} Known key: `auto_changelog` \u2014 set to "false" to silence the new-lessons digest at session_start.'," \u{1F4CA} 140 MCP tools"],"0.10.114":["\u{1F4CB} **`brain_changelog` \u2014 weekly knowledge digest in one call**"," \u{1F4C5} Generates a grouped Markdown changelog of lessons learned in the last N days."," \u{1F465} Grouped by topic category, annotated with author, recall count, and confidence \u2014 paste directly into standup or Slack."," \u2699\uFE0F Params: `days` (default 7), `max_lessons` (default 30), `include_failures` (default true)."," \u{1F4CA} 138 MCP tools"],"0.10.113":["\u{1F4C8} **Week-over-week savings trend in `cache_stats`**"," \u{1F4C5} `cache_stats` now shows **7-day hits** + **WoW trend %** (e.g. `+23.0% vs prev week`) so ROI momentum is visible, not just the cumulative total."," \u2B07\uFE0F Goes red (\u{1F4C9}) on drops, green (\u{1F4C8}) on growth \u2014 first week always shows +100% (new)."," \u{1F527} Backed by new `CountHitsInWindow` repo method + `hits_last_7d`, `hits_prev_7d`, `week_over_week_pct` fields in `SavingsEstimate`."," \u{1F4CA} 137 MCP tools"],"0.10.112":["\u2699\uFE0F **Configurable cost_per_call_usd \u2014 accurate ROI for any LLM**"," \u{1F4A1} New `set_cost_per_call` tool: set your real per-call cost (claude-opus-4.8 \u2192 $0.02, gpt-5.5 \u2192 $0.015, claude-sonnet-4.6 \u2192 $0.009, claude-haiku-4.5 \u2192 $0.001) so savings estimates in `cache_stats` reflect your actual bill."," \u{1F527} New API: `PUT /api/v1/instances/:id/cost-per-call` \u2014 persisted per instance, used by `cache_stats`, org savings, and SSE analytics stream."," \u{1F4CA} 137 MCP tools"],"0.10.111":["\u{1F3E2} **Org-wide ROI + GitLab CI \u2014 the CFO number, aggregated**"," \u{1F4B0} `cache_org_stats` now shows **org-wide Tokenmaxxing ROI**: total savings summed across every instance in your org, monthly projection, top-5 instances by savings. One number for the whole team."," \u{1F50C} Backed by new API endpoint `GET /api/v1/orgs/:id/savings` (org members only)"," \u{1F98A} GitLab CI integration: `brain-from-ci-gitlab.yml` \u2014 two `.post` jobs (on_success/on_failure), same helper script, pipeline never fails because of Brain push"," \u{1F6E0}\uFE0F GitHub Action template fixed: `secrets.*` in job-level `if` is invalid \u2014 guard removed (helper script skips cleanly on missing secrets)"," \u{1F4CA} 136 MCP tools"],"0.10.110":["\u{1F3E2} **Zero friction: ROI-Projektor, Org-Shared-Cache, CI ready-to-paste**"," \u{1F4C8} `cache_stats` \u2014 zero-hit projection calculator: shows expected monthly savings for 5/10/20-dev teams before a single cache hit lands. ROI visible from day 1."," \u{1F3E2} New `cache_org_stats` \u2014 shared org-level cache stats across multiple instances. Convention-based (`org:{id}:sem`), zero API changes needed."," \u{1F517} `cache_set`/`cache_get` now accept optional `org_id` \u2014 write to personal + org namespace, fall back to org on miss. Fully backwards-compatible."," \u{1F4CB} Copy-paste CI integration: `brain-from-ci-action.yml` \u2192 Brain self-calibrates confidence on every GitHub Actions run. No config beyond two repo secrets."," \u{1F4CA} 136 MCP tools"],"0.10.109":["\u{1F4B0} **Tokenmaxxing ROI + Closed-loop CI learning**"," \u{1F4CA} `cache_stats` now shows a **Tokenmaxxing ROI** section \u2014 total tokens saved, monthly cost projection, and top 3 most-cached prompts. Finally a number you can show the CFO."," \u{1F504} New `brain_from_ci` \u2014 bulk-ingest CI history into the Brain (red\u2192green = learned fix, green\u2192red = CKG causal edge). The brain_from_git equivalent for CI. Bootstrap the Brain from your CI logs in one call."," \u{1F4CA} 134 MCP tools"],"0.10.108":["\u{1F9E0} **Focused briefing + trustworthy autopilot**"," \u{1F3AF} New `session_start_summary` \u2014 top-N focused briefing by topic. Scores lessons by relevance \xD7 confidence + recall_count + severity + recency. Use it for a quick pre-brief without loading the full Brain.",' \u{1F91D} Autopilot template now explains the data flow upfront ("your own Brain, EU-hosted, no third parties") \u2014 no more friction with cautious AI assistants during onboarding'," \u{1F4CA} 132 MCP tools"],"0.10.107":["\u{1F3AF} **Recall@3 gap closed \u2014 the moat proof got sharper (the head-to-head that matters)**"," \u{1F50D} External-corpus Recall@3 **82.1% \u2192 98.2%** \xB7 Precision@1 **80.4%** \xB7 MRR **89.0%** \u2014 now ahead of flat-file memory on every metric"," \u{1F9EC} Root-cause fix: documents are no longer indexed with cross-lingual synonyms (the symmetric-expansion bug inflated any doc containing a common word ~28\xD7, burying topic-specific lessons). Queries still expand \u2014 a \u65E5\u672C\u8A9E query still finds English lessons."," \u2696\uFE0F Reranker now compresses BM25 with score^0.3 before applying lesson quality, so a proven success can overtake a text-similar failed attempt even when the distractor scores 5\u20136\xD7 higher in raw BM25"," \u{1F6E1}\uFE0F CI bench gate widened to both home + external corpora with committed floors (`npm run bench:gate`) \u2014 recall quality can never silently regress again"," \u{1F4CA} 121 MCP tools"],"0.10.98":['\u{1F310} **Model-Neutrality as Feature (W9) \u2014 "Bring your own model, keep your brain."**'," \u{1F50C} New `brain_portability()` \u2014 shows your Brain ID, all compatible MCP clients, and ready-to-paste config snippets for each; proves the same Brain works in Claude, Cursor, Copilot, Windsurf, Cline, Zed and more"," \u{1F9E0} Your lessons, crystals, and predictions are model-agnostic \u2014 no vendor lock-in at the memory layer",' \u{1F4D6} New docs: cachly.dev/docs/model-neutral \u2014 "Same Brain, Any Model" guide with live config examples'," \u{1F4CA} 121 MCP tools (new: `brain_portability`)"],"0.10.97":['\u{1F4A0} **Team Crystallize (W8) \u2014 the team-wide, causal counter to per-user "Dreaming"**'," \u{1F9EC} New `team_crystallize()` \u2014 surfaces fixes that 2+ teammates *independently converged on*, the one thing a single-user memory structurally can't build",' \u{1F9E9} Cross-person clustering: groups structurally similar problems across people & namespaces (e.g. "pool exhaustion" solved the same way in payments, auth & db)',' \u{1F465} Each pattern names who converged \u2014 instant "ask @alice and @bob, they both hit this"'," \u{1F48E} Shows up in `crystal_view` alongside your per-brain crystal"," \u{1F4CA} 120 MCP tools (new: `team_crystallize`)"],"0.10.96":["\u{1F510} **Roles & Team-Scopes now ENFORCED (W6) \u2014 the enterprise governance layer**"," \u{1F6E1}\uFE0F `team_confirm` is now reviewer-gated, `team_learn` blocks viewers (recall-only) \u2014 roles stop being cosmetic the moment an admin is assigned"," \u{1F4DC} New `team_audit` tool \u2014 immutable, admin-only trail of every role change & lesson confirmation, for compliance & security reviews"," \u{1F513} Zero impact on open teams: governance activates only once you bootstrap an admin; before that everything works exactly as before"," \u{1F4CA} 119 MCP tools (new: `team_audit`)"],"0.10.95":["\u{1F9E0} **Domain Brain Marketplace (W10) \u2014 bootstrap your Brain with curated community knowledge**"," \u{1F6D2} `brain_marketplace()` \u2014 browse installable packs of high-trust lessons by domain: \u2638\uFE0F Kubernetes, \u{1F510} Auth, \u{1F5C4}\uFE0F Database, \u269B\uFE0F React, \u{1F4B3} Payments & more",' \u{1F4E6} `brain_install(slug="k8s")` \u2014 merges a domain\'s verified lessons into your Brain; live in `smart_recall` instantly, even offline',' \u{1F6E1}\uFE0F Idempotent + non-destructive: installed lessons are tagged `source:"marketplace:<slug>"` and NEVER override your own'," \u{1F50C} New gRPC `Subscribe` RPC \u2014 agents get new lessons streamed live the moment they're learned (completes the M2M loop with `Learn`)"," \u{1F4CA} 118 MCP tools (new: `brain_marketplace`, `brain_install`)"],"0.10.94":['\u{1F91D} **Person\u2194Person Collaboration Graph (W5) \u2014 "Frag X und Y, die haben das zusammen gel\xF6st"**'," \u{1F578}\uFE0F New `brain_collab_pairs()` tool: shows every contributor pair who've touched the same files or recalled each other's lessons \u2014 ideal for onboarding and bus-factor analysis"," \u{1F4E1} `smart_recall` now wires CKG `collaborates` edges live when cross-author reuse fires \u2014 collaboration graph grows with every team recall"," \u26A0\uFE0F Bus-factor section: flags solo contributors whose knowledge no teammate has yet recalled"," \u{1F4CA} 116 MCP tools (new: `brain_collab_pairs`)"],"0.10.93":['\u{1F5FA}\uFE0F **`brain_plan` \u2014 your Brain goes from "what did we learn?" to "what should I do?"**',` \u{1F9ED} Give it a task you're about to start ("upgrade Postgres 14\u219216") and it returns an ordered, grounded action plan: ranked failure modes to avoid, proven fix steps (dependency-aware, with commands), and a pre-flight checklist \u2014 all from your own lessons`,' \u{1F52C} Generative layer on the CKG: where `brain_predict` answers "what might fail?", `brain_plan` answers "what, in what order?"'," \u{1F4CA} 115 MCP tools (new: `brain_plan`)"],"0.10.92":["\u{1F44B} **Welcome-back digest \u2014 re-entry after a week away now leads with what changed**"," \u{1F331} `session_start` detects a gap \u2265 7 days and surfaces how many lessons your Brain gained while you were gone (git, CI & teammates kept it learning), with the freshest topics"," \u{1F9E0} Zero extra latency \u2014 the digest is computed from data session_start already loads"," \u{1F50C} New gRPC `Learn` RPC (M2M write path) \u2014 agents & CI can now teach the Brain directly, byte-compatible with the MCP lesson format"," \u{1F4CA} 115 MCP tools"],"0.10.91":["\u{1F550} **Lesson-anchored time attribution \u2014 every recall shows when it was learned and how much it saves**",` \u{1F4A1} "Brain saved you" banner now includes: when the lesson was learned (e.g. "12 May"), estimated original debug cost by severity (critical=2h, major=1h, minor=20min), and team attribution when a teammate's lesson fires`,' \u{1F4C5} Origin date formatted as "12 May" (same year) or "12 May 2024" (different year) \u2014 no clutter',' \u{1F465} Cross-author recalls now show "@author" on the same banner line \u2014 the "team knowledge reuse" value is front-and-center'," \u{1F4CA} 115 MCP tools"],"0.10.90":["\u{1F4CA} **External benchmark corpus v2 \u2014 the proof is now statistically solid**"," \u{1F9EA} Expanded from 8 queries \u2192 61 lessons / 56 queries across 10 real-world engineering domains (k8s, DB, auth, CI, frontend, API, payments, observability, network, Node.js, security, infra)"," \u2694\uFE0F 10 adversarial distractors added \u2014 failure lessons that share the exact same vocabulary as the query, forcing the quality reranker to earn its lift"," \u{1F4C8} Results on the larger corpus: cachly +2.9% Precision@1 vs flat-file, +12.5% vs raw BM25 baseline \u2014 on a harder dataset, not an easy one"," \u{1F4CA} 115 MCP tools"],"0.10.89":["\u26A1 **One-command onboarding \u2014 `autopilot` is now the single canonical setup**"," \u{1F680} Every surface (README, docs, emails, dashboard, blog) now leads with `npx @cachly-dev/mcp-server@latest autopilot` \u2014 one command signs you in, configures every editor, and bootstraps from git",' \u{1F9F9} Retired the split-brain instructions (legacy `@cachly-dev/init` wrapper + the old "three steps") so there\'s exactly one thing to copy-paste'," \u{1F527} Fixed a build-breaking duplicate `export` on buildClaudeMdBlock that failed CI on v0.10.88"," \u{1F522} Version hygiene \u2014 package.json, server.json, lockfile and MCP_VERSION resynced (server.json/lockfile were stuck at 0.10.85)"," \u{1F4CA} 115 MCP tools"],"0.10.88":["\u2705 **Honest setup + tested config writer (v0.10.88)**",' \u{1F512} setup/autopilot now report the truth: if no editor config could be written it exits non-zero with the exact failures instead of falsely claiming "Brain is ready"'," \u{1F4CA} New setup_config_write_failed telemetry \u2014 permission/path failures that block activation are now visible in reporting"," \u{1F9EA} 24 new unit tests for the config writer (buildServerEnv, buildMcpConfig, mergeMcpConfig, buildClaudeMdBlock) \u2014 the merge logic that must never clobber your other MCP servers is now regression-guarded"," \u{1F4CA} 115 MCP tools"],"0.10.87":["\u{1F310} **Multi-editor auth persistence + full activation telemetry (v0.10.87)**"," \u2705 JWT + instance_id now persisted to Cursor (`~/.cursor/mcp.json`) and Windsurf configs on auth \u2014 no more infinite re-auth for non-Claude-Code users",' \u{1F4E1} `device_flow_failed(reason="timeout")` now fires when sign-in window expires \u2014 blind spot in the funnel is gone'," \u{1F4E1} `auto_provision_failed` now fires on network errors too (was only HTTP non-2xx)"," \u{1F4E1} `brain_from_git_failed` fires with error reason when auto-bootstrap throws \u2014 no more empty brain with no explanation",' \u2728 Git bootstrap shows lesson count in session_start: "Brain bootstrapped \u2014 23 lessons loaded" \u2014 the WOW moment'," \u{1F527} API: McpEvent stores brain quality metrics (fixes/features/refactors/total) \u2014 git learning quality now measurable"," \u{1F4CA} 115 MCP tools"],"0.10.86":["\u{1F6E1}\uFE0F **Zero-friction activation \u2014 your Brain self-heals into existence**"," \u{1F527} Auto-provision now runs on *any* tool call, not just at sign-in \u2014 if instance creation ever fails once, the next call recovers it automatically"," \u{1F91D} Parallel tool calls on startup are coalesced into one resolve (no more duplicate-instance races)",' \u{1F4AC} Clearer "instance still starting" message \u2014 leads with "just retry", no manual config needed'," \u{1F4C8} New activation-funnel telemetry: install \u2192 sign-in \u2192 provision, so silent churn is visible"," \u{1F4CA} 115 MCP tools"],"0.10.85":["\u{1F680} **One-command onboarding \u2014 `npx @cachly-dev/mcp-server@latest autopilot`**"," \u26A1 Single command does it all: auth \u2192 instance \u2192 every editor config \u2192 CLAUDE.md \u2192 Brain bootstrap \u2192 health"," \u{1F331} Seeds the 16-lesson starter corpus when git history is empty \u2014 your first smart_recall hits instantly"," \u{1F916} Fully automatic (zero prompts); `setup` remains for interactive, pick-your-editors onboarding"],"0.10.84":["\u{1F916} **M2M & agent-ecosystem reach \u2014 cachly for every caller, human or machine**"," \u{1F511} OAuth2 `client_credentials` grant \u2014 set CACHLY_CLIENT_ID + CACHLY_CLIENT_SECRET for fully headless auth (CI, agents, AI-to-AI)"," \u{1F5C2}\uFE0F `npx ... tool-specs --format=openai|anthropic|langchain` \u2014 export all 121 tools in any framework's dialect"," \u{1F310} `npx ... openapi` \u2014 OpenAPI 3.1 doc (1 POST path per tool) for Assistants / codegen / Postman"," \u{1F9EA} 14 new tests: client_credentials helpers, all four spec dialects, OpenAPI required-body inference"],"0.10.83":["\u{1F9E0} **Brain Viz \u2014 3D graph export**"," \u{1F310} `brain_graph(instance_id)` \u2014 exports the Causal Knowledge Graph as a render-ready {nodes, links} payload"," \u{1F3A8} Schema `cachly.brain_graph/v1`: node kinds (concept/person/file/service) with color groups + size, edges with confidence"," \u{1F5A5}\uFE0F Consumed verbatim by the 3D frontend (react-force-graph-3d / three.js) \u2014 the visual brain map",' \u{1F50E} Filters: `domain`, `min_confidence`, `max_nodes` (with truncation flag), `format="summary"`'," \u{1F9EA} 10 tests: kind detection, dangling-edge pruning, confidence/domain filters, schema contract"," \u{1F4CA} 115 MCP tools"],"0.10.82":["\u{1F4E1} **Telemetry API contracts \u2014 dashboard ingest pipeline prepared**"," \u{1F5C2}\uFE0F `src/telemetry-types.ts` \u2014 canonical event types + resolved event format (TelemetryEventRaw / TelemetryEventResolved)"," \u{1F510} `user_fingerprint` \u2014 non-reversible JWT sub hash, PII-free user clustering for dashboard"," \u{1F4CA} `metrics` block on key events: smart_recall (hit/topic), brain_from_git (fixes/features/total), brain_seed_starter (seeded_count)"," \u{1F6A6} Internal API contract documented: GET /internal/telemetry/stream \u2192 TelemetryEventResolved[]"],"0.10.81":["\u23F1\uFE0F **Onboarding-Bench \u2014 time-to-first-recall, now measured**"," \u{1F4D0} `npm run bench:onboarding` \u2014 cold (empty) vs seeded (starter) first-query hit rate via the real search engine"," \u{1F4CA} Result: first-query hit@1 **0% \u2192 87.5%**, hit@3 **0% \u2192 100%**, MRR **0% \u2192 93.8%**"," \u{1F6E1}\uFE0F CI-defended in `onboarding-bench.test.ts` (cold must answer 0%, seeded thresholds enforced)"," \u{1F4CB} `PLAN-DASHBOARD.md` \u2014 full build spec for the external Team-Knowledge-Reuse dashboard (separate repo)"],"0.10.80":["\u{1F331} **Starter corpus \u2014 first recall in seconds, not sessions**"," \u{1F4DA} `brain_seed_starter(instance_id)` \u2014 seed 16 curated universal lessons (Docker cache, JWT skew, K8s OOM, N+1, cache stampede\u2026)"," \u{1F680} Auto-seeds on first session when git history is empty/shallow \u2014 your first `smart_recall` returns a real hit",' \u{1F6E1}\uFE0F Tagged `source:"starter"`, idempotent, never overrides your own lessons'," \u23F1\uFE0F Directly attacks time-to-first-recall (<2 min goal); stamps `born_at` on seed"," \u{1F9EA} 18 new tests: seeding, idempotency, topic_filter, force, user-lesson protection"," \u{1F4CA} 113 MCP tools"],"0.10.79":["\u{1F310} **Brain Marketplace \u2014 full shareable Brain lifecycle**"," \u{1F4CB} `brain_share_list(instance_id)` \u2014 see all your public shares with lesson counts + share IDs"," \u{1F5D1}\uFE0F `brain_unshare(share_id)` \u2014 revoke a share; link goes dead immediately"," \u{1F50D} `brain_discover(query, topic)` \u2014 search public Brains in the cachly marketplace"," \u{1F4E4} `publish` CLI \u2014 fancy card + share URL; `--public` for discoverable; `--title` custom name"," \u{1F9EA} stress tests: team_expertise_map with 50 contributors, chain import/unshare, discover fallback"," \u{1F4CA} 112 MCP tools"],"0.10.78":["\u{1F310} **Phase 3: Shareable / Public Brains**",' \u{1F4E4} `brain_share(instance_id="...")` \u2014 export a Brain snapshot as a shareable link (public or unlisted)',' \u{1F4E5} `brain_import(instance_id="...", share_id="...")` \u2014 import any public Brain into yours (1-line)'," \u{1F50D} Optional topic_filter, min_confidence, topic_prefix \u2014 precise control over what gets shared/imported"," \u{1F512} dry_run mode on both tools \u2014 preview before committing"," \u{1F9EA} Regression suite added: share handler, buildServerEnv, stdout cleanness"," \u{1F4CA} 109 MCP tools"],"0.10.77":["\u{1FA79} **Frictionless onboarding + first-class self-hosting/BYOK**"," \u{1F680} Editor-launched server now serves all tools even before sign-in \u2014 zero-credential device flow finally triggers on first tool call"," \u{1F512} No more stdout pollution: stdio JSON-RPC stream stays clean when no JWT is set"," \u{1F3E0} `setup --api-url` / `init --api-url` point at a self-hosted backend; URL baked into config only when non-default",' \u{1F9EC} `health` now shows your BYOK embedding provider + accepts cky_ long-lived keys (was a false "invalid token" failure)'],"0.10.76":["\u{1F4CA} **Agent-trace benchmark + editor matrix + setup timer**"," \u{1F4C2} New `agent-traces-corpus.json` \u2014 22 lessons, 15 queries, realistic AI-agent debug patterns"," \u{1F3C6} Benchmark result: **P@1 +66.7%, MRR +9.5% vs flat-file** (adversarial failure-distractors per category)"," \u{1F4CB} README: first-class editor support matrix (Claude Code, Cursor, Windsurf, VSCode, Cline, Continue.dev, Zed)",' \u23F1\uFE0F setup now shows elapsed time + "Brain is ready" banner at the end'],"0.10.75":["\u{1FA79} **Setup hardened \u2014 works from the VSCode plugin & any non-TTY terminal**"," \u{1F50C} `setup` no longer hangs on a non-interactive stdin (VSCode tasks, CI) \u2014 auto-detects + runs in automatic mode"," \u{1F510} Device-flow now uses the API proxy first (the old direct-Keycloak call returned 403) \u2014 sign-in actually completes"," \u{1F310} When auto sign-in is unavailable, the browser opens with a step-by-step API-key guide instead of a silent paste prompt"," \u{1F4CA} Funnel fix: `device_flow_completed` / `device_flow_failed(reason)` now emitted from setup too"],"0.10.73":["\u{1F510} **Team visibility scopes + one-command init + external bench**",' \u{1F195} `team_grant_scope` / `team_scopes` \u2014 scope lessons to a sub-team (group="security"); only members + admins recall them',' \u{1F3F7}\uFE0F `learn_from_attempts(group="...")` \u2014 orthogonal to private; smart_recall enforces it per requester'," \u26A1 `init` is now zero-arg + idempotent (reuses saved creds, only writes what changed, <60s)"," \u{1F4E6} `npm run bench:external` \u2014 prove recall-lift on a third-party-labeled corpus (portable JSON format)"," \u{1F4CA} 107 MCP tools"],"0.10.72":["\u{1F451} **Role model \u2014 admin \xB7 reviewer \xB7 contributor \xB7 viewer (Phase 3)**"," \u{1F195} `team_assign_role` \u2014 establish governance; first call bootstraps, admins manage the rest"," \u{1F195} `team_whoami` \u2014 see your own role and capabilities"," \u{1F195} `team_roster` \u2014 full team role table (\u{1F451}\u{1F6E1}\uFE0F\u270F\uFE0F\u{1F441}\uFE0F)"," \u{1F6E1}\uFE0F `team_confirm` is now role-aware \u2014 admin/reviewer auto-get senior weight; contributor gets peer; no self-promotion"," \u{1F451} Setup CLI now prompts for governance bootstrap (idempotent). 105 MCP tools"],"0.10.71":['\u{1F6E1}\uFE0F **Self-healing auth** \u2014 no more silent "0 recalls because the token quietly died"'," \u267B\uFE0F Near-expiry tokens auto-refresh into a long-lived key while still valid (zero interaction)"," \u{1F501} A rejected (401) call self-heals once and retries before surfacing an error"," \u{1F4E3} If the credential is truly dead, session_start + get_api_status say so plainly + how to fix"],"0.10.70":["\u{1F6F0}\uFE0F **Service/System nodes in the graph (Phase 3)** \u2014 the brain now models running systems",' \u{1F195} `brain_service_map(service="prometheus")` \u2014 who owns it + every failure/fix known',' \u{1F3F7}\uFE0F Tag lessons with `service="..."` (`service_kind="system"` for infra) \u2014 person\u2192operates, file\u2192runs_in edges',` \u{1F6A8} Incident triage: a restarting pod \u2192 instant "who knows this and what's broken before"`," \u{1F4CA} 102 MCP tools"],"0.10.69":["\u{1F4C1} **Personalized context-aware recall (Phase 3)** \u2014 pass `context_files` to `smart_recall`"," \u{1F3AF} Lessons learned on your current files bubble up \u2014 even when the query doesn't name the file"," \u{1F3F7}\uFE0F `\u{1F4C1} context match` badge on every file-boosted result so you know WHY it ranked up"," \u2705 Works alongside keyword, semantic, CKG, and governance signals \u2014 a 6th ranking dimension"],"0.10.68":["\u{1F91D} **Collaboration graph (Phase 3)** \u2014 person\u2194person edges from shared files"," \u{1F465} `brain_who_knows` now shows who the top expert frequently works with",' \u{1F68C} Bus-factor insight: "ask X and Y together \u2014 they solved this on shared files"'," \u{1F6E1}\uFE0F Stability: every network call in the agent hot path is now timeout-bounded"],"0.10.64":["\u{1F4C8} **The three decisive metrics, now measurable**"," \u23F1\uFE0F `brain_metrics()` \u2014 time-to-first-recall, recall-lift, team-knowledge-reuse in one view"," \u{1F465} Cross-author reuse tracked: recall a teammate's lesson \u2192 counted + surfaced inline"," \u{1F6E1}\uFE0F Stability: scans now capped + timed out (a huge keyspace can't hang the agent)"],"0.10.61":["\u{1F3AF} **Phase 3C: 100 MCP tools milestone \u2014 zero-setup knowledge graph**"," \u{1F504} `brain_from_git` now auto-builds Person+File nodes from git history (zero setup!)"," \u{1F50D} `skill_gaps()` \u2014 find domains with unresolved failures, missing attribution"," \u{1F4CA} `brain_coverage()` \u2014 scored 0-100 health report: lessons \xB7 attribution \xB7 file coverage"],"0.10.60":["\u{1F195} **Phase 3B: File map + team overview + visibility**"," \u{1F4C1} `brain_file_map(file_paths=[...])` \u2014 experts + lessons per file before you touch it"," \u{1F5FA}\uFE0F `team_expertise_map()` \u2014 full team skills matrix in one table",' \u{1F512} `visibility: "private"` on `learn_from_attempts` \u2014 private notes never leak to smart_recall'," \u{1F4CA} 98 MCP tools"],"0.10.59":["\u{1F195} **Phase 3A: Org-wide knowledge graph**",' \u{1F465} `brain_who_knows(topic="...")` \u2014 find your team\'s experts on any topic instantly',' \u{1F578}\uFE0F Person + File nodes auto-built from `learn_from_attempts(author="...", file_paths=[...])`'," \u{1F464} Author attribution now shown inline in `smart_recall` results"," \u{1F4CA} 96 MCP tools \xB7 386 tests green"],"0.10.58":["\u{1F9F9} Zero lint warnings \u2014 all unused imports cleaned across every handler","\u2705 Build: 0 errors, 0 warnings \xB7 379 tests green"],"0.10.57":[`\u{1F195} **What's new in v${qe}:**`," \u{1F527} **Critical fix** \u2014 corrected the npm bin/main entry path (`dist/src/index.js`); 0.10.50\u20130.10.52 shipped a broken entry point"," \u{1F527} Version hygiene \u2014 synced package.json, server.json, lockfile, MCP_VERSION; `latest` now points forward again"," \u2705 Accurate tool count (95) across README, server.json, CLI banners"," \u2705 Includes all Phase 2/3 work: quality reranking, Cachly-Bench, hybrid + CKG recall, team_confirm governance"],"0.10.52":[" \u2705 `smart_recall` \u2014 CKG traversal as Layer 3: finds lessons that FIXED causal-graph-similar problems (\u{1F578}\uFE0F causal graph badge)"," \u2705 Bench corpus expanded: governance adversarial pair proves review-boost end-to-end (+22% P@1 headline)"," \u{1F527} Import cleanup: unused symbols removed from brain.ts (no functional change)"," \u{1F4A1} `smart_recall` now shows keyword / semantic / CKG / hybrid match type for every result"],"0.10.51":[" \u2705 `team_confirm` \u2014 human review raises lesson recall ranking (\u{1F6E1}\uFE0F senior / \u2714\uFE0F peer)"," \u2705 Governance-aware recall \u2014 confirmed lessons outrank unreviewed auto-learned entries"],"0.10.50":[" \u2705 `smart_recall` \u2014 unified keyword + semantic hybrid list (one ranked result, not two sections)",' \u2705 `smart_recall` \u2014 "Brain saved you here" banner surfaces time saved inline per proven lesson'," \u2705 Quality reranking \u2014 proven successes outrank symptom-dense failures (+11% Precision@1)"," \u2705 Cachly-Bench \u2014 IR benchmark with CI regression guard (see BENCH.md for the proof)"," \u{1F527} Contradiction resolution now persisted to Redis (90-day TTL)"," \u{1F4A1} Run `smart_recall` to see your Brain's recall quality in action"],"0.10.49":[" \u2705 `brain_from_git` \u2014 auto-seed your Brain from git history in seconds"," \u2705 `brain_predict_failures` \u2014 predict CI/build failures before they happen"," \u2705 VS Code extension \u2014 Brain status bar, ambient learning, CodeLens hints"," \u2705 Team Brain \u2014 share lessons across your whole engineering team"," \u{1F527} Stability \u2014 auto-expiring memory keys, longer provisioning wait, robust recall"]},ba=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"]),mo=ao("/billing","upgrade"),ts=new Map,ss=new Set,po=1680*60*60;function wo(F=new Date){return`cachly:quota:recalls:${F.toISOString().slice(0,7)}`}async function bt(F){try{const D=wo();await F.incr(D)===1&&await F.expire(D,po)}catch{}}function ns(F){return`cachly:stats:drei-ausgaenge:${F}`}async function $t(F,D,P){try{await F.hincrby(ns(D),P,1)}catch{}}function os(F,D,P,ae){bt(F),pt(F,P,ae);const f={ts:new Date().toISOString(),frage:P.slice(0,200),geliefert:[]};(async()=>{const e=mt(D);await F.lpush(e,JSON.stringify(f)),await F.ltrim(e,0,jt-1)})().catch(()=>{}),$t(F,D,"schweigen")}async function as(F){const D={tage:0,rekord:0};try{const P=await F.get("cachly:streak:current"),ae=z(P,null),f=new Date().toISOString().slice(0,10);if(ae){const e=ae.last_date,u=new Date(Date.now()-864e5).toISOString().slice(0,10);e===f?(D.tage=ae.days,D.rekord=ae.record):e===u?(D.tage=ae.days+1,D.rekord=Math.max(D.tage,ae.record),await F.set("cachly:streak:current",JSON.stringify({days:D.tage,last_date:f,record:D.rekord}))):(D.tage=1,D.rekord=ae.record,await F.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:D.rekord})))}else D.tage=1,D.rekord=1,await F.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:1}))}catch{}return D}async function is(F,D,P){await F.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:D,provider:P}),"EX",86400)}async function rs(F,D){const P=ts.get(F);if(P&&P.expiresAt>Date.now())return P.gate;try{const ae=await D(`/api/v1/instances/${F}/memory`),f=ae?.recall_limit??-1,e=ae?.total_recall_count??0,u={reached:f>0&&e>=f,limit:f,used:e,goodwillMessage:ae?.goodwill_message,notice:ae?.notice};return ts.set(F,{gate:u,expiresAt:Date.now()+6e4}),u}catch{return{reached:!1,limit:-1,used:0}}}const yo={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function $a(F,D,P,ae){const f=await _o(F,D,P,ae),e=yo[F];if(e&&typeof f=="string")try{Dn(String(D.instance_id??""),String(D[e]??""),f.length)}catch{}return f}async function _o(F,D,P,ae){switch(F){case"learn_from_attempts":{const f=ro(D),e=lo(f.felder),u=e.length?{...f.felder,tags:co(f.felder.tags)}:f.felder,{instance_id:_,topic:o,outcome:n,what_worked:N,what_failed:a="",context:r="",severity:S="major",file_paths:i=[],commands:t=[],tags:C=[],depends_on:l=[],author:c="",visibility:k="team",service:m="",service_kind:p="service",group:I="",grund:A="",ersetzt:E="",gilt_ab:s="",gilt_fuer:ie}=u,{what_worked:ue,what_failed:ge="",context:me=""}=qs({what_worked:N,what_failed:a,context:r}),d=await P(_),H=new Date,oe=H.toISOString();let V=zt(ie,void 0);const X=s&&!Number.isNaN(Date.parse(String(s)))?new Date(String(s)):H,J=nt(ue,X),te=nt(ge,X),j=nt(me,X),h=ot(ue,X)+ot(ge,X)+ot(me,X),$=Qn({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:Xn(process.env.CACHLY_WORKSPACE??process.cwd())});let y="";try{y=Zn(await d.get(`cachly:prefs:${Un}:${_}`))}catch{}const b=eo($.autor,y),v=Yn($);if(k!=="private"&&await Bs(d,_))return Rs(d,o,{topic:o,outcome:n,what_worked:J,what_failed:te,context:j,severity:S,file_paths:i,commands:t,tags:C,depends_on:l,...V.angaben.length?{gilt_fuer:V.angaben}:{},...b?{author:b}:{},source:Vt(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:k,recall_count:0,ts:oe,confidence:1,version:3});const R=o.split(":")[0],K=ds[R],Y=[];if(K)for(const x of K.required)x==="commands"&&t.length===0&&Y.push(`\u{1F4CB} ${K.hint}`);let U=!1,ce=0,ye,Q=[];const q=await d.get(`cachly:lesson:best:${o}`),Ne=String(A??"").trim();if(q&&!Ne)return[`\u270B **Update abgewiesen:** \`${o}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
|
+
`);if(q)try{const x=JSON.parse(q);V=zt(ie,x.gilt_fuer),ce=x.recall_count??0,ye=x.last_recalled_at,Q=x.audit_trail??[],Q.push({ts:oe,action:"updated",prev_outcome:x.outcome,grund:Ne}),Q.length>20&&(Q=Q.slice(-20)),U=!0;const W=[];if(x.outcome==="success"&&n==="failure"?W.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."):x.outcome==="failure"&&n==="success"&&W.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),W.length>0){Q[Q.length-1].action="contradiction-resolved";try{const de=pe(o),ne=pe(`resolution:${o}`);await Se(d,de,"contradicts",ne,!1)}catch{}try{const de=`cachly:contradictions:${o}`,ne=x.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await d.rpush(de,JSON.stringify({ts:oe,prev_outcome:x.outcome,new_outcome:n,direction:ne})),await d.ltrim(de,-50,-1),await d.expire(de,180*86400)}catch{}W.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${o}")\` to resolve via expert agent voting.`)}}catch{}else Q=[{ts:oe,action:"created"}];const _e=[];if(n==="failure"){const x=[],W=d.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((ne,T)=>{W.on("data",O=>x.push(...O)),W.on("end",ne),W.on("error",T)});const de=o.split(/[:\-_]/).filter(ne=>ne.length>2);for(const ne of x.slice(0,50)){const T=await d.get(ne);if(T)try{const O=JSON.parse(T);if(O.outcome!=="success")continue;const re=(O.topic??"").split(/[:\-_]/).filter(Ie=>Ie.length>2);if(de.filter(Ie=>re.includes(Ie)).length>=1&&O.topic!==o){_e.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${O.topic}\` (success, ${O.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${O.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${O.topic}", ..., severity="critical")\``);break}}catch{}}}for(const x of l){const W=`cachly:dep:${x}`,de=await d.get(W),ne=z(de,[]);ne.includes(o)||ne.push(o),await d.set(W,JSON.stringify(ne),"EX",90*86400)}const we={topic:o,outcome:n,what_worked:J,what_failed:te,context:j,severity:S,file_paths:i,commands:t,tags:C,depends_on:l,...b?{author:b}:{},source:Vt(),...m?{service:m}:{},...I?{group:String(I).toLowerCase().trim()}:{},visibility:k,recall_count:ce,...ye?{last_recalled_at:ye}:{},...s&&!Number.isNaN(Date.parse(String(s)))?{gilt_ab:new Date(String(s)).toISOString()}:{},...V.angaben.length?{gilt_fuer:V.angaben}:{},ts:oe,verified_at:n==="success"||n==="partial"?oe:void 0,confidence:1,audit_trail:Q,version:3},he=String(E??"").trim();let Ce="",Ae=null;he===o&&he?Ce="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":he&&(Ae=await d.get(`cachly:lesson:best:${he}`),Ae?z(Ae,{}).ersetzt===o?(Ae=null,Ce=`\u26A0\uFE0F \`${he}\` ersetzt bereits \`${o}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${he}\` entfernen und danach hier setzen.`):we.ersetzt=he:Ce=`\u26A0\uFE0F Die zu ersetzende Lektion \`${he}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let g="";if(!he)try{const x=O=>{const re=z(O.content,{});return{topic:re.topic??O.key.slice(19),what_worked:re.what_worked}},[W,de]=await Promise.all([Ze(d,["cachly:lesson:best:*"],`${o} ${J}`.slice(0,300),5),Ls(d,["cachly:lesson:best:*"],i??[])]),ne=new Set,T=[...W,...de].filter(O=>O.key.startsWith("cachly:lesson:best:")).filter(O=>!ne.has(O.key)&&ne.add(O.key)).map(x);g=sn(o,J,T)??""}catch{}if(n==="failure")try{const W=(await d.lrange(mt(_),0,199)).map(T=>z(T,{ts:"",frage:"",geliefert:[]})).filter(T=>T.ts!==""),de=(await Ze(d,["cachly:lesson:best:*"],`${o} ${te||J}`.slice(0,300),5)).filter(T=>T.key.startsWith("cachly:lesson:best:")).map(T=>{const O=z(T.content,{});return{topic:O.topic??T.key.slice(19),what_worked:O.what_worked}}),ne=hn(o,String(te||""),W,de);await d.hincrby(Pt(_),ne,1)}catch{}const w=un([J,te,r].filter(Boolean).join(" ").slice(0,2e3));w&&(we.entscheidung=w);const B=io(o,oe,J);we.beleg=B;const M=JSON.stringify(we);d.set(`cachly:stats:born_at:${_}`,oe,"EX",365*86400,"NX").catch(()=>{});const ee=`cachly:lessons:${o}`;await d.rpush(ee,M),await d.ltrim(ee,-100,-1),await d.expire(ee,rn*86400);let L=!1;if(n==="success"||n==="partial"?(await d.set(`cachly:lesson:best:${o}`,M),L=!0):q||(await d.set(`cachly:lesson:best:${o}`,M),L=!0),Ae&&L)try{const x=JSON.parse(Ae);x.ersetzt_durch=o,x.gilt_bis=oe,x.ersetzt_am=oe,Ne&&(x.ersetzt_grund=Ne.slice(0,200)),await d.set(`cachly:lesson:best:${he}`,JSON.stringify(x))}catch{}L&&It();let se=()=>{};const Z=new Promise(x=>{se=x});L&&Le()||se(null),L&&Le()&&(await d.sadd(Ke,o).catch(()=>{}),await d.sadd(gt,o).catch(()=>{}),(Te==="cachly"||Te==="ollama")&&await d.sadd(Xe,o).catch(()=>{}),(async()=>{const x=z(M,{});try{const W=await xe(Ge(x),{geduld:"lang"});if(W?.length?(await d.set(`${Rt}${o}`,ze(W)),await d.srem(Ke,o).catch(()=>{}),se(await Mn(d,{...x,topic:o},W,$e))):se(null),Te==="cachly"||Te==="ollama")try{const de=await xe(Ge(x),{geduld:"lang",modell:Ve});de?.length&&(await d.set(`${Fe}${o}`,ze(de)),await d.srem(Xe,o).catch(()=>{}))}catch{}}catch(W){se(null),await d.sadd(Ke,o).catch(()=>{}),await Ye(d,rt,`Volltext-Vektor nicht geschrieben (${Te}): ${it(W)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const W=await xe(Lt(o),{geduld:"lang"});W?.length&&(await d.set(`${dt}${o}`,ze(W)),await d.srem(gt,o).catch(()=>{}))}catch(W){await Ye(d,rt,`Namens-Vektor nicht geschrieben (${Te}): ${it(W)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await Ys(d,o,x,W=>xe(W,{geduld:"lang"}))}catch(W){await Ye(d,rt,`Eingaenge nicht geschrieben (${Te}): ${it(W)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await cs(d,o,3),se(null)})());try{const x="cachly:session:decision-log",W=JSON.stringify({ts:oe,topic:o,outcome:n,what_worked:J.slice(0,120)});await d.rpush(x,W),await d.ltrim(x,-50,-1)}catch{}let le=null;try{const x=pe(o),W=o.split(":")[0]??"unknown";await je(d,x,W,W);for(const ne of C){const T=pe(`tag:${ne}`);await je(d,T,"tag","tag"),await Se(d,x,"co-occurs",T,n==="success",n==="partial")}for(const ne of l){const T=pe(ne);await Se(d,x,"requires",T,!0)}if((W==="fix"||W==="debug")&&(n==="success"||n==="partial")){const ne=te||j||"",T=ne?tt(ne):null;if(T){const O=pe(`problem:${T}`);await je(d,O,"problem","problem"),await Se(d,x,"fixes",O,n==="success",n==="partial")}}if(n==="failure"&&(te||J)){const T=tt(te||J);if(T){const O=pe(`cause:${T}`);await je(d,O,"cause","cause"),await Se(d,x,"causes",O,!1)}}if(n==="failure"){const ne=await d.smembers(`cachly:ckg:idx:from:${x}`);for(const T of ne){const O=await d.get(T);if(!O)continue;const re=z(O,null);if(re&&re.edgeType==="fixes"&&re.confidence>.7&&re.trials>=3){le=`\u26A0\uFE0F **belief_conflict** on \`${o}\`: 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="${o}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${x}")\` to review.`;const fe=`cachly:ckg:conflict:${x}`;await d.set(fe,JSON.stringify({topic:o,concept_id:x,detected_at:new Date().toISOString(),fix_confidence:re.confidence,fix_trials:re.trials,failure_outcome:n,reported_by:b||"unknown",what_failed:te||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(W==="fix"||W==="debug")){const ne=await d.smembers(`cachly:ckg:idx:from:${x}`);for(const T of ne.slice(0,10)){const O=await d.get(T);if(!O)continue;const re=z(O,null);if(!re||re.edgeType!=="fixes")continue;const fe=await d.smembers(`cachly:ckg:idx:from:${re.to}`);for(const Ie of fe.slice(0,5)){const Be=await d.get(Ie);if(!Be)continue;const Me=z(Be,null);Me&&Me.edgeType==="co-occurs"&&(Me.successes=(Me.successes||0)+.1,Me.trials=(Me.trials||0)+.1,Me.confidence=(Me.successes+1)/(Me.trials+2),Me.last_updated=new Date().toISOString(),await d.set(Ie,JSON.stringify(Me)))}}}if(Math.random()<.01){const ne=Date.now()-7776e6,T=await d.smembers(`cachly:ckg:idx:from:${x}`);for(const O of T){const re=await d.get(O);if(!re)continue;const fe=z(re,null);fe&&fe.trials<3&&fe.last_updated&&new Date(fe.last_updated).getTime()<ne&&(fe.confidence=fe.confidence*.9,fe.last_updated=new Date().toISOString(),await d.set(O,JSON.stringify(fe)))}}}catch{}if(b){d.set(`cachly:agents:active:${b}`,JSON.stringify({author:b,last_topic:o,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const x=o.split(":")[0]??"unknown",W=await ws(d,Ut(b),x),de=pe(o);await Se(d,W,"authored",de,n==="success",n==="partial");for(const ne of i.slice(0,8)){const T=await St(d,ne);await Se(d,W,"touched",T,!0),await ys(d,T,W)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const x=o.split(":")[0]??"unknown",W=p==="system"?"system":"service",de=await _s(d,m.trim(),x,W),ne=pe(o);if(await Se(d,ne,"affects",de,n==="success",n==="partial"),b){const T=`person:${pe(Ut(b))}`;await Se(d,T,"operates",de,!0)}for(const T of i.slice(0,8)){const O=`file:${pe(T)}`;await Se(d,O,"runs_in",de,!0)}}catch{}if(b&&(n==="success"||n==="partial")){const x={topic:o,outcome:n,what_worked:J,what_failed:te??"",severity:S,author:b,file_paths:i,commands:t,tags:[...new Set([...C,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},W=`cachly:lessons:${o}`;d.rpush(W,JSON.stringify(x)).catch(()=>{})}const G=n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C",ve=S==="critical"?"\u{1F534}":S==="major"?"\u{1F7E1}":"\u{1F7E2}",Ee=U?"updated":"stored",be=await In(Z);return[`${G} **Lesson ${Ee}:** \`${o}\` (${n}) ${ve} ${S} \xB7 Beleg: \`${B}\``,f.funde.length?`\u{1F512} **${f.funde.length} Geheimnis(se) geschwaerzt** vor dem Speichern (${f.funde.join("; ")}). Der Wert ist nicht im Brain \u2014 verweise kuenftig auf den Ort (z. B. Infisical-Pfad oder Variablenname).`:"",ho(e),le??"","",`**What worked:** ${J}`,te?`**What failed:** ${te}`:"",j?`**Context:** ${j}`:"",i.length>0?`**Files:** ${i.map(x=>`\`${x}\``).join(", ")}`:"",t.length>0?`**Commands:** ${t.map(x=>`\`${x}\``).join(", ")}`:"",C.length>0?`**Tags:** ${C.map(x=>`#${x}`).join(" ")}`:"","",U?`\u267B\uFE0F Updated (recall count: ${ce} \xB7 audit entries: ${Q.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${o}")\``,b&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${b}_${$.quelle!=="uebergeben"?` \xB7 aus ${$.quelle}`:""}) \u2014 visible in \`team_recall\``:"",v??"",l.length>0?`\u{1F517} Depends on: ${l.map(x=>`\`${x}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",g,An(be,g),V.angaben.length?`\u{1F4E6} Gilt fuer ${V.angaben.map(x=>`\`${x}\``).join(", ")}${V.uebernommen?" (aus der Vorfassung uebernommen)":""} \u2014 passt das Projekt nicht, steht die Lektion im Abruf hinten und ist markiert.`:"",...V.fehler.map(x=>`\u26A0\uFE0F gilt_fuer nicht gespeichert, ${x}. Form: paket@bereich, zum Beispiel next@<15 oder python:fastapi@>=0.100 <0.110.`),Ae&&L?Ne?`\u21B7 Ersetzt \`${he}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${he}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin. Ohne \`grund\` steht dort 'Grund nicht erfasst' \u2014 eine Zeile (warum die alte falsch war) macht den Verweis pruefbar.`:Ce,...Y,..._e,h>0?`\u{1F5D3}\uFE0F ${h} relative Zeitangabe${h===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(H.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",so(J)??""].filter(x=>x!=="").join(`
|
|
3
|
+
`)}case"lesson_verified":{const{instance_id:f}=D,e=await P(f),u=new Date().toISOString(),_=D,o=Oe({geprueft_mit:_.geprueft_mit,befund:_.befund}),n=ms({..._,...o.felder},u);if(!n.ok)return[`\u26A0\uFE0F ${n.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
|
|
4
|
+
`);const N=n.eintrag,a=`cachly:lesson:best:${N.topic}`,r=await e.get(a);if(!r)return`\u{1F4ED} Keine Lektion \`${N.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const S=z(r,{}),i=ps(S,N);return await e.set(a,JSON.stringify(o.verdacht.length?{...i,tags:uo(i.tags,o.verdacht)}:i)),It(),N.haelt?[`\u2705 \`${N.topic}\` ist wieder frisch \u2014 geprueft am ${u.slice(0,10)}.`,N.geprueft_mit?` geprueft mit: \`${N.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...He(o)].filter(Boolean).join(`
|
|
5
|
+
`):[`\u26A0\uFE0F \`${N.topic}\` ist als fraglich markiert.`,` Befund: ${N.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="${N.topic}", \u2026, grund="\u2026")\`.`,...He(o)].join(`
|
|
6
|
+
`)}case"recall_feedback":{const{instance_id:f}=D,e=await P(f),u=wn(D,new Date().toISOString());if(!u.ok)return[`\u26A0\uFE0F ${u.grund}`,"","Beispiel:","```",'recall_feedback(instance_id="\u2026", query="warum bricht der Deploy ab",',' topic="ci:zeitgrenze-meldet-cancelled", helped=true, rank=0)',"```","rank=0 heisst: die Lektion stand GAR NICHT in der Antwort.","Das ist die wertvollste Rueckmeldung von allen."].join(`
|
|
7
|
+
`);const _=u.eintrag,o=`cachly:wirkung:${f}`;await e.rpush(o,JSON.stringify(_));const N=(await e.lrange(o,0,-1).catch(()=>[])).map(t=>z(t,null)).filter(Boolean),a=yn(N),r=_n(_),S={"fehlender-treffer":"Sie half, stand aber gar nicht in der Antwort \u2014 der Topf hat sie nicht aufgenommen. Das ist der wertvollste Fall.","zu-weit-hinten":`Sie half, stand aber auf Platz ${_.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${_.platz} und half nicht \u2014 die Sortierung war sich sicher und lag falsch.`,bestaetigung:"Sie stand vorn und half. Bestaetigung.",unauffaellig:"Half nicht und stand hinten. Sagt wenig."},i=a.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${(a.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${_.thema}** \u2014 ${_.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${_.platz===0?"\u2014 (stand nicht drin)":_.platz}`,"",S[r],"",`Spur: ${a.gesamt} Rueckmeldungen, ${i}.`,`Davon: ${a.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${a.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${a.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
|
|
8
|
+
`)}case"recall_best_solution":{const f=Date.now(),{instance_id:e,topic:u,author:_}=D,o=await js(e,ae,`\u{1F4ED} No lessons found for \`${u}\`.`);if(o)return o;const n=await P(e);try{const t=await n.get(`cachly:letzter-recall:${e}`),C=t?z(t,null):null,l=bn(C,u,new Date().toISOString());l&&(await n.rpush(`cachly:wirkung:${e}`,JSON.stringify(l)),await n.del(`cachly:letzter-recall:${e}`))}catch{}const N=await n.get(`cachly:lesson:best:${u}`);if(N){const t=z(N,null);if(!t)return`\u26A0\uFE0F Lesson data for \`${u}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const C=t.group;if(C){const Q=_?await At(n,e,_).catch(()=>new Set):new Set,q=_?await lt(n,e,_).catch(()=>null)==="admin":!1;if(!Et(C,Q,q))return`\u{1F4ED} No lessons found for \`${u}\`. Use \`learn_from_attempts\` after solving it.`}const l=vt(t),c=t.verified_at??t.ts,k=(Date.now()-new Date(c).getTime())/864e5,m=t.commands,p=us(l,k,Array.isArray(m)&&typeof m[0]=="string"?m[0]:void 0,t.pruefung_gefallen_am?{am:t.pruefung_gefallen_am,befund:t.pruefung_befund}:void 0),I=new Date().toISOString(),A={...t,recall_count:(t.recall_count??0)+1,last_recalled_at:I};await n.set(`cachly:lesson:best:${u}`,JSON.stringify(A)),bt(n),pt(n,String(u??""),Date.now()-f);const E=xt(t)?Ct(t):0;E>0&&n.incrbyfloat(`cachly:stats:time_saved_mins:${e}`,E).catch(()=>{});const s=t.severity==="critical"?"\u{1F534}":t.severity==="major"?"\u{1F7E1}":t.severity?"\u{1F7E2}":"",ie=t.audit_trail??[],ue=ie.filter(Q=>Q&&typeof Q.grund=="string"&&Q.grund.trim().length>0).slice(-3).map(Q=>` \xB7 ${Q.ts?new Date(Q.ts).toLocaleDateString("de-DE"):"?"}: ${Q.grund.trim()}`),ge=ie.length>1?[`_Audit: ${ie.length} changes \xB7 stored ${new Date(t.ts).toLocaleDateString("de-DE")}_`,...ue.length>0?["**Warum zuletzt geaendert:**",...ue]:[]].join(`
|
|
9
|
+
`):"",me=(Date.now()-new Date(t.ts).getTime())/864e5,d=me>60?`\u{1F4AD} _Remember when you solved this ${Math.round(me/30)} months ago? Still works._`:"",H=A.recall_count===3&&!t.pinned?"\u{1F4CC} **You've looked this up 3 times.** Consider pinning it for instant access: add `pinned: true` via `learn_from_attempts` to always surface it first.":"",oe=t.authors??(t.author?[t.author]:[]),V=[...new Set(oe.filter(Boolean))],X=A.recall_count;let J="";V.length>=2&&X>=5?J=`\u{1F3C6} **Battle-tested** \u2014 recalled ${X}\xD7 \xB7 verified by ${V.length} developers. Trust this.`:X>=10?J=`\u{1F3C6} **Battle-tested** \u2014 recalled ${X}\xD7. This is one of your most-proven solutions.`:V.length>=2?J=`\u2705 **Team-verified** \u2014 confirmed by ${V.length} developers.`:X>=5&&(J=`\u2705 **Proven** \u2014 recalled ${X}\xD7 without contradiction.`);const te=t.ersetzt_durch,j=t.ersetzt_am?` (am ${t.ersetzt_am.slice(0,10)})`:"",h=te?await n.get(`cachly:lesson:best:${te}`):null,$=String(t.ersetzt_grund??"").trim(),y=$?` Grund: ${$}`:" Grund nicht erfasst.",b=h?!We(Re(h)):!1,v=te?h?b?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${j} \u2014 die Nachfolge-Lektion ist nicht team-sichtbar (privat). Der Text unten bleibt als Vorgeschichte lesbar; die gueltige Fassung kennt ihr Autor.`:`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${j} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${te}")\`.${y} Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${j} \u2014 der Nachfolger \`${te}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",R=t.gilt_ab,K=t.gilt_bis,Y=R?`\u{1F4C5} Gilt seit ${String(R).slice(0,10)}.`:"",U=t.entscheidung,ce=U?.gegen?Wt({gegen:U.gegen,grund:U.grund??null}):"",ye=K&&Date.parse(String(K))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(K).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[Zt(t),v,ye,an(t.gilt_fuer),Y,ce,d,J,`${p} **Best solution for \`${u}\`** ${s}${t.severity?` (${t.severity})`:""} \xB7 recalled ${A.recall_count}\xD7`,Nn(t.author,t.source),"",t.what_worked?`**What worked:** ${t.what_worked}`:"",t.what_failed?`**What failed (avoid this):** ${t.what_failed}`:"",t.context?`**Context:** ${t.context}`:"",(t.file_paths??[]).length>0?`**Files:** ${(t.file_paths??[]).map(Q=>`\`${Q}\``).join(", ")}`:"",(t.commands??[]).length>0?`**Commands:** ${(t.commands??[]).map(Q=>`\`${Q}\``).join(", ")}`:"",(t.tags??[]).length>0?`**Tags:** ${(t.tags??[]).map(Q=>`#${Q}`).join(" ")}`:"",ge,H].filter(Q=>Q!=="").join(`
|
|
10
|
+
`)}const a=[],r=n.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((t,C)=>{r.on("data",l=>a.push(...l)),r.on("end",t),r.on("error",C)});const S=a.filter(t=>t.toLowerCase().includes(u.toLowerCase()));if(S.length===0){const t=`cachly:lessons:${u}`,C=await n.lrange(t,-3,-1);if(C.length>0){const c=C.map(k=>z(k,null)).filter(Boolean).map(k=>`- ${k.outcome==="success"?"\u2705":"\u274C"} ${k.what_worked.slice(0,120)} (${new Date(k.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${u}\` yet. Last attempts:
|
|
11
11
|
|
|
12
|
-
${
|
|
13
|
-
`)}`}return`\u{1F4ED} No lessons found for \`${u}\`. Use \`learn_from_attempts\` after solving it.`}const
|
|
12
|
+
${c.join(`
|
|
13
|
+
`)}`}return`\u{1F4ED} No lessons found for \`${u}\`. Use \`learn_from_attempts\` after solving it.`}const i=[];for(const t of S.slice(0,5)){const C=await n.get(t);if(!C)continue;const l=z(C,null);if(!l)continue;const c=Zt(l);i.push(`${c?`${c}
|
|
14
14
|
`:""}**\`${l.topic}\`** \u2014 ${l.what_worked.slice(0,400)}${l.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${u}\`:**
|
|
15
15
|
|
|
16
|
-
${
|
|
16
|
+
${i.join(`
|
|
17
17
|
|
|
18
|
-
`)}`}case"smart_recall":{const f=Date.now(),{instance_id:s,query:u,threshold:_=.78,author:c="",context_files:n=[]}=R,E=Array.isArray(n)?n.filter(d=>typeof d=="string"):[];if(ke("smart_recall: Anfang"),await Et(s,ie)){const d=Date.now()-f;return G(s).then(w=>ts(w,s,String(u??""),d)).catch(()=>{}),ke("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),It(String(u??""),{startet:!0,...ht(s)})}const o=await G(s);ke("smart_recall: Verbindung steht"),as(o,void 0,2);let i=new Set,S=!1;c&&(i=await xt(o,s,c).catch(()=>new Set),S=await ct(o,s,c).catch(()=>null)==="admin");const a=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],e=await Ls(o,a);if(!e)return ts(o,s,String(u??""),Date.now()-f),ke("smart_recall: Brain leer \u2014 sofort geantwortet"),It(String(u??""),{startet:!1,...ht(s)});const C=e.docs.reduce((d,w)=>d+(w.key.startsWith("cachly:lesson:best:")?1:0),0),l=await Ye(o,a,u,25);ke(`smart_recall: Wortsuche fertig (${l.length} Treffer)`);const r=Os(l);let k=!1,m=null;const p=await(async()=>{if(!Re())return ot(ks,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),r;try{if(await $e.aktualisiere(o),ke(`smart_recall: Vektorbestand geladen (${$e.groesse})`),$e.groesse===0)return C>0&&ot($s,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),r;const d=await Ie(u);if(ke("smart_recall: Frage eingebettet"),!d?.length)return ot(vs,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),r;await gt.aktualisiere(o),await mt.aktualisiere(o),await Je.aktualisiere(o),await Xe.aktualisiere(o);const w=$e.groesse>0?Xe.groesse/$e.groesse:0;w<Wt&&$e.groesse>0&&wo(o,3);const D=w>=Wt?Ie(u,{modell:Ze}).catch(()=>null):null,M=r.filter(T=>T.key.startsWith("cachly:lesson:best:")).map(T=>T.key.slice(19)),ee=T=>Math.max($e.naehe(d,T),gt.naehe(d,T)),L=[...Je.themen()],se=(L.length>0?L:$e.aehnlichste(d,500).map(T=>T.topic)).map(T=>({t:T,n:ee(T)})).sort((T,O)=>O.n-T.n).slice(0,Kt).map(T=>T.t),Z=[...new Set([...M,...se])],le=se.slice(0,3).map(T=>$e.rohvektor(T)).filter(Boolean),W=le.length?hn(d,le):d,ve=jt(u),Ne=Je.statistik,be=Z.map(T=>{const O=new Set([...jt(Je.textVon(T))].map(un));return{naeheText:$e.naehe(d,T),naeheThema:gt.naehe(d,T),naeheRueckkopplung:$e.naehe(W,T),seltenheitsDeckung:Ne?Ne.deckung(ve,O):0,besterZeuge:Ne?Ne.besterZeuge(ve,O):0}});let x=ln(be,dn);{const T=[...x].sort((O,re)=>re-O);m=T.length>1?T[0]-T[1]:null}if(mt.groesse>0){const T=Z.map(re=>{const fe=mt.besteNaehe(d,re);return fe>=Bn?fe:-2}),O=Pt(T);x=x.map((re,fe)=>re+Ln*O[fe])}if(D){const T=await D;if(T?.length){const O=Pt(Z.map(re=>Xe.naehe(T,re)));x=x.map((re,fe)=>re+vn*O[fe])}}let j=Z.map((T,O)=>({t:T,p:x[O]})).sort((T,O)=>O.p-T.p).map(T=>T.t);if(Ws(s)&&j.length>1){const T=j.slice(0,Ft),O=j.slice(Ft),re=new Map(Z.map((Ae,Be)=>[Ae,x[Be]]));ke("smart_recall: Leser Anfang");const fe=await Fs(u,T.map(Ae=>Je.leserTextVon(Ae)),{instanceId:s});ke(`smart_recall: Leser ${fe?"fertig":"ohne Ergebnis"}`),fe&&(j=[...Gs(T.map(Be=>re.get(Be)??0),fe).map(Be=>T[Be]),...O])}const de=new Map(r.map(T=>[T.key,T])),ne=[];for(const T of j){const O=`cachly:lesson:best:${T}`,re=de.get(O);if(re){ne.push(re),de.delete(O);continue}const fe=await o.get(O).catch(()=>null);fe&&ne.push({key:O,content:fe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return ne.push(...de.values()),_n&&yn({frage:u.slice(0,200),themen:Z,ausWortsuche:M.length,ausSinnsuche:se.length,obergrenze:Kt,gezeigt:j.slice(0,10)}),k=!0,ne}catch(d){return await Ue(o,Ss,`der Bedeutungspfad brach ab (${d instanceof Error?d.message:String(d)}) \u2014 diese Suche lief nur ueber Woerter`),r}})();ke("smart_recall: Bedeutungspfad fertig"),wt(o),ft(o,String(u??""),Date.now()-f);{const d=p.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));if(d.length>0){const w={ts:new Date().toISOString(),themen:d};(async()=>{const D=Lt(s);await o.lpush(D,JSON.stringify(w)),await o.ltrim(D,0,an-1)})().catch(()=>{})}{const w={ts:new Date().toISOString(),frage:u.slice(0,200),geliefert:d};(async()=>{const D=dt(s);await o.lpush(D,JSON.stringify(w)),await o.ltrim(D,0,zt-1)})().catch(()=>{})}}if(Re()){const d=p.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));Xs(o,u,d,Ie).catch(()=>{})}const I=[],N=p.filter(d=>d.key.startsWith("cachly:lesson:best:"));let A=0,t=0;for(const d of N.slice(0,5)){const w=await o.get(d.key).catch(()=>null);if(w){const D=z(w,null);if(D?.state==="archived")continue;if(D){const M=new Date().toISOString(),ee={...D,recall_count:(D.recall_count??0)+1,last_recalled_at:M};o.set(d.key,JSON.stringify(ee)).catch(()=>{});const L=vt(D)?kt(D):0;if(L>0&&o.incrbyfloat(`cachly:stats:time_saved_mins:${s}`,L).catch(()=>{}),D.author&&c&&D.author!==c){A++,o.sadd(`cachly:stats:reuse_pairs:${s}`,`${c}<-${D.author}`).catch(()=>{});const se=`person:${pe(c)}`,Z=`person:${pe(D.author)}`;Se(o,se,"collaborates",Z,!0).catch(()=>{}),Se(o,Z,"collaborates",se,!0).catch(()=>{})}D.outcome==="success"&&t++,D.outcome==="success"&&(D.recall_count??0)>=1&&!tt(D)&&I.push({topic:d.key.replace("cachly:lesson:best:",""),severity:D.severity??"major",recall_count:(D.recall_count??0)+1,savedMins:L,ts:D.ts,author:D.author})}}}t>0&&o.set(`cachly:stats:first_recall_at:${s}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),N.length>0&&(o.incr(`cachly:stats:recalls_total:${s}`).catch(()=>{}),A>0&&o.incr(`cachly:stats:cross_author_recalls:${s}`).catch(()=>{})),ke("smart_recall: Treffer gezaehlt");const ae=await ie(`/api/v1/instances/${s}`).catch(()=>null);ke("smart_recall: Tarif abgefragt");const ue=!ae?.tier||ae.tier.toLowerCase()==="free",ge=[];if(!ue&&ae?.vector_token&&Re())try{const d=await Ie(u),w=`https://api.cachly.dev/v1/sem/${ae.vector_token}`,D=await fetch(`${w}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:d,namespace:"cachly:ctx",threshold:_,top_k:5}),signal:AbortSignal.timeout(8e3)});if(D.ok){const M=await D.json();for(const ee of M.filter(L=>L.found&&L.id)){const L=ee.id.replace("ctx:","").split(":"),se=L[0],Z=L.slice(1).join(":"),le=`cachly:ctx:${se}:${Z}`,W=await o.get(le).catch(()=>null);ge.push({key:le,similarity:ee.similarity??0,content:W??"(evicted)"})}}}catch{}const me=p.map(d=>d.score),g=me.length?Math.min(...me):0,K=me.length&&Math.max(...me)-g||1,oe=d=>(d-g)/K,H=new Map,X=k?Ys(p.map(d=>oe(d.score))):null,J=new Map;for(const[d,w]of p.entries()){const D=oe(w.score),M=X?X[d]:D;X&&H.set(w.key,d),J.set(w.key,{key:w.key,content:w.content,bm25Score:D,hausWert:M,hybridScore:M*(ge.length>0?.7:1),matchedWords:w.matchedWords,matchType:"keyword",subQuery:w.subQuery,wortBelege:w.wortBelege})}for(const d of ge){const w=J.get(d.key);w?(w.semScore=d.similarity,w.hybridScore=(w.hausWert??0)*.6+d.similarity*.4,w.matchType="hybrid"):J.set(d.key,{key:d.key,content:d.content,semScore:d.similarity,hybridScore:d.similarity*.5,matchType:"semantic"})}try{const d=lt(u).filter(M=>M.length>=4).slice(0,4),w=new Set;for(const M of d){const ee=o.scanStream({match:`cachly:ckg:node:*${M}*`,count:20});await new Promise((L,se)=>{ee.on("data",Z=>{for(const le of Z.slice(0,5))w.add(le.replace("cachly:ckg:node:",""))}),ee.on("end",L),ee.on("error",se)})}const D=new Set;for(const M of[...w].slice(0,12)){const ee=await o.smembers(`cachly:ckg:idx:to:${M}`);for(const L of ee.slice(0,6)){const se=await o.get(L);if(!se)continue;const Z=z(se,null);if(!Z||Z.edgeType!=="fixes"||Z.confidence<.35||D.has(Z.from))continue;D.add(Z.from);const le=`cachly:lesson:best:${Z.from}`,W=J.get(le);if(W)W.ckgScore=Math.max(W.ckgScore??0,Z.confidence),W.hybridScore=W.hybridScore*.88+Z.confidence*.12,W.matchType==="keyword"&&(W.matchType="hybrid");else{const ve=await o.get(le).catch(()=>null);if(!ve)continue;J.set(le,{key:le,content:ve,ckgScore:Z.confidence,hybridScore:Z.confidence*.3,matchType:"ckg"})}}}}catch{}if(ke("smart_recall: Sinn-Dienst und CKG fertig"),E.length>0){const d=new Set(E.map(w=>w.replace(/\\/g,"/")));for(const w of J.values()){if(!w.key.startsWith("cachly:lesson:best:"))continue;const D=z(w.content,{});(Array.isArray(D.file_paths)?D.file_paths.filter(ee=>typeof ee=="string").map(ee=>ee.replace(/\\/g,"/")):[]).some(ee=>d.has(ee))&&(w.hybridScore*=1.15,w.contextBoost=!0)}}for(const d of J.values()){if(d.matchType!=="semantic"&&d.matchType!=="ckg")continue;const w=js({key:d.key,content:d.content});w&&(d.hybridScore*=Ps(w))}const te=[...J.values()].filter(d=>{if(!d.key.startsWith("cachly:lesson:best:"))return!0;const w=Le(d.content);return!(!je(w)||!Tt(w?.group,i,S))}),P=X?Us(te,H):te.sort((d,w)=>w.hybridScore-d.hybridScore),h=[];for(const d of P){if(!d.key.startsWith("cachly:lesson:best:"))continue;const w=z(d.content,{});w.gilt_bis&&Date.parse(String(w.gilt_bis))<Date.now()&&h.push(`\u23F3 \`${d.key.replace("cachly:lesson:best:","")}\` galt bis ${String(w.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const D=z(d.content,{});if(D.pruefung_gefallen_am){const M=d.key.replace("cachly:lesson:best:",""),ee=String(D.pruefung_gefallen_am).slice(0,10),L=String(D.pruefung_befund??"").trim().slice(0,200);h.push(`\u274C \`${M}\` \u2014 Pruefung am ${ee} FEHLGESCHLAGEN`+(L?`: ${L}`:""))}}{const d=new Set(P.map(w=>w.key));for(let w=P.length-1;w>=0;w--){const D=P[w];if(!D.key.startsWith("cachly:lesson:best:"))continue;const M=z(D.content,{});if(!M.ersetzt_durch)continue;const ee=String(M.ersetzt_grund??"").trim(),L=D.key.replace("cachly:lesson:best:","");if(d.has(`cachly:lesson:best:${M.ersetzt_durch}`))P.splice(w,1),h.push(`\u21B7 \`${L}\` verdraengt \u2014 ersetzt durch \`${M.ersetzt_durch}\`${M.ersetzt_am?` am ${M.ersetzt_am.slice(0,10)}`:""}${ee?` \u2014 Grund: ${ee}`:" \u2014 Grund nicht erfasst"}`);else if(await o.get(`cachly:lesson:best:${M.ersetzt_durch}`)){const se=Le(await o.get(`cachly:lesson:best:${M.ersetzt_durch}`));je(se)?h.push(`\u26A0\uFE0F \`${L}\` ist ersetzt durch \`${M.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${M.ersetzt_durch}")\``):h.push(`\u21B7 \`${L}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else h.push(`\u21A9\uFE0F \`${L}\` war ersetzt durch \`${M.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const $=en(P,E),y=[];{await $e.aktualisiere(o).catch(()=>{});const d=P.slice(0,8).filter(w=>w.key.startsWith("cachly:lesson:best:"));for(let w=0;w<d.length;w++)for(let D=w+1;D<d.length;D++){const M=d[w].key.replace("cachly:lesson:best:",""),ee=d[D].key.replace("cachly:lesson:best:",""),L=$e.rohvektor(M),se=$e.rohvektor(ee);if(!L||!se)continue;let Z=0,le=0,W=0;for(let be=0;be<L.length;be++)Z+=L[be]*se[be],le+=L[be]*L[be],W+=se[be]*se[be];if((le>0&&W>0?Z/(Math.sqrt(le)*Math.sqrt(W)):0)<Sn)continue;const Ne=be=>{const x=z(be??"",{});return String(x.verified_at??x.ts??"").slice(0,10)||"ohne Datum"};y.push(`\u26A0\uFE0F \`${M}\` (${Ne(d[w].content)}) und \`${ee}\` (${Ne(d[D].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}y.length>3&&(y.length=3)}if(h.push(...y),P.length>=2){const d=P[0].hybridScore,w=P[Math.min(4,P.length-1)].hybridScore,D=Math.max(0,d-w);(async()=>{try{await o.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(D.toFixed(4)),n:P.length})),await o.ltrim("cachly:recall:spread",0,199)}catch{}})()}const b=Cs();let v="",B=null;if(b!==null){v=xs();const d=P[0]?.hybridScore??0,w=Ts(P.map(D=>({key:D.key,content:D.content,punktzahl:D.hybridScore})),v,b,d);w.weggelassenesThema!==void 0?P.splice(0,1):w.markierungGesetzt&&P[0]&&w.treffer[0]&&(P[0]={...P[0],content:w.treffer[0].content}),B={frage:u,hoechstePunktzahl:d,themen:[],zulassungsfaehig:w.zulassungsfaehig,zulassungsGrund:w.zulassungsGrund,zuteilung:w.zuteilung,weggelassenesThema:w.weggelassenesThema,markierungGesetzt:w.markierungGesetzt}}ke("smart_recall: Notizen und Duplikate fertig");const F=await os(s,ie);ke("smart_recall: Abruf-Grenze abgefragt");const Y=F.reached,q=Ht({ueberLimit:Y,gesamt:P.length,volleTiefe:zn}),ce=process.env.CACHLY_RECALL_COMPACT==="1",ye=(()=>{const d=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(d)?Math.min(20,Math.max(1,d)):5})(),Q=ce?Math.min(ye,q.sichtbar):q.sichtbar,V=[`\u{1F9E0} **Smart Recall** for: _"${u}"_
|
|
19
|
-
`];
|
|
20
|
-
`);const
|
|
21
|
-
`)}
|
|
22
|
-
`);const we=
|
|
23
|
-
`);const he=
|
|
24
|
-
`);const Ce=
|
|
25
|
-
`);const
|
|
26
|
-
`),Ce.belegte<
|
|
27
|
-
`)}if(h.push(...
|
|
28
|
-
`);for(const
|
|
29
|
-
\u26A0\uFE0F **No results for:** ${se.map(Z=>`"${Z}"`).join(", ")}`)}else for(const M of
|
|
30
|
-
`)}}else{
|
|
31
|
-
\u{1F4A1} Tips:`),
|
|
32
|
-
`))}return
|
|
33
|
-
`)}case"session_start":{const{instance_id:f,focus:
|
|
34
|
-
`).slice(0,8))
|
|
35
|
-
`).filter(b=>b.includes("|")||b.includes("changed"));if(y.length>0){t.push(" **Recent changes:**");for(const b of y.slice(0,5))t.push(` ${b.trim()}`)}}t.push("")}}catch{}if(l){const h=Math.round((Date.now()-new Date(l.ts).getTime())/6e4),$=h<60?`${h}m ago`:h<1440?`${Math.round(h/60)}h ago`:`${Math.round(h/1440)}d ago`;t.push(`\u{1F4C5} **Last session** (${$}): ${l.summary}`),l.duration_min&&t.push(` Duration: ${l.duration_min} min`),(l.files_changed??[]).length>0&&t.push(` Files: ${(l.files_changed??[]).slice(0,5).map(y=>`\`${y}\``).join(", ")}`),t.push("")}t.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${a} context entries`,""),S>0&&t.push(`\u26A0 ${S} Lektion(en) wurden beim Speichern als verd\xE4chtig markiert und stehen nicht in diesem Briefing. Ausdr\xFCcklich abrufbar mit recall_best_solution (mit Warnzeile); pr\xFCfen oder neu speichern.`,"");{const $=i.filter(y=>!tt(y)).filter(y=>y.outcome==="success"&&(y.pinned===!0||(y.recall_count??0)>=5)).filter(y=>!g.has(y.topic)).sort((y,b)=>(b.recall_count??0)-(y.recall_count??0)).slice(0,5);if($.length>0){t.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const y of $){g.add(y.topic);const b=y.severity==="critical"?"\u{1F534}":y.severity==="major"?"\u{1F7E1}":"",v=y.recall_count??0,B=y.pinned===!0?"pinned":`recalled ${v}\xD7`,F=qe(y);t.push(` \u{1F3C6}${b} \`${y.topic}\` _(${B})_ \u2014 ${F[0]??""}`,...F.slice(1))}t.push("")}}try{const h=[],$=n.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((y,b)=>{$.on("data",v=>h.push(...v)),$.on("end",y),$.on("error",b)}),h.length>0){t.push(`\u26A1 **Active belief conflicts (${h.length}):**`);for(const y of h.slice(0,3)){const b=await n.get(y);if(!b)continue;const v=z(b,null);v&&t.push(` \u26A0\uFE0F \`${v.topic}\` \u2014 previously confirmed fix (${(v.fix_confidence*100).toFixed(0)}%, n=${v.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${pe(v.topic)}")\``)}t.push("")}}catch{}if(me.length>0){t.push(`\u{1F3AF} **Relevant for "${s}":**`);for(const h of me){const $=h.outcome==="success"?"\u2705":h.outcome==="partial"?"\u26A0\uFE0F":"\u274C",y=h.severity==="critical"?"\u{1F534}":h.severity==="major"?"\u{1F7E1}":"",b=qe(h);t.push(` ${$}${y} \`${h.topic}\` \u2014 ${b[0]??""}`,...b.slice(1))}t.push("")}if(i.length>0){const h=(k.length>0?i.filter($=>!k.includes($)):i).filter($=>!g.has($.topic)).slice(0,k.length>0?3:4);if(h.length>0){t.push("\u{1F550} **Recent lessons:**");for(const $ of h){g.add($.topic);const y=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C",b=$.severity==="critical"?"\u{1F534}":$.severity==="major"?"\u{1F7E1}":"",v=qe($);t.push(` ${y}${b} \`${$.topic}\` \u2014 ${v[0]??""}`,...v.slice(1))}t.push("")}}else t.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some($=>$.author)||(t.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),t.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const X=await Tn(n,i);if(X.length>0){t.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const h of X.slice(0,3))t.push(` \`${h.neu}\` \u2248 \`${h.alt}\` (${h.naehe.toFixed(2)})`);t.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),t.push("")}const J=l;if(J?.decision_log?.length){const h=J.decision_log,$=h.filter((v,B)=>!g.has(v.topic)&&h.findIndex(F=>F.topic===v.topic)===B),y=$.filter(v=>v.outcome==="success"),b=$.filter(v=>v.outcome==="failure");if(y.length>0||b.length>0){t.push(`\u{1F3AC} **Last session decisions** (${h.length} lessons stored):`),y.length>0&&t.push(` \u2705 Worked: ${y.slice(0,3).map(v=>`\`${v.topic}\``).join(", ")}`),b.length>0&&t.push(` \u274C Failed: ${b.slice(0,3).map(v=>`\`${v.topic}\``).join(", ")}`),t.push("");for(const v of[...y.slice(0,3),...b.slice(0,3)])g.add(v.topic)}}{const h=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"]),$=B=>{const F=new Set;for(const Y of B)for(const q of Y.toLowerCase().split(/[/\\._-]/))q.length>3&&!h.has(q)&&F.add(q);return[...F]};let y=r,b=s,v=!1;if(y.length===0&&l){const B=$(l.files_changed??[]),F=(l.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(Y=>Y.length>3&&!h.has(Y));y=[...new Set([...B,...F])],b="where you left off last session",v=!0}if(y.length>0){const B=i.filter(F=>{if(F.outcome==="success")return!1;const Y=F.topic.split(":")[0];return y.some(q=>F.topic.toLowerCase().includes(q)||Y===q||(F.tags??[]).some(ce=>ce.toLowerCase()===q))});if(B.length>=1){const Y=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",v?` You're likely to continue **${b}** \u2014 ${B.length} known pitfall${B.length>1?"s":""} there:`:` Known pitfalls for **"${b}"** (${B.length} past failure${B.length>1?"s":""}):`,...B.slice(0,3).map(q=>` \u274C \`${q.topic}\` \u2014 ${(q.what_failed??q.what_worked).slice(0,80)}`),""];t.splice(2,0,...Y)}}}if(u){const h=Date.now()-6048e5,$=i.filter(y=>y.author&&y.author!==u&&new Date(y.ts).getTime()>h&&!g.has(y.topic));if($.length>0){const y=new Map;for(const b of $){const v=b.author;y.has(v)||y.set(v,[]),y.get(v).push(b)}t.push(`\u{1F465} **Team this week** (${$.length} lesson${$.length>1?"s":""} from teammates):`);for(const[b,v]of y){t.push(` \u{1F464} **${b}**:`);for(const B of v.slice(0,3)){const F=B.outcome==="success"?"\u2705":B.outcome==="partial"?"\u26A0\uFE0F":"\u274C";t.push(` ${F} \`${B.topic}\` \u2014 ${B.what_worked.slice(0,80)}`),g.add(B.topic)}v.length>3&&t.push(` \u2026 and ${v.length-3} more`)}t.push("")}}try{const h=await n.get("cachly:crystal:latest");if(h){const $=z(h,null);if($&&Math.round((Date.now()-new Date($.ts).getTime())/864e5)<=90){t.push(`\u{1F48E} **Memory Crystal** (${$.label} \xB7 ${$.session_count} sessions compressed):`);for(const b of $.top_patterns.slice(0,3))t.push(` \u2022 **${b.category}** (${b.count}\xD7): ${b.insight.slice(0,90)}`);t.push("")}}}catch{}try{const h=await n.hgetall(`cachly:roadmap:${f}`);if(h&&Object.keys(h).length>0){const $={critical:0,high:1,medium:2,low:3},y={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},b=new Set(["planned","in-progress","blocked"]),v=Object.values(h).flatMap(Y=>{const q=z(Y,null);return q?[q]:[]}),B=v.filter(Y=>b.has(Y.status)).sort((Y,q)=>Y.status==="in-progress"&&q.status!=="in-progress"?-1:q.status==="in-progress"&&Y.status!=="in-progress"?1:($[Y.priority]??99)-($[q.priority]??99)),F=v.filter(Y=>Y.status==="done").length;if(B.length>0){t.push(`\u{1F5FA}\uFE0F **Roadmap** (${B.length} open \xB7 ${F} done):`);for(const Y of B.slice(0,5)){const q=Y.status==="in-progress"?"\u26A1":Y.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";t.push(` ${q} ${y[Y.priority]??"\u26AA"} \`${Y.id}\` **${Y.title}**`)}B.length>5&&t.push(` \u2026 and ${B.length-5} more`),t.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),t.push("")}}}catch{}try{const h=await n.get("cachly:mcm:calibration:last"),$=z(h,null)?.ts??0;if((Date.now()-$)/864e5>=30&&i.length>=5){const b=i.filter(B=>B.outcome==="success"&&(B.recall_count??0)>0),v=i.filter(B=>(B.recall_count??0)>0);if(v.length>=3){const B=v.length>0?b.length/v.length:1,F=[],Y=new Map;for(const q of v){const ce=q.topic.split(":")[0]??"other";Y.has(ce)||Y.set(ce,{success:0,total:0});const ye=Y.get(ce);ye.total++,q.outcome==="success"&&ye.success++}for(const[q,ce]of Y)ce.total>=2&&ce.success/ce.total<.6&&F.push(q);await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:B,recalled:v.length,low_precision_domains:F})),(F.length>0||B<.7)&&(t.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${v.length} recalled lessons):`),t.push(` Overall precision: **${(B*100).toFixed(0)}%** recalled lessons actually worked`),F.length>0&&t.push(` \u26A0\uFE0F Low-precision domains: ${F.map(q=>`\`${q}\``).join(", ")} \u2014 consider revisiting these lessons`),t.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),t.push(""))}await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const te=i.filter(h=>h.outcome==="failure"||h.outcome==="partial").length,P=i.filter(h=>h.outcome==="success"&&bt(h)<ls).length;if(i.length===0||te>0||P>0){const h=[];i.length===0&&h.push("brain is empty"),te>0&&h.push(`${te} open failure${te>1?"s":""}`),P>0&&h.push(`${P} stale lesson${P>1?"s":""}`),t.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${h.join(", ")}._`)}try{if(await n.get(`cachly:prefs:auto_changelog:${f}`).catch(()=>null)!=="false"&&l?.ts&&!ge){const y=new Date(l.ts).getTime();if(!Number.isNaN(y)){const b=i.filter(B=>{const F=new Date(B.ts).getTime();return!Number.isNaN(F)&&F>y}),v=b.filter(B=>!g.has(B.topic));if(v.length>0){const B=Math.round((Date.now()-y)/6e4),F=B<60?`${B}m`:B<1440?`${Math.round(B/60)}h`:`${Math.round(B/1440)}d`,Y=b.length-v.length;t.push(""),t.push(`\u{1F4CB} **${b.length} new lesson${b.length!==1?"s":""} since your last session** (${F} ago${Y>0?`, ${Y} already listed above`:""}):`);const q=new Map;for(const ce of v.slice(0,20)){const ye=ce.topic.includes(":")?ce.topic.split(":")[0]:"general",Q=q.get(ye)??[];Q.push(ce),q.set(ye,Q)}for(const[ce,ye]of q){t.push(` **${ce}**`);for(const Q of ye){const V=Q.outcome==="failure"?"\u274C":Q.severity==="critical"?"\u{1F6A8}":Q.severity==="major"?"\u26A0\uFE0F":"\u2705",xe=(Q.outcome==="failure"?Q.what_failed:Q.what_worked)??"";t.push(` ${V} \`${Q.topic}\`${xe?` \u2014 ${xe.slice(0,80)}`:""}`)}}v.length>20&&t.push(` \u2026 and ${v.length-20} more. Call \`brain_changelog\` for the full list.`),t.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${f}", key="auto_changelog", value="false")\`_`)}}}}catch{}return t.join(`
|
|
36
|
-
`)}case"session_start_summary":{const{instance_id:f,focus:
|
|
37
|
-
`);const S=
|
|
38
|
-
`)}case"session_end":{const{instance_id:f,summary:
|
|
39
|
-
`).map(he=>he.trim()).filter(Boolean).slice(0,12):[],we=[];for(const he of _e)we.push(await
|
|
18
|
+
`)}`}case"smart_recall":{const f=Date.now(),{instance_id:e,query:u,threshold:_=.78,author:o="",context_files:n=[]}=D,N=Array.isArray(n)?n.filter(g=>typeof g=="string"):[];if(ke("smart_recall: Anfang"),await Dt(e,ae)){const g=Date.now()-f;return P(e).then(w=>os(w,e,String(u??""),g)).catch(()=>{}),ke("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),Bt(String(u??""),{startet:!0,...ut(e)})}const a=await P(e);ke("smart_recall: Verbindung steht"),cs(a,void 0,2);let r=new Set,S=!1;o&&(r=await At(a,e,o).catch(()=>new Set),S=await lt(a,e,o).catch(()=>null)==="admin");const i=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],t=await Ps(a,i);if(!t)return os(a,e,String(u??""),Date.now()-f),ke("smart_recall: Brain leer \u2014 sofort geantwortet"),Bt(String(u??""),{startet:!1,...ut(e)});const C=t.docs.reduce((g,w)=>g+(w.key.startsWith("cachly:lesson:best:")?1:0),0),l=await Ze(a,i,u,25);ke(`smart_recall: Wortsuche fertig (${l.length} Treffer)`);const c=Fs(l);let k=!1,m=null;const p=await(async()=>{if(!Le())return at(xs,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),c;try{if(await $e.aktualisiere(a),ke(`smart_recall: Vektorbestand geladen (${$e.groesse})`),$e.groesse===0)return C>0&&at(Cs,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),c;const g=await xe(u);if(ke("smart_recall: Frage eingebettet"),!g?.length)return at(Ts,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),c;await wt.aktualisiere(a),await yt.aktualisiere(a),await Je.aktualisiere(a),await Qe.aktualisiere(a);const w=$e.groesse>0?Qe.groesse/$e.groesse:0;w<Kt&&$e.groesse>0&&bo(a,3);const B=w>=Kt?xe(u,{modell:Ve}).catch(()=>null):null,M=c.filter(T=>T.key.startsWith("cachly:lesson:best:")).map(T=>T.key.slice(19)),ee=T=>Math.max($e.naehe(g,T),wt.naehe(g,T)),L=[...Je.themen()],se=(L.length>0?L:$e.aehnlichste(g,500).map(T=>T.topic)).map(T=>({t:T,n:ee(T)})).sort((T,O)=>O.n-T.n).slice(0,Jt).map(T=>T.t),Z=[...new Set([...M,...se])],le=se.slice(0,3).map(T=>$e.rohvektor(T)).filter(Boolean),G=le.length?fn(g,le):g,ve=Gt(u),Ee=Je.statistik,be=Z.map(T=>{const O=new Set([...Gt(Je.textVon(T))].map(gn));return{naeheText:$e.naehe(g,T),naeheThema:wt.naehe(g,T),naeheRueckkopplung:$e.naehe(G,T),seltenheitsDeckung:Ee?Ee.deckung(ve,O):0,besterZeuge:Ee?Ee.besterZeuge(ve,O):0}});let x=dn(be,mn);{const T=[...x].sort((O,re)=>re-O);m=T.length>1?T[0]-T[1]:null}if(yt.groesse>0){const T=Z.map(re=>{const fe=yt.besteNaehe(g,re);return fe>=zn?fe:-2}),O=Ft(T);x=x.map((re,fe)=>re+On*O[fe])}if(B){const T=await B;if(T?.length){const O=Ft(Z.map(re=>Qe.naehe(T,re)));x=x.map((re,fe)=>re+xn*O[fe])}}let W=Z.map((T,O)=>({t:T,p:x[O]})).sort((T,O)=>O.p-T.p).map(T=>T.t);if(Hs(e)&&W.length>1){const T=W.slice(0,Ht),O=W.slice(Ht),re=new Map(Z.map((Ie,Be)=>[Ie,x[Be]]));ke("smart_recall: Leser Anfang");const fe=await Vs(u,T.map(Ie=>Je.leserTextVon(Ie)),{instanceId:e});ke(`smart_recall: Leser ${fe?"fertig":"ohne Ergebnis"}`),fe&&(W=[...Js(T.map(Be=>re.get(Be)??0),fe).map(Be=>T[Be]),...O])}const de=new Map(c.map(T=>[T.key,T])),ne=[];for(const T of W){const O=`cachly:lesson:best:${T}`,re=de.get(O);if(re){ne.push(re),de.delete(O);continue}const fe=await a.get(O).catch(()=>null);fe&&ne.push({key:O,content:fe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return ne.push(...de.values()),kn&&$n({frage:u.slice(0,200),themen:Z,ausWortsuche:M.length,ausSinnsuche:se.length,obergrenze:Jt,gezeigt:W.slice(0,10)}),k=!0,ne}catch(g){return await Ye(a,Ns,`der Bedeutungspfad brach ab (${g instanceof Error?g.message:String(g)}) \u2014 diese Suche lief nur ueber Woerter`),c}})();ke("smart_recall: Bedeutungspfad fertig"),bt(a),pt(a,String(u??""),Date.now()-f);{const g=p.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));if(g.length>0){const w={ts:new Date().toISOString(),themen:g};(async()=>{const B=Ot(e);await a.lpush(B,JSON.stringify(w)),await a.ltrim(B,0,ln-1)})().catch(()=>{})}{const w={ts:new Date().toISOString(),frage:u.slice(0,200),geliefert:g};(async()=>{const B=mt(e);await a.lpush(B,JSON.stringify(w)),await a.ltrim(B,0,jt-1)})().catch(()=>{})}}if(Le()){const g=p.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));tn(a,u,g,xe).catch(()=>{})}const I=[],A=p.filter(g=>g.key.startsWith("cachly:lesson:best:"));let E=0,s=0;for(const g of A.slice(0,5)){const w=await a.get(g.key).catch(()=>null);if(w){const B=z(w,null);if(B?.state==="archived")continue;if(B){const M=new Date().toISOString(),ee={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:M};a.set(g.key,JSON.stringify(ee)).catch(()=>{});const L=xt(B)?Ct(B):0;if(L>0&&a.incrbyfloat(`cachly:stats:time_saved_mins:${e}`,L).catch(()=>{}),B.author&&o&&B.author!==o){E++,a.sadd(`cachly:stats:reuse_pairs:${e}`,`${o}<-${B.author}`).catch(()=>{});const se=`person:${pe(o)}`,Z=`person:${pe(B.author)}`;Se(a,se,"collaborates",Z,!0).catch(()=>{}),Se(a,Z,"collaborates",se,!0).catch(()=>{})}B.outcome==="success"&&s++,B.outcome==="success"&&(B.recall_count??0)>=1&&!st(B)&&I.push({topic:g.key.replace("cachly:lesson:best:",""),severity:B.severity??"major",recall_count:(B.recall_count??0)+1,savedMins:L,ts:B.ts,author:B.author})}}}s>0&&a.set(`cachly:stats:first_recall_at:${e}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),A.length>0&&(a.incr(`cachly:stats:recalls_total:${e}`).catch(()=>{}),E>0&&a.incr(`cachly:stats:cross_author_recalls:${e}`).catch(()=>{})),ke("smart_recall: Treffer gezaehlt");const ie=await ae(`/api/v1/instances/${e}`).catch(()=>null);ke("smart_recall: Tarif abgefragt");const ue=!ie?.tier||ie.tier.toLowerCase()==="free",ge=[];if(!ue&&ie?.vector_token&&Le())try{const g=await xe(u),w=`https://api.cachly.dev/v1/sem/${ie.vector_token}`,B=await fetch(`${w}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:g,namespace:"cachly:ctx",threshold:_,top_k:5}),signal:AbortSignal.timeout(8e3)});if(B.ok){const M=await B.json();for(const ee of M.filter(L=>L.found&&L.id)){const L=ee.id.replace("ctx:","").split(":"),se=L[0],Z=L.slice(1).join(":"),le=`cachly:ctx:${se}:${Z}`,G=await a.get(le).catch(()=>null);ge.push({key:le,similarity:ee.similarity??0,content:G??"(evicted)"})}}}catch{}const me=p.map(g=>g.score),d=me.length?Math.min(...me):0,H=me.length&&Math.max(...me)-d||1,oe=g=>(g-d)/H,V=new Map,X=k?Qs(p.map(g=>oe(g.score))):null,J=new Map;for(const[g,w]of p.entries()){const B=oe(w.score),M=X?X[g]:B;X&&V.set(w.key,g),J.set(w.key,{key:w.key,content:w.content,bm25Score:B,hausWert:M,hybridScore:M*(ge.length>0?.7:1),matchedWords:w.matchedWords,matchType:"keyword",subQuery:w.subQuery,wortBelege:w.wortBelege})}for(const g of ge){const w=J.get(g.key);w?(w.semScore=g.similarity,w.hybridScore=(w.hausWert??0)*.6+g.similarity*.4,w.matchType="hybrid"):J.set(g.key,{key:g.key,content:g.content,semScore:g.similarity,hybridScore:g.similarity*.5,matchType:"semantic"})}try{const g=ht(u).filter(M=>M.length>=4).slice(0,4),w=new Set;for(const M of g){const ee=a.scanStream({match:`cachly:ckg:node:*${M}*`,count:20});await new Promise((L,se)=>{ee.on("data",Z=>{for(const le of Z.slice(0,5))w.add(le.replace("cachly:ckg:node:",""))}),ee.on("end",L),ee.on("error",se)})}const B=new Set;for(const M of[...w].slice(0,12)){const ee=await a.smembers(`cachly:ckg:idx:to:${M}`);for(const L of ee.slice(0,6)){const se=await a.get(L);if(!se)continue;const Z=z(se,null);if(!Z||Z.edgeType!=="fixes"||Z.confidence<.35||B.has(Z.from))continue;B.add(Z.from);const le=`cachly:lesson:best:${Z.from}`,G=J.get(le);if(G)G.ckgScore=Math.max(G.ckgScore??0,Z.confidence),G.hybridScore=G.hybridScore*.88+Z.confidence*.12,G.matchType==="keyword"&&(G.matchType="hybrid");else{const ve=await a.get(le).catch(()=>null);if(!ve)continue;J.set(le,{key:le,content:ve,ckgScore:Z.confidence,hybridScore:Z.confidence*.3,matchType:"ckg"})}}}}catch{}if(ke("smart_recall: Sinn-Dienst und CKG fertig"),N.length>0){const g=new Set(N.map(w=>w.replace(/\\/g,"/")));for(const w of J.values()){if(!w.key.startsWith("cachly:lesson:best:"))continue;const B=z(w.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(ee=>typeof ee=="string").map(ee=>ee.replace(/\\/g,"/")):[]).some(ee=>g.has(ee))&&(w.hybridScore*=1.15,w.contextBoost=!0)}}for(const g of J.values()){if(g.matchType!=="semantic"&&g.matchType!=="ckg")continue;const w=Ks({key:g.key,content:g.content});w&&(g.hybridScore*=Gs(w))}const te=[...J.values()].filter(g=>{if(!g.key.startsWith("cachly:lesson:best:"))return!0;const w=Re(g.content);return!(!We(w)||!Et(w?.group,r,S))}),j=X?Xs(te,V):te.sort((g,w)=>w.hybridScore-g.hybridScore),h=[];for(const g of j){if(!g.key.startsWith("cachly:lesson:best:"))continue;const w=z(g.content,{});w.gilt_bis&&Date.parse(String(w.gilt_bis))<Date.now()&&h.push(`\u23F3 \`${g.key.replace("cachly:lesson:best:","")}\` galt bis ${String(w.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const B=z(g.content,{});if(B.pruefung_gefallen_am){const M=g.key.replace("cachly:lesson:best:",""),ee=String(B.pruefung_gefallen_am).slice(0,10),L=String(B.pruefung_befund??"").trim().slice(0,200);h.push(`\u274C \`${M}\` \u2014 Pruefung am ${ee} FEHLGESCHLAGEN`+(L?`: ${L}`:""))}}{const g=new Set(j.map(w=>w.key));for(let w=j.length-1;w>=0;w--){const B=j[w];if(!B.key.startsWith("cachly:lesson:best:"))continue;const M=z(B.content,{});if(!M.ersetzt_durch)continue;const ee=String(M.ersetzt_grund??"").trim(),L=B.key.replace("cachly:lesson:best:","");if(g.has(`cachly:lesson:best:${M.ersetzt_durch}`))j.splice(w,1),h.push(`\u21B7 \`${L}\` verdraengt \u2014 ersetzt durch \`${M.ersetzt_durch}\`${M.ersetzt_am?` am ${M.ersetzt_am.slice(0,10)}`:""}${ee?` \u2014 Grund: ${ee}`:" \u2014 Grund nicht erfasst"}`);else if(await a.get(`cachly:lesson:best:${M.ersetzt_durch}`)){const se=Re(await a.get(`cachly:lesson:best:${M.ersetzt_durch}`));We(se)?h.push(`\u26A0\uFE0F \`${L}\` ist ersetzt durch \`${M.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${M.ersetzt_durch}")\``):h.push(`\u21B7 \`${L}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else h.push(`\u21A9\uFE0F \`${L}\` war ersetzt durch \`${M.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const $=nn(j,N),y=[];{await $e.aktualisiere(a).catch(()=>{});const g=j.slice(0,8).filter(w=>w.key.startsWith("cachly:lesson:best:"));for(let w=0;w<g.length;w++)for(let B=w+1;B<g.length;B++){const M=g[w].key.replace("cachly:lesson:best:",""),ee=g[B].key.replace("cachly:lesson:best:",""),L=$e.rohvektor(M),se=$e.rohvektor(ee);if(!L||!se)continue;let Z=0,le=0,G=0;for(let be=0;be<L.length;be++)Z+=L[be]*se[be],le+=L[be]*L[be],G+=se[be]*se[be];if((le>0&&G>0?Z/(Math.sqrt(le)*Math.sqrt(G)):0)<Tn)continue;const Ee=be=>{const x=z(be??"",{});return String(x.verified_at??x.ts??"").slice(0,10)||"ohne Datum"};y.push(`\u26A0\uFE0F \`${M}\` (${Ee(g[w].content)}) und \`${ee}\` (${Ee(g[B].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}y.length>3&&(y.length=3)}if(h.push(...y),j.length>=2){const g=j[0].hybridScore,w=j[Math.min(4,j.length-1)].hybridScore,B=Math.max(0,g-w);(async()=>{try{await a.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:j.length})),await a.ltrim("cachly:recall:spread",0,199)}catch{}})()}const b=As();let v="",R=null;if(b!==null){v=Es();const g=j[0]?.hybridScore??0,w=Is(j.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),v,b,g);w.weggelassenesThema!==void 0?j.splice(0,1):w.markierungGesetzt&&j[0]&&w.treffer[0]&&(j[0]={...j[0],content:w.treffer[0].content}),R={frage:u,hoechstePunktzahl:g,themen:[],zulassungsfaehig:w.zulassungsfaehig,zulassungsGrund:w.zulassungsGrund,zuteilung:w.zuteilung,weggelassenesThema:w.weggelassenesThema,markierungGesetzt:w.markierungGesetzt}}ke("smart_recall: Notizen und Duplikate fertig");const K=await rs(e,ae);ke("smart_recall: Abruf-Grenze abgefragt");const Y=K.reached,U=qt({ueberLimit:Y,gesamt:j.length,volleTiefe:jn}),ce=process.env.CACHLY_RECALL_COMPACT==="1",ye=(()=>{const g=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(g)?Math.min(20,Math.max(1,g)):5})(),Q=ce?Math.min(ye,U.sichtbar):U.sichtbar,q=[`\u{1F9E0} **Smart Recall** for: _"${u}"_
|
|
19
|
+
`];K.goodwillMessage&&q.push(`${K.goodwillMessage}
|
|
20
|
+
`);const Ne={critical:0,major:1,minor:2},_e=I.sort((g,w)=>(Ne[g.severity]??1)-(Ne[w.severity]??1))[0];if(_e){const g=L=>L>=60?`${L/60}h`:`${L}min`,w=(()=>{if(!_e.ts)return null;const L=new Date(_e.ts);if(isNaN(L.getTime()))return null;const se=new Date,Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return L.getFullYear()===se.getFullYear()?`${L.getDate()} ${Z[L.getMonth()]}`:`${L.getDate()} ${Z[L.getMonth()]} ${L.getFullYear()}`})(),B=_e.severity==="critical"?120:_e.severity==="major"?60:20,M=_e.author&&_e.author!==o?` \xB7 by @${_e.author}`:"",ee=w?` \xB7 learned ${w} (was a ${g(B)} debug)`:"";q.push(`> \u{1F4A1} **Brain saved you ~${g(_e.savedMins)} here** \u2014 \`${_e.topic}\`${ee} \xB7 recalled ${_e.recall_count}\xD7${M}
|
|
21
|
+
`)}E>0&&q.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${E} of these lesson${E!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
|
|
22
|
+
`);const we=j.filter(g=>g.contextBoost).length;we>0&&q.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 he=zs(u);he.length>1&&q.push(`_Detected ${he.length} sub-topics:_ ${he.map((g,w)=>`${w+1}. "${g}"`).join(", ")}
|
|
24
|
+
`);const Ce=vs(j.map(g=>({wortBelege:g.wortBelege,semScore:g.semScore,ckgScore:g.ckgScore})));if(Ce.schweigen)return $t(a,e,"schweigen"),q.push($s(Ce)),q.join(`
|
|
25
|
+
`);const Ae=pn(m);if(Ae&&q.push(Ae,""),$t(a,e,Ae?"knapp":"beantwortet"),j.length>0){const g=j.some(M=>M.ckgScore!==void 0),w=k||ge.length>0,B=w&&g?"keyword + semantic + CKG hybrid":w?"keyword + semantic hybrid":g?"keyword + CKG hybrid":"keyword";if(q.push(`### \u{1F50D} Results (${j.length} \u2014 ${B})
|
|
26
|
+
`),Ce.belegte<j.length){const M=[];for(const L of j){if(!L.key.startsWith("cachly:lesson:best:")||!Ss({wortBelege:L.wortBelege,semScore:L.semScore,ckgScore:L.ckgScore}))continue;const se=z(L.content,{}),Z=Date.parse(se.verified_at??se.ts??"");Number.isFinite(Z)&&M.push(Math.floor((Date.now()-Z)/864e5))}const ee=ks(M);q.push(`> \u{1F4CA} ${Ce.belegte} von ${j.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(ee?` \u23F3 ${ee}`:"")+`
|
|
27
|
+
`)}if(h.push(...on(j.slice(0,Q),$)),h.length>0&&q.push(...h.map(M=>`> ${M}`),""),he.length>1){const M=new Map,ee=qt({ueberLimit:Y,gesamt:j.length,volleTiefe:Wn});for(const Z of j.slice(0,ee.sichtbar)){const le=Z.subQuery??u;M.has(le)||M.set(le,[]),M.get(le).push(Z)}for(const[Z,le]of M){q.push(`**Topic: "${Z}"** (${le.length} results)
|
|
28
|
+
`);for(const G of le.slice(0,ce?2:4)){const ve=G.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),Ee=G.matchType==="ckg"?`CKG: ${(G.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:G.ckgScore!==void 0&&G.bm25Score!==void 0?`BM25: ${G.bm25Score.toFixed(2)}, CKG: ${G.ckgScore.toFixed(2)}, \u{1F500} hybrid`:G.matchType==="hybrid"?`BM25: ${(G.bm25Score??0).toFixed(2)}, sem: ${((G.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:G.matchType==="semantic"?`sem: ${((G.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(G.bm25Score??0).toFixed(2)}, matched: ${G.matchedWords?.join(", ")}`,be=ce?ct(G.key,G.content,300):ct(G.key,G.content,Tt,300);if(q.push(ce?` **${ve}**`:` **${ve}** _(${Ee})_`),G.key.startsWith("cachly:lesson:best:")){const x=await a.get(G.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(G.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),W=x?z(x,{}):{};W.title&&q.push(` \u{1F4D6} **${W.title}** \u2014 ${W.summary??""}`)}{const x=G.key.startsWith("cachly:lesson:best:")?Xt(G.content):"";x&&q.push(` ${x}`)}for(const x of be)q.push(` > ${x}`);q.push("")}}const L=[...M.keys()],se=he.filter(Z=>!L.includes(Z));se.length>0&&q.push(`
|
|
29
|
+
\u26A0\uFE0F **No results for:** ${se.map(Z=>`"${Z}"`).join(", ")}`)}else for(const M of j.slice(0,Q)){const ee=M.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let L="";if(M.key.startsWith("cachly:lesson:best:")){const G=z(M.content,{});G.author&&(L=` \xB7 \u{1F464} ${G.author}`)}const se=M.contextBoost?" \xB7 \u{1F4C1} context match":"",Z=M.matchType==="hybrid"?`BM25: ${(M.bm25Score??0).toFixed(2)}, sem: ${((M.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:M.matchType==="semantic"?`sem: ${((M.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(M.bm25Score??0).toFixed(2)}, matched: ${M.matchedWords?.join(", ")}`,le=ct(M.key,M.content,ce?Nt:Tt,Nt);q.push(ce?`**${ee}**`:`**${ee}**${L}${se} _(${Z})_`);{const G=z(M.content??"",{});G.entscheidung?.gegen&&q.push(Wt({gegen:G.entscheidung.gegen,grund:G.entscheidung.grund??null}))}if(M.key.startsWith("cachly:lesson:best:")){const G=await a.get(M.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await a.get(M.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ve=G?z(G,{}):{};ve.title&&q.push(`\u{1F4D6} **${ve.title}** \u2014 ${ve.summary??""}`)}{const G=M.key.startsWith("cachly:lesson:best:")?Xt(M.content):"";G&&q.push(G)}for(const G of le)q.push(`> ${G}`);q.push("")}if(Y&&U.zurueckgehalten>0){const M=U.zurueckgehalten;q.push(`\u{1F512} **Free recall limit reached** (${K.used}/${K.limit} this month). Showing your top match; ${M} further relevant lesson${M!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${mo}
|
|
30
|
+
`)}}else{q.push(`\u26A0\uFE0F No matches found for: "${u}"`),h.length>0&&q.push("",...h.map(B=>`> ${B}`));const g=ht(u),w=[];if(Mt.size>0&&g.length>0)for(const B of g.slice(0,3)){if(B.length<4)continue;let M=3,ee="";for(const L of Mt){if(L.length<3||Math.abs(L.length-B.length)>4)continue;const se=Os(B,L);se>0&&se<M&&(M=se,ee=L)}ee&&w.push(`"${ee}" (instead of "${B}")`)}w.length>0?q.push(`\u{1F4A1} **Did you mean:** ${w.join(", ")}?`):(q.push(`
|
|
31
|
+
\u{1F4A1} Tips:`),q.push(" \u2022 Try different keywords"),q.push(" \u2022 Use `list_remembered` to see available context"),q.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!ce&&j.length>0){q.push(""),q.push("\u21A9\uFE0E Hat eine davon geholfen? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` \u2014 und wenn die richtige Lektion **nicht** dabei war: dieselbe Meldung mit `rank=0`. Das ist die einzige Zahl, die die Sortierung besser macht.");const g=j.filter(w=>w.key.startsWith("cachly:lesson:best:")).map(w=>w.key.slice(19));if(g.length>0)try{await a.setex(`cachly:letzter-recall:${e}`,7200,JSON.stringify({frage:u,themen:g}))}catch{}}if(ce&&j.length>0){const g=gs();g&&(q.push(""),q.push(g))}if(b!==null&&R){const g=j.slice(0,Q).filter(w=>w.key.startsWith("cachly:lesson:best:")).map(w=>w.key.slice(19));return Ms(a,v,{...R,themen:g},q.join(`
|
|
32
|
+
`))}return q.join(`
|
|
33
|
+
`)}case"session_start":{const{instance_id:f,focus:e="",author:u="",provider:_="",workspace_path:o=""}=D;if(await Dt(f,ae))return P(f).then(async h=>{await as(h),await is(h,e,_),await h.set("cachly:mcp:version:last_seen",qe,"EX",365*86400)}).catch(()=>{}),ke("session_start: neues Brain startet noch \u2014 sofort geantwortet"),Ws({instanzId:f,provider:_,...ut(f)});const n=await P(f),N=[],a=n.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((h,$)=>{a.on("data",y=>N.push(...y)),a.on("end",h),a.on("error",$)});const r=[];let S=0;if(N.length>0){const h=await n.mget(...N);for(const $ of h){const y=z($??null,null);if(y){if(Yt(y)){S++;continue}es(y.topic)||r.push(y)}}}r.sort((h,$)=>new Date($.ts).getTime()-new Date(h.ts).getTime());let i=0;const t=n.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((h,$)=>{t.on("data",y=>{i+=y.filter(b=>!b.endsWith(":meta")).length}),t.on("end",h),t.on("error",$)});const C=await n.get("cachly:session:last"),l=z(C,null),c=e.toLowerCase().split(/\s+/).filter(Boolean),k=c.length>0?r.filter(h=>c.some($=>h.topic.toLowerCase().includes($)||(h.tags??[]).some(y=>y.toLowerCase().includes($)))):[],{tage:m,rekord:p}=await as(n);let I="";m>=7?I=`\u{1F525} **${m}-day streak!** ${m===p?" New record!":`Best: ${p}d`}`:m>1&&(I=`\u{1F525} ${m}-day streak`),await is(n,e,_);let A=0;try{const h=await n.get(`cachly:stats:time_saved_mins:${f}`);A=parseFloat(h??"0")}catch{}const s=[`\u{1F9E0} **Session Briefing**${_?` \xB7 ${_}`:""}`,""];if(I&&s.push(I,""),A>=30){const h=Math.floor(A/60),$=Math.round(A%60),y=h>0?`${h}h${$>0?` ${$}m`:""}`:`${$}m`,b=r.filter(R=>!st(R)&&(R.recall_count??0)>0).length,v=b>0?` \u2014 ${b} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";s.push(`\u23F1\uFE0F **Brain saved you ~${y} total**${v}`,"")}const ie=await rs(f,ae),ue=Pn({used:ie.used,limit:ie.limit,savedMins:A});if(ue&&s.push(ue,""),ie.notice&&!ss.has(f)&&(ss.add(f),s.push(ie.notice,"")),l?.ts){const h=new Date(l.ts).getTime(),$=Math.floor((Date.now()-h)/864e5);if($>=7&&!Number.isNaN(h)){const y=r.filter(b=>{const v=new Date(b.ts).getTime();return!Number.isNaN(v)&&v>h});if(s.push(`\u{1F44B} **Welcome back** \u2014 it's been ${$} days since your last session.`),y.length>0){const b=y.slice(0,3).map(v=>`\`${v.topic}\``).join(", ");s.push(` \u{1F331} Your Brain grew by **${y.length} lesson${y.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${b}${y.length>3?", \u2026":""}`)}else s.push(` \u{1F9E0} ${r.length} lesson${r.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);s.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await n.get("cachly:mcp:version:last_seen")!==qe){await n.set("cachly:mcp:version:last_seen",qe,"EX",365*86400);const $=go[qe];if($){s.push(...$,"");const y=fo();y&&s.push(`\u{1F4CA} ${y} MCP tools`,"")}}}catch{}const ge=!l&&r.length===0&&S===0&&i===0;ge&&(s.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),o?(s.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),s.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(s.push("It learns from your work automatically. After your first session it will look like this:",""),s.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),s.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),s.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),s.push(""),s.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),s.push("")),s.push("**Your brain grows automatically:**"),s.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),s.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),s.push(""),s.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),s.push(" `smart_recall` returns a hit instead of nothing:"),s.push(` \`brain_seed_starter(instance_id="${f}")\``),s.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),s.push(""),s.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),s.push(""));const me=k.slice(0,4),d=new Set(me.map(h=>h.topic));if(u&&!ge)try{const h=`cachly:team:first_briefing:${u}`;if(!await n.get(h)){const y=r.filter(b=>b.author&&b.author!==u&&!d.has(b.topic));if(y.length>0){await n.set(h,"1","EX",365*86400);const b=new Map;for(const v of y){const R=v.author;b.has(R)||b.set(R,[]),b.get(R).push(v)}s.push(""),s.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"),s.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),s.push(""),s.push("Your teammates have already solved problems you're about to hit:"),s.push("");for(const[v,R]of b){s.push(` \u{1F464} **${v}** fixed ${R.length} thing${R.length>1?"s":""}:`);for(const K of R.slice(0,2)){const Y=K.outcome==="success"?"\u2705":"\u26A0\uFE0F";s.push(` ${Y} \`${K.topic}\` \u2014 ${K.what_worked.slice(0,90)}`),d.add(K.topic)}R.length>2&&s.push(` \u2026 and ${R.length-2} more lessons`)}s.push(""),s.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),s.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"),s.push("")}}}catch{}const H=await n.get("cachly:session:handoff");if(H)try{const h=JSON.parse(H),$=Math.round((Date.now()-new Date(h.ts).getTime())/6e4),y=$<60?`${$}m ago`:$<1440?`${Math.round($/60)}h ago`:`${Math.round($/1440)}d ago`;if(s.push(`\u{1F91D} **Handoff from previous window** (${y}):`),h.context_summary&&s.push(` ${h.context_summary}`),h.remaining_tasks.length>0){s.push(" \u23F3 **Remaining tasks:**");for(const v of h.remaining_tasks)s.push(` - ${v}`)}h.completed_tasks.length>0&&s.push(` \u2705 **Already done:** ${h.completed_tasks.join(", ")}`);const b=(h.files_changed??[]).filter(v=>v.status==="broken"||v.status==="partial");b.length>0&&s.push(` \u26A0\uFE0F **Needs fix:** ${b.map(v=>`\`${v.path}\` (${v.status}${v.description?": "+v.description:""})`).join(", ")}`),h.blocked_on&&s.push(` \u{1F6AB} **Blocked on:** ${h.blocked_on}`),h.instructions&&s.push(` \u{1F4DD} **Instructions:** ${h.instructions}`),s.push("")}catch{}const oe=await n.get("cachly:session:checkpoint");if(oe)try{const h=JSON.parse(oe),$=new Date(h.ts).getTime(),y=l?new Date(l.ts).getTime():0;if($>y){const b=Math.round((Date.now()-$)/6e4),v=b<60?`${b}m ago`:b<1440?`${Math.round(b/60)}h ago`:`${Math.round(b/1440)}d ago`,R=h.provider?` [${h.provider}]`:"";s.push(`\u{1F4CC} **Last checkpoint**${R} (${v}): ${h.task}`),h.files_touched.length>0&&s.push(` Files: ${h.files_touched.slice(0,5).map(K=>`\`${K}\``).join(", ")}`),h.next_step&&s.push(` \u{1F4CD} Next step was: ${h.next_step}`),(!l||$-y>3e5)&&s.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),s.push("")}}catch{}const V=l?null:et(o);if(V)try{const h=Pe(V,["log","--oneline","--format=%h %s","-15"]).trim();let $;try{$=Pe(V,["diff","--stat","HEAD~3"]).trim()}catch{$=Pe(V,["diff","--stat"]).trim()}if(h){s.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const y of h.split(`
|
|
34
|
+
`).slice(0,8))s.push(` ${y}`);if($){const y=$.split(`
|
|
35
|
+
`).filter(b=>b.includes("|")||b.includes("changed"));if(y.length>0){s.push(" **Recent changes:**");for(const b of y.slice(0,5))s.push(` ${b.trim()}`)}}s.push("")}}catch{}if(l){const h=Math.round((Date.now()-new Date(l.ts).getTime())/6e4),$=h<60?`${h}m ago`:h<1440?`${Math.round(h/60)}h ago`:`${Math.round(h/1440)}d ago`;s.push(`\u{1F4C5} **Last session** (${$}): ${l.summary}`),l.duration_min&&s.push(` Duration: ${l.duration_min} min`),(l.files_changed??[]).length>0&&s.push(` Files: ${(l.files_changed??[]).slice(0,5).map(y=>`\`${y}\``).join(", ")}`),s.push("")}s.push(`\u{1F4CA} **Brain:** ${r.length} lessons \xB7 ${i} context entries`,""),S>0&&s.push(`\u26A0 ${S} Lektion(en) wurden beim Speichern als verd\xE4chtig markiert und stehen nicht in diesem Briefing. Ausdr\xFCcklich abrufbar mit recall_best_solution (mit Warnzeile); pr\xFCfen oder neu speichern.`,"");{const $=r.filter(y=>!st(y)).filter(y=>y.outcome==="success"&&(y.pinned===!0||(y.recall_count??0)>=5)).filter(y=>!d.has(y.topic)).sort((y,b)=>(b.recall_count??0)-(y.recall_count??0)).slice(0,5);if($.length>0){s.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const y of $){d.add(y.topic);const b=y.severity==="critical"?"\u{1F534}":y.severity==="major"?"\u{1F7E1}":"",v=y.recall_count??0,R=y.pinned===!0?"pinned":`recalled ${v}\xD7`,K=Ue(y);s.push(` \u{1F3C6}${b} \`${y.topic}\` _(${R})_ \u2014 ${K[0]??""}`,...K.slice(1))}s.push("")}}try{const h=[],$=n.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((y,b)=>{$.on("data",v=>h.push(...v)),$.on("end",y),$.on("error",b)}),h.length>0){s.push(`\u26A1 **Active belief conflicts (${h.length}):**`);for(const y of h.slice(0,3)){const b=await n.get(y);if(!b)continue;const v=z(b,null);v&&s.push(` \u26A0\uFE0F \`${v.topic}\` \u2014 previously confirmed fix (${(v.fix_confidence*100).toFixed(0)}%, n=${v.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${pe(v.topic)}")\``)}s.push("")}}catch{}if(me.length>0){s.push(`\u{1F3AF} **Relevant for "${e}":**`);for(const h of me){const $=h.outcome==="success"?"\u2705":h.outcome==="partial"?"\u26A0\uFE0F":"\u274C",y=h.severity==="critical"?"\u{1F534}":h.severity==="major"?"\u{1F7E1}":"",b=Ue(h);s.push(` ${$}${y} \`${h.topic}\` \u2014 ${b[0]??""}`,...b.slice(1))}s.push("")}if(r.length>0){const h=(k.length>0?r.filter($=>!k.includes($)):r).filter($=>!d.has($.topic)).slice(0,k.length>0?3:4);if(h.length>0){s.push("\u{1F550} **Recent lessons:**");for(const $ of h){d.add($.topic);const y=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C",b=$.severity==="critical"?"\u{1F534}":$.severity==="major"?"\u{1F7E1}":"",v=Ue($);s.push(` ${y}${b} \`${$.topic}\` \u2014 ${v[0]??""}`,...v.slice(1))}s.push("")}}else s.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");r.length>=10&&(r.some($=>$.author)||(s.push(`\u{1F91D} **Your Brain has ${r.length} lessons \u2014 your team could benefit instantly.**`),s.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const X=await En(n,r);if(X.length>0){s.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const h of X.slice(0,3))s.push(` \`${h.neu}\` \u2248 \`${h.alt}\` (${h.naehe.toFixed(2)})`);s.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),s.push("")}const J=l;if(J?.decision_log?.length){const h=J.decision_log,$=h.filter((v,R)=>!d.has(v.topic)&&h.findIndex(K=>K.topic===v.topic)===R),y=$.filter(v=>v.outcome==="success"),b=$.filter(v=>v.outcome==="failure");if(y.length>0||b.length>0){s.push(`\u{1F3AC} **Last session decisions** (${h.length} lessons stored):`),y.length>0&&s.push(` \u2705 Worked: ${y.slice(0,3).map(v=>`\`${v.topic}\``).join(", ")}`),b.length>0&&s.push(` \u274C Failed: ${b.slice(0,3).map(v=>`\`${v.topic}\``).join(", ")}`),s.push("");for(const v of[...y.slice(0,3),...b.slice(0,3)])d.add(v.topic)}}{const h=new Set(["src","lib","test","tests","dist","index","main","app","internal","pkg","cmd","node_modules","components","utils","ts","tsx","js","jsx","go","py","rs","java","json","yaml","yml"]),$=R=>{const K=new Set;for(const Y of R)for(const U of Y.toLowerCase().split(/[/\\._-]/))U.length>3&&!h.has(U)&&K.add(U);return[...K]};let y=c,b=e,v=!1;if(y.length===0&&l){const R=$(l.files_changed??[]),K=(l.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(Y=>Y.length>3&&!h.has(Y));y=[...new Set([...R,...K])],b="where you left off last session",v=!0}if(y.length>0){const R=r.filter(K=>{if(K.outcome==="success")return!1;const Y=K.topic.split(":")[0];return y.some(U=>K.topic.toLowerCase().includes(U)||Y===U||(K.tags??[]).some(ce=>ce.toLowerCase()===U))});if(R.length>=1){const Y=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",v?` You're likely to continue **${b}** \u2014 ${R.length} known pitfall${R.length>1?"s":""} there:`:` Known pitfalls for **"${b}"** (${R.length} past failure${R.length>1?"s":""}):`,...R.slice(0,3).map(U=>` \u274C \`${U.topic}\` \u2014 ${(U.what_failed??U.what_worked).slice(0,80)}`),""];s.splice(2,0,...Y)}}}if(u){const h=Date.now()-6048e5,$=r.filter(y=>y.author&&y.author!==u&&new Date(y.ts).getTime()>h&&!d.has(y.topic));if($.length>0){const y=new Map;for(const b of $){const v=b.author;y.has(v)||y.set(v,[]),y.get(v).push(b)}s.push(`\u{1F465} **Team this week** (${$.length} lesson${$.length>1?"s":""} from teammates):`);for(const[b,v]of y){s.push(` \u{1F464} **${b}**:`);for(const R of v.slice(0,3)){const K=R.outcome==="success"?"\u2705":R.outcome==="partial"?"\u26A0\uFE0F":"\u274C";s.push(` ${K} \`${R.topic}\` \u2014 ${R.what_worked.slice(0,80)}`),d.add(R.topic)}v.length>3&&s.push(` \u2026 and ${v.length-3} more`)}s.push("")}}try{const h=await n.get("cachly:crystal:latest");if(h){const $=z(h,null);if($&&Math.round((Date.now()-new Date($.ts).getTime())/864e5)<=90){s.push(`\u{1F48E} **Memory Crystal** (${$.label} \xB7 ${$.session_count} sessions compressed):`);for(const b of $.top_patterns.slice(0,3))s.push(` \u2022 **${b.category}** (${b.count}\xD7): ${b.insight.slice(0,90)}`);s.push("")}}}catch{}try{const h=await n.hgetall(`cachly:roadmap:${f}`);if(h&&Object.keys(h).length>0){const $={critical:0,high:1,medium:2,low:3},y={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},b=new Set(["planned","in-progress","blocked"]),v=Object.values(h).flatMap(Y=>{const U=z(Y,null);return U?[U]:[]}),R=v.filter(Y=>b.has(Y.status)).sort((Y,U)=>Y.status==="in-progress"&&U.status!=="in-progress"?-1:U.status==="in-progress"&&Y.status!=="in-progress"?1:($[Y.priority]??99)-($[U.priority]??99)),K=v.filter(Y=>Y.status==="done").length;if(R.length>0){s.push(`\u{1F5FA}\uFE0F **Roadmap** (${R.length} open \xB7 ${K} done):`);for(const Y of R.slice(0,5)){const U=Y.status==="in-progress"?"\u26A1":Y.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";s.push(` ${U} ${y[Y.priority]??"\u26AA"} \`${Y.id}\` **${Y.title}**`)}R.length>5&&s.push(` \u2026 and ${R.length-5} more`),s.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),s.push("")}}}catch{}try{const h=await n.get("cachly:mcm:calibration:last"),$=z(h,null)?.ts??0;if((Date.now()-$)/864e5>=30&&r.length>=5){const b=r.filter(R=>R.outcome==="success"&&(R.recall_count??0)>0),v=r.filter(R=>(R.recall_count??0)>0);if(v.length>=3){const R=v.length>0?b.length/v.length:1,K=[],Y=new Map;for(const U of v){const ce=U.topic.split(":")[0]??"other";Y.has(ce)||Y.set(ce,{success:0,total:0});const ye=Y.get(ce);ye.total++,U.outcome==="success"&&ye.success++}for(const[U,ce]of Y)ce.total>=2&&ce.success/ce.total<.6&&K.push(U);await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:R,recalled:v.length,low_precision_domains:K})),(K.length>0||R<.7)&&(s.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${v.length} recalled lessons):`),s.push(` Overall precision: **${(R*100).toFixed(0)}%** recalled lessons actually worked`),K.length>0&&s.push(` \u26A0\uFE0F Low-precision domains: ${K.map(U=>`\`${U}\``).join(", ")} \u2014 consider revisiting these lessons`),s.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),s.push(""))}await n.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const te=r.filter(h=>h.outcome==="failure"||h.outcome==="partial").length,j=r.filter(h=>h.outcome==="success"&&vt(h)<fs).length;if(r.length===0||te>0||j>0){const h=[];r.length===0&&h.push("brain is empty"),te>0&&h.push(`${te} open failure${te>1?"s":""}`),j>0&&h.push(`${j} stale lesson${j>1?"s":""}`),s.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${h.join(", ")}._`)}try{if(await n.get(`cachly:prefs:auto_changelog:${f}`).catch(()=>null)!=="false"&&l?.ts&&!ge){const y=new Date(l.ts).getTime();if(!Number.isNaN(y)){const b=r.filter(R=>{const K=new Date(R.ts).getTime();return!Number.isNaN(K)&&K>y}),v=b.filter(R=>!d.has(R.topic));if(v.length>0){const R=Math.round((Date.now()-y)/6e4),K=R<60?`${R}m`:R<1440?`${Math.round(R/60)}h`:`${Math.round(R/1440)}d`,Y=b.length-v.length;s.push(""),s.push(`\u{1F4CB} **${b.length} new lesson${b.length!==1?"s":""} since your last session** (${K} ago${Y>0?`, ${Y} already listed above`:""}):`);const U=new Map;for(const ce of v.slice(0,20)){const ye=ce.topic.includes(":")?ce.topic.split(":")[0]:"general",Q=U.get(ye)??[];Q.push(ce),U.set(ye,Q)}for(const[ce,ye]of U){s.push(` **${ce}**`);for(const Q of ye){const q=Q.outcome==="failure"?"\u274C":Q.severity==="critical"?"\u{1F6A8}":Q.severity==="major"?"\u26A0\uFE0F":"\u2705",Ne=(Q.outcome==="failure"?Q.what_failed:Q.what_worked)??"";s.push(` ${q} \`${Q.topic}\`${Ne?` \u2014 ${Ne.slice(0,80)}`:""}`)}}v.length>20&&s.push(` \u2026 and ${v.length-20} more. Call \`brain_changelog\` for the full list.`),s.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${f}", key="auto_changelog", value="false")\`_`)}}}}catch{}return s.join(`
|
|
36
|
+
`)}case"session_start_summary":{const{instance_id:f,focus:e,top_n:u=10,author:_=""}=D;if(!e||!e.trim())throw new Error("focus is required for session_start_summary");const o=Math.min(Math.max(1,Math.floor(Number(u)||10)),25),n=await P(f),N=[],a=n.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((E,s)=>{a.on("data",ie=>N.push(...ie)),a.on("end",E),a.on("error",s)});const r=[];if(N.length>0){const E=await n.mget(...N);for(const s of E){const ie=z(s??null,null);ie&&!Yt(ie)&&!es(ie.topic)&&r.push(ie)}}if(r.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="${f}")\` to bootstrap with 16 universal lessons.`].join(`
|
|
37
|
+
`);const S=r.length>o,i=e.toLowerCase().split(/\s+/).filter(Boolean),t=Date.now(),C=r.map(E=>{const s=i.filter(J=>E.topic.toLowerCase().includes(J)).length,ie=i.filter(J=>(E.tags??[]).some(te=>te.toLowerCase().includes(J))).length,ue=s*2+ie,ge=Math.max(0,E.recall_count??0),me=Math.min(1.5,Math.log1p(ge)/10),d=E.severity==="critical"?1:E.severity==="major"?.5:0,H=(t-new Date(E.verified_at??E.ts).getTime())/864e5,oe=H<30?.5*(1-H/30):0,V=E.outcome==="success"?.5:E.outcome==="partial"?.2:0,X=ue+me+d+oe+V;return{lesson:E,score:X}});C.sort((E,s)=>s.score!==E.score?s.score-E.score:new Date(s.lesson.ts).getTime()-new Date(E.lesson.ts).getTime());const l=(S?C.slice(0,o):C).map(E=>E.lesson),c=r.length,k=l.length,I=[S?`\u{1F9E0} Brain Summary \u2014 top ${k} of ${c} lessons for "${e}"`:`\u{1F9E0} Brain Summary \u2014 all ${k} lesson${k!==1?"s":""} for "${e}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(const E of l){const s=E.severity==="critical"?"\u{1F534}":E.severity==="major"?"\u26A0\uFE0F":"\u2705",ie=E.severity?`[${E.severity}] `:"[minor] ",ue=E.recall_count??0,ge=ue>0?` (\u2713 recalled ${ue}\xD7)`:"",me=E.what_worked.slice(0,110),d=no(E.author,_);I.push(`${s} ${ie}\`${E.topic}\` \u2014 ${me}${ge}${d}`)}I.push("");const A=oo(l,_);return A>0&&I.push(`\u{1F465} ${A} of these ${A===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),S?I.push(`\u{1F4A1} Showing top ${k} of ${c} lessons \xB7 \`session_start\` for full briefing`):I.push(`\u{1F4A1} All ${k} lesson${k!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),I.join(`
|
|
38
|
+
`)}case"session_end":{const{instance_id:f,summary:e,files_changed:u=[],lessons_learned:_,workspace_path:o=""}=D,n=Oe({summary:e,files_changed:u}),N=n.felder.summary,a=n.felder.files_changed,r=await P(f),S=new Date;let i;const t=await r.get("cachly:session:current");if(!t)return"\u26A0\uFE0F No active session found.\n\nRun `session_start` first to begin tracking a session, then call `session_end` when you're done.";const C=z(t,null);C?.started&&(i=Math.round((S.getTime()-new Date(C.started).getTime())/6e4));let l=[];try{l=(await r.lrange("cachly:session:decision-log",0,-1)).flatMap(oe=>{const V=z(oe,null);return V?[V]:[]}),await r.del("cachly:session:decision-log")}catch{}const c=Bn(f);Rn(f);const k={ts:S.toISOString(),summary:N,files_changed:a,...c.recalls>0?{memory_cost:c}:{},...n.verdacht.length?{verdacht:n.verdacht}:{},..._!==void 0?{lessons_learned:_}:{},...i!==void 0?{duration_min:i}:{},...l.length>0?{decision_log:l}:{}};await r.set("cachly:session:last",JSON.stringify(k)),await r.lpush("cachly:session:history",JSON.stringify(k)),await r.ltrim("cachly:session:history",0,49),await r.expire("cachly:session:history",90*86400),await r.del("cachly:session:current");const m=[];try{const H=/\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,oe=N.split(/[.!\n]+/).map(V=>V.trim()).filter(V=>V.length>20&&H.test(V));for(const V of oe.slice(0,6)){const J=V.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(y=>y.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(y)).slice(0,4).join("-");if(!J)continue;const te=`auto:${J}`,j=`cachly:lesson:best:${te}`,h=await r.get(j);if(h)try{if(JSON.parse(h).outcome==="success")continue}catch{}const $={topic:te,outcome:"success",what_worked:V,context:`Auto-learned from session summary. Full summary: ${N.slice(0,300)}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,session_ts:S.toISOString(),version:2,...n.verdacht.length?{tags:[_t]}:{}};await r.set(j,JSON.stringify($)),await r.expire(j,90*86400),m.push(te)}}catch{}const p=[],I=et(o);let A=0,E=0;if(I)try{const oe=`--since=${(t?(()=>{try{return JSON.parse(t).started??""}catch{return""}})():"")||"1 hour ago"}`,V=Pe(I,["log",oe,"--oneline","--format=%H|||%s|||%b|||%ai|||ENDE"]).trim();if(V){const X=/\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,J=V.split("|||ENDE").map(te=>te.trim()).filter(Boolean);for(const te of J.slice(0,10)){const[j,h,$,y]=te.split("|||"),b=Oe({msg:h??"",body:$??""}),v=b.felder.msg,R=b.felder.body;if(hs(j))try{const q=Pe(I,["diff-tree","--no-commit-id","--name-only","-r","--root",j]).trim(),_e=q?q.split(`
|
|
39
|
+
`).map(he=>he.trim()).filter(Boolean).slice(0,12):[],we=[];for(const he of _e)we.push(await St(r,he));for(let he=0;he<we.length;he++)for(let Ce=he+1;Ce<we.length;Ce++)await Se(r,we[he],"co-occurs",we[Ce],!0),await Se(r,we[Ce],"co-occurs",we[he],!0)}catch{}if(!v||!X.test(v))continue;const K=(R??"").trim();if(K.length<120)continue;const Y=v.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(!Y)continue;const U=`git:${Y}`,ce=`cachly:lesson:best:${U}`;if(await r.get(ce))continue;const Q={topic:U,outcome:"success",what_worked:`${v}
|
|
40
40
|
|
|
41
|
-
${
|
|
41
|
+
${K.slice(0,1200)}`,context:`Auto-learned from git commit ${(j??"").slice(0,7)} at ${y??""} in ${I}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3,...b.verdacht.length?{tags:[_t]}:{}};await r.set(ce,JSON.stringify(Q)),await r.expire(ce,60*86400),p.push(U),b.geschwaerzt.length&&A++,b.verdacht.length&&E++}}}catch{}const s=i!==void 0?` \xB7 ${i} min`:"",ie=m.length+p.length,ue=[];i!==void 0&&i>0&&ue.push(`\u23F1 ${i} min session`),ie>0&&ue.push(`\u{1F9E0} ${ie} lessons saved to Brain`),a.length>0&&ue.push(`\u{1F4C1} ${a.length} file${a.length>1?"s":""} changed`);const ge=ue.length>0?`${ue.join(" \xB7 ")}
|
|
42
42
|
|
|
43
43
|
My AI Brain remembers this so I never repeat it. @cachlydev
|
|
44
44
|
cachly.dev`:`Session saved to my AI Brain. No more re-explaining this tomorrow. @cachlydev
|
|
45
|
-
cachly.dev`,me=`https://twitter.com/intent/tweet?text=${encodeURIComponent(ge)}`,
|
|
46
|
-
`);return[`\u2705 **Session saved**${
|
|
47
|
-
`)}case"session_ping":{const{instance_id:f,task:
|
|
48
|
-
\u{1F4CD} **Next step:** ${
|
|
49
|
-
`)}case"session_handoff":{const{instance_id:f,completed_tasks:
|
|
50
|
-
${
|
|
45
|
+
cachly.dev`,me=`https://twitter.com/intent/tweet?text=${encodeURIComponent(ge)}`,d=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",i!==void 0?`\u2502 \u23F1 Duration : ${(i+" min").padEnd(26)}\u2502`:"",ie>0?`\u2502 \u{1F4DA} Learned : ${(ie+" lessons").padEnd(26)}\u2502`:"",a.length>0?`\u2502 \u{1F4C1} Changed : ${(a.length+" file"+(a.length>1?"s":"")).padEnd(26)}\u2502`:"","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",`\u2502 \u{1F4E3} Share: ${me.slice(0,34).padEnd(34)}\u2502`,"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"].filter(H=>H!=="").join(`
|
|
46
|
+
`);return[`\u2705 **Session saved**${s}`,"",`\u{1F4CB} **Summary:** ${N}`,a.length>0?`\u{1F4C1} **Files changed:** ${a.map(H=>`\`${H}\``).join(", ")}`:"",_!==void 0?`\u{1F9E0} **Lessons stored:** ${_}`:"",...Ln(c),m.length>0?`\u{1F916} **Auto-learned:** ${m.length} lessons extracted from summary (${m.slice(0,3).map(H=>`\`${H}\``).join(", ")}${m.length>3?"\u2026":""})`:"",p.length>0?`\u{1F33F} **Ambient git learning:** ${p.length} commit${p.length>1?"s":""} auto-learned (${p.slice(0,3).map(H=>`\`${H}\``).join(", ")}${p.length>3?"\u2026":""})`:"",...He(n,"notiz"),...Qt(A,E,`${p.length} Git-Lektionen`),d,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(H=>H!=="").join(`
|
|
47
|
+
`)}case"session_ping":{const{instance_id:f,task:e,files_touched:u=[],next_step:_="",provider:o=""}=D,n=Oe({task:e,files_touched:u,next_step:_,provider:o}),{task:N,files_touched:a,next_step:r,provider:S}=n.felder,i=await P(f),t={ts:new Date().toISOString(),task:N,files_touched:a,next_step:r,provider:S,...n.verdacht.length?{verdacht:n.verdacht}:{}};await i.set("cachly:session:checkpoint",JSON.stringify(t),"EX",86400*3),await i.lpush("cachly:session:checkpoint:log",JSON.stringify(t)),await i.ltrim("cachly:session:checkpoint:log",0,19);const C=S?` [${S}]`:"",l=a.length>0?` \xB7 ${a.length} file${a.length>1?"s":""} touched`:"",c=r?`
|
|
48
|
+
\u{1F4CD} **Next step:** ${r}`:"";return[`\u{1F4CC} **Checkpoint saved**${C} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${N}${l}`,c,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...He(n,"notiz")].filter(k=>k!=="").join(`
|
|
49
|
+
`)}case"session_handoff":{const{instance_id:f,completed_tasks:e=[],remaining_tasks:u=[],files_changed:_=[],instructions:o="",context_summary:n="",blocked_on:N=""}=D,a=Oe({completed_tasks:e,remaining_tasks:u,files_changed:_,instructions:o,context_summary:n,blocked_on:N}),{completed_tasks:r,remaining_tasks:S,files_changed:i,instructions:t,context_summary:C,blocked_on:l}=a.felder,c=await P(f),m={ts:new Date().toISOString(),completed_tasks:r,remaining_tasks:S,files_changed:i,instructions:t,context_summary:C,blocked_on:l,...a.verdacht.length?{verdacht:a.verdacht}:{}};await c.set("cachly:session:handoff",JSON.stringify(m)),await c.lpush("cachly:session:handoff:history",JSON.stringify(m)),await c.ltrim("cachly:session:handoff:history",0,19);const p=r.length+S.length,I=p>0?Math.round(r.length/p*100):0,A=i.filter(E=>E.status==="broken"||E.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${r.length}/${p} tasks done (${I}%)`,"",r.length>0?`\u2705 **Completed:**
|
|
50
|
+
${r.map(E=>` - ${E}`).join(`
|
|
51
51
|
`)}`:"",S.length>0?`
|
|
52
52
|
\u23F3 **Remaining for next window:**
|
|
53
|
-
${S.map(
|
|
54
|
-
`)}`:"",
|
|
55
|
-
\u26A0\uFE0F **Needs attention:** ${
|
|
56
|
-
\u{1F6AB} **Blocked on:** ${l}`:"",
|
|
57
|
-
\u{1F4DD} **Instructions:** ${
|
|
58
|
-
`)}case"auto_learn_session":{const{instance_id:f,observations:
|
|
59
|
-
`)}case"brain_who_knows":{const{instance_id:f,topic:
|
|
60
|
-
`);const S=[...
|
|
61
|
-
`)}case"brain_file_map":{const{instance_id:f,file_paths:
|
|
62
|
-
`)}case"team_expertise_map":{const{instance_id:f,top_n:
|
|
63
|
-
`);const
|
|
64
|
-
`)}case"skill_gaps":{const{instance_id:f,min_failures:
|
|
65
|
-
`)}case"brain_coverage":{const{instance_id:f,repo_path:
|
|
66
|
-
`).filter(Boolean).length,
|
|
67
|
-
`)}case"brain_metrics":{const{instance_id:f}=
|
|
68
|
-
`),
|
|
69
|
-
`)}case"brain_service_map":{const{instance_id:f,service:
|
|
70
|
-
`);const l=n?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",
|
|
71
|
-
`)}case"brain_collab_pairs":{const{instance_id:f,min_weight:
|
|
72
|
-
`);const
|
|
73
|
-
`)}case"brain_portability":{const{instance_id:f}=
|
|
74
|
-
`)}case"brain_changelog":{const{instance_id:f,days:
|
|
75
|
-
`);const S=new Map;for(const
|
|
76
|
-
`)}case"brain_set_pref":{const{instance_id:f,key:
|
|
77
|
-
`)}case"brain_get_pref":{const{instance_id:f,key:
|
|
78
|
-
`)}default:return null}}async function
|
|
53
|
+
${S.map(E=>` - ${E}`).join(`
|
|
54
|
+
`)}`:"",A.length>0?`
|
|
55
|
+
\u26A0\uFE0F **Needs attention:** ${A.map(E=>`\`${E.path}\` (${E.status})`).join(", ")}`:"",l?`
|
|
56
|
+
\u{1F6AB} **Blocked on:** ${l}`:"",t?`
|
|
57
|
+
\u{1F4DD} **Instructions:** ${t}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically.",...He(a,"notiz")].filter(E=>E!=="").join(`
|
|
58
|
+
`)}case"auto_learn_session":{const{instance_id:f,observations:e}=D,u=await P(f),_=[],o=[];let n=0,N=0;for(const r of e){const S=Oe(r),i=S.felder,t=i.topic??i.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),C=t.includes(":")?t:`auto:${t}`,l=`cachly:lesson:best:${C}`,c=await u.get(l);if(c&&JSON.parse(c).outcome==="success"&&i.outcome!=="success"){o.push(C);continue}const k={topic:C,outcome:i.outcome,what_worked:i.outcome==="success"?i.action:i.details??i.action,what_failed:i.outcome==="failure"?i.action:void 0,context:i.details,severity:i.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2,...S.verdacht.length?{tags:[_t]}:{}},m=JSON.stringify(k);S.geschwaerzt.length&&n++,S.verdacht.length&&N++,await u.set(l,m);const p=`cachly:lessons:${C}`;await u.rpush(p,m),await u.ltrim(p,-100,-1),await u.expire(p,90*86400);try{const I=C.split(":")[0]??"auto",A=pe(C);if(await je(u,A,I,I),i.outcome==="success"||i.outcome==="partial"){const E=i.details?tt(i.details):null;if(E){const s=pe(`problem:${E}`);await je(u,s,"problem","problem"),await Se(u,A,"fixes",s,i.outcome==="success",i.outcome==="partial")}}}catch{}_.push(`${i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${C}\``)}const a=[`\u{1F916} **Auto-learn complete**: ${_.length} stored, ${o.length} skipped`,""];return _.length>0&&a.push("**Stored:**",..._.map(r=>" "+r),""),o.length>0&&a.push(`**Skipped** (better lesson already exists): ${o.map(r=>`\`${r}\``).join(", ")}`),a.push(...Qt(n,N,`${_.length} Beobachtungen`)),a.join(`
|
|
59
|
+
`)}case"brain_who_knows":{const{instance_id:f,topic:e,limit:u=10}=D;if(!e||typeof e!="string"||!e.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const _=Math.max(1,Math.min(Number(u)||10,50)),o=await P(f),n=pe(e),N=ht(e).filter(l=>l.length>=3).slice(0,5),a=new Set([n]);for(const l of N.slice(0,3)){const c=o.scanStream({match:`cachly:ckg:node:*${l}*`,count:30});await new Promise((k,m)=>{c.on("data",p=>{for(const I of p.slice(0,10)){const A=I.replace("cachly:ckg:node:","");!A.startsWith("person:")&&!A.startsWith("file:")&&a.add(A)}}),c.on("end",k),c.on("error",m)})}const r=new Map;for(const l of[...a].slice(0,25)){const c=await o.smembers(`cachly:ckg:idx:to:${l}`);for(const k of c){const m=await o.get(k);if(!m)continue;const p=z(m,null);if(!p||p.edgeType!=="authored")continue;const I=await o.get(`cachly:ckg:node:${p.from}`);if(!I)continue;const A=z(I,null);if(!A||A.type!=="person")continue;const E=r.get(p.from);E?(E.lessonCount++,E.totalConfidence+=p.confidence,E.domains.add(A.domain),p.last_updated>E.lastActive&&(E.lastActive=p.last_updated)):r.set(p.from,{handle:A.handle,lessonCount:1,totalConfidence:p.confidence,domains:new Set([A.domain]),lastActive:A.last_active??p.last_updated})}}if(r.size===0)return[`## \u{1F465} Who Knows About \`${e}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${e}", author="your-handle", ...)\``].join(`
|
|
60
|
+
`);const S=[...r.entries()].map(([l,c])=>({id:l,handle:c.handle,lessonCount:c.lessonCount,avgConfidence:c.totalConfidence/c.lessonCount,domains:[...c.domains].slice(0,3).join(", "),lastActive:c.lastActive})).sort((l,c)=>c.lessonCount*c.avgConfidence-l.lessonCount*l.avgConfidence).slice(0,_),i=[],t=S[0];if(t)try{const l=await o.smembers(`cachly:ckg:idx:from:${t.id}`),c=[];for(const k of l){const m=await o.get(k);if(!m)continue;const p=z(m,null);if(!p||p.edgeType!=="collaborates")continue;const I=await o.get(`cachly:ckg:node:${p.to}`),A=I?z(I,null):null;A?.handle&&c.push({handle:A.handle,trials:p.trials})}c.sort((k,m)=>m.trials-k.trials);for(const k of c.slice(0,3))i.push(k.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${e}\`?`,"",`**${S.length}** contributor${S.length!==1?"s":""} with relevant lessons:`,""];for(const[l,c]of S.entries()){const k=l===0?"\u{1F947}":l===1?"\u{1F948}":l===2?"\u{1F949}":`${l+1}.`,m=(c.avgConfidence*100).toFixed(0),p=Math.floor((Date.now()-new Date(c.lastActive).getTime())/864e5),I=p<1?"today":p<7?`${p}d ago`:p<30?`${Math.floor(p/7)}w ago`:`${Math.floor(p/30)}mo ago`,A=await lt(o,f,c.handle).catch(()=>null),E=A?` ${Ds[A]}`:"";C.push(`${k} **${c.handle}**${E} \u2014 ${c.lessonCount} lesson${c.lessonCount!==1?"s":""} \xB7 ${m}% confidence \xB7 last active ${I}`,` _domains: ${c.domains}_`,"")}return i.length>0&&t&&C.push(`\u{1F91D} **${t.handle}** frequently works with: ${i.map(l=>`**${l}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),C.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),C.join(`
|
|
61
|
+
`)}case"brain_file_map":{const{instance_id:f,file_paths:e=[]}=D,u=(Array.isArray(e)?e:[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());if(!u.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const _=await P(f),o=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const n of u.slice(0,10)){o.push(`### \`${n}\``);const N=`file:${pe(n)}`,a=await _.smembers(`cachly:ckg:idx:to:${N}`),r=[];for(const C of a){const l=await _.get(C);if(!l)continue;const c=z(l,null);if(!c||c.edgeType!=="touched")continue;const k=await _.get(`cachly:ckg:node:${c.from}`);if(!k)continue;const m=z(k,null);!m||m.type!=="person"||r.push({handle:m.handle,touches:c.trials,lastSeen:c.last_updated})}if(r.sort((C,l)=>l.touches-C.touches),r.length>0){const C=r.slice(0,5).map((l,c)=>{const k=c===0?"\u{1F947}":c===1?"\u{1F948}":c===2?"\u{1F949}":`${c+1}.`,m=Math.floor((Date.now()-new Date(l.lastSeen).getTime())/864e5),p=m<1?"today":m<7?`${m}d ago`:`${Math.floor(m/7)}w ago`;return`${k} **${l.handle}** (${l.touches}\xD7 \xB7 ${p})`}).join(" \xB7 ");o.push(`**Experts:** ${C}`)}else o.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const i=n.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),t=[];if(i)try{const C=await Ze(_,["cachly:lesson:best:*"],i,4);for(const l of C){const c=Re(l.content);if(!We(c))continue;const k=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",m=c.severity==="critical"?" \u{1F534}":c.severity==="major"?" \u{1F7E1}":"",p=c.author?` \xB7 \u{1F464} ${c.author}`:"",I=l.key.replace("cachly:lesson:best:","");t.push(` - ${k} \`${I}\`${m}${p} \u2014 ${(c.what_worked??"").slice(0,100)}`)}}catch{}if(t.length<2){const C=await De(_,"cachly:lesson:best:*",{max:1500});for(const l of C.slice(0,300)){const c=await _.get(l);if(!c)continue;const k=Re(c);if(!We(k)||!(k.file_paths??[]).includes(n))continue;const m=l.replace("cachly:lesson:best:","");if(t.some(E=>E.includes(`\`${m}\``)))continue;const p=k.outcome==="success"?"\u2705":k.outcome==="partial"?"\u26A0\uFE0F":"\u274C",I=k.severity==="critical"?" \u{1F534}":k.severity==="major"?" \u{1F7E1}":"",A=k.author?` \xB7 \u{1F464} ${k.author}`:"";t.push(` - ${p} \`${m}\`${I}${A} \u2014 ${(k.what_worked??"").slice(0,100)}`)}}t.length>0?(o.push("**Related lessons:**"),o.push(...t.slice(0,5))):o.push("**Related lessons:** _None yet_"),o.push("")}return o.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),o.join(`
|
|
62
|
+
`)}case"team_expertise_map":{const{instance_id:f,top_n:e=20}=D,u=await P(f),_=await De(u,"cachly:ckg:node:person:*",{max:2e3});if(_.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(`
|
|
63
|
+
`);const o=[];for(const a of _){const r=await u.get(a);if(!r)continue;const S=z(r,null);if(!S||S.type!=="person")continue;const i=await u.smembers(`cachly:ckg:idx:from:${S.id}`),t=new Map;let C=0;for(const l of i){const c=await u.get(l);if(!c)continue;const k=z(c,null);if(!k||k.edgeType!=="authored")continue;C++;const m=k.to.split(":")[0]??"unknown";t.set(m,(t.get(m)??0)+1)}o.push({handle:S.handle,lessonCount:C,domains:t,lastActive:S.last_active})}o.sort((a,r)=>r.lessonCount-a.lessonCount);const n=o.slice(0,e),N=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${n.length}** contributor${n.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[a,r]of n.entries()){const S=a===0?"\u{1F947}":a===1?"\u{1F948}":a===2?"\u{1F949}":`${a+1}`,i=Math.floor((Date.now()-new Date(r.lastActive).getTime())/864e5),t=i<1?"today":i<7?`${i}d ago`:i<30?`${Math.floor(i/7)}w ago`:`${Math.floor(i/30)}mo ago`,C=[...r.domains.entries()].sort((l,c)=>c[1]-l[1]).slice(0,3).map(([l,c])=>`${l}(${c})`).join(", ")||"\u2014";N.push(`| ${S} | **${r.handle}** | ${r.lessonCount} | ${C} | ${t} |`)}return N.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),N.join(`
|
|
64
|
+
`)}case"skill_gaps":{const{instance_id:f,min_failures:e=1}=D,u=await P(f),_=await De(u,"cachly:lesson:best:*",{max:3e3}),o=new Map;let n=0,N=0;for(const S of _){const i=await u.get(S);if(!i)continue;const t=Re(i);if(t===null)continue;const C=(t.topic??"").split(":")[0]??"unknown",l=o.get(C)??{successes:0,failures:0,attributed:0,topics:[]};t.outcome==="success"||t.outcome==="partial"?l.successes++:l.failures++,t.author&&(l.attributed++,n++),t.visibility==="private"&&N++,l.topics.push(t.topic??""),o.set(C,l)}const a=[];for(const[S,i]of o)i.failures>=e&&i.successes===0&&a.push({domain:S,type:"unresolved failures",severity:i.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${i.failures} failure${i.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),i.successes+i.failures>=3&&i.attributed===0&&a.push({domain:S,type:"no attribution",severity:"\u{1F535} info",detail:`${i.successes+i.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const r=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${_.length}** lessons scanned \xB7 **${n}** attributed \xB7 **${a.length}** gap${a.length!==1?"s":""} found`,N>0?`_(${N} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(a.length===0)r.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const S=[...a.filter(i=>i.severity.includes("critical")),...a.filter(i=>i.severity.includes("warn")),...a.filter(i=>i.severity.includes("info"))];for(const i of S.slice(0,15))r.push(`${i.severity} **\`${i.domain}\`** \u2014 ${i.type}`),r.push(` ${i.detail}`),r.push("");a.length>15&&r.push(`_\u2026and ${a.length-15} more gaps. Fix critical ones first._`)}return r.push("---",`_Fix gaps with \`learn_from_attempts(topic="${a[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),r.join(`
|
|
65
|
+
`)}case"brain_coverage":{const{instance_id:f,repo_path:e="."}=D,u=await P(f),[_,o,n]=await Promise.all([De(u,"cachly:lesson:best:*",{max:5e3}),De(u,"cachly:ckg:node:person:*",{max:2e3}),De(u,"cachly:ckg:node:file:*",{max:5e3})]);let N=0,a="n/a";try{const m=et(e);if(!m)throw new Error("repo_path ist kein Ordner");N=Pe(m,["ls-files"],{timeoutMs:3e4}).trim().split(`
|
|
66
|
+
`).filter(Boolean).length,a=String(N)}catch{}let r=0,S=0,i=0;const t=new Set;for(const m of _){const p=await u.get(m);if(!p)continue;const I=z(p,{});I.outcome==="success"||I.outcome==="partial"?r++:S++,I.author&&i++,t.add((I.topic??"").split(":")[0]??"unknown")}const C=N>0?`${Math.round(n.length/N*100)}% (${n.length}/${N} files)`:`${n.length} files tracked`,l=_.length>0?Math.round(i/_.length*100):0,c=Math.round(Math.min(1,_.length/50)*25+Math.min(1,r/Math.max(1,_.length))*25+Math.min(1,l/100)*25+Math.min(1,o.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${c>=80?"\u{1F7E2}":c>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${c}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${_.length}** (${r} success \xB7 ${S} failure) |`,`| Problem domains | **${t.size}** |`,`| Attribution | **${i}/${_.length}** (${l}%) |`,`| Contributors | **${o.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,_.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,r/Math.max(1,_.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,l/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,o.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(`
|
|
67
|
+
`)}case"brain_metrics":{const{instance_id:f}=D,e=await P(f),[u,_,o,n,N,a]=await Promise.all([e.get(`cachly:stats:born_at:${f}`).catch(()=>null),e.get(`cachly:stats:first_recall_at:${f}`).catch(()=>null),e.get(`cachly:stats:recalls_total:${f}`).catch(()=>null),e.get(`cachly:stats:cross_author_recalls:${f}`).catch(()=>null),e.get(`cachly:stats:time_saved_mins:${f}`).catch(()=>null),e.smembers(`cachly:stats:reuse_pairs:${f}`).catch(()=>[])]);let r={};try{r=await e.hgetall(ns(f))??{}}catch{r={}}let S={};try{S=await e.hgetall(Pt(f))??{}}catch{S={}}const i={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const d=await e.lrange(Ot(f),0,499),H=new Map;for(const oe of d){const V=z(oe,{ts:"",themen:[]});if(!(!V.ts||!Array.isArray(V.themen)))for(const X of V.themen){if(i.lieferungen++,!H.has(X)){const te=await e.get(`cachly:lesson:best:${X}`).catch(()=>null);H.set(X,te?z(te,{}):null)}const J=cn(V.ts,H.get(X)??null);if(J.length===0){i.ohneEreignis++;continue}for(const te of J)i[te]++}}}catch{}let t=0,C=0;try{const d=await e.lrange(`cachly:wirkung:${f}`,0,-1);for(const H of d){const oe=z(H,{});C++,oe.geholfen===!0&&t++}}catch{}let l={};try{l=await e.hgetall(Gn(f))??{}}catch{l={}}const c=Kn(l,10);let k={token:0,abrufe:0,treffer:0};try{const d=await e.get(Jn(f)),H=await e.hgetall(qn(f))??{};k={token:d??0,abrufe:H.abrufe??0,treffer:H.treffer??0}}catch{}const m=Vn(k);let p;if(u&&_){const d=new Date(_).getTime()-new Date(u).getTime(),H=Math.max(0,Math.round(d/6e4)),oe=H<1?"<1 min":H<60?`${H} min`:`${(H/60).toFixed(1)} h`,V=d<=2*6e4?"\u{1F7E2} under 2 min target":d<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";p=`**${oe}** from first lesson \u2192 first proven recall \xB7 ${V}`}else u&&!_?p="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":p="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const I=["\u26AA **Nicht gemessen** \u2014 diese Zahl erhebt der Server nicht selbst."," Selbst messen: `npm run bench` in `sdk/mcp`."," Achtung, der Pruefstand hat 17 Lektionen und 13 Fragen \u2014 ein Beispielsatz, kein Bestand."," Auf 498 ECHTEN Lektionen gemessen am 19.08.2026: Precision@1 **30 %** (vorher 15 %)."].join(`
|
|
68
|
+
`),A=Number(o??0),E=Number(n??0),s=A>0?Math.round(E/A*100):0,ie=s>=30?"\u{1F7E2} above 30 % target":A===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",ue=Math.round(Number(N??0)),ge=ue<60?`${ue} min`:`${(ue/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",p,"","### 2. Recall-lift _(the moat proof)_",I,"_Reproduce: `npm run bench` \xB7 CI-defended in `rerank.test.ts` \xB7 details in BENCH.md_","","### 3. Team-knowledge-reuse _(the value only a shared brain delivers)_",`**${s}%** of proven recalls used a teammate's lesson (${E}/${A}) \xB7 ${ie}`,a.length>0?`**${a.length}** distinct reuse relationship${a.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",Hn(m),"",m.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ge} 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 ${ge} \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 d=Number(r.beantwortet??0),H=Number(r.knapp??0),oe=Number(r.schweigen??0),V=d+H+oe;if(V===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const X=J=>`${Math.round(100*J/V)} %`;return`**${V}** Suchen: ${X(d)} beantwortet \xB7 ${X(H)} als knapper Sieg markiert \xB7 ${X(oe)} 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 d=X=>Number(S[X]??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)"]],oe=H.reduce((X,[J])=>X+d(J),0);if(oe===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const V=H.filter(([X])=>X!=="ohne-vorwissen").sort((X,J)=>d(J[0])-d(X[0]))[0];return`**${oe}** klassifizierte Fehlschlaege: `+H.map(([X,J])=>`${d(X)} ${J}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${V[1]}** (${d(V[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)_",i.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${i.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${i.widersprochen} widersprochen \xB7 ${i.korrigiert} korrigiert \xB7 ${i.veraltet} veraltet \xB7 ${i.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 d=Number(i.widersprochen)+Number(i.veraltet);if(C===0&&d===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const H=t-d;return`**${H>=0?"+":""}${H}** = ${t} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${d} Schadenslieferungen (${i.widersprochen} spaeter widerlegt + ${i.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",Fn(c,to.length),...c.spitze.length>0?c.spitze.map((d,H)=>` ${String(H+1).padStart(2)}. \`${d.name}\` \u2014 ${d.aufrufe}\xD7 (${Math.round(d.anteil*100)} %)`):[]].filter(Boolean).join(`
|
|
69
|
+
`)}case"brain_service_map":{const{instance_id:f,service:e}=D;if(!e||typeof e!="string"||!e.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const u=await P(f),_=`service:${pe(e.trim())}`,o=await u.get(`cachly:ckg:node:${_}`).catch(()=>null),n=o?z(o,null):null,N=await u.smembers(`cachly:ckg:idx:to:${_}`).catch(()=>[]),a=[],r=[],S=[];for(const p of N){const I=await u.get(p).catch(()=>null);if(!I)continue;const A=z(I,null);if(A)if(A.edgeType==="operates"){const E=await u.get(`cachly:ckg:node:${A.from}`).catch(()=>null),s=E?z(E,null):null;s?.handle&&a.push({handle:s.handle,trials:A.trials})}else if(A.edgeType==="runs_in"){const E=await u.get(`cachly:ckg:node:${A.from}`).catch(()=>null),s=E?z(E,null):null;s?.path&&r.push({path:s.path,trials:A.trials})}else A.edgeType==="affects"&&S.push({id:A.from,confidence:A.confidence})}a.sort((p,I)=>I.trials-p.trials),r.sort((p,I)=>I.trials-p.trials),S.sort((p,I)=>I.confidence-p.confidence);const i=[],t=await De(u,"cachly:lesson:best:*",{max:1500}),C=e.trim().toLowerCase();for(const p of t.slice(0,400)){const I=await u.get(p).catch(()=>null);if(!I)continue;const A=Re(I);We(A)&&(A.service??"").toLowerCase()===C&&i.push({...A,topic:p.replace("cachly:lesson:best:","")})}if(!n&&i.length===0&&a.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${e}\``,"","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="${e}", author="you", file_paths=[...])\``].join(`
|
|
70
|
+
`);const l=n?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",c=[`## ${n?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${e}\``,"",n?`_${l} \xB7 ${n.count} lesson${n.count!==1?"s":""} referenced \xB7 domain: ${n.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(a.length>0){const p=a.slice(0,5).map((I,A)=>`${A===0?"\u{1F947}":A===1?"\u{1F948}":A===2?"\u{1F949}":`${A+1}.`} **${I.handle}** (${I.trials}\xD7)`).join(" \xB7 ");c.push(`**Operators:** ${p}`,"")}else c.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const k=i.filter(p=>p.outcome==="failure"),m=i.filter(p=>p.outcome!=="failure");if(k.length>0){c.push(`**\u26A0\uFE0F Known failures (${k.length}):**`);for(const p of k.slice(0,6)){const I=p.severity==="critical"?" \u{1F534}":p.severity==="major"?" \u{1F7E1}":"",A=p.author?` \xB7 \u{1F464} ${p.author}`:"";c.push(` - \u274C \`${p.topic}\`${I}${A} \u2014 ${(p.what_worked??"").slice(0,100)}`)}c.push("")}if(m.length>0){c.push(`**\u2705 Proven fixes (${m.length}):**`);for(const p of m.slice(0,6)){const I=p.outcome==="partial"?"\u26A0\uFE0F":"\u2705",A=p.author?` \xB7 \u{1F464} ${p.author}`:"";c.push(` - ${I} \`${p.topic}\`${A} \u2014 ${(p.what_worked??"").slice(0,100)}`)}c.push("")}return r.length>0&&c.push(`**Files in this service:** ${r.slice(0,8).map(p=>`\`${p.path}\``).join(", ")}`,""),c.push("---",`_Tag lessons with \`service="${e}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),c.join(`
|
|
71
|
+
`)}case"brain_collab_pairs":{const{instance_id:f,min_weight:e=1}=D,u=await P(f),_=typeof e=="number"&&e>=1?Math.floor(e):1,o=await De(u,"cachly:ckg:node:person:*",{max:500}),n=new Map;for(const t of o){const C=await u.get(t);if(!C)continue;const l=z(C,null);!l||l.type!=="person"||n.set(l.id,{id:l.id,handle:l.handle,domain:l.domain,count:l.count})}if(n.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
|
|
72
|
+
`);const N=new Map;for(const[t,C]of n){const l=await u.smembers(`cachly:ckg:idx:from:${t}`);for(const c of l){const k=await u.get(c);if(!k)continue;const m=z(k,null);if(!m||m.edgeType!=="collaborates")continue;const p=n.get(m.to);if(!p)continue;const[I,A]=t<m.to?[t,m.to]:[m.to,t],E=`${I}||${A}`,s=N.get(E);if(s)s.trials+=m.trials;else{const[ie,ue]=t<m.to?[C,p]:[p,C];N.set(E,{a:ie,b:ue,trials:m.trials,confidence:m.confidence})}}}const a=[...N.values()].filter(t=>t.trials>=_).sort((t,C)=>C.trials-t.trials),r=new Set;for(const t of a)r.add(t.a.id),r.add(t.b.id);const S=[...n.values()].filter(t=>!r.has(t.id)),i=["## \u{1F91D} Team Collaboration Graph",""];if(a.length===0)i.push(`No collaboration pairs yet (min weight: ${_}).`,"","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{i.push(`**${a.length} collaboration pair${a.length!==1?"s":""}** across ${r.size} contributor${r.size!==1?"s":""}:`,"");for(const t of a.slice(0,20)){const C=(t.confidence*100).toFixed(0),l=[t.a.domain,t.b.domain].filter((c,k,m)=>c&&m.indexOf(c)===k).map(c=>`\`${c}\``).join(", ");i.push(`### @${t.a.handle} \u2194 @${t.b.handle}`,`- **${t.trials} collaboration event${t.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${l||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${t.a.handle}** und **@${t.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}a.length>20&&i.push(`_...and ${a.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return S.length>0&&i.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${S.length} contributor${S.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...S.slice(0,10).map(t=>`- **@${t.handle}** \u2014 ${t.count} lesson${t.count!==1?"s":""} \xB7 domain: \`${t.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),i.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),i.join(`
|
|
73
|
+
`)}case"brain_portability":{const{instance_id:f}=D,e=[{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:f}}}},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:f}}}},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:f}}}},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:f}}}},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:f}}}},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:f}}}},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:f}}]},null,2)}],u=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${f}\``,"","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 (${e.length} supported)`,""];for(const _ of e)u.push(`#### ${_.icon} ${_.name}`,`Config: \`${_.configPath}\``,"","```json",_.configBlock,"```","");return u.push("---","","### What travels with you","","| Data | Model-neutral? |","|------|---------------|","| Lessons (learn_from_attempts) | \u2705 Full access in all clients |","| Memory Crystals (memory_crystalize) | \u2705 Included in every session_start |","| Causal Knowledge Graph (brain_predict) | \u2705 Same graph, same predictions |","| Team lessons (team_learn, team_confirm) | \u2705 Team is per-Brain, not per-model |","| Domain Brain Marketplace installs | \u2705 Installed once, available everywhere |","| Session handoffs (session_handoff) | \u2705 Cross-client continuity |","","---","","### One-command setup for any new client","","```bash","npx @cachly-dev/mcp-server@latest autopilot","```","",`Autopilot detects all installed editors and writes the config for each \u2014 with your \`${f}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),u.join(`
|
|
74
|
+
`)}case"brain_changelog":{const{instance_id:f,days:e=7,max_lessons:u=30,include_failures:_=!0}=D,o=await P(f),n=Date.now()-Number(e)*864e5,N=await De(o,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),a=[];for(const c of N){const k=await o.get(c).catch(()=>null);if(!k)continue;const m=z(k,{});if((m.ts?new Date(m.ts).getTime():0)<n||!_&&m.outcome==="failure")continue;const I=c.replace("cachly:lesson:best:","");a.push({...m,topic:I})}a.sort((c,k)=>{const m=c.ts?new Date(c.ts).getTime():0;return(k.ts?new Date(k.ts).getTime():0)-m});const r=a.slice(0,Number(u));if(r.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${e} day${Number(e)!==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(`
|
|
75
|
+
`);const S=new Map;for(const c of r){const k=c.topic.includes(":")?c.topic.split(":")[0]:"general",m=S.get(k)??[];m.push(c),S.set(k,m)}const i=c=>c==="critical"?"\u{1F6A8}":c==="major"?"\u26A0\uFE0F":c==="minor"?"\u{1F4A1}":"\u2728",t=c=>c==="failure"?"\u274C":c==="partial"?"\u{1F536}":"\u2705",l=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${e} day${Number(e)!==1?"s":""})`,"",`_${r.length} lesson${r.length!==1?"s":""} learned across ${S.size} topic area${S.size!==1?"s":""}_`,""];for(const[c,k]of Array.from(S.entries()).sort((m,p)=>p[1].length-m[1].length)){l.push(`### ${c}`),l.push("");for(const m of k){const p=m.outcome==="failure"?t(m.outcome):i(m.severity),I=m.outcome==="failure"?m.what_failed:m.what_worked,A=[];m.author&&A.push(`by **${m.author}**`),m.recall_count&&A.push(`${m.recall_count} recall${m.recall_count!==1?"s":""}`),m.confidence!==void 0&&A.push(`${Math.round(m.confidence*100)}% confidence`),l.push(`- ${p} **${m.topic}**${I?` \u2014 ${I}`:""}`),A.length&&l.push(` _${A.join(" \xB7 ")}_`)}l.push("")}return l.push("---",`_Generated from Brain \`${f}\` \xB7 Share this in your standup or Slack_`),l.join(`
|
|
76
|
+
`)}case"brain_set_pref":{const{instance_id:f,key:e,value:u}=D;if(!e||!e.trim())throw new Error("key is required");const _=Oe({value:String(u)}),o=_.felder.value,n=await P(f),N=`cachly:prefs:${e.trim()}:${f}`;return await n.set(N,o),[`\u2705 Preference \`${e}\` set to \`${o}\` for this Brain instance.`,...He(_,"wert")].join(`
|
|
77
|
+
`)}case"brain_get_pref":{const{instance_id:f,key:e}=D,u=await P(f);if(e&&e.trim()){const N=await u.get(`cachly:prefs:${e.trim()}:${f}`).catch(()=>null);return N===null?`\u2139\uFE0F Preference \`${e}\` is not set (using default).`:`\u{1F527} Preference \`${e}\` = \`${N}\``}const _=await De(u,`cachly:prefs:*:${f}`,{max:200,timeoutMs:2e3});if(_.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const o=await u.mget(..._),n=["\u{1F527} **Brain preferences:**",""];for(let N=0;N<_.length;N++){const a=_[N].replace("cachly:prefs:","").replace(`:${f}`,"");n.push(`- \`${a}\` = \`${o[N]??"(null)"}\``)}return n.join(`
|
|
78
|
+
`)}default:return null}}async function bo(F,D){try{if(!Le()||Te!=="cachly"&&Te!=="ollama")return 0;let P=0;for(const ae of $e.themen()){if(P>=D)break;if(Qe.hat(ae)||await F.exists(`${Fe}${ae}`))continue;const f=await F.get(`cachly:lesson:best:${ae}`);if(!f)continue;const e=z(f,{});try{const u=await xe(Ge(e),{geduld:"lang",modell:Ve});u?.length&&(await F.set(`${Fe}${ae}`,ze(u)),P++)}catch{}}return P}catch{return 0}}async function cs(F,D,P){try{if(!Le())return;const ae=await F.srandmember(Ke,P),f=Array.isArray(ae)?ae:ae?[ae]:[];for(const e of f){if(e===D)continue;const u=await F.get(`cachly:lesson:best:${e}`);if(!u){await F.srem(Ke,e);continue}const _=z(u,{});try{const o=await xe(Ge(_),{geduld:"lang"});if(o?.length)await F.set(`${Rt}${e}`,ze(o)),await F.srem(Ke,e);else continue;if(Te==="cachly"||Te==="ollama")try{const n=await xe(Ge(_),{geduld:"lang",modell:Ve});n?.length&&(await F.set(`${Fe}${e}`,ze(n)),await F.srem(Xe,e))}catch{}}catch{}}await ls(F,gt,dt,D,P,e=>xe(Lt(e),{geduld:"lang"})),(Te==="cachly"||Te==="ollama")&&await ls(F,Xe,Fe,D,P,(e,u)=>xe(Ge(u),{geduld:"lang",modell:Ve}))}catch{}}async function ls(F,D,P,ae,f,e){const u=await F.srandmember(D,f),_=Array.isArray(u)?u:u?[u]:[];for(const o of _){if(o===ae)continue;const n=await F.get(`cachly:lesson:best:${o}`);if(!n){await F.srem(D,o);continue}if(await F.exists(`${P}${o}`)){await F.srem(D,o);continue}try{const N=await e(o,z(n,{}));N?.length&&(await F.set(`${P}${o}`,ze(N)),await F.srem(D,o))}catch{}}}export{ba as BRAIN_TOOL_NAMES,Nt as RECALL_ROH_ZEICHEN,Tt as RECALL_VOLLTEXT_ZEICHEN,$a as handleBrainTool,ct as recallVorschau};
|