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