@cachly-dev/mcp-server 0.10.170 → 0.10.172

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