@cachly-dev/mcp-server 0.10.155 → 0.10.156

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,5 +1,5 @@
1
- import{execSync as Xe}from"node:child_process";import{createRequire as Qe}from"node:module";import{calculateConfidence as Ae,confidenceBadge as Ct,STRUCTURED_TEMPLATES as xt,CONFIDENCE_WARN_VALUE as et,CONFIDENCE_STALE_VALUE as Tt,CONFIDENCE_WARN_DAYS as Nt}from"../confidence.js";import{ckgSlug as he,extractProblemConcept as Oe,ckgUpsertNode as Se,ckgUpdateEdge as pe,ckgUpsertPersonNode as Et,ckgUpsertFileNode as tt,ckgRecordCollaboration as At,ckgUpsertServiceNode as Mt}from"../ckg.js";import{safeJsonParse as z,scanKeys as _e,leseOderNull as ve,darfHeraus as Ce}from"../utils.js";import{ersparteMinuten as st,istStarterLektion as Me,zaehltAlsErsparnis as nt}from"../wertbeitrag.js";import{lessonPreviewLines as Te,trimTo as It}from"../lesson-preview.js";import{normalisiereZeit as Pe,zaehleZeitangaben as je}from"../zeit-normalisieren.js";import{abstentionSatz as Rt,alterssatzFuerBelegte as Dt,beurteileTreffer as Lt,istBelegt as Bt}from"../abstention.js";import{meldeEinmal as ze,meldeUndVermerke as Ie,fehlerText as Fe,OHNE_VEKTOREN as Ot,OHNE_DIENST as Pt,OHNE_FRAGEVEKTOR as jt,SINNPFAD_ABBRUCH as zt,OHNE_SCHREIBVEKTOR as We}from"../aussetzer.js";import{versuchStart as Ft,neueKennung as Wt,wendeZuteilungAn as Kt,schliesseVersuchAb as Gt}from"../versuch.js";function ot(ae,Z,X){if(ae.includes("lesson:best:")){const p=z(Z,{});if(p&&typeof p=="object"&&(p.what_worked||p.what_failed||p.commands?.length))return Te(p,{maxChars:X,indent:" "})}const ue=It(Z,X);return ue?[ue]:[]}import{getRole as Ke,ROLE_BADGE as Ht,getScopes as at,lessonVisibleToScope as it,reviewModeEnabled as Jt,storeLessonProposal as qt}from"./team.js";import{keywordSearch as Re,wortindexEntwerten as Ut,tokenize as Ge,splitMultiQuery as Vt,levenshtein as Yt,indexVocab as rt}from"../search.js";import{rerankByQuality as Zt,qualityMultiplier as Xt,extractLessonQuality as Qt}from"../rerank.js";import{computeEmbedding as be,hasEmbedProvider as Ne,EMBED_PROVIDER as ke}from"../embeddings.js";import{repariereFelder as es}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as ct,NAME_VEKTOR_PRAEFIX as lt,ZWEIT_VEKTOR_PRAEFIX as He,packe as Ee,textFuerVektor as De,textFuerNamensVektor as ts,Vektorbestand as Je}from"../bedeutung.js";import{schreibeEingaenge as ss,Eingangsbestand as ns}from"../eingaenge.js";import{Seltenheitsbestand as os}from"../seltenheitsbestand.js";import{spurLegen as as}from"../spuren.js";import{schlageErsetzungVor as is}from"../ersetzung-vorschlag.js";const xe="cachly:vek:nachtrag",rs=365;import{etikettenFuer as cs,lieferJournalSchluessel as ht,JOURNAL_DECKEL as ls}from"../etiketten.js";import{klassifiziereFehlschlag as hs,suchProtokollSchluessel as ut,trichterSchluessel as dt,SUCH_DECKEL as us}from"../recall-trichter.js";import{leiteEntscheidungAb as ds,entscheidungsZeile as ft}from"../entscheidung-ableiten.js";import{bewerteTopf as fs,spreizeImTopf as pt,reichereAn as ps,inhaltsWoerter as mt,grobStamm as ms,GEWICHTE as gs,knapperSiegSatz as ys}from"../rangfolge.js";import{pruefeWirkung as ws,werteAus as _s,lehrwert as bs,leiteAb as $s}from"../wirkungsspur.js";import{SINN_TOPF as vs,EINGANG_SCHWELLE as ks,EINGANG_SORTIER_GEWICHT as Ss,ZWEIT_MODELL as qe,ZWEIT_GEWICHT as Cs,ZWEIT_MINDESTDECKUNG as xs,NAHDUPLIKAT_SCHWELLE as Ts}from"../rangfolge-stellschrauben.js";const me=new Je,Ue=new Je(6e4,lt),Ve=new Je(6e4,He),Ye=new ns,Le=new os,Ns=vs,Es=ks,As=Ss;import{upgradeNudge as Ms}from"../upgrade-nudge.js";import{recallTiefe as gt,TIEFE_VOLL as Is,TIEFE_VOLL_MEHRTHEMIG as Rs}from"../recall-tiefe.js";import{nutzungInWorten as Ds,nutzungsSchluessel as Ls,verdichte as Bs}from"../werkzeug-nutzung.js";import{inWorten as Os,lieferBild as Ps,lieferSchluessel as js,trefferSchluessel as zs}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Fs,autorHinweis as Ws,coautorAus as Ks,echterGitLeser as Gs,ermittleAutor as Hs,mitCoautor as Js,nurMensch as yt}from"../autor.js";import{TOOLS as qs}from"../tools.js";import{vorspannHinweis as Us}from"../vorspann.js";import{autorAbzeichen as Vs,fremdanteil as Ys}from"../autor-abzeichen.js";import{cachlyUrl as Zs}from"../cachly-url.js";const Be=(()=>{try{const ae=Qe(import.meta.url);for(const Z of["../../../package.json","../../package.json"])try{const X=ae(Z);if(X.name==="@cachly-dev/mcp-server"&&X.version)return X.version}catch{}}catch{}return"0.10.100"})(),Xs=()=>{try{return Qe(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Qs={"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${Be}:**`," \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"]},zn=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","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"]),en=Zs("/billing","upgrade"),wt=new Map,_t=new Set,tn=1680*60*60;function sn(ae=new Date){return`cachly:quota:recalls:${ae.toISOString().slice(0,7)}`}async function bt(ae){try{const Z=sn();await ae.incr(Z)===1&&await ae.expire(Z,tn)}catch{}}function $t(ae){return`cachly:stats:drei-ausgaenge:${ae}`}async function vt(ae,Z,X){try{await ae.hincrby($t(Z),X,1)}catch{}}async function kt(ae,Z){const X=wt.get(ae);if(X&&X.expiresAt>Date.now())return X.gate;try{const ue=await Z(`/api/v1/instances/${ae}/memory`),p=ue?.recall_limit??-1,t=ue?.total_recall_count??0,n={reached:p>0&&t>=p,limit:p,used:t,goodwillMessage:ue?.goodwill_message,notice:ue?.notice};return wt.set(ae,{gate:n,expiresAt:Date.now()+6e4}),n}catch{return{reached:!1,limit:-1,used:0}}}async function Fn(ae,Z,X,ue){switch(ae){case"learn_from_attempts":{const{instance_id:p,topic:t,outcome:n,what_worked:w,what_failed:A="",context:f="",severity:o="major",file_paths:b=[],commands:h=[],tags:u=[],depends_on:d=[],author:S="",visibility:T="team",service:a="",service_kind:l="service",group:x="",grund:y="",ersetzt:$="",gilt_ab:R=""}=Z,{what_worked:D,what_failed:e="",context:H=""}=es({what_worked:w,what_failed:A,context:f}),_=await X(p),ne=new Date,oe=ne.toISOString(),V=Pe(D,ne),E=Pe(e,ne),O=Pe(H,ne),se=je(D,ne)+je(e,ne)+je(H,ne),Y=Hs({uebergeben:S,umgebung:process.env.CACHLY_AUTHOR,git:Gs(process.env.CACHLY_WORKSPACE??process.cwd())});let Q="";try{Q=Ks(await _.get(`cachly:prefs:${Fs}:${p}`))}catch{}const s=Js(Y.autor,Q),m=Ws(Y);if(T!=="private"&&await Jt(_,p))return qt(_,t,{topic:t,outcome:n,what_worked:V,what_failed:E,context:O,severity:o,file_paths:b,commands:h,tags:u,depends_on:d,...s?{author:s}:{},...a?{service:a}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:0,ts:oe,confidence:1,version:3});const g=t.split(":")[0],i=xt[g],r=[];if(i)for(const I of i.required)I==="commands"&&h.length===0&&r.push(`\u{1F4CB} ${i.hint}`);let N=!1,C=0,j,M=[];const B=await _.get(`cachly:lesson:best:${t}`),ce=String(y??"").trim();if(B&&!ce)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(B)try{const I=JSON.parse(B);C=I.recall_count??0,j=I.last_recalled_at,M=I.audit_trail??[],M.push({ts:oe,action:"updated",prev_outcome:I.outcome,grund:ce}),M.length>20&&(M=M.slice(-20)),N=!0;const P=[];if(I.outcome==="success"&&n==="failure"?P.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."):I.outcome==="failure"&&n==="success"&&P.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),P.length>0){M[M.length-1].action="contradiction-resolved";try{const ie=he(t),ee=he(`resolution:${t}`);await pe(_,ie,"contradicts",ee,!1)}catch{}try{const ie=`cachly:contradictions:${t}`,ee=I.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await _.rpush(ie,JSON.stringify({ts:oe,prev_outcome:I.outcome,new_outcome:n,direction:ee})),await _.ltrim(ie,-50,-1),await _.expire(ie,180*86400)}catch{}P.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else M=[{ts:oe,action:"created"}];const fe=[];if(n==="failure"){const I=[],P=_.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((ee,q)=>{P.on("data",L=>I.push(...L)),P.on("end",ee),P.on("error",q)});const ie=t.split(/[:\-_]/).filter(ee=>ee.length>2);for(const ee of I.slice(0,50)){const q=await _.get(ee);if(q)try{const L=JSON.parse(q);if(L.outcome!=="success")continue;const te=(L.topic??"").split(/[:\-_]/).filter(de=>de.length>2);if(ie.filter(de=>te.includes(de)).length>=1&&L.topic!==t){fe.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${L.topic}\` (success, ${L.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${L.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${L.topic}", ..., severity="critical")\``);break}}catch{}}}for(const I of d){const P=`cachly:dep:${I}`,ie=await _.get(P),ee=z(ie,[]);ee.includes(t)||ee.push(t),await _.set(P,JSON.stringify(ee),"EX",90*86400)}const ye={topic:t,outcome:n,what_worked:V,what_failed:E,context:O,severity:o,file_paths:b,commands:h,tags:u,depends_on:d,...s?{author:s}:{},...a?{service:a}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:C,...j?{last_recalled_at:j}:{},...R&&!Number.isNaN(Date.parse(String(R)))?{gilt_ab:new Date(String(R)).toISOString()}:{},ts:oe,verified_at:n==="success"||n==="partial"?oe:void 0,confidence:1,audit_trail:M,version:3},c=String($??"").trim();let v="",k=null;c===t&&c?v="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":c&&(k=await _.get(`cachly:lesson:best:${c}`),k?ye.ersetzt=c:v=`\u26A0\uFE0F Die zu ersetzende Lektion \`${c}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let G="";if(!c)try{const I=(await Re(_,["cachly:lesson:best:*"],`${t} ${V}`.slice(0,300),5)).filter(P=>P.key.startsWith("cachly:lesson:best:")).map(P=>{const ie=z(P.content,{});return{topic:ie.topic??P.key.slice(19),what_worked:ie.what_worked}});G=is(t,V,I)??""}catch{}if(n==="failure")try{const P=(await _.lrange(ut(p),0,199)).map(q=>z(q,{ts:"",frage:"",geliefert:[]})).filter(q=>q.ts!==""),ie=(await Re(_,["cachly:lesson:best:*"],`${t} ${E||V}`.slice(0,300),5)).filter(q=>q.key.startsWith("cachly:lesson:best:")).map(q=>{const L=z(q.content,{});return{topic:L.topic??q.key.slice(19),what_worked:L.what_worked}}),ee=hs(t,String(E||""),P,ie);await _.hincrby(dt(p),ee,1)}catch{}const K=ds([V,E,f].filter(Boolean).join(" ").slice(0,2e3));K&&(ye.entscheidung=K);const F=JSON.stringify(ye);_.set(`cachly:stats:born_at:${p}`,oe,"EX",365*86400,"NX").catch(()=>{});const U=`cachly:lessons:${t}`;await _.rpush(U,F),await _.ltrim(U,-100,-1),await _.expire(U,rs*86400);let J=!1;if(n==="success"||n==="partial"?(await _.set(`cachly:lesson:best:${t}`,F),J=!0):B||(await _.set(`cachly:lesson:best:${t}`,F),J=!0),k&&J)try{const I=JSON.parse(k);I.ersetzt_durch=t,I.gilt_bis=oe,I.ersetzt_am=oe,await _.set(`cachly:lesson:best:${c}`,JSON.stringify(I))}catch{}J&&Ut(),J&&Ne()&&(await _.sadd(xe,t).catch(()=>{}),(async()=>{const I=z(F,{});try{const P=await be(De(I),{geduld:"lang"});if(P?.length&&(await _.set(`${ct}${t}`,Ee(P)),await _.srem(xe,t).catch(()=>{})),ke==="cachly"||ke==="ollama")try{const ie=await be(De(I),{geduld:"lang",modell:qe});ie?.length&&await _.set(`${He}${t}`,Ee(ie))}catch{}}catch(P){await _.sadd(xe,t).catch(()=>{}),await Ie(_,We,`Volltext-Vektor nicht geschrieben (${ke}): ${Fe(P)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const P=await be(ts(t),{geduld:"lang"});P?.length&&await _.set(`${lt}${t}`,Ee(P))}catch(P){await Ie(_,We,`Namens-Vektor nicht geschrieben (${ke}): ${Fe(P)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await ss(_,t,I,P=>be(P,{geduld:"lang"}))}catch(P){await Ie(_,We,`Eingaenge nicht geschrieben (${ke}): ${Fe(P)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await St(_,t,3)})());try{const I="cachly:session:decision-log",P=JSON.stringify({ts:oe,topic:t,outcome:n,what_worked:V.slice(0,120)});await _.rpush(I,P),await _.ltrim(I,-50,-1)}catch{}let W=null;try{const I=he(t),P=t.split(":")[0]??"unknown";await Se(_,I,P,P);for(const ee of u){const q=he(`tag:${ee}`);await Se(_,q,"tag","tag"),await pe(_,I,"co-occurs",q,n==="success",n==="partial")}for(const ee of d){const q=he(ee);await pe(_,I,"requires",q,!0)}if((P==="fix"||P==="debug")&&(n==="success"||n==="partial")){const ee=E||O||"",q=ee?Oe(ee):null;if(q){const L=he(`problem:${q}`);await Se(_,L,"problem","problem"),await pe(_,I,"fixes",L,n==="success",n==="partial")}}if(n==="failure"&&(E||V)){const q=Oe(E||V);if(q){const L=he(`cause:${q}`);await Se(_,L,"cause","cause"),await pe(_,I,"causes",L,!1)}}if(n==="failure"){const ee=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const q of ee){const L=await _.get(q);if(!L)continue;const te=z(L,null);if(te&&te.edgeType==="fixes"&&te.confidence>.7&&te.trials>=3){W=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${te.confidence.toFixed(2)}, n=${te.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="${I}")\` to review.`;const re=`cachly:ckg:conflict:${I}`;await _.set(re,JSON.stringify({topic:t,concept_id:I,detected_at:new Date().toISOString(),fix_confidence:te.confidence,fix_trials:te.trials,failure_outcome:n,reported_by:s||"unknown",what_failed:E||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(P==="fix"||P==="debug")){const ee=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const q of ee.slice(0,10)){const L=await _.get(q);if(!L)continue;const te=z(L,null);if(!te||te.edgeType!=="fixes")continue;const re=await _.smembers(`cachly:ckg:idx:from:${te.to}`);for(const de of re.slice(0,5)){const Ze=await _.get(de);if(!Ze)continue;const ge=z(Ze,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 _.set(de,JSON.stringify(ge)))}}}if(Math.random()<.01){const ee=Date.now()-7776e6,q=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const L of q){const te=await _.get(L);if(!te)continue;const re=z(te,null);re&&re.trials<3&&re.last_updated&&new Date(re.last_updated).getTime()<ee&&(re.confidence=re.confidence*.9,re.last_updated=new Date().toISOString(),await _.set(L,JSON.stringify(re)))}}}catch{}if(s){_.set(`cachly:agents:active:${s}`,JSON.stringify({author:s,last_topic:t,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const I=t.split(":")[0]??"unknown",P=await Et(_,yt(s),I),ie=he(t);await pe(_,P,"authored",ie,n==="success",n==="partial");for(const ee of b.slice(0,8)){const q=await tt(_,ee);await pe(_,P,"touched",q,!0),await At(_,q,P)}}catch{}}if(a&&typeof a=="string"&&a.trim())try{const I=t.split(":")[0]??"unknown",P=l==="system"?"system":"service",ie=await Mt(_,a.trim(),I,P),ee=he(t);if(await pe(_,ee,"affects",ie,n==="success",n==="partial"),s){const q=`person:${he(yt(s))}`;await pe(_,q,"operates",ie,!0)}for(const q of b.slice(0,8)){const L=`file:${he(q)}`;await pe(_,L,"runs_in",ie,!0)}}catch{}if(s&&(n==="success"||n==="partial")){const I={topic:t,outcome:n,what_worked:V,what_failed:E??"",severity:o,author:s,file_paths:b,commands:h,tags:[...new Set([...u,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},P=`cachly:lessons:${t}`;_.rpush(P,JSON.stringify(I)).catch(()=>{})}return[`${n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${N?"updated":"stored"}:** \`${t}\` (${n}) ${o==="critical"?"\u{1F534}":o==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${o}`,W??"","",`**What worked:** ${V}`,E?`**What failed:** ${E}`:"",O?`**Context:** ${O}`:"",b.length>0?`**Files:** ${b.map(I=>`\`${I}\``).join(", ")}`:"",h.length>0?`**Commands:** ${h.map(I=>`\`${I}\``).join(", ")}`:"",u.length>0?`**Tags:** ${u.map(I=>`#${I}`).join(" ")}`:"","",N?`\u267B\uFE0F Updated (recall count: ${C} \xB7 audit entries: ${M.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,s&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${s}_${Y.quelle!=="uebergeben"?` \xB7 aus ${Y.quelle}`:""}) \u2014 visible in \`team_recall\``:"",m??"",d.length>0?`\u{1F517} Depends on: ${d.map(I=>`\`${I}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",G,k&&J?`\u21B7 Ersetzt \`${c}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin.`:v,...r,...fe,se>0?`\u{1F5D3}\uFE0F ${se} relative Zeitangabe${se===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(ne.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",Us(V)??""].filter(I=>I!=="").join(`
1
+ import{execSync as Xe}from"node:child_process";import{createRequire as Qe}from"node:module";import{calculateConfidence as Ae,confidenceBadge as Ct,STRUCTURED_TEMPLATES as xt,CONFIDENCE_WARN_VALUE as et,CONFIDENCE_STALE_VALUE as Tt,CONFIDENCE_WARN_DAYS as Nt}from"../confidence.js";import{ckgSlug as he,extractProblemConcept as Oe,ckgUpsertNode as Se,ckgUpdateEdge as pe,ckgUpsertPersonNode as Et,ckgUpsertFileNode as tt,ckgRecordCollaboration as At,ckgUpsertServiceNode as Mt}from"../ckg.js";import{safeJsonParse as z,scanKeys as _e,leseOderNull as ve,darfHeraus as Ce}from"../utils.js";import{ersparteMinuten as st,istStarterLektion as Me,zaehltAlsErsparnis as nt}from"../wertbeitrag.js";import{lessonPreviewLines as Te,trimTo as It}from"../lesson-preview.js";import{normalisiereZeit as Pe,zaehleZeitangaben as je}from"../zeit-normalisieren.js";import{abstentionSatz as Rt,alterssatzFuerBelegte as Dt,beurteileTreffer as Lt,istBelegt as Bt}from"../abstention.js";import{meldeEinmal as ze,meldeUndVermerke as Ie,fehlerText as We,OHNE_VEKTOREN as Ot,OHNE_DIENST as Pt,OHNE_FRAGEVEKTOR as jt,SINNPFAD_ABBRUCH as zt,OHNE_SCHREIBVEKTOR as Fe}from"../aussetzer.js";import{versuchStart as Wt,neueKennung as Ft,wendeZuteilungAn as Kt,schliesseVersuchAb as Gt}from"../versuch.js";function ot(ae,Z,X){if(ae.includes("lesson:best:")){const p=z(Z,{});if(p&&typeof p=="object"&&(p.what_worked||p.what_failed||p.commands?.length))return Te(p,{maxChars:X,indent:" "})}const ue=It(Z,X);return ue?[ue]:[]}import{getRole as Ke,ROLE_BADGE as Ht,getScopes as at,lessonVisibleToScope as it,reviewModeEnabled as Jt,storeLessonProposal as qt}from"./team.js";import{keywordSearch as Re,wortindexEntwerten as Ut,tokenize as Ge,splitMultiQuery as Vt,levenshtein as Yt,indexVocab as rt}from"../search.js";import{rerankByQuality as Zt,qualityMultiplier as Xt,extractLessonQuality as Qt}from"../rerank.js";import{computeEmbedding as be,hasEmbedProvider as Ne,EMBED_PROVIDER as ke}from"../embeddings.js";import{repariereFelder as es}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as ct,NAME_VEKTOR_PRAEFIX as lt,ZWEIT_VEKTOR_PRAEFIX as He,packe as Ee,textFuerVektor as De,textFuerNamensVektor as ts,Vektorbestand as Je}from"../bedeutung.js";import{schreibeEingaenge as ss,Eingangsbestand as ns}from"../eingaenge.js";import{Seltenheitsbestand as os}from"../seltenheitsbestand.js";import{spurLegen as as}from"../spuren.js";import{schlageErsetzungVor as is}from"../ersetzung-vorschlag.js";const xe="cachly:vek:nachtrag",rs=365;import{etikettenFuer as cs,lieferJournalSchluessel as ht,JOURNAL_DECKEL as ls}from"../etiketten.js";import{klassifiziereFehlschlag as hs,suchProtokollSchluessel as ut,trichterSchluessel as dt,SUCH_DECKEL as us}from"../recall-trichter.js";import{leiteEntscheidungAb as ds,entscheidungsZeile as ft}from"../entscheidung-ableiten.js";import{bewerteTopf as fs,spreizeImTopf as pt,reichereAn as ps,inhaltsWoerter as mt,grobStamm as ms,GEWICHTE as gs,knapperSiegSatz as ys}from"../rangfolge.js";import{pruefeWirkung as ws,werteAus as _s,lehrwert as bs,leiteAb as $s}from"../wirkungsspur.js";import{SINN_TOPF as vs,EINGANG_SCHWELLE as ks,EINGANG_SORTIER_GEWICHT as Ss,ZWEIT_MODELL as qe,ZWEIT_GEWICHT as Cs,ZWEIT_MINDESTDECKUNG as xs,NAHDUPLIKAT_SCHWELLE as Ts}from"../rangfolge-stellschrauben.js";const me=new Je,Ue=new Je(6e4,lt),Ve=new Je(6e4,He),Ye=new ns,Le=new os,Ns=vs,Es=ks,As=Ss;import{upgradeNudge as Ms}from"../upgrade-nudge.js";import{recallTiefe as gt,TIEFE_VOLL as Is,TIEFE_VOLL_MEHRTHEMIG as Rs}from"../recall-tiefe.js";import{nutzungInWorten as Ds,nutzungsSchluessel as Ls,verdichte as Bs}from"../werkzeug-nutzung.js";import{inWorten as Os,lieferBild as Ps,lieferSchluessel as js,trefferSchluessel as zs}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Ws,autorHinweis as Fs,coautorAus as Ks,echterGitLeser as Gs,ermittleAutor as Hs,mitCoautor as Js,nurMensch as yt}from"../autor.js";import{TOOLS as qs}from"../tools.js";import{vorspannHinweis as Us}from"../vorspann.js";import{autorAbzeichen as Vs,fremdanteil as Ys}from"../autor-abzeichen.js";import{cachlyUrl as Zs}from"../cachly-url.js";const Be=(()=>{try{const ae=Qe(import.meta.url);for(const Z of["../../../package.json","../../package.json"])try{const X=ae(Z);if(X.name==="@cachly-dev/mcp-server"&&X.version)return X.version}catch{}}catch{}return"0.10.100"})(),Xs=()=>{try{return Qe(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},Qs={"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${Be}:**`," \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"]},zn=new Set(["learn_from_attempts","recall_best_solution","smart_recall","recall_feedback","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"]),en=Zs("/billing","upgrade"),wt=new Map,_t=new Set,tn=1680*60*60;function sn(ae=new Date){return`cachly:quota:recalls:${ae.toISOString().slice(0,7)}`}async function bt(ae){try{const Z=sn();await ae.incr(Z)===1&&await ae.expire(Z,tn)}catch{}}function $t(ae){return`cachly:stats:drei-ausgaenge:${ae}`}async function vt(ae,Z,X){try{await ae.hincrby($t(Z),X,1)}catch{}}async function kt(ae,Z){const X=wt.get(ae);if(X&&X.expiresAt>Date.now())return X.gate;try{const ue=await Z(`/api/v1/instances/${ae}/memory`),p=ue?.recall_limit??-1,t=ue?.total_recall_count??0,n={reached:p>0&&t>=p,limit:p,used:t,goodwillMessage:ue?.goodwill_message,notice:ue?.notice};return wt.set(ae,{gate:n,expiresAt:Date.now()+6e4}),n}catch{return{reached:!1,limit:-1,used:0}}}async function Wn(ae,Z,X,ue){switch(ae){case"learn_from_attempts":{const{instance_id:p,topic:t,outcome:n,what_worked:w,what_failed:A="",context:f="",severity:o="major",file_paths:b=[],commands:h=[],tags:u=[],depends_on:d=[],author:S="",visibility:T="team",service:a="",service_kind:l="service",group:x="",grund:y="",ersetzt:$="",gilt_ab:R=""}=Z,{what_worked:D,what_failed:e="",context:H=""}=es({what_worked:w,what_failed:A,context:f}),_=await X(p),ne=new Date,oe=ne.toISOString(),V=Pe(D,ne),E=Pe(e,ne),O=Pe(H,ne),se=je(D,ne)+je(e,ne)+je(H,ne),Y=Hs({uebergeben:S,umgebung:process.env.CACHLY_AUTHOR,git:Gs(process.env.CACHLY_WORKSPACE??process.cwd())});let Q="";try{Q=Ks(await _.get(`cachly:prefs:${Ws}:${p}`))}catch{}const s=Js(Y.autor,Q),m=Fs(Y);if(T!=="private"&&await Jt(_,p))return qt(_,t,{topic:t,outcome:n,what_worked:V,what_failed:E,context:O,severity:o,file_paths:b,commands:h,tags:u,depends_on:d,...s?{author:s}:{},...a?{service:a}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:0,ts:oe,confidence:1,version:3});const g=t.split(":")[0],i=xt[g],r=[];if(i)for(const I of i.required)I==="commands"&&h.length===0&&r.push(`\u{1F4CB} ${i.hint}`);let N=!1,C=0,j,M=[];const B=await _.get(`cachly:lesson:best:${t}`),ce=String(y??"").trim();if(B&&!ce)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(B)try{const I=JSON.parse(B);C=I.recall_count??0,j=I.last_recalled_at,M=I.audit_trail??[],M.push({ts:oe,action:"updated",prev_outcome:I.outcome,grund:ce}),M.length>20&&(M=M.slice(-20)),N=!0;const P=[];if(I.outcome==="success"&&n==="failure"?P.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."):I.outcome==="failure"&&n==="success"&&P.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),P.length>0){M[M.length-1].action="contradiction-resolved";try{const ie=he(t),ee=he(`resolution:${t}`);await pe(_,ie,"contradicts",ee,!1)}catch{}try{const ie=`cachly:contradictions:${t}`,ee=I.outcome==="success"&&n==="failure"?"kept-success":"overwrote-failure";await _.rpush(ie,JSON.stringify({ts:oe,prev_outcome:I.outcome,new_outcome:n,direction:ee})),await _.ltrim(ie,-50,-1),await _.expire(ie,180*86400)}catch{}P.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${t}")\` to resolve via expert agent voting.`)}}catch{}else M=[{ts:oe,action:"created"}];const fe=[];if(n==="failure"){const I=[],P=_.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((ee,q)=>{P.on("data",L=>I.push(...L)),P.on("end",ee),P.on("error",q)});const ie=t.split(/[:\-_]/).filter(ee=>ee.length>2);for(const ee of I.slice(0,50)){const q=await _.get(ee);if(q)try{const L=JSON.parse(q);if(L.outcome!=="success")continue;const te=(L.topic??"").split(/[:\-_]/).filter(de=>de.length>2);if(ie.filter(de=>te.includes(de)).length>=1&&L.topic!==t){fe.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${L.topic}\` (success, ${L.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${L.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${L.topic}", ..., severity="critical")\``);break}}catch{}}}for(const I of d){const P=`cachly:dep:${I}`,ie=await _.get(P),ee=z(ie,[]);ee.includes(t)||ee.push(t),await _.set(P,JSON.stringify(ee),"EX",90*86400)}const ye={topic:t,outcome:n,what_worked:V,what_failed:E,context:O,severity:o,file_paths:b,commands:h,tags:u,depends_on:d,...s?{author:s}:{},...a?{service:a}:{},...x?{group:String(x).toLowerCase().trim()}:{},visibility:T,recall_count:C,...j?{last_recalled_at:j}:{},...R&&!Number.isNaN(Date.parse(String(R)))?{gilt_ab:new Date(String(R)).toISOString()}:{},ts:oe,verified_at:n==="success"||n==="partial"?oe:void 0,confidence:1,audit_trail:M,version:3},c=String($??"").trim();let k="",v=null;c===t&&c?k="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":c&&(v=await _.get(`cachly:lesson:best:${c}`),v?ye.ersetzt=c:k=`\u26A0\uFE0F Die zu ersetzende Lektion \`${c}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let G="";if(!c)try{const I=(await Re(_,["cachly:lesson:best:*"],`${t} ${V}`.slice(0,300),5)).filter(P=>P.key.startsWith("cachly:lesson:best:")).map(P=>{const ie=z(P.content,{});return{topic:ie.topic??P.key.slice(19),what_worked:ie.what_worked}});G=is(t,V,I)??""}catch{}if(n==="failure")try{const P=(await _.lrange(ut(p),0,199)).map(q=>z(q,{ts:"",frage:"",geliefert:[]})).filter(q=>q.ts!==""),ie=(await Re(_,["cachly:lesson:best:*"],`${t} ${E||V}`.slice(0,300),5)).filter(q=>q.key.startsWith("cachly:lesson:best:")).map(q=>{const L=z(q.content,{});return{topic:L.topic??q.key.slice(19),what_worked:L.what_worked}}),ee=hs(t,String(E||""),P,ie);await _.hincrby(dt(p),ee,1)}catch{}const K=ds([V,E,f].filter(Boolean).join(" ").slice(0,2e3));K&&(ye.entscheidung=K);const W=JSON.stringify(ye);_.set(`cachly:stats:born_at:${p}`,oe,"EX",365*86400,"NX").catch(()=>{});const U=`cachly:lessons:${t}`;await _.rpush(U,W),await _.ltrim(U,-100,-1),await _.expire(U,rs*86400);let J=!1;if(n==="success"||n==="partial"?(await _.set(`cachly:lesson:best:${t}`,W),J=!0):B||(await _.set(`cachly:lesson:best:${t}`,W),J=!0),v&&J)try{const I=JSON.parse(v);I.ersetzt_durch=t,I.gilt_bis=oe,I.ersetzt_am=oe,await _.set(`cachly:lesson:best:${c}`,JSON.stringify(I))}catch{}J&&Ut(),J&&Ne()&&(await _.sadd(xe,t).catch(()=>{}),(async()=>{const I=z(W,{});try{const P=await be(De(I),{geduld:"lang"});if(P?.length&&(await _.set(`${ct}${t}`,Ee(P)),await _.srem(xe,t).catch(()=>{})),ke==="cachly"||ke==="ollama")try{const ie=await be(De(I),{geduld:"lang",modell:qe});ie?.length&&await _.set(`${He}${t}`,Ee(ie))}catch{}}catch(P){await _.sadd(xe,t).catch(()=>{}),await Ie(_,Fe,`Volltext-Vektor nicht geschrieben (${ke}): ${We(P)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const P=await be(ts(t),{geduld:"lang"});P?.length&&await _.set(`${lt}${t}`,Ee(P))}catch(P){await Ie(_,Fe,`Namens-Vektor nicht geschrieben (${ke}): ${We(P)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await ss(_,t,I,P=>be(P,{geduld:"lang"}))}catch(P){await Ie(_,Fe,`Eingaenge nicht geschrieben (${ke}): ${We(P)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await St(_,t,3)})());try{const I="cachly:session:decision-log",P=JSON.stringify({ts:oe,topic:t,outcome:n,what_worked:V.slice(0,120)});await _.rpush(I,P),await _.ltrim(I,-50,-1)}catch{}let F=null;try{const I=he(t),P=t.split(":")[0]??"unknown";await Se(_,I,P,P);for(const ee of u){const q=he(`tag:${ee}`);await Se(_,q,"tag","tag"),await pe(_,I,"co-occurs",q,n==="success",n==="partial")}for(const ee of d){const q=he(ee);await pe(_,I,"requires",q,!0)}if((P==="fix"||P==="debug")&&(n==="success"||n==="partial")){const ee=E||O||"",q=ee?Oe(ee):null;if(q){const L=he(`problem:${q}`);await Se(_,L,"problem","problem"),await pe(_,I,"fixes",L,n==="success",n==="partial")}}if(n==="failure"&&(E||V)){const q=Oe(E||V);if(q){const L=he(`cause:${q}`);await Se(_,L,"cause","cause"),await pe(_,I,"causes",L,!1)}}if(n==="failure"){const ee=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const q of ee){const L=await _.get(q);if(!L)continue;const te=z(L,null);if(te&&te.edgeType==="fixes"&&te.confidence>.7&&te.trials>=3){F=`\u26A0\uFE0F **belief_conflict** on \`${t}\`: previously confirmed fix (confidence ${te.confidence.toFixed(2)}, n=${te.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="${I}")\` to review.`;const re=`cachly:ckg:conflict:${I}`;await _.set(re,JSON.stringify({topic:t,concept_id:I,detected_at:new Date().toISOString(),fix_confidence:te.confidence,fix_trials:te.trials,failure_outcome:n,reported_by:s||"unknown",what_failed:E||"",resolved:!1}),"EX",3600*24*90)}}}if(n==="success"&&(P==="fix"||P==="debug")){const ee=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const q of ee.slice(0,10)){const L=await _.get(q);if(!L)continue;const te=z(L,null);if(!te||te.edgeType!=="fixes")continue;const re=await _.smembers(`cachly:ckg:idx:from:${te.to}`);for(const de of re.slice(0,5)){const Ze=await _.get(de);if(!Ze)continue;const ge=z(Ze,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 _.set(de,JSON.stringify(ge)))}}}if(Math.random()<.01){const ee=Date.now()-7776e6,q=await _.smembers(`cachly:ckg:idx:from:${I}`);for(const L of q){const te=await _.get(L);if(!te)continue;const re=z(te,null);re&&re.trials<3&&re.last_updated&&new Date(re.last_updated).getTime()<ee&&(re.confidence=re.confidence*.9,re.last_updated=new Date().toISOString(),await _.set(L,JSON.stringify(re)))}}}catch{}if(s){_.set(`cachly:agents:active:${s}`,JSON.stringify({author:s,last_topic:t,last_outcome:n,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const I=t.split(":")[0]??"unknown",P=await Et(_,yt(s),I),ie=he(t);await pe(_,P,"authored",ie,n==="success",n==="partial");for(const ee of b.slice(0,8)){const q=await tt(_,ee);await pe(_,P,"touched",q,!0),await At(_,q,P)}}catch{}}if(a&&typeof a=="string"&&a.trim())try{const I=t.split(":")[0]??"unknown",P=l==="system"?"system":"service",ie=await Mt(_,a.trim(),I,P),ee=he(t);if(await pe(_,ee,"affects",ie,n==="success",n==="partial"),s){const q=`person:${he(yt(s))}`;await pe(_,q,"operates",ie,!0)}for(const q of b.slice(0,8)){const L=`file:${he(q)}`;await pe(_,L,"runs_in",ie,!0)}}catch{}if(s&&(n==="success"||n==="partial")){const I={topic:t,outcome:n,what_worked:V,what_failed:E??"",severity:o,author:s,file_paths:b,commands:h,tags:[...new Set([...u,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},P=`cachly:lessons:${t}`;_.rpush(P,JSON.stringify(I)).catch(()=>{})}return[`${n==="success"?"\u2705":n==="partial"?"\u26A0\uFE0F":"\u274C"} **Lesson ${N?"updated":"stored"}:** \`${t}\` (${n}) ${o==="critical"?"\u{1F534}":o==="major"?"\u{1F7E1}":"\u{1F7E2}"} ${o}`,F??"","",`**What worked:** ${V}`,E?`**What failed:** ${E}`:"",O?`**Context:** ${O}`:"",b.length>0?`**Files:** ${b.map(I=>`\`${I}\``).join(", ")}`:"",h.length>0?`**Commands:** ${h.map(I=>`\`${I}\``).join(", ")}`:"",u.length>0?`**Tags:** ${u.map(I=>`#${I}`).join(" ")}`:"","",N?`\u267B\uFE0F Updated (recall count: ${C} \xB7 audit entries: ${M.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${t}")\``,s&&(n==="success"||n==="partial")?`\u{1F465} Auto-shared with team (by _${s}_${Y.quelle!=="uebergeben"?` \xB7 aus ${Y.quelle}`:""}) \u2014 visible in \`team_recall\``:"",m??"",d.length>0?`\u{1F517} Depends on: ${d.map(I=>`\`${I}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",G,v&&J?`\u21B7 Ersetzt \`${c}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin.`:k,...r,...fe,se>0?`\u{1F5D3}\uFE0F ${se} relative Zeitangabe${se===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(ne.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",Us(V)??""].filter(I=>I!=="").join(`
3
3
  `)}case"recall_feedback":{const{instance_id:p}=Z,t=await X(p),n=ws(Z,new Date().toISOString());if(!n.ok)return[`\u26A0\uFE0F ${n.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(`
4
4
  `);const w=n.eintrag,A=`cachly:wirkung:${p}`;await t.rpush(A,JSON.stringify(w));const o=(await t.lrange(A,0,-1).catch(()=>[])).map(S=>z(S,null)).filter(Boolean),b=_s(o),h=bs(w),u={"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 ${w.platz} \u2014 die Sortierung war zu schwach.`,"falsch-und-sicher":`Sie stand auf Platz ${w.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."},d=b.trefferquote===null?"noch keine hilfreiche Rueckmeldung":`${(b.trefferquote*100).toFixed(0)} % der hilfreichen Lektionen standen unter den ersten dreien`;return[`\u2705 Notiert: **${w.thema}** \u2014 ${w.geholfen?"hat geholfen":"hat nicht geholfen"}, Platz ${w.platz===0?"\u2014 (stand nicht drin)":w.platz}`,"",u[h],"",`Spur: ${b.gesamt} Rueckmeldungen, ${d}.`,`Davon: ${b.nachLehrwert["fehlender-treffer"]} nicht gefunden \xB7 ${b.nachLehrwert["zu-weit-hinten"]} zu weit hinten \xB7 ${b.nachLehrwert["falsch-und-sicher"]} falsch und sicher.`].join(`
5
5
  `)}case"recall_best_solution":{const{instance_id:p,topic:t,author:n}=Z,w=await X(p);try{const u=await w.get(`cachly:letzter-recall:${p}`),d=u?z(u,null):null,S=$s(d,t,new Date().toISOString());S&&(await w.rpush(`cachly:wirkung:${p}`,JSON.stringify(S)),await w.del(`cachly:letzter-recall:${p}`))}catch{}const A=await w.get(`cachly:lesson:best:${t}`);if(A){const u=z(A,null);if(!u)return`\u26A0\uFE0F Lesson data for \`${t}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const d=u.group;if(d){const B=n?await at(w,p,n).catch(()=>new Set):new Set,ce=n?await Ke(w,p,n).catch(()=>null)==="admin":!1;if(!it(d,B,ce))return`\u{1F4ED} No lessons found for \`${t}\`. Use \`learn_from_attempts\` after solving it.`}const S=Ae(u),T=u.verified_at??u.ts,a=(Date.now()-new Date(T).getTime())/864e5,l=Ct(S,a),x=new Date().toISOString(),y={...u,recall_count:(u.recall_count??0)+1,verified_at:x,last_recalled_at:x,confidence:1};await w.set(`cachly:lesson:best:${t}`,JSON.stringify(y)),bt(w);const $=nt(u)?st(u):0;$>0&&w.incrbyfloat(`cachly:stats:time_saved_mins:${p}`,$).catch(()=>{});const R=u.severity==="critical"?"\u{1F534}":u.severity==="major"?"\u{1F7E1}":u.severity?"\u{1F7E2}":"",D=u.audit_trail??[],e=D.filter(B=>B&&typeof B.grund=="string"&&B.grund.trim().length>0).slice(-3).map(B=>` \xB7 ${B.ts?new Date(B.ts).toLocaleDateString("de-DE"):"?"}: ${B.grund.trim()}`),H=D.length>1?[`_Audit: ${D.length} changes \xB7 stored ${new Date(u.ts).toLocaleDateString("de-DE")}_`,...e.length>0?["**Warum zuletzt geaendert:**",...e]:[]].join(`
@@ -11,24 +11,24 @@ ${T.join(`
11
11
 
12
12
  ${h.join(`
13
13
 
14
- `)}`}case"smart_recall":{const{instance_id:p,query:t,threshold:n=.78,author:w="",context_files:A=[]}=Z,f=Array.isArray(A)?A.filter(c=>typeof c=="string"):[],o=await X(p);St(o,void 0,2);let b=new Set,h=!1;w&&(b=await at(o,p,w).catch(()=>new Set),h=await Ke(o,p,w).catch(()=>null)==="admin");const u=await Re(o,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],t,25),d=Zt(u);let S=!1,T=null;const a=await(async()=>{if(!Ne())return ze(Pt,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),d;try{if(await me.aktualisiere(o),me.groesse===0)return ze(Ot,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),d;const c=await be(t);if(!c?.length)return ze(jt,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),d;await Ue.aktualisiere(o),await Ye.aktualisiere(o),await Le.aktualisiere(o),await Ve.aktualisiere(o);const k=(me.groesse>0?Ve.groesse/me.groesse:0)>=xs?be(t,{modell:qe}).catch(()=>null):null,G=d.filter(L=>L.key.startsWith("cachly:lesson:best:")).map(L=>L.key.slice(19)),K=L=>Math.max(me.naehe(c,L),Ue.naehe(c,L)),F=[...Le.themen()],U=(F.length>0?F:me.aehnlichste(c,500).map(L=>L.topic)).map(L=>({t:L,n:K(L)})).sort((L,te)=>te.n-L.n).slice(0,Ns).map(L=>L.t),J=[...new Set([...G,...U])],W=U.slice(0,3).map(L=>me.rohvektor(L)).filter(Boolean),le=W.length?ps(c,W):c,$e=mt(t),we=Le.statistik,I=J.map(L=>{const te=new Set([...mt(Le.textVon(L))].map(ms));return{naeheText:me.naehe(c,L),naeheThema:Ue.naehe(c,L),naeheRueckkopplung:me.naehe(le,L),seltenheitsDeckung:we?we.deckung($e,te):0,besterZeuge:we?we.besterZeuge($e,te):0}});let P=fs(I,gs);{const L=[...P].sort((te,re)=>re-te);T=L.length>1?L[0]-L[1]:null}if(Ye.groesse>0){const L=J.map(re=>{const de=Ye.besteNaehe(c,re);return de>=Es?de:-2}),te=pt(L);P=P.map((re,de)=>re+As*te[de])}if(k){const L=await k;if(L?.length){const te=pt(J.map(re=>Ve.naehe(L,re)));P=P.map((re,de)=>re+Cs*te[de])}}const ie=J.map((L,te)=>({t:L,p:P[te]})).sort((L,te)=>te.p-L.p).map(L=>L.t),ee=new Map(d.map(L=>[L.key,L])),q=[];for(const L of ie){const te=`cachly:lesson:best:${L}`,re=ee.get(te);if(re){q.push(re),ee.delete(te);continue}const de=await o.get(te).catch(()=>null);de&&q.push({key:te,content:de,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return q.push(...ee.values()),S=!0,q}catch(c){return await Ie(o,zt,`der Bedeutungspfad brach ab (${c instanceof Error?c.message:String(c)}) \u2014 diese Suche lief nur ueber Woerter`),d}})();bt(o);{const c=a.filter(v=>v.key.startsWith("cachly:lesson:best:")).slice(0,3).map(v=>v.key.slice(19));if(c.length>0){const v={ts:new Date().toISOString(),themen:c};(async()=>{const k=ht(p);await o.lpush(k,JSON.stringify(v)),await o.ltrim(k,0,ls-1)})().catch(()=>{})}{const v={ts:new Date().toISOString(),frage:t.slice(0,200),geliefert:c};(async()=>{const k=ut(p);await o.lpush(k,JSON.stringify(v)),await o.ltrim(k,0,us-1)})().catch(()=>{})}}if(Ne()){const c=a.filter(v=>v.key.startsWith("cachly:lesson:best:")).slice(0,3).map(v=>v.key.slice(19));as(o,t,c,be).catch(()=>{})}const l=[],x=a.filter(c=>c.key.startsWith("cachly:lesson:best:"));let y=0,$=0;for(const c of x.slice(0,5)){const v=await o.get(c.key).catch(()=>null);if(v){const k=z(v,null);if(k?.state==="archived")continue;if(k){const G=new Date().toISOString(),K={...k,recall_count:(k.recall_count??0)+1,verified_at:G,last_recalled_at:G};o.set(c.key,JSON.stringify(K)).catch(()=>{});const F=nt(k)?st(k):0;if(F>0&&o.incrbyfloat(`cachly:stats:time_saved_mins:${p}`,F).catch(()=>{}),o.incr(`cachly:stats:recalls_total:${p}`).catch(()=>{}),k.author&&w&&k.author!==w){y++,o.incr(`cachly:stats:cross_author_recalls:${p}`).catch(()=>{}),o.sadd(`cachly:stats:reuse_pairs:${p}`,`${w}<-${k.author}`).catch(()=>{});const U=`person:${he(w)}`,J=`person:${he(k.author)}`;pe(o,U,"collaborates",J,!0).catch(()=>{}),pe(o,J,"collaborates",U,!0).catch(()=>{})}k.outcome==="success"&&$++,k.outcome==="success"&&(k.recall_count??0)>=1&&!Me(k)&&l.push({topic:c.key.replace("cachly:lesson:best:",""),severity:k.severity??"major",recall_count:(k.recall_count??0)+1,savedMins:F,ts:k.ts,author:k.author})}}}$>0&&o.set(`cachly:stats:first_recall_at:${p}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{});const R=await ue(`/api/v1/instances/${p}`).catch(()=>null),D=!R?.tier||R.tier.toLowerCase()==="free",e=[];if(!D&&R?.vector_token&&Ne())try{const c=await be(t),v=`https://api.cachly.dev/v1/sem/${R.vector_token}`,k=await fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:c,namespace:"cachly:ctx",threshold:n,top_k:5}),signal:AbortSignal.timeout(8e3)});if(k.ok){const G=await k.json();for(const K of G.filter(F=>F.found&&F.id)){const F=K.id.replace("ctx:","").split(":"),U=F[0],J=F.slice(1).join(":"),W=`cachly:ctx:${U}:${J}`,le=await o.get(W).catch(()=>null);e.push({key:W,similarity:K.similarity??0,content:le??"(evicted)"})}}}catch{}const H=a.map(c=>c.score),_=H.length?Math.min(...H):0,ne=H.length&&Math.max(...H)-_||1,oe=c=>(c-_)/ne,V=new Map;for(const c of a){const v=oe(c.score);V.set(c.key,{key:c.key,content:c.content,bm25Score:v,hybridScore:v*(e.length>0?.7:1),matchedWords:c.matchedWords,matchType:"keyword",subQuery:c.subQuery,wortBelege:c.wortBelege})}for(const c of e){const v=V.get(c.key);v?(v.semScore=c.similarity,v.hybridScore=(v.bm25Score??0)*.6+c.similarity*.4,v.matchType="hybrid"):V.set(c.key,{key:c.key,content:c.content,semScore:c.similarity,hybridScore:c.similarity*.5,matchType:"semantic"})}try{const c=Ge(t).filter(G=>G.length>=4).slice(0,4),v=new Set;for(const G of c){const K=o.scanStream({match:`cachly:ckg:node:*${G}*`,count:20});await new Promise((F,U)=>{K.on("data",J=>{for(const W of J.slice(0,5))v.add(W.replace("cachly:ckg:node:",""))}),K.on("end",F),K.on("error",U)})}const k=new Set;for(const G of[...v].slice(0,12)){const K=await o.smembers(`cachly:ckg:idx:to:${G}`);for(const F of K.slice(0,6)){const U=await o.get(F);if(!U)continue;const J=z(U,null);if(!J||J.edgeType!=="fixes"||J.confidence<.35||k.has(J.from))continue;k.add(J.from);const W=`cachly:lesson:best:${J.from}`,le=V.get(W);if(le)le.ckgScore=Math.max(le.ckgScore??0,J.confidence),le.hybridScore=le.hybridScore*.88+J.confidence*.12,le.matchType==="keyword"&&(le.matchType="hybrid");else{const $e=await o.get(W).catch(()=>null);if(!$e)continue;V.set(W,{key:W,content:$e,ckgScore:J.confidence,hybridScore:J.confidence*.3,matchType:"ckg"})}}}}catch{}if(f.length>0){const c=new Set(f.map(v=>v.replace(/\\/g,"/")));for(const v of V.values()){if(!v.key.startsWith("cachly:lesson:best:"))continue;const k=z(v.content,{});(Array.isArray(k.file_paths)?k.file_paths.filter(K=>typeof K=="string").map(K=>K.replace(/\\/g,"/")):[]).some(K=>c.has(K))&&(v.hybridScore*=1.15,v.contextBoost=!0)}}for(const c of V.values()){if(c.matchType!=="semantic"&&c.matchType!=="ckg")continue;const v=Qt({key:c.key,content:c.content});v&&(c.hybridScore*=Xt(v))}const E=[...V.values()].filter(c=>{if(!c.key.startsWith("cachly:lesson:best:"))return!0;const v=ve(c.content);return!(!Ce(v)||!it(v?.group,b,h))}).sort((c,v)=>v.hybridScore-c.hybridScore),O=[];for(const c of E){if(!c.key.startsWith("cachly:lesson:best:"))continue;const v=z(c.content,{});v.gilt_bis&&Date.parse(String(v.gilt_bis))<Date.now()&&O.push(`\u23F3 \`${c.key.replace("cachly:lesson:best:","")}\` galt bis ${String(v.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`)}{const c=new Set(E.map(v=>v.key));for(let v=E.length-1;v>=0;v--){const k=E[v];if(!k.key.startsWith("cachly:lesson:best:"))continue;const G=z(k.content,{});if(!G.ersetzt_durch)continue;const K=k.key.replace("cachly:lesson:best:","");if(c.has(`cachly:lesson:best:${G.ersetzt_durch}`))E.splice(v,1),O.push(`\u21B7 \`${K}\` verdraengt \u2014 ersetzt durch \`${G.ersetzt_durch}\`${G.ersetzt_am?` am ${G.ersetzt_am.slice(0,10)}`:""}`);else if(await o.get(`cachly:lesson:best:${G.ersetzt_durch}`)){const F=ve(await o.get(`cachly:lesson:best:${G.ersetzt_durch}`));Ce(F)?O.push(`\u26A0\uFE0F \`${K}\` ist ersetzt durch \`${G.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${G.ersetzt_durch}")\``):O.push(`\u21B7 \`${K}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else O.push(`\u21A9\uFE0F \`${K}\` war ersetzt durch \`${G.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const se=[];{await me.aktualisiere(o).catch(()=>{});const c=E.slice(0,8).filter(v=>v.key.startsWith("cachly:lesson:best:"));for(let v=0;v<c.length;v++)for(let k=v+1;k<c.length;k++){const G=c[v].key.replace("cachly:lesson:best:",""),K=c[k].key.replace("cachly:lesson:best:",""),F=me.rohvektor(G),U=me.rohvektor(K);if(!F||!U)continue;let J=0,W=0,le=0;for(let I=0;I<F.length;I++)J+=F[I]*U[I],W+=F[I]*F[I],le+=U[I]*U[I];if((W>0&&le>0?J/(Math.sqrt(W)*Math.sqrt(le)):0)<Ts)continue;const we=I=>{const P=z(I??"",{});return String(P.verified_at??P.ts??"").slice(0,10)||"ohne Datum"};se.push(`\u26A0\uFE0F \`${G}\` (${we(c[v].content)}) und \`${K}\` (${we(c[k].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)}O.push(...se);const Y=Ft();let Q="",s=null;if(Y!==null){Q=Wt();const c=E[0]?.hybridScore??0,v=Kt(E.map(k=>({key:k.key,content:k.content,punktzahl:k.hybridScore})),Q,Y,c);v.weggelassenesThema!==void 0?E.splice(0,1):v.markierungGesetzt&&E[0]&&v.treffer[0]&&(E[0]={...E[0],content:v.treffer[0].content}),s={frage:t,hoechstePunktzahl:c,themen:[],zulassungsfaehig:v.zulassungsfaehig,zulassungsGrund:v.zulassungsGrund,zuteilung:v.zuteilung,weggelassenesThema:v.weggelassenesThema,markierungGesetzt:v.markierungGesetzt}}const m=await kt(p,ue),g=m.reached,i=gt({ueberLimit:g,gesamt:E.length,volleTiefe:Is}),r=process.env.CACHLY_RECALL_COMPACT==="1",N=r?Math.min(3,i.sichtbar):i.sichtbar,C=[`\u{1F9E0} **Smart Recall** for: _"${t}"_
14
+ `)}`}case"smart_recall":{const{instance_id:p,query:t,threshold:n=.78,author:w="",context_files:A=[]}=Z,f=Array.isArray(A)?A.filter(c=>typeof c=="string"):[],o=await X(p);St(o,void 0,2);let b=new Set,h=!1;w&&(b=await at(o,p,w).catch(()=>new Set),h=await Ke(o,p,w).catch(()=>null)==="admin");const u=await Re(o,["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],t,25),d=Zt(u);let S=!1,T=null;const a=await(async()=>{if(!Ne())return ze(Pt,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),d;try{if(await me.aktualisiere(o),me.groesse===0)return ze(Ot,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),d;const c=await be(t);if(!c?.length)return ze(jt,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),d;await Ue.aktualisiere(o),await Ye.aktualisiere(o),await Le.aktualisiere(o),await Ve.aktualisiere(o);const v=(me.groesse>0?Ve.groesse/me.groesse:0)>=xs?be(t,{modell:qe}).catch(()=>null):null,G=d.filter(L=>L.key.startsWith("cachly:lesson:best:")).map(L=>L.key.slice(19)),K=L=>Math.max(me.naehe(c,L),Ue.naehe(c,L)),W=[...Le.themen()],U=(W.length>0?W:me.aehnlichste(c,500).map(L=>L.topic)).map(L=>({t:L,n:K(L)})).sort((L,te)=>te.n-L.n).slice(0,Ns).map(L=>L.t),J=[...new Set([...G,...U])],F=U.slice(0,3).map(L=>me.rohvektor(L)).filter(Boolean),le=F.length?ps(c,F):c,$e=mt(t),we=Le.statistik,I=J.map(L=>{const te=new Set([...mt(Le.textVon(L))].map(ms));return{naeheText:me.naehe(c,L),naeheThema:Ue.naehe(c,L),naeheRueckkopplung:me.naehe(le,L),seltenheitsDeckung:we?we.deckung($e,te):0,besterZeuge:we?we.besterZeuge($e,te):0}});let P=fs(I,gs);{const L=[...P].sort((te,re)=>re-te);T=L.length>1?L[0]-L[1]:null}if(Ye.groesse>0){const L=J.map(re=>{const de=Ye.besteNaehe(c,re);return de>=Es?de:-2}),te=pt(L);P=P.map((re,de)=>re+As*te[de])}if(v){const L=await v;if(L?.length){const te=pt(J.map(re=>Ve.naehe(L,re)));P=P.map((re,de)=>re+Cs*te[de])}}const ie=J.map((L,te)=>({t:L,p:P[te]})).sort((L,te)=>te.p-L.p).map(L=>L.t),ee=new Map(d.map(L=>[L.key,L])),q=[];for(const L of ie){const te=`cachly:lesson:best:${L}`,re=ee.get(te);if(re){q.push(re),ee.delete(te);continue}const de=await o.get(te).catch(()=>null);de&&q.push({key:te,content:de,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return q.push(...ee.values()),S=!0,q}catch(c){return await Ie(o,zt,`der Bedeutungspfad brach ab (${c instanceof Error?c.message:String(c)}) \u2014 diese Suche lief nur ueber Woerter`),d}})();bt(o);{const c=a.filter(k=>k.key.startsWith("cachly:lesson:best:")).slice(0,3).map(k=>k.key.slice(19));if(c.length>0){const k={ts:new Date().toISOString(),themen:c};(async()=>{const v=ht(p);await o.lpush(v,JSON.stringify(k)),await o.ltrim(v,0,ls-1)})().catch(()=>{})}{const k={ts:new Date().toISOString(),frage:t.slice(0,200),geliefert:c};(async()=>{const v=ut(p);await o.lpush(v,JSON.stringify(k)),await o.ltrim(v,0,us-1)})().catch(()=>{})}}if(Ne()){const c=a.filter(k=>k.key.startsWith("cachly:lesson:best:")).slice(0,3).map(k=>k.key.slice(19));as(o,t,c,be).catch(()=>{})}const l=[],x=a.filter(c=>c.key.startsWith("cachly:lesson:best:"));let y=0,$=0;for(const c of x.slice(0,5)){const k=await o.get(c.key).catch(()=>null);if(k){const v=z(k,null);if(v?.state==="archived")continue;if(v){const G=new Date().toISOString(),K={...v,recall_count:(v.recall_count??0)+1,verified_at:G,last_recalled_at:G};o.set(c.key,JSON.stringify(K)).catch(()=>{});const W=nt(v)?st(v):0;if(W>0&&o.incrbyfloat(`cachly:stats:time_saved_mins:${p}`,W).catch(()=>{}),o.incr(`cachly:stats:recalls_total:${p}`).catch(()=>{}),v.author&&w&&v.author!==w){y++,o.incr(`cachly:stats:cross_author_recalls:${p}`).catch(()=>{}),o.sadd(`cachly:stats:reuse_pairs:${p}`,`${w}<-${v.author}`).catch(()=>{});const U=`person:${he(w)}`,J=`person:${he(v.author)}`;pe(o,U,"collaborates",J,!0).catch(()=>{}),pe(o,J,"collaborates",U,!0).catch(()=>{})}v.outcome==="success"&&$++,v.outcome==="success"&&(v.recall_count??0)>=1&&!Me(v)&&l.push({topic:c.key.replace("cachly:lesson:best:",""),severity:v.severity??"major",recall_count:(v.recall_count??0)+1,savedMins:W,ts:v.ts,author:v.author})}}}$>0&&o.set(`cachly:stats:first_recall_at:${p}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{});const R=await ue(`/api/v1/instances/${p}`).catch(()=>null),D=!R?.tier||R.tier.toLowerCase()==="free",e=[];if(!D&&R?.vector_token&&Ne())try{const c=await be(t),k=`https://api.cachly.dev/v1/sem/${R.vector_token}`,v=await fetch(`${k}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:c,namespace:"cachly:ctx",threshold:n,top_k:5}),signal:AbortSignal.timeout(8e3)});if(v.ok){const G=await v.json();for(const K of G.filter(W=>W.found&&W.id)){const W=K.id.replace("ctx:","").split(":"),U=W[0],J=W.slice(1).join(":"),F=`cachly:ctx:${U}:${J}`,le=await o.get(F).catch(()=>null);e.push({key:F,similarity:K.similarity??0,content:le??"(evicted)"})}}}catch{}const H=a.map(c=>c.score),_=H.length?Math.min(...H):0,ne=H.length&&Math.max(...H)-_||1,oe=c=>(c-_)/ne,V=new Map;for(const c of a){const k=oe(c.score);V.set(c.key,{key:c.key,content:c.content,bm25Score:k,hybridScore:k*(e.length>0?.7:1),matchedWords:c.matchedWords,matchType:"keyword",subQuery:c.subQuery,wortBelege:c.wortBelege})}for(const c of e){const k=V.get(c.key);k?(k.semScore=c.similarity,k.hybridScore=(k.bm25Score??0)*.6+c.similarity*.4,k.matchType="hybrid"):V.set(c.key,{key:c.key,content:c.content,semScore:c.similarity,hybridScore:c.similarity*.5,matchType:"semantic"})}try{const c=Ge(t).filter(G=>G.length>=4).slice(0,4),k=new Set;for(const G of c){const K=o.scanStream({match:`cachly:ckg:node:*${G}*`,count:20});await new Promise((W,U)=>{K.on("data",J=>{for(const F of J.slice(0,5))k.add(F.replace("cachly:ckg:node:",""))}),K.on("end",W),K.on("error",U)})}const v=new Set;for(const G of[...k].slice(0,12)){const K=await o.smembers(`cachly:ckg:idx:to:${G}`);for(const W of K.slice(0,6)){const U=await o.get(W);if(!U)continue;const J=z(U,null);if(!J||J.edgeType!=="fixes"||J.confidence<.35||v.has(J.from))continue;v.add(J.from);const F=`cachly:lesson:best:${J.from}`,le=V.get(F);if(le)le.ckgScore=Math.max(le.ckgScore??0,J.confidence),le.hybridScore=le.hybridScore*.88+J.confidence*.12,le.matchType==="keyword"&&(le.matchType="hybrid");else{const $e=await o.get(F).catch(()=>null);if(!$e)continue;V.set(F,{key:F,content:$e,ckgScore:J.confidence,hybridScore:J.confidence*.3,matchType:"ckg"})}}}}catch{}if(f.length>0){const c=new Set(f.map(k=>k.replace(/\\/g,"/")));for(const k of V.values()){if(!k.key.startsWith("cachly:lesson:best:"))continue;const v=z(k.content,{});(Array.isArray(v.file_paths)?v.file_paths.filter(K=>typeof K=="string").map(K=>K.replace(/\\/g,"/")):[]).some(K=>c.has(K))&&(k.hybridScore*=1.15,k.contextBoost=!0)}}for(const c of V.values()){if(c.matchType!=="semantic"&&c.matchType!=="ckg")continue;const k=Qt({key:c.key,content:c.content});k&&(c.hybridScore*=Xt(k))}const E=[...V.values()].filter(c=>{if(!c.key.startsWith("cachly:lesson:best:"))return!0;const k=ve(c.content);return!(!Ce(k)||!it(k?.group,b,h))}).sort((c,k)=>k.hybridScore-c.hybridScore),O=[];for(const c of E){if(!c.key.startsWith("cachly:lesson:best:"))continue;const k=z(c.content,{});k.gilt_bis&&Date.parse(String(k.gilt_bis))<Date.now()&&O.push(`\u23F3 \`${c.key.replace("cachly:lesson:best:","")}\` galt bis ${String(k.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`)}{const c=new Set(E.map(k=>k.key));for(let k=E.length-1;k>=0;k--){const v=E[k];if(!v.key.startsWith("cachly:lesson:best:"))continue;const G=z(v.content,{});if(!G.ersetzt_durch)continue;const K=v.key.replace("cachly:lesson:best:","");if(c.has(`cachly:lesson:best:${G.ersetzt_durch}`))E.splice(k,1),O.push(`\u21B7 \`${K}\` verdraengt \u2014 ersetzt durch \`${G.ersetzt_durch}\`${G.ersetzt_am?` am ${G.ersetzt_am.slice(0,10)}`:""}`);else if(await o.get(`cachly:lesson:best:${G.ersetzt_durch}`)){const W=ve(await o.get(`cachly:lesson:best:${G.ersetzt_durch}`));Ce(W)?O.push(`\u26A0\uFE0F \`${K}\` ist ersetzt durch \`${G.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${G.ersetzt_durch}")\``):O.push(`\u21B7 \`${K}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else O.push(`\u21A9\uFE0F \`${K}\` war ersetzt durch \`${G.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const se=[];{await me.aktualisiere(o).catch(()=>{});const c=E.slice(0,8).filter(k=>k.key.startsWith("cachly:lesson:best:"));for(let k=0;k<c.length;k++)for(let v=k+1;v<c.length;v++){const G=c[k].key.replace("cachly:lesson:best:",""),K=c[v].key.replace("cachly:lesson:best:",""),W=me.rohvektor(G),U=me.rohvektor(K);if(!W||!U)continue;let J=0,F=0,le=0;for(let I=0;I<W.length;I++)J+=W[I]*U[I],F+=W[I]*W[I],le+=U[I]*U[I];if((F>0&&le>0?J/(Math.sqrt(F)*Math.sqrt(le)):0)<Ts)continue;const we=I=>{const P=z(I??"",{});return String(P.verified_at??P.ts??"").slice(0,10)||"ohne Datum"};se.push(`\u26A0\uFE0F \`${G}\` (${we(c[k].content)}) und \`${K}\` (${we(c[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)}O.push(...se);const Y=Wt();let Q="",s=null;if(Y!==null){Q=Ft();const c=E[0]?.hybridScore??0,k=Kt(E.map(v=>({key:v.key,content:v.content,punktzahl:v.hybridScore})),Q,Y,c);k.weggelassenesThema!==void 0?E.splice(0,1):k.markierungGesetzt&&E[0]&&k.treffer[0]&&(E[0]={...E[0],content:k.treffer[0].content}),s={frage:t,hoechstePunktzahl:c,themen:[],zulassungsfaehig:k.zulassungsfaehig,zulassungsGrund:k.zulassungsGrund,zuteilung:k.zuteilung,weggelassenesThema:k.weggelassenesThema,markierungGesetzt:k.markierungGesetzt}}const m=await kt(p,ue),g=m.reached,i=gt({ueberLimit:g,gesamt:E.length,volleTiefe:Is}),r=process.env.CACHLY_RECALL_COMPACT==="1",N=r?Math.min(5,i.sichtbar):i.sichtbar,C=[`\u{1F9E0} **Smart Recall** for: _"${t}"_
15
15
  `];m.goodwillMessage&&C.push(`${m.goodwillMessage}
16
- `);const j={critical:0,major:1,minor:2},M=l.sort((c,v)=>(j[c.severity]??1)-(j[v.severity]??1))[0];if(M){const c=F=>F>=60?`${F/60}h`:`${F}min`,v=(()=>{if(!M.ts)return null;const F=new Date(M.ts);if(isNaN(F.getTime()))return null;const U=new Date,J=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return F.getFullYear()===U.getFullYear()?`${F.getDate()} ${J[F.getMonth()]}`:`${F.getDate()} ${J[F.getMonth()]} ${F.getFullYear()}`})(),k=M.severity==="critical"?120:M.severity==="major"?60:20,G=M.author&&M.author!==w?` \xB7 by @${M.author}`:"",K=v?` \xB7 learned ${v} (was a ${c(k)} debug)`:"";C.push(`> \u{1F4A1} **Brain saved you ~${c(M.savedMins)} here** \u2014 \`${M.topic}\`${K} \xB7 recalled ${M.recall_count}\xD7${G}
16
+ `);const j={critical:0,major:1,minor:2},M=l.sort((c,k)=>(j[c.severity]??1)-(j[k.severity]??1))[0];if(M){const c=W=>W>=60?`${W/60}h`:`${W}min`,k=(()=>{if(!M.ts)return null;const W=new Date(M.ts);if(isNaN(W.getTime()))return null;const U=new Date,J=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return W.getFullYear()===U.getFullYear()?`${W.getDate()} ${J[W.getMonth()]}`:`${W.getDate()} ${J[W.getMonth()]} ${W.getFullYear()}`})(),v=M.severity==="critical"?120:M.severity==="major"?60:20,G=M.author&&M.author!==w?` \xB7 by @${M.author}`:"",K=k?` \xB7 learned ${k} (was a ${c(v)} debug)`:"";C.push(`> \u{1F4A1} **Brain saved you ~${c(M.savedMins)} here** \u2014 \`${M.topic}\`${K} \xB7 recalled ${M.recall_count}\xD7${G}
17
17
  `)}y>0&&C.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.
18
18
  `);const B=E.filter(c=>c.contextBoost).length;B>0&&C.push(`> \u{1F4C1} **Personalized** \u2014 ${B} lesson${B!==1?"s":""} boosted because ${B!==1?"they match":"it matches"} your current file context (${f.slice(0,3).join(", ")}${f.length>3?", \u2026":""})
19
- `);const ce=Vt(t);ce.length>1&&C.push(`_Detected ${ce.length} sub-topics:_ ${ce.map((c,v)=>`${v+1}. "${c}"`).join(", ")}
19
+ `);const ce=Vt(t);ce.length>1&&C.push(`_Detected ${ce.length} sub-topics:_ ${ce.map((c,k)=>`${k+1}. "${c}"`).join(", ")}
20
20
  `);const fe=Lt(E.map(c=>({wortBelege:c.wortBelege,semScore:c.semScore,ckgScore:c.ckgScore})));if(fe.schweigen)return vt(o,p,"schweigen"),C.push(Rt(fe)),C.join(`
21
- `);const ye=ys(T);if(ye&&C.push(ye,""),vt(o,p,ye?"knapp":"beantwortet"),E.length>0){const c=E.some(k=>k.ckgScore!==void 0),v=e.length>0&&c?"keyword + semantic + CKG hybrid":e.length>0?"keyword + semantic hybrid":c?"keyword + CKG hybrid":"keyword";if(C.push(`### \u{1F50D} Results (${E.length} \u2014 ${v})
22
- `),!r&&fe.belegte<E.length){const k=[];for(const K of E){if(!K.key.startsWith("cachly:lesson:best:")||!Bt({wortBelege:K.wortBelege,semScore:K.semScore,ckgScore:K.ckgScore}))continue;const F=z(K.content,{}),U=Date.parse(F.verified_at??F.ts??"");Number.isFinite(U)&&k.push(Math.floor((Date.now()-U)/864e5))}const G=Dt(k);C.push(`> \u{1F4CA} ${fe.belegte} von ${E.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(G?` \u23F3 ${G}`:"")+`
23
- `)}if(O.length>0&&C.push(...O.map(k=>`> ${k}`),""),ce.length>1){const k=new Map,G=gt({ueberLimit:g,gesamt:E.length,volleTiefe:Rs});for(const U of E.slice(0,G.sichtbar)){const J=U.subQuery??t;k.has(J)||k.set(J,[]),k.get(J).push(U)}for(const[U,J]of k){C.push(`**Topic: "${U}"** (${J.length} results)
24
- `);for(const W of J.slice(0,4)){const le=W.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),$e=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(", ")}`,we=ot(W.key,W.content,300);if(C.push(` **${le}** _(${$e})_`),W.key.startsWith("cachly:lesson:best:")){const I=await o.get(W.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await o.get(W.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),P=I?z(I,{}):{};P.title&&C.push(` \u{1F4D6} **${P.title}** \u2014 ${P.summary??""}`)}for(const I of we)C.push(` > ${I}`);C.push("")}}const K=[...k.keys()],F=ce.filter(U=>!K.includes(U));F.length>0&&C.push(`
25
- \u26A0\uFE0F **No results for:** ${F.map(U=>`"${U}"`).join(", ")}`)}else for(const k of E.slice(0,N)){const G=k.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let K="";if(k.key.startsWith("cachly:lesson:best:")){const W=z(k.content,{});W.author&&(K=` \xB7 \u{1F464} ${W.author}`)}const F=k.contextBoost?" \xB7 \u{1F4C1} context match":"",U=k.matchType==="hybrid"?`BM25: ${(k.bm25Score??0).toFixed(2)}, sem: ${((k.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:k.matchType==="semantic"?`sem: ${((k.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(k.bm25Score??0).toFixed(2)}, matched: ${k.matchedWords?.join(", ")}`,J=ot(k.key,k.content,r?220:400);C.push(r?`**${G}**`:`**${G}**${K}${F} _(${U})_`);{const W=z(k.content??"",{});W.entscheidung?.gegen&&C.push(ft({gegen:W.entscheidung.gegen,grund:W.entscheidung.grund??null}))}if(k.key.startsWith("cachly:lesson:best:")){const W=await o.get(k.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await o.get(k.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),le=W?z(W,{}):{};le.title&&C.push(`\u{1F4D6} **${le.title}** \u2014 ${le.summary??""}`)}for(const W of J)C.push(`> ${W}`);C.push("")}if(g&&i.zurueckgehalten>0){const k=i.zurueckgehalten;C.push(`\u{1F512} **Free recall limit reached** (${m.used}/${m.limit} this month). Showing your top match; ${k} further relevant lesson${k!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${en}
26
- `)}}else{C.push(`\u26A0\uFE0F No matches found for: "${t}"`),O.length>0&&C.push("",...O.map(k=>`> ${k}`));const c=Ge(t),v=[];if(rt.size>0&&c.length>0)for(const k of c.slice(0,3)){if(k.length<4)continue;let G=3,K="";for(const F of rt){if(F.length<3||Math.abs(F.length-k.length)>4)continue;const U=Yt(k,F);U>0&&U<G&&(G=U,K=F)}K&&v.push(`"${K}" (instead of "${k}")`)}v.length>0?C.push(`\u{1F4A1} **Did you mean:** ${v.join(", ")}?`):(C.push(`
27
- \u{1F4A1} Tips:`),C.push(" \u2022 Try different keywords"),C.push(" \u2022 Use `list_remembered` to see available context"),C.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!r&&E.length>0){C.push(""),C.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 c=E.filter(v=>v.key.startsWith("cachly:lesson:best:")).map(v=>v.key.slice(19));if(c.length>0)try{await o.setex(`cachly:letzter-recall:${p}`,7200,JSON.stringify({frage:t,themen:c}))}catch{}}if(Y!==null&&s){const c=E.slice(0,N).filter(v=>v.key.startsWith("cachly:lesson:best:")).map(v=>v.key.slice(19));return Gt(o,Q,{...s,themen:c},C.join(`
21
+ `);const ye=ys(T);if(ye&&C.push(ye,""),vt(o,p,ye?"knapp":"beantwortet"),E.length>0){const c=E.some(v=>v.ckgScore!==void 0),k=e.length>0&&c?"keyword + semantic + CKG hybrid":e.length>0?"keyword + semantic hybrid":c?"keyword + CKG hybrid":"keyword";if(C.push(`### \u{1F50D} Results (${E.length} \u2014 ${k})
22
+ `),fe.belegte<E.length){const v=[];for(const K of E){if(!K.key.startsWith("cachly:lesson:best:")||!Bt({wortBelege:K.wortBelege,semScore:K.semScore,ckgScore:K.ckgScore}))continue;const W=z(K.content,{}),U=Date.parse(W.verified_at??W.ts??"");Number.isFinite(U)&&v.push(Math.floor((Date.now()-U)/864e5))}const G=Dt(v);C.push(`> \u{1F4CA} ${fe.belegte} von ${E.length} belegt (mind. ein getroffenes Wort, Bedeutungsn\xE4he oder Kante). Die \xFCbrigen sind das N\xE4chstliegende, kein Beleg.`+(G?` \u23F3 ${G}`:"")+`
23
+ `)}if(O.length>0&&C.push(...O.map(v=>`> ${v}`),""),ce.length>1){const v=new Map,G=gt({ueberLimit:g,gesamt:E.length,volleTiefe:Rs});for(const U of E.slice(0,G.sichtbar)){const J=U.subQuery??t;v.has(J)||v.set(J,[]),v.get(J).push(U)}for(const[U,J]of v){C.push(`**Topic: "${U}"** (${J.length} results)
24
+ `);for(const F of J.slice(0,r?2:4)){const le=F.key.replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),$e=F.matchType==="ckg"?`CKG: ${(F.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:F.ckgScore!==void 0&&F.bm25Score!==void 0?`BM25: ${F.bm25Score.toFixed(2)}, CKG: ${F.ckgScore.toFixed(2)}, \u{1F500} hybrid`:F.matchType==="hybrid"?`BM25: ${(F.bm25Score??0).toFixed(2)}, sem: ${((F.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:F.matchType==="semantic"?`sem: ${((F.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(F.bm25Score??0).toFixed(2)}, matched: ${F.matchedWords?.join(", ")}`,we=ot(F.key,F.content,r&&F.key.startsWith("cachly:lesson:best:")?220:300);if(C.push(r?` **${le}**`:` **${le}** _(${$e})_`),F.key.startsWith("cachly:lesson:best:")){const I=await o.get(F.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await o.get(F.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),P=I?z(I,{}):{};P.title&&C.push(` \u{1F4D6} **${P.title}** \u2014 ${P.summary??""}`)}for(const I of we)C.push(` > ${I}`);C.push("")}}const K=[...v.keys()],W=ce.filter(U=>!K.includes(U));W.length>0&&C.push(`
25
+ \u26A0\uFE0F **No results for:** ${W.map(U=>`"${U}"`).join(", ")}`)}else for(const v of E.slice(0,N)){const G=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 F=z(v.content,{});F.author&&(K=` \xB7 \u{1F464} ${F.author}`)}const W=v.contextBoost?" \xB7 \u{1F4C1} context match":"",U=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(", ")}`,J=ot(v.key,v.content,r&&v.key.startsWith("cachly:lesson:best:")?220:400);C.push(r?`**${G}**`:`**${G}**${K}${W} _(${U})_`);{const F=z(v.content??"",{});F.entscheidung?.gegen&&C.push(ft({gegen:F.entscheidung.gegen,grund:F.entscheidung.grund??null}))}if(v.key.startsWith("cachly:lesson:best:")){const F=await o.get(v.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await o.get(v.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),le=F?z(F,{}):{};le.title&&C.push(`\u{1F4D6} **${le.title}** \u2014 ${le.summary??""}`)}for(const F of J)C.push(`> ${F}`);C.push("")}if(g&&i.zurueckgehalten>0){const v=i.zurueckgehalten;C.push(`\u{1F512} **Free recall limit reached** (${m.used}/${m.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 ${en}
26
+ `)}}else{C.push(`\u26A0\uFE0F No matches found for: "${t}"`),O.length>0&&C.push("",...O.map(v=>`> ${v}`));const c=Ge(t),k=[];if(rt.size>0&&c.length>0)for(const v of c.slice(0,3)){if(v.length<4)continue;let G=3,K="";for(const W of rt){if(W.length<3||Math.abs(W.length-v.length)>4)continue;const U=Yt(v,W);U>0&&U<G&&(G=U,K=W)}K&&k.push(`"${K}" (instead of "${v}")`)}k.length>0?C.push(`\u{1F4A1} **Did you mean:** ${k.join(", ")}?`):(C.push(`
27
+ \u{1F4A1} Tips:`),C.push(" \u2022 Try different keywords"),C.push(" \u2022 Use `list_remembered` to see available context"),C.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!r&&E.length>0){C.push(""),C.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 c=E.filter(k=>k.key.startsWith("cachly:lesson:best:")).map(k=>k.key.slice(19));if(c.length>0)try{await o.setex(`cachly:letzter-recall:${p}`,7200,JSON.stringify({frage:t,themen:c}))}catch{}}if(Y!==null&&s){const c=E.slice(0,N).filter(k=>k.key.startsWith("cachly:lesson:best:")).map(k=>k.key.slice(19));return Gt(o,Q,{...s,themen:c},C.join(`
28
28
  `))}return C.join(`
29
29
  `)}case"session_start":{const{instance_id:p,focus:t="",author:n="",provider:w="",workspace_path:A=""}=Z,f=await X(p),o=[],b=f.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((s,m)=>{b.on("data",g=>o.push(...g)),b.on("end",s),b.on("error",m)});const h=[];if(o.length>0){const s=await f.mget(...o);for(const m of s){const g=z(m??null,null);g&&h.push(g)}}h.sort((s,m)=>new Date(m.ts).getTime()-new Date(s.ts).getTime());let u=0;const d=f.scanStream({match:"cachly:ctx:*",count:200});await new Promise((s,m)=>{d.on("data",g=>{u+=g.filter(i=>!i.endsWith(":meta")).length}),d.on("end",s),d.on("error",m)});const S=await f.get("cachly:session:last"),T=z(S,null),a=t.toLowerCase().split(/\s+/).filter(Boolean),l=a.length>0?h.filter(s=>a.some(m=>s.topic.toLowerCase().includes(m)||(s.tags??[]).some(g=>g.toLowerCase().includes(m)))):[];let x=0,y=0,$="";try{const s=await f.get("cachly:streak:current"),m=z(s,null),g=new Date().toISOString().slice(0,10);if(m){const i=m.last_date,r=new Date(Date.now()-864e5).toISOString().slice(0,10);i===g?(x=m.days,y=m.record):i===r?(x=m.days+1,y=Math.max(x,m.record),await f.set("cachly:streak:current",JSON.stringify({days:x,last_date:g,record:y}))):(x=1,y=m.record,await f.set("cachly:streak:current",JSON.stringify({days:1,last_date:g,record:y})))}else x=1,y=1,await f.set("cachly:streak:current",JSON.stringify({days:1,last_date:g,record:1}));x>=7?$=`\u{1F525} **${x}-day streak!** ${x===y?" New record!":`Best: ${y}d`}`:x>1&&($=`\u{1F525} ${x}-day streak`)}catch{}await f.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:t,provider:w}),"EX",86400);let R=0;try{const s=await f.get(`cachly:stats:time_saved_mins:${p}`);R=parseFloat(s??"0")}catch{}const e=[`\u{1F9E0} **Session Briefing**${w?` \xB7 ${w}`:""}`,""];if($&&e.push($,""),R>=30){const s=Math.floor(R/60),m=Math.round(R%60),g=s>0?`${s}h${m>0?` ${m}m`:""}`:`${m}m`,i=h.filter(N=>!Me(N)&&(N.recall_count??0)>0).length,r=i>0?` \u2014 ${i} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";e.push(`\u23F1\uFE0F **Brain saved you ~${g} total**${r}`,"")}const H=await kt(p,ue),_=Ms({used:H.used,limit:H.limit,savedMins:R});if(_&&e.push(_,""),H.notice&&!_t.has(p)&&(_t.add(p),e.push(H.notice,"")),T?.ts){const s=new Date(T.ts).getTime(),m=Math.floor((Date.now()-s)/864e5);if(m>=7&&!Number.isNaN(s)){const g=h.filter(i=>{const r=new Date(i.ts).getTime();return!Number.isNaN(r)&&r>s});if(e.push(`\u{1F44B} **Welcome back** \u2014 it's been ${m} days since your last session.`),g.length>0){const i=g.slice(0,3).map(r=>`\`${r.topic}\``).join(", ");e.push(` \u{1F331} Your Brain grew by **${g.length} lesson${g.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${i}${g.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")!==Be){await f.set("cachly:mcp:version:last_seen",Be,"EX",365*86400);const m=Qs[Be];if(m){e.push(...m,"");const g=Xs();g&&e.push(`\u{1F4CA} ${g} MCP tools`,"")}}}catch{}const ne=!T&&h.length===0&&u===0;if(ne&&(e.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),A?(e.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),e.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(e.push("It learns from your work automatically. After your first session it will look like this:",""),e.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),e.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),e.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),e.push(""),e.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),e.push("")),e.push("**Your brain grows automatically:**"),e.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),e.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),e.push(""),e.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),e.push(" `smart_recall` returns a hit instead of nothing:"),e.push(` \`brain_seed_starter(instance_id="${p}")\``),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("")),n&&!ne)try{const s=`cachly:team:first_briefing:${n}`;if(!await f.get(s)){const g=h.filter(i=>i.author&&i.author!==n);if(g.length>0){await f.set(s,"1","EX",365*86400);const i=new Map;for(const r of g){const N=r.author;i.has(N)||i.set(N,[]),i.get(N).push(r)}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[r,N]of i){e.push(` \u{1F464} **${r}** fixed ${N.length} thing${N.length>1?"s":""}:`);for(const C of N.slice(0,2)){const j=C.outcome==="success"?"\u2705":"\u26A0\uFE0F";e.push(` ${j} \`${C.topic}\` \u2014 ${C.what_worked.slice(0,90)}`)}N.length>2&&e.push(` \u2026 and ${N.length-2} more lessons`)}e.push(""),e.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),e.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),e.push("")}}}catch{}const oe=await f.get("cachly:session:handoff");if(oe)try{const s=JSON.parse(oe),m=Math.round((Date.now()-new Date(s.ts).getTime())/6e4),g=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** (${g}):`),s.context_summary&&e.push(` ${s.context_summary}`),s.remaining_tasks.length>0){e.push(" \u23F3 **Remaining tasks:**");for(const r of s.remaining_tasks)e.push(` - ${r}`)}s.completed_tasks.length>0&&e.push(` \u2705 **Already done:** ${s.completed_tasks.join(", ")}`);const i=(s.files_changed??[]).filter(r=>r.status==="broken"||r.status==="partial");i.length>0&&e.push(` \u26A0\uFE0F **Needs fix:** ${i.map(r=>`\`${r.path}\` (${r.status}${r.description?": "+r.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 V=await f.get("cachly:session:checkpoint");if(V)try{const s=JSON.parse(V),m=new Date(s.ts).getTime(),g=T?new Date(T.ts).getTime():0;if(m>g){const i=Math.round((Date.now()-m)/6e4),r=i<60?`${i}m ago`:i<1440?`${Math.round(i/60)}h ago`:`${Math.round(i/1440)}d ago`,N=s.provider?` [${s.provider}]`:"";e.push(`\u{1F4CC} **Last checkpoint**${N} (${r}): ${s.task}`),s.files_touched.length>0&&e.push(` Files: ${s.files_touched.slice(0,5).map(C=>`\`${C}\``).join(", ")}`),s.next_step&&e.push(` \u{1F4CD} Next step was: ${s.next_step}`),(!T||m-g>3e5)&&e.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),e.push("")}}catch{}if(A&&!T)try{const{execSync:s}=await import("node:child_process"),m=s(`git -C "${A}" log --oneline --format="%h %s" -15 2>/dev/null`,{encoding:"utf-8",timeout:5e3}).trim(),g=s(`git -C "${A}" diff --stat HEAD~3 2>/dev/null || git -C "${A}" 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 i of m.split(`
30
30
  `).slice(0,8))e.push(` ${i}`);if(g){const i=g.split(`
31
- `).filter(r=>r.includes("|")||r.includes("changed"));if(i.length>0){e.push(" **Recent changes:**");for(const r of i.slice(0,5))e.push(` ${r.trim()}`)}}e.push("")}}catch{}if(T){const s=Math.round((Date.now()-new Date(T.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}): ${T.summary}`),T.duration_min&&e.push(` Duration: ${T.duration_min} min`),(T.files_changed??[]).length>0&&e.push(` Files: ${(T.files_changed??[]).slice(0,5).map(g=>`\`${g}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${h.length} lessons \xB7 ${u} context entries`,"");{const m=h.filter(g=>!Me(g)).filter(g=>g.outcome==="success"&&(g.pinned===!0||(g.recall_count??0)>=5)).sort((g,i)=>(i.recall_count??0)-(g.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 g of m){const i=g.severity==="critical"?"\u{1F534}":g.severity==="major"?"\u{1F7E1}":"",r=g.recall_count??0,N=g.pinned===!0?"pinned":`recalled ${r}\xD7`,C=Te(g);e.push(` \u{1F3C6}${i} \`${g.topic}\` _(${N})_ \u2014 ${C[0]??""}`,...C.slice(1))}e.push("")}}if(h.length>=3){const s=new Map;for(const i of h){const r=i.topic.split(":")[0]??"other";s.has(r)||s.set(r,{total:0,success:0,critical:0});const N=s.get(r);N.total++,i.outcome==="success"&&N.success++,i.severity==="critical"&&N.critical++}const m=[...s.entries()].sort((i,r)=>r[1].total-i[1].total).slice(0,6),g=m.some(([,i])=>i.success<i.total*.4&&i.total>=2);if(m.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[i,r]of m){const N=Math.round(r.success/r.total*100),C=Math.round(N/10),j="\u2588".repeat(C)+"\u2591".repeat(10-C),M=r.critical>0?" \u{1F534}":N<40&&r.total>=2?" \u26A0\uFE0F":"";e.push(` ${j} ${i.padEnd(18)} ${String(N).padStart(3)}% (${r.success}/${r.total} confirmed)${M}`)}g&&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((g,i)=>{m.on("data",r=>s.push(...r)),m.on("end",g),m.on("error",i)}),s.length>0){e.push(`\u26A1 **Active belief conflicts (${s.length}):**`);for(const g of s.slice(0,3)){const i=await f.get(g);if(!i)continue;const r=z(i,null);r&&e.push(` \u26A0\uFE0F \`${r.topic}\` \u2014 previously confirmed fix (${(r.fix_confidence*100).toFixed(0)}%, n=${r.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${he(r.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(g=>g.length>3),m=[];for(const g of s.slice(0,6))if(!await f.exists(`cachly:ckg:node:${g}`)){const r=[],N=f.scanStream({match:`cachly:ckg:node:${g}*`,count:10});await new Promise((C,j)=>{N.on("data",M=>r.push(...M)),N.on("end",C),N.on("error",j)}),r.length===0&&m.push(g)}if(m.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const g of m.slice(0,3))e.push(` \u2B1C \`${g}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${g}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${g}")\` \u2014 search global commons`);e.push("")}}catch{}if(l.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const s of l.slice(0,4)){const m=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",g=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":"",i=Te(s);e.push(` ${m}${g} \`${s.topic}\` \u2014 ${i[0]??""}`,...i.slice(1))}e.push("")}if(h.length>0){const m=[...h].filter(i=>!Me(i)).sort((i,r)=>(r.recall_count??0)-(i.recall_count??0)).filter(i=>(i.recall_count??0)>0).slice(0,3),g=(l.length>0?h.filter(i=>!l.includes(i)):h).filter(i=>!m.includes(i)).slice(0,l.length>0?3:4);if(m.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${m[0].recall_count}\xD7 before):`);for(const i of m){const r=i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C",N=i.severity==="critical"?"\u{1F534}":i.severity==="major"?"\u{1F7E1}":"",C=i.recall_count??0,j=i.authors??(i.author?[i.author]:[]),M=new Set(j.filter(Boolean)).size,B=M>=2&&C>=5||C>=10?" \u{1F3C6}":M>=2||C>=5?" \u2705":"",ce=C>1?` _(${C}\xD7 recalled)_`:"",fe=Te(i);e.push(` ${r}${N}${B} \`${i.topic}\`${ce} \u2014 ${fe[0]??""}`,...fe.slice(1))}e.push("")}if(g.length>0){const i=m.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(i);for(const r of g){const N=r.outcome==="success"?"\u2705":r.outcome==="partial"?"\u26A0\uFE0F":"\u274C",C=r.severity==="critical"?"\u{1F534}":r.severity==="major"?"\u{1F7E1}":"",j=Te(r);e.push(` ${N}${C} \`${r.topic}\` \u2014 ${j[0]??""}`,...j.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 E=h.filter(s=>s.outcome==="failure"||s.outcome==="partial");if(E.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${E.length} topic${E.length>1?"s":""} with no success yet):`);for(const s of E.slice(0,3))e.push(` \u274C \`${s.topic}\` \u2014 ${(s.what_failed??s.what_worked).slice(0,80)}`);e.push("")}const O=h.filter(s=>s.outcome!=="success"&&s.outcome!=="partial"?!1:Ae(s)<et);if(O.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Nt}d \u2014 verify before applying):`);for(const s of O.slice(0,4)){const m=Ae(s),g=Math.round((Date.now()-new Date(s.verified_at??s.ts).getTime())/864e5),i=m<Tt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${i} \`${s.topic}\` \u2014 ${g}d stale, ${(m*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const se=T;if(se?.decision_log?.length){const s=se.decision_log,m=s.filter(i=>i.outcome==="success"),g=s.filter(i=>i.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(i=>`\`${i.topic}\``).join(", ")}`),g.length>0&&e.push(` \u274C Failed: ${g.slice(0,3).map(i=>`\`${i.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=N=>{const C=new Set;for(const j of N)for(const M of j.toLowerCase().split(/[/\\._-]/))M.length>3&&!s.has(M)&&C.add(M);return[...C]};let g=a,i=t,r=!1;if(g.length===0&&T){const N=m(T.files_changed??[]),C=(T.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(j=>j.length>3&&!s.has(j));g=[...new Set([...N,...C])],i="where you left off last session",r=!0}if(g.length>0){const N=h.filter(C=>{if(C.outcome==="success")return!1;const j=C.topic.split(":")[0];return g.some(M=>C.topic.toLowerCase().includes(M)||j===M||(C.tags??[]).some(B=>B.toLowerCase()===M))});if(N.length>=1){const j=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",r?` You're likely to continue **${i}** \u2014 ${N.length} known pitfall${N.length>1?"s":""} there:`:` Known pitfalls for **"${i}"** (${N.length} past failure${N.length>1?"s":""}):`,...N.slice(0,3).map(M=>` \u274C \`${M.topic}\` \u2014 ${(M.what_failed??M.what_worked).slice(0,80)}`),""];e.splice(2,0,...j)}}}if(n){const s=Date.now()-6048e5,m=h.filter(g=>g.author&&g.author!==n&&new Date(g.ts).getTime()>s);if(m.length>0){const g=new Map;for(const i of m){const r=i.author;g.has(r)||g.set(r,[]),g.get(r).push(i)}e.push(`\u{1F465} **Team this week** (${m.length} lesson${m.length>1?"s":""} from teammates):`);for(const[i,r]of g){e.push(` \u{1F464} **${i}**:`);for(const N of r.slice(0,3)){const C=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${C} \`${N.topic}\` \u2014 ${N.what_worked.slice(0,80)}`)}r.length>3&&e.push(` \u2026 and ${r.length-3} more`)}e.push("")}}try{const s=await f.get("cachly:crystal:latest");if(s){const m=z(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 i of m.top_patterns.slice(0,3))e.push(` \u2022 **${i.category}** (${i.count}\xD7): ${i.insight.slice(0,90)}`);e.push("")}}}catch{}try{const s=await f.hgetall(`cachly:roadmap:${p}`);if(s&&Object.keys(s).length>0){const m={critical:0,high:1,medium:2,low:3},g={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},i=new Set(["planned","in-progress","blocked"]),r=Object.values(s).flatMap(j=>{const M=z(j,null);return M?[M]:[]}),N=r.filter(j=>i.has(j.status)).sort((j,M)=>j.status==="in-progress"&&M.status!=="in-progress"?-1:M.status==="in-progress"&&j.status!=="in-progress"?1:(m[j.priority]??99)-(m[M.priority]??99)),C=r.filter(j=>j.status==="done").length;if(N.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${N.length} open \xB7 ${C} done):`);for(const j of N.slice(0,5)){const M=j.status==="in-progress"?"\u26A1":j.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${M} ${g[j.priority]??"\u26AA"} \`${j.id}\` **${j.title}**`)}N.length>5&&e.push(` \u2026 and ${N.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(r=>r.length>2).slice(0,5),m=[];for(const r of s){const N=[],C=f.scanStream({match:`cachly:ckg:node:*${r}*`,count:20});await new Promise((j,M)=>{C.on("data",B=>N.push(...B)),C.on("end",j),C.on("error",M)});for(const j of N.slice(0,3)){const M=await f.get(j);if(!M)continue;const B=z(M,null);if(!B)continue;const ce=await f.smembers(`cachly:ckg:idx:from:${B.id}`);for(const fe of ce.slice(0,15)){const ye=await f.get(fe);if(!ye)continue;const c=z(ye,null);if(!c||c.edgeType!=="causes"&&c.edgeType!=="co-occurs"&&c.edgeType!=="fixes"||c.confidence<.35)continue;const v=c.edgeType==="fixes"?`cachly:lesson:best:${c.from}`:`cachly:lesson:best:${c.to}`,k=await f.get(v),G=z(k,null);m.push({concept:B.id,edgeType:c.edgeType,target:c.to,confidence:c.confidence,lesson:G??void 0})}}}const g=new Set,i=m.filter(r=>{const N=`${r.concept}:${r.target}`;return g.has(N)?!1:(g.add(N),!0)}).sort((r,N)=>N.confidence-r.confidence).slice(0,4);if(i.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const r of i){const N=Math.round(r.confidence*100),C=r.edgeType==="causes"?"\u26A1":r.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${C} **${N}%** \`${r.concept}\` ${r.edgeType} \`${r.target}\``),r.lesson?.what_worked&&e.push(` \u2705 ${r.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const s=await f.get("cachly:mcm:calibration:last"),m=z(s,null)?.ts??0;if((Date.now()-m)/864e5>=30&&h.length>=5){const i=h.filter(N=>N.outcome==="success"&&(N.recall_count??0)>0),r=h.filter(N=>(N.recall_count??0)>0);if(r.length>=3){const N=r.length>0?i.length/r.length:1,C=[],j=new Map;for(const M of r){const B=M.topic.split(":")[0]??"other";j.has(B)||j.set(B,{success:0,total:0});const ce=j.get(B);ce.total++,M.outcome==="success"&&ce.success++}for(const[M,B]of j)B.total>=2&&B.success/B.total<.6&&C.push(M);await f.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:N,recalled:r.length,low_precision_domains:C})),(C.length>0||N<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${r.length} recalled lessons):`),e.push(` Overall precision: **${(N*100).toFixed(0)}%** recalled lessons actually worked`),C.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${C.map(M=>`\`${M}\``).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 Y=h.filter(s=>s.outcome==="failure"||s.outcome==="partial").length>0,Q=h.some(s=>s.outcome==="success"&&Ae(s)<et);if(h.length===0||Y||Q){const s=[];h.length===0&&s.push("brain is empty"),Y&&s.push("open failures"),Q&&s.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${s.join(", ")}._`)}try{if(await f.get(`cachly:prefs:auto_changelog:${p}`).catch(()=>null)!=="false"&&T?.ts&&!ne){const g=new Date(T.ts).getTime();if(!Number.isNaN(g)){const i=h.filter(r=>{const N=new Date(r.ts).getTime();return!Number.isNaN(N)&&N>g});if(i.length>0){const r=Math.round((Date.now()-g)/6e4),N=r<60?`${r}m`:r<1440?`${Math.round(r/60)}h`:`${Math.round(r/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${i.length} new lesson${i.length!==1?"s":""} since your last session** (${N} ago):`);const C=new Map;for(const j of i.slice(0,20)){const M=j.topic.includes(":")?j.topic.split(":")[0]:"general",B=C.get(M)??[];B.push(j),C.set(M,B)}for(const[j,M]of C){e.push(` **${j}**`);for(const B of M){const ce=B.outcome==="failure"?"\u274C":B.severity==="critical"?"\u{1F6A8}":B.severity==="major"?"\u26A0\uFE0F":"\u2705",fe=(B.outcome==="failure"?B.what_failed:B.what_worked)??"";e.push(` ${ce} \`${B.topic}\`${fe?` \u2014 ${fe.slice(0,80)}`:""}`)}}i.length>20&&e.push(` \u2026 and ${i.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${p}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
31
+ `).filter(r=>r.includes("|")||r.includes("changed"));if(i.length>0){e.push(" **Recent changes:**");for(const r of i.slice(0,5))e.push(` ${r.trim()}`)}}e.push("")}}catch{}if(T){const s=Math.round((Date.now()-new Date(T.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}): ${T.summary}`),T.duration_min&&e.push(` Duration: ${T.duration_min} min`),(T.files_changed??[]).length>0&&e.push(` Files: ${(T.files_changed??[]).slice(0,5).map(g=>`\`${g}\``).join(", ")}`),e.push("")}e.push(`\u{1F4CA} **Brain:** ${h.length} lessons \xB7 ${u} context entries`,"");{const m=h.filter(g=>!Me(g)).filter(g=>g.outcome==="success"&&(g.pinned===!0||(g.recall_count??0)>=5)).sort((g,i)=>(i.recall_count??0)-(g.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 g of m){const i=g.severity==="critical"?"\u{1F534}":g.severity==="major"?"\u{1F7E1}":"",r=g.recall_count??0,N=g.pinned===!0?"pinned":`recalled ${r}\xD7`,C=Te(g);e.push(` \u{1F3C6}${i} \`${g.topic}\` _(${N})_ \u2014 ${C[0]??""}`,...C.slice(1))}e.push("")}}if(h.length>=3){const s=new Map;for(const i of h){const r=i.topic.split(":")[0]??"other";s.has(r)||s.set(r,{total:0,success:0,critical:0});const N=s.get(r);N.total++,i.outcome==="success"&&N.success++,i.severity==="critical"&&N.critical++}const m=[...s.entries()].sort((i,r)=>r[1].total-i[1].total).slice(0,6),g=m.some(([,i])=>i.success<i.total*.4&&i.total>=2);if(m.length>0){e.push("\u{1F5FA}\uFE0F **Knowledge Coverage:**");for(const[i,r]of m){const N=Math.round(r.success/r.total*100),C=Math.round(N/10),j="\u2588".repeat(C)+"\u2591".repeat(10-C),M=r.critical>0?" \u{1F534}":N<40&&r.total>=2?" \u26A0\uFE0F":"";e.push(` ${j} ${i.padEnd(18)} ${String(N).padStart(3)}% (${r.success}/${r.total} confirmed)${M}`)}g&&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((g,i)=>{m.on("data",r=>s.push(...r)),m.on("end",g),m.on("error",i)}),s.length>0){e.push(`\u26A1 **Active belief conflicts (${s.length}):**`);for(const g of s.slice(0,3)){const i=await f.get(g);if(!i)continue;const r=z(i,null);r&&e.push(` \u26A0\uFE0F \`${r.topic}\` \u2014 previously confirmed fix (${(r.fix_confidence*100).toFixed(0)}%, n=${r.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${he(r.topic)}")\``)}e.push("")}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(g=>g.length>3),m=[];for(const g of s.slice(0,6))if(!await f.exists(`cachly:ckg:node:${g}`)){const r=[],N=f.scanStream({match:`cachly:ckg:node:${g}*`,count:10});await new Promise((C,j)=>{N.on("data",M=>r.push(...M)),N.on("end",C),N.on("error",j)}),r.length===0&&m.push(g)}if(m.length>0){e.push("\u{1F52D} **Blind spots detected for this focus:**");for(const g of m.slice(0,3))e.push(` \u2B1C \`${g}\` \u2014 no CKG knowledge. Suggestions:`),e.push(` \u2022 \`brain_from_git(instance_id="...", concept="${g}")\` \u2014 bootstrap from commits`),e.push(` \u2022 \`fedbrain_search(query="${g}")\` \u2014 search global commons`);e.push("")}}catch{}if(l.length>0){e.push(`\u{1F3AF} **Relevant for "${t}":**`);for(const s of l.slice(0,4)){const m=s.outcome==="success"?"\u2705":s.outcome==="partial"?"\u26A0\uFE0F":"\u274C",g=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":"",i=Te(s);e.push(` ${m}${g} \`${s.topic}\` \u2014 ${i[0]??""}`,...i.slice(1))}e.push("")}if(h.length>0){const m=[...h].filter(i=>!Me(i)).sort((i,r)=>(r.recall_count??0)-(i.recall_count??0)).filter(i=>(i.recall_count??0)>0).slice(0,3),g=(l.length>0?h.filter(i=>!l.includes(i)):h).filter(i=>!m.includes(i)).slice(0,l.length>0?3:4);if(m.length>0){e.push(`\u{1F3C6} **Most valuable** (recalled ${m[0].recall_count}\xD7 before):`);for(const i of m){const r=i.outcome==="success"?"\u2705":i.outcome==="partial"?"\u26A0\uFE0F":"\u274C",N=i.severity==="critical"?"\u{1F534}":i.severity==="major"?"\u{1F7E1}":"",C=i.recall_count??0,j=i.authors??(i.author?[i.author]:[]),M=new Set(j.filter(Boolean)).size,B=M>=2&&C>=5||C>=10?" \u{1F3C6}":M>=2||C>=5?" \u2705":"",ce=C>1?` _(${C}\xD7 recalled)_`:"",fe=Te(i);e.push(` ${r}${N}${B} \`${i.topic}\`${ce} \u2014 ${fe[0]??""}`,...fe.slice(1))}e.push("")}if(g.length>0){const i=m.length>0?"\u{1F550} **Recent:**":"\u{1F550} **Recent lessons:**";e.push(i);for(const r of g){const N=r.outcome==="success"?"\u2705":r.outcome==="partial"?"\u26A0\uFE0F":"\u274C",C=r.severity==="critical"?"\u{1F534}":r.severity==="major"?"\u{1F7E1}":"",j=Te(r);e.push(` ${N}${C} \`${r.topic}\` \u2014 ${j[0]??""}`,...j.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 E=h.filter(s=>s.outcome==="failure"||s.outcome==="partial");if(E.length>0){e.push(`\u26A0\uFE0F **Unresolved** (${E.length} topic${E.length>1?"s":""} with no success yet):`);for(const s of E.slice(0,3))e.push(` \u274C \`${s.topic}\` \u2014 ${(s.what_failed??s.what_worked).slice(0,80)}`);e.push("")}const O=h.filter(s=>s.outcome!=="success"&&s.outcome!=="partial"?!1:Ae(s)<et);if(O.length>0){e.push(`\u{1F534} **Stale lessons** (not recalled in >${Nt}d \u2014 verify before applying):`);for(const s of O.slice(0,4)){const m=Ae(s),g=Math.round((Date.now()-new Date(s.verified_at??s.ts).getTime())/864e5),i=m<Tt?"\u{1F534}":"\u26A0\uFE0F";e.push(` ${i} \`${s.topic}\` \u2014 ${g}d stale, ${(m*100).toFixed(0)}% confidence`)}e.push(" _Run `recall_best_solution` on these to reset their confidence clock._"),e.push("")}const se=T;if(se?.decision_log?.length){const s=se.decision_log,m=s.filter(i=>i.outcome==="success"),g=s.filter(i=>i.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(i=>`\`${i.topic}\``).join(", ")}`),g.length>0&&e.push(` \u274C Failed: ${g.slice(0,3).map(i=>`\`${i.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=N=>{const C=new Set;for(const j of N)for(const M of j.toLowerCase().split(/[/\\._-]/))M.length>3&&!s.has(M)&&C.add(M);return[...C]};let g=a,i=t,r=!1;if(g.length===0&&T){const N=m(T.files_changed??[]),C=(T.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(j=>j.length>3&&!s.has(j));g=[...new Set([...N,...C])],i="where you left off last session",r=!0}if(g.length>0){const N=h.filter(C=>{if(C.outcome==="success")return!1;const j=C.topic.split(":")[0];return g.some(M=>C.topic.toLowerCase().includes(M)||j===M||(C.tags??[]).some(B=>B.toLowerCase()===M))});if(N.length>=1){const j=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",r?` You're likely to continue **${i}** \u2014 ${N.length} known pitfall${N.length>1?"s":""} there:`:` Known pitfalls for **"${i}"** (${N.length} past failure${N.length>1?"s":""}):`,...N.slice(0,3).map(M=>` \u274C \`${M.topic}\` \u2014 ${(M.what_failed??M.what_worked).slice(0,80)}`),""];e.splice(2,0,...j)}}}if(n){const s=Date.now()-6048e5,m=h.filter(g=>g.author&&g.author!==n&&new Date(g.ts).getTime()>s);if(m.length>0){const g=new Map;for(const i of m){const r=i.author;g.has(r)||g.set(r,[]),g.get(r).push(i)}e.push(`\u{1F465} **Team this week** (${m.length} lesson${m.length>1?"s":""} from teammates):`);for(const[i,r]of g){e.push(` \u{1F464} **${i}**:`);for(const N of r.slice(0,3)){const C=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C";e.push(` ${C} \`${N.topic}\` \u2014 ${N.what_worked.slice(0,80)}`)}r.length>3&&e.push(` \u2026 and ${r.length-3} more`)}e.push("")}}try{const s=await f.get("cachly:crystal:latest");if(s){const m=z(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 i of m.top_patterns.slice(0,3))e.push(` \u2022 **${i.category}** (${i.count}\xD7): ${i.insight.slice(0,90)}`);e.push("")}}}catch{}try{const s=await f.hgetall(`cachly:roadmap:${p}`);if(s&&Object.keys(s).length>0){const m={critical:0,high:1,medium:2,low:3},g={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},i=new Set(["planned","in-progress","blocked"]),r=Object.values(s).flatMap(j=>{const M=z(j,null);return M?[M]:[]}),N=r.filter(j=>i.has(j.status)).sort((j,M)=>j.status==="in-progress"&&M.status!=="in-progress"?-1:M.status==="in-progress"&&j.status!=="in-progress"?1:(m[j.priority]??99)-(m[M.priority]??99)),C=r.filter(j=>j.status==="done").length;if(N.length>0){e.push(`\u{1F5FA}\uFE0F **Roadmap** (${N.length} open \xB7 ${C} done):`);for(const j of N.slice(0,5)){const M=j.status==="in-progress"?"\u26A1":j.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";e.push(` ${M} ${g[j.priority]??"\u26AA"} \`${j.id}\` **${j.title}**`)}N.length>5&&e.push(` \u2026 and ${N.length-5} more`),e.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),e.push("")}}}catch{}if(t&&t.length>3)try{const s=t.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(r=>r.length>2).slice(0,5),m=[];for(const r of s){const N=[],C=f.scanStream({match:`cachly:ckg:node:*${r}*`,count:20});await new Promise((j,M)=>{C.on("data",B=>N.push(...B)),C.on("end",j),C.on("error",M)});for(const j of N.slice(0,3)){const M=await f.get(j);if(!M)continue;const B=z(M,null);if(!B)continue;const ce=await f.smembers(`cachly:ckg:idx:from:${B.id}`);for(const fe of ce.slice(0,15)){const ye=await f.get(fe);if(!ye)continue;const c=z(ye,null);if(!c||c.edgeType!=="causes"&&c.edgeType!=="co-occurs"&&c.edgeType!=="fixes"||c.confidence<.35)continue;const k=c.edgeType==="fixes"?`cachly:lesson:best:${c.from}`:`cachly:lesson:best:${c.to}`,v=await f.get(k),G=z(v,null);m.push({concept:B.id,edgeType:c.edgeType,target:c.to,confidence:c.confidence,lesson:G??void 0})}}}const g=new Set,i=m.filter(r=>{const N=`${r.concept}:${r.target}`;return g.has(N)?!1:(g.add(N),!0)}).sort((r,N)=>N.confidence-r.confidence).slice(0,4);if(i.length>0){e.push(`\u{1F52E} **Predicted risks for "${t}"** (PPE pre-fetch):`);for(const r of i){const N=Math.round(r.confidence*100),C=r.edgeType==="causes"?"\u26A1":r.edgeType==="fixes"?"\u{1F527}":"\u{1F504}";e.push(` ${C} **${N}%** \`${r.concept}\` ${r.edgeType} \`${r.target}\``),r.lesson?.what_worked&&e.push(` \u2705 ${r.lesson.what_worked.slice(0,110)}`)}e.push(` _Full analysis: \`brain_predict(context="${t}")\`_`),e.push("")}}catch{}try{const s=await f.get("cachly:mcm:calibration:last"),m=z(s,null)?.ts??0;if((Date.now()-m)/864e5>=30&&h.length>=5){const i=h.filter(N=>N.outcome==="success"&&(N.recall_count??0)>0),r=h.filter(N=>(N.recall_count??0)>0);if(r.length>=3){const N=r.length>0?i.length/r.length:1,C=[],j=new Map;for(const M of r){const B=M.topic.split(":")[0]??"other";j.has(B)||j.set(B,{success:0,total:0});const ce=j.get(B);ce.total++,M.outcome==="success"&&ce.success++}for(const[M,B]of j)B.total>=2&&B.success/B.total<.6&&C.push(M);await f.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:N,recalled:r.length,low_precision_domains:C})),(C.length>0||N<.7)&&(e.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${r.length} recalled lessons):`),e.push(` Overall precision: **${(N*100).toFixed(0)}%** recalled lessons actually worked`),C.length>0&&e.push(` \u26A0\uFE0F Low-precision domains: ${C.map(M=>`\`${M}\``).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 Y=h.filter(s=>s.outcome==="failure"||s.outcome==="partial").length>0,Q=h.some(s=>s.outcome==="success"&&Ae(s)<et);if(h.length===0||Y||Q){const s=[];h.length===0&&s.push("brain is empty"),Y&&s.push("open failures"),Q&&s.push("stale lessons"),e.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${s.join(", ")}._`)}try{if(await f.get(`cachly:prefs:auto_changelog:${p}`).catch(()=>null)!=="false"&&T?.ts&&!ne){const g=new Date(T.ts).getTime();if(!Number.isNaN(g)){const i=h.filter(r=>{const N=new Date(r.ts).getTime();return!Number.isNaN(N)&&N>g});if(i.length>0){const r=Math.round((Date.now()-g)/6e4),N=r<60?`${r}m`:r<1440?`${Math.round(r/60)}h`:`${Math.round(r/1440)}d`;e.push(""),e.push(`\u{1F4CB} **${i.length} new lesson${i.length!==1?"s":""} since your last session** (${N} ago):`);const C=new Map;for(const j of i.slice(0,20)){const M=j.topic.includes(":")?j.topic.split(":")[0]:"general",B=C.get(M)??[];B.push(j),C.set(M,B)}for(const[j,M]of C){e.push(` **${j}**`);for(const B of M){const ce=B.outcome==="failure"?"\u274C":B.severity==="critical"?"\u{1F6A8}":B.severity==="major"?"\u26A0\uFE0F":"\u2705",fe=(B.outcome==="failure"?B.what_failed:B.what_worked)??"";e.push(` ${ce} \`${B.topic}\`${fe?` \u2014 ${fe.slice(0,80)}`:""}`)}}i.length>20&&e.push(` \u2026 and ${i.length-20} more. Call \`brain_changelog\` for the full list.`),e.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${p}", key="auto_changelog", value="false")\`_`)}}}}catch{}return e.join(`
32
32
  `)}case"session_start_summary":{const{instance_id:p,focus:t,top_n:n=10,author:w=""}=Z;if(!t||!t.trim())throw new Error("focus is required for session_start_summary");const A=Math.min(Math.max(1,Math.floor(Number(n)||10)),25),f=await X(p),o=[],b=f.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((e,H)=>{b.on("data",_=>o.push(..._)),b.on("end",e),b.on("error",H)});const h=[];if(o.length>0){const e=await f.mget(...o);for(const H of e){const _=z(H??null,null);_&&h.push(_)}}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="${p}")\` to bootstrap with 16 universal lessons.`].join(`
33
33
  `);const u=h.length>A,d=t.toLowerCase().split(/\s+/).filter(Boolean),S=Date.now(),T=h.map(e=>{const H=d.filter(s=>e.topic.toLowerCase().includes(s)).length,_=d.filter(s=>(e.tags??[]).some(m=>m.toLowerCase().includes(s))).length,ne=H*2+_,oe=Math.max(0,e.recall_count??0),V=Math.min(1.5,Math.log1p(oe)/10),E=e.severity==="critical"?1:e.severity==="major"?.5:0,O=(S-new Date(e.verified_at??e.ts).getTime())/864e5,se=O<30?.5*(1-O/30):0,Y=e.outcome==="success"?.5:e.outcome==="partial"?.2:0,Q=ne+V+E+se+Y;return{lesson:e,score:Q}});T.sort((e,H)=>H.score!==e.score?H.score-e.score:new Date(H.lesson.ts).getTime()-new Date(e.lesson.ts).getTime());const a=(u?T.slice(0,A):T).map(e=>e.lesson),l=h.length,x=a.length,R=[u?`\u{1F9E0} Brain Summary \u2014 top ${x} of ${l} 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 a){const H=e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u26A0\uFE0F":"\u2705",_=e.severity?`[${e.severity}] `:"[minor] ",ne=e.recall_count??0,oe=ne>0?` (\u2713 recalled ${ne}\xD7)`:"",V=e.what_worked.slice(0,110),E=Vs(e.author,w);R.push(`${H} ${_}\`${e.topic}\` \u2014 ${V}${oe}${E}`)}R.push("");const D=Ys(a,w);return D>0&&R.push(`\u{1F465} ${D} of these ${D===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),u?R.push(`\u{1F4A1} Showing top ${x} of ${l} lessons \xB7 \`session_start\` for full briefing`):R.push(`\u{1F4A1} All ${x} lesson${x!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),R.join(`
34
34
  `)}case"session_end":{const{instance_id:p,summary:t,files_changed:n=[],lessons_learned:w,workspace_path:A=""}=Z,f=await X(p),o=new Date;let b;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 u=z(h,null);u?.started&&(b=Math.round((o.getTime()-new Date(u.started).getTime())/6e4));let d=[];try{d=(await f.lrange("cachly:session:decision-log",0,-1)).flatMap(H=>{const _=z(H,null);return _?[_]:[]}),await f.del("cachly:session:decision-log")}catch{}const S={ts:o.toISOString(),summary:t,files_changed:n,...w!==void 0?{lessons_learned:w}:{},...b!==void 0?{duration_min:b}:{},...d.length>0?{decision_log:d}:{}};await f.set("cachly:session:last",JSON.stringify(S)),await f.lpush("cachly:session:history",JSON.stringify(S)),await f.ltrim("cachly:session:history",0,49),await f.expire("cachly:session:history",90*86400),await f.del("cachly:session:current");const T=[];try{const e=/\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,H=t.split(/[.!\n]+/).map(_=>_.trim()).filter(_=>_.length>20&&e.test(_));for(const _ of H.slice(0,6)){const oe=_.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(!oe)continue;const V=`auto:${oe}`,E=`cachly:lesson:best:${V}`,O=await f.get(E);if(O)try{if(JSON.parse(O).outcome==="success")continue}catch{}const se={topic:V,outcome:"success",what_worked:_,context:`Auto-learned from session summary. Full summary: ${t.slice(0,300)}`,severity:"minor",ts:o.toISOString(),recall_count:0,auto_learned:!0,session_ts:o.toISOString(),version:2};await f.set(E,JSON.stringify(se)),await f.expire(E,90*86400),T.push(V)}}catch{}const a=[];if(A)try{const e=h?(()=>{try{return JSON.parse(h).started??""}catch{return""}})():"",H=e?`--since="${e}"`:'--since="1 hour ago"',_=Xe(`git -C "${A}" log ${H} --oneline --format="%H|||%s|||%b|||%ai|||ENDE"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(_){const ne=/\b(fix|add|remove|refactor|migrate|update|resolve|implement|improve|optimize|configure|create|delete|disable|enable|debug|patch|upgrade|build|rewrite|deploy|feat|chore|docs|test|perf|ci)\b/i,oe=_.split("|||ENDE").map(V=>V.trim()).filter(Boolean);for(const V of oe.slice(0,10)){const[E,O,se,Y]=V.split("|||");if(E)try{const N=Xe(`git -C "${A}" diff-tree --no-commit-id --name-only -r --root "${E}"`,{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),j=N?N.split(`
@@ -70,4 +70,4 @@ ${n.map(a=>` - ${a}`).join(`
70
70
  `)}case"brain_changelog":{const{instance_id:p,days:t=7,max_lessons:n=30,include_failures:w=!0}=Z,A=await X(p),f=Date.now()-Number(t)*864e5,o=await _e(A,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),b=[];for(const l of o){const x=await A.get(l).catch(()=>null);if(!x)continue;const y=z(x,{});if((y.ts?new Date(y.ts).getTime():0)<f||!w&&y.outcome==="failure")continue;const R=l.replace("cachly:lesson:best:","");b.push({...y,topic:R})}b.sort((l,x)=>{const y=l.ts?new Date(l.ts).getTime():0;return(x.ts?new Date(x.ts).getTime():0)-y});const h=b.slice(0,Number(n));if(h.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(`
71
71
  `);const u=new Map;for(const l of h){const x=l.topic.includes(":")?l.topic.split(":")[0]:"general",y=u.get(x)??[];y.push(l),u.set(x,y)}const d=l=>l==="critical"?"\u{1F6A8}":l==="major"?"\u26A0\uFE0F":l==="minor"?"\u{1F4A1}":"\u2728",S=l=>l==="failure"?"\u274C":l==="partial"?"\u{1F536}":"\u2705",a=[`## \u{1F4CB} Brain Changelog \u2014 ${new Date().toISOString().slice(0,10)} (last ${t} day${Number(t)!==1?"s":""})`,"",`_${h.length} lesson${h.length!==1?"s":""} learned across ${u.size} topic area${u.size!==1?"s":""}_`,""];for(const[l,x]of Array.from(u.entries()).sort((y,$)=>$[1].length-y[1].length)){a.push(`### ${l}`),a.push("");for(const y of x){const $=y.outcome==="failure"?S(y.outcome):d(y.severity),R=y.outcome==="failure"?y.what_failed:y.what_worked,D=[];y.author&&D.push(`by **${y.author}**`),y.recall_count&&D.push(`${y.recall_count} recall${y.recall_count!==1?"s":""}`),y.confidence!==void 0&&D.push(`${Math.round(y.confidence*100)}% confidence`),a.push(`- ${$} **${y.topic}**${R?` \u2014 ${R}`:""}`),D.length&&a.push(` _${D.join(" \xB7 ")}_`)}a.push("")}return a.push("---",`_Generated from Brain \`${p}\` \xB7 Share this in your standup or Slack_`),a.join(`
72
72
  `)}case"brain_set_pref":{const{instance_id:p,key:t,value:n}=Z;if(!t||!t.trim())throw new Error("key is required");const w=await X(p),A=`cachly:prefs:${t.trim()}:${p}`;return await w.set(A,String(n)),`\u2705 Preference \`${t}\` set to \`${n}\` for this Brain instance.`}case"brain_get_pref":{const{instance_id:p,key:t}=Z,n=await X(p);if(t&&t.trim()){const o=await n.get(`cachly:prefs:${t.trim()}:${p}`).catch(()=>null);return o===null?`\u2139\uFE0F Preference \`${t}\` is not set (using default).`:`\u{1F527} Preference \`${t}\` = \`${o}\``}const w=await _e(n,`cachly:prefs:*:${p}`,{max:200,timeoutMs:2e3});if(w.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const A=await n.mget(...w),f=["\u{1F527} **Brain preferences:**",""];for(let o=0;o<w.length;o++){const b=w[o].replace("cachly:prefs:","").replace(`:${p}`,"");f.push(`- \`${b}\` = \`${A[o]??"(null)"}\``)}return f.join(`
73
- `)}default:return null}}async function St(ae,Z,X){try{if(!Ne())return;const ue=await ae.srandmember(xe,X),p=Array.isArray(ue)?ue:ue?[ue]:[];for(const t of p){if(t===Z)continue;const n=await ae.get(`cachly:lesson:best:${t}`);if(!n){await ae.srem(xe,t);continue}const w=z(n,{});try{const A=await be(De(w),{geduld:"lang"});if(A?.length)await ae.set(`${ct}${t}`,Ee(A)),await ae.srem(xe,t);else continue;if(ke==="cachly"||ke==="ollama")try{const f=await be(De(w),{geduld:"lang",modell:qe});f?.length&&await ae.set(`${He}${t}`,Ee(f))}catch{}}catch{}}}catch{}}export{zn as BRAIN_TOOL_NAMES,Fn as handleBrainTool,ot as recallVorschau};
73
+ `)}default:return null}}async function St(ae,Z,X){try{if(!Ne())return;const ue=await ae.srandmember(xe,X),p=Array.isArray(ue)?ue:ue?[ue]:[];for(const t of p){if(t===Z)continue;const n=await ae.get(`cachly:lesson:best:${t}`);if(!n){await ae.srem(xe,t);continue}const w=z(n,{});try{const A=await be(De(w),{geduld:"lang"});if(A?.length)await ae.set(`${ct}${t}`,Ee(A)),await ae.srem(xe,t);else continue;if(ke==="cachly"||ke==="ollama")try{const f=await be(De(w),{geduld:"lang",modell:qe});f?.length&&await ae.set(`${He}${t}`,Ee(f))}catch{}}catch{}}}catch{}}export{zn as BRAIN_TOOL_NAMES,Wn as handleBrainTool,ot as recallVorschau};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.155",
3
+ "version": "0.10.156",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.155",
3
+ "version": "0.10.156",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Your AI forgets everything between sessions. cachly fixes that permanently: 123 MCP tools for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run. Arrives pre-briefed. Free tier forever, EU servers, GDPR.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -6,13 +6,13 @@
6
6
  "url": "https://github.com/cachly-dev/cachly-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.10.155",
9
+ "version": "0.10.156",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "name": "@cachly-dev/mcp-server",
14
14
  "identifier": "@cachly-dev/mcp-server",
15
- "version": "0.10.155",
15
+ "version": "0.10.156",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }