@cachly-dev/mcp-server 0.10.176 → 0.10.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,76 +1,76 @@
1
- import{execSync as nt}from"node:child_process";import{createRequire as ot}from"node:module";import{calculateConfidence as Pe,confidenceBadge as Bt,STRUCTURED_TEMPLATES as zt,CONFIDENCE_WARN_VALUE as at,CONFIDENCE_STALE_VALUE as Ot,CONFIDENCE_WARN_DAYS as Pt}from"../confidence.js";import{kurzfassenHinweis as jt}from"../antwort-hinweis.js";import{pruefeMeldung as Wt,wendeAn as Ft}from"../pruefung-melden.js";import{ckgSlug as ye,extractProblemConcept as Je,ckgUpsertNode as Ne,ckgUpdateEdge as be,ckgUpsertPersonNode as Gt,ckgUpsertFileNode as it,ckgRecordCollaboration as Kt,ckgUpsertServiceNode as Ht}from"../ckg.js";import{safeJsonParse as B,scanKeys as Ce,leseOderNull as Te,darfHeraus as Ee}from"../utils.js";import{ersparteMinuten as rt,istStarterLektion as je,zaehltAlsErsparnis as ct}from"../wertbeitrag.js";import{lessonPreviewLines as De,trimTo as Jt}from"../lesson-preview.js";import{normalisiereZeit as qe,zaehleZeitangaben as Ue}from"../zeit-normalisieren.js";import{abstentionSatz as qt,alterssatzFuerBelegte as Ut,beurteileTreffer as Vt,istBelegt as Yt}from"../abstention.js";import{meldeEinmal as Ve,meldeUndVermerke as We,fehlerText as Ye,OHNE_VEKTOREN as Zt,OHNE_DIENST as Xt,OHNE_FRAGEVEKTOR as Qt,SINNPFAD_ABBRUCH as es,OHNE_SCHREIBVEKTOR as Ze}from"../aussetzer.js";import{versuchStart as ts,neueKennung as ss,wendeZuteilungAn as ns,schliesseVersuchAb as os}from"../versuch.js";function lt(ae,U,Y){if(ae.includes("lesson:best:")){const y=B(U,{});if(y&&typeof y=="object"&&(y.what_worked||y.what_failed||y.commands?.length))return De(y,{maxChars:Y,indent:" "})}const de=Jt(U,Y);return de?[de]:[]}import{getRole as Xe,ROLE_BADGE as as,getScopes as ut,lessonVisibleToScope as ht,reviewModeEnabled as is,storeLessonProposal as rs}from"./team.js";import{keywordSearch as Fe,treffeUeberDateipfad as cs,wortindexEntwerten as dt,tokenize as Qe,splitMultiQuery as ls,levenshtein as us,indexVocab as ft}from"../search.js";import{rerankByQuality as hs,qualityMultiplier as ds,extractLessonQuality as fs}from"../rerank.js";import{computeEmbedding as Se,hasEmbedProvider as Ae,EMBED_PROVIDER as xe}from"../embeddings.js";import{leserAktiv as ps,leserPunkte as ms,mischeMitLeser as gs}from"../leser.js";import{repariereFelder as ws}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as pt,NAME_VEKTOR_PRAEFIX as mt,ZWEIT_VEKTOR_PRAEFIX as Le,packe as Me,textFuerVektor as Be,textFuerNamensVektor as ys,Vektorbestand as et}from"../bedeutung.js";import{schreibeEingaenge as _s,Eingangsbestand as bs}from"../eingaenge.js";import{ordneNachHausordnung as $s,rangWerte as vs}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as ks}from"../seltenheitsbestand.js";import{spurLegen as Ss}from"../spuren.js";import{schlageErsetzungVor as Cs}from"../ersetzung-vorschlag.js";const Ie="cachly:vek:nachtrag",xs=365;import{etikettenFuer as Ts,lieferJournalSchluessel as gt,JOURNAL_DECKEL as Ns}from"../etiketten.js";import{klassifiziereFehlschlag as Es,suchProtokollSchluessel as wt,trichterSchluessel as yt,SUCH_DECKEL as As}from"../recall-trichter.js";import{leiteEntscheidungAb as Ms,entscheidungsZeile as _t}from"../entscheidung-ableiten.js";import{bewerteTopf as Is,spreizeImTopf as bt,reichereAn as Rs,inhaltsWoerter as $t,grobStamm as Ds,GEWICHTE as Ls,knapperSiegSatz as Bs}from"../rangfolge.js";import{pruefeWirkung as zs,werteAus as Os,lehrwert as Ps,leiteAb as js}from"../wirkungsspur.js";import{merkeSuchlauf as vt}from"../suchstatistik.js";import{schreibeTopfNotiz as Ws,topfProtokollAktiv as Fs}from"../topf-protokoll.js";import{SINN_TOPF as Gs,EINGANG_SCHWELLE as Ks,EINGANG_SORTIER_GEWICHT as Hs,ZWEIT_MODELL as Ge,ZWEIT_GEWICHT as Js,ZWEIT_MINDESTDECKUNG as kt,NAHDUPLIKAT_SCHWELLE as qs,LESER_TIEFE as St}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Ct,quelleZeile as Us}from"../herkunft.js";import{merkeRecall as Vs,sitzungsKosten as Ys,vergissSitzungsKosten as Zs,kostenZeilen as Xs}from"../sitzungs-kosten.js";const $e=new et,tt=new et(6e4,mt),Ke=new et(6e4,Le),st=new bs,ze=new ks,xt=Gs,Qs=Ks,en=Hs;import{upgradeNudge as tn}from"../upgrade-nudge.js";import{recallTiefe as Tt,TIEFE_VOLL as sn,TIEFE_VOLL_MEHRTHEMIG as nn}from"../recall-tiefe.js";import{nutzungInWorten as on,nutzungsSchluessel as an,verdichte as rn}from"../werkzeug-nutzung.js";import{inWorten as cn,lieferBild as ln,lieferSchluessel as un,trefferSchluessel as hn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as dn,autorHinweis as fn,coautorAus as pn,echterGitLeser as mn,ermittleAutor as gn,mitCoautor as wn,nurMensch as Nt}from"../autor.js";import{TOOLS as yn}from"../tools.js";import{vorspannHinweis as _n}from"../vorspann.js";import{autorAbzeichen as bn,fremdanteil as $n}from"../autor-abzeichen.js";import{cachlyUrl as vn}from"../cachly-url.js";import{belegFuer as kn}from"../schreibbeleg.js";import{schwaerzeFelder as Sn}from"../geheimnis-filter.js";const He=(()=>{try{const ae=ot(import.meta.url);for(const U of["../../../package.json","../../package.json"])try{const Y=ae(U);if(Y.name==="@cachly-dev/mcp-server"&&Y.version)return Y.version}catch{}}catch{}return"0.10.100"})(),Cn=()=>{try{return ot(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},xn={"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${He}:**`," \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"]},xo=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"]),Tn=vn("/billing","upgrade"),Et=new Map,At=new Set,Nn=1680*60*60;function En(ae=new Date){return`cachly:quota:recalls:${ae.toISOString().slice(0,7)}`}async function Mt(ae){try{const U=En();await ae.incr(U)===1&&await ae.expire(U,Nn)}catch{}}function It(ae){return`cachly:stats:drei-ausgaenge:${ae}`}async function Rt(ae,U,Y){try{await ae.hincrby(It(U),Y,1)}catch{}}async function Dt(ae,U){const Y=Et.get(ae);if(Y&&Y.expiresAt>Date.now())return Y.gate;try{const de=await U(`/api/v1/instances/${ae}/memory`),y=de?.recall_limit??-1,n=de?.total_recall_count??0,t={reached:y>0&&n>=y,limit:y,used:n,goodwillMessage:de?.goodwill_message,notice:de?.notice};return Et.set(ae,{gate:t,expiresAt:Date.now()+6e4}),t}catch{return{reached:!1,limit:-1,used:0}}}const An={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function To(ae,U,Y,de){const y=await Mn(ae,U,Y,de),n=An[ae];if(n&&typeof y=="string")try{Vs(String(U.instance_id??""),String(U[n]??""),y.length)}catch{}return y}async function Mn(ae,U,Y,de){switch(ae){case"learn_from_attempts":{const y=Sn(U),{instance_id:n,topic:t,outcome:r,what_worked:m,what_failed:h="",context:S="",severity:i="major",file_paths:u=[],commands:A=[],tags:s=[],depends_on:w=[],author:C="",visibility:f="team",service:o="",service_kind:N="service",group:_="",grund:b="",ersetzt:I="",gilt_ab:E=""}=y.felder,{what_worked:e,what_failed:j="",context:ie=""}=ws({what_worked:m,what_failed:h,context:S}),k=await Y(n),ge=new Date,le=ge.toISOString(),F=E&&!Number.isNaN(Date.parse(String(E)))?new Date(String(E)):ge,O=qe(e,F),G=qe(j,F),se=qe(ie,F),R=Ue(e,F)+Ue(j,F)+Ue(ie,F),Z=gn({uebergeben:C,umgebung:process.env.CACHLY_AUTHOR,git:mn(process.env.CACHLY_WORKSPACE??process.cwd())});let fe="";try{fe=pn(await k.get(`cachly:prefs:${dn}:${n}`))}catch{}const re=wn(Z.autor,fe),a=fn(Z);if(f!=="private"&&await is(k,n))return rs(k,t,{topic:t,outcome:r,what_worked:O,what_failed:G,context:se,severity:i,file_paths:u,commands:A,tags:s,depends_on:w,...re?{author:re}:{},source:Ct(),...o?{service:o}:{},..._?{group:String(_).toLowerCase().trim()}:{},visibility:f,recall_count:0,ts:le,confidence:1,version:3});const g=t.split(":")[0],d=zt[g],c=[];if(d)for(const D of d.required)D==="commands"&&A.length===0&&c.push(`\u{1F4CB} ${d.hint}`);let l=!1,x=0,L,M=[];const T=await k.get(`cachly:lesson:best:${t}`),oe=String(b??"").trim();if(T&&!oe)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
- `);if(T)try{const D=JSON.parse(T);x=D.recall_count??0,L=D.last_recalled_at,M=D.audit_trail??[],M.push({ts:le,action:"updated",prev_outcome:D.outcome,grund:oe}),M.length>20&&(M=M.slice(-20)),l=!0;const W=[];if(D.outcome==="success"&&r==="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."):D.outcome==="failure"&&r==="success"&&W.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),W.length>0){M[M.length-1].action="contradiction-resolved";try{const ee=ye(t),H=ye(`resolution:${t}`);await be(k,ee,"contradicts",H,!1)}catch{}try{const ee=`cachly:contradictions:${t}`,H=D.outcome==="success"&&r==="failure"?"kept-success":"overwrote-failure";await k.rpush(ee,JSON.stringify({ts:le,prev_outcome:D.outcome,new_outcome:r,direction:H})),await k.ltrim(ee,-50,-1),await k.expire(ee,180*86400)}catch{}W.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else M=[{ts:le,action:"created"}];const Q=[];if(r==="failure"){const D=[],W=k.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((H,V)=>{W.on("data",te=>D.push(...te)),W.on("end",H),W.on("error",V)});const ee=t.split(/[:\-_]/).filter(H=>H.length>2);for(const H of D.slice(0,50)){const V=await k.get(H);if(V)try{const te=JSON.parse(V);if(te.outcome!=="success")continue;const he=(te.topic??"").split(/[:\-_]/).filter(ue=>ue.length>2);if(ee.filter(ue=>he.includes(ue)).length>=1&&te.topic!==t){Q.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${te.topic}\` (success, ${te.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${te.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${te.topic}", ..., severity="critical")\``);break}}catch{}}}for(const D of w){const W=`cachly:dep:${D}`,ee=await k.get(W),H=B(ee,[]);H.includes(t)||H.push(t),await k.set(W,JSON.stringify(H),"EX",90*86400)}const we={topic:t,outcome:r,what_worked:O,what_failed:G,context:se,severity:i,file_paths:u,commands:A,tags:s,depends_on:w,...re?{author:re}:{},source:Ct(),...o?{service:o}:{},..._?{group:String(_).toLowerCase().trim()}:{},visibility:f,recall_count:x,...L?{last_recalled_at:L}:{},...E&&!Number.isNaN(Date.parse(String(E)))?{gilt_ab:new Date(String(E)).toISOString()}:{},ts:le,verified_at:r==="success"||r==="partial"?le:void 0,confidence:1,audit_trail:M,version:3},ce=String(I??"").trim();let ke="",ve=null;ce===t&&ce?ke="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":ce&&(ve=await k.get(`cachly:lesson:best:${ce}`),ve?B(ve,{}).ersetzt===t?(ve=null,ke=`\u26A0\uFE0F \`${ce}\` ersetzt bereits \`${t}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${ce}\` entfernen und danach hier setzen.`):we.ersetzt=ce:ke=`\u26A0\uFE0F Die zu ersetzende Lektion \`${ce}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let p="";if(!ce)try{const D=te=>{const he=B(te.content,{});return{topic:he.topic??te.key.slice(19),what_worked:he.what_worked}},[W,ee]=await Promise.all([Fe(k,["cachly:lesson:best:*"],`${t} ${O}`.slice(0,300),5),cs(k,["cachly:lesson:best:*"],u??[])]),H=new Set,V=[...W,...ee].filter(te=>te.key.startsWith("cachly:lesson:best:")).filter(te=>!H.has(te.key)&&H.add(te.key)).map(D);p=Cs(t,O,V)??""}catch{}if(r==="failure")try{const W=(await k.lrange(wt(n),0,199)).map(V=>B(V,{ts:"",frage:"",geliefert:[]})).filter(V=>V.ts!==""),ee=(await Fe(k,["cachly:lesson:best:*"],`${t} ${G||O}`.slice(0,300),5)).filter(V=>V.key.startsWith("cachly:lesson:best:")).map(V=>{const te=B(V.content,{});return{topic:te.topic??V.key.slice(19),what_worked:te.what_worked}}),H=Es(t,String(G||""),W,ee);await k.hincrby(yt(n),H,1)}catch{}const $=Ms([O,G,S].filter(Boolean).join(" ").slice(0,2e3));$&&(we.entscheidung=$);const v=kn(t,le,O);we.beleg=v;const K=JSON.stringify(we);k.set(`cachly:stats:born_at:${n}`,le,"EX",365*86400,"NX").catch(()=>{});const q=`cachly:lessons:${t}`;await k.rpush(q,K),await k.ltrim(q,-100,-1),await k.expire(q,xs*86400);let z=!1;if(r==="success"||r==="partial"?(await k.set(`cachly:lesson:best:${t}`,K),z=!0):T||(await k.set(`cachly:lesson:best:${t}`,K),z=!0),ve&&z)try{const D=JSON.parse(ve);D.ersetzt_durch=t,D.gilt_bis=le,D.ersetzt_am=le,oe&&(D.ersetzt_grund=oe.slice(0,200)),await k.set(`cachly:lesson:best:${ce}`,JSON.stringify(D))}catch{}z&&dt(),z&&Ae()&&(await k.sadd(Ie,t).catch(()=>{}),(async()=>{const D=B(K,{});try{const W=await Se(Be(D),{geduld:"lang"});if(W?.length&&(await k.set(`${pt}${t}`,Me(W)),await k.srem(Ie,t).catch(()=>{})),xe==="cachly"||xe==="ollama")try{const ee=await Se(Be(D),{geduld:"lang",modell:Ge});ee?.length&&await k.set(`${Le}${t}`,Me(ee))}catch{}}catch(W){await k.sadd(Ie,t).catch(()=>{}),await We(k,Ze,`Volltext-Vektor nicht geschrieben (${xe}): ${Ye(W)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const W=await Se(ys(t),{geduld:"lang"});W?.length&&await k.set(`${mt}${t}`,Me(W))}catch(W){await We(k,Ze,`Namens-Vektor nicht geschrieben (${xe}): ${Ye(W)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await _s(k,t,D,W=>Se(W,{geduld:"lang"}))}catch(W){await We(k,Ze,`Eingaenge nicht geschrieben (${xe}): ${Ye(W)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await Lt(k,t,3)})());try{const D="cachly:session:decision-log",W=JSON.stringify({ts:le,topic:t,outcome:r,what_worked:O.slice(0,120)});await k.rpush(D,W),await k.ltrim(D,-50,-1)}catch{}let X=null;try{const D=ye(t),W=t.split(":")[0]??"unknown";await Ne(k,D,W,W);for(const H of s){const V=ye(`tag:${H}`);await Ne(k,V,"tag","tag"),await be(k,D,"co-occurs",V,r==="success",r==="partial")}for(const H of w){const V=ye(H);await be(k,D,"requires",V,!0)}if((W==="fix"||W==="debug")&&(r==="success"||r==="partial")){const H=G||se||"",V=H?Je(H):null;if(V){const te=ye(`problem:${V}`);await Ne(k,te,"problem","problem"),await be(k,D,"fixes",te,r==="success",r==="partial")}}if(r==="failure"&&(G||O)){const V=Je(G||O);if(V){const te=ye(`cause:${V}`);await Ne(k,te,"cause","cause"),await be(k,D,"causes",te,!1)}}if(r==="failure"){const H=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const V of H){const te=await k.get(V);if(!te)continue;const he=B(te,null);if(he&&he.edgeType==="fixes"&&he.confidence>.7&&he.trials>=3){X=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${he.confidence.toFixed(2)}, n=${he.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${D}")\` to review.`;const P=`cachly:ckg:conflict:${D}`;await k.set(P,JSON.stringify({topic:t,concept_id:D,detected_at:new Date().toISOString(),fix_confidence:he.confidence,fix_trials:he.trials,failure_outcome:r,reported_by:re||"unknown",what_failed:G||"",resolved:!1}),"EX",3600*24*90)}}}if(r==="success"&&(W==="fix"||W==="debug")){const H=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const V of H.slice(0,10)){const te=await k.get(V);if(!te)continue;const he=B(te,null);if(!he||he.edgeType!=="fixes")continue;const P=await k.smembers(`cachly:ckg:idx:from:${he.to}`);for(const ue of P.slice(0,5)){const _e=await k.get(ue);if(!_e)continue;const pe=B(_e,null);pe&&pe.edgeType==="co-occurs"&&(pe.successes=(pe.successes||0)+.1,pe.trials=(pe.trials||0)+.1,pe.confidence=(pe.successes+1)/(pe.trials+2),pe.last_updated=new Date().toISOString(),await k.set(ue,JSON.stringify(pe)))}}}if(Math.random()<.01){const H=Date.now()-7776e6,V=await k.smembers(`cachly:ckg:idx:from:${D}`);for(const te of V){const he=await k.get(te);if(!he)continue;const P=B(he,null);P&&P.trials<3&&P.last_updated&&new Date(P.last_updated).getTime()<H&&(P.confidence=P.confidence*.9,P.last_updated=new Date().toISOString(),await k.set(te,JSON.stringify(P)))}}}catch{}if(re){k.set(`cachly:agents:active:${re}`,JSON.stringify({author:re,last_topic:t,last_outcome:r,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const D=t.split(":")[0]??"unknown",W=await Gt(k,Nt(re),D),ee=ye(t);await be(k,W,"authored",ee,r==="success",r==="partial");for(const H of u.slice(0,8)){const V=await it(k,H);await be(k,W,"touched",V,!0),await Kt(k,V,W)}}catch{}}if(o&&typeof o=="string"&&o.trim())try{const D=t.split(":")[0]??"unknown",W=N==="system"?"system":"service",ee=await Ht(k,o.trim(),D,W),H=ye(t);if(await be(k,H,"affects",ee,r==="success",r==="partial"),re){const V=`person:${ye(Nt(re))}`;await be(k,V,"operates",ee,!0)}for(const V of u.slice(0,8)){const te=`file:${ye(V)}`;await be(k,te,"runs_in",ee,!0)}}catch{}if(re&&(r==="success"||r==="partial")){const D={topic:t,outcome:r,what_worked:O,what_failed:G??"",severity:i,author:re,file_paths:u,commands:A,tags:[...new Set([...s,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},W=`cachly:lessons:${t}`;k.rpush(W,JSON.stringify(D)).catch(()=>{})}return[`${r==="success"?"\u2705":r==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${l?"updated":"stored"}:** \`${t}\` (${r}) ${i==="critical"?"\u{1F534}":i==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${i} \xB7 Beleg: \`${v}\``,y.funde.length?`\u{1F512} **${y.funde.length} Geheimnis(se) geschwaerzt** vor dem Speichern (${y.funde.join("; ")}). Der Wert ist nicht im Brain \u2014 verweise kuenftig auf den Ort (z. B. Infisical-Pfad oder Variablenname).`:"",X??"","",`**What worked:** ${O}`,G?`**What failed:** ${G}`:"",se?`**Context:** ${se}`:"",u.length>0?`**Files:** ${u.map(D=>`\`${D}\``).join(", ")}`:"",A.length>0?`**Commands:** ${A.map(D=>`\`${D}\``).join(", ")}`:"",s.length>0?`**Tags:** ${s.map(D=>`#${D}`).join(" ")}`:"","",l?`\u267B\uFE0F Updated (recall count: ${x} \xB7 audit entries: ${M.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,re&&(r==="success"||r==="partial")?`\u{1F465} Auto-shared with team (by _${re}_${Z.quelle!=="uebergeben"?` \xB7 aus ${Z.quelle}`:""}) \u2014 visible in \`team_recall\``:"",a??"",w.length>0?`\u{1F517} Depends on: ${w.map(D=>`\`${D}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",p,ve&&z?oe?`\u21B7 Ersetzt \`${ce}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${ce}\` \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.`:ke,...c,...Q,R>0?`\u{1F5D3}\uFE0F ${R} relative Zeitangabe${R===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(ge.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",_n(O)??""].filter(D=>D!=="").join(`
3
- `)}case"lesson_verified":{const{instance_id:y}=U,n=await Y(y),t=new Date().toISOString(),r=Wt(U,t);if(!r.ok)return[`\u26A0\uFE0F ${r.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
4
- `);const m=r.eintrag,h=`cachly:lesson:best:${m.topic}`,S=await n.get(h);if(!S)return`\u{1F4ED} Keine Lektion \`${m.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const i=B(S,{});return await n.set(h,JSON.stringify(Ft(i,m))),dt(),m.haelt?[`\u2705 \`${m.topic}\` ist wieder frisch \u2014 geprueft am ${t.slice(0,10)}.`,m.geprueft_mit?` geprueft mit: \`${m.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht."].filter(Boolean).join(`
1
+ import{execSync as dt}from"node:child_process";import{createRequire as ft}from"node:module";import{calculateConfidence as Ke,confidenceBadge as Ht,STRUCTURED_TEMPLATES as Jt,CONFIDENCE_WARN_VALUE as pt,CONFIDENCE_STALE_VALUE as qt,CONFIDENCE_WARN_DAYS as Vt}from"../confidence.js";import{kurzfassenHinweis as Ut}from"../antwort-hinweis.js";import{pruefeMeldung as Yt,wendeAn as Zt}from"../pruefung-melden.js";import{ckgSlug as pe,extractProblemConcept as Ze,ckgUpsertNode as De,ckgUpdateEdge as we,ckgUpsertPersonNode as Xt,ckgUpsertFileNode as gt,ckgRecordCollaboration as Qt,ckgUpsertServiceNode as es}from"../ckg.js";import{safeJsonParse as B,scanKeys as Se,leseOderNull as Me,darfHeraus as Re}from"../utils.js";import{ersparteMinuten as mt,istStarterLektion as He,zaehltAlsErsparnis as wt}from"../wertbeitrag.js";import{lessonPreviewLines as Pe,trimTo as ts}from"../lesson-preview.js";import{normalisiereZeit as Xe,zaehleZeitangaben as Qe}from"../zeit-normalisieren.js";import{abstentionSatz as ss,alterssatzFuerBelegte as ns,beurteileTreffer as os,istBelegt as as}from"../abstention.js";import{meldeEinmal as et,meldeUndVermerke as Je,fehlerText as tt,OHNE_VEKTOREN as is,OHNE_DIENST as rs,OHNE_FRAGEVEKTOR as cs,SINNPFAD_ABBRUCH as ls,OHNE_SCHREIBVEKTOR as st}from"../aussetzer.js";import{versuchStart as us,neueKennung as hs,wendeZuteilungAn as ds,schliesseVersuchAb as fs}from"../versuch.js";function yt(ee,K,H){if(ee.includes("lesson:best:")){const w=B(K,{});if(w&&typeof w=="object"&&(w.what_worked||w.what_failed||w.commands?.length))return Pe(w,{maxChars:H,indent:" "})}const ue=ts(K,H);return ue?[ue]:[]}import{getRole as nt,ROLE_BADGE as ps,getScopes as _t,lessonVisibleToScope as bt,reviewModeEnabled as gs,storeLessonProposal as ms}from"./team.js";import{keywordSearch as qe,treffeUeberDateipfad as ws,wortindexEntwerten as $t,tokenize as ot,splitMultiQuery as ys,levenshtein as _s,indexVocab as vt,bestandHolen as bs}from"../search.js";import{neuesBrain as $s,leeresBrainAntwort as kt,lerntNochAusGit as St}from"../leeres-brain.js";import{rerankByQuality as vs,qualityMultiplier as ks,extractLessonQuality as Ss}from"../rerank.js";import{computeEmbedding as ke,hasEmbedProvider as Le,EMBED_PROVIDER as Te}from"../embeddings.js";import{leserAktiv as Cs,leserPunkte as xs,mischeMitLeser as Ts}from"../leser.js";import{repariereFelder as Ns}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Ct,NAME_VEKTOR_PRAEFIX as xt,ZWEIT_VEKTOR_PRAEFIX as je,packe as Be,textFuerVektor as We,textFuerNamensVektor as Es,Vektorbestand as at,VEKTOR_NACHTRAG as As}from"../bedeutung.js";import{schreibeEingaenge as Ms,Eingangsbestand as Is}from"../eingaenge.js";import{ordneNachHausordnung as Ds,rangWerte as Rs}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as Ls}from"../seltenheitsbestand.js";import{spurLegen as Bs}from"../spuren.js";import{schlageErsetzungVor as zs}from"../ersetzung-vorschlag.js";const ze=As,Os=365;import{etikettenFuer as Ps,lieferJournalSchluessel as Tt,JOURNAL_DECKEL as js}from"../etiketten.js";import{klassifiziereFehlschlag as Ws,suchProtokollSchluessel as it,trichterSchluessel as Nt,SUCH_DECKEL as Et}from"../recall-trichter.js";import{leiteEntscheidungAb as Fs,entscheidungsZeile as At}from"../entscheidung-ableiten.js";import{bewerteTopf as Gs,spreizeImTopf as Mt,reichereAn as Ks,inhaltsWoerter as It,grobStamm as Hs,GEWICHTE as Js,knapperSiegSatz as qs}from"../rangfolge.js";import{pruefeWirkung as Vs,werteAus as Us,lehrwert as Ys,leiteAb as Zs}from"../wirkungsspur.js";import{merkeSuchlauf as rt}from"../suchstatistik.js";import{schreibeTopfNotiz as Xs,topfProtokollAktiv as Qs}from"../topf-protokoll.js";import{SINN_TOPF as en,EINGANG_SCHWELLE as tn,EINGANG_SORTIER_GEWICHT as sn,ZWEIT_MODELL as Ve,ZWEIT_GEWICHT as nn,ZWEIT_MINDESTDECKUNG as Dt,NAHDUPLIKAT_SCHWELLE as on,LESER_TIEFE as Rt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Lt,quelleZeile as an}from"../herkunft.js";import{merkeRecall as rn,sitzungsKosten as cn,vergissSitzungsKosten as ln,kostenZeilen as un}from"../sitzungs-kosten.js";const ye=new at,ct=new at(6e4,xt),Ue=new at(6e4,je),lt=new Is,Fe=new Ls,Bt=en,hn=tn,dn=sn;import{upgradeNudge as fn}from"../upgrade-nudge.js";import{recallTiefe as zt,TIEFE_VOLL as pn,TIEFE_VOLL_MEHRTHEMIG as gn}from"../recall-tiefe.js";import{nutzungInWorten as mn,nutzungsSchluessel as wn,verdichte as yn}from"../werkzeug-nutzung.js";import{inWorten as _n,lieferBild as bn,lieferSchluessel as $n,trefferSchluessel as vn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as kn,autorHinweis as Sn,coautorAus as Cn,echterGitLeser as xn,ermittleAutor as Tn,mitCoautor as Nn,nurMensch as Ot}from"../autor.js";import{TOOLS as En}from"../tools.js";import{vorspannHinweis as An}from"../vorspann.js";import{autorAbzeichen as Mn,fremdanteil as In}from"../autor-abzeichen.js";import{cachlyUrl as Dn}from"../cachly-url.js";import{belegFuer as Rn}from"../schreibbeleg.js";import{schwaerzeFelder as Ln}from"../geheimnis-filter.js";import{zeitpunkt as _e}from"../zeitmessung.js";const Ye=(()=>{try{const ee=ft(import.meta.url);for(const K of["../../../package.json","../../package.json"])try{const H=ee(K);if(H.name==="@cachly-dev/mcp-server"&&H.version)return H.version}catch{}}catch{}return"0.10.100"})(),Bn=()=>{try{return ft(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},zn={"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${Ye}:**`," \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"]},Po=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"]),On=Dn("/billing","upgrade"),Pt=new Map,jt=new Set,Pn=1680*60*60;function jn(ee=new Date){return`cachly:quota:recalls:${ee.toISOString().slice(0,7)}`}async function ut(ee){try{const K=jn();await ee.incr(K)===1&&await ee.expire(K,Pn)}catch{}}function Wt(ee){return`cachly:stats:drei-ausgaenge:${ee}`}async function ht(ee,K,H){try{await ee.hincrby(Wt(K),H,1)}catch{}}function Ft(ee,K,H,ue){ut(ee),rt(ee,H,ue);const w={ts:new Date().toISOString(),frage:H.slice(0,200),geliefert:[]};(async()=>{const o=it(K);await ee.lpush(o,JSON.stringify(w)),await ee.ltrim(o,0,Et-1)})().catch(()=>{}),ht(ee,K,"schweigen")}async function Gt(ee,K){const H=Pt.get(ee);if(H&&H.expiresAt>Date.now())return H.gate;try{const ue=await K(`/api/v1/instances/${ee}/memory`),w=ue?.recall_limit??-1,o=ue?.total_recall_count??0,t={reached:w>0&&o>=w,limit:w,used:o,goodwillMessage:ue?.goodwill_message,notice:ue?.notice};return Pt.set(ee,{gate:t,expiresAt:Date.now()+6e4}),t}catch{return{reached:!1,limit:-1,used:0}}}const Wn={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function jo(ee,K,H,ue){const w=await Fn(ee,K,H,ue),o=Wn[ee];if(o&&typeof w=="string")try{rn(String(K.instance_id??""),String(K[o]??""),w.length)}catch{}return w}async function Fn(ee,K,H,ue){switch(ee){case"learn_from_attempts":{const w=Ln(K),{instance_id:o,topic:t,outcome:r,what_worked:m,what_failed:u="",context:C="",severity:$="major",file_paths:n=[],commands:D=[],tags:a=[],depends_on:b=[],author:x="",visibility:p="team",service:i="",service_kind:T="service",group:y="",grund:v="",ersetzt:A="",gilt_ab:M=""}=w.felder,{what_worked:e,what_failed:W="",context:ie=""}=Ns({what_worked:m,what_failed:u,context:C}),k=await H(o),he=new Date,oe=he.toISOString(),F=M&&!Number.isNaN(Date.parse(String(M)))?new Date(String(M)):he,O=Xe(e,F),Y=Xe(W,F),Q=Xe(ie,F),X=Qe(e,F)+Qe(W,F)+Qe(ie,F),ne=Tn({uebergeben:x,umgebung:process.env.CACHLY_AUTHOR,git:xn(process.env.CACHLY_WORKSPACE??process.cwd())});let ce="";try{ce=Cn(await k.get(`cachly:prefs:${kn}:${o}`))}catch{}const re=Nn(ne.autor,ce),s=Sn(ne);if(p!=="private"&&await gs(k,o))return ms(k,t,{topic:t,outcome:r,what_worked:O,what_failed:Y,context:Q,severity:$,file_paths:n,commands:D,tags:a,depends_on:b,...re?{author:re}:{},source:Lt(),...i?{service:i}:{},...y?{group:String(y).toLowerCase().trim()}:{},visibility:p,recall_count:0,ts:oe,confidence:1,version:3});const d=t.split(":")[0],f=Jt[d],c=[];if(f)for(const S of f.required)S==="commands"&&D.length===0&&c.push(`\u{1F4CB} ${f.hint}`);let l=!1,N=0,L,I=[];const j=await k.get(`cachly:lesson:best:${t}`),te=String(v??"").trim();if(j&&!te)return[`\u270B **Update abgewiesen:** \`${t}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
2
+ `);if(j)try{const S=JSON.parse(j);N=S.recall_count??0,L=S.last_recalled_at,I=S.audit_trail??[],I.push({ts:oe,action:"updated",prev_outcome:S.outcome,grund:te}),I.length>20&&(I=I.slice(-20)),l=!0;const E=[];if(S.outcome==="success"&&r==="failure"?E.push("\u26A0\uFE0F **Contradiction detected!** Existing lesson has outcome: `success`, but you're storing `failure`.",'The existing "success" lesson will be preserved. Only the audit trail is updated.',"If you meant to mark this as failed permanently, store a new lesson with a distinct topic slug."):S.outcome==="failure"&&r==="success"&&E.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),E.length>0){I[I.length-1].action="contradiction-resolved";try{const R=pe(t),P=pe(`resolution:${t}`);await we(k,R,"contradicts",P,!1)}catch{}try{const R=`cachly:contradictions:${t}`,P=S.outcome==="success"&&r==="failure"?"kept-success":"overwrote-failure";await k.rpush(R,JSON.stringify({ts:oe,prev_outcome:S.outcome,new_outcome:r,direction:P})),await k.ltrim(R,-50,-1),await k.expire(R,180*86400)}catch{}E.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else I=[{ts:oe,action:"created"}];const ae=[];if(r==="failure"){const S=[],E=k.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((P,J)=>{E.on("data",V=>S.push(...V)),E.on("end",P),E.on("error",J)});const R=t.split(/[:\-_]/).filter(P=>P.length>2);for(const P of S.slice(0,50)){const J=await k.get(P);if(J)try{const V=JSON.parse(J);if(V.outcome!=="success")continue;const se=(V.topic??"").split(/[:\-_]/).filter($e=>$e.length>2);if(R.filter($e=>se.includes($e)).length>=1&&V.topic!==t){ae.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${V.topic}\` (success, ${V.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${V.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${V.topic}", ..., severity="critical")\``);break}}catch{}}}for(const S of b){const E=`cachly:dep:${S}`,R=await k.get(E),P=B(R,[]);P.includes(t)||P.push(t),await k.set(E,JSON.stringify(P),"EX",90*86400)}const ge={topic:t,outcome:r,what_worked:O,what_failed:Y,context:Q,severity:$,file_paths:n,commands:D,tags:a,depends_on:b,...re?{author:re}:{},source:Lt(),...i?{service:i}:{},...y?{group:String(y).toLowerCase().trim()}:{},visibility:p,recall_count:N,...L?{last_recalled_at:L}:{},...M&&!Number.isNaN(Date.parse(String(M)))?{gilt_ab:new Date(String(M)).toISOString()}:{},ts:oe,verified_at:r==="success"||r==="partial"?oe:void 0,confidence:1,audit_trail:I,version:3},z=String(A??"").trim();let Ce="",de=null;z===t&&z?Ce="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":z&&(de=await k.get(`cachly:lesson:best:${z}`),de?B(de,{}).ersetzt===t?(de=null,Ce=`\u26A0\uFE0F \`${z}\` ersetzt bereits \`${t}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${z}\` entfernen und danach hier setzen.`):ge.ersetzt=z:Ce=`\u26A0\uFE0F Die zu ersetzende Lektion \`${z}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let xe="";if(!z)try{const S=V=>{const se=B(V.content,{});return{topic:se.topic??V.key.slice(19),what_worked:se.what_worked}},[E,R]=await Promise.all([qe(k,["cachly:lesson:best:*"],`${t} ${O}`.slice(0,300),5),ws(k,["cachly:lesson:best:*"],n??[])]),P=new Set,J=[...E,...R].filter(V=>V.key.startsWith("cachly:lesson:best:")).filter(V=>!P.has(V.key)&&P.add(V.key)).map(S);xe=zs(t,O,J)??""}catch{}if(r==="failure")try{const E=(await k.lrange(it(o),0,199)).map(J=>B(J,{ts:"",frage:"",geliefert:[]})).filter(J=>J.ts!==""),R=(await qe(k,["cachly:lesson:best:*"],`${t} ${Y||O}`.slice(0,300),5)).filter(J=>J.key.startsWith("cachly:lesson:best:")).map(J=>{const V=B(J.content,{});return{topic:V.topic??J.key.slice(19),what_worked:V.what_worked}}),P=Ws(t,String(Y||""),E,R);await k.hincrby(Nt(o),P,1)}catch{}const Ne=Fs([O,Y,C].filter(Boolean).join(" ").slice(0,2e3));Ne&&(ge.entscheidung=Ne);const Ae=Rn(t,oe,O);ge.beleg=Ae;const Ee=JSON.stringify(ge);k.set(`cachly:stats:born_at:${o}`,oe,"EX",365*86400,"NX").catch(()=>{});const h=`cachly:lessons:${t}`;await k.rpush(h,Ee),await k.ltrim(h,-100,-1),await k.expire(h,Os*86400);let g=!1;if(r==="success"||r==="partial"?(await k.set(`cachly:lesson:best:${t}`,Ee),g=!0):j||(await k.set(`cachly:lesson:best:${t}`,Ee),g=!0),de&&g)try{const S=JSON.parse(de);S.ersetzt_durch=t,S.gilt_bis=oe,S.ersetzt_am=oe,te&&(S.ersetzt_grund=te.slice(0,200)),await k.set(`cachly:lesson:best:${z}`,JSON.stringify(S))}catch{}g&&$t(),g&&Le()&&(await k.sadd(ze,t).catch(()=>{}),(async()=>{const S=B(Ee,{});try{const E=await ke(We(S),{geduld:"lang"});if(E?.length&&(await k.set(`${Ct}${t}`,Be(E)),await k.srem(ze,t).catch(()=>{})),Te==="cachly"||Te==="ollama")try{const R=await ke(We(S),{geduld:"lang",modell:Ve});R?.length&&await k.set(`${je}${t}`,Be(R))}catch{}}catch(E){await k.sadd(ze,t).catch(()=>{}),await Je(k,st,`Volltext-Vektor nicht geschrieben (${Te}): ${tt(E)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const E=await ke(Es(t),{geduld:"lang"});E?.length&&await k.set(`${xt}${t}`,Be(E))}catch(E){await Je(k,st,`Namens-Vektor nicht geschrieben (${Te}): ${tt(E)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await Ms(k,t,S,E=>ke(E,{geduld:"lang"}))}catch(E){await Je(k,st,`Eingaenge nicht geschrieben (${Te}): ${tt(E)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await Kt(k,t,3)})());try{const S="cachly:session:decision-log",E=JSON.stringify({ts:oe,topic:t,outcome:r,what_worked:O.slice(0,120)});await k.rpush(S,E),await k.ltrim(S,-50,-1)}catch{}let _=null;try{const S=pe(t),E=t.split(":")[0]??"unknown";await De(k,S,E,E);for(const P of a){const J=pe(`tag:${P}`);await De(k,J,"tag","tag"),await we(k,S,"co-occurs",J,r==="success",r==="partial")}for(const P of b){const J=pe(P);await we(k,S,"requires",J,!0)}if((E==="fix"||E==="debug")&&(r==="success"||r==="partial")){const P=Y||Q||"",J=P?Ze(P):null;if(J){const V=pe(`problem:${J}`);await De(k,V,"problem","problem"),await we(k,S,"fixes",V,r==="success",r==="partial")}}if(r==="failure"&&(Y||O)){const J=Ze(Y||O);if(J){const V=pe(`cause:${J}`);await De(k,V,"cause","cause"),await we(k,S,"causes",V,!1)}}if(r==="failure"){const P=await k.smembers(`cachly:ckg:idx:from:${S}`);for(const J of P){const V=await k.get(J);if(!V)continue;const se=B(V,null);if(se&&se.edgeType==="fixes"&&se.confidence>.7&&se.trials>=3){_=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${se.confidence.toFixed(2)}, n=${se.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${t}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${S}")\` to review.`;const le=`cachly:ckg:conflict:${S}`;await k.set(le,JSON.stringify({topic:t,concept_id:S,detected_at:new Date().toISOString(),fix_confidence:se.confidence,fix_trials:se.trials,failure_outcome:r,reported_by:re||"unknown",what_failed:Y||"",resolved:!1}),"EX",3600*24*90)}}}if(r==="success"&&(E==="fix"||E==="debug")){const P=await k.smembers(`cachly:ckg:idx:from:${S}`);for(const J of P.slice(0,10)){const V=await k.get(J);if(!V)continue;const se=B(V,null);if(!se||se.edgeType!=="fixes")continue;const le=await k.smembers(`cachly:ckg:idx:from:${se.to}`);for(const $e of le.slice(0,5)){const Ie=await k.get($e);if(!Ie)continue;const me=B(Ie,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 k.set($e,JSON.stringify(me)))}}}if(Math.random()<.01){const P=Date.now()-7776e6,J=await k.smembers(`cachly:ckg:idx:from:${S}`);for(const V of J){const se=await k.get(V);if(!se)continue;const le=B(se,null);le&&le.trials<3&&le.last_updated&&new Date(le.last_updated).getTime()<P&&(le.confidence=le.confidence*.9,le.last_updated=new Date().toISOString(),await k.set(V,JSON.stringify(le)))}}}catch{}if(re){k.set(`cachly:agents:active:${re}`,JSON.stringify({author:re,last_topic:t,last_outcome:r,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const S=t.split(":")[0]??"unknown",E=await Xt(k,Ot(re),S),R=pe(t);await we(k,E,"authored",R,r==="success",r==="partial");for(const P of n.slice(0,8)){const J=await gt(k,P);await we(k,E,"touched",J,!0),await Qt(k,J,E)}}catch{}}if(i&&typeof i=="string"&&i.trim())try{const S=t.split(":")[0]??"unknown",E=T==="system"?"system":"service",R=await es(k,i.trim(),S,E),P=pe(t);if(await we(k,P,"affects",R,r==="success",r==="partial"),re){const J=`person:${pe(Ot(re))}`;await we(k,J,"operates",R,!0)}for(const J of n.slice(0,8)){const V=`file:${pe(J)}`;await we(k,V,"runs_in",R,!0)}}catch{}if(re&&(r==="success"||r==="partial")){const S={topic:t,outcome:r,what_worked:O,what_failed:Y??"",severity:$,author:re,file_paths:n,commands:D,tags:[...new Set([...a,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},E=`cachly:lessons:${t}`;k.rpush(E,JSON.stringify(S)).catch(()=>{})}return[`${r==="success"?"\u2705":r==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${l?"updated":"stored"}:** \`${t}\` (${r}) ${$==="critical"?"\u{1F534}":$==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${$} \xB7 Beleg: \`${Ae}\``,w.funde.length?`\u{1F512} **${w.funde.length} Geheimnis(se) geschwaerzt** vor dem Speichern (${w.funde.join("; ")}). Der Wert ist nicht im Brain \u2014 verweise kuenftig auf den Ort (z. B. Infisical-Pfad oder Variablenname).`:"",_??"","",`**What worked:** ${O}`,Y?`**What failed:** ${Y}`:"",Q?`**Context:** ${Q}`:"",n.length>0?`**Files:** ${n.map(S=>`\`${S}\``).join(", ")}`:"",D.length>0?`**Commands:** ${D.map(S=>`\`${S}\``).join(", ")}`:"",a.length>0?`**Tags:** ${a.map(S=>`#${S}`).join(" ")}`:"","",l?`\u267B\uFE0F Updated (recall count: ${N} \xB7 audit entries: ${I.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,re&&(r==="success"||r==="partial")?`\u{1F465} Auto-shared with team (by _${re}_${ne.quelle!=="uebergeben"?` \xB7 aus ${ne.quelle}`:""}) \u2014 visible in \`team_recall\``:"",s??"",b.length>0?`\u{1F517} Depends on: ${b.map(S=>`\`${S}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",xe,de&&g?te?`\u21B7 Ersetzt \`${z}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${z}\` \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,...c,...ae,X>0?`\u{1F5D3}\uFE0F ${X} relative Zeitangabe${X===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(he.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",An(O)??""].filter(S=>S!=="").join(`
3
+ `)}case"lesson_verified":{const{instance_id:w}=K,o=await H(w),t=new Date().toISOString(),r=Yt(K,t);if(!r.ok)return[`\u26A0\uFE0F ${r.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
4
+ `);const m=r.eintrag,u=`cachly:lesson:best:${m.topic}`,C=await o.get(u);if(!C)return`\u{1F4ED} Keine Lektion \`${m.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const $=B(C,{});return await o.set(u,JSON.stringify(Zt($,m))),$t(),m.haelt?[`\u2705 \`${m.topic}\` ist wieder frisch \u2014 geprueft am ${t.slice(0,10)}.`,m.geprueft_mit?` geprueft mit: \`${m.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht."].filter(Boolean).join(`
5
5
  `):[`\u26A0\uFE0F \`${m.topic}\` ist als fraglich markiert.`,` Befund: ${m.befund}`,"","Geloescht wurde nichts \u2014 eine Pruefung kann aus Gruenden fehlschlagen,","die mit der Lektion nichts zu tun haben. Wenn du weisst, was jetzt gilt:",`\`learn_from_attempts(topic="${m.topic}", \u2026, grund="\u2026")\`.`].join(`
6
- `)}case"recall_feedback":{const{instance_id:y}=U,n=await Y(y),t=zs(U,new Date().toISOString());if(!t.ok)return[`\u26A0\uFE0F ${t.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 r=t.eintrag,m=`cachly:wirkung:${y}`;await n.rpush(m,JSON.stringify(r));const S=(await n.lrange(m,0,-1).catch(()=>[])).map(w=>B(w,null)).filter(Boolean),i=Os(S),u=Ps(r),A={"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 ${r.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${r.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."},s=i.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${(i.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${r.thema}** \u2014 ${r.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${r.platz===0?"\u2014 (stand nicht drin)":r.platz}`,"",A[u],"",`Spur: ${i.gesamt} Rueckmeldungen, ${s}.`,`Davon: ${i.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${i.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${i.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
8
- `)}case"recall_best_solution":{const y=Date.now(),{instance_id:n,topic:t,author:r}=U,m=await Y(n);try{const s=await m.get(`cachly:letzter-recall:${n}`),w=s?B(s,null):null,C=js(w,t,new Date().toISOString());C&&(await m.rpush(`cachly:wirkung:${n}`,JSON.stringify(C)),await m.del(`cachly:letzter-recall:${n}`))}catch{}const h=await m.get(`cachly:lesson:best:${t}`);if(h){const s=B(h,null);if(!s)return`\u26A0\uFE0F Lesson data for \`${t}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const w=s.group;if(w){const Q=r?await ut(m,n,r).catch(()=>new Set):new Set,we=r?await Xe(m,n,r).catch(()=>null)==="admin":!1;if(!ht(w,Q,we))return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const C=Pe(s),f=s.verified_at??s.ts,o=(Date.now()-new Date(f).getTime())/864e5,N=s.commands,_=Bt(C,o,Array.isArray(N)&&typeof N[0]=="string"?N[0]:void 0,s.pruefung_gefallen_am?{am:s.pruefung_gefallen_am,befund:s.pruefung_befund}:void 0),b=new Date().toISOString(),I={...s,recall_count:(s.recall_count??0)+1,last_recalled_at:b};await m.set(`cachly:lesson:best:${t}`,JSON.stringify(I)),Mt(m),vt(m,String(t??""),Date.now()-y);const E=ct(s)?rt(s):0;E>0&&m.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,E).catch(()=>{});const e=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":s.severity?"\u{1F7E2}":"",j=s.audit_trail??[],ie=j.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()}`),k=j.length>1?[`_Audit: ${j.length} changes \xB7 stored ${new Date(s.ts).toLocaleDateString("de-DE")}_`,...ie.length>0?["**Warum zuletzt geaendert:**",...ie]:[]].join(`
9
- `):"",ge=(Date.now()-new Date(s.ts).getTime())/864e5,le=ge>60?`\u{1F4AD} _Remember when you solved this ${Math.round(ge/30)} months ago? Still works._`:"",F=I.recall_count===3&&!s.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.":"",O=s.authors??(s.author?[s.author]:[]),G=[...new Set(O.filter(Boolean))],se=I.recall_count;let R="";G.length>=2&&se>=5?R=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7 \xB7 verified by ${G.length} developers. Trust this.`:se>=10?R=`\u{1F3C6} **Battle-tested** \u2014 recalled ${se}\xD7. This is one of your most-proven solutions.`:G.length>=2?R=`\u2705 **Team-verified** \u2014 confirmed by ${G.length} developers.`:se>=5&&(R=`\u2705 **Proven** \u2014 recalled ${se}\xD7 without contradiction.`);const Z=s.ersetzt_durch,fe=s.ersetzt_am?` (am ${s.ersetzt_am.slice(0,10)})`:"",re=Z?await m.get(`cachly:lesson:best:${Z}`):null,a=String(s.ersetzt_grund??"").trim(),g=a?` Grund: ${a}`:" Grund nicht erfasst.",d=re?!Ee(Te(re)):!1,c=Z?re?d?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${fe} \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**${fe} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${Z}")\`.${g} Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${fe} \u2014 der Nachfolger \`${Z}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",l=s.gilt_ab,x=s.gilt_bis,L=l?`\u{1F4C5} Gilt seit ${String(l).slice(0,10)}.`:"",M=s.entscheidung,T=M?.gegen?_t({gegen:M.gegen,grund:M.grund??null}):"",oe=x&&Date.parse(String(x))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(x).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[c,oe,L,T,le,R,`${_} **Best solution for \`${t}\`** ${e}${s.severity?` (${s.severity})`:""} \xB7 recalled ${I.recall_count}\xD7`,Us(s.author,s.source),"",s.what_worked?`**What worked:** ${s.what_worked}`:"",s.what_failed?`**What failed (avoid this):** ${s.what_failed}`:"",s.context?`**Context:** ${s.context}`:"",(s.file_paths??[]).length>0?`**Files:** ${(s.file_paths??[]).map(Q=>`\`${Q}\``).join(", ")}`:"",(s.commands??[]).length>0?`**Commands:** ${(s.commands??[]).map(Q=>`\`${Q}\``).join(", ")}`:"",(s.tags??[]).length>0?`**Tags:** ${(s.tags??[]).map(Q=>`#${Q}`).join(" ")}`:"",k,F].filter(Q=>Q!=="").join(`
10
- `)}const S=[],i=m.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((s,w)=>{i.on("data",C=>S.push(...C)),i.on("end",s),i.on("error",w)});const u=S.filter(s=>s.toLowerCase().includes(t.toLowerCase()));if(u.length===0){const s=`cachly:lessons:${t}`,w=await m.lrange(s,-3,-1);if(w.length>0){const f=w.map(o=>B(o,null)).filter(Boolean).map(o=>`- ${o.outcome==="success"?"\u2705":"\u274C"} ${o.what_worked.slice(0,120)} (${new Date(o.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${t}\` yet. Last attempts:
6
+ `)}case"recall_feedback":{const{instance_id:w}=K,o=await H(w),t=Vs(K,new Date().toISOString());if(!t.ok)return[`\u26A0\uFE0F ${t.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 r=t.eintrag,m=`cachly:wirkung:${w}`;await o.rpush(m,JSON.stringify(r));const C=(await o.lrange(m,0,-1).catch(()=>[])).map(b=>B(b,null)).filter(Boolean),$=Us(C),n=Ys(r),D={"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 ${r.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${r.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."},a=$.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${($.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${r.thema}** \u2014 ${r.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${r.platz===0?"\u2014 (stand nicht drin)":r.platz}`,"",D[n],"",`Spur: ${$.gesamt} Rueckmeldungen, ${a}.`,`Davon: ${$.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${$.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${$.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
8
+ `)}case"recall_best_solution":{const w=Date.now(),{instance_id:o,topic:t,author:r}=K,m=await H(o);try{const a=await m.get(`cachly:letzter-recall:${o}`),b=a?B(a,null):null,x=Zs(b,t,new Date().toISOString());x&&(await m.rpush(`cachly:wirkung:${o}`,JSON.stringify(x)),await m.del(`cachly:letzter-recall:${o}`))}catch{}const u=await m.get(`cachly:lesson:best:${t}`);if(u){const a=B(u,null);if(!a)return`\u26A0\uFE0F Lesson data for \`${t}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const b=a.group;if(b){const ae=r?await _t(m,o,r).catch(()=>new Set):new Set,ge=r?await nt(m,o,r).catch(()=>null)==="admin":!1;if(!bt(b,ae,ge))return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const x=Ke(a),p=a.verified_at??a.ts,i=(Date.now()-new Date(p).getTime())/864e5,T=a.commands,y=Ht(x,i,Array.isArray(T)&&typeof T[0]=="string"?T[0]:void 0,a.pruefung_gefallen_am?{am:a.pruefung_gefallen_am,befund:a.pruefung_befund}:void 0),v=new Date().toISOString(),A={...a,recall_count:(a.recall_count??0)+1,last_recalled_at:v};await m.set(`cachly:lesson:best:${t}`,JSON.stringify(A)),ut(m),rt(m,String(t??""),Date.now()-w);const M=wt(a)?mt(a):0;M>0&&m.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,M).catch(()=>{});const e=a.severity==="critical"?"\u{1F534}":a.severity==="major"?"\u{1F7E1}":a.severity?"\u{1F7E2}":"",W=a.audit_trail??[],ie=W.filter(ae=>ae&&typeof ae.grund=="string"&&ae.grund.trim().length>0).slice(-3).map(ae=>` \xB7 ${ae.ts?new Date(ae.ts).toLocaleDateString("de-DE"):"?"}: ${ae.grund.trim()}`),k=W.length>1?[`_Audit: ${W.length} changes \xB7 stored ${new Date(a.ts).toLocaleDateString("de-DE")}_`,...ie.length>0?["**Warum zuletzt geaendert:**",...ie]:[]].join(`
9
+ `):"",he=(Date.now()-new Date(a.ts).getTime())/864e5,oe=he>60?`\u{1F4AD} _Remember when you solved this ${Math.round(he/30)} months ago? Still works._`:"",F=A.recall_count===3&&!a.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.":"",O=a.authors??(a.author?[a.author]:[]),Y=[...new Set(O.filter(Boolean))],Q=A.recall_count;let X="";Y.length>=2&&Q>=5?X=`\u{1F3C6} **Battle-tested** \u2014 recalled ${Q}\xD7 \xB7 verified by ${Y.length} developers. Trust this.`:Q>=10?X=`\u{1F3C6} **Battle-tested** \u2014 recalled ${Q}\xD7. This is one of your most-proven solutions.`:Y.length>=2?X=`\u2705 **Team-verified** \u2014 confirmed by ${Y.length} developers.`:Q>=5&&(X=`\u2705 **Proven** \u2014 recalled ${Q}\xD7 without contradiction.`);const ne=a.ersetzt_durch,ce=a.ersetzt_am?` (am ${a.ersetzt_am.slice(0,10)})`:"",re=ne?await m.get(`cachly:lesson:best:${ne}`):null,s=String(a.ersetzt_grund??"").trim(),d=s?` Grund: ${s}`:" Grund nicht erfasst.",f=re?!Re(Me(re)):!1,c=ne?re?f?`\u{1F6AB} **DIESE FASSUNG IST ERSETZT**${ce} \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**${ce} \u2014 die gueltige Antwort steht in \`recall_best_solution(topic="${ne}")\`.${d} Der Text unten bleibt als Vorgeschichte lesbar.`:`\u26A0\uFE0F **ERSETZT-VERWEIS INS LEERE**${ce} \u2014 der Nachfolger \`${ne}\` wurde inzwischen geloescht. Diese Fassung gilt wieder als beste VORHANDENE Antwort; bei Gelegenheit neu bestaetigen (learn_from_attempts mit grund).`:"",l=a.gilt_ab,N=a.gilt_bis,L=l?`\u{1F4C5} Gilt seit ${String(l).slice(0,10)}.`:"",I=a.entscheidung,j=I?.gegen?At({gegen:I.gegen,grund:I.grund??null}):"",te=N&&Date.parse(String(N))<Date.now()?`\u23F3 **DIESE TATSACHE GALT BIS ${String(N).slice(0,10)}** \u2014 sie ist Geschichte, keine aktuelle Auskunft.`:"";return[c,te,L,j,oe,X,`${y} **Best solution for \`${t}\`** ${e}${a.severity?` (${a.severity})`:""} \xB7 recalled ${A.recall_count}\xD7`,an(a.author,a.source),"",a.what_worked?`**What worked:** ${a.what_worked}`:"",a.what_failed?`**What failed (avoid this):** ${a.what_failed}`:"",a.context?`**Context:** ${a.context}`:"",(a.file_paths??[]).length>0?`**Files:** ${(a.file_paths??[]).map(ae=>`\`${ae}\``).join(", ")}`:"",(a.commands??[]).length>0?`**Commands:** ${(a.commands??[]).map(ae=>`\`${ae}\``).join(", ")}`:"",(a.tags??[]).length>0?`**Tags:** ${(a.tags??[]).map(ae=>`#${ae}`).join(" ")}`:"",k,F].filter(ae=>ae!=="").join(`
10
+ `)}const C=[],$=m.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((a,b)=>{$.on("data",x=>C.push(...x)),$.on("end",a),$.on("error",b)});const n=C.filter(a=>a.toLowerCase().includes(t.toLowerCase()));if(n.length===0){const a=`cachly:lessons:${t}`,b=await m.lrange(a,-3,-1);if(b.length>0){const p=b.map(i=>B(i,null)).filter(Boolean).map(i=>`- ${i.outcome==="success"?"\u2705":"\u274C"} ${i.what_worked.slice(0,120)} (${new Date(i.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${t}\` yet. Last attempts:
11
11
 
12
- ${f.join(`
13
- `)}`}return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const A=[];for(const s of u.slice(0,5)){const w=await m.get(s);if(!w)continue;const C=B(w,null);C&&A.push(`**\`${C.topic}\`** \u2014 ${C.what_worked.slice(0,400)}${C.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${t}\`:**
12
+ ${p.join(`
13
+ `)}`}return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const D=[];for(const a of n.slice(0,5)){const b=await m.get(a);if(!b)continue;const x=B(b,null);x&&D.push(`**\`${x.topic}\`** \u2014 ${x.what_worked.slice(0,400)}${x.what_worked.length>400?" \u2026":""}`)}return`\u{1F50D} **Partial matches for \`${t}\`:**
14
14
 
15
- ${A.join(`
15
+ ${D.join(`
16
16
 
17
- `)}`}case"smart_recall":{const y=Date.now(),{instance_id:n,query:t,threshold:r=.78,author:m="",context_files:h=[]}=U,S=Array.isArray(h)?h.filter(p=>typeof p=="string"):[],i=await Y(n);Lt(i,void 0,2);let u=new Set,A=!1;m&&(u=await ut(i,n,m).catch(()=>new Set),A=await Xe(i,n,m).catch(()=>null)==="admin");const s=await Fe(i,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],t,25),w=hs(s);let C=!1,f=null;const o=await(async()=>{if(!Ae())return Ve(Xt,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),w;try{if(await $e.aktualisiere(i),$e.groesse===0)return Ve(Zt,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),w;const p=await Se(t);if(!p?.length)return Ve(Qt,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),w;await tt.aktualisiere(i),await st.aktualisiere(i),await ze.aktualisiere(i),await Ke.aktualisiere(i);const $=$e.groesse>0?Ke.groesse/$e.groesse:0;$<kt&&$e.groesse>0&&In(i,3);const v=$>=kt?Se(t,{modell:Ge}).catch(()=>null):null,K=w.filter(P=>P.key.startsWith("cachly:lesson:best:")).map(P=>P.key.slice(19)),q=P=>Math.max($e.naehe(p,P),tt.naehe(p,P)),z=[...ze.themen()],X=(z.length>0?z:$e.aehnlichste(p,500).map(P=>P.topic)).map(P=>({t:P,n:q(P)})).sort((P,ue)=>ue.n-P.n).slice(0,xt).map(P=>P.t),ne=[...new Set([...K,...X])],J=X.slice(0,3).map(P=>$e.rohvektor(P)).filter(Boolean),me=J.length?Rs(p,J):p,D=$t(t),W=ze.statistik,ee=ne.map(P=>{const ue=new Set([...$t(ze.textVon(P))].map(Ds));return{naeheText:$e.naehe(p,P),naeheThema:tt.naehe(p,P),naeheRueckkopplung:$e.naehe(me,P),seltenheitsDeckung:W?W.deckung(D,ue):0,besterZeuge:W?W.besterZeuge(D,ue):0}});let H=Is(ee,Ls);{const P=[...H].sort((ue,_e)=>_e-ue);f=P.length>1?P[0]-P[1]:null}if(st.groesse>0){const P=ne.map(_e=>{const pe=st.besteNaehe(p,_e);return pe>=Qs?pe:-2}),ue=bt(P);H=H.map((_e,pe)=>_e+en*ue[pe])}if(v){const P=await v;if(P?.length){const ue=bt(ne.map(_e=>Ke.naehe(P,_e)));H=H.map((_e,pe)=>_e+Js*ue[pe])}}let V=ne.map((P,ue)=>({t:P,p:H[ue]})).sort((P,ue)=>ue.p-P.p).map(P=>P.t);if(ps(n)&&V.length>1){const P=V.slice(0,St),ue=V.slice(St),_e=new Map(ne.map((Oe,Re)=>[Oe,H[Re]])),pe=await ms(t,P.map(Oe=>ze.leserTextVon(Oe)),{instanceId:n});pe&&(V=[...gs(P.map(Re=>_e.get(Re)??0),pe).map(Re=>P[Re]),...ue])}const te=new Map(w.map(P=>[P.key,P])),he=[];for(const P of V){const ue=`cachly:lesson:best:${P}`,_e=te.get(ue);if(_e){he.push(_e),te.delete(ue);continue}const pe=await i.get(ue).catch(()=>null);pe&&he.push({key:ue,content:pe,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return he.push(...te.values()),Fs&&Ws({frage:t.slice(0,200),themen:ne,ausWortsuche:K.length,ausSinnsuche:X.length,obergrenze:xt,gezeigt:V.slice(0,10)}),C=!0,he}catch(p){return await We(i,es,`der Bedeutungspfad brach ab (${p instanceof Error?p.message:String(p)}) \u2014 diese Suche lief nur ueber Woerter`),w}})();Mt(i),vt(i,String(t??""),Date.now()-y);{const p=o.filter($=>$.key.startsWith("cachly:lesson:best:")).slice(0,3).map($=>$.key.slice(19));if(p.length>0){const $={ts:new Date().toISOString(),themen:p};(async()=>{const v=gt(n);await i.lpush(v,JSON.stringify($)),await i.ltrim(v,0,Ns-1)})().catch(()=>{})}{const $={ts:new Date().toISOString(),frage:t.slice(0,200),geliefert:p};(async()=>{const v=wt(n);await i.lpush(v,JSON.stringify($)),await i.ltrim(v,0,As-1)})().catch(()=>{})}}if(Ae()){const p=o.filter($=>$.key.startsWith("cachly:lesson:best:")).slice(0,3).map($=>$.key.slice(19));Ss(i,t,p,Se).catch(()=>{})}const N=[],_=o.filter(p=>p.key.startsWith("cachly:lesson:best:"));let b=0,I=0;for(const p of _.slice(0,5)){const $=await i.get(p.key).catch(()=>null);if($){const v=B($,null);if(v?.state==="archived")continue;if(v){const K=new Date().toISOString(),q={...v,recall_count:(v.recall_count??0)+1,last_recalled_at:K};i.set(p.key,JSON.stringify(q)).catch(()=>{});const z=ct(v)?rt(v):0;if(z>0&&i.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,z).catch(()=>{}),v.author&&m&&v.author!==m){b++,i.sadd(`cachly:stats:reuse_pairs:${n}`,`${m}<-${v.author}`).catch(()=>{});const X=`person:${ye(m)}`,ne=`person:${ye(v.author)}`;be(i,X,"collaborates",ne,!0).catch(()=>{}),be(i,ne,"collaborates",X,!0).catch(()=>{})}v.outcome==="success"&&I++,v.outcome==="success"&&(v.recall_count??0)>=1&&!je(v)&&N.push({topic:p.key.replace("cachly:lesson:best:",""),severity:v.severity??"major",recall_count:(v.recall_count??0)+1,savedMins:z,ts:v.ts,author:v.author})}}}I>0&&i.set(`cachly:stats:first_recall_at:${n}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),_.length>0&&(i.incr(`cachly:stats:recalls_total:${n}`).catch(()=>{}),b>0&&i.incr(`cachly:stats:cross_author_recalls:${n}`).catch(()=>{}));const E=await de(`/api/v1/instances/${n}`).catch(()=>null),e=!E?.tier||E.tier.toLowerCase()==="free",j=[];if(!e&&E?.vector_token&&Ae())try{const p=await Se(t),$=`https://api.cachly.dev/v1/sem/${E.vector_token}`,v=await fetch(`${$}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:p,namespace:"cachly:ctx",threshold:r,top_k:5}),signal:AbortSignal.timeout(8e3)});if(v.ok){const K=await v.json();for(const q of K.filter(z=>z.found&&z.id)){const z=q.id.replace("ctx:","").split(":"),X=z[0],ne=z.slice(1).join(":"),J=`cachly:ctx:${X}:${ne}`,me=await i.get(J).catch(()=>null);j.push({key:J,similarity:q.similarity??0,content:me??"(evicted)"})}}}catch{}const ie=o.map(p=>p.score),k=ie.length?Math.min(...ie):0,ge=ie.length&&Math.max(...ie)-k||1,le=p=>(p-k)/ge,F=new Map,O=C?vs(o.map(p=>le(p.score))):null,G=new Map;for(const[p,$]of o.entries()){const v=le($.score),K=O?O[p]:v;O&&F.set($.key,p),G.set($.key,{key:$.key,content:$.content,bm25Score:v,hausWert:K,hybridScore:K*(j.length>0?.7:1),matchedWords:$.matchedWords,matchType:"keyword",subQuery:$.subQuery,wortBelege:$.wortBelege})}for(const p of j){const $=G.get(p.key);$?($.semScore=p.similarity,$.hybridScore=($.hausWert??0)*.6+p.similarity*.4,$.matchType="hybrid"):G.set(p.key,{key:p.key,content:p.content,semScore:p.similarity,hybridScore:p.similarity*.5,matchType:"semantic"})}try{const p=Qe(t).filter(K=>K.length>=4).slice(0,4),$=new Set;for(const K of p){const q=i.scanStream({match:`cachly:ckg:node:*${K}*`,count:20});await new Promise((z,X)=>{q.on("data",ne=>{for(const J of ne.slice(0,5))$.add(J.replace("cachly:ckg:node:",""))}),q.on("end",z),q.on("error",X)})}const v=new Set;for(const K of[...$].slice(0,12)){const q=await i.smembers(`cachly:ckg:idx:to:${K}`);for(const z of q.slice(0,6)){const X=await i.get(z);if(!X)continue;const ne=B(X,null);if(!ne||ne.edgeType!=="fixes"||ne.confidence<.35||v.has(ne.from))continue;v.add(ne.from);const J=`cachly:lesson:best:${ne.from}`,me=G.get(J);if(me)me.ckgScore=Math.max(me.ckgScore??0,ne.confidence),me.hybridScore=me.hybridScore*.88+ne.confidence*.12,me.matchType==="keyword"&&(me.matchType="hybrid");else{const D=await i.get(J).catch(()=>null);if(!D)continue;G.set(J,{key:J,content:D,ckgScore:ne.confidence,hybridScore:ne.confidence*.3,matchType:"ckg"})}}}}catch{}if(S.length>0){const p=new Set(S.map($=>$.replace(/\\/g,"/")));for(const $ of G.values()){if(!$.key.startsWith("cachly:lesson:best:"))continue;const v=B($.content,{});(Array.isArray(v.file_paths)?v.file_paths.filter(q=>typeof q=="string").map(q=>q.replace(/\\/g,"/")):[]).some(q=>p.has(q))&&($.hybridScore*=1.15,$.contextBoost=!0)}}for(const p of G.values()){if(p.matchType!=="semantic"&&p.matchType!=="ckg")continue;const $=fs({key:p.key,content:p.content});$&&(p.hybridScore*=ds($))}const se=[...G.values()].filter(p=>{if(!p.key.startsWith("cachly:lesson:best:"))return!0;const $=Te(p.content);return!(!Ee($)||!ht($?.group,u,A))}),R=O?$s(se,F):se.sort((p,$)=>$.hybridScore-p.hybridScore),Z=[];for(const p of R){if(!p.key.startsWith("cachly:lesson:best:"))continue;const $=B(p.content,{});$.gilt_bis&&Date.parse(String($.gilt_bis))<Date.now()&&Z.push(`\u23F3 \`${p.key.replace("cachly:lesson:best:","")}\` galt bis ${String($.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const v=B(p.content,{});if(v.pruefung_gefallen_am){const K=p.key.replace("cachly:lesson:best:",""),q=String(v.pruefung_gefallen_am).slice(0,10),z=String(v.pruefung_befund??"").trim().slice(0,200);Z.push(`\u274C \`${K}\` \u2014 Pruefung am ${q} FEHLGESCHLAGEN`+(z?`: ${z}`:""))}}{const p=new Set(R.map($=>$.key));for(let $=R.length-1;$>=0;$--){const v=R[$];if(!v.key.startsWith("cachly:lesson:best:"))continue;const K=B(v.content,{});if(!K.ersetzt_durch)continue;const q=String(K.ersetzt_grund??"").trim(),z=v.key.replace("cachly:lesson:best:","");if(p.has(`cachly:lesson:best:${K.ersetzt_durch}`))R.splice($,1),Z.push(`\u21B7 \`${z}\` verdraengt \u2014 ersetzt durch \`${K.ersetzt_durch}\`${K.ersetzt_am?` am ${K.ersetzt_am.slice(0,10)}`:""}${q?` \u2014 Grund: ${q}`:" \u2014 Grund nicht erfasst"}`);else if(await i.get(`cachly:lesson:best:${K.ersetzt_durch}`)){const X=Te(await i.get(`cachly:lesson:best:${K.ersetzt_durch}`));Ee(X)?Z.push(`\u26A0\uFE0F \`${z}\` ist ersetzt durch \`${K.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${K.ersetzt_durch}")\``):Z.push(`\u21B7 \`${z}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else Z.push(`\u21A9\uFE0F \`${z}\` war ersetzt durch \`${K.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const fe=[];{await $e.aktualisiere(i).catch(()=>{});const p=R.slice(0,8).filter($=>$.key.startsWith("cachly:lesson:best:"));for(let $=0;$<p.length;$++)for(let v=$+1;v<p.length;v++){const K=p[$].key.replace("cachly:lesson:best:",""),q=p[v].key.replace("cachly:lesson:best:",""),z=$e.rohvektor(K),X=$e.rohvektor(q);if(!z||!X)continue;let ne=0,J=0,me=0;for(let ee=0;ee<z.length;ee++)ne+=z[ee]*X[ee],J+=z[ee]*z[ee],me+=X[ee]*X[ee];if((J>0&&me>0?ne/(Math.sqrt(J)*Math.sqrt(me)):0)<qs)continue;const W=ee=>{const H=B(ee??"",{});return String(H.verified_at??H.ts??"").slice(0,10)||"ohne Datum"};fe.push(`\u26A0\uFE0F \`${K}\` (${W(p[$].content)}) und \`${q}\` (${W(p[v].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}fe.length>3&&(fe.length=3)}if(Z.push(...fe),R.length>=2){const p=R[0].hybridScore,$=R[Math.min(4,R.length-1)].hybridScore,v=Math.max(0,p-$);(async()=>{try{await i.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(v.toFixed(4)),n:R.length})),await i.ltrim("cachly:recall:spread",0,199)}catch{}})()}const re=ts();let a="",g=null;if(re!==null){a=ss();const p=R[0]?.hybridScore??0,$=ns(R.map(v=>({key:v.key,content:v.content,punktzahl:v.hybridScore})),a,re,p);$.weggelassenesThema!==void 0?R.splice(0,1):$.markierungGesetzt&&R[0]&&$.treffer[0]&&(R[0]={...R[0],content:$.treffer[0].content}),g={frage:t,hoechstePunktzahl:p,themen:[],zulassungsfaehig:$.zulassungsfaehig,zulassungsGrund:$.zulassungsGrund,zuteilung:$.zuteilung,weggelassenesThema:$.weggelassenesThema,markierungGesetzt:$.markierungGesetzt}}const d=await Dt(n,de),c=d.reached,l=Tt({ueberLimit:c,gesamt:R.length,volleTiefe:sn}),x=process.env.CACHLY_RECALL_COMPACT==="1",L=(()=>{const p=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(p)?Math.min(20,Math.max(1,p)):5})(),M=x?Math.min(L,l.sichtbar):l.sichtbar,T=[`\u{1F9E0} **Smart Recall** for: _"${t}"_
18
- `];d.goodwillMessage&&T.push(`${d.goodwillMessage}
19
- `);const oe={critical:0,major:1,minor:2},Q=N.sort((p,$)=>(oe[p.severity]??1)-(oe[$.severity]??1))[0];if(Q){const p=z=>z>=60?`${z/60}h`:`${z}min`,$=(()=>{if(!Q.ts)return null;const z=new Date(Q.ts);if(isNaN(z.getTime()))return null;const X=new Date,ne=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return z.getFullYear()===X.getFullYear()?`${z.getDate()} ${ne[z.getMonth()]}`:`${z.getDate()} ${ne[z.getMonth()]} ${z.getFullYear()}`})(),v=Q.severity==="critical"?120:Q.severity==="major"?60:20,K=Q.author&&Q.author!==m?` \xB7 by @${Q.author}`:"",q=$?` \xB7 learned ${$} (was a ${p(v)} debug)`:"";T.push(`> \u{1F4A1} **Brain saved you ~${p(Q.savedMins)} here** \u2014 \`${Q.topic}\`${q} \xB7 recalled ${Q.recall_count}\xD7${K}
20
- `)}b>0&&T.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${b} of these lesson${b!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
21
- `);const we=R.filter(p=>p.contextBoost).length;we>0&&T.push(`> \u{1F4C1} **Personalized** \u2014 ${we} lesson${we!==1?"s":""} boosted because ${we!==1?"they match":"it matches"} your current file context (${S.slice(0,3).join(", ")}${S.length>3?", \u2026":""})
22
- `);const ce=ls(t);ce.length>1&&T.push(`_Detected ${ce.length} sub-topics:_ ${ce.map((p,$)=>`${$+1}. "${p}"`).join(", ")}
23
- `);const ke=Vt(R.map(p=>({wortBelege:p.wortBelege,semScore:p.semScore,ckgScore:p.ckgScore})));if(ke.schweigen)return Rt(i,n,"schweigen"),T.push(qt(ke)),T.join(`
24
- `);const ve=Bs(f);if(ve&&T.push(ve,""),Rt(i,n,ve?"knapp":"beantwortet"),R.length>0){const p=R.some(v=>v.ckgScore!==void 0),$=j.length>0&&p?"keyword + semantic + CKG hybrid":j.length>0?"keyword + semantic hybrid":p?"keyword + CKG hybrid":"keyword";if(T.push(`### \u{1F50D} Results (${R.length} \u2014 ${$})
25
- `),ke.belegte<R.length){const v=[];for(const q of R){if(!q.key.startsWith("cachly:lesson:best:")||!Yt({wortBelege:q.wortBelege,semScore:q.semScore,ckgScore:q.ckgScore}))continue;const z=B(q.content,{}),X=Date.parse(z.verified_at??z.ts??"");Number.isFinite(X)&&v.push(Math.floor((Date.now()-X)/864e5))}const K=Ut(v);T.push(`> \u{1F4CA} ${ke.belegte} von ${R.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(K?` \u23F3 ${K}`:"")+`
26
- `)}if(Z.length>0&&T.push(...Z.map(v=>`> ${v}`),""),ce.length>1){const v=new Map,K=Tt({ueberLimit:c,gesamt:R.length,volleTiefe:nn});for(const X of R.slice(0,K.sichtbar)){const ne=X.subQuery??t;v.has(ne)||v.set(ne,[]),v.get(ne).push(X)}for(const[X,ne]of v){T.push(`**Topic: "${X}"** (${ne.length} results)
27
- `);for(const J of ne.slice(0,x?2:4)){const me=J.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),D=J.matchType==="ckg"?`CKG: ${(J.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:J.ckgScore!==void 0&&J.bm25Score!==void 0?`BM25: ${J.bm25Score.toFixed(2)}, CKG: ${J.ckgScore.toFixed(2)}, \u{1F500} hybrid`:J.matchType==="hybrid"?`BM25: ${(J.bm25Score??0).toFixed(2)}, sem: ${((J.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:J.matchType==="semantic"?`sem: ${((J.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(J.bm25Score??0).toFixed(2)}, matched: ${J.matchedWords?.join(", ")}`,W=lt(J.key,J.content,300);if(T.push(x?` **${me}**`:` **${me}** _(${D})_`),J.key.startsWith("cachly:lesson:best:")){const ee=await i.get(J.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await i.get(J.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),H=ee?B(ee,{}):{};H.title&&T.push(` \u{1F4D6} **${H.title}** \u2014 ${H.summary??""}`)}for(const ee of W)T.push(` > ${ee}`);T.push("")}}const q=[...v.keys()],z=ce.filter(X=>!q.includes(X));z.length>0&&T.push(`
28
- \u26A0\uFE0F **No results for:** ${z.map(X=>`"${X}"`).join(", ")}`)}else for(const v of R.slice(0,M)){const K=v.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let q="";if(v.key.startsWith("cachly:lesson:best:")){const J=B(v.content,{});J.author&&(q=` \xB7 \u{1F464} ${J.author}`)}const z=v.contextBoost?" \xB7 \u{1F4C1} context match":"",X=v.matchType==="hybrid"?`BM25: ${(v.bm25Score??0).toFixed(2)}, sem: ${((v.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:v.matchType==="semantic"?`sem: ${((v.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(v.bm25Score??0).toFixed(2)}, matched: ${v.matchedWords?.join(", ")}`,ne=lt(v.key,v.content,400);T.push(x?`**${K}**`:`**${K}**${q}${z} _(${X})_`);{const J=B(v.content??"",{});J.entscheidung?.gegen&&T.push(_t({gegen:J.entscheidung.gegen,grund:J.entscheidung.grund??null}))}if(v.key.startsWith("cachly:lesson:best:")){const J=await i.get(v.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await i.get(v.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),me=J?B(J,{}):{};me.title&&T.push(`\u{1F4D6} **${me.title}** \u2014 ${me.summary??""}`)}for(const J of ne)T.push(`> ${J}`);T.push("")}if(c&&l.zurueckgehalten>0){const v=l.zurueckgehalten;T.push(`\u{1F512} **Free recall limit reached** (${d.used}/${d.limit} this month). Showing your top match; ${v} further relevant lesson${v!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${Tn}
29
- `)}}else{T.push(`\u26A0\uFE0F No matches found for: "${t}"`),Z.length>0&&T.push("",...Z.map(v=>`> ${v}`));const p=Qe(t),$=[];if(ft.size>0&&p.length>0)for(const v of p.slice(0,3)){if(v.length<4)continue;let K=3,q="";for(const z of ft){if(z.length<3||Math.abs(z.length-v.length)>4)continue;const X=us(v,z);X>0&&X<K&&(K=X,q=z)}q&&$.push(`"${q}" (instead of "${v}")`)}$.length>0?T.push(`\u{1F4A1} **Did you mean:** ${$.join(", ")}?`):(T.push(`
30
- \u{1F4A1} Tips:`),T.push(" \u2022 Try different keywords"),T.push(" \u2022 Use `list_remembered` to see available context"),T.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!x&&R.length>0){T.push(""),T.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 p=R.filter($=>$.key.startsWith("cachly:lesson:best:")).map($=>$.key.slice(19));if(p.length>0)try{await i.setex(`cachly:letzter-recall:${n}`,7200,JSON.stringify({frage:t,themen:p}))}catch{}}if(x&&R.length>0){const p=jt();p&&(T.push(""),T.push(p))}if(re!==null&&g){const p=R.slice(0,M).filter($=>$.key.startsWith("cachly:lesson:best:")).map($=>$.key.slice(19));return os(i,a,{...g,themen:p},T.join(`
31
- `))}return T.join(`
32
- `)}case"session_start":{const{instance_id:y,focus:n="",author:t="",provider:r="",workspace_path:m=""}=U,h=await Y(y),S=[],i=h.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((a,g)=>{i.on("data",d=>S.push(...d)),i.on("end",a),i.on("error",g)});const u=[];if(S.length>0){const a=await h.mget(...S);for(const g of a){const d=B(g??null,null);d&&u.push(d)}}u.sort((a,g)=>new Date(g.ts).getTime()-new Date(a.ts).getTime());let A=0;const s=h.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((a,g)=>{s.on("data",d=>{A+=d.filter(c=>!c.endsWith(":meta")).length}),s.on("end",a),s.on("error",g)});const w=await h.get("cachly:session:last"),C=B(w,null),f=n.toLowerCase().split(/\s+/).filter(Boolean),o=f.length>0?u.filter(a=>f.some(g=>a.topic.toLowerCase().includes(g)||(a.tags??[]).some(d=>d.toLowerCase().includes(g)))):[];let N=0,_=0,b="";try{const a=await h.get("cachly:streak:current"),g=B(a,null),d=new Date().toISOString().slice(0,10);if(g){const c=g.last_date,l=new Date(Date.now()-864e5).toISOString().slice(0,10);c===d?(N=g.days,_=g.record):c===l?(N=g.days+1,_=Math.max(N,g.record),await h.set("cachly:streak:current",JSON.stringify({days:N,last_date:d,record:_}))):(N=1,_=g.record,await h.set("cachly:streak:current",JSON.stringify({days:1,last_date:d,record:_})))}else N=1,_=1,await h.set("cachly:streak:current",JSON.stringify({days:1,last_date:d,record:1}));N>=7?b=`\u{1F525} **${N}-day streak!** ${N===_?" New record!":`Best: ${_}d`}`:N>1&&(b=`\u{1F525} ${N}-day streak`)}catch{}await h.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:n,provider:r}),"EX",86400);let I=0;try{const a=await h.get(`cachly:stats:time_saved_mins:${y}`);I=parseFloat(a??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${r?` \xB7 ${r}`:""}`,""];if(b&&e.push(b,""),I>=30){const a=Math.floor(I/60),g=Math.round(I%60),d=a>0?`${a}h${g>0?` ${g}m`:""}`:`${g}m`,c=u.filter(x=>!je(x)&&(x.recall_count??0)>0).length,l=c>0?` \u2014 ${c} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${d} total**${l}`,"")}const j=await Dt(y,de),ie=tn({used:j.used,limit:j.limit,savedMins:I});if(ie&&e.push(ie,""),j.notice&&!At.has(y)&&(At.add(y),e.push(j.notice,"")),C?.ts){const a=new Date(C.ts).getTime(),g=Math.floor((Date.now()-a)/864e5);if(g>=7&&!Number.isNaN(a)){const d=u.filter(c=>{const l=new Date(c.ts).getTime();return!Number.isNaN(l)&&l>a});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${g} days since your last session.`),d.length>0){const c=d.slice(0,3).map(l=>`\`${l.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${d.length} lesson${d.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${c}${d.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${u.length} lesson${u.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);e.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await h.get("cachly:mcp:version:last_seen")!==He){await h.set("cachly:mcp:version:last_seen",He,"EX",365*86400);const g=xn[He];if(g){e.push(...g,"");const d=Cn();d&&e.push(`\u{1F4CA} ${d} MCP tools`,"")}}}catch{}const k=!C&&u.length===0&&A===0;if(k&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),m?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${y}")\``),e.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),e.push(""),e.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),e.push("")),t&&!k)try{const a=`cachly:team:first_briefing:${t}`;if(!await h.get(a)){const d=u.filter(c=>c.author&&c.author!==t);if(d.length>0){await h.set(a,"1","EX",365*86400);const c=new Map;for(const l of d){const x=l.author;c.has(x)||c.set(x,[]),c.get(x).push(l)}e.push(""),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),e.push(""),e.push("Your teammates have already solved problems you're about to hit:"),e.push("");for(const[l,x]of c){e.push(` \u{1F464} **${l}** fixed ${x.length} thing${x.length>1?"s":""}:`);for(const L of x.slice(0,2)){const M=L.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${M} \`${L.topic}\` \u2014 ${L.what_worked.slice(0,90)}`)}x.length>2&&e.push(` \u2026 and ${x.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const ge=await h.get("cachly:session:handoff");if(ge)try{const a=JSON.parse(ge),g=Math.round((Date.now()-new Date(a.ts).getTime())/6e4),d=g<60?`${g}m ago`:g<1440?`${Math.round(g/60)}h ago`:`${Math.round(g/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${d}):`),a.context_summary&&e.push(` ${a.context_summary}`),a.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const l of a.remaining_tasks)e.push(` - ${l}`)}a.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${a.completed_tasks.join(", ")}`);const c=(a.files_changed??[]).filter(l=>l.status==="broken"||l.status==="partial");c.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${c.map(l=>`\`${l.path}\` (${l.status}${l.description?": "+l.description:""})`).join(", ")}`),a.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${a.blocked_on}`),a.instructions&&e.push(` \u{1F4DD} **Instructions:** ${a.instructions}`),e.push("")}catch{}const le=await h.get("cachly:session:checkpoint");if(le)try{const a=JSON.parse(le),g=new Date(a.ts).getTime(),d=C?new Date(C.ts).getTime():0;if(g>d){const c=Math.round((Date.now()-g)/6e4),l=c<60?`${c}m ago`:c<1440?`${Math.round(c/60)}h ago`:`${Math.round(c/1440)}d ago`,x=a.provider?` [${a.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${x} (${l}): ${a.task}`),a.files_touched.length>0&&e.push(` Files: ${a.files_touched.slice(0,5).map(L=>`\`${L}\``).join(", ")}`),a.next_step&&e.push(` \u{1F4CD} Next step was: ${a.next_step}`),(!C||g-d>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(m&&!C)try{const{execSync:a}=await import("node:child_process"),g=a(`git -C "${m}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),d=a(`git -C "${m}" diff --stat HEAD~3 2>/dev/null || git -C "${m}" diff --stat 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim();if(g){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const c of g.split(`
33
- `).slice(0,8))e.push(` ${c}`);if(d){const c=d.split(`
34
- `).filter(l=>l.includes("|")||l.includes("changed"));if(c.length>0){e.push(" **Recent changes:**");for(const l of c.slice(0,5))e.push(` ${l.trim()}`)}}e.push("")}}catch{}if(C){const a=Math.round((Date.now()-new Date(C.ts).getTime())/6e4),g=a<60?`${a}m ago`:a<1440?`${Math.round(a/60)}h ago`:`${Math.round(a/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${g}): ${C.summary}`),C.duration_min&&e.push(` Duration: ${C.duration_min} min`),(C.files_changed??[]).length>0&&e.push(` Files: ${(C.files_changed??[]).slice(0,5).map(d=>`\`${d}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${u.length} lessons \xB7 ${A} context entries`,"");{const g=u.filter(d=>!je(d)).filter(d=>d.outcome==="success"&&(d.pinned===!0||(d.recall_count??0)>=5)).sort((d,c)=>(c.recall_count??0)-(d.recall_count??0)).slice(0,5);if(g.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const d of g){const c=d.severity==="critical"?"\u{1F534}":d.severity==="major"?"\u{1F7E1}":"",l=d.recall_count??0,x=d.pinned===!0?"pinned":`recalled ${l}\xD7`,L=De(d);e.push(` \u{1F3C6}${c} \`${d.topic}\` _(${x})_ \u2014 ${L[0]??""}`,...L.slice(1))}e.push("")}}if(u.length>=3){const a=new Map;for(const c of u){const l=c.topic.split(":")[0]??"other";a.has(l)||a.set(l,{total:0,success:0,critical:0});const x=a.get(l);x.total++,c.outcome==="success"&&x.success++,c.severity==="critical"&&x.critical++}const g=[...a.entries()].sort((c,l)=>l[1].total-c[1].total).slice(0,6),d=g.some(([,c])=>c.success<c.total*.4&&c.total>=2);if(g.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[c,l]of g){const x=Math.round(l.success/l.total*100),L=Math.round(x/10),M="\u2588".repeat(L)+"\u2591".repeat(10-L),T=l.critical>0?" \u{1F534}":x<40&&l.total>=2?" \u26A0\uFE0F":"";e.push(` ${M} ${c.padEnd(18)} ${String(x).padStart(3)}% (${l.success}/${l.total} confirmed)${T}`)}d&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}const F="cachly:ckg:node:";let O=null;const G=async()=>{if(O)return O;const a=[],g=h.scanStream({match:`${F}*`,count:1e3});return await new Promise((d,c)=>{g.on("data",l=>a.push(...l)),g.on("end",d),g.on("error",c)}),O=a,a};try{const a=[],g=h.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((d,c)=>{g.on("data",l=>a.push(...l)),g.on("end",d),g.on("error",c)}),a.length>0){e.push(`\u26A1 **Active belief conflicts (${a.length}):**`);for(const d of a.slice(0,3)){const c=await h.get(d);if(!c)continue;const l=B(c,null);l&&e.push(` \u26A0\uFE0F \`${l.topic}\` \u2014 previously confirmed fix (${(l.fix_confidence*100).toFixed(0)}%, n=${l.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${ye(l.topic)}")\``)}e.push("")}}catch{}if(n&&n.length>3)try{const a=n.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(d=>d.length>3),g=[];for(const d of a.slice(0,6))await h.exists(`cachly:ckg:node:${d}`)||(await G()).some(x=>x.startsWith(`${F}${d}`))||g.push(d);if(g.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const d of g.slice(0,3))e.push(` \u2B1C \`${d}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${d}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${d}")\` \u2014 search global commons`);e.push("")}}catch{}if(o.length>0){e.push(`\u{1F3AF} **Relevant for "${n}":**`);for(const a of o.slice(0,4)){const g=a.outcome==="success"?"\u2705":a.outcome==="partial"?"\u26A0\uFE0F":"\u274C",d=a.severity==="critical"?"\u{1F534}":a.severity==="major"?"\u{1F7E1}":"",c=De(a);e.push(` ${g}${d} \`${a.topic}\` \u2014 ${c[0]??""}`,...c.slice(1))}e.push("")}if(u.length>0){const g=[...u].filter(c=>!je(c)).sort((c,l)=>(l.recall_count??0)-(c.recall_count??0)).filter(c=>(c.recall_count??0)>0).slice(0,3),d=(o.length>0?u.filter(c=>!o.includes(c)):u).filter(c=>!g.includes(c)).slice(0,o.length>0?3:4);if(g.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${g[0].recall_count}\xD7 before):`);for(const c of g){const l=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",x=c.severity==="critical"?"\u{1F534}":c.severity==="major"?"\u{1F7E1}":"",L=c.recall_count??0,M=c.authors??(c.author?[c.author]:[]),T=new Set(M.filter(Boolean)).size,oe=T>=2&&L>=5||L>=10?" \u{1F3C6}":T>=2||L>=5?" \u2705":"",Q=L>1?` _(${L}\xD7 recalled)_`:"",we=De(c);e.push(` ${l}${x}${oe} \`${c.topic}\`${Q} \u2014 ${we[0]??""}`,...we.slice(1))}e.push("")}if(d.length>0){const c=g.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(c);for(const l of d){const x=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",L=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",M=De(l);e.push(` ${x}${L} \`${l.topic}\` \u2014 ${M[0]??""}`,...M.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");u.length>=10&&(u.some(g=>g.author)||(e.push(`\u{1F91D} **Your Brain has ${u.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const se=u.filter(a=>a.outcome==="failure"||a.outcome==="partial");if(se.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${se.length} topic${se.length>1?"s":""} with no success yet):`);for(const a of se.slice(0,3))e.push(` \u274C \`${a.topic}\` \u2014 ${(a.what_failed??a.what_worked).slice(0,80)}`);e.push("")}const R=u.filter(a=>a.outcome!=="success"&&a.outcome!=="partial"?!1:Pe(a)<at);if(R.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Pt}d \u2014 verify before applying):`);for(const a of R.slice(0,4)){const g=Pe(a),d=Math.round((Date.now()-new Date(a.verified_at??a.ts).getTime())/864e5),c=g<Ot?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${c} \`${a.topic}\` \u2014 ${d}d stale, ${(g*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const Z=C;if(Z?.decision_log?.length){const a=Z.decision_log,g=a.filter(c=>c.outcome==="success"),d=a.filter(c=>c.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${a.length} lessons stored):`),g.length>0&&e.push(` \u2705 Worked: ${g.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),d.length>0&&e.push(` \u274C Failed: ${d.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),e.push("")}{const a=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"]),g=x=>{const L=new Set;for(const M of x)for(const T of M.toLowerCase().split(/[/\\._-]/))T.length>3&&!a.has(T)&&L.add(T);return[...L]};let d=f,c=n,l=!1;if(d.length===0&&C){const x=g(C.files_changed??[]),L=(C.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(M=>M.length>3&&!a.has(M));d=[...new Set([...x,...L])],c="where you left off last session",l=!0}if(d.length>0){const x=u.filter(L=>{if(L.outcome==="success")return!1;const M=L.topic.split(":")[0];return d.some(T=>L.topic.toLowerCase().includes(T)||M===T||(L.tags??[]).some(oe=>oe.toLowerCase()===T))});if(x.length>=1){const M=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",l?` You're likely to continue **${c}** \u2014 ${x.length} known pitfall${x.length>1?"s":""} there:`:` Known pitfalls for **"${c}"** (${x.length} past failure${x.length>1?"s":""}):`,...x.slice(0,3).map(T=>` \u274C \`${T.topic}\` \u2014 ${(T.what_failed??T.what_worked).slice(0,80)}`),""];e.splice(2,0,...M)}}}if(t){const a=Date.now()-6048e5,g=u.filter(d=>d.author&&d.author!==t&&new Date(d.ts).getTime()>a);if(g.length>0){const d=new Map;for(const c of g){const l=c.author;d.has(l)||d.set(l,[]),d.get(l).push(c)}e.push(`\u{1F465} **Team this week** (${g.length} lesson${g.length>1?"s":""} from teammates):`);for(const[c,l]of d){e.push(` \u{1F464} **${c}**:`);for(const x of l.slice(0,3)){const L=x.outcome==="success"?"\u2705":x.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${L} \`${x.topic}\` \u2014 ${x.what_worked.slice(0,80)}`)}l.length>3&&e.push(` \u2026 and ${l.length-3} more`)}e.push("")}}try{const a=await h.get("cachly:crystal:latest");if(a){const g=B(a,null);if(g&&Math.round((Date.now()-new Date(g.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${g.label} \xB7 ${g.session_count} sessions compressed):`);for(const c of g.top_patterns.slice(0,3))e.push(` \u2022 **${c.category}** (${c.count}\xD7): ${c.insight.slice(0,90)}`);e.push("")}}}catch{}try{const a=await h.hgetall(`cachly:roadmap:${y}`);if(a&&Object.keys(a).length>0){const g={critical:0,high:1,medium:2,low:3},d={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},c=new Set(["planned","in-progress","blocked"]),l=Object.values(a).flatMap(M=>{const T=B(M,null);return T?[T]:[]}),x=l.filter(M=>c.has(M.status)).sort((M,T)=>M.status==="in-progress"&&T.status!=="in-progress"?-1:T.status==="in-progress"&&M.status!=="in-progress"?1:(g[M.priority]??99)-(g[T.priority]??99)),L=l.filter(M=>M.status==="done").length;if(x.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${x.length} open \xB7 ${L} done):`);for(const M of x.slice(0,5)){const T=M.status==="in-progress"?"\u26A1":M.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${T} ${d[M.priority]??"\u26AA"} \`${M.id}\` **${M.title}**`)}x.length>5&&e.push(` \u2026 and ${x.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(n&&n.length>3)try{const a=n.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2).slice(0,5),g=[];for(const l of a){const x=(await G()).filter(L=>L.slice(F.length).includes(l));for(const L of x.slice(0,3)){const M=await h.get(L);if(!M)continue;const T=B(M,null);if(!T)continue;const oe=await h.smembers(`cachly:ckg:idx:from:${T.id}`);for(const Q of oe.slice(0,15)){const we=await h.get(Q);if(!we)continue;const ce=B(we,null);if(!ce||ce.edgeType!=="causes"&&ce.edgeType!=="co-occurs"&&ce.edgeType!=="fixes"||ce.confidence<.35)continue;const ke=ce.edgeType==="fixes"?`cachly:lesson:best:${ce.from}`:`cachly:lesson:best:${ce.to}`,ve=await h.get(ke),p=B(ve,null);g.push({concept:T.id,edgeType:ce.edgeType,target:ce.to,confidence:ce.confidence,lesson:p??void 0})}}}const d=new Set,c=g.filter(l=>{const x=`${l.concept}:${l.target}`;return d.has(x)?!1:(d.add(x),!0)}).sort((l,x)=>x.confidence-l.confidence).slice(0,4);if(c.length>0){e.push(`\u{1F52E} **Predicted risks for "${n}"** (PPE pre-fetch):`);for(const l of c){const x=Math.round(l.confidence*100),L=l.edgeType==="causes"?"\u26A1":l.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${L} **${x}%** \`${l.concept}\` ${l.edgeType} \`${l.target}\``),l.lesson?.what_worked&&e.push(` \u2705 ${l.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${n}")\`_`),e.push("")}}catch{}try{const a=await h.get("cachly:mcm:calibration:last"),g=B(a,null)?.ts??0;if((Date.now()-g)/864e5>=30&&u.length>=5){const c=u.filter(x=>x.outcome==="success"&&(x.recall_count??0)>0),l=u.filter(x=>(x.recall_count??0)>0);if(l.length>=3){const x=l.length>0?c.length/l.length:1,L=[],M=new Map;for(const T of l){const oe=T.topic.split(":")[0]??"other";M.has(oe)||M.set(oe,{success:0,total:0});const Q=M.get(oe);Q.total++,T.outcome==="success"&&Q.success++}for(const[T,oe]of M)oe.total>=2&&oe.success/oe.total<.6&&L.push(T);await h.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:x,recalled:l.length,low_precision_domains:L})),(L.length>0||x<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${l.length} recalled lessons):`),e.push(` Overall precision: **${(x*100).toFixed(0)}%** recalled lessons actually worked`),L.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${L.map(T=>`\`${T}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await h.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const a=await de("/api/v1/syndication/stats");a.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${a.total_lessons.toLocaleString()} lessons \xB7 ${a.total_confirms.toLocaleString()} confirms \xB7 +${a.added_last_7_days} this week`),e.push(""))}catch{}const fe=u.filter(a=>a.outcome==="failure"||a.outcome==="partial").length>0,re=u.some(a=>a.outcome==="success"&&Pe(a)<at);if(u.length===0||fe||re){const a=[];u.length===0&&a.push("brain is empty"),fe&&a.push("open failures"),re&&a.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${a.join(", ")}._`)}try{if(await h.get(`cachly:prefs:auto_changelog:${y}`).catch(()=>null)!=="false"&&C?.ts&&!k){const d=new Date(C.ts).getTime();if(!Number.isNaN(d)){const c=u.filter(l=>{const x=new Date(l.ts).getTime();return!Number.isNaN(x)&&x>d});if(c.length>0){const l=Math.round((Date.now()-d)/6e4),x=l<60?`${l}m`:l<1440?`${Math.round(l/60)}h`:`${Math.round(l/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${c.length} new lesson${c.length!==1?"s":""} since your last session** (${x} ago):`);const L=new Map;for(const M of c.slice(0,20)){const T=M.topic.includes(":")?M.topic.split(":")[0]:"general",oe=L.get(T)??[];oe.push(M),L.set(T,oe)}for(const[M,T]of L){e.push(` **${M}**`);for(const oe of T){const Q=oe.outcome==="failure"?"\u274C":oe.severity==="critical"?"\u{1F6A8}":oe.severity==="major"?"\u26A0\uFE0F":"\u2705",we=(oe.outcome==="failure"?oe.what_failed:oe.what_worked)??"";e.push(` ${Q} \`${oe.topic}\`${we?` \u2014 ${we.slice(0,80)}`:""}`)}}c.length>20&&e.push(` \u2026 and ${c.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${y}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
35
- `)}case"session_start_summary":{const{instance_id:y,focus:n,top_n:t=10,author:r=""}=U;if(!n||!n.trim())throw new Error("focus is required for session_start_summary");const m=Math.min(Math.max(1,Math.floor(Number(t)||10)),25),h=await Y(y),S=[],i=h.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,j)=>{i.on("data",ie=>S.push(...ie)),i.on("end",e),i.on("error",j)});const u=[];if(S.length>0){const e=await h.mget(...S);for(const j of e){const ie=B(j??null,null);ie&&u.push(ie)}}if(u.length===0)return["\u{1F9E0} Brain Summary \u2014 no lessons yet","","Your brain is empty. Use `learn_from_attempts` after solving tasks to build it up.",`\u{1F4A1} Tip: \`brain_seed_starter(instance_id="${y}")\` to bootstrap with 16 universal lessons.`].join(`
36
- `);const A=u.length>m,s=n.toLowerCase().split(/\s+/).filter(Boolean),w=Date.now(),C=u.map(e=>{const j=s.filter(Z=>e.topic.toLowerCase().includes(Z)).length,ie=s.filter(Z=>(e.tags??[]).some(fe=>fe.toLowerCase().includes(Z))).length,k=j*2+ie,ge=Math.max(0,e.recall_count??0),le=Math.min(1.5,Math.log1p(ge)/10),F=e.severity==="critical"?1:e.severity==="major"?.5:0,O=(w-new Date(e.verified_at??e.ts).getTime())/864e5,G=O<30?.5*(1-O/30):0,se=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,R=k+le+F+G+se;return{lesson:e,score:R}});C.sort((e,j)=>j.score!==e.score?j.score-e.score:new Date(j.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const f=(A?C.slice(0,m):C).map(e=>e.lesson),o=u.length,N=f.length,I=[A?`\u{1F9E0} Brain Summary \u2014 top ${N} of ${o} lessons for "${n}"`:`\u{1F9E0} Brain Summary \u2014 all ${N} lesson${N!==1?"s":""} for "${n}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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 f){const j=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",ie=e.severity?`[${e.severity}] `:"[minor] ",k=e.recall_count??0,ge=k>0?` (\u2713 recalled ${k}\xD7)`:"",le=e.what_worked.slice(0,110),F=bn(e.author,r);I.push(`${j} ${ie}\`${e.topic}\` \u2014 ${le}${ge}${F}`)}I.push("");const E=$n(f,r);return E>0&&I.push(`\u{1F465} ${E} of these ${E===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),A?I.push(`\u{1F4A1} Showing top ${N} of ${o} lessons \xB7 \`session_start\` for full briefing`):I.push(`\u{1F4A1} All ${N} lesson${N!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),I.join(`
37
- `)}case"session_end":{const{instance_id:y,summary:n,files_changed:t=[],lessons_learned:r,workspace_path:m=""}=U,h=await Y(y),S=new Date;let i;const u=await h.get("cachly:session:current");if(!u)return"\u26A0\uFE0F No active session found.\n\nRun `session_start` first to begin tracking a session, then call `session_end` when you're done.";const A=B(u,null);A?.started&&(i=Math.round((S.getTime()-new Date(A.started).getTime())/6e4));let s=[];try{s=(await h.lrange("cachly:session:decision-log",0,-1)).flatMap(ie=>{const k=B(ie,null);return k?[k]:[]}),await h.del("cachly:session:decision-log")}catch{}const w=Ys(y);Zs(y);const C={ts:S.toISOString(),summary:n,files_changed:t,...w.recalls>0?{memory_cost:w}:{},...r!==void 0?{lessons_learned:r}:{},...i!==void 0?{duration_min:i}:{},...s.length>0?{decision_log:s}:{}};await h.set("cachly:session:last",JSON.stringify(C)),await h.lpush("cachly:session:history",JSON.stringify(C)),await h.ltrim("cachly:session:history",0,49),await h.expire("cachly:session:history",90*86400),await h.del("cachly:session:current");const f=[];try{const j=/\b(fixed|deployed|added|removed|refactored|migrated|updated|resolved|implemented|improved|optimized|configured|created|deleted|disabled|enabled|discovered|found|learned|debugged|patched|upgraded|installed|tested|built|rewrote|moved|renamed|split|merged|extracted)\b/i,ie=n.split(/[.!\n]+/).map(k=>k.trim()).filter(k=>k.length>20&&j.test(k));for(const k of ie.slice(0,6)){const le=k.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(R=>R.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(R)).slice(0,4).join("-");if(!le)continue;const F=`auto:${le}`,O=`cachly:lesson:best:${F}`,G=await h.get(O);if(G)try{if(JSON.parse(G).outcome==="success")continue}catch{}const se={topic:F,outcome:"success",what_worked:k,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};await h.set(O,JSON.stringify(se)),await h.expire(O,90*86400),f.push(F)}}catch{}const o=[];if(m)try{const j=u?(()=>{try{return JSON.parse(u).started??""}catch{return""}})():"",ie=j?`--since="${j}"`:'--since="1 hour ago"',k=nt(`git -C "${m}" log ${ie} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(k){const ge=/\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,le=k.split("|||ENDE").map(F=>F.trim()).filter(Boolean);for(const F of le.slice(0,10)){const[O,G,se,R]=F.split("|||");if(O)try{const c=nt(`git -C "${m}" diff-tree --no-commit-id --name-only -r --root "${O}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),x=c?c.split(`
38
- `).map(M=>M.trim()).filter(Boolean).slice(0,12):[],L=[];for(const M of x)L.push(await it(h,M));for(let M=0;M<L.length;M++)for(let T=M+1;T<L.length;T++)await be(h,L[M],"co-occurs",L[T],!0),await be(h,L[T],"co-occurs",L[M],!0)}catch{}if(!G||!ge.test(G))continue;const Z=(se??"").trim();if(Z.length<120)continue;const fe=G.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(!fe)continue;const re=`git:${fe}`,a=`cachly:lesson:best:${re}`;if(await h.get(a))continue;const d={topic:re,outcome:"success",what_worked:`${G}
17
+ `)}`}case"smart_recall":{const w=Date.now(),{instance_id:o,query:t,threshold:r=.78,author:m="",context_files:u=[]}=K,C=Array.isArray(u)?u.filter(h=>typeof h=="string"):[];_e("smart_recall: Anfang");const $=$s(o);if($&&!$.laeuft){if((await ue(`/api/v1/instances/${o}`).catch(()=>null))?.status==="provisioning"){const g=Date.now()-w;return H(o).then(_=>Ft(_,o,String(t??""),g)).catch(()=>{}),_e("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),kt(String(t??""),{startet:!0,lerntAusGit:St(o)})}$.laeuft=!0}const n=await H(o);_e("smart_recall: Verbindung steht"),Kt(n,void 0,2);let D=new Set,a=!1;m&&(D=await _t(n,o,m).catch(()=>new Set),a=await nt(n,o,m).catch(()=>null)==="admin");const b=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],x=await bs(n,b);if(!x)return Ft(n,o,String(t??""),Date.now()-w),_e("smart_recall: Brain leer \u2014 sofort geantwortet"),kt(String(t??""),{startet:!1,lerntAusGit:St(o)});const p=x.docs.reduce((h,g)=>h+(g.key.startsWith("cachly:lesson:best:")?1:0),0),i=await qe(n,b,t,25);_e(`smart_recall: Wortsuche fertig (${i.length} Treffer)`);const T=vs(i);let y=!1,v=null;const A=await(async()=>{if(!Le())return et(rs,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),T;try{if(await ye.aktualisiere(n),_e(`smart_recall: Vektorbestand geladen (${ye.groesse})`),ye.groesse===0)return p>0&&et(is,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),T;const h=await ke(t);if(_e("smart_recall: Frage eingebettet"),!h?.length)return et(cs,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),T;await ct.aktualisiere(n),await lt.aktualisiere(n),await Fe.aktualisiere(n),await Ue.aktualisiere(n);const g=ye.groesse>0?Ue.groesse/ye.groesse:0;g<Dt&&ye.groesse>0&&Gn(n,3);const _=g>=Dt?ke(t,{modell:Ve}).catch(()=>null):null,q=T.filter(U=>U.key.startsWith("cachly:lesson:best:")).map(U=>U.key.slice(19)),Z=U=>Math.max(ye.naehe(h,U),ct.naehe(h,U)),G=[...Fe.themen()],S=(G.length>0?G:ye.aehnlichste(h,500).map(U=>U.topic)).map(U=>({t:U,n:Z(U)})).sort((U,fe)=>fe.n-U.n).slice(0,Bt).map(U=>U.t),E=[...new Set([...q,...S])],R=S.slice(0,3).map(U=>ye.rohvektor(U)).filter(Boolean),P=R.length?Ks(h,R):h,J=It(t),V=Fe.statistik,se=E.map(U=>{const fe=new Set([...It(Fe.textVon(U))].map(Hs));return{naeheText:ye.naehe(h,U),naeheThema:ct.naehe(h,U),naeheRueckkopplung:ye.naehe(P,U),seltenheitsDeckung:V?V.deckung(J,fe):0,besterZeuge:V?V.besterZeuge(J,fe):0}});let le=Gs(se,Js);{const U=[...le].sort((fe,be)=>be-fe);v=U.length>1?U[0]-U[1]:null}if(lt.groesse>0){const U=E.map(be=>{const ve=lt.besteNaehe(h,be);return ve>=hn?ve:-2}),fe=Mt(U);le=le.map((be,ve)=>be+dn*fe[ve])}if(_){const U=await _;if(U?.length){const fe=Mt(E.map(be=>Ue.naehe(U,be)));le=le.map((be,ve)=>be+nn*fe[ve])}}let $e=E.map((U,fe)=>({t:U,p:le[fe]})).sort((U,fe)=>fe.p-U.p).map(U=>U.t);if(Cs(o)&&$e.length>1){const U=$e.slice(0,Rt),fe=$e.slice(Rt),be=new Map(E.map((Ge,Oe)=>[Ge,le[Oe]]));_e("smart_recall: Leser Anfang");const ve=await xs(t,U.map(Ge=>Fe.leserTextVon(Ge)),{instanceId:o});_e(`smart_recall: Leser ${ve?"fertig":"ohne Ergebnis"}`),ve&&($e=[...Ts(U.map(Oe=>be.get(Oe)??0),ve).map(Oe=>U[Oe]),...fe])}const Ie=new Map(T.map(U=>[U.key,U])),me=[];for(const U of $e){const fe=`cachly:lesson:best:${U}`,be=Ie.get(fe);if(be){me.push(be),Ie.delete(fe);continue}const ve=await n.get(fe).catch(()=>null);ve&&me.push({key:fe,content:ve,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return me.push(...Ie.values()),Qs&&Xs({frage:t.slice(0,200),themen:E,ausWortsuche:q.length,ausSinnsuche:S.length,obergrenze:Bt,gezeigt:$e.slice(0,10)}),y=!0,me}catch(h){return await Je(n,ls,`der Bedeutungspfad brach ab (${h instanceof Error?h.message:String(h)}) \u2014 diese Suche lief nur ueber Woerter`),T}})();_e("smart_recall: Bedeutungspfad fertig"),ut(n),rt(n,String(t??""),Date.now()-w);{const h=A.filter(g=>g.key.startsWith("cachly:lesson:best:")).slice(0,3).map(g=>g.key.slice(19));if(h.length>0){const g={ts:new Date().toISOString(),themen:h};(async()=>{const _=Tt(o);await n.lpush(_,JSON.stringify(g)),await n.ltrim(_,0,js-1)})().catch(()=>{})}{const g={ts:new Date().toISOString(),frage:t.slice(0,200),geliefert:h};(async()=>{const _=it(o);await n.lpush(_,JSON.stringify(g)),await n.ltrim(_,0,Et-1)})().catch(()=>{})}}if(Le()){const h=A.filter(g=>g.key.startsWith("cachly:lesson:best:")).slice(0,3).map(g=>g.key.slice(19));Bs(n,t,h,ke).catch(()=>{})}const M=[],e=A.filter(h=>h.key.startsWith("cachly:lesson:best:"));let W=0,ie=0;for(const h of e.slice(0,5)){const g=await n.get(h.key).catch(()=>null);if(g){const _=B(g,null);if(_?.state==="archived")continue;if(_){const q=new Date().toISOString(),Z={..._,recall_count:(_.recall_count??0)+1,last_recalled_at:q};n.set(h.key,JSON.stringify(Z)).catch(()=>{});const G=wt(_)?mt(_):0;if(G>0&&n.incrbyfloat(`cachly:stats:time_saved_mins:${o}`,G).catch(()=>{}),_.author&&m&&_.author!==m){W++,n.sadd(`cachly:stats:reuse_pairs:${o}`,`${m}<-${_.author}`).catch(()=>{});const S=`person:${pe(m)}`,E=`person:${pe(_.author)}`;we(n,S,"collaborates",E,!0).catch(()=>{}),we(n,E,"collaborates",S,!0).catch(()=>{})}_.outcome==="success"&&ie++,_.outcome==="success"&&(_.recall_count??0)>=1&&!He(_)&&M.push({topic:h.key.replace("cachly:lesson:best:",""),severity:_.severity??"major",recall_count:(_.recall_count??0)+1,savedMins:G,ts:_.ts,author:_.author})}}}ie>0&&n.set(`cachly:stats:first_recall_at:${o}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),e.length>0&&(n.incr(`cachly:stats:recalls_total:${o}`).catch(()=>{}),W>0&&n.incr(`cachly:stats:cross_author_recalls:${o}`).catch(()=>{})),_e("smart_recall: Treffer gezaehlt");const k=await ue(`/api/v1/instances/${o}`).catch(()=>null);_e("smart_recall: Tarif abgefragt");const he=!k?.tier||k.tier.toLowerCase()==="free",oe=[];if(!he&&k?.vector_token&&Le())try{const h=await ke(t),g=`https://api.cachly.dev/v1/sem/${k.vector_token}`,_=await fetch(`${g}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:h,namespace:"cachly:ctx",threshold:r,top_k:5}),signal:AbortSignal.timeout(8e3)});if(_.ok){const q=await _.json();for(const Z of q.filter(G=>G.found&&G.id)){const G=Z.id.replace("ctx:","").split(":"),S=G[0],E=G.slice(1).join(":"),R=`cachly:ctx:${S}:${E}`,P=await n.get(R).catch(()=>null);oe.push({key:R,similarity:Z.similarity??0,content:P??"(evicted)"})}}}catch{}const F=A.map(h=>h.score),O=F.length?Math.min(...F):0,Y=F.length&&Math.max(...F)-O||1,Q=h=>(h-O)/Y,X=new Map,ne=y?Rs(A.map(h=>Q(h.score))):null,ce=new Map;for(const[h,g]of A.entries()){const _=Q(g.score),q=ne?ne[h]:_;ne&&X.set(g.key,h),ce.set(g.key,{key:g.key,content:g.content,bm25Score:_,hausWert:q,hybridScore:q*(oe.length>0?.7:1),matchedWords:g.matchedWords,matchType:"keyword",subQuery:g.subQuery,wortBelege:g.wortBelege})}for(const h of oe){const g=ce.get(h.key);g?(g.semScore=h.similarity,g.hybridScore=(g.hausWert??0)*.6+h.similarity*.4,g.matchType="hybrid"):ce.set(h.key,{key:h.key,content:h.content,semScore:h.similarity,hybridScore:h.similarity*.5,matchType:"semantic"})}try{const h=ot(t).filter(q=>q.length>=4).slice(0,4),g=new Set;for(const q of h){const Z=n.scanStream({match:`cachly:ckg:node:*${q}*`,count:20});await new Promise((G,S)=>{Z.on("data",E=>{for(const R of E.slice(0,5))g.add(R.replace("cachly:ckg:node:",""))}),Z.on("end",G),Z.on("error",S)})}const _=new Set;for(const q of[...g].slice(0,12)){const Z=await n.smembers(`cachly:ckg:idx:to:${q}`);for(const G of Z.slice(0,6)){const S=await n.get(G);if(!S)continue;const E=B(S,null);if(!E||E.edgeType!=="fixes"||E.confidence<.35||_.has(E.from))continue;_.add(E.from);const R=`cachly:lesson:best:${E.from}`,P=ce.get(R);if(P)P.ckgScore=Math.max(P.ckgScore??0,E.confidence),P.hybridScore=P.hybridScore*.88+E.confidence*.12,P.matchType==="keyword"&&(P.matchType="hybrid");else{const J=await n.get(R).catch(()=>null);if(!J)continue;ce.set(R,{key:R,content:J,ckgScore:E.confidence,hybridScore:E.confidence*.3,matchType:"ckg"})}}}}catch{}if(_e("smart_recall: Sinn-Dienst und CKG fertig"),C.length>0){const h=new Set(C.map(g=>g.replace(/\\/g,"/")));for(const g of ce.values()){if(!g.key.startsWith("cachly:lesson:best:"))continue;const _=B(g.content,{});(Array.isArray(_.file_paths)?_.file_paths.filter(Z=>typeof Z=="string").map(Z=>Z.replace(/\\/g,"/")):[]).some(Z=>h.has(Z))&&(g.hybridScore*=1.15,g.contextBoost=!0)}}for(const h of ce.values()){if(h.matchType!=="semantic"&&h.matchType!=="ckg")continue;const g=Ss({key:h.key,content:h.content});g&&(h.hybridScore*=ks(g))}const re=[...ce.values()].filter(h=>{if(!h.key.startsWith("cachly:lesson:best:"))return!0;const g=Me(h.content);return!(!Re(g)||!bt(g?.group,D,a))}),s=ne?Ds(re,X):re.sort((h,g)=>g.hybridScore-h.hybridScore),d=[];for(const h of s){if(!h.key.startsWith("cachly:lesson:best:"))continue;const g=B(h.content,{});g.gilt_bis&&Date.parse(String(g.gilt_bis))<Date.now()&&d.push(`\u23F3 \`${h.key.replace("cachly:lesson:best:","")}\` galt bis ${String(g.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const _=B(h.content,{});if(_.pruefung_gefallen_am){const q=h.key.replace("cachly:lesson:best:",""),Z=String(_.pruefung_gefallen_am).slice(0,10),G=String(_.pruefung_befund??"").trim().slice(0,200);d.push(`\u274C \`${q}\` \u2014 Pruefung am ${Z} FEHLGESCHLAGEN`+(G?`: ${G}`:""))}}{const h=new Set(s.map(g=>g.key));for(let g=s.length-1;g>=0;g--){const _=s[g];if(!_.key.startsWith("cachly:lesson:best:"))continue;const q=B(_.content,{});if(!q.ersetzt_durch)continue;const Z=String(q.ersetzt_grund??"").trim(),G=_.key.replace("cachly:lesson:best:","");if(h.has(`cachly:lesson:best:${q.ersetzt_durch}`))s.splice(g,1),d.push(`\u21B7 \`${G}\` verdraengt \u2014 ersetzt durch \`${q.ersetzt_durch}\`${q.ersetzt_am?` am ${q.ersetzt_am.slice(0,10)}`:""}${Z?` \u2014 Grund: ${Z}`:" \u2014 Grund nicht erfasst"}`);else if(await n.get(`cachly:lesson:best:${q.ersetzt_durch}`)){const S=Me(await n.get(`cachly:lesson:best:${q.ersetzt_durch}`));Re(S)?d.push(`\u26A0\uFE0F \`${G}\` ist ersetzt durch \`${q.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${q.ersetzt_durch}")\``):d.push(`\u21B7 \`${G}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else d.push(`\u21A9\uFE0F \`${G}\` war ersetzt durch \`${q.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const f=[];{await ye.aktualisiere(n).catch(()=>{});const h=s.slice(0,8).filter(g=>g.key.startsWith("cachly:lesson:best:"));for(let g=0;g<h.length;g++)for(let _=g+1;_<h.length;_++){const q=h[g].key.replace("cachly:lesson:best:",""),Z=h[_].key.replace("cachly:lesson:best:",""),G=ye.rohvektor(q),S=ye.rohvektor(Z);if(!G||!S)continue;let E=0,R=0,P=0;for(let se=0;se<G.length;se++)E+=G[se]*S[se],R+=G[se]*G[se],P+=S[se]*S[se];if((R>0&&P>0?E/(Math.sqrt(R)*Math.sqrt(P)):0)<on)continue;const V=se=>{const le=B(se??"",{});return String(le.verified_at??le.ts??"").slice(0,10)||"ohne Datum"};f.push(`\u26A0\uFE0F \`${q}\` (${V(h[g].content)}) und \`${Z}\` (${V(h[_].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}f.length>3&&(f.length=3)}if(d.push(...f),s.length>=2){const h=s[0].hybridScore,g=s[Math.min(4,s.length-1)].hybridScore,_=Math.max(0,h-g);(async()=>{try{await n.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(_.toFixed(4)),n:s.length})),await n.ltrim("cachly:recall:spread",0,199)}catch{}})()}const c=us();let l="",N=null;if(c!==null){l=hs();const h=s[0]?.hybridScore??0,g=ds(s.map(_=>({key:_.key,content:_.content,punktzahl:_.hybridScore})),l,c,h);g.weggelassenesThema!==void 0?s.splice(0,1):g.markierungGesetzt&&s[0]&&g.treffer[0]&&(s[0]={...s[0],content:g.treffer[0].content}),N={frage:t,hoechstePunktzahl:h,themen:[],zulassungsfaehig:g.zulassungsfaehig,zulassungsGrund:g.zulassungsGrund,zuteilung:g.zuteilung,weggelassenesThema:g.weggelassenesThema,markierungGesetzt:g.markierungGesetzt}}_e("smart_recall: Notizen und Duplikate fertig");const L=await Gt(o,ue);_e("smart_recall: Abruf-Grenze abgefragt");const I=L.reached,j=zt({ueberLimit:I,gesamt:s.length,volleTiefe:pn}),te=process.env.CACHLY_RECALL_COMPACT==="1",ae=(()=>{const h=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(h)?Math.min(20,Math.max(1,h)):5})(),ge=te?Math.min(ae,j.sichtbar):j.sichtbar,z=[`\u{1F9E0} **Smart Recall** for: _"${t}"_
18
+ `];L.goodwillMessage&&z.push(`${L.goodwillMessage}
19
+ `);const Ce={critical:0,major:1,minor:2},de=M.sort((h,g)=>(Ce[h.severity]??1)-(Ce[g.severity]??1))[0];if(de){const h=G=>G>=60?`${G/60}h`:`${G}min`,g=(()=>{if(!de.ts)return null;const G=new Date(de.ts);if(isNaN(G.getTime()))return null;const S=new Date,E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return G.getFullYear()===S.getFullYear()?`${G.getDate()} ${E[G.getMonth()]}`:`${G.getDate()} ${E[G.getMonth()]} ${G.getFullYear()}`})(),_=de.severity==="critical"?120:de.severity==="major"?60:20,q=de.author&&de.author!==m?` \xB7 by @${de.author}`:"",Z=g?` \xB7 learned ${g} (was a ${h(_)} debug)`:"";z.push(`> \u{1F4A1} **Brain saved you ~${h(de.savedMins)} here** \u2014 \`${de.topic}\`${Z} \xB7 recalled ${de.recall_count}\xD7${q}
20
+ `)}W>0&&z.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${W} of these lesson${W!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
21
+ `);const xe=s.filter(h=>h.contextBoost).length;xe>0&&z.push(`> \u{1F4C1} **Personalized** \u2014 ${xe} lesson${xe!==1?"s":""} boosted because ${xe!==1?"they match":"it matches"} your current file context (${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""})
22
+ `);const Ne=ys(t);Ne.length>1&&z.push(`_Detected ${Ne.length} sub-topics:_ ${Ne.map((h,g)=>`${g+1}. "${h}"`).join(", ")}
23
+ `);const Ae=os(s.map(h=>({wortBelege:h.wortBelege,semScore:h.semScore,ckgScore:h.ckgScore})));if(Ae.schweigen)return ht(n,o,"schweigen"),z.push(ss(Ae)),z.join(`
24
+ `);const Ee=qs(v);if(Ee&&z.push(Ee,""),ht(n,o,Ee?"knapp":"beantwortet"),s.length>0){const h=s.some(_=>_.ckgScore!==void 0),g=oe.length>0&&h?"keyword + semantic + CKG hybrid":oe.length>0?"keyword + semantic hybrid":h?"keyword + CKG hybrid":"keyword";if(z.push(`### \u{1F50D} Results (${s.length} \u2014 ${g})
25
+ `),Ae.belegte<s.length){const _=[];for(const Z of s){if(!Z.key.startsWith("cachly:lesson:best:")||!as({wortBelege:Z.wortBelege,semScore:Z.semScore,ckgScore:Z.ckgScore}))continue;const G=B(Z.content,{}),S=Date.parse(G.verified_at??G.ts??"");Number.isFinite(S)&&_.push(Math.floor((Date.now()-S)/864e5))}const q=ns(_);z.push(`> \u{1F4CA} ${Ae.belegte} von ${s.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(q?` \u23F3 ${q}`:"")+`
26
+ `)}if(d.length>0&&z.push(...d.map(_=>`> ${_}`),""),Ne.length>1){const _=new Map,q=zt({ueberLimit:I,gesamt:s.length,volleTiefe:gn});for(const S of s.slice(0,q.sichtbar)){const E=S.subQuery??t;_.has(E)||_.set(E,[]),_.get(E).push(S)}for(const[S,E]of _){z.push(`**Topic: "${S}"** (${E.length} results)
27
+ `);for(const R of E.slice(0,te?2:4)){const P=R.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),J=R.matchType==="ckg"?`CKG: ${(R.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:R.ckgScore!==void 0&&R.bm25Score!==void 0?`BM25: ${R.bm25Score.toFixed(2)}, CKG: ${R.ckgScore.toFixed(2)}, \u{1F500} hybrid`:R.matchType==="hybrid"?`BM25: ${(R.bm25Score??0).toFixed(2)}, sem: ${((R.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:R.matchType==="semantic"?`sem: ${((R.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(R.bm25Score??0).toFixed(2)}, matched: ${R.matchedWords?.join(", ")}`,V=yt(R.key,R.content,300);if(z.push(te?` **${P}**`:` **${P}** _(${J})_`),R.key.startsWith("cachly:lesson:best:")){const se=await n.get(R.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await n.get(R.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),le=se?B(se,{}):{};le.title&&z.push(` \u{1F4D6} **${le.title}** \u2014 ${le.summary??""}`)}for(const se of V)z.push(` > ${se}`);z.push("")}}const Z=[..._.keys()],G=Ne.filter(S=>!Z.includes(S));G.length>0&&z.push(`
28
+ \u26A0\uFE0F **No results for:** ${G.map(S=>`"${S}"`).join(", ")}`)}else for(const _ of s.slice(0,ge)){const q=_.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let Z="";if(_.key.startsWith("cachly:lesson:best:")){const R=B(_.content,{});R.author&&(Z=` \xB7 \u{1F464} ${R.author}`)}const G=_.contextBoost?" \xB7 \u{1F4C1} context match":"",S=_.matchType==="hybrid"?`BM25: ${(_.bm25Score??0).toFixed(2)}, sem: ${((_.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:_.matchType==="semantic"?`sem: ${((_.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(_.bm25Score??0).toFixed(2)}, matched: ${_.matchedWords?.join(", ")}`,E=yt(_.key,_.content,400);z.push(te?`**${q}**`:`**${q}**${Z}${G} _(${S})_`);{const R=B(_.content??"",{});R.entscheidung?.gegen&&z.push(At({gegen:R.entscheidung.gegen,grund:R.entscheidung.grund??null}))}if(_.key.startsWith("cachly:lesson:best:")){const R=await n.get(_.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await n.get(_.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),P=R?B(R,{}):{};P.title&&z.push(`\u{1F4D6} **${P.title}** \u2014 ${P.summary??""}`)}for(const R of E)z.push(`> ${R}`);z.push("")}if(I&&j.zurueckgehalten>0){const _=j.zurueckgehalten;z.push(`\u{1F512} **Free recall limit reached** (${L.used}/${L.limit} this month). Showing your top match; ${_} further relevant lesson${_!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${On}
29
+ `)}}else{z.push(`\u26A0\uFE0F No matches found for: "${t}"`),d.length>0&&z.push("",...d.map(_=>`> ${_}`));const h=ot(t),g=[];if(vt.size>0&&h.length>0)for(const _ of h.slice(0,3)){if(_.length<4)continue;let q=3,Z="";for(const G of vt){if(G.length<3||Math.abs(G.length-_.length)>4)continue;const S=_s(_,G);S>0&&S<q&&(q=S,Z=G)}Z&&g.push(`"${Z}" (instead of "${_}")`)}g.length>0?z.push(`\u{1F4A1} **Did you mean:** ${g.join(", ")}?`):(z.push(`
30
+ \u{1F4A1} Tips:`),z.push(" \u2022 Try different keywords"),z.push(" \u2022 Use `list_remembered` to see available context"),z.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!te&&s.length>0){z.push(""),z.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 h=s.filter(g=>g.key.startsWith("cachly:lesson:best:")).map(g=>g.key.slice(19));if(h.length>0)try{await n.setex(`cachly:letzter-recall:${o}`,7200,JSON.stringify({frage:t,themen:h}))}catch{}}if(te&&s.length>0){const h=Ut();h&&(z.push(""),z.push(h))}if(c!==null&&N){const h=s.slice(0,ge).filter(g=>g.key.startsWith("cachly:lesson:best:")).map(g=>g.key.slice(19));return fs(n,l,{...N,themen:h},z.join(`
31
+ `))}return z.join(`
32
+ `)}case"session_start":{const{instance_id:w,focus:o="",author:t="",provider:r="",workspace_path:m=""}=K,u=await H(w),C=[],$=u.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((s,d)=>{$.on("data",f=>C.push(...f)),$.on("end",s),$.on("error",d)});const n=[];if(C.length>0){const s=await u.mget(...C);for(const d of s){const f=B(d??null,null);f&&n.push(f)}}n.sort((s,d)=>new Date(d.ts).getTime()-new Date(s.ts).getTime());let D=0;const a=u.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((s,d)=>{a.on("data",f=>{D+=f.filter(c=>!c.endsWith(":meta")).length}),a.on("end",s),a.on("error",d)});const b=await u.get("cachly:session:last"),x=B(b,null),p=o.toLowerCase().split(/\s+/).filter(Boolean),i=p.length>0?n.filter(s=>p.some(d=>s.topic.toLowerCase().includes(d)||(s.tags??[]).some(f=>f.toLowerCase().includes(d)))):[];let T=0,y=0,v="";try{const s=await u.get("cachly:streak:current"),d=B(s,null),f=new Date().toISOString().slice(0,10);if(d){const c=d.last_date,l=new Date(Date.now()-864e5).toISOString().slice(0,10);c===f?(T=d.days,y=d.record):c===l?(T=d.days+1,y=Math.max(T,d.record),await u.set("cachly:streak:current",JSON.stringify({days:T,last_date:f,record:y}))):(T=1,y=d.record,await u.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:y})))}else T=1,y=1,await u.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:1}));T>=7?v=`\u{1F525} **${T}-day streak!** ${T===y?" New record!":`Best: ${y}d`}`:T>1&&(v=`\u{1F525} ${T}-day streak`)}catch{}await u.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:o,provider:r}),"EX",86400);let A=0;try{const s=await u.get(`cachly:stats:time_saved_mins:${w}`);A=parseFloat(s??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${r?` \xB7 ${r}`:""}`,""];if(v&&e.push(v,""),A>=30){const s=Math.floor(A/60),d=Math.round(A%60),f=s>0?`${s}h${d>0?` ${d}m`:""}`:`${d}m`,c=n.filter(N=>!He(N)&&(N.recall_count??0)>0).length,l=c>0?` \u2014 ${c} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${f} total**${l}`,"")}const W=await Gt(w,ue),ie=fn({used:W.used,limit:W.limit,savedMins:A});if(ie&&e.push(ie,""),W.notice&&!jt.has(w)&&(jt.add(w),e.push(W.notice,"")),x?.ts){const s=new Date(x.ts).getTime(),d=Math.floor((Date.now()-s)/864e5);if(d>=7&&!Number.isNaN(s)){const f=n.filter(c=>{const l=new Date(c.ts).getTime();return!Number.isNaN(l)&&l>s});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${d} days since your last session.`),f.length>0){const c=f.slice(0,3).map(l=>`\`${l.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${f.length} lesson${f.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${c}${f.length>3?", \u2026":""}`)}else e.push(` \u{1F9E0} ${n.length} lesson${n.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);e.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await u.get("cachly:mcp:version:last_seen")!==Ye){await u.set("cachly:mcp:version:last_seen",Ye,"EX",365*86400);const d=zn[Ye];if(d){e.push(...d,"");const f=Bn();f&&e.push(`\u{1F4CA} ${f} MCP tools`,"")}}}catch{}const k=!x&&n.length===0&&D===0;if(k&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),m?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${w}")\``),e.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),e.push(""),e.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),e.push("")),t&&!k)try{const s=`cachly:team:first_briefing:${t}`;if(!await u.get(s)){const f=n.filter(c=>c.author&&c.author!==t);if(f.length>0){await u.set(s,"1","EX",365*86400);const c=new Map;for(const l of f){const N=l.author;c.has(N)||c.set(N,[]),c.get(N).push(l)}e.push(""),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),e.push(""),e.push("Your teammates have already solved problems you're about to hit:"),e.push("");for(const[l,N]of c){e.push(` \u{1F464} **${l}** fixed ${N.length} thing${N.length>1?"s":""}:`);for(const L of N.slice(0,2)){const I=L.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${I} \`${L.topic}\` \u2014 ${L.what_worked.slice(0,90)}`)}N.length>2&&e.push(` \u2026 and ${N.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const he=await u.get("cachly:session:handoff");if(he)try{const s=JSON.parse(he),d=Math.round((Date.now()-new Date(s.ts).getTime())/6e4),f=d<60?`${d}m ago`:d<1440?`${Math.round(d/60)}h ago`:`${Math.round(d/1440)}d ago`;if(e.push(`\u{1F91D} **Handoff from previous window** (${f}):`),s.context_summary&&e.push(` ${s.context_summary}`),s.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const l of s.remaining_tasks)e.push(` - ${l}`)}s.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${s.completed_tasks.join(", ")}`);const c=(s.files_changed??[]).filter(l=>l.status==="broken"||l.status==="partial");c.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${c.map(l=>`\`${l.path}\` (${l.status}${l.description?": "+l.description:""})`).join(", ")}`),s.blocked_on&&e.push(` \u{1F6AB} **Blocked on:** ${s.blocked_on}`),s.instructions&&e.push(` \u{1F4DD} **Instructions:** ${s.instructions}`),e.push("")}catch{}const oe=await u.get("cachly:session:checkpoint");if(oe)try{const s=JSON.parse(oe),d=new Date(s.ts).getTime(),f=x?new Date(x.ts).getTime():0;if(d>f){const c=Math.round((Date.now()-d)/6e4),l=c<60?`${c}m ago`:c<1440?`${Math.round(c/60)}h ago`:`${Math.round(c/1440)}d ago`,N=s.provider?` [${s.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${N} (${l}): ${s.task}`),s.files_touched.length>0&&e.push(` Files: ${s.files_touched.slice(0,5).map(L=>`\`${L}\``).join(", ")}`),s.next_step&&e.push(` \u{1F4CD} Next step was: ${s.next_step}`),(!x||d-f>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(m&&!x)try{const{execSync:s}=await import("node:child_process"),d=s(`git -C "${m}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),f=s(`git -C "${m}" diff --stat HEAD~3 2>/dev/null || git -C "${m}" diff --stat 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim();if(d){e.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const c of d.split(`
33
+ `).slice(0,8))e.push(` ${c}`);if(f){const c=f.split(`
34
+ `).filter(l=>l.includes("|")||l.includes("changed"));if(c.length>0){e.push(" **Recent changes:**");for(const l of c.slice(0,5))e.push(` ${l.trim()}`)}}e.push("")}}catch{}if(x){const s=Math.round((Date.now()-new Date(x.ts).getTime())/6e4),d=s<60?`${s}m ago`:s<1440?`${Math.round(s/60)}h ago`:`${Math.round(s/1440)}d ago`;e.push(`\u{1F4C5} **Last session** (${d}): ${x.summary}`),x.duration_min&&e.push(` Duration: ${x.duration_min} min`),(x.files_changed??[]).length>0&&e.push(` Files: ${(x.files_changed??[]).slice(0,5).map(f=>`\`${f}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${n.length} lessons \xB7 ${D} context entries`,"");{const d=n.filter(f=>!He(f)).filter(f=>f.outcome==="success"&&(f.pinned===!0||(f.recall_count??0)>=5)).sort((f,c)=>(c.recall_count??0)-(f.recall_count??0)).slice(0,5);if(d.length>0){e.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const f of d){const c=f.severity==="critical"?"\u{1F534}":f.severity==="major"?"\u{1F7E1}":"",l=f.recall_count??0,N=f.pinned===!0?"pinned":`recalled ${l}\xD7`,L=Pe(f);e.push(` \u{1F3C6}${c} \`${f.topic}\` _(${N})_ \u2014 ${L[0]??""}`,...L.slice(1))}e.push("")}}if(n.length>=3){const s=new Map;for(const c of n){const l=c.topic.split(":")[0]??"other";s.has(l)||s.set(l,{total:0,success:0,critical:0});const N=s.get(l);N.total++,c.outcome==="success"&&N.success++,c.severity==="critical"&&N.critical++}const d=[...s.entries()].sort((c,l)=>l[1].total-c[1].total).slice(0,6),f=d.some(([,c])=>c.success<c.total*.4&&c.total>=2);if(d.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[c,l]of d){const N=Math.round(l.success/l.total*100),L=Math.round(N/10),I="\u2588".repeat(L)+"\u2591".repeat(10-L),j=l.critical>0?" \u{1F534}":N<40&&l.total>=2?" \u26A0\uFE0F":"";e.push(` ${I} ${c.padEnd(18)} ${String(N).padStart(3)}% (${l.success}/${l.total} confirmed)${j}`)}f&&e.push(" \u26A0\uFE0F _Some domains have contested beliefs \u2014 use `ckg_inspect` to review_"),e.push("")}}const F="cachly:ckg:node:";let O=null;const Y=async()=>{if(O)return O;const s=[],d=u.scanStream({match:`${F}*`,count:1e3});return await new Promise((f,c)=>{d.on("data",l=>s.push(...l)),d.on("end",f),d.on("error",c)}),O=s,s};try{const s=[],d=u.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((f,c)=>{d.on("data",l=>s.push(...l)),d.on("end",f),d.on("error",c)}),s.length>0){e.push(`\u26A1 **Active belief conflicts (${s.length}):**`);for(const f of s.slice(0,3)){const c=await u.get(f);if(!c)continue;const l=B(c,null);l&&e.push(` \u26A0\uFE0F \`${l.topic}\` \u2014 previously confirmed fix (${(l.fix_confidence*100).toFixed(0)}%, n=${l.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${pe(l.topic)}")\``)}e.push("")}}catch{}if(o&&o.length>3)try{const s=o.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(f=>f.length>3),d=[];for(const f of s.slice(0,6))await u.exists(`cachly:ckg:node:${f}`)||(await Y()).some(N=>N.startsWith(`${F}${f}`))||d.push(f);if(d.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const f of d.slice(0,3))e.push(` \u2B1C \`${f}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${f}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${f}")\` \u2014 search global commons`);e.push("")}}catch{}if(i.length>0){e.push(`\u{1F3AF} **Relevant for "${o}":**`);for(const s of i.slice(0,4)){const d=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",f=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":"",c=Pe(s);e.push(` ${d}${f} \`${s.topic}\` \u2014 ${c[0]??""}`,...c.slice(1))}e.push("")}if(n.length>0){const d=[...n].filter(c=>!He(c)).sort((c,l)=>(l.recall_count??0)-(c.recall_count??0)).filter(c=>(c.recall_count??0)>0).slice(0,3),f=(i.length>0?n.filter(c=>!i.includes(c)):n).filter(c=>!d.includes(c)).slice(0,i.length>0?3:4);if(d.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${d[0].recall_count}\xD7 before):`);for(const c of d){const l=c.outcome==="success"?"\u2705":c.outcome==="partial"?"\u26A0\uFE0F":"\u274C",N=c.severity==="critical"?"\u{1F534}":c.severity==="major"?"\u{1F7E1}":"",L=c.recall_count??0,I=c.authors??(c.author?[c.author]:[]),j=new Set(I.filter(Boolean)).size,te=j>=2&&L>=5||L>=10?" \u{1F3C6}":j>=2||L>=5?" \u2705":"",ae=L>1?` _(${L}\xD7 recalled)_`:"",ge=Pe(c);e.push(` ${l}${N}${te} \`${c.topic}\`${ae} \u2014 ${ge[0]??""}`,...ge.slice(1))}e.push("")}if(f.length>0){const c=d.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(c);for(const l of f){const N=l.outcome==="success"?"\u2705":l.outcome==="partial"?"\u26A0\uFE0F":"\u274C",L=l.severity==="critical"?"\u{1F534}":l.severity==="major"?"\u{1F7E1}":"",I=Pe(l);e.push(` ${N}${L} \`${l.topic}\` \u2014 ${I[0]??""}`,...I.slice(1))}e.push("")}}else e.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");n.length>=10&&(n.some(d=>d.author)||(e.push(`\u{1F91D} **Your Brain has ${n.length} lessons \u2014 your team could benefit instantly.**`),e.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Q=n.filter(s=>s.outcome==="failure"||s.outcome==="partial");if(Q.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${Q.length} topic${Q.length>1?"s":""} with no success yet):`);for(const s of Q.slice(0,3))e.push(` \u274C \`${s.topic}\` \u2014 ${(s.what_failed??s.what_worked).slice(0,80)}`);e.push("")}const X=n.filter(s=>s.outcome!=="success"&&s.outcome!=="partial"?!1:Ke(s)<pt);if(X.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Vt}d \u2014 verify before applying):`);for(const s of X.slice(0,4)){const d=Ke(s),f=Math.round((Date.now()-new Date(s.verified_at??s.ts).getTime())/864e5),c=d<qt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${c} \`${s.topic}\` \u2014 ${f}d stale, ${(d*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const ne=x;if(ne?.decision_log?.length){const s=ne.decision_log,d=s.filter(c=>c.outcome==="success"),f=s.filter(c=>c.outcome==="failure");e.push(`\u{1F3AC} **Last session decisions** (${s.length} lessons stored):`),d.length>0&&e.push(` \u2705 Worked: ${d.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),f.length>0&&e.push(` \u274C Failed: ${f.slice(0,3).map(c=>`\`${c.topic}\``).join(", ")}`),e.push("")}{const s=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"]),d=N=>{const L=new Set;for(const I of N)for(const j of I.toLowerCase().split(/[/\\._-]/))j.length>3&&!s.has(j)&&L.add(j);return[...L]};let f=p,c=o,l=!1;if(f.length===0&&x){const N=d(x.files_changed??[]),L=(x.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(I=>I.length>3&&!s.has(I));f=[...new Set([...N,...L])],c="where you left off last session",l=!0}if(f.length>0){const N=n.filter(L=>{if(L.outcome==="success")return!1;const I=L.topic.split(":")[0];return f.some(j=>L.topic.toLowerCase().includes(j)||I===j||(L.tags??[]).some(te=>te.toLowerCase()===j))});if(N.length>=1){const I=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",l?` You're likely to continue **${c}** \u2014 ${N.length} known pitfall${N.length>1?"s":""} there:`:` Known pitfalls for **"${c}"** (${N.length} past failure${N.length>1?"s":""}):`,...N.slice(0,3).map(j=>` \u274C \`${j.topic}\` \u2014 ${(j.what_failed??j.what_worked).slice(0,80)}`),""];e.splice(2,0,...I)}}}if(t){const s=Date.now()-6048e5,d=n.filter(f=>f.author&&f.author!==t&&new Date(f.ts).getTime()>s);if(d.length>0){const f=new Map;for(const c of d){const l=c.author;f.has(l)||f.set(l,[]),f.get(l).push(c)}e.push(`\u{1F465} **Team this week** (${d.length} lesson${d.length>1?"s":""} from teammates):`);for(const[c,l]of f){e.push(` \u{1F464} **${c}**:`);for(const N of l.slice(0,3)){const L=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${L} \`${N.topic}\` \u2014 ${N.what_worked.slice(0,80)}`)}l.length>3&&e.push(` \u2026 and ${l.length-3} more`)}e.push("")}}try{const s=await u.get("cachly:crystal:latest");if(s){const d=B(s,null);if(d&&Math.round((Date.now()-new Date(d.ts).getTime())/864e5)<=90){e.push(`\u{1F48E} **Memory Crystal** (${d.label} \xB7 ${d.session_count} sessions compressed):`);for(const c of d.top_patterns.slice(0,3))e.push(` \u2022 **${c.category}** (${c.count}\xD7): ${c.insight.slice(0,90)}`);e.push("")}}}catch{}try{const s=await u.hgetall(`cachly:roadmap:${w}`);if(s&&Object.keys(s).length>0){const d={critical:0,high:1,medium:2,low:3},f={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},c=new Set(["planned","in-progress","blocked"]),l=Object.values(s).flatMap(I=>{const j=B(I,null);return j?[j]:[]}),N=l.filter(I=>c.has(I.status)).sort((I,j)=>I.status==="in-progress"&&j.status!=="in-progress"?-1:j.status==="in-progress"&&I.status!=="in-progress"?1:(d[I.priority]??99)-(d[j.priority]??99)),L=l.filter(I=>I.status==="done").length;if(N.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${N.length} open \xB7 ${L} done):`);for(const I of N.slice(0,5)){const j=I.status==="in-progress"?"\u26A1":I.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${j} ${f[I.priority]??"\u26AA"} \`${I.id}\` **${I.title}**`)}N.length>5&&e.push(` \u2026 and ${N.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(o&&o.length>3)try{const s=o.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(l=>l.length>2).slice(0,5),d=[];for(const l of s){const N=(await Y()).filter(L=>L.slice(F.length).includes(l));for(const L of N.slice(0,3)){const I=await u.get(L);if(!I)continue;const j=B(I,null);if(!j)continue;const te=await u.smembers(`cachly:ckg:idx:from:${j.id}`);for(const ae of te.slice(0,15)){const ge=await u.get(ae);if(!ge)continue;const z=B(ge,null);if(!z||z.edgeType!=="causes"&&z.edgeType!=="co-occurs"&&z.edgeType!=="fixes"||z.confidence<.35)continue;const Ce=z.edgeType==="fixes"?`cachly:lesson:best:${z.from}`:`cachly:lesson:best:${z.to}`,de=await u.get(Ce),xe=B(de,null);d.push({concept:j.id,edgeType:z.edgeType,target:z.to,confidence:z.confidence,lesson:xe??void 0})}}}const f=new Set,c=d.filter(l=>{const N=`${l.concept}:${l.target}`;return f.has(N)?!1:(f.add(N),!0)}).sort((l,N)=>N.confidence-l.confidence).slice(0,4);if(c.length>0){e.push(`\u{1F52E} **Predicted risks for "${o}"** (PPE pre-fetch):`);for(const l of c){const N=Math.round(l.confidence*100),L=l.edgeType==="causes"?"\u26A1":l.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${L} **${N}%** \`${l.concept}\` ${l.edgeType} \`${l.target}\``),l.lesson?.what_worked&&e.push(` \u2705 ${l.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${o}")\`_`),e.push("")}}catch{}try{const s=await u.get("cachly:mcm:calibration:last"),d=B(s,null)?.ts??0;if((Date.now()-d)/864e5>=30&&n.length>=5){const c=n.filter(N=>N.outcome==="success"&&(N.recall_count??0)>0),l=n.filter(N=>(N.recall_count??0)>0);if(l.length>=3){const N=l.length>0?c.length/l.length:1,L=[],I=new Map;for(const j of l){const te=j.topic.split(":")[0]??"other";I.has(te)||I.set(te,{success:0,total:0});const ae=I.get(te);ae.total++,j.outcome==="success"&&ae.success++}for(const[j,te]of I)te.total>=2&&te.success/te.total<.6&&L.push(j);await u.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:N,recalled:l.length,low_precision_domains:L})),(L.length>0||N<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${l.length} recalled lessons):`),e.push(` Overall precision: **${(N*100).toFixed(0)}%** recalled lessons actually worked`),L.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${L.map(j=>`\`${j}\``).join(", ")} \u2014 consider revisiting these lessons`),e.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),e.push(""))}await u.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}try{const s=await ue("/api/v1/syndication/stats");s.total_lessons>0&&(e.push(`\u{1F30D} **Commons:** ${s.total_lessons.toLocaleString()} lessons \xB7 ${s.total_confirms.toLocaleString()} confirms \xB7 +${s.added_last_7_days} this week`),e.push(""))}catch{}const ce=n.filter(s=>s.outcome==="failure"||s.outcome==="partial").length>0,re=n.some(s=>s.outcome==="success"&&Ke(s)<pt);if(n.length===0||ce||re){const s=[];n.length===0&&s.push("brain is empty"),ce&&s.push("open failures"),re&&s.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${s.join(", ")}._`)}try{if(await u.get(`cachly:prefs:auto_changelog:${w}`).catch(()=>null)!=="false"&&x?.ts&&!k){const f=new Date(x.ts).getTime();if(!Number.isNaN(f)){const c=n.filter(l=>{const N=new Date(l.ts).getTime();return!Number.isNaN(N)&&N>f});if(c.length>0){const l=Math.round((Date.now()-f)/6e4),N=l<60?`${l}m`:l<1440?`${Math.round(l/60)}h`:`${Math.round(l/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${c.length} new lesson${c.length!==1?"s":""} since your last session** (${N} ago):`);const L=new Map;for(const I of c.slice(0,20)){const j=I.topic.includes(":")?I.topic.split(":")[0]:"general",te=L.get(j)??[];te.push(I),L.set(j,te)}for(const[I,j]of L){e.push(` **${I}**`);for(const te of j){const ae=te.outcome==="failure"?"\u274C":te.severity==="critical"?"\u{1F6A8}":te.severity==="major"?"\u26A0\uFE0F":"\u2705",ge=(te.outcome==="failure"?te.what_failed:te.what_worked)??"";e.push(` ${ae} \`${te.topic}\`${ge?` \u2014 ${ge.slice(0,80)}`:""}`)}}c.length>20&&e.push(` \u2026 and ${c.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${w}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
35
+ `)}case"session_start_summary":{const{instance_id:w,focus:o,top_n:t=10,author:r=""}=K;if(!o||!o.trim())throw new Error("focus is required for session_start_summary");const m=Math.min(Math.max(1,Math.floor(Number(t)||10)),25),u=await H(w),C=[],$=u.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,W)=>{$.on("data",ie=>C.push(...ie)),$.on("end",e),$.on("error",W)});const n=[];if(C.length>0){const e=await u.mget(...C);for(const W of e){const ie=B(W??null,null);ie&&n.push(ie)}}if(n.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="${w}")\` to bootstrap with 16 universal lessons.`].join(`
36
+ `);const D=n.length>m,a=o.toLowerCase().split(/\s+/).filter(Boolean),b=Date.now(),x=n.map(e=>{const W=a.filter(ne=>e.topic.toLowerCase().includes(ne)).length,ie=a.filter(ne=>(e.tags??[]).some(ce=>ce.toLowerCase().includes(ne))).length,k=W*2+ie,he=Math.max(0,e.recall_count??0),oe=Math.min(1.5,Math.log1p(he)/10),F=e.severity==="critical"?1:e.severity==="major"?.5:0,O=(b-new Date(e.verified_at??e.ts).getTime())/864e5,Y=O<30?.5*(1-O/30):0,Q=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,X=k+oe+F+Y+Q;return{lesson:e,score:X}});x.sort((e,W)=>W.score!==e.score?W.score-e.score:new Date(W.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const p=(D?x.slice(0,m):x).map(e=>e.lesson),i=n.length,T=p.length,A=[D?`\u{1F9E0} Brain Summary \u2014 top ${T} of ${i} lessons for "${o}"`:`\u{1F9E0} Brain Summary \u2014 all ${T} lesson${T!==1?"s":""} for "${o}"`,"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(const e of p){const W=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",ie=e.severity?`[${e.severity}] `:"[minor] ",k=e.recall_count??0,he=k>0?` (\u2713 recalled ${k}\xD7)`:"",oe=e.what_worked.slice(0,110),F=Mn(e.author,r);A.push(`${W} ${ie}\`${e.topic}\` \u2014 ${oe}${he}${F}`)}A.push("");const M=In(p,r);return M>0&&A.push(`\u{1F465} ${M} of these ${M===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),D?A.push(`\u{1F4A1} Showing top ${T} of ${i} lessons \xB7 \`session_start\` for full briefing`):A.push(`\u{1F4A1} All ${T} lesson${T!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),A.join(`
37
+ `)}case"session_end":{const{instance_id:w,summary:o,files_changed:t=[],lessons_learned:r,workspace_path:m=""}=K,u=await H(w),C=new Date;let $;const n=await u.get("cachly:session:current");if(!n)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 D=B(n,null);D?.started&&($=Math.round((C.getTime()-new Date(D.started).getTime())/6e4));let a=[];try{a=(await u.lrange("cachly:session:decision-log",0,-1)).flatMap(ie=>{const k=B(ie,null);return k?[k]:[]}),await u.del("cachly:session:decision-log")}catch{}const b=cn(w);ln(w);const x={ts:C.toISOString(),summary:o,files_changed:t,...b.recalls>0?{memory_cost:b}:{},...r!==void 0?{lessons_learned:r}:{},...$!==void 0?{duration_min:$}:{},...a.length>0?{decision_log:a}:{}};await u.set("cachly:session:last",JSON.stringify(x)),await u.lpush("cachly:session:history",JSON.stringify(x)),await u.ltrim("cachly:session:history",0,49),await u.expire("cachly:session:history",90*86400),await u.del("cachly:session:current");const p=[];try{const W=/\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,ie=o.split(/[.!\n]+/).map(k=>k.trim()).filter(k=>k.length>20&&W.test(k));for(const k of ie.slice(0,6)){const oe=k.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(X=>X.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(X)).slice(0,4).join("-");if(!oe)continue;const F=`auto:${oe}`,O=`cachly:lesson:best:${F}`,Y=await u.get(O);if(Y)try{if(JSON.parse(Y).outcome==="success")continue}catch{}const Q={topic:F,outcome:"success",what_worked:k,context:`Auto-learned from session summary. Full summary: ${o.slice(0,300)}`,severity:"minor",ts:C.toISOString(),recall_count:0,auto_learned:!0,session_ts:C.toISOString(),version:2};await u.set(O,JSON.stringify(Q)),await u.expire(O,90*86400),p.push(F)}}catch{}const i=[];if(m)try{const W=n?(()=>{try{return JSON.parse(n).started??""}catch{return""}})():"",ie=W?`--since="${W}"`:'--since="1 hour ago"',k=dt(`git -C "${m}" log ${ie} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(k){const he=/\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,oe=k.split("|||ENDE").map(F=>F.trim()).filter(Boolean);for(const F of oe.slice(0,10)){const[O,Y,Q,X]=F.split("|||");if(O)try{const c=dt(`git -C "${m}" diff-tree --no-commit-id --name-only -r --root "${O}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),N=c?c.split(`
38
+ `).map(I=>I.trim()).filter(Boolean).slice(0,12):[],L=[];for(const I of N)L.push(await gt(u,I));for(let I=0;I<L.length;I++)for(let j=I+1;j<L.length;j++)await we(u,L[I],"co-occurs",L[j],!0),await we(u,L[j],"co-occurs",L[I],!0)}catch{}if(!Y||!he.test(Y))continue;const ne=(Q??"").trim();if(ne.length<120)continue;const ce=Y.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(!ce)continue;const re=`git:${ce}`,s=`cachly:lesson:best:${re}`;if(await u.get(s))continue;const f={topic:re,outcome:"success",what_worked:`${Y}
39
39
 
40
- ${Z.slice(0,1200)}`,context:`Auto-learned from git commit ${(O??"").slice(0,7)} at ${R??""} in ${m}`,severity:"minor",ts:S.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3};await h.set(a,JSON.stringify(d)),await h.expire(a,60*86400),o.push(re)}}}catch{}const N=i!==void 0?` \xB7 ${i} min`:"",_=f.length+o.length,b=[];i!==void 0&&i>0&&b.push(`\u23F1 ${i} min session`),_>0&&b.push(`\u{1F9E0} ${_} lessons saved to Brain`),t.length>0&&b.push(`\u{1F4C1} ${t.length} file${t.length>1?"s":""} changed`);const I=b.length>0?`${b.join(" \xB7 ")}
40
+ ${ne.slice(0,1200)}`,context:`Auto-learned from git commit ${(O??"").slice(0,7)} at ${X??""} in ${m}`,severity:"minor",ts:C.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3};await u.set(s,JSON.stringify(f)),await u.expire(s,60*86400),i.push(re)}}}catch{}const T=$!==void 0?` \xB7 ${$} min`:"",y=p.length+i.length,v=[];$!==void 0&&$>0&&v.push(`\u23F1 ${$} min session`),y>0&&v.push(`\u{1F9E0} ${y} lessons saved to Brain`),t.length>0&&v.push(`\u{1F4C1} ${t.length} file${t.length>1?"s":""} changed`);const A=v.length>0?`${v.join(" \xB7 ")}
41
41
 
42
42
  My AI Brain remembers this so I never repeat it. @cachlydev
43
43
  cachly.dev`:`Session saved to my AI Brain. No more re-explaining this tomorrow. @cachlydev
44
- cachly.dev`,E=`https://twitter.com/intent/tweet?text=${encodeURIComponent(I)}`,e=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",i!==void 0?`\u2502 \u23F1 Duration : ${(i+" min").padEnd(26)}\u2502`:"",_>0?`\u2502 \u{1F4DA} Learned : ${(_+" lessons").padEnd(26)}\u2502`:"",t.length>0?`\u2502 \u{1F4C1} Changed : ${(t.length+" file"+(t.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: ${E.slice(0,34).padEnd(34)}\u2502`,"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"].filter(j=>j!=="").join(`
45
- `);return[`\u2705 **Session saved**${N}`,"",`\u{1F4CB} **Summary:** ${n}`,t.length>0?`\u{1F4C1} **Files changed:** ${t.map(j=>`\`${j}\``).join(", ")}`:"",r!==void 0?`\u{1F9E0} **Lessons stored:** ${r}`:"",...Xs(w),f.length>0?`\u{1F916} **Auto-learned:** ${f.length} lessons extracted from summary (${f.slice(0,3).map(j=>`\`${j}\``).join(", ")}${f.length>3?"\u2026":""})`:"",o.length>0?`\u{1F33F} **Ambient git learning:** ${o.length} commit${o.length>1?"s":""} auto-learned (${o.slice(0,3).map(j=>`\`${j}\``).join(", ")}${o.length>3?"\u2026":""})`:"",e,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(j=>j!=="").join(`
46
- `)}case"session_ping":{const{instance_id:y,task:n,files_touched:t=[],next_step:r="",provider:m=""}=U,h=await Y(y),S={ts:new Date().toISOString(),task:n,files_touched:t,next_step:r,provider:m};await h.set("cachly:session:checkpoint",JSON.stringify(S),"EX",86400*3),await h.lpush("cachly:session:checkpoint:log",JSON.stringify(S)),await h.ltrim("cachly:session:checkpoint:log",0,19);const i=m?` [${m}]`:"",u=t.length>0?` \xB7 ${t.length} file${t.length>1?"s":""} touched`:"",A=r?`
47
- \u{1F4CD} **Next step:** ${r}`:"";return[`\u{1F4CC} **Checkpoint saved**${i} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${n}${u}`,A,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically."].filter(s=>s!=="").join(`
48
- `)}case"session_handoff":{const{instance_id:y,completed_tasks:n=[],remaining_tasks:t=[],files_changed:r=[],instructions:m="",context_summary:h="",blocked_on:S=""}=U,i=await Y(y),A={ts:new Date().toISOString(),completed_tasks:n,remaining_tasks:t,files_changed:r,instructions:m,context_summary:h,blocked_on:S};await i.set("cachly:session:handoff",JSON.stringify(A)),await i.lpush("cachly:session:handoff:history",JSON.stringify(A)),await i.ltrim("cachly:session:handoff:history",0,19);const s=n.length+t.length,w=s>0?Math.round(n.length/s*100):0,C=r.filter(f=>f.status==="broken"||f.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${n.length}/${s} tasks done (${w}%)`,"",n.length>0?`\u2705 **Completed:**
49
- ${n.map(f=>` - ${f}`).join(`
44
+ cachly.dev`,M=`https://twitter.com/intent/tweet?text=${encodeURIComponent(A)}`,e=["","\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","\u2502 \u{1F9E0} Session Summary Card \u2502","\u2502 Share your progress \u2014 cached forever \u2502","\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",$!==void 0?`\u2502 \u23F1 Duration : ${($+" min").padEnd(26)}\u2502`:"",y>0?`\u2502 \u{1F4DA} Learned : ${(y+" lessons").padEnd(26)}\u2502`:"",t.length>0?`\u2502 \u{1F4C1} Changed : ${(t.length+" file"+(t.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: ${M.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(W=>W!=="").join(`
45
+ `);return[`\u2705 **Session saved**${T}`,"",`\u{1F4CB} **Summary:** ${o}`,t.length>0?`\u{1F4C1} **Files changed:** ${t.map(W=>`\`${W}\``).join(", ")}`:"",r!==void 0?`\u{1F9E0} **Lessons stored:** ${r}`:"",...un(b),p.length>0?`\u{1F916} **Auto-learned:** ${p.length} lessons extracted from summary (${p.slice(0,3).map(W=>`\`${W}\``).join(", ")}${p.length>3?"\u2026":""})`:"",i.length>0?`\u{1F33F} **Ambient git learning:** ${i.length} commit${i.length>1?"s":""} auto-learned (${i.slice(0,3).map(W=>`\`${W}\``).join(", ")}${i.length>3?"\u2026":""})`:"",e,"",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(W=>W!=="").join(`
46
+ `)}case"session_ping":{const{instance_id:w,task:o,files_touched:t=[],next_step:r="",provider:m=""}=K,u=await H(w),C={ts:new Date().toISOString(),task:o,files_touched:t,next_step:r,provider:m};await u.set("cachly:session:checkpoint",JSON.stringify(C),"EX",86400*3),await u.lpush("cachly:session:checkpoint:log",JSON.stringify(C)),await u.ltrim("cachly:session:checkpoint:log",0,19);const $=m?` [${m}]`:"",n=t.length>0?` \xB7 ${t.length} file${t.length>1?"s":""} touched`:"",D=r?`
47
+ \u{1F4CD} **Next step:** ${r}`:"";return[`\u{1F4CC} **Checkpoint saved**${$} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${o}${n}`,D,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically."].filter(a=>a!=="").join(`
48
+ `)}case"session_handoff":{const{instance_id:w,completed_tasks:o=[],remaining_tasks:t=[],files_changed:r=[],instructions:m="",context_summary:u="",blocked_on:C=""}=K,$=await H(w),D={ts:new Date().toISOString(),completed_tasks:o,remaining_tasks:t,files_changed:r,instructions:m,context_summary:u,blocked_on:C};await $.set("cachly:session:handoff",JSON.stringify(D)),await $.lpush("cachly:session:handoff:history",JSON.stringify(D)),await $.ltrim("cachly:session:handoff:history",0,19);const a=o.length+t.length,b=a>0?Math.round(o.length/a*100):0,x=r.filter(p=>p.status==="broken"||p.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${o.length}/${a} tasks done (${b}%)`,"",o.length>0?`\u2705 **Completed:**
49
+ ${o.map(p=>` - ${p}`).join(`
50
50
  `)}`:"",t.length>0?`
51
51
  \u23F3 **Remaining for next window:**
52
- ${t.map(f=>` - ${f}`).join(`
53
- `)}`:"",C.length>0?`
54
- \u26A0\uFE0F **Needs attention:** ${C.map(f=>`\`${f.path}\` (${f.status})`).join(", ")}`:"",S?`
55
- \u{1F6AB} **Blocked on:** ${S}`:"",m?`
56
- \u{1F4DD} **Instructions:** ${m}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically."].filter(f=>f!=="").join(`
57
- `)}case"auto_learn_session":{const{instance_id:y,observations:n}=U,t=await Y(y),r=[],m=[];for(const S of n){const i=S.topic??S.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),u=i.includes(":")?i:`auto:${i}`,A=`cachly:lesson:best:${u}`,s=await t.get(A);if(s&&JSON.parse(s).outcome==="success"&&S.outcome!=="success"){m.push(u);continue}const w={topic:u,outcome:S.outcome,what_worked:S.outcome==="success"?S.action:S.details??S.action,what_failed:S.outcome==="failure"?S.action:void 0,context:S.details,severity:S.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2},C=JSON.stringify(w);await t.set(A,C);const f=`cachly:lessons:${u}`;await t.rpush(f,C),await t.ltrim(f,-100,-1),await t.expire(f,90*86400);try{const o=u.split(":")[0]??"auto",N=ye(u);if(await Ne(t,N,o,o),S.outcome==="success"||S.outcome==="partial"){const _=S.details?Je(S.details):null;if(_){const b=ye(`problem:${_}`);await Ne(t,b,"problem","problem"),await be(t,N,"fixes",b,S.outcome==="success",S.outcome==="partial")}}}catch{}r.push(`${S.outcome==="success"?"\u2705":S.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${u}\``)}const h=[`\u{1F916} **Auto-learn complete**: ${r.length} stored, ${m.length} skipped`,""];return r.length>0&&h.push("**Stored:**",...r.map(S=>" "+S),""),m.length>0&&h.push(`**Skipped** (better lesson already exists): ${m.map(S=>`\`${S}\``).join(", ")}`),h.join(`
58
- `)}case"brain_who_knows":{const{instance_id:y,topic:n,limit:t=10}=U;if(!n||typeof n!="string"||!n.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const r=Math.max(1,Math.min(Number(t)||10,50)),m=await Y(y),h=ye(n),S=Qe(n).filter(f=>f.length>=3).slice(0,5),i=new Set([h]);for(const f of S.slice(0,3)){const o=m.scanStream({match:`cachly:ckg:node:*${f}*`,count:30});await new Promise((N,_)=>{o.on("data",b=>{for(const I of b.slice(0,10)){const E=I.replace("cachly:ckg:node:","");!E.startsWith("person:")&&!E.startsWith("file:")&&i.add(E)}}),o.on("end",N),o.on("error",_)})}const u=new Map;for(const f of[...i].slice(0,25)){const o=await m.smembers(`cachly:ckg:idx:to:${f}`);for(const N of o){const _=await m.get(N);if(!_)continue;const b=B(_,null);if(!b||b.edgeType!=="authored")continue;const I=await m.get(`cachly:ckg:node:${b.from}`);if(!I)continue;const E=B(I,null);if(!E||E.type!=="person")continue;const e=u.get(b.from);e?(e.lessonCount++,e.totalConfidence+=b.confidence,e.domains.add(E.domain),b.last_updated>e.lastActive&&(e.lastActive=b.last_updated)):u.set(b.from,{handle:E.handle,lessonCount:1,totalConfidence:b.confidence,domains:new Set([E.domain]),lastActive:E.last_active??b.last_updated})}}if(u.size===0)return[`## \u{1F465} Who Knows About \`${n}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${n}", author="your-handle", ...)\``].join(`
59
- `);const A=[...u.entries()].map(([f,o])=>({id:f,handle:o.handle,lessonCount:o.lessonCount,avgConfidence:o.totalConfidence/o.lessonCount,domains:[...o.domains].slice(0,3).join(", "),lastActive:o.lastActive})).sort((f,o)=>o.lessonCount*o.avgConfidence-f.lessonCount*f.avgConfidence).slice(0,r),s=[],w=A[0];if(w)try{const f=await m.smembers(`cachly:ckg:idx:from:${w.id}`),o=[];for(const N of f){const _=await m.get(N);if(!_)continue;const b=B(_,null);if(!b||b.edgeType!=="collaborates")continue;const I=await m.get(`cachly:ckg:node:${b.to}`),E=I?B(I,null):null;E?.handle&&o.push({handle:E.handle,trials:b.trials})}o.sort((N,_)=>_.trials-N.trials);for(const N of o.slice(0,3))s.push(N.handle)}catch{}const C=[`## \u{1F465} Who Knows About \`${n}\`?`,"",`**${A.length}** contributor${A.length!==1?"s":""} with relevant lessons:`,""];for(const[f,o]of A.entries()){const N=f===0?"\u{1F947}":f===1?"\u{1F948}":f===2?"\u{1F949}":`${f+1}.`,_=(o.avgConfidence*100).toFixed(0),b=Math.floor((Date.now()-new Date(o.lastActive).getTime())/864e5),I=b<1?"today":b<7?`${b}d ago`:b<30?`${Math.floor(b/7)}w ago`:`${Math.floor(b/30)}mo ago`,E=await Xe(m,y,o.handle).catch(()=>null),e=E?` ${as[E]}`:"";C.push(`${N} **${o.handle}**${e} \u2014 ${o.lessonCount} lesson${o.lessonCount!==1?"s":""} \xB7 ${_}% confidence \xB7 last active ${I}`,` _domains: ${o.domains}_`,"")}return s.length>0&&w&&C.push(`\u{1F91D} **${w.handle}** frequently works with: ${s.map(f=>`**${f}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),C.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),C.join(`
60
- `)}case"brain_file_map":{const{instance_id:y,file_paths:n=[]}=U,t=(Array.isArray(n)?n:[]).filter(h=>typeof h=="string"&&h.trim().length>0).map(h=>h.trim());if(!t.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const r=await Y(y),m=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const h of t.slice(0,10)){m.push(`### \`${h}\``);const S=`file:${ye(h)}`,i=await r.smembers(`cachly:ckg:idx:to:${S}`),u=[];for(const C of i){const f=await r.get(C);if(!f)continue;const o=B(f,null);if(!o||o.edgeType!=="touched")continue;const N=await r.get(`cachly:ckg:node:${o.from}`);if(!N)continue;const _=B(N,null);!_||_.type!=="person"||u.push({handle:_.handle,touches:o.trials,lastSeen:o.last_updated})}if(u.sort((C,f)=>f.touches-C.touches),u.length>0){const C=u.slice(0,5).map((f,o)=>{const N=o===0?"\u{1F947}":o===1?"\u{1F948}":o===2?"\u{1F949}":`${o+1}.`,_=Math.floor((Date.now()-new Date(f.lastSeen).getTime())/864e5),b=_<1?"today":_<7?`${_}d ago`:`${Math.floor(_/7)}w ago`;return`${N} **${f.handle}** (${f.touches}\xD7 \xB7 ${b})`}).join(" \xB7 ");m.push(`**Experts:** ${C}`)}else m.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const s=h.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(C=>C.length>=4).slice(0,3).join(" "),w=[];if(s)try{const C=await Fe(r,["cachly:lesson:best:*"],s,4);for(const f of C){const o=Te(f.content);if(!Ee(o))continue;const N=o.outcome==="success"?"\u2705":o.outcome==="partial"?"\u26A0\uFE0F":"\u274C",_=o.severity==="critical"?" \u{1F534}":o.severity==="major"?" \u{1F7E1}":"",b=o.author?` \xB7 \u{1F464} ${o.author}`:"",I=f.key.replace("cachly:lesson:best:","");w.push(` - ${N} \`${I}\`${_}${b} \u2014 ${(o.what_worked??"").slice(0,100)}`)}}catch{}if(w.length<2){const C=await Ce(r,"cachly:lesson:best:*",{max:1500});for(const f of C.slice(0,300)){const o=await r.get(f);if(!o)continue;const N=Te(o);if(!Ee(N)||!(N.file_paths??[]).includes(h))continue;const _=f.replace("cachly:lesson:best:","");if(w.some(e=>e.includes(`\`${_}\``)))continue;const b=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C",I=N.severity==="critical"?" \u{1F534}":N.severity==="major"?" \u{1F7E1}":"",E=N.author?` \xB7 \u{1F464} ${N.author}`:"";w.push(` - ${b} \`${_}\`${I}${E} \u2014 ${(N.what_worked??"").slice(0,100)}`)}}w.length>0?(m.push("**Related lessons:**"),m.push(...w.slice(0,5))):m.push("**Related lessons:** _None yet_"),m.push("")}return m.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),m.join(`
61
- `)}case"team_expertise_map":{const{instance_id:y,top_n:n=20}=U,t=await Y(y),r=await Ce(t,"cachly:ckg:node:person:*",{max:2e3});if(r.length===0)return["## \u{1F5FA}\uFE0F Team Expertise Map","","No contributors yet.","",'Add `author="handle"` to any `learn_from_attempts` call to start building the map.'].join(`
62
- `);const m=[];for(const i of r){const u=await t.get(i);if(!u)continue;const A=B(u,null);if(!A||A.type!=="person")continue;const s=await t.smembers(`cachly:ckg:idx:from:${A.id}`),w=new Map;let C=0;for(const f of s){const o=await t.get(f);if(!o)continue;const N=B(o,null);if(!N||N.edgeType!=="authored")continue;C++;const _=N.to.split(":")[0]??"unknown";w.set(_,(w.get(_)??0)+1)}m.push({handle:A.handle,lessonCount:C,domains:w,lastActive:A.last_active})}m.sort((i,u)=>u.lessonCount-i.lessonCount);const h=m.slice(0,n),S=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${h.length}** contributor${h.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[i,u]of h.entries()){const A=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}`,s=Math.floor((Date.now()-new Date(u.lastActive).getTime())/864e5),w=s<1?"today":s<7?`${s}d ago`:s<30?`${Math.floor(s/7)}w ago`:`${Math.floor(s/30)}mo ago`,C=[...u.domains.entries()].sort((f,o)=>o[1]-f[1]).slice(0,3).map(([f,o])=>`${f}(${o})`).join(", ")||"\u2014";S.push(`| ${A} | **${u.handle}** | ${u.lessonCount} | ${C} | ${w} |`)}return S.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),S.join(`
63
- `)}case"skill_gaps":{const{instance_id:y,min_failures:n=1}=U,t=await Y(y),r=await Ce(t,"cachly:lesson:best:*",{max:3e3}),m=new Map;let h=0,S=0;for(const A of r){const s=await t.get(A);if(!s)continue;const w=Te(s);if(w===null)continue;const C=(w.topic??"").split(":")[0]??"unknown",f=m.get(C)??{successes:0,failures:0,attributed:0,topics:[]};w.outcome==="success"||w.outcome==="partial"?f.successes++:f.failures++,w.author&&(f.attributed++,h++),w.visibility==="private"&&S++,f.topics.push(w.topic??""),m.set(C,f)}const i=[];for(const[A,s]of m)s.failures>=n&&s.successes===0&&i.push({domain:A,type:"unresolved failures",severity:s.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${s.failures} failure${s.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),s.successes+s.failures>=3&&s.attributed===0&&i.push({domain:A,type:"no attribution",severity:"\u{1F535} info",detail:`${s.successes+s.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const u=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${r.length}** lessons scanned \xB7 **${h}** attributed \xB7 **${i.length}** gap${i.length!==1?"s":""} found`,S>0?`_(${S} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(i.length===0)u.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const A=[...i.filter(s=>s.severity.includes("critical")),...i.filter(s=>s.severity.includes("warn")),...i.filter(s=>s.severity.includes("info"))];for(const s of A.slice(0,15))u.push(`${s.severity} **\`${s.domain}\`** \u2014 ${s.type}`),u.push(` ${s.detail}`),u.push("");i.length>15&&u.push(`_\u2026and ${i.length-15} more gaps. Fix critical ones first._`)}return u.push("---",`_Fix gaps with \`learn_from_attempts(topic="${i[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),u.join(`
64
- `)}case"brain_coverage":{const{instance_id:y,repo_path:n="."}=U,t=await Y(y),[r,m,h]=await Promise.all([Ce(t,"cachly:lesson:best:*",{max:5e3}),Ce(t,"cachly:ckg:node:person:*",{max:2e3}),Ce(t,"cachly:ckg:node:file:*",{max:5e3})]);let S=0,i="n/a";try{const{execSync:_}=await import("node:child_process"),{resolve:b}=await import("node:path"),I=b(n);S=_("git ls-files",{cwd:I,encoding:"utf-8",stdio:"pipe"}).trim().split(`
65
- `).filter(Boolean).length,i=String(S)}catch{}let u=0,A=0,s=0;const w=new Set;for(const _ of r){const b=await t.get(_);if(!b)continue;const I=B(b,{});I.outcome==="success"||I.outcome==="partial"?u++:A++,I.author&&s++,w.add((I.topic??"").split(":")[0]??"unknown")}const C=S>0?`${Math.round(h.length/S*100)}% (${h.length}/${S} files)`:`${h.length} files tracked`,f=r.length>0?Math.round(s/r.length*100):0,o=Math.round(Math.min(1,r.length/50)*25+Math.min(1,u/Math.max(1,r.length))*25+Math.min(1,f/100)*25+Math.min(1,m.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${o>=80?"\u{1F7E2}":o>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${o}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${r.length}** (${u} success \xB7 ${A} failure) |`,`| Problem domains | **${w.size}** |`,`| Attribution | **${s}/${r.length}** (${f}%) |`,`| Contributors | **${m.length}** tracked in knowledge graph |`,`| File coverage | **${C}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,r.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,u/Math.max(1,r.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,f/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,m.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
66
- `)}case"brain_metrics":{const{instance_id:y}=U,n=await Y(y),[t,r,m,h,S,i]=await Promise.all([n.get(`cachly:stats:born_at:${y}`).catch(()=>null),n.get(`cachly:stats:first_recall_at:${y}`).catch(()=>null),n.get(`cachly:stats:recalls_total:${y}`).catch(()=>null),n.get(`cachly:stats:cross_author_recalls:${y}`).catch(()=>null),n.get(`cachly:stats:time_saved_mins:${y}`).catch(()=>null),n.smembers(`cachly:stats:reuse_pairs:${y}`).catch(()=>[])]);let u={};try{u=await n.hgetall(It(y))??{}}catch{u={}}let A={};try{A=await n.hgetall(yt(y))??{}}catch{A={}}const s={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const F=await n.lrange(gt(y),0,499),O=new Map;for(const G of F){const se=B(G,{ts:"",themen:[]});if(!(!se.ts||!Array.isArray(se.themen)))for(const R of se.themen){if(s.lieferungen++,!O.has(R)){const fe=await n.get(`cachly:lesson:best:${R}`).catch(()=>null);O.set(R,fe?B(fe,{}):null)}const Z=Ts(se.ts,O.get(R)??null);if(Z.length===0){s.ohneEreignis++;continue}for(const fe of Z)s[fe]++}}}catch{}let w=0,C=0;try{const F=await n.lrange(`cachly:wirkung:${y}`,0,-1);for(const O of F){const G=B(O,{});C++,G.geholfen===!0&&w++}}catch{}let f={};try{f=await n.hgetall(an(y))??{}}catch{f={}}const o=rn(f,10);let N={token:0,abrufe:0,treffer:0};try{const F=await n.get(un(y)),O=await n.hgetall(hn(y))??{};N={token:F??0,abrufe:O.abrufe??0,treffer:O.treffer??0}}catch{}const _=ln(N);let b;if(t&&r){const F=new Date(r).getTime()-new Date(t).getTime(),O=Math.max(0,Math.round(F/6e4)),G=O<1?"<1 min":O<60?`${O} min`:`${(O/60).toFixed(1)} h`,se=F<=2*6e4?"\u{1F7E2} under 2 min target":F<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";b=`**${G}** from first lesson \u2192 first proven recall \xB7 ${se}`}else t&&!r?b="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":b="\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(`
67
- `),E=Number(m??0),e=Number(h??0),j=E>0?Math.round(e/E*100):0,ie=j>=30?"\u{1F7E2} above 30 % target":E===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",k=Math.round(Number(S??0)),ge=k<60?`${k} min`:`${(k/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",b,"","### 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)_",`**${j}%** of proven recalls used a teammate's lesson (${e}/${E}) \xB7 ${ie}`,i.length>0?`**${i.length}** distinct reuse relationship${i.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",cn(_),"",_.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._`,E===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 F=Number(u.beantwortet??0),O=Number(u.knapp??0),G=Number(u.schweigen??0),se=F+O+G;if(se===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const R=Z=>`${Math.round(100*Z/se)} %`;return`**${se}** Suchen: ${R(F)} beantwortet \xB7 ${R(O)} als knapper Sieg markiert \xB7 ${R(G)} 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 F=R=>Number(A[R]??0),O=[["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)"]],G=O.reduce((R,[Z])=>R+F(Z),0);if(G===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const se=O.filter(([R])=>R!=="ohne-vorwissen").sort((R,Z)=>F(Z[0])-F(R[0]))[0];return`**${G}** klassifizierte Fehlschlaege: `+O.map(([R,Z])=>`${F(R)} ${Z}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${se[1]}** (${F(se[0])}) \u2014 dorthin gehoert das naechste Investment. (Heuristik je Einzelfall; erst die Verteilung ueber viele Sessions traegt.)`})(),"","### \u{1F3F7}\uFE0F Drei Etiketten ohne Selbstauskunft _(widersprochen \xB7 korrigiert \xB7 veraltet)_",s.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${s.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${s.widersprochen} widersprochen \xB7 ${s.korrigiert} korrigiert \xB7 ${s.veraltet} veraltet \xB7 ${s.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 F=Number(s.widersprochen)+Number(s.veraltet);if(C===0&&F===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const O=w-F;return`**${O>=0?"+":""}${O}** = ${w} bestaetigt geholfen (Wirkungsspur, ${C} Eintraege) \u2212 ${F} Schadenslieferungen (${s.widersprochen} spaeter widerlegt + ${s.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",on(o,yn.length),...o.spitze.length>0?o.spitze.map((F,O)=>` ${String(O+1).padStart(2)}. \`${F.name}\` \u2014 ${F.aufrufe}\xD7 (${Math.round(F.anteil*100)} %)`):[]].filter(Boolean).join(`
68
- `)}case"brain_service_map":{const{instance_id:y,service:n}=U;if(!n||typeof n!="string"||!n.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const t=await Y(y),r=`service:${ye(n.trim())}`,m=await t.get(`cachly:ckg:node:${r}`).catch(()=>null),h=m?B(m,null):null,S=await t.smembers(`cachly:ckg:idx:to:${r}`).catch(()=>[]),i=[],u=[],A=[];for(const b of S){const I=await t.get(b).catch(()=>null);if(!I)continue;const E=B(I,null);if(E)if(E.edgeType==="operates"){const e=await t.get(`cachly:ckg:node:${E.from}`).catch(()=>null),j=e?B(e,null):null;j?.handle&&i.push({handle:j.handle,trials:E.trials})}else if(E.edgeType==="runs_in"){const e=await t.get(`cachly:ckg:node:${E.from}`).catch(()=>null),j=e?B(e,null):null;j?.path&&u.push({path:j.path,trials:E.trials})}else E.edgeType==="affects"&&A.push({id:E.from,confidence:E.confidence})}i.sort((b,I)=>I.trials-b.trials),u.sort((b,I)=>I.trials-b.trials),A.sort((b,I)=>I.confidence-b.confidence);const s=[],w=await Ce(t,"cachly:lesson:best:*",{max:1500}),C=n.trim().toLowerCase();for(const b of w.slice(0,400)){const I=await t.get(b).catch(()=>null);if(!I)continue;const E=Te(I);Ee(E)&&(E.service??"").toLowerCase()===C&&s.push({...E,topic:b.replace("cachly:lesson:best:","")})}if(!h&&s.length===0&&i.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${n}\``,"","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="${n}", author="you", file_paths=[...])\``].join(`
69
- `);const f=h?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",o=[`## ${h?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${n}\``,"",h?`_${f} \xB7 ${h.count} lesson${h.count!==1?"s":""} referenced \xB7 domain: ${h.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(i.length>0){const b=i.slice(0,5).map((I,E)=>`${E===0?"\u{1F947}":E===1?"\u{1F948}":E===2?"\u{1F949}":`${E+1}.`} **${I.handle}** (${I.trials}\xD7)`).join(" \xB7 ");o.push(`**Operators:** ${b}`,"")}else o.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const N=s.filter(b=>b.outcome==="failure"),_=s.filter(b=>b.outcome!=="failure");if(N.length>0){o.push(`**\u26A0\uFE0F Known failures (${N.length}):**`);for(const b of N.slice(0,6)){const I=b.severity==="critical"?" \u{1F534}":b.severity==="major"?" \u{1F7E1}":"",E=b.author?` \xB7 \u{1F464} ${b.author}`:"";o.push(` - \u274C \`${b.topic}\`${I}${E} \u2014 ${(b.what_worked??"").slice(0,100)}`)}o.push("")}if(_.length>0){o.push(`**\u2705 Proven fixes (${_.length}):**`);for(const b of _.slice(0,6)){const I=b.outcome==="partial"?"\u26A0\uFE0F":"\u2705",E=b.author?` \xB7 \u{1F464} ${b.author}`:"";o.push(` - ${I} \`${b.topic}\`${E} \u2014 ${(b.what_worked??"").slice(0,100)}`)}o.push("")}return u.length>0&&o.push(`**Files in this service:** ${u.slice(0,8).map(b=>`\`${b.path}\``).join(", ")}`,""),o.push("---",`_Tag lessons with \`service="${n}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),o.join(`
70
- `)}case"brain_collab_pairs":{const{instance_id:y,min_weight:n=1}=U,t=await Y(y),r=typeof n=="number"&&n>=1?Math.floor(n):1,m=await Ce(t,"cachly:ckg:node:person:*",{max:500}),h=new Map;for(const w of m){const C=await t.get(w);if(!C)continue;const f=B(C,null);!f||f.type!=="person"||h.set(f.id,{id:f.id,handle:f.handle,domain:f.domain,count:f.count})}if(h.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
71
- `);const S=new Map;for(const[w,C]of h){const f=await t.smembers(`cachly:ckg:idx:from:${w}`);for(const o of f){const N=await t.get(o);if(!N)continue;const _=B(N,null);if(!_||_.edgeType!=="collaborates")continue;const b=h.get(_.to);if(!b)continue;const[I,E]=w<_.to?[w,_.to]:[_.to,w],e=`${I}||${E}`,j=S.get(e);if(j)j.trials+=_.trials;else{const[ie,k]=w<_.to?[C,b]:[b,C];S.set(e,{a:ie,b:k,trials:_.trials,confidence:_.confidence})}}}const i=[...S.values()].filter(w=>w.trials>=r).sort((w,C)=>C.trials-w.trials),u=new Set;for(const w of i)u.add(w.a.id),u.add(w.b.id);const A=[...h.values()].filter(w=>!u.has(w.id)),s=["## \u{1F91D} Team Collaboration Graph",""];if(i.length===0)s.push(`No collaboration pairs yet (min weight: ${r}).`,"","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{s.push(`**${i.length} collaboration pair${i.length!==1?"s":""}** across ${u.size} contributor${u.size!==1?"s":""}:`,"");for(const w of i.slice(0,20)){const C=(w.confidence*100).toFixed(0),f=[w.a.domain,w.b.domain].filter((o,N,_)=>o&&_.indexOf(o)===N).map(o=>`\`${o}\``).join(", ");s.push(`### @${w.a.handle} \u2194 @${w.b.handle}`,`- **${w.trials} collaboration event${w.trials!==1?"s":""}** \xB7 ${C}% confidence`,`- Domains: ${f||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${w.a.handle}** und **@${w.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}i.length>20&&s.push(`_...and ${i.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return A.length>0&&s.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${A.length} contributor${A.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...A.slice(0,10).map(w=>`- **@${w.handle}** \u2014 ${w.count} lesson${w.count!==1?"s":""} \xB7 domain: \`${w.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),s.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),s.join(`
72
- `)}case"brain_portability":{const{instance_id:y}=U,n=[{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:y}}}},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:y}}}},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:y}}}},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:y}}}},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:y}}}},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:y}}}},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:y}}]},null,2)}],t=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${y}\``,"","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 (${n.length} supported)`,""];for(const r of n)t.push(`#### ${r.icon} ${r.name}`,`Config: \`${r.configPath}\``,"","```json",r.configBlock,"```","");return t.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 \`${y}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),t.join(`
73
- `)}case"brain_changelog":{const{instance_id:y,days:n=7,max_lessons:t=30,include_failures:r=!0}=U,m=await Y(y),h=Date.now()-Number(n)*864e5,S=await Ce(m,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),i=[];for(const o of S){const N=await m.get(o).catch(()=>null);if(!N)continue;const _=B(N,{});if((_.ts?new Date(_.ts).getTime():0)<h||!r&&_.outcome==="failure")continue;const I=o.replace("cachly:lesson:best:","");i.push({..._,topic:I})}i.sort((o,N)=>{const _=o.ts?new Date(o.ts).getTime():0;return(N.ts?new Date(N.ts).getTime():0)-_});const u=i.slice(0,Number(t));if(u.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${n} day${Number(n)!==1?"s":""}`,"","_No new lessons learned in this window. Your Brain already knows everything it knows \u2014 add new lessons with `learn_from_attempts`._"].join(`
74
- `);const A=new Map;for(const o of u){const N=o.topic.includes(":")?o.topic.split(":")[0]:"general",_=A.get(N)??[];_.push(o),A.set(N,_)}const s=o=>o==="critical"?"\u{1F6A8}":o==="major"?"\u26A0\uFE0F":o==="minor"?"\u{1F4A1}":"\u2728",w=o=>o==="failure"?"\u274C":o==="partial"?"\u{1F536}":"\u2705",f=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${n} day${Number(n)!==1?"s":""})`,"",`_${u.length} lesson${u.length!==1?"s":""} learned across ${A.size} topic area${A.size!==1?"s":""}_`,""];for(const[o,N]of Array.from(A.entries()).sort((_,b)=>b[1].length-_[1].length)){f.push(`### ${o}`),f.push("");for(const _ of N){const b=_.outcome==="failure"?w(_.outcome):s(_.severity),I=_.outcome==="failure"?_.what_failed:_.what_worked,E=[];_.author&&E.push(`by **${_.author}**`),_.recall_count&&E.push(`${_.recall_count} recall${_.recall_count!==1?"s":""}`),_.confidence!==void 0&&E.push(`${Math.round(_.confidence*100)}% confidence`),f.push(`- ${b} **${_.topic}**${I?` \u2014 ${I}`:""}`),E.length&&f.push(` _${E.join(" \xB7 ")}_`)}f.push("")}return f.push("---",`_Generated from Brain \`${y}\` \xB7 Share this in your standup or Slack_`),f.join(`
75
- `)}case"brain_set_pref":{const{instance_id:y,key:n,value:t}=U;if(!n||!n.trim())throw new Error("key is required");const r=await Y(y),m=`cachly:prefs:${n.trim()}:${y}`;return await r.set(m,String(t)),`\u2705 Preference \`${n}\` set to \`${t}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:y,key:n}=U,t=await Y(y);if(n&&n.trim()){const S=await t.get(`cachly:prefs:${n.trim()}:${y}`).catch(()=>null);return S===null?`\u2139\uFE0F Preference \`${n}\` is not set (using default).`:`\u{1F527} Preference \`${n}\` = \`${S}\``}const r=await Ce(t,`cachly:prefs:*:${y}`,{max:200,timeoutMs:2e3});if(r.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const m=await t.mget(...r),h=["\u{1F527} **Brain preferences:**",""];for(let S=0;S<r.length;S++){const i=r[S].replace("cachly:prefs:","").replace(`:${y}`,"");h.push(`- \`${i}\` = \`${m[S]??"(null)"}\``)}return h.join(`
76
- `)}default:return null}}async function In(ae,U){try{if(!Ae()||xe!=="cachly"&&xe!=="ollama")return 0;let Y=0;for(const de of $e.themen()){if(Y>=U)break;if(Ke.hat(de)||await ae.exists(`${Le}${de}`))continue;const y=await ae.get(`cachly:lesson:best:${de}`);if(!y)continue;const n=B(y,{});try{const t=await Se(Be(n),{geduld:"lang",modell:Ge});t?.length&&(await ae.set(`${Le}${de}`,Me(t)),Y++)}catch{}}return Y}catch{return 0}}async function Lt(ae,U,Y){try{if(!Ae())return;const de=await ae.srandmember(Ie,Y),y=Array.isArray(de)?de:de?[de]:[];for(const n of y){if(n===U)continue;const t=await ae.get(`cachly:lesson:best:${n}`);if(!t){await ae.srem(Ie,n);continue}const r=B(t,{});try{const m=await Se(Be(r),{geduld:"lang"});if(m?.length)await ae.set(`${pt}${n}`,Me(m)),await ae.srem(Ie,n);else continue;if(xe==="cachly"||xe==="ollama")try{const h=await Se(Be(r),{geduld:"lang",modell:Ge});h?.length&&await ae.set(`${Le}${n}`,Me(h))}catch{}}catch{}}}catch{}}export{xo as BRAIN_TOOL_NAMES,To as handleBrainTool,lt as recallVorschau};
52
+ ${t.map(p=>` - ${p}`).join(`
53
+ `)}`:"",x.length>0?`
54
+ \u26A0\uFE0F **Needs attention:** ${x.map(p=>`\`${p.path}\` (${p.status})`).join(", ")}`:"",C?`
55
+ \u{1F6AB} **Blocked on:** ${C}`:"",m?`
56
+ \u{1F4DD} **Instructions:** ${m}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically."].filter(p=>p!=="").join(`
57
+ `)}case"auto_learn_session":{const{instance_id:w,observations:o}=K,t=await H(w),r=[],m=[];for(const C of o){const $=C.topic??C.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),n=$.includes(":")?$:`auto:${$}`,D=`cachly:lesson:best:${n}`,a=await t.get(D);if(a&&JSON.parse(a).outcome==="success"&&C.outcome!=="success"){m.push(n);continue}const b={topic:n,outcome:C.outcome,what_worked:C.outcome==="success"?C.action:C.details??C.action,what_failed:C.outcome==="failure"?C.action:void 0,context:C.details,severity:C.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2},x=JSON.stringify(b);await t.set(D,x);const p=`cachly:lessons:${n}`;await t.rpush(p,x),await t.ltrim(p,-100,-1),await t.expire(p,90*86400);try{const i=n.split(":")[0]??"auto",T=pe(n);if(await De(t,T,i,i),C.outcome==="success"||C.outcome==="partial"){const y=C.details?Ze(C.details):null;if(y){const v=pe(`problem:${y}`);await De(t,v,"problem","problem"),await we(t,T,"fixes",v,C.outcome==="success",C.outcome==="partial")}}}catch{}r.push(`${C.outcome==="success"?"\u2705":C.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${n}\``)}const u=[`\u{1F916} **Auto-learn complete**: ${r.length} stored, ${m.length} skipped`,""];return r.length>0&&u.push("**Stored:**",...r.map(C=>" "+C),""),m.length>0&&u.push(`**Skipped** (better lesson already exists): ${m.map(C=>`\`${C}\``).join(", ")}`),u.join(`
58
+ `)}case"brain_who_knows":{const{instance_id:w,topic:o,limit:t=10}=K;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_who_knows` requires a non-empty `topic`. Example: `brain_who_knows(topic="kubernetes deployment")`.';const r=Math.max(1,Math.min(Number(t)||10,50)),m=await H(w),u=pe(o),C=ot(o).filter(p=>p.length>=3).slice(0,5),$=new Set([u]);for(const p of C.slice(0,3)){const i=m.scanStream({match:`cachly:ckg:node:*${p}*`,count:30});await new Promise((T,y)=>{i.on("data",v=>{for(const A of v.slice(0,10)){const M=A.replace("cachly:ckg:node:","");!M.startsWith("person:")&&!M.startsWith("file:")&&$.add(M)}}),i.on("end",T),i.on("error",y)})}const n=new Map;for(const p of[...$].slice(0,25)){const i=await m.smembers(`cachly:ckg:idx:to:${p}`);for(const T of i){const y=await m.get(T);if(!y)continue;const v=B(y,null);if(!v||v.edgeType!=="authored")continue;const A=await m.get(`cachly:ckg:node:${v.from}`);if(!A)continue;const M=B(A,null);if(!M||M.type!=="person")continue;const e=n.get(v.from);e?(e.lessonCount++,e.totalConfidence+=v.confidence,e.domains.add(M.domain),v.last_updated>e.lastActive&&(e.lastActive=v.last_updated)):n.set(v.from,{handle:M.handle,lessonCount:1,totalConfidence:v.confidence,domains:new Set([M.domain]),lastActive:M.last_active??v.last_updated})}}if(n.size===0)return[`## \u{1F465} Who Knows About \`${o}\`?`,"","No attributed lessons found yet.","",'Knowledge attribution builds automatically \u2014 add `author="name"` to `learn_from_attempts` calls:',`\`learn_from_attempts(topic="${o}", author="your-handle", ...)\``].join(`
59
+ `);const D=[...n.entries()].map(([p,i])=>({id:p,handle:i.handle,lessonCount:i.lessonCount,avgConfidence:i.totalConfidence/i.lessonCount,domains:[...i.domains].slice(0,3).join(", "),lastActive:i.lastActive})).sort((p,i)=>i.lessonCount*i.avgConfidence-p.lessonCount*p.avgConfidence).slice(0,r),a=[],b=D[0];if(b)try{const p=await m.smembers(`cachly:ckg:idx:from:${b.id}`),i=[];for(const T of p){const y=await m.get(T);if(!y)continue;const v=B(y,null);if(!v||v.edgeType!=="collaborates")continue;const A=await m.get(`cachly:ckg:node:${v.to}`),M=A?B(A,null):null;M?.handle&&i.push({handle:M.handle,trials:v.trials})}i.sort((T,y)=>y.trials-T.trials);for(const T of i.slice(0,3))a.push(T.handle)}catch{}const x=[`## \u{1F465} Who Knows About \`${o}\`?`,"",`**${D.length}** contributor${D.length!==1?"s":""} with relevant lessons:`,""];for(const[p,i]of D.entries()){const T=p===0?"\u{1F947}":p===1?"\u{1F948}":p===2?"\u{1F949}":`${p+1}.`,y=(i.avgConfidence*100).toFixed(0),v=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),A=v<1?"today":v<7?`${v}d ago`:v<30?`${Math.floor(v/7)}w ago`:`${Math.floor(v/30)}mo ago`,M=await nt(m,w,i.handle).catch(()=>null),e=M?` ${ps[M]}`:"";x.push(`${T} **${i.handle}**${e} \u2014 ${i.lessonCount} lesson${i.lessonCount!==1?"s":""} \xB7 ${y}% confidence \xB7 last active ${A}`,` _domains: ${i.domains}_`,"")}return a.length>0&&b&&x.push(`\u{1F91D} **${b.handle}** frequently works with: ${a.map(p=>`**${p}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),x.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),x.join(`
60
+ `)}case"brain_file_map":{const{instance_id:w,file_paths:o=[]}=K,t=(Array.isArray(o)?o:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim());if(!t.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const r=await H(w),m=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const u of t.slice(0,10)){m.push(`### \`${u}\``);const C=`file:${pe(u)}`,$=await r.smembers(`cachly:ckg:idx:to:${C}`),n=[];for(const x of $){const p=await r.get(x);if(!p)continue;const i=B(p,null);if(!i||i.edgeType!=="touched")continue;const T=await r.get(`cachly:ckg:node:${i.from}`);if(!T)continue;const y=B(T,null);!y||y.type!=="person"||n.push({handle:y.handle,touches:i.trials,lastSeen:i.last_updated})}if(n.sort((x,p)=>p.touches-x.touches),n.length>0){const x=n.slice(0,5).map((p,i)=>{const T=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":`${i+1}.`,y=Math.floor((Date.now()-new Date(p.lastSeen).getTime())/864e5),v=y<1?"today":y<7?`${y}d ago`:`${Math.floor(y/7)}w ago`;return`${T} **${p.handle}** (${p.touches}\xD7 \xB7 ${v})`}).join(" \xB7 ");m.push(`**Experts:** ${x}`)}else m.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const a=u.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(x=>x.length>=4).slice(0,3).join(" "),b=[];if(a)try{const x=await qe(r,["cachly:lesson:best:*"],a,4);for(const p of x){const i=Me(p.content);if(!Re(i))continue;const T=i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C",y=i.severity==="critical"?" \u{1F534}":i.severity==="major"?" \u{1F7E1}":"",v=i.author?` \xB7 \u{1F464} ${i.author}`:"",A=p.key.replace("cachly:lesson:best:","");b.push(` - ${T} \`${A}\`${y}${v} \u2014 ${(i.what_worked??"").slice(0,100)}`)}}catch{}if(b.length<2){const x=await Se(r,"cachly:lesson:best:*",{max:1500});for(const p of x.slice(0,300)){const i=await r.get(p);if(!i)continue;const T=Me(i);if(!Re(T)||!(T.file_paths??[]).includes(u))continue;const y=p.replace("cachly:lesson:best:","");if(b.some(e=>e.includes(`\`${y}\``)))continue;const v=T.outcome==="success"?"\u2705":T.outcome==="partial"?"\u26A0\uFE0F":"\u274C",A=T.severity==="critical"?" \u{1F534}":T.severity==="major"?" \u{1F7E1}":"",M=T.author?` \xB7 \u{1F464} ${T.author}`:"";b.push(` - ${v} \`${y}\`${A}${M} \u2014 ${(T.what_worked??"").slice(0,100)}`)}}b.length>0?(m.push("**Related lessons:**"),m.push(...b.slice(0,5))):m.push("**Related lessons:** _None yet_"),m.push("")}return m.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),m.join(`
61
+ `)}case"team_expertise_map":{const{instance_id:w,top_n:o=20}=K,t=await H(w),r=await Se(t,"cachly:ckg:node:person:*",{max:2e3});if(r.length===0)return["## \u{1F5FA}\uFE0F Team Expertise Map","","No contributors yet.","",'Add `author="handle"` to any `learn_from_attempts` call to start building the map.'].join(`
62
+ `);const m=[];for(const $ of r){const n=await t.get($);if(!n)continue;const D=B(n,null);if(!D||D.type!=="person")continue;const a=await t.smembers(`cachly:ckg:idx:from:${D.id}`),b=new Map;let x=0;for(const p of a){const i=await t.get(p);if(!i)continue;const T=B(i,null);if(!T||T.edgeType!=="authored")continue;x++;const y=T.to.split(":")[0]??"unknown";b.set(y,(b.get(y)??0)+1)}m.push({handle:D.handle,lessonCount:x,domains:b,lastActive:D.last_active})}m.sort(($,n)=>n.lessonCount-$.lessonCount);const u=m.slice(0,o),C=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${u.length}** contributor${u.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[$,n]of u.entries()){const D=$===0?"\u{1F947}":$===1?"\u{1F948}":$===2?"\u{1F949}":`${$+1}`,a=Math.floor((Date.now()-new Date(n.lastActive).getTime())/864e5),b=a<1?"today":a<7?`${a}d ago`:a<30?`${Math.floor(a/7)}w ago`:`${Math.floor(a/30)}mo ago`,x=[...n.domains.entries()].sort((p,i)=>i[1]-p[1]).slice(0,3).map(([p,i])=>`${p}(${i})`).join(", ")||"\u2014";C.push(`| ${D} | **${n.handle}** | ${n.lessonCount} | ${x} | ${b} |`)}return C.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),C.join(`
63
+ `)}case"skill_gaps":{const{instance_id:w,min_failures:o=1}=K,t=await H(w),r=await Se(t,"cachly:lesson:best:*",{max:3e3}),m=new Map;let u=0,C=0;for(const D of r){const a=await t.get(D);if(!a)continue;const b=Me(a);if(b===null)continue;const x=(b.topic??"").split(":")[0]??"unknown",p=m.get(x)??{successes:0,failures:0,attributed:0,topics:[]};b.outcome==="success"||b.outcome==="partial"?p.successes++:p.failures++,b.author&&(p.attributed++,u++),b.visibility==="private"&&C++,p.topics.push(b.topic??""),m.set(x,p)}const $=[];for(const[D,a]of m)a.failures>=o&&a.successes===0&&$.push({domain:D,type:"unresolved failures",severity:a.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${a.failures} failure${a.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),a.successes+a.failures>=3&&a.attributed===0&&$.push({domain:D,type:"no attribution",severity:"\u{1F535} info",detail:`${a.successes+a.failures} lessons with no \`author\` field \u2014 attribution lost, \`brain_who_knows\` can't help here`});const n=["## \u{1F50D} Skill Gaps \u2014 Knowledge Blind Spots","",`**${r.length}** lessons scanned \xB7 **${u}** attributed \xB7 **${$.length}** gap${$.length!==1?"s":""} found`,C>0?`_(${C} private lessons excluded from gap analysis)_`:"",""].filter(Boolean);if($.length===0)n.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const D=[...$.filter(a=>a.severity.includes("critical")),...$.filter(a=>a.severity.includes("warn")),...$.filter(a=>a.severity.includes("info"))];for(const a of D.slice(0,15))n.push(`${a.severity} **\`${a.domain}\`** \u2014 ${a.type}`),n.push(` ${a.detail}`),n.push("");$.length>15&&n.push(`_\u2026and ${$.length-15} more gaps. Fix critical ones first._`)}return n.push("---",`_Fix gaps with \`learn_from_attempts(topic="${$[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),n.join(`
64
+ `)}case"brain_coverage":{const{instance_id:w,repo_path:o="."}=K,t=await H(w),[r,m,u]=await Promise.all([Se(t,"cachly:lesson:best:*",{max:5e3}),Se(t,"cachly:ckg:node:person:*",{max:2e3}),Se(t,"cachly:ckg:node:file:*",{max:5e3})]);let C=0,$="n/a";try{const{execSync:y}=await import("node:child_process"),{resolve:v}=await import("node:path"),A=v(o);C=y("git ls-files",{cwd:A,encoding:"utf-8",stdio:"pipe"}).trim().split(`
65
+ `).filter(Boolean).length,$=String(C)}catch{}let n=0,D=0,a=0;const b=new Set;for(const y of r){const v=await t.get(y);if(!v)continue;const A=B(v,{});A.outcome==="success"||A.outcome==="partial"?n++:D++,A.author&&a++,b.add((A.topic??"").split(":")[0]??"unknown")}const x=C>0?`${Math.round(u.length/C*100)}% (${u.length}/${C} files)`:`${u.length} files tracked`,p=r.length>0?Math.round(a/r.length*100):0,i=Math.round(Math.min(1,r.length/50)*25+Math.min(1,n/Math.max(1,r.length))*25+Math.min(1,p/100)*25+Math.min(1,m.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${i>=80?"\u{1F7E2}":i>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${i}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${r.length}** (${n} success \xB7 ${D} failure) |`,`| Problem domains | **${b.size}** |`,`| Attribution | **${a}/${r.length}** (${p}%) |`,`| Contributors | **${m.length}** tracked in knowledge graph |`,`| File coverage | **${x}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,r.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,n/Math.max(1,r.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,p/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,m.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
66
+ `)}case"brain_metrics":{const{instance_id:w}=K,o=await H(w),[t,r,m,u,C,$]=await Promise.all([o.get(`cachly:stats:born_at:${w}`).catch(()=>null),o.get(`cachly:stats:first_recall_at:${w}`).catch(()=>null),o.get(`cachly:stats:recalls_total:${w}`).catch(()=>null),o.get(`cachly:stats:cross_author_recalls:${w}`).catch(()=>null),o.get(`cachly:stats:time_saved_mins:${w}`).catch(()=>null),o.smembers(`cachly:stats:reuse_pairs:${w}`).catch(()=>[])]);let n={};try{n=await o.hgetall(Wt(w))??{}}catch{n={}}let D={};try{D=await o.hgetall(Nt(w))??{}}catch{D={}}const a={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const F=await o.lrange(Tt(w),0,499),O=new Map;for(const Y of F){const Q=B(Y,{ts:"",themen:[]});if(!(!Q.ts||!Array.isArray(Q.themen)))for(const X of Q.themen){if(a.lieferungen++,!O.has(X)){const ce=await o.get(`cachly:lesson:best:${X}`).catch(()=>null);O.set(X,ce?B(ce,{}):null)}const ne=Ps(Q.ts,O.get(X)??null);if(ne.length===0){a.ohneEreignis++;continue}for(const ce of ne)a[ce]++}}}catch{}let b=0,x=0;try{const F=await o.lrange(`cachly:wirkung:${w}`,0,-1);for(const O of F){const Y=B(O,{});x++,Y.geholfen===!0&&b++}}catch{}let p={};try{p=await o.hgetall(wn(w))??{}}catch{p={}}const i=yn(p,10);let T={token:0,abrufe:0,treffer:0};try{const F=await o.get($n(w)),O=await o.hgetall(vn(w))??{};T={token:F??0,abrufe:O.abrufe??0,treffer:O.treffer??0}}catch{}const y=bn(T);let v;if(t&&r){const F=new Date(r).getTime()-new Date(t).getTime(),O=Math.max(0,Math.round(F/6e4)),Y=O<1?"<1 min":O<60?`${O} min`:`${(O/60).toFixed(1)} h`,Q=F<=2*6e4?"\u{1F7E2} under 2 min target":F<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";v=`**${Y}** from first lesson \u2192 first proven recall \xB7 ${Q}`}else t&&!r?v="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":v="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const A=["\u26AA **Nicht gemessen** \u2014 diese Zahl erhebt der Server nicht selbst."," Selbst messen: `npm run bench` in `sdk/mcp`."," Achtung, der Pruefstand hat 17 Lektionen und 13 Fragen \u2014 ein Beispielsatz, kein Bestand."," Auf 498 ECHTEN Lektionen gemessen am 19.08.2026: Precision@1 **30 %** (vorher 15 %)."].join(`
67
+ `),M=Number(m??0),e=Number(u??0),W=M>0?Math.round(e/M*100):0,ie=W>=30?"\u{1F7E2} above 30 % target":M===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",k=Math.round(Number(C??0)),he=k<60?`${k} min`:`${(k/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",v,"","### 2. Recall-lift _(the moat proof)_",A,"_Reproduce: `npm run bench` \xB7 CI-defended in `rerank.test.ts` \xB7 details in BENCH.md_","","### 3. Team-knowledge-reuse _(the value only a shared brain delivers)_",`**${W}%** of proven recalls used a teammate's lesson (${e}/${M}) \xB7 ${ie}`,$.length>0?`**${$.length}** distinct reuse relationship${$.length!==1?"s":""} across the team`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",_n(y),"",y.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${he} nicht neu recherchiert \u2014 gerechnet mit 30\u2013240 Min. je Lektion nach Schwere, nicht gemessen. Die Zahl dar\xFCber braucht diese Annahme nicht._`:`_Eine **Sch\xE4tzung** von ${he} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,M===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 F=Number(n.beantwortet??0),O=Number(n.knapp??0),Y=Number(n.schweigen??0),Q=F+O+Y;if(Q===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const X=ne=>`${Math.round(100*ne/Q)} %`;return`**${Q}** Suchen: ${X(F)} beantwortet \xB7 ${X(O)} als knapper Sieg markiert \xB7 ${X(Y)} 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 F=X=>Number(D[X]??0),O=[["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)"]],Y=O.reduce((X,[ne])=>X+F(ne),0);if(Y===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const Q=O.filter(([X])=>X!=="ohne-vorwissen").sort((X,ne)=>F(ne[0])-F(X[0]))[0];return`**${Y}** klassifizierte Fehlschlaege: `+O.map(([X,ne])=>`${F(X)} ${ne}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${Q[1]}** (${F(Q[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)_",a.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${a.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${a.widersprochen} widersprochen \xB7 ${a.korrigiert} korrigiert \xB7 ${a.veraltet} veraltet \xB7 ${a.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 F=Number(a.widersprochen)+Number(a.veraltet);if(x===0&&F===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const O=b-F;return`**${O>=0?"+":""}${O}** = ${b} bestaetigt geholfen (Wirkungsspur, ${x} Eintraege) \u2212 ${F} Schadenslieferungen (${a.widersprochen} spaeter widerlegt + ${a.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",mn(i,En.length),...i.spitze.length>0?i.spitze.map((F,O)=>` ${String(O+1).padStart(2)}. \`${F.name}\` \u2014 ${F.aufrufe}\xD7 (${Math.round(F.anteil*100)} %)`):[]].filter(Boolean).join(`
68
+ `)}case"brain_service_map":{const{instance_id:w,service:o}=K;if(!o||typeof o!="string"||!o.trim())return'\u26A0\uFE0F `brain_service_map` requires a non-empty `service`. Example: `brain_service_map(service="prometheus")`.';const t=await H(w),r=`service:${pe(o.trim())}`,m=await t.get(`cachly:ckg:node:${r}`).catch(()=>null),u=m?B(m,null):null,C=await t.smembers(`cachly:ckg:idx:to:${r}`).catch(()=>[]),$=[],n=[],D=[];for(const v of C){const A=await t.get(v).catch(()=>null);if(!A)continue;const M=B(A,null);if(M)if(M.edgeType==="operates"){const e=await t.get(`cachly:ckg:node:${M.from}`).catch(()=>null),W=e?B(e,null):null;W?.handle&&$.push({handle:W.handle,trials:M.trials})}else if(M.edgeType==="runs_in"){const e=await t.get(`cachly:ckg:node:${M.from}`).catch(()=>null),W=e?B(e,null):null;W?.path&&n.push({path:W.path,trials:M.trials})}else M.edgeType==="affects"&&D.push({id:M.from,confidence:M.confidence})}$.sort((v,A)=>A.trials-v.trials),n.sort((v,A)=>A.trials-v.trials),D.sort((v,A)=>A.confidence-v.confidence);const a=[],b=await Se(t,"cachly:lesson:best:*",{max:1500}),x=o.trim().toLowerCase();for(const v of b.slice(0,400)){const A=await t.get(v).catch(()=>null);if(!A)continue;const M=Me(A);Re(M)&&(M.service??"").toLowerCase()===x&&a.push({...M,topic:v.replace("cachly:lesson:best:","")})}if(!u&&a.length===0&&$.length===0)return[`## \u{1F6F0}\uFE0F Service Map \u2014 \`${o}\``,"","Nothing known about this service yet.","","Tag lessons with the service they concern so the brain can build this map:",`\`learn_from_attempts(topic="...", service="${o}", author="you", file_paths=[...])\``].join(`
69
+ `);const p=u?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",i=[`## ${u?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${o}\``,"",u?`_${p} \xB7 ${u.count} lesson${u.count!==1?"s":""} referenced \xB7 domain: ${u.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if($.length>0){const v=$.slice(0,5).map((A,M)=>`${M===0?"\u{1F947}":M===1?"\u{1F948}":M===2?"\u{1F949}":`${M+1}.`} **${A.handle}** (${A.trials}\xD7)`).join(" \xB7 ");i.push(`**Operators:** ${v}`,"")}else i.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const T=a.filter(v=>v.outcome==="failure"),y=a.filter(v=>v.outcome!=="failure");if(T.length>0){i.push(`**\u26A0\uFE0F Known failures (${T.length}):**`);for(const v of T.slice(0,6)){const A=v.severity==="critical"?" \u{1F534}":v.severity==="major"?" \u{1F7E1}":"",M=v.author?` \xB7 \u{1F464} ${v.author}`:"";i.push(` - \u274C \`${v.topic}\`${A}${M} \u2014 ${(v.what_worked??"").slice(0,100)}`)}i.push("")}if(y.length>0){i.push(`**\u2705 Proven fixes (${y.length}):**`);for(const v of y.slice(0,6)){const A=v.outcome==="partial"?"\u26A0\uFE0F":"\u2705",M=v.author?` \xB7 \u{1F464} ${v.author}`:"";i.push(` - ${A} \`${v.topic}\`${M} \u2014 ${(v.what_worked??"").slice(0,100)}`)}i.push("")}return n.length>0&&i.push(`**Files in this service:** ${n.slice(0,8).map(v=>`\`${v.path}\``).join(", ")}`,""),i.push("---",`_Tag lessons with \`service="${o}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),i.join(`
70
+ `)}case"brain_collab_pairs":{const{instance_id:w,min_weight:o=1}=K,t=await H(w),r=typeof o=="number"&&o>=1?Math.floor(o):1,m=await Se(t,"cachly:ckg:node:person:*",{max:500}),u=new Map;for(const b of m){const x=await t.get(b);if(!x)continue;const p=B(x,null);!p||p.type!=="person"||u.set(p.id,{id:p.id,handle:p.handle,domain:p.domain,count:p.count})}if(u.size===0)return["## \u{1F91D} Team Collaboration Graph","","No contributors found yet.","",'The graph builds automatically as teammates store lessons with `author="name"`:','`learn_from_attempts(topic="...", author="alice", file_paths=["src/auth.ts"], ...)`'].join(`
71
+ `);const C=new Map;for(const[b,x]of u){const p=await t.smembers(`cachly:ckg:idx:from:${b}`);for(const i of p){const T=await t.get(i);if(!T)continue;const y=B(T,null);if(!y||y.edgeType!=="collaborates")continue;const v=u.get(y.to);if(!v)continue;const[A,M]=b<y.to?[b,y.to]:[y.to,b],e=`${A}||${M}`,W=C.get(e);if(W)W.trials+=y.trials;else{const[ie,k]=b<y.to?[x,v]:[v,x];C.set(e,{a:ie,b:k,trials:y.trials,confidence:y.confidence})}}}const $=[...C.values()].filter(b=>b.trials>=r).sort((b,x)=>x.trials-b.trials),n=new Set;for(const b of $)n.add(b.a.id),n.add(b.b.id);const D=[...u.values()].filter(b=>!n.has(b.id)),a=["## \u{1F91D} Team Collaboration Graph",""];if($.length===0)a.push(`No collaboration pairs yet (min weight: ${r}).`,"","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{a.push(`**${$.length} collaboration pair${$.length!==1?"s":""}** across ${n.size} contributor${n.size!==1?"s":""}:`,"");for(const b of $.slice(0,20)){const x=(b.confidence*100).toFixed(0),p=[b.a.domain,b.b.domain].filter((i,T,y)=>i&&y.indexOf(i)===T).map(i=>`\`${i}\``).join(", ");a.push(`### @${b.a.handle} \u2194 @${b.b.handle}`,`- **${b.trials} collaboration event${b.trials!==1?"s":""}** \xB7 ${x}% confidence`,`- Domains: ${p||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${b.a.handle}** und **@${b.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}$.length>20&&a.push(`_...and ${$.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return D.length>0&&a.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${D.length} contributor${D.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...D.slice(0,10).map(b=>`- **@${b.handle}** \u2014 ${b.count} lesson${b.count!==1?"s":""} \xB7 domain: \`${b.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),a.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),a.join(`
72
+ `)}case"brain_portability":{const{instance_id:w}=K,o=[{name:"Claude Code",slug:"claude-code",icon:"\u{1F916}",configPath:"~/.claude/settings.json",configBlock:JSON.stringify({mcpServers:{cachly:{command:"npx",args:["@cachly-dev/mcp-server@latest"],env:{CACHLY_JWT:"<cky_live_...>",CACHLY_BRAIN_INSTANCE_ID:w}}}},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:w}}}},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:w}}}},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:w}}}},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:w}}}},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:w}}}},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:w}}]},null,2)}],t=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${w}\``,"","Replace `<cky_live_...>` below with your own API key (get one at https://cachly.dev/setup-ai) \u2014 the Brain ID alone does not authenticate you.","","This Brain ID is model-agnostic. Every lesson you've learned, every Memory Crystal you've distilled,","and every prediction from your Causal Knowledge Graph is accessible from **any MCP-compatible AI client**.","","---","",`### Compatible Clients (${o.length} supported)`,""];for(const r of o)t.push(`#### ${r.icon} ${r.name}`,`Config: \`${r.configPath}\``,"","```json",r.configBlock,"```","");return t.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 \`${w}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),t.join(`
73
+ `)}case"brain_changelog":{const{instance_id:w,days:o=7,max_lessons:t=30,include_failures:r=!0}=K,m=await H(w),u=Date.now()-Number(o)*864e5,C=await Se(m,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),$=[];for(const i of C){const T=await m.get(i).catch(()=>null);if(!T)continue;const y=B(T,{});if((y.ts?new Date(y.ts).getTime():0)<u||!r&&y.outcome==="failure")continue;const A=i.replace("cachly:lesson:best:","");$.push({...y,topic:A})}$.sort((i,T)=>{const y=i.ts?new Date(i.ts).getTime():0;return(T.ts?new Date(T.ts).getTime():0)-y});const n=$.slice(0,Number(t));if(n.length===0)return[`## \u{1F4CB} Brain Changelog \u2014 last ${o} day${Number(o)!==1?"s":""}`,"","_No new lessons learned in this window. Your Brain already knows everything it knows \u2014 add new lessons with `learn_from_attempts`._"].join(`
74
+ `);const D=new Map;for(const i of n){const T=i.topic.includes(":")?i.topic.split(":")[0]:"general",y=D.get(T)??[];y.push(i),D.set(T,y)}const a=i=>i==="critical"?"\u{1F6A8}":i==="major"?"\u26A0\uFE0F":i==="minor"?"\u{1F4A1}":"\u2728",b=i=>i==="failure"?"\u274C":i==="partial"?"\u{1F536}":"\u2705",p=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${o} day${Number(o)!==1?"s":""})`,"",`_${n.length} lesson${n.length!==1?"s":""} learned across ${D.size} topic area${D.size!==1?"s":""}_`,""];for(const[i,T]of Array.from(D.entries()).sort((y,v)=>v[1].length-y[1].length)){p.push(`### ${i}`),p.push("");for(const y of T){const v=y.outcome==="failure"?b(y.outcome):a(y.severity),A=y.outcome==="failure"?y.what_failed:y.what_worked,M=[];y.author&&M.push(`by **${y.author}**`),y.recall_count&&M.push(`${y.recall_count} recall${y.recall_count!==1?"s":""}`),y.confidence!==void 0&&M.push(`${Math.round(y.confidence*100)}% confidence`),p.push(`- ${v} **${y.topic}**${A?` \u2014 ${A}`:""}`),M.length&&p.push(` _${M.join(" \xB7 ")}_`)}p.push("")}return p.push("---",`_Generated from Brain \`${w}\` \xB7 Share this in your standup or Slack_`),p.join(`
75
+ `)}case"brain_set_pref":{const{instance_id:w,key:o,value:t}=K;if(!o||!o.trim())throw new Error("key is required");const r=await H(w),m=`cachly:prefs:${o.trim()}:${w}`;return await r.set(m,String(t)),`\u2705 Preference \`${o}\` set to \`${t}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:w,key:o}=K,t=await H(w);if(o&&o.trim()){const C=await t.get(`cachly:prefs:${o.trim()}:${w}`).catch(()=>null);return C===null?`\u2139\uFE0F Preference \`${o}\` is not set (using default).`:`\u{1F527} Preference \`${o}\` = \`${C}\``}const r=await Se(t,`cachly:prefs:*:${w}`,{max:200,timeoutMs:2e3});if(r.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const m=await t.mget(...r),u=["\u{1F527} **Brain preferences:**",""];for(let C=0;C<r.length;C++){const $=r[C].replace("cachly:prefs:","").replace(`:${w}`,"");u.push(`- \`${$}\` = \`${m[C]??"(null)"}\``)}return u.join(`
76
+ `)}default:return null}}async function Gn(ee,K){try{if(!Le()||Te!=="cachly"&&Te!=="ollama")return 0;let H=0;for(const ue of ye.themen()){if(H>=K)break;if(Ue.hat(ue)||await ee.exists(`${je}${ue}`))continue;const w=await ee.get(`cachly:lesson:best:${ue}`);if(!w)continue;const o=B(w,{});try{const t=await ke(We(o),{geduld:"lang",modell:Ve});t?.length&&(await ee.set(`${je}${ue}`,Be(t)),H++)}catch{}}return H}catch{return 0}}async function Kt(ee,K,H){try{if(!Le())return;const ue=await ee.srandmember(ze,H),w=Array.isArray(ue)?ue:ue?[ue]:[];for(const o of w){if(o===K)continue;const t=await ee.get(`cachly:lesson:best:${o}`);if(!t){await ee.srem(ze,o);continue}const r=B(t,{});try{const m=await ke(We(r),{geduld:"lang"});if(m?.length)await ee.set(`${Ct}${o}`,Be(m)),await ee.srem(ze,o);else continue;if(Te==="cachly"||Te==="ollama")try{const u=await ke(We(r),{geduld:"lang",modell:Ve});u?.length&&await ee.set(`${je}${o}`,Be(u))}catch{}}catch{}}}catch{}}export{Po as BRAIN_TOOL_NAMES,jo as handleBrainTool,yt as recallVorschau};