@cachly-dev/mcp-server 0.10.285 → 0.10.287
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/handlers/brain.js +70 -70
- package/dist/src/handlers/context.js +12 -12
- package/dist/src/handlers/fedbrain.js +37 -37
- package/dist/src/handlers/syndicate.js +31 -31
- package/dist/src/handlers/team.js +46 -46
- package/dist/src/konto-bereich.js +1 -0
- package/dist/src/raeume.js +1 -1
- package/dist/src/rolle.js +3 -3
- package/dist/src/schluessel-klassen.js +1 -1
- package/dist/src/sitzungs-kennung.js +1 -0
- package/glama.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
import{gitLesen as qe,istCommitHash as Ps,pruefeOrdner as gt}from"../git-ohne-shell.js";import{createRequire as Ht}from"node:module";import{istMehrmandant as wt}from"../remote-zugang.js";import{calculateConfidence as Gt,confidenceBadge as js,STRUCTURED_TEMPLATES as Ws,CONFIDENCE_WARN_VALUE as Fs}from"../confidence.js";import{kurzfassenHinweis as Hs}from"../antwort-hinweis.js";import{pruefeMeldung as Gs,wendeAn as Ks}from"../pruefung-melden.js";import{ckgSlug as ke,extractProblemConcept as yt,ckgUpsertNode as Ye,ckgUpdateEdge as Te,ckgUpsertPersonNode as Vs,ckgUpsertFileNode as Kt,ckgRecordCollaboration as Js,ckgUpsertServiceNode as Us}from"../ckg.js";import{safeJsonParse as F,scanKeys as Le,leseOderNull as Pe,darfHeraus as _t}from"../utils.js";import{ersparteMinuten as Vt,istStarterLektion as qs,zaehltAlsErsparnis as Jt}from"../wertbeitrag.js";import{lessonPreviewLines as lt,trimTo as Ys}from"../lesson-preview.js";import{normalisiereZeit as bt,zaehleZeitangaben as $t}from"../zeit-normalisieren.js";import{abstentionSatz as Zs,alterssatzFuerBelegte as Xs,beurteileTreffer as Qs,istBelegt as Ut}from"../abstention.js";import{meldeEinmal as kt,meldeUndVermerke as st,fehlerText as ht,OHNE_VEKTOREN as en,OHNE_DIENST as tn,OHNE_FRAGEVEKTOR as sn,SINNPFAD_ABBRUCH as nn,OHNE_SCHREIBVEKTOR as ut}from"../aussetzer.js";import{versuchStart as on,neueKennung as an,wendeZuteilungAn as rn,schliesseVersuchAb as cn}from"../versuch.js";function vt(T,y,E,j=E){if(T.includes("lesson:best:")){const n=F(y,{});if(n&&typeof n=="object"&&(n.what_worked||n.what_failed||n.commands?.length))return lt(n,{maxChars:E,indent:" "})}const l=Ys(y,j);return l?[l]:[]}const qt=2e3,Yt=400;function St(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as ln,holeKantenVorrat as hn,SPEICHER_SCAN_SCHRITT as Zt}from"../kanten-vorrat.js";import{getRole as un,eigeneRolle as Ct,ROLE_BADGE as dn,getScopes as xt,lessonVisibleToScope as nt,reviewModeEnabled as fn,storeLessonProposal as pn,fragenderAusweis as dt,sichtbarFuer as je,NIEMAND as ot}from"./team.js";import{leseRaumLektion as mn,ladeRaumLektionen as gn,raumTreffer as wn,raeumeVon as Xt}from"../raeume.js";import{holeRolle as Tt,istMitglied as He,rolleFuer as yn,lerneUeberApi as _n,meldeAbrufe as Qt,darfDirektSchreiben as bn}from"../rolle.js";import{keywordSearch as ft,treffeUeberDateipfad as $n,wortindexEntwerten as es,tokenize as Nt,splitMultiQuery as kn,levenshtein as vn,indexVocab as ts,bestandHolen as Sn}from"../search.js";import{startetNochLeer as ss,leeresBrainAntwort as ns,startLageMitCommits as At,sofortAntwortNeuesBrain as Cn,neuesBrainBriefing as xn}from"../leeres-brain.js";import{rerankByQuality as Tn,qualityMultiplier as Nn,extractLessonQuality as An}from"../rerank.js";import{computeEmbedding as Ie,hasEmbedProvider as Ge,EMBED_PROVIDER as Ne}from"../embeddings.js";import{leserAktiv as En,leserPunkte as In,mischeMitLeser as Mn}from"../leser.js";import{repariereFelder as Rn}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Et,NAME_VEKTOR_PRAEFIX as pt,ZWEIT_VEKTOR_PRAEFIX as Ze,packe as Ve,textFuerVektor as Xe,textFuerNamensVektor as It,Vektorbestand as Mt,VEKTOR_NACHTRAG as Ln,NAME_VEKTOR_NACHTRAG as at,ZWEIT_VEKTOR_NACHTRAG as mt}from"../bedeutung.js";import{schreibeEingaenge as Bn,Eingangsbestand as On}from"../eingaenge.js";import{ordneNachHausordnung as Dn,rangWerte as zn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as Pn}from"../seltenheitsbestand.js";import{spurLegen as jn}from"../spuren.js";import{schlageErsetzungVor as Wn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as os,stufeSucheNachProjektversion as Fn,versionsNotizen as Hn,versionsBanner as Gn}from"../gueltigkeit-version.js";const Qe=Ln,Kn=365;import{etikettenFuer as Vn,lieferJournalSchluessel as as,JOURNAL_DECKEL as Jn}from"../etiketten.js";import{klassifiziereFehlschlag as Un,suchProtokollSchluessel as Rt,trichterSchluessel as rs,SUCH_DECKEL as is}from"../recall-trichter.js";import{leiteEntscheidungAb as qn,entscheidungsZeile as cs}from"../entscheidung-ableiten.js";import{bewerteTopf as Yn,spreizeImTopf as ls,reichereAn as Zn,inhaltsWoerter as hs,grobStamm as Xn,GEWICHTE as Qn,knapperSiegSatz as eo}from"../rangfolge.js";import{fehlendeLernfelder as to,hatFrage as so,kappeAnfrage as no,ungueltigerAusgang as oo}from"../pflichtfelder.js";import{pruefeWirkung as ao,wirkungsEingabeAus as ro,werteAus as io,lehrwert as co,leiteAb as lo,belegeJeThema as ho}from"../wirkungsspur.js";import{merkeSuchlauf as Lt}from"../suchstatistik.js";import{schreibeTopfNotiz as uo,topfProtokollAktiv as fo}from"../topf-protokoll.js";import{SINN_TOPF as po,EINGANG_SCHWELLE as mo,EINGANG_SORTIER_GEWICHT as go,ZWEIT_MODELL as et,ZWEIT_GEWICHT as wo,ZWEIT_MINDESTDECKUNG as us,NAHDUPLIKAT_SCHWELLE as yo,LESER_TIEFE as ds}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as fs,quelleZeile as _o}from"../herkunft.js";import{doppelHinweis as ps,KEINE_NACHBARN as rt,leseDoppelKandidaten as bo,mitFrist as $o,nahHinweis as ko,pruefeNachbarn as vo}from"../doppel-kandidat.js";import{merkeRecall as So,sitzungsKosten as Co,vergissSitzungsKosten as xo,kostenZeilen as To}from"../sitzungs-kosten.js";const ms=new WeakMap;function Bt(T){let y=ms.get(T);return y||(y={vektor:new Mt,namen:new Mt(6e4,pt),zweit:new Mt(6e4,Ze),eingang:new On,seltenheit:new Pn},ms.set(T,y)),y}const gs=po,No=mo,Ao=go;import{upgradeNudge as Eo}from"../upgrade-nudge.js";import{recallTiefe as ws,verlangteTiefe as Io,TIEFE_VOLL as Mo,TIEFE_VOLL_MEHRTHEMIG as Ro}from"../recall-tiefe.js";import{nutzungInWorten as Lo,nutzungsSchluessel as Bo,verdichte as Oo}from"../werkzeug-nutzung.js";import{inWorten as Do,lieferBild as zo,lieferSchluessel as Po,trefferSchluessel as jo}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Wo,autorHinweisEinmal as Fo,coautorAus as Ho,echterGitLeser as Go,ermittleAutor as Ko,mitCoautor as Vo,nurMensch as ys}from"../autor.js";import{TOOLS as Jo}from"../tools.js";import{vorspannHinweis as Uo}from"../vorspann.js";import{autorAbzeichen as qo,fremdanteil as Yo}from"../autor-abzeichen.js";import{cachlyUrl as Zo}from"../cachly-url.js";import{belegFuer as Xo}from"../schreibbeleg.js";import{rueckfallHinweis as Qo,dazuHinweis as ea}from"../rueckfall.js";import{schwaerzeFelder as ta}from"../geheimnis-filter.js";import{VERDACHT_TAG as Ot,mitVerdachtTag as sa,pruefeFelder as na,verdachtsWarnung as oa}from"../tuersteher.js";import{fuerEigenenSpeicher as Je,hinweise as Ue,istMarkiert as _s,markiert as aa,markierungsWarnung as bs,markierungsWarnungAusRohwert as $s,zaehlHinweise as ks}from"../schreibtor.js";import{istBlossesThema as vs}from"../blosses-thema.js";import{zeitpunkt as Ce}from"../zeitmessung.js";import{wartetAufFrischenBestand as ra}from"../bestand-frische.js";import{leseZurueckgezogen as Ss,ruecknahmeHinweis as ia,ruecknahmeWarnung as ca}from"../zurueckgezogen.js";import{holeRegeln as la,regelBlock as ha,regelHinweisEinmal as ua,passendeRegeln as da,regelStandImSpeicher as fa,markiereVertraut as Cs}from"../firmenregeln.js";import{wissensAbschnitt as pa,wissensSucheMitApi as ma,WISSEN_MIN_WOERTER as ga,WISSEN_PLATZ_MAX as wa}from"../wissenssuche.js";const it=(()=>{try{const T=Ht(import.meta.url);for(const y of["../../../package.json","../../package.json"])try{const E=T(y);if(E.name==="@cachly-dev/mcp-server"&&E.version)return E.version}catch{}}catch{}return"0.10.100"})(),ya=()=>{try{return Ht(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},_a={"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${it}:**`," \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"]},jr=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"]),ba=Zo("/billing","upgrade"),xs=new Map,Ts=new Set,$a=1680*60*60;function ka(T=new Date){return`cachly:quota:recalls:${T.toISOString().slice(0,7)}`}const va=2e4,Dt=new WeakMap;async function Ns(T){if(!Xt(T))return[];const y=Dt.get(T);if(y&&Date.now()-y.am<va)return y.lektionen;const E=await gn(T).catch(()=>[]);return Dt.set(T,{am:Date.now(),lektionen:E}),E}async function As(T,y){const E=wn(await Ns(T),y,3);return E.length===0?[]:["","\u{1F510} **From your rooms** (private and group lessons):",...E.map(j=>{const l=String(j.lektion.what_worked??j.lektion.what_failed??""),n=j.art==="p"?"private":"group"+(j.gruppe?" "+j.gruppe:"");return"- `"+j.thema+"` ("+n+") \u2014 "+l.slice(0,400)+(l.length>400?" \u2026":"")})]}async function Es(T){const y=Xt(T);if(!y)return[];const E=new Set([...y.privat?[y.privat]:[],...y.gruppen.map(l=>l.praefix)]),j=(await Ns(T)).filter(l=>E.has(l.praefix)).length;return j>0?["\u{1F510} "+j+" lesson"+(j===1?"":"s")+" in your own rooms (private and groups).",""]:[]}async function zt(T){try{const y=ka();await T.incr(y)===1&&await T.expire(y,$a)}catch{}}function Is(T){return`cachly:stats:drei-ausgaenge:${T}`}async function Pt(T,y,E){try{await T.hincrby(Is(y),E,1)}catch{}}function Ms(T,y,E,j){zt(T),Lt(T,E,j);const l={ts:new Date().toISOString(),frage:E.slice(0,200),geliefert:[]};(async()=>{const n=Rt(y);await T.lpush(n,JSON.stringify(l)),await T.ltrim(n,0,is-1)})().catch(()=>{}),Pt(T,y,"schweigen")}async function Rs(T){const y={tage:0,rekord:0};try{const E=await T.get("cachly:streak:current"),j=F(E,null),l=new Date().toISOString().slice(0,10);if(j){const n=j.last_date,r=new Date(Date.now()-864e5).toISOString().slice(0,10);n===l?(y.tage=j.days,y.rekord=j.record):n===r?(y.tage=j.days+1,y.rekord=Math.max(y.tage,j.record),await T.set("cachly:streak:current",JSON.stringify({days:y.tage,last_date:l,record:y.rekord}))):(y.tage=1,y.rekord=j.record,await T.set("cachly:streak:current",JSON.stringify({days:1,last_date:l,record:y.rekord})))}else y.tage=1,y.rekord=1,await T.set("cachly:streak:current",JSON.stringify({days:1,last_date:l,record:1}))}catch{}return y}async function Ls(T,y,E){await T.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:y,provider:E}),"EX",86400)}const jt=new Map;async function Bs(T,y){const E=xs.get(T);if(E&&E.expiresAt>Date.now())return E.gate;let j=jt.get(T);return j||(j=Sa(T,y).finally(()=>{jt.delete(T)}),jt.set(T,j)),E&&!ra()?E.gate:j}async function Sa(T,y){try{const E=await y(`/api/v1/instances/${T}/memory`),j=E?.recall_limit??-1,l=E?.total_recall_count??0,n={reached:j>0&&l>=j,limit:j,used:l,goodwillMessage:E?.goodwill_message,notice:E?.notice};return xs.set(T,{gate:n,expiresAt:Date.now()+6e4}),n}catch{return{reached:!1,limit:-1,used:0}}}const Ca={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function Wr(T,y,E,j){const l=T==="session_start"&&y.instance_id?la(String(y.instance_id),(k,c)=>j(k,c)):null,n=xa(T,y,j),r=await Ta(T,y,E,j),f=Ca[T];if(f&&typeof r=="string")try{So(String(y.instance_id??""),String(y[f]??""),r.length)}catch{}if(typeof r!="string")return r;const o=String(y.instance_id??""),t=await n;if(l){const k=await l,c=ha(k),i=t?`${t}
|
|
1
|
+
import{gitLesen as Je,istCommitHash as Gs,pruefeOrdner as pt}from"../git-ohne-shell.js";import{createRequire as Kt}from"node:module";import{istMehrmandant as gt}from"../remote-zugang.js";import{calculateConfidence as Vt,confidenceBadge as Ks,STRUCTURED_TEMPLATES as Vs,CONFIDENCE_WARN_VALUE as Js}from"../confidence.js";import{kurzfassenHinweis as Us}from"../antwort-hinweis.js";import{pruefeMeldung as qs,wendeAn as Ys}from"../pruefung-melden.js";import{ckgSlug as Se,extractProblemConcept as wt,ckgUpsertNode as Ue,ckgUpdateEdge as Ee,ckgUpsertPersonNode as Zs,ckgUpsertFileNode as Jt,ckgRecordCollaboration as Xs,ckgUpsertServiceNode as Qs}from"../ckg.js";import{safeJsonParse as F,scanKeys as De,leseOderNull as je,darfHeraus as yt}from"../utils.js";import{sitzungsKennung as _t,startmarkenSchluessel as Ut,gehoertDieserSitzung as qt}from"../sitzungs-kennung.js";import{ersparteMinuten as Yt,istStarterLektion as en,zaehltAlsErsparnis as Zt}from"../wertbeitrag.js";import{lessonPreviewLines as ct,trimTo as tn}from"../lesson-preview.js";import{normalisiereZeit as bt,zaehleZeitangaben as $t}from"../zeit-normalisieren.js";import{abstentionSatz as sn,alterssatzFuerBelegte as nn,beurteileTreffer as on,istBelegt as Xt}from"../abstention.js";import{meldeEinmal as kt,meldeUndVermerke as tt,fehlerText as lt,OHNE_VEKTOREN as an,OHNE_DIENST as rn,OHNE_FRAGEVEKTOR as cn,SINNPFAD_ABBRUCH as ln,OHNE_SCHREIBVEKTOR as ht}from"../aussetzer.js";import{versuchStart as hn,neueKennung as un,wendeZuteilungAn as dn,schliesseVersuchAb as fn}from"../versuch.js";function vt(k,w,M,j=M){if(k.includes("lesson:best:")){const n=F(w,{});if(n&&typeof n=="object"&&(n.what_worked||n.what_failed||n.commands?.length))return ct(n,{maxChars:M,indent:" "})}const c=tn(w,j);return c?[c]:[]}const Qt=2e3,es=400;function St(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{gemerkterTarif as mn,holeKantenVorrat as pn,SPEICHER_SCAN_SCHRITT as ts}from"../kanten-vorrat.js";import{getRole as gn,eigeneRolle as Ct,ROLE_BADGE as wn,getScopes as xt,lessonVisibleToScope as st,reviewModeEnabled as yn,storeLessonProposal as _n,fragenderAusweis as ut,sichtbarFuer as We,NIEMAND as nt}from"./team.js";import{leseRaumLektion as bn,ladeRaumLektionen as $n,raumTreffer as kn,raeumeVon as ss}from"../raeume.js";import{holeRolle as Tt,istMitglied as qe,rolleFuer as vn,lerneUeberApi as Sn,meldeAbrufe as ns,darfDirektSchreiben as Nt}from"../rolle.js";import{kontoBereichVon as At,kontoSchluessel as ae,alterSchluessel as os}from"../konto-bereich.js";import{keywordSearch as dt,treffeUeberDateipfad as Cn,wortindexEntwerten as as,tokenize as Et,splitMultiQuery as xn,levenshtein as Tn,indexVocab as is,bestandHolen as Nn}from"../search.js";import{startetNochLeer as rs,leeresBrainAntwort as cs,startLageMitCommits as It,sofortAntwortNeuesBrain as An,neuesBrainBriefing as En}from"../leeres-brain.js";import{rerankByQuality as In,qualityMultiplier as Mn,extractLessonQuality as Rn}from"../rerank.js";import{computeEmbedding as Be,hasEmbedProvider as Fe,EMBED_PROVIDER as Le}from"../embeddings.js";import{leserAktiv as Ln,leserPunkte as Bn,mischeMitLeser as On}from"../leser.js";import{repariereFelder as Dn}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Mt,NAME_VEKTOR_PRAEFIX as ft,ZWEIT_VEKTOR_PRAEFIX as Ye,packe as He,textFuerVektor as Ze,textFuerNamensVektor as Rt,Vektorbestand as Lt,VEKTOR_NACHTRAG as zn,NAME_VEKTOR_NACHTRAG as ot,ZWEIT_VEKTOR_NACHTRAG as mt}from"../bedeutung.js";import{schreibeEingaenge as Pn,Eingangsbestand as jn}from"../eingaenge.js";import{ordneNachHausordnung as Wn,rangWerte as Fn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as Hn}from"../seltenheitsbestand.js";import{spurLegen as Gn}from"../spuren.js";import{schlageErsetzungVor as Kn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as ls,stufeSucheNachProjektversion as Vn,versionsNotizen as Jn,versionsBanner as Un}from"../gueltigkeit-version.js";const Xe=zn,qn=365;import{etikettenFuer as Yn,lieferJournalSchluessel as hs,JOURNAL_DECKEL as Zn}from"../etiketten.js";import{klassifiziereFehlschlag as Xn,suchProtokollSchluessel as Bt,trichterSchluessel as us,SUCH_DECKEL as ds}from"../recall-trichter.js";import{leiteEntscheidungAb as Qn,entscheidungsZeile as fs}from"../entscheidung-ableiten.js";import{bewerteTopf as eo,spreizeImTopf as ms,reichereAn as to,inhaltsWoerter as ps,grobStamm as so,GEWICHTE as no,knapperSiegSatz as oo}from"../rangfolge.js";import{fehlendeLernfelder as ao,hatFrage as io,kappeAnfrage as ro,ungueltigerAusgang as co}from"../pflichtfelder.js";import{pruefeWirkung as lo,wirkungsEingabeAus as ho,werteAus as uo,lehrwert as fo,leiteAb as mo,belegeJeThema as po}from"../wirkungsspur.js";import{merkeSuchlauf as Ot}from"../suchstatistik.js";import{schreibeTopfNotiz as go,topfProtokollAktiv as wo}from"../topf-protokoll.js";import{SINN_TOPF as yo,EINGANG_SCHWELLE as _o,EINGANG_SORTIER_GEWICHT as bo,ZWEIT_MODELL as Qe,ZWEIT_GEWICHT as $o,ZWEIT_MINDESTDECKUNG as gs,NAHDUPLIKAT_SCHWELLE as ko,LESER_TIEFE as ws}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as ys,quelleZeile as vo}from"../herkunft.js";import{doppelHinweis as _s,KEINE_NACHBARN as at,leseDoppelKandidaten as So,mitFrist as Co,nahHinweis as xo,pruefeNachbarn as To}from"../doppel-kandidat.js";import{merkeRecall as No,sitzungsKosten as Ao,vergissSitzungsKosten as Eo,kostenZeilen as Io}from"../sitzungs-kosten.js";const bs=new WeakMap;function Dt(k){let w=bs.get(k);return w||(w={vektor:new Lt,namen:new Lt(6e4,ft),zweit:new Lt(6e4,Ye),eingang:new jn,seltenheit:new Hn},bs.set(k,w)),w}const $s=yo,Mo=_o,Ro=bo;import{upgradeNudge as Lo}from"../upgrade-nudge.js";import{recallTiefe as ks,verlangteTiefe as Bo,TIEFE_VOLL as Oo,TIEFE_VOLL_MEHRTHEMIG as Do}from"../recall-tiefe.js";import{nutzungInWorten as zo,nutzungsSchluessel as Po,verdichte as jo}from"../werkzeug-nutzung.js";import{inWorten as Wo,lieferBild as Fo,lieferSchluessel as Ho,trefferSchluessel as Go}from"../geliefert.js";import{COAUTHOR_PREF_KEY as Ko,autorHinweisEinmal as Vo,coautorAus as Jo,echterGitLeser as Uo,ermittleAutor as qo,mitCoautor as Yo,nurMensch as vs}from"../autor.js";import{TOOLS as Zo}from"../tools.js";import{vorspannHinweis as Xo}from"../vorspann.js";import{autorAbzeichen as Qo,fremdanteil as ea}from"../autor-abzeichen.js";import{cachlyUrl as ta}from"../cachly-url.js";import{belegFuer as sa}from"../schreibbeleg.js";import{rueckfallHinweis as na,dazuHinweis as oa}from"../rueckfall.js";import{schwaerzeFelder as aa}from"../geheimnis-filter.js";import{VERDACHT_TAG as zt,mitVerdachtTag as ia,pruefeFelder as ra,verdachtsWarnung as ca}from"../tuersteher.js";import{fuerEigenenSpeicher as Ge,hinweise as Ke,istMarkiert as Ss,markiert as la,markierungsWarnung as Cs,markierungsWarnungAusRohwert as xs,zaehlHinweise as Ts}from"../schreibtor.js";import{istBlossesThema as Ns}from"../blosses-thema.js";import{zeitpunkt as xe}from"../zeitmessung.js";import{wartetAufFrischenBestand as ha}from"../bestand-frische.js";import{leseZurueckgezogen as As,ruecknahmeHinweis as ua,ruecknahmeWarnung as da}from"../zurueckgezogen.js";import{holeRegeln as fa,regelBlock as ma,regelHinweisEinmal as pa,passendeRegeln as ga,regelStandImSpeicher as wa,markiereVertraut as Es}from"../firmenregeln.js";import{wissensAbschnitt as ya,wissensSucheMitApi as _a,WISSEN_MIN_WOERTER as ba,WISSEN_PLATZ_MAX as $a}from"../wissenssuche.js";const it=(()=>{try{const k=Kt(import.meta.url);for(const w of["../../../package.json","../../package.json"])try{const M=k(w);if(M.name==="@cachly-dev/mcp-server"&&M.version)return M.version}catch{}}catch{}return"0.10.100"})(),ka=()=>{try{return Kt(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},va={"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${it}:**`," \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"]},Ji=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"]),Sa=ta("/billing","upgrade"),Is=new Map,Ms=new Set,Ca=1680*60*60;function xa(k=new Date){return`cachly:quota:recalls:${k.toISOString().slice(0,7)}`}const Ta=2e4,Pt=new WeakMap;async function Rs(k){if(!ss(k))return[];const w=Pt.get(k);if(w&&Date.now()-w.am<Ta)return w.lektionen;const M=await $n(k).catch(()=>[]);return Pt.set(k,{am:Date.now(),lektionen:M}),M}async function Ls(k,w){const M=kn(await Rs(k),w,3);return M.length===0?[]:["","\u{1F510} **From your rooms** (private and group lessons):",...M.map(j=>{const c=String(j.lektion.what_worked??j.lektion.what_failed??""),n=j.art==="p"?"private":"group"+(j.gruppe?" "+j.gruppe:"");return"- `"+j.thema+"` ("+n+") \u2014 "+c.slice(0,400)+(c.length>400?" \u2026":"")})]}async function Bs(k){const w=ss(k);if(!w)return[];const M=new Set([...w.privat?[w.privat]:[],...w.gruppen.map(c=>c.praefix)]),j=(await Rs(k)).filter(c=>M.has(c.praefix)).length;return j>0?["\u{1F510} "+j+" lesson"+(j===1?"":"s")+" in your own rooms (private and groups).",""]:[]}async function jt(k){try{const w=xa();await k.incr(w)===1&&await k.expire(w,Ca)}catch{}}function Os(k){return`cachly:stats:drei-ausgaenge:${k}`}async function Wt(k,w,M){try{await k.hincrby(Os(w),M,1)}catch{}}function Ds(k,w,M,j){jt(k),Ot(k,M,j);const c={ts:new Date().toISOString(),frage:M.slice(0,200),geliefert:[]};(async()=>{const n=ae(k,Bt(w));await k.lpush(n,JSON.stringify(c)),await k.ltrim(n,0,ds-1)})().catch(()=>{}),Wt(k,w,"schweigen")}async function zs(k){const w={tage:0,rekord:0};try{const M=await k.get("cachly:streak:current"),j=F(M,null),c=new Date().toISOString().slice(0,10);if(j){const n=j.last_date,a=new Date(Date.now()-864e5).toISOString().slice(0,10);n===c?(w.tage=j.days,w.rekord=j.record):n===a?(w.tage=j.days+1,w.rekord=Math.max(w.tage,j.record),await k.set("cachly:streak:current",JSON.stringify({days:w.tage,last_date:c,record:w.rekord}))):(w.tage=1,w.rekord=j.record,await k.set("cachly:streak:current",JSON.stringify({days:1,last_date:c,record:w.rekord})))}else w.tage=1,w.rekord=1,await k.set("cachly:streak:current",JSON.stringify({days:1,last_date:c,record:1}))}catch{}return w}async function Ps(k,w,M){const j=new Date().toISOString(),c=_t();await k.set(ae(k,Ut(c)),JSON.stringify({started:j}),"EX",86400),await k.set(ae(k,"cachly:session:current"),JSON.stringify({started:j,focus:w,provider:M,sid:c}),"EX",86400)}async function Na(k){const w=_t(),M=ae(k,Ut(w)),j=ae(k,"cachly:session:current"),[c,n]=await Promise.all([k.get(M),k.get(j)]),a=c?F(c,null):null,u=n?F(n,null):null,o=!!u&&qt(u.sid,w),t=[M,...o?[j]:[]],S=a?.started||(o?u?.started:void 0)||void 0;return{...S?{started:S}:{},loeschen:t}}const Ft=new Map;async function js(k,w){const M=Is.get(k);if(M&&M.expiresAt>Date.now())return M.gate;let j=Ft.get(k);return j||(j=Aa(k,w).finally(()=>{Ft.delete(k)}),Ft.set(k,j)),M&&!ha()?M.gate:j}async function Aa(k,w){try{const M=await w(`/api/v1/instances/${k}/memory`),j=M?.recall_limit??-1,c=M?.total_recall_count??0,n={reached:j>0&&c>=j,limit:j,used:c,goodwillMessage:M?.goodwill_message,notice:M?.notice};return Is.set(k,{gate:n,expiresAt:Date.now()+6e4}),n}catch{return{reached:!1,limit:-1,used:0}}}const Ea={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function Ui(k,w,M,j){const c=k==="session_start"&&w.instance_id?fa(String(w.instance_id),(S,l)=>j(S,l)):null,n=Ia(k,w,j),a=await Ma(k,w,M,j),u=Ea[k];if(u&&typeof a=="string")try{No(String(w.instance_id??""),String(w[u]??""),a.length)}catch{}if(typeof a!="string")return a;const o=String(w.instance_id??""),t=await n;if(c){const S=await c,l=ma(S),i=t?`${t}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${a}`:a;return l?(pa(o,S,{cwd:String(w.workspace_path||process.cwd()),prozessStart:Date.now()}),`${Es(l)}
|
|
4
4
|
|
|
5
|
-
${i}`):i}if(
|
|
5
|
+
${i}`):i}if(k==="smart_recall"&&o){const S=ga(String(w.query??""),wa(o)),l=t?`${a}
|
|
6
6
|
|
|
7
|
-
${t}`:
|
|
7
|
+
${t}`:a;return S?`${l}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
`);const
|
|
11
|
-
`);const Be=[];if(We)try{const _=JSON.parse(We);if(Q=os(a,_.gilt_fuer),$e=_.recall_count??0,re=_.last_recalled_at,ve=_.audit_trail??[],ve.push({ts:te,action:"updated",prev_outcome:_.outcome,grund:Me}),ve.length>20&&(ve=ve.slice(-20)),me=!0,_.outcome==="success"&&t==="failure"?Be.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."):_.outcome==="failure"&&t==="success"&&Be.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),Be.length>0){ve[ve.length-1].action="contradiction-resolved";try{const H=ke(o),ce=ke(`resolution:${o}`);await Te(h,H,"contradicts",ce,!1)}catch{}try{const H=`cachly:contradictions:${o}`,ce=_.outcome==="success"&&t==="failure"?"kept-success":"overwrote-failure";await h.rpush(H,JSON.stringify({ts:te,prev_outcome:_.outcome,new_outcome:t,direction:ce})),await h.ltrim(H,-50,-1),await h.expire(H,180*86400)}catch{}Be.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${o}")\` to resolve via expert agent voting.`)}}catch{}else ve=[{ts:te,action:"created"}];const Ke=[];if(t==="failure"){const _=[],H=h.scanStream({match:"cachly:lesson:best:*",count:Zt});await new Promise((J,P)=>{H.on("data",Z=>_.push(...Z)),H.on("end",J),H.on("error",P)});const ce=o.split(/[:\-_]/).filter(J=>J.length>2);for(const J of _.slice(0,50)){const P=await h.get(J);if(P)try{const Z=JSON.parse(P);if(Z.outcome!=="success")continue;const be=(Z.topic??"").split(/[:\-_]/).filter(W=>W.length>2);if(ce.filter(W=>be.includes(W)).length>=1&&Z.topic!==o){Ke.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${Z.topic}\` (success, ${Z.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${Z.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${Z.topic}", ..., severity="critical")\``);break}}catch{}}}for(const _ of C){const H=`cachly:dep:${_}`,ce=await h.get(H),J=F(ce,[]);J.includes(o)||J.push(o),await h.set(H,JSON.stringify(J),"EX",90*86400)}const Ae={topic:o,outcome:t,what_worked:ee,what_failed:ne,context:ue,severity:A,file_paths:e,commands:m,tags:I,depends_on:C,...v?{author:v}:{},source:fs(),...d?{service:d}:{},...S?{group:String(S).toLowerCase().trim()}:{},visibility:x,recall_count:$e,...re?{last_recalled_at:re}:{},...O&&!Number.isNaN(Date.parse(String(O)))?{gilt_ab:new Date(String(O)).toISOString()}:{},...Q.angaben.length?{gilt_fuer:Q.angaben}:{},ts:te,verified_at:t==="success"||t==="partial"?te:void 0,confidence:1,audit_trail:ve,version:3},xe=String(z??"").trim();let Oe="",Y=null;xe===o&&xe?Oe="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":xe&&(Y=await h.get(`cachly:lesson:best:${xe}`),Y?F(Y,{}).ersetzt===o?(Y=null,Oe=`\u26A0\uFE0F \`${xe}\` already replaces \`${o}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${xe}\` first, then set it here.`):Ae.ersetzt=xe:Oe=`\u26A0\uFE0F The lesson to replace, \`${xe}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Re="";if(!xe)try{const _=Z=>{const be=F(Z.content,{});return{topic:be.topic??Z.key.slice(19),what_worked:be.what_worked}},[H,ce]=await Promise.all([ft(h,["cachly:lesson:best:*"],`${o} ${ee}`.slice(0,300),5),$n(h,["cachly:lesson:best:*"],e??[])]),J=new Set,P=[...H,...ce].filter(Z=>Z.key.startsWith("cachly:lesson:best:")).filter(Z=>!J.has(Z.key)&&J.add(Z.key)).map(_);Re=Wn(o,ee,P)??""}catch{}if(t==="failure")try{const H=(await h.lrange(Rt(f),0,199)).map(P=>F(P,{ts:"",frage:"",geliefert:[]})).filter(P=>P.ts!==""),ce=(await ft(h,["cachly:lesson:best:*"],`${o} ${ne||ee}`.slice(0,300),5)).filter(P=>P.key.startsWith("cachly:lesson:best:")).map(P=>{const Z=F(P.content,{});return{topic:Z.topic??P.key.slice(19),what_worked:Z.what_worked}}),J=Un(o,String(ne||""),H,ce);await h.hincrby(rs(f),J,1)}catch{}const De=qn([ee,ne,i].filter(Boolean).join(" ").slice(0,2e3));De&&(Ae.entscheidung=De);const ze=Xo(o,te,ee);Ae.beleg=ze;const Fe=JSON.stringify(Ae);h.set(`cachly:stats:born_at:${f}`,te,"EX",365*86400,"NX").catch(()=>{});const g=`cachly:lessons:${o}`;await h.rpush(g,Fe),await h.ltrim(g,-100,-1),await h.expire(g,Kn*86400);let w=!1;if(t==="success"||t==="partial"?(await h.set(`cachly:lesson:best:${o}`,Fe),w=!0):We||(await h.set(`cachly:lesson:best:${o}`,Fe),w=!0),Y&&w)try{const _=JSON.parse(Y);_.ersetzt_durch=o,_.gilt_bis=te,_.ersetzt_am=te,Me&&(_.ersetzt_grund=Me.slice(0,200)),await h.set(`cachly:lesson:best:${xe}`,JSON.stringify(_))}catch{}w&&es();let L=()=>{};const se=new Promise(_=>{L=_});if(w&&Ge()||L(rt),w&&Ge()){await h.sadd(Qe,o).catch(()=>{}),await h.sadd(at,o).catch(()=>{}),(Ne==="cachly"||Ne==="ollama")&&await h.sadd(mt,o).catch(()=>{});const _=Ft(h);_.add(o),(async()=>{const H=F(Fe,{});let ce=Promise.resolve();try{const P=await Ie(Xe(H),{geduld:"lang"});P?.length?(await h.set(`${Et}${o}`,Ve(P)),await h.srem(Qe,o).catch(()=>{}),L(await vo(h,{...H,topic:o},P,Bt(h).vektor))):L(rt),(Ne==="cachly"||Ne==="ollama")&&(ce=(async()=>{try{const Z=await Ie(Xe(H),{geduld:"lang",modell:et});Z?.length&&(await h.set(`${Ze}${o}`,Ve(Z)),await h.srem(mt,o).catch(()=>{}))}catch(Z){await st(h,ut,`second vector not written (${Ne}, ${et}): ${ht(Z)} - the lesson is saved, the backfill adds it later.`)}})())}catch(P){L(rt),await h.sadd(Qe,o).catch(()=>{}),await st(h,ut,`lesson vector not written (${Ne}): ${ht(P)} - the lesson is saved; search by meaning skips it until the backfill adds the vector.`)}const J=It(o);try{if(!J)await h.srem(at,o).catch(()=>{});else{const P=await Ie(J,{geduld:"lang"});P?.length&&(await h.set(`${pt}${o}`,Ve(P)),await h.srem(at,o).catch(()=>{}))}}catch(P){await st(h,ut,`topic-name vector not written (${Ne}): ${ht(P)} - the lesson itself is saved.`)}try{await Bn(h,o,H,P=>Ie(P,{geduld:"lang"}))}catch(P){await st(h,ut,`entry points not written (${Ne}): ${ht(P)} - the lesson itself is saved.`)}await ce,await Wt(h,o,3),L(rt)})().finally(()=>_.delete(o))}try{const _="cachly:session:decision-log",H=JSON.stringify({ts:te,topic:o,outcome:t,what_worked:ee.slice(0,120)});await h.rpush(_,H),await h.ltrim(_,-50,-1)}catch{}let B=null;try{const _=ke(o),H=o.split(":")[0]??"unknown";await Ye(h,_,H,H);for(const J of I){const P=ke(`tag:${J}`);await Ye(h,P,"tag","tag"),await Te(h,_,"co-occurs",P,t==="success",t==="partial")}for(const J of C){const P=ke(J);await Te(h,_,"requires",P,!0)}if((H==="fix"||H==="debug")&&(t==="success"||t==="partial")){const J=ne||ue||"",P=J?yt(J):null;if(P){const Z=ke(`problem:${P}`);await Ye(h,Z,"problem","problem"),await Te(h,_,"fixes",Z,t==="success",t==="partial")}}if(t==="failure"&&(ne||ee)){const P=yt(ne||ee);if(P){const Z=ke(`cause:${P}`);await Ye(h,Z,"cause","cause"),await Te(h,_,"causes",Z,!1)}}if(t==="failure"){const J=await h.smembers(`cachly:ckg:idx:from:${_}`);for(const P of J){const Z=await h.get(P);if(!Z)continue;const be=F(Z,null);if(be&&be.edgeType==="fixes"&&be.confidence>.7&&be.trials>=3){B=`\u26A0\uFE0F **belief_conflict** on \`${o}\`: previously confirmed fix (confidence ${be.confidence.toFixed(2)}, n=${be.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${o}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${_}")\` to review.`;const Se=`cachly:ckg:conflict:${_}`;await h.set(Se,JSON.stringify({topic:o,concept_id:_,detected_at:new Date().toISOString(),fix_confidence:be.confidence,fix_trials:be.trials,failure_outcome:t,reported_by:v||"unknown",what_failed:ne||"",resolved:!1}),"EX",3600*24*90)}}}if(t==="success"&&(H==="fix"||H==="debug")){const J=await h.smembers(`cachly:ckg:idx:from:${_}`);for(const P of J.slice(0,10)){const Z=await h.get(P);if(!Z)continue;const be=F(Z,null);if(!be||be.edgeType!=="fixes")continue;const Se=await h.smembers(`cachly:ckg:idx:from:${be.to}`);for(const W of Se.slice(0,5)){const fe=await h.get(W);if(!fe)continue;const pe=F(fe,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 h.set(W,JSON.stringify(pe)))}}}if(Math.random()<.01){const J=Date.now()-7776e6,P=await h.smembers(`cachly:ckg:idx:from:${_}`);for(const Z of P){const be=await h.get(Z);if(!be)continue;const Se=F(be,null);Se&&Se.trials<3&&Se.last_updated&&new Date(Se.last_updated).getTime()<J&&(Se.confidence=Se.confidence*.9,Se.last_updated=new Date().toISOString(),await h.set(Z,JSON.stringify(Se)))}}}catch{}if(v){h.set(`cachly:agents:active:${v}`,JSON.stringify({author:v,last_topic:o,last_outcome:t,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const _=o.split(":")[0]??"unknown",H=await Vs(h,ys(v),_),ce=ke(o);await Te(h,H,"authored",ce,t==="success",t==="partial");for(const J of e.slice(0,8)){const P=await Kt(h,J);await Te(h,H,"touched",P,!0),await Js(h,P,H)}}catch{}}if(d&&typeof d=="string"&&d.trim())try{const _=o.split(":")[0]??"unknown",H=b==="system"?"system":"service",ce=await Us(h,d.trim(),_,H),J=ke(o);if(await Te(h,J,"affects",ce,t==="success",t==="partial"),v){const P=`person:${ke(ys(v))}`;await Te(h,P,"operates",ce,!0)}for(const P of e.slice(0,8)){const Z=`file:${ke(P)}`;await Te(h,Z,"runs_in",ce,!0)}}catch{}if(V&&v&&(t==="success"||t==="partial")){const _={topic:o,outcome:t,what_worked:ee,what_failed:ne??"",severity:A,author:v,file_paths:e,commands:m,tags:[...new Set([...I,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},H=`cachly:lessons:${o}`;h.rpush(H,JSON.stringify(_)).catch(()=>{})}const q=t==="success"?"\u2705":t==="partial"?"\u26A0\uFE0F":"\u274C",le=A==="critical"?"\u{1F534}":A==="major"?"\u{1F7E1}":"\u{1F7E2}",we=me?"updated":"stored",ye=await $o(se)??rt,de=ye.doppel,oe=await Ss(h,o);return[`${q} **Lesson ${we}:** \`${o}\` (${t}) ${le} ${A} \xB7 receipt: \`${ze}\``,l.funde.length?`\u{1F512} **${l.funde.length} secret(s) redacted** before saving (${l.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",oa(n),B??"",oe?ca(oe):"","",`**What worked:** ${ee}`,ne?`**What failed:** ${ne}`:"",ue?`**Context:** ${ue}`:"",e.length>0?`**Files:** ${e.map(_=>`\`${_}\``).join(", ")}`:"",m.length>0?`**Commands:** ${m.map(_=>`\`${_}\``).join(", ")}`:"",I.length>0?`**Tags:** ${I.map(_=>`#${_}`).join(" ")}`:"","",me?`\u267B\uFE0F Updated (recall count: ${$e} \xB7 audit entries: ${ve.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${o}")\``,x==="private"?"\u{1F512} Private \u2014 kept out of `team_recall` and out of teammates' recall":S?`\u{1F465} Group \`${S}\` only \u2014 teammates outside the group don't see it`:v&&(t==="success"||t==="partial")?`\u{1F465} Auto-shared with team (by _${v}_${p.quelle!=="uebergeben"?` \xB7 from ${p.quelle}`:""}) \u2014 visible in \`team_recall\``:"",R??"",C.length>0?`\u{1F517} Depends on: ${C.map(_=>`\`${_}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Re,ps(de,Re),xe?"":ko(ye.nahe,Re+ps(de,Re)),Q.angaben.length?`\u{1F4E6} Applies to ${Q.angaben.map(_=>`\`${_}\``).join(", ")}${Q.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...Q.fehler.map(_=>`\u26A0\uFE0F gilt_fuer not stored, ${_}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),Y&&w?Me?`\u21B7 Replaces \`${xe}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${xe}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:Oe,...he,...Be,...Ke,_e>0?`\u{1F5D3}\uFE0F ${_e} relative time reference${_e===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(G.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",Uo(ee)??"",Qo({outcome:t,topic:o,what_worked:ee,what_failed:ne,file_paths:e}),ea({outcome:t,topic:o,what_worked:ee,what_failed:ne,file_paths:e})].filter(_=>_!=="").join(`
|
|
12
|
-
`)}case"lesson_verified":{const{instance_id:
|
|
13
|
-
`);const
|
|
14
|
-
`):
|
|
15
|
-
`):[`\u26A0\uFE0F \`${
|
|
16
|
-
`)}case"recall_feedback":{const{instance_id:
|
|
17
|
-
`);const
|
|
18
|
-
`)}case"recall_best_solution":{const
|
|
19
|
-
`):"",
|
|
20
|
-
`)}const
|
|
9
|
+
${Es(S)}`:l}return a}async function Ia(k,w,M){try{const j=String(w.instance_id??""),c=k==="session_start";if(!j||!c&&k!=="smart_recall")return"";const n=String(c?w.focus??"":w.query??"").trim();if((n.match(/[\p{L}\p{N}]+/gu)??[]).length<ba)return"";const a=_a(j,(o,t)=>M(o,t),c?"focus":"recall");if(!a)return"";const u=await a(n,$a);return ya(c?"Company knowledge for this focus":"Company knowledge",u)}catch{return""}}async function Ma(k,w,M,j){switch(k){case"learn_from_attempts":{{const N=ao(w);if(N.length)return`\u26A0\uFE0F learn_from_attempts needs ${N.join(" and ")}. Nothing was stored.`;const V=co(w);if(V)return V}const c=aa(w),n=ra(c.felder),a=n.length?{...c.felder,tags:ia(c.felder.tags)}:c.felder,{instance_id:u,topic:o,outcome:t,what_worked:S,what_failed:l="",context:i="",severity:A="major",file_paths:e=[],commands:g=[],tags:I=[],depends_on:x=[],author:d="",visibility:m,service:s="",service_kind:_="service",group:b,grund:R="",ersetzt:z="",gilt_ab:P="",gilt_fuer:r}=a,{what_worked:re,what_failed:ee="",context:we=""}=Dn({what_worked:S,what_failed:l,context:i}),h=await M(u),W=new Date,te=W.toISOString();let X=ls(r,void 0);const Y=P&&!Number.isNaN(Date.parse(String(P)))?new Date(String(P)):W,Q=bt(re,Y),ie=bt(ee,Y),pe=bt(we,Y),$e=$t(re,Y)+$t(ee,Y)+$t(we,Y),f=qo({uebergeben:d,umgebung:gt()?void 0:process.env.CACHLY_AUTHOR,git:gt()?(()=>""):Uo(process.env.CACHLY_WORKSPACE??process.cwd())});let T="";try{T=Jo(await h.get(`cachly:prefs:${Ko}:${u}`))}catch{}const v=Yo(f.autor,T),L=Vo(f);let C=m??"team",$=b??"";if(m===void 0||b===void 0){const N=je(await h.get(`cachly:lesson:best:${o}`));N&&(m===void 0&&(N.visibility==="public"||N.visibility==="private")&&(C=N.visibility),b===void 0&&N.group&&($=N.group))}const K=C!=="private"&&!$;if(qe(h)||!K&&(await Tt(u))?.rooms===!0){if(!K&&(await Tt(u))?.rooms!==!0)return[`\u26A0\uFE0F Nicht gespeichert: Diese Lektion ist ${C==="private"?"privat":`fuer die Gruppe \`${$}\``} gedacht.`,"Die API dieses Brains kennt noch keine privaten Raeume und Gruppen-Raeume; die Lektion wuerde fuer alle sichtbar.","Ohne `visibility`/`group` erneut speichern, wenn sie das ganze Team sehen soll."].join(`
|
|
10
|
+
`);const N=await Sn(j,u,{topic:o,outcome:t,what_worked:Q,what_failed:ie,context:pe,severity:A,file_paths:Array.isArray(e)?e:[],commands:Array.isArray(g)?g:[],tags:Array.isArray(I)?I:[],...v?{author:v}:{},...K?{}:{visibility:C,...$?{group:$}:{}}},vn(h));return Pt.delete(h),N}if(C!=="private"&&await yn(h,u))return _n(h,o,{topic:o,outcome:t,what_worked:Q,what_failed:ie,context:pe,severity:A,file_paths:e,commands:g,tags:I,depends_on:x,...X.angaben.length?{gilt_fuer:X.angaben}:{},...v?{author:v}:{},source:ys(),...s?{service:s}:{},...$?{group:String($).toLowerCase().trim()}:{},visibility:C,recall_count:0,ts:te,confidence:1,version:3});const H=o.split(":")[0],he=Vs[H],ke=[];if(he)for(const N of he.required)N==="commands"&&g.length===0&&ke.push(`\u{1F4CB} ${he.hint}`);let ue=!1,_e=0,Te,Ce=[];const de=await h.get(`cachly:lesson:best:${o}`),Ie=String(R||a.reason||"").trim();if(de&&!Ie)return[`\u270B **Update rejected:** \`${o}\` already exists \u2014 an update needs the field \`grund\` (the reason; \`reason\` works too).`,"","One line is enough: WHY was the previous version wrong or incomplete?",'Example: grund="The deploy target moved from port 3000 to 8080"',"","The diff says WHAT changes. The grund line says why the old version was wrong \u2014","and that is the line someone reads two months from now (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
11
|
+
`);const Me=[];if(de)try{const N=JSON.parse(de);if(X=ls(r,N.gilt_fuer),_e=N.recall_count??0,Te=N.last_recalled_at,Ce=N.audit_trail??[],Ce.push({ts:te,action:"updated",prev_outcome:N.outcome,grund:Ie}),Ce.length>20&&(Ce=Ce.slice(-20)),ue=!0,N.outcome==="success"&&t==="failure"?Me.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."):N.outcome==="failure"&&t==="success"&&Me.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),Me.length>0){Ce[Ce.length-1].action="contradiction-resolved";try{const V=Se(o),le=Se(`resolution:${o}`);await Ee(h,V,"contradicts",le,!1)}catch{}try{const V=`cachly:contradictions:${o}`,le=N.outcome==="success"&&t==="failure"?"kept-success":"overwrote-failure";await h.rpush(V,JSON.stringify({ts:te,prev_outcome:N.outcome,new_outcome:t,direction:le})),await h.ltrim(V,-50,-1),await h.expire(V,180*86400)}catch{}Me.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${o}")\` to resolve via expert agent voting.`)}}catch{}else Ce=[{ts:te,action:"created"}];const rt=[];if(t==="failure"){const N=[],V=h.scanStream({match:"cachly:lesson:best:*",count:ts});await new Promise((se,G)=>{V.on("data",U=>N.push(...U)),V.on("end",se),V.on("error",G)});const le=o.split(/[:\-_]/).filter(se=>se.length>2);for(const se of N.slice(0,50)){const G=await h.get(se);if(G)try{const U=JSON.parse(G);if(U.outcome!=="success")continue;const D=(U.topic??"").split(/[:\-_]/).filter(be=>be.length>2);if(le.filter(be=>D.includes(be)).length>=1&&U.topic!==o){rt.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${U.topic}\` (success, ${U.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${U.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${U.topic}", ..., severity="critical")\``);break}}catch{}}}for(const N of x){const V=`cachly:dep:${N}`,le=await h.get(V),se=F(le,[]);se.includes(o)||se.push(o),await h.set(V,JSON.stringify(se),"EX",90*86400)}const ze={topic:o,outcome:t,what_worked:Q,what_failed:ie,context:pe,severity:A,file_paths:e,commands:g,tags:I,depends_on:x,...v?{author:v}:{},source:ys(),...s?{service:s}:{},...$?{group:String($).toLowerCase().trim()}:{},visibility:C,recall_count:_e,...Te?{last_recalled_at:Te}:{},...P&&!Number.isNaN(Date.parse(String(P)))?{gilt_ab:new Date(String(P)).toISOString()}:{},...X.angaben.length?{gilt_fuer:X.angaben}:{},ts:te,verified_at:t==="success"||t==="partial"?te:void 0,confidence:1,audit_trail:Ce,version:3},J=String(z??"").trim();let Pe="",Re=null;J===o&&J?Pe="\u26A0\uFE0F `ersetzt` points to the same topic \u2014 for a correction within one topic, an update with `grund` is enough. The link was ignored.":J&&(Re=await h.get(`cachly:lesson:best:${J}`),Re?F(Re,{}).ersetzt===o?(Re=null,Pe=`\u26A0\uFE0F \`${J}\` already replaces \`${o}\` \u2014 two lessons cannot replace each other. The link was NOT stored. If this version is the newer one: remove the link in \`${J}\` first, then set it here.`):ze.ersetzt=J:Pe=`\u26A0\uFE0F The lesson to replace, \`${J}\`, does not exist \u2014 the link was NOT stored. \`smart_recall\` shows topic names.`);let Oe="";if(!J)try{const N=U=>{const D=F(U.content,{});return{topic:D.topic??U.key.slice(19),what_worked:D.what_worked}},[V,le]=await Promise.all([dt(h,["cachly:lesson:best:*"],`${o} ${Q}`.slice(0,300),5),Cn(h,["cachly:lesson:best:*"],e??[])]),se=new Set,G=[...V,...le].filter(U=>U.key.startsWith("cachly:lesson:best:")).filter(U=>!se.has(U.key)&&se.add(U.key)).map(N);Oe=Kn(o,Q,G)??""}catch{}if(t==="failure")try{const V=(await h.lrange(ae(h,Bt(u)),0,199)).map(G=>F(G,{ts:"",frage:"",geliefert:[]})).filter(G=>G.ts!==""),le=(await dt(h,["cachly:lesson:best:*"],`${o} ${ie||Q}`.slice(0,300),5)).filter(G=>G.key.startsWith("cachly:lesson:best:")).map(G=>{const U=F(G.content,{});return{topic:U.topic??G.key.slice(19),what_worked:U.what_worked}}),se=Xn(o,String(ie||""),V,le);await h.hincrby(us(u),se,1)}catch{}const Ve=Qn([Q,ie,i].filter(Boolean).join(" ").slice(0,2e3));Ve&&(ze.entscheidung=Ve);const p=sa(o,te,Q);ze.beleg=p;const y=JSON.stringify(ze);h.set(`cachly:stats:born_at:${u}`,te,"EX",365*86400,"NX").catch(()=>{});const B=`cachly:lessons:${o}`;await h.rpush(B,y),await h.ltrim(B,-100,-1),await h.expire(B,qn*86400);let Z=!1;if(t==="success"||t==="partial"?(await h.set(`cachly:lesson:best:${o}`,y),Z=!0):de||(await h.set(`cachly:lesson:best:${o}`,y),Z=!0),Re&&Z)try{const N=JSON.parse(Re);N.ersetzt_durch=o,N.gilt_bis=te,N.ersetzt_am=te,Ie&&(N.ersetzt_grund=Ie.slice(0,200)),await h.set(`cachly:lesson:best:${J}`,JSON.stringify(N))}catch{}Z&&as();let O=()=>{};const q=new Promise(N=>{O=N});if(Z&&Fe()||O(at),Z&&Fe()){await h.sadd(Xe,o).catch(()=>{}),await h.sadd(ot,o).catch(()=>{}),(Le==="cachly"||Le==="ollama")&&await h.sadd(mt,o).catch(()=>{});const N=Gt(h);N.add(o),(async()=>{const V=F(y,{});let le=Promise.resolve();try{const G=await Be(Ze(V),{geduld:"lang"});G?.length?(await h.set(`${Mt}${o}`,He(G)),await h.srem(Xe,o).catch(()=>{}),O(await To(h,{...V,topic:o},G,Dt(h).vektor))):O(at),(Le==="cachly"||Le==="ollama")&&(le=(async()=>{try{const U=await Be(Ze(V),{geduld:"lang",modell:Qe});U?.length&&(await h.set(`${Ye}${o}`,He(U)),await h.srem(mt,o).catch(()=>{}))}catch(U){await tt(h,ht,`second vector not written (${Le}, ${Qe}): ${lt(U)} - the lesson is saved, the backfill adds it later.`)}})())}catch(G){O(at),await h.sadd(Xe,o).catch(()=>{}),await tt(h,ht,`lesson vector not written (${Le}): ${lt(G)} - the lesson is saved; search by meaning skips it until the backfill adds the vector.`)}const se=Rt(o);try{if(!se)await h.srem(ot,o).catch(()=>{});else{const G=await Be(se,{geduld:"lang"});G?.length&&(await h.set(`${ft}${o}`,He(G)),await h.srem(ot,o).catch(()=>{}))}}catch(G){await tt(h,ht,`topic-name vector not written (${Le}): ${lt(G)} - the lesson itself is saved.`)}try{await Pn(h,o,V,G=>Be(G,{geduld:"lang"}))}catch(G){await tt(h,ht,`entry points not written (${Le}): ${lt(G)} - the lesson itself is saved.`)}await le,await Ht(h,o,3),O(at)})().finally(()=>N.delete(o))}try{const N=ae(h,"cachly:session:decision-log"),V=JSON.stringify({ts:te,topic:o,outcome:t,what_worked:Q.slice(0,120),sid:_t()});await h.rpush(N,V),await h.ltrim(N,-50,-1)}catch{}let ce=null;try{const N=Se(o),V=o.split(":")[0]??"unknown";await Ue(h,N,V,V);for(const se of I){const G=Se(`tag:${se}`);await Ue(h,G,"tag","tag"),await Ee(h,N,"co-occurs",G,t==="success",t==="partial")}for(const se of x){const G=Se(se);await Ee(h,N,"requires",G,!0)}if((V==="fix"||V==="debug")&&(t==="success"||t==="partial")){const se=ie||pe||"",G=se?wt(se):null;if(G){const U=Se(`problem:${G}`);await Ue(h,U,"problem","problem"),await Ee(h,N,"fixes",U,t==="success",t==="partial")}}if(t==="failure"&&(ie||Q)){const G=wt(ie||Q);if(G){const U=Se(`cause:${G}`);await Ue(h,U,"cause","cause"),await Ee(h,N,"causes",U,!1)}}if(t==="failure"){const se=await h.smembers(`cachly:ckg:idx:from:${N}`);for(const G of se){const U=await h.get(G);if(!U)continue;const D=F(U,null);if(D&&D.edgeType==="fixes"&&D.confidence>.7&&D.trials>=3){ce=`\u26A0\uFE0F **belief_conflict** on \`${o}\`: previously confirmed fix (confidence ${D.confidence.toFixed(2)}, n=${D.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${o}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${N}")\` to review.`;const ne=`cachly:ckg:conflict:${N}`;await h.set(ne,JSON.stringify({topic:o,concept_id:N,detected_at:new Date().toISOString(),fix_confidence:D.confidence,fix_trials:D.trials,failure_outcome:t,reported_by:v||"unknown",what_failed:ie||"",resolved:!1}),"EX",3600*24*90)}}}if(t==="success"&&(V==="fix"||V==="debug")){const se=await h.smembers(`cachly:ckg:idx:from:${N}`);for(const G of se.slice(0,10)){const U=await h.get(G);if(!U)continue;const D=F(U,null);if(!D||D.edgeType!=="fixes")continue;const ne=await h.smembers(`cachly:ckg:idx:from:${D.to}`);for(const be of ne.slice(0,5)){const Ne=await h.get(be);if(!Ne)continue;const Ae=F(Ne,null);Ae&&Ae.edgeType==="co-occurs"&&(Ae.successes=(Ae.successes||0)+.1,Ae.trials=(Ae.trials||0)+.1,Ae.confidence=(Ae.successes+1)/(Ae.trials+2),Ae.last_updated=new Date().toISOString(),await h.set(be,JSON.stringify(Ae)))}}}if(Math.random()<.01){const se=Date.now()-7776e6,G=await h.smembers(`cachly:ckg:idx:from:${N}`);for(const U of G){const D=await h.get(U);if(!D)continue;const ne=F(D,null);ne&&ne.trials<3&&ne.last_updated&&new Date(ne.last_updated).getTime()<se&&(ne.confidence=ne.confidence*.9,ne.last_updated=new Date().toISOString(),await h.set(U,JSON.stringify(ne)))}}}catch{}if(v){const N=ae(h,`cachly:agents:active:${v}`);h.set(N,JSON.stringify({author:v,last_topic:o,last_outcome:t,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const V=o.split(":")[0]??"unknown",le=await Zs(h,vs(v),V),se=Se(o);await Ee(h,le,"authored",se,t==="success",t==="partial");for(const G of e.slice(0,8)){const U=await Jt(h,G);await Ee(h,le,"touched",U,!0),await Xs(h,U,le)}}catch{}}if(s&&typeof s=="string"&&s.trim())try{const N=o.split(":")[0]??"unknown",V=_==="system"?"system":"service",le=await Qs(h,s.trim(),N,V),se=Se(o);if(await Ee(h,se,"affects",le,t==="success",t==="partial"),v){const G=`person:${Se(vs(v))}`;await Ee(h,G,"operates",le,!0)}for(const G of e.slice(0,8)){const U=`file:${Se(G)}`;await Ee(h,U,"runs_in",le,!0)}}catch{}if(K&&v&&(t==="success"||t==="partial")){const N={topic:o,outcome:t,what_worked:Q,what_failed:ie??"",severity:A,author:v,file_paths:e,commands:g,tags:[...new Set([...I,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},V=`cachly:lessons:${o}`;h.rpush(V,JSON.stringify(N)).catch(()=>{})}const ge=t==="success"?"\u2705":t==="partial"?"\u26A0\uFE0F":"\u274C",ye=A==="critical"?"\u{1F534}":A==="major"?"\u{1F7E1}":"\u{1F7E2}",me=ue?"updated":"stored",oe=await Co(q)??at,fe=oe.doppel,ve=await As(h,o);return[`${ge} **Lesson ${me}:** \`${o}\` (${t}) ${ye} ${A} \xB7 receipt: \`${p}\``,c.funde.length?`\u{1F512} **${c.funde.length} secret(s) redacted** before saving (${c.funde.join("; ")}). The value is not in the Brain \u2014 refer to where it lives instead (e.g. an Infisical path or a variable name).`:"",ca(n),ce??"",ve?da(ve):"","",`**What worked:** ${Q}`,ie?`**What failed:** ${ie}`:"",pe?`**Context:** ${pe}`:"",e.length>0?`**Files:** ${e.map(N=>`\`${N}\``).join(", ")}`:"",g.length>0?`**Commands:** ${g.map(N=>`\`${N}\``).join(", ")}`:"",I.length>0?`**Tags:** ${I.map(N=>`#${N}`).join(" ")}`:"","",ue?`\u267B\uFE0F Updated (recall count: ${_e} \xB7 audit entries: ${Ce.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${o}")\``,C==="private"?"\u{1F512} Private \u2014 kept out of `team_recall` and out of teammates' recall":$?`\u{1F465} Group \`${$}\` only \u2014 teammates outside the group don't see it`:v&&(t==="success"||t==="partial")?`\u{1F465} Auto-shared with team (by _${v}_${f.quelle!=="uebergeben"?` \xB7 from ${f.quelle}`:""}) \u2014 visible in \`team_recall\``:"",L??"",x.length>0?`\u{1F517} Depends on: ${x.map(N=>`\`${N}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",Oe,_s(fe,Oe),J?"":xo(oe.nahe,Oe+_s(fe,Oe)),X.angaben.length?`\u{1F4E6} Applies to ${X.angaben.map(N=>`\`${N}\``).join(", ")}${X.uebernommen?" (carried over from the previous version)":""} \u2014 if the project does not match, the lesson ranks last in recall and is marked.`:"",...X.fehler.map(N=>`\u26A0\uFE0F gilt_fuer not stored, ${N}. Format: package@range, for example next@<15 or python:fastapi@>=0.100 <0.110.`),Re&&Z?Ie?`\u21B7 Replaces \`${J}\` \u2014 recall hides the old version and names its successor with the reason.`:`\u21B7 Replaces \`${J}\` \u2014 recall hides the old version and names its successor. Without \`grund\` it says 'No reason recorded' \u2014 one line (why the old one was wrong) makes the link checkable.`:Pe,...ke,...Me,...rt,$e>0?`\u{1F5D3}\uFE0F ${$e} relative time reference${$e===1?"":"s"} dated (e.g. "yesterday" \u2192 "yesterday (${new Date(W.getTime()-864e5).toISOString().slice(0,10)})") \u2014 the original text stays unchanged, the date stands next to it.`:"",Xo(Q)??"",na({outcome:t,topic:o,what_worked:Q,what_failed:ie,file_paths:e}),oa({outcome:t,topic:o,what_worked:Q,what_failed:ie,file_paths:e})].filter(N=>N!=="").join(`
|
|
12
|
+
`)}case"lesson_verified":{const{instance_id:c}=w,n=await M(c),a=new Date().toISOString(),u=w,o=Ge({geprueft_mit:u.geprueft_mit,befund:u.befund}),t=qs({...u,...o.felder},a);if(!t.ok)return[`\u26A0\uFE0F ${t.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(`
|
|
13
|
+
`);const S=t.eintrag,l=`cachly:lesson:best:${S.topic}`,i=await n.get(l);if(!i)return`\u{1F4ED} Keine Lektion \`${S.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const A=F(i,{}),e=Ys(A,S);return await n.set(l,JSON.stringify(o.verdacht.length?{...e,tags:la(e.tags,o.verdacht)}:e)),as(),!S.haelt&&S.ursache==="umgebung"?[`\u2139\uFE0F \`${S.topic}\`: Pruefung an der Umgebung gescheitert \u2014 die Lektion bleibt, wie sie war.`,` Befund: ${S.befund}`,"","Nicht als fraglich markiert, `verified_at` unveraendert. Das sagt etwas ueber","den Tag, nicht ueber die Lektion. Pruefe noch einmal, wenn die Umgebung wieder steht.",...Ke(o)].join(`
|
|
14
|
+
`):S.haelt?[`\u2705 \`${S.topic}\` ist wieder frisch \u2014 geprueft am ${a.slice(0,10)}.`,S.geprueft_mit?` geprueft mit: \`${S.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...Ke(o)].filter(Boolean).join(`
|
|
15
|
+
`):[`\u26A0\uFE0F \`${S.topic}\` ist als fraglich markiert.`,` Befund: ${S.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="${S.topic}", \u2026, grund="\u2026")\`.`,...Ke(o)].join(`
|
|
16
|
+
`)}case"recall_feedback":{const{instance_id:c}=w,n=await M(c),a=lo(ho(w),new Date().toISOString());if(!a.ok)return[`\u26A0\uFE0F ${a.grund}`,"","Example:","```",'recall_feedback(instance_id="\u2026", query="why does the deploy abort",',' topic="ci:timeout-reports-cancelled", helped=true, rank=0)',"```","rank=0 means: the lesson was NOT in the answer at all.","That is the most valuable feedback there is."].join(`
|
|
17
|
+
`);const u=a.eintrag,o=ae(n,`cachly:wirkung:${c}`);await n.rpush(o,JSON.stringify(u));const S=(await n.lrange(o,0,-1).catch(()=>[])).map(g=>F(g,null)).filter(Boolean),l=uo(S),i=fo(u),A={"fehlender-treffer":"It helped but was not in the answer at all \u2014 the search never picked it up. That is the most valuable case.","zu-weit-hinten":`It helped but was only at rank ${u.platz} \u2014 the ranking was too weak.`,"falsch-und-sicher":`It was at rank ${u.platz} and did not help \u2014 the ranking was confident and wrong.`,bestaetigung:"It was near the top and helped. Confirmed.",unauffaellig:"It did not help and was far down. Says little."},e=l.trefferquote===null?"no helpful feedback yet":`${(l.trefferquote*100).toFixed(0)} % of the helpful lessons were in the top three`;return[`\u2705 Noted: **${u.thema}** \u2014 ${u.geholfen?"helped":"did not help"}, rank ${u.platz===0?"\u2014 (not in the answer)":u.platz}`,"",A[i],"",`Feedback so far: ${l.gesamt}, ${e}.`,`Of these: ${l.nachLehrwert["fehlender-treffer"]} not found \xB7 ${l.nachLehrwert["zu-weit-hinten"]} too far down \xB7 ${l.nachLehrwert["falsch-und-sicher"]} confident and wrong.`].join(`
|
|
18
|
+
`)}case"recall_best_solution":{const c=Date.now(),{instance_id:n,topic:a,author:u}=w,o=await An(n,j,`\u{1F4ED} No lessons found for \`${a}\`.`);if(o)return o;const t=await M(n);let S=await t.get(`cachly:lesson:best:${a}`);const l=S?null:await bn(t,a).catch(()=>null);l&&(S=l.roh);const i=ae(t,`cachly:letzter-recall:${n}`),A=ae(t,`cachly:wirkung:${n}`);if(Nt(t,i)&&!l)try{const s=await t.get(i),_=s?F(s,null):null,b=mo(_,a,new Date().toISOString());b&&(await t.rpush(A,JSON.stringify(b)),await t.del(i))}catch{}if(S){const s=F(S,null);if(!s)return`\u26A0\uFE0F Lesson data for \`${a}\` is corrupted. Re-store it with \`learn_from_attempts\`.`;const _=s.group;if(_&&!l){const de=u?await xt(t,n,u).catch(()=>new Set):new Set,Ie=await Ct(t,n,u??"").catch(()=>null)==="admin";if(!st(_,de,Ie))return`\u{1F4ED} No lessons found for \`${a}\`. Use \`learn_from_attempts\` after solving it.`}const b=Vt(s),R=s.verified_at??s.ts,z=(Date.now()-new Date(R).getTime())/864e5,P=s.commands,r=Ks(b,z,Array.isArray(P)&&typeof P[0]=="string"?P[0]:void 0,s.pruefung_gefallen_am?{am:s.pruefung_gefallen_am,befund:s.pruefung_befund}:void 0,s.pruefung_umgebung_am?{am:s.pruefung_umgebung_am,befund:s.pruefung_umgebung_befund}:void 0),re=new Date().toISOString(),ee={...s,recall_count:(s.recall_count??0)+1,last_recalled_at:re};!l&&qe(t)?ns(j,n,[a]):l||await t.set(`cachly:lesson:best:${a}`,JSON.stringify(ee)),jt(t),l||Ot(t,String(a??""),Date.now()-c);const we=Zt(s)?Yt(s):0;we>0&&!l&&t.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,we).catch(()=>{});const h=s.severity==="critical"?"\u{1F534}":s.severity==="major"?"\u{1F7E1}":s.severity?"\u{1F7E2}":"",W=s.audit_trail??[],te=W.filter(de=>de&&typeof de.grund=="string"&&de.grund.trim().length>0).slice(-3).map(de=>` \xB7 ${de.ts?new Date(de.ts).toLocaleDateString("de-DE"):"?"}: ${de.grund.trim()}`),X=W.length>1?[`_Audit: ${W.length} changes \xB7 stored ${new Date(s.ts).toLocaleDateString("de-DE")}_`,...te.length>0?["**Warum zuletzt geaendert:**",...te]:[]].join(`
|
|
19
|
+
`):"",Y=(Date.now()-new Date(s.ts).getTime())/864e5,Q=Y>60?`\u{1F4AD} _Remember when you solved this ${Math.round(Y/30)} months ago? Still works._`:"",ie=s.authors??(s.author?[s.author]:[]),pe=[...new Set(ie.filter(Boolean))];let $e="";pe.length>=2&&($e=`\u2705 **Team-verified** \u2014 confirmed by ${pe.length} developers.`);const f=s.ersetzt_durch,T=s.ersetzt_am?` (on ${s.ersetzt_am.slice(0,10)})`:"",v=f?await t.get(`cachly:lesson:best:${f}`):null,L=String(s.ersetzt_grund??"").trim(),C=L?` Reason: ${L}`:" No reason recorded.",$=v?je(v):null,K=v?!yt($):!1;let E=!1;if(v&&!K&&$?.group){const de=u?await xt(t,n,u).catch(()=>new Set):new Set,Ie=await Ct(t,n,u??"").catch(()=>null)==="admin";E=!st($.group,de,Ie)}const H=f?v?K?`\u{1F6AB} **THIS VERSION IS REPLACED**${T} \u2014 the successor lesson is private, not visible to the team. The text below stays readable as history; its author knows the current version.`:E?`\u{1F6AB} **THIS VERSION IS REPLACED**${T} \u2014 the successor lesson is not visible to you. The text below stays readable as history.`:`\u{1F6AB} **THIS VERSION IS REPLACED**${T} \u2014 the current answer is in \`recall_best_solution(topic="${f}")\`.${C} The text below stays readable as history.`:`\u26A0\uFE0F **REPLACEMENT POINTS NOWHERE**${T} \u2014 the successor \`${f}\` has been deleted. This version applies again as the best EXISTING answer; confirm it when you can (learn_from_attempts with grund).`:"",he=s.gilt_ab,ke=s.gilt_bis,ue=he?`\u{1F4C5} Valid since ${String(he).slice(0,10)}.`:"",_e=s.entscheidung,Te=_e?.gegen?fs({gegen:_e.gegen,grund:_e.grund??null}):"",Ce=ke&&Date.parse(String(ke))<Date.now()?`\u23F3 **THIS FACT WAS VALID UNTIL ${String(ke).slice(0,10)}** \u2014 it is history, not current information.`:"";return[Cs(s),H,Ce,Un(s.gilt_fuer),ue,Te,Q,$e,`${r} **Best solution for \`${a}\`** ${h}${s.severity?` (${s.severity})`:""} \xB7 in ${ee.recall_count} answer${ee.recall_count===1?"":"s"} so far`,vo(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(de=>`\`${de}\``).join(", ")}`:"",(s.commands??[]).length>0?`**Commands:** ${(s.commands??[]).map(de=>`\`${de}\``).join(", ")}`:"",(s.tags??[]).length>0?`**Tags:** ${(s.tags??[]).map(de=>`#${de}`).join(" ")}`:"",X].filter(de=>de!=="").join(`
|
|
20
|
+
`)}const e=await As(t,a);if(e){const s=await ut(t,n,u);return We(e,s)?ua(a,e):`\u{1F4ED} No lessons found for \`${a}\`. Use \`learn_from_attempts\` after solving it.`}const g=[],I=t.scanStream({match:"cachly:lesson:best:*",count:ts});await new Promise((s,_)=>{I.on("data",b=>g.push(...b)),I.on("end",s),I.on("error",_)});const x=await ut(t,n,u),d=g.filter(s=>s.toLowerCase().includes(a.toLowerCase()));if(d.length===0){const s=`cachly:lessons:${a}`,_=await t.lrange(s,-3,-1);if(_.length>0){const b=_.map(z=>F(z,null)).filter(z=>!!z&&st(z.group,x.scopes,x.isAdmin));if(b.length===0)return`\u{1F4ED} No lessons found for \`${a}\`. Use \`learn_from_attempts\` after solving it.`;const R=b.map(z=>`- ${z.outcome==="success"?"\u2705":"\u274C"} ${z.what_worked.slice(0,120)} (${new Date(z.ts).toLocaleDateString("de-DE")})`);return`\u26A0\uFE0F No successful solution for \`${a}\` yet. Last attempts:
|
|
21
21
|
|
|
22
|
-
${
|
|
23
|
-
`)}`}return`\u{1F4ED} No lessons found for \`${
|
|
24
|
-
`:""}**\`${
|
|
22
|
+
${R.join(`
|
|
23
|
+
`)}`}return`\u{1F4ED} No lessons found for \`${a}\`. Use \`learn_from_attempts\` after solving it.`}const m=[];for(const s of d.slice(0,50)){if(m.length>=5)break;const _=await t.get(s);if(!_)continue;const b=F(_,null);if(!We(b,x))continue;const R=Cs(b);m.push(`${R?`${R}
|
|
24
|
+
`:""}**\`${b.topic}\`** \u2014 ${b.what_worked.slice(0,400)}${b.what_worked.length>400?" \u2026":""}`)}return m.length===0?`\u{1F4ED} No lessons found for \`${a}\`. Use \`learn_from_attempts\` after solving it.`:`\u{1F50D} **Partial matches for \`${a}\`:**
|
|
25
25
|
|
|
26
|
-
${
|
|
26
|
+
${m.join(`
|
|
27
27
|
|
|
28
|
-
`)}`}case"smart_recall":{const l=Date.now(),{instance_id:n,query:r,threshold:f=.78,author:o="",context_files:t=[],limit:k}=y,c=no(r),i=Io(k),A=Array.isArray(t)?t.filter(g=>typeof g=="string"):[];if(Ce("smart_recall: Anfang"),!so(c))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await ss(n,j)){const g=Date.now()-l;return E(n).then(w=>Ms(w,n,String(c??""),g)).catch(()=>{}),Ce("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),ns(String(c??""),{startet:!0,...await At(n)})}const e=await E(n);Ce("smart_recall: Verbindung steht");const{vektor:m,namen:I,zweit:C,eingang:s,seltenheit:u}=Bt(e);Ge()&&Promise.allSettled([m.aktualisiere(e),I.aktualisiere(e),s.aktualisiere(e),u.aktualisiere(e),C.aktualisiere(e)]),Wt(e,void 0,2);let d=new Set,b=!1;o&&(d=await xt(e,n,o).catch(()=>new Set)),b=await Ct(e,n,o).catch(()=>null)==="admin";const $=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],M=await Sn(e,$);if(Ce(`smart_recall: Wortbestand da (${M?.docs.length??0} Eintraege)`),!M)return Ms(e,n,String(c??""),Date.now()-l),Ce("smart_recall: Brain leer \u2014 sofort geantwortet"),ns(String(c??""),{startet:!1,...await At(n)});const z=M.docs.reduce((g,w)=>g+(w.key.startsWith("cachly:lesson:best:")?1:0),0),O=hn(e,Nt(c).filter(g=>g.length>=4).slice(0,4)).catch(()=>null),a=(async()=>{const g=await ln(n,()=>j(`/api/v1/instances/${n}`)),w=[];if(!(!g?.tier||g.tier.toLowerCase()==="free")&&g?.vector_token&&Ge())try{const se=await Ie(c),B=`https://api.cachly.dev/v1/sem/${g.vector_token}`,q=await fetch(`${B}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:se,namespace:"cachly:ctx",threshold:f,top_k:5}),signal:AbortSignal.timeout(8e3)});if(q.ok){const we=(await q.json()).filter(de=>de.found&&de.id).map(de=>{const oe=de.id.replace("ctx:","").split(":");return{hit:de,redisKey:`cachly:ctx:${oe[0]}:${oe.slice(1).join(":")}`}}),ye=await Promise.all(we.map(de=>e.get(de.redisKey).catch(()=>null)));we.forEach((de,oe)=>{w.push({key:de.redisKey,similarity:de.hit.similarity??0,content:ye[oe]??"(evicted)"})})}}catch{}return{inst:g,semHits:w}})().catch(()=>({inst:null,semHits:[]})),ie=await ft(e,$,c,25);Ce(`smart_recall: Wortsuche fertig (${ie.length} Treffer)`);const ae=Tn(ie);let ge=!1,h=null;const G=await(async()=>{if(!Ge())return kt(tn,"no embedding service configured, so search uses words only"),ae;try{if(await m.aktualisiere(e),Ce(`smart_recall: Vektorbestand geladen (${m.groesse})`),m.groesse===0)return z>0&&(kt(en,"no lesson has an embedding yet, so search uses words only. A new brain fills them in the background; if this stays, run brain_doctor"),Wt(e,void 0,6)),ae;const g=await Ie(c);if(Ce("smart_recall: Frage eingebettet"),!g?.length)return kt(sn,"the question could not be embedded, so this search uses words only"),ae;await I.aktualisiere(e),await s.aktualisiere(e),await u.aktualisiere(e),await C.aktualisiere(e),Ce(`smart_recall: Bestaende geladen (Namen ${I.groesse}, Eingaenge ${s.groesse}, Seltenheit ${u.groesse}, Zweit ${C.groesse})`);const w=m.groesse>0?C.groesse/m.groesse:0;w<us&&m.groesse>0&&Na(e,3);const L=w>=us?Ie(c,{modell:et}).catch(()=>null):null,se=ae.filter(W=>W.key.startsWith("cachly:lesson:best:")).map(W=>W.key.slice(19)),B=W=>Math.max(m.naehe(g,W),I.naehe(g,W)),q=[...u.themen()],le=(q.length>0?q:m.aehnlichste(g,500).map(W=>W.topic)).map(W=>({t:W,n:B(W)})).sort((W,fe)=>fe.n-W.n||(W.t<fe.t?-1:W.t>fe.t?1:0)).slice(0,gs).map(W=>W.t),we=[...new Set([...se,...le])],ye=le.slice(0,3).map(W=>m.rohvektor(W)).filter(Boolean),de=ye.length?Zn(g,ye):g,oe=hs(c),_=u.statistik,H=we.map(W=>{const fe=new Set([...hs(u.textVon(W))].map(Xn));return{naeheText:m.naehe(g,W),naeheThema:I.naehe(g,W),naeheRueckkopplung:m.naehe(de,W),seltenheitsDeckung:_?_.deckung(oe,fe):0,besterZeuge:_?_.besterZeuge(oe,fe):0}});let ce=Yn(H,Qn);{const W=[...ce].sort((fe,pe)=>pe-fe);h=W.length>1?W[0]-W[1]:null}if(s.groesse>0){const W=we.map(pe=>{const Ee=s.besteNaehe(g,pe);return Ee>=No?Ee:-2}),fe=ls(W);ce=ce.map((pe,Ee)=>pe+Ao*fe[Ee])}if(L){const W=await L;if(W?.length){const fe=ls(we.map(pe=>C.naehe(W,pe)));ce=ce.map((pe,Ee)=>pe+wo*fe[Ee])}}let J=we.map((W,fe)=>({t:W,p:ce[fe]})).sort((W,fe)=>fe.p-W.p).map(W=>W.t);if(En(n)&&J.length>1){const W=J.slice(0,ds),fe=J.slice(ds),pe=new Map(we.map((ct,tt)=>[ct,ce[tt]]));Ce("smart_recall: Leser Anfang");const Ee=await In(c,W.map(ct=>u.leserTextVon(ct)),{instanceId:n});Ce(`smart_recall: Leser ${Ee?"fertig":"ohne Ergebnis"}`),Ee&&(J=[...Mn(W.map(tt=>pe.get(tt)??0),Ee).map(tt=>W[tt]),...fe])}const P=new Map(ae.map(W=>[W.key,W])),Z=J.map(W=>`cachly:lesson:best:${W}`).filter(W=>!P.has(W)),be=new Map;if(Z.length>0){const W=await e.mget(...Z).catch(()=>[]);Z.forEach((fe,pe)=>be.set(fe,W[pe]??null))}const Se=[];for(const W of J){const fe=`cachly:lesson:best:${W}`,pe=P.get(fe);if(pe){Se.push(pe),P.delete(fe);continue}const Ee=be.get(fe)??null;Ee&&Se.push({key:fe,content:Ee,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return Se.push(...P.values()),fo&&uo({frage:c.slice(0,200),themen:we,ausWortsuche:se.length,ausSinnsuche:le.length,obergrenze:gs,gezeigt:J.slice(0,10)}),ge=!0,Se}catch(g){return await st(e,nn,`search by meaning stopped (${g instanceof Error?g.message:String(g)}) - this search used words only`),ae}})();Ce("smart_recall: Bedeutungspfad fertig"),zt(e),Lt(e,String(c??""),Date.now()-l);{const g=G.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));if(g.length>0){const w={ts:new Date().toISOString(),themen:g},L=as(n);bn(e,L)&&(async()=>{await e.lpush(L,JSON.stringify(w)),await e.ltrim(L,0,Jn-1)})().catch(()=>{})}{const w={ts:new Date().toISOString(),frage:c.slice(0,200),geliefert:g};(async()=>{const L=Rt(n);await e.lpush(L,JSON.stringify(w)),await e.ltrim(L,0,is-1)})().catch(()=>{})}}if(Ge()&&!St()&&!He(e)){const g=G.filter(w=>w.key.startsWith("cachly:lesson:best:")).slice(0,3).map(w=>w.key.slice(19));jn(e,c,g,Ie).catch(()=>{})}const te=G.filter(g=>g.key.startsWith("cachly:lesson:best:"));let Q=0,X=0;const ee=He(e),ne=[];for(const g of te.slice(0,5)){const w=await e.get(g.key).catch(()=>null);if(w){const L=F(w,null);if(L?.state==="archived")continue;if(L){const se=new Date().toISOString(),B={...L,recall_count:(L.recall_count??0)+1,last_recalled_at:se};ee?ne.push(g.key.slice(19)):St()||e.set(g.key,JSON.stringify(B)).catch(()=>{});const q=Jt(L)?Vt(L):0;if(q>0&&e.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,q).catch(()=>{}),L.author&&o&&L.author!==o&&(Q++,e.sadd(`cachly:stats:reuse_pairs:${n}`,`${o}<-${L.author}`).catch(()=>{}),!ee)){const le=`person:${ke(o)}`,we=`person:${ke(L.author)}`;Te(e,le,"collaborates",we,!0).catch(()=>{}),Te(e,we,"collaborates",le,!0).catch(()=>{})}L.outcome==="success"&&X++}}}ee&&ne.length>0&&!St()&&Qt(j,n,ne),X>0&&e.set(`cachly:stats:first_recall_at:${n}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),te.length>0&&(e.incr(`cachly:stats:recalls_total:${n}`).catch(()=>{}),Q>0&&e.incr(`cachly:stats:cross_author_recalls:${n}`).catch(()=>{})),Ce("smart_recall: Treffer gezaehlt");const{inst:ue,semHits:_e}=await a;Ce("smart_recall: Tarif abgefragt");const p=!ue?.tier||ue.tier.toLowerCase()==="free",N=G.map(g=>g.score),v=N.length?Math.min(...N):0,R=N.length&&Math.max(...N)-v||1,x=g=>(g-v)/R,S=new Map,V=ge?zn(G.map(g=>x(g.score))):null,K=new Map;for(const[g,w]of G.entries()){const L=x(w.score),se=V?V[g]:L;V&&S.set(w.key,g),K.set(w.key,{key:w.key,content:w.content,bm25Score:L,hausWert:se,hybridScore:se*(_e.length>0?.7:1),matchedWords:w.matchedWords,matchType:"keyword",subQuery:w.subQuery,wortBelege:w.wortBelege})}for(const g of _e){const w=K.get(g.key);w?(w.semScore=g.similarity,w.hybridScore=(w.hausWert??0)*.6+g.similarity*.4,w.matchType="hybrid"):K.set(g.key,{key:g.key,content:g.content,semScore:g.similarity,hybridScore:g.similarity*.5,matchType:"semantic"})}try{const g=await O,w=new Set;for(const{kante:L,inhalt:se}of g??[]){if(L.edgeType!=="fixes"||L.confidence<.35||w.has(L.from))continue;w.add(L.from);const B=`cachly:lesson:best:${L.from}`,q=K.get(B);if(q)q.ckgScore=Math.max(q.ckgScore??0,L.confidence),q.hybridScore=q.hybridScore*.88+L.confidence*.12,q.matchType==="keyword"&&(q.matchType="hybrid");else{if(!se)continue;K.set(B,{key:B,content:se,ckgScore:L.confidence,hybridScore:L.confidence*.3,matchType:"ckg"})}}}catch{}if(Ce("smart_recall: Sinn-Dienst und CKG fertig"),A.length>0){const g=new Set(A.map(w=>w.replace(/\\/g,"/")));for(const w of K.values()){if(!w.key.startsWith("cachly:lesson:best:"))continue;const L=F(w.content,{});(Array.isArray(L.file_paths)?L.file_paths.filter(B=>typeof B=="string").map(B=>B.replace(/\\/g,"/")):[]).some(B=>g.has(B))&&(w.hybridScore*=1.15,w.contextBoost=!0)}}for(const g of K.values()){if(g.matchType!=="semantic"&&g.matchType!=="ckg")continue;const w=An({key:g.key,content:g.content});w&&(g.hybridScore*=Nn(w))}const U=[...K.values()].filter(g=>{if(!g.key.startsWith("cachly:lesson:best:"))return!0;const w=Pe(g.content);return!(!_t(w)||!nt(w?.group,d,b))}),D=V?Dn(U,S):U.sort((g,w)=>w.hybridScore-g.hybridScore),he=[];for(const g of D){if(!g.key.startsWith("cachly:lesson:best:"))continue;const w=F(g.content,{});w.gilt_bis&&Date.parse(String(w.gilt_bis))<Date.now()&&he.push(`\u23F3 \`${g.key.replace("cachly:lesson:best:","")}\` was valid until ${String(w.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const L=F(g.content,{});if(L.pruefung_gefallen_am){const se=g.key.replace("cachly:lesson:best:",""),B=String(L.pruefung_gefallen_am).slice(0,10),q=String(L.pruefung_befund??"").trim().slice(0,200);he.push(`\u274C \`${se}\` \u2014 Pruefung am ${B} FEHLGESCHLAGEN`+(q?`: ${q}`:""))}else if(L.pruefung_umgebung_am){const se=g.key.replace("cachly:lesson:best:",""),B=String(L.pruefung_umgebung_am).slice(0,10),q=String(L.pruefung_umgebung_befund??"").trim().slice(0,120);he.push(`\u2139\uFE0F \`${se}\` \u2014 Pruefung am ${B} an der Umgebung gescheitert, sagt nichts ueber die Lektion`+(q?`: ${q}`:""))}}{const g=new Set(D.map(w=>w.key));for(let w=D.length-1;w>=0;w--){const L=D[w];if(!L.key.startsWith("cachly:lesson:best:"))continue;const se=F(L.content,{});if(!se.ersetzt_durch)continue;const B=String(se.ersetzt_grund??"").trim(),q=L.key.replace("cachly:lesson:best:","");if(g.has(`cachly:lesson:best:${se.ersetzt_durch}`))D.splice(w,1),he.push(`\u21B7 \`${q}\` hidden \u2014 replaced by \`${se.ersetzt_durch}\`${se.ersetzt_am?` on ${se.ersetzt_am.slice(0,10)}`:""}${B?` \u2014 reason: ${B}`:" \u2014 no reason recorded"}`);else if(await e.get(`cachly:lesson:best:${se.ersetzt_durch}`)){const le=Pe(await e.get(`cachly:lesson:best:${se.ersetzt_durch}`));!_t(le)||!nt(le.group,d,b)?he.push(`\u21B7 \`${q}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`):he.push(`\u26A0\uFE0F \`${q}\` is replaced by \`${se.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${se.ersetzt_durch}")\``)}else he.push(`\u21A9\uFE0F \`${q}\` was replaced by \`${se.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const me=wt()?new Map:Fn(D,A),$e=[];{await m.aktualisiere(e).catch(()=>{});const g=D.slice(0,8).filter(w=>w.key.startsWith("cachly:lesson:best:"));for(let w=0;w<g.length;w++)for(let L=w+1;L<g.length;L++){const se=g[w].key.replace("cachly:lesson:best:",""),B=g[L].key.replace("cachly:lesson:best:",""),q=m.rohvektor(se),le=m.rohvektor(B);if(!q||!le)continue;let we=0,ye=0,de=0;for(let H=0;H<q.length;H++)we+=q[H]*le[H],ye+=q[H]*q[H],de+=le[H]*le[H];if((ye>0&&de>0?we/(Math.sqrt(ye)*Math.sqrt(de)):0)<yo)continue;const _=H=>{const ce=F(H??"",{});return String(ce.verified_at??ce.ts??"").slice(0,10)||"no date"};$e.push(`\u26A0\uFE0F \`${se}\` (${_(g[w].content)}) und \`${B}\` (${_(g[L].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}$e.length>3&&($e.length=3)}if(he.push(...$e),D.length>=2){const g=D[0].hybridScore,w=D[Math.min(4,D.length-1)].hybridScore,L=Math.max(0,g-w);(async()=>{try{await e.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(L.toFixed(4)),n:D.length})),await e.ltrim("cachly:recall:spread",0,199)}catch{}})()}const re=on();let ve="",We=null;if(re!==null){ve=an();const g=D[0]?.hybridScore??0,w=rn(D.map(L=>({key:L.key,content:L.content,punktzahl:L.hybridScore})),ve,re,g);w.weggelassenesThema!==void 0?D.splice(0,1):w.markierungGesetzt&&D[0]&&w.treffer[0]&&(D[0]={...D[0],content:w.treffer[0].content}),We={frage:c,hoechstePunktzahl:g,themen:[],zulassungsfaehig:w.zulassungsfaehig,zulassungsGrund:w.zulassungsGrund,zuteilung:w.zuteilung,weggelassenesThema:w.weggelassenesThema,markierungGesetzt:w.markierungGesetzt}}Ce("smart_recall: Notizen und Duplikate fertig");const Me=await Bs(n,j);Ce("smart_recall: Abruf-Grenze abgefragt");const Be=Me.reached,Ke=ws({ueberLimit:Be,gesamt:D.length,volleTiefe:i??Mo}),Ae=process.env.CACHLY_RECALL_COMPACT==="1",xe=(()=>{const g=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(g)?Math.min(20,Math.max(1,g)):5})(),Oe=Ae?Math.min(xe,Ke.sichtbar):Ke.sichtbar,Y=[`\u{1F9E0} **Smart Recall** for: _"${c}"_
|
|
29
|
-
`];
|
|
30
|
-
`),
|
|
31
|
-
`);const
|
|
32
|
-
`);const
|
|
33
|
-
`);const
|
|
34
|
-
`);const
|
|
35
|
-
`),
|
|
36
|
-
`)}if(
|
|
37
|
-
`);for(const oe of
|
|
38
|
-
\u26A0\uFE0F **No results for:** ${
|
|
39
|
-
`)}}else{
|
|
40
|
-
\u{1F4A1} Tips:`),
|
|
41
|
-
`))}return
|
|
42
|
-
`)}case"session_start":{const{instance_id:
|
|
43
|
-
`).slice(0,8))
|
|
44
|
-
`).filter(R=>R.includes("|")||R.includes("changed"));if(v.length>0){a.push(" **Recent changes:**");for(const R of v.slice(0,5))a.push(` ${R.trim()}`)}}a.push("")}}catch{}if(u){const p=Math.round((Date.now()-new Date(u.ts).getTime())/6e4),N=p<60?`${p}m ago`:p<1440?`${Math.round(p/60)}h ago`:`${Math.round(p/1440)}d ago`;a.push(`\u{1F4C5} **Last session** (${N}): ${u.summary}`),u.duration_min&&a.push(` Duration: ${u.duration_min} min`),(u.files_changed??[]).length>0&&a.push(` Files: ${(u.files_changed??[]).slice(0,5).map(v=>`\`${v}\``).join(", ")}`),a.push("")}a.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${I} context entries`,""),A>0&&a.push(`\u26A0 ${A} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const N=await t.lrange(`cachly:wirkung:${l}`,0,-1).catch(()=>[]),v=ho(N.map(S=>F(S,null)).filter(Boolean)),R=S=>v.get(S)??{geholfen:0,geoeffnet:0},x=i.filter(S=>!qs(S)).filter(S=>{if(S.outcome!=="success")return!1;const V=R(S.topic);return V.geholfen>=1||V.geoeffnet>=2}).filter(S=>!G.has(S.topic)).sort((S,V)=>{const K=R(S.topic),U=R(V.topic);return U.geholfen-K.geholfen||U.geoeffnet-K.geoeffnet||(V.recall_count??0)-(S.recall_count??0)}).slice(0,5);if(x.length>0){a.push("\u{1F4CC} **Confirmed lessons** (reported helpful, or opened after a search \u2014 being shown does not count):");for(const S of x){G.add(S.topic);const V=S.severity==="critical"?"\u{1F534}":S.severity==="major"?"\u{1F7E1}":"",K=R(S.topic),U=[K.geholfen>0?`reported helpful ${K.geholfen}\xD7`:"",K.geoeffnet>0?`opened ${K.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),D=lt(S);a.push(` \u2705${V} \`${S.topic}\` _(${U})_ \u2014 ${D[0]??""}`,...D.slice(1))}a.push("")}}try{const p=[],N=t.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((v,R)=>{N.on("data",x=>p.push(...x)),N.on("end",v),N.on("error",R)}),p.length>0){a.push(`\u26A1 **Active belief conflicts (${p.length}):**`);for(const v of p.slice(0,3)){const R=await t.get(v);if(!R)continue;const x=F(R,null);x&&(!m.has(x.topic)&&await t.exists(`cachly:lesson:best:${x.topic}`)||a.push(` \u26A0\uFE0F \`${x.topic}\` \u2014 previously confirmed fix (${(x.fix_confidence*100).toFixed(0)}%, n=${x.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${ke(x.topic)}")\``))}a.push("")}}catch{}if(h.length>0){a.push(`\u{1F3AF} **Relevant for "${n}":**`);for(const p of h){const N=p.outcome==="success"?"\u2705":p.outcome==="partial"?"\u26A0\uFE0F":"\u274C",v=p.severity==="critical"?"\u{1F534}":p.severity==="major"?"\u{1F7E1}":"",R=lt(p);a.push(` ${N}${v} \`${p.topic}\` \u2014 ${R[0]??""}`,...R.slice(1))}a.push("")}if(i.length>0){const p=(b.length>0?i.filter(N=>!b.includes(N)):i).filter(N=>!G.has(N.topic)).slice(0,b.length>0?3:4);if(p.length>0){a.push("\u{1F550} **Recent lessons:**");for(const N of p){G.add(N.topic);const v=N.outcome==="success"?"\u2705":N.outcome==="partial"?"\u26A0\uFE0F":"\u274C",R=N.severity==="critical"?"\u{1F534}":N.severity==="major"?"\u{1F7E1}":"",x=lt(N);a.push(` ${v}${R} \`${N.topic}\` \u2014 ${x[0]??""}`,...x.slice(1))}a.push("")}}else a.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some(N=>N.author)||(a.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),a.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const ee=await bo(t,i);if(ee.length>0){a.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const p of ee.slice(0,3))a.push(` \`${p.neu}\` \u2248 \`${p.alt}\` (${p.naehe.toFixed(2)})`);a.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),a.push("")}const ne=u;if(ne?.decision_log?.length){const p=ne.decision_log,N=p.filter((x,S)=>!G.has(x.topic)&&p.findIndex(V=>V.topic===x.topic)===S),v=N.filter(x=>x.outcome==="success"),R=N.filter(x=>x.outcome==="failure");if(v.length>0||R.length>0){a.push(`\u{1F3AC} **Last session decisions** (${p.length} lessons stored):`),v.length>0&&a.push(` \u2705 Worked: ${v.slice(0,3).map(x=>`\`${x.topic}\``).join(", ")}`),R.length>0&&a.push(` \u274C Failed: ${R.slice(0,3).map(x=>`\`${x.topic}\``).join(", ")}`),a.push("");for(const x of[...v.slice(0,3),...R.slice(0,3)])G.add(x.topic)}}{const p=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"]),N=S=>{const V=new Set;for(const K of S)for(const U of K.toLowerCase().split(/[/\\._-]/))U.length>3&&!p.has(U)&&V.add(U);return[...V]};let v=d,R=n,x=!1;if(v.length===0&&u){const S=N(u.files_changed??[]),V=(u.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(K=>K.length>3&&!p.has(K));v=[...new Set([...S,...V])],R="where you left off last session",x=!0}if(v.length>0){const S=i.filter(V=>{if(V.outcome==="success")return!1;const K=V.topic.split(":")[0];return v.some(U=>V.topic.toLowerCase().includes(U)||K===U||(V.tags??[]).some(D=>D.toLowerCase()===U))});if(S.length>=1){const K=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",x?` You're likely to continue **${R}** \u2014 ${S.length} known pitfall${S.length>1?"s":""} there:`:` Known pitfalls for **"${R}"** (${S.length} past failure${S.length>1?"s":""}):`,...S.slice(0,3).map(U=>` \u274C \`${U.topic}\` \u2014 ${(U.what_failed??U.what_worked).slice(0,80)}`),""];a.splice(2,0,...K)}}}if(r){const p=Date.now()-6048e5,N=i.filter(v=>v.author&&v.author!==r&&new Date(v.ts).getTime()>p&&!G.has(v.topic));if(N.length>0){const v=new Map;for(const R of N){const x=R.author;v.has(x)||v.set(x,[]),v.get(x).push(R)}a.push(`\u{1F465} **Team this week** (${N.length} lesson${N.length>1?"s":""} from teammates):`);for(const[R,x]of v){a.push(` \u{1F464} **${R}**:`);for(const S of x.slice(0,3)){const V=S.outcome==="success"?"\u2705":S.outcome==="partial"?"\u26A0\uFE0F":"\u274C";a.push(` ${V} \`${S.topic}\` \u2014 ${S.what_worked.slice(0,80)}`),G.add(S.topic)}x.length>3&&a.push(` \u2026 and ${x.length-3} more`)}a.push("")}}try{const p=await t.get("cachly:crystal:latest");if(p){const N=F(p,null);if(N&&Math.round((Date.now()-new Date(N.ts).getTime())/864e5)<=90){a.push(`\u{1F48E} **Memory Crystal** (${N.label} \xB7 ${N.session_count} sessions compressed):`);for(const R of N.top_patterns.slice(0,3))a.push(` \u2022 **${R.category}** (${R.count}\xD7): ${R.insight.slice(0,90)}`);a.push("")}}}catch{}try{const p=await t.hgetall(`cachly:roadmap:${l}`);if(p&&Object.keys(p).length>0){const N={critical:0,high:1,medium:2,low:3},v={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},R=new Set(["planned","in-progress","blocked"]),x=Object.values(p).flatMap(K=>{const U=F(K,null);return U?[U]:[]}),S=x.filter(K=>R.has(K.status)).sort((K,U)=>K.status==="in-progress"&&U.status!=="in-progress"?-1:U.status==="in-progress"&&K.status!=="in-progress"?1:(N[K.priority]??99)-(N[U.priority]??99)),V=x.filter(K=>K.status==="done").length;if(S.length>0){a.push(`\u{1F5FA}\uFE0F **Roadmap** (${S.length} open \xB7 ${V} done):`);for(const K of S.slice(0,5)){const U=K.status==="in-progress"?"\u26A1":K.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";a.push(` ${U} ${v[K.priority]??"\u26AA"} \`${K.id}\` **${K.title}**`)}S.length>5&&a.push(` \u2026 and ${S.length-5} more`),a.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),a.push("")}}}catch{}try{const p=await t.get("cachly:mcm:calibration:last"),N=F(p,null)?.ts??0;if((Date.now()-N)/864e5>=30&&i.length>=5){const R=i.filter(S=>S.outcome==="success"&&(S.recall_count??0)>0),x=i.filter(S=>(S.recall_count??0)>0);if(x.length>=3){const S=x.length>0?R.length/x.length:1,V=[],K=new Map;for(const U of x){const D=U.topic.split(":")[0]??"other";K.has(D)||K.set(D,{success:0,total:0});const he=K.get(D);he.total++,U.outcome==="success"&&he.success++}for(const[U,D]of K)D.total>=2&&D.success/D.total<.6&&V.push(U);await t.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:S,recalled:x.length,low_precision_domains:V})),(V.length>0||S<.7)&&(a.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${x.length} recalled lessons):`),a.push(` Overall precision: **${(S*100).toFixed(0)}%** recalled lessons actually worked`),V.length>0&&a.push(` \u26A0\uFE0F Low-precision domains: ${V.map(U=>`\`${U}\``).join(", ")} \u2014 consider revisiting these lessons`),a.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),a.push(""))}await t.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const ue=i.filter(p=>p.outcome==="failure"||p.outcome==="partial").length,_e=i.filter(p=>p.outcome==="success"&&Gt(p)<Fs).length;if(i.length===0||ue>0||_e>0){const p=[];i.length===0&&p.push("brain is empty"),ue>0&&p.push(`${ue} open failure${ue>1?"s":""}`),_e>0&&p.push(`${_e} stale lesson${_e>1?"s":""}`),a.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${p.join(", ")}._`)}try{if(await t.get(`cachly:prefs:auto_changelog:${l}`).catch(()=>null)!=="false"&&u?.ts&&!ge){const v=new Date(u.ts).getTime();if(!Number.isNaN(v)){const R=i.filter(S=>{const V=new Date(S.ts).getTime();return!Number.isNaN(V)&&V>v}),x=R.filter(S=>!G.has(S.topic));if(x.length>0){const S=Math.round((Date.now()-v)/6e4),V=S<60?`${S}m`:S<1440?`${Math.round(S/60)}h`:`${Math.round(S/1440)}d`,K=R.length-x.length;a.push(""),a.push(`\u{1F4CB} **${R.length} new lesson${R.length!==1?"s":""} since your last session** (${V} ago${K>0?`, ${K} already listed above`:""}):`);const U=new Map;for(const D of x.slice(0,20)){const he=D.topic.includes(":")?D.topic.split(":")[0]:"general",me=U.get(he)??[];me.push(D),U.set(he,me)}for(const[D,he]of U){a.push(` **${D}**`);for(const me of he){const $e=me.outcome==="failure"?"\u274C":me.severity==="critical"?"\u{1F6A8}":me.severity==="major"?"\u26A0\uFE0F":"\u2705",re=(me.outcome==="failure"?me.what_failed:me.what_worked)??"";a.push(` ${$e} \`${me.topic}\`${re?` \u2014 ${re.slice(0,80)}`:""}`)}}x.length>20&&a.push(` \u2026 and ${x.length-20} more. Call \`brain_changelog\` for the full list.`),a.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${l}", key="auto_changelog", value="false")\`_`)}}}}catch{}return a.join(`
|
|
45
|
-
`)}case"session_start_summary":{const{instance_id:
|
|
46
|
-
`);const e=i.length>o,
|
|
47
|
-
`)}case"session_end":{const{instance_id:
|
|
48
|
-
`).map(
|
|
28
|
+
`)}`}case"smart_recall":{const c=Date.now(),{instance_id:n,query:a,threshold:u=.78,author:o="",context_files:t=[],limit:S}=w,l=ro(a),i=Bo(S),A=Array.isArray(t)?t.filter(p=>typeof p=="string"):[];if(xe("smart_recall: Anfang"),!io(l))return'\u26A0\uFE0F smart_recall needs `query`: one line about the task or the error, e.g. query="login redirect loop after OAuth callback".';if(await rs(n,j)){const p=Date.now()-c;return M(n).then(y=>Ds(y,n,String(l??""),p)).catch(()=>{}),xe("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),cs(String(l??""),{startet:!0,...await It(n)})}const e=await M(n);xe("smart_recall: Verbindung steht");const{vektor:g,namen:I,zweit:x,eingang:d,seltenheit:m}=Dt(e);Fe()&&Promise.allSettled([g.aktualisiere(e),I.aktualisiere(e),d.aktualisiere(e),m.aktualisiere(e),x.aktualisiere(e)]),Ht(e,void 0,2);let s=new Set,_=!1;o&&(s=await xt(e,n,o).catch(()=>new Set)),_=await Ct(e,n,o).catch(()=>null)==="admin";const b=[ae(e,"cachly:ctx:*"),"cachly:lesson:best:*","cachly:idx:*"],R=await Nn(e,b);if(xe(`smart_recall: Wortbestand da (${R?.docs.length??0} Eintraege)`),!R)return Ds(e,n,String(l??""),Date.now()-c),xe("smart_recall: Brain leer \u2014 sofort geantwortet"),cs(String(l??""),{startet:!1,...await It(n)});const z=R.docs.reduce((p,y)=>p+(y.key.startsWith("cachly:lesson:best:")?1:0),0),P=pn(e,Et(l).filter(p=>p.length>=4).slice(0,4)).catch(()=>null),r=(async()=>{const p=await mn(n,()=>j(`/api/v1/instances/${n}`)),y=[];if(!(!p?.tier||p.tier.toLowerCase()==="free")&&p?.vector_token&&Fe()&&!At(e))try{const Z=await Be(l),O=`https://api.cachly.dev/v1/sem/${p.vector_token}`,q=await fetch(`${O}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:Z,namespace:ae(e,"cachly:ctx:").slice(0,-1),threshold:u,top_k:5}),signal:AbortSignal.timeout(8e3)});if(q.ok){const ge=(await q.json()).filter(me=>me.found&&me.id).map(me=>{const oe=me.id.replace("ctx:","").split(":");return{hit:me,redisKey:ae(e,`cachly:ctx:${oe[0]}:${oe.slice(1).join(":")}`)}}),ye=await Promise.all(ge.map(me=>e.get(me.redisKey).catch(()=>null)));ge.forEach((me,oe)=>{y.push({key:me.redisKey,similarity:me.hit.similarity??0,content:ye[oe]??"(evicted)"})})}}catch{}return{inst:p,semHits:y}})().catch(()=>({inst:null,semHits:[]})),re=await dt(e,b,l,25);xe(`smart_recall: Wortsuche fertig (${re.length} Treffer)`);const ee=In(re);let we=!1,h=null;const W=await(async()=>{if(!Fe())return kt(rn,"no embedding service configured, so search uses words only"),ee;try{if(await g.aktualisiere(e),xe(`smart_recall: Vektorbestand geladen (${g.groesse})`),g.groesse===0)return z>0&&(kt(an,"no lesson has an embedding yet, so search uses words only. A new brain fills them in the background; if this stays, run brain_doctor"),Ht(e,void 0,6)),ee;const p=await Be(l);if(xe("smart_recall: Frage eingebettet"),!p?.length)return kt(cn,"the question could not be embedded, so this search uses words only"),ee;await I.aktualisiere(e),await d.aktualisiere(e),await m.aktualisiere(e),await x.aktualisiere(e),xe(`smart_recall: Bestaende geladen (Namen ${I.groesse}, Eingaenge ${d.groesse}, Seltenheit ${m.groesse}, Zweit ${x.groesse})`);const y=g.groesse>0?x.groesse/g.groesse:0;y<gs&&g.groesse>0&&Ra(e,3);const B=y>=gs?Be(l,{modell:Qe}).catch(()=>null):null,Z=ee.filter(D=>D.key.startsWith("cachly:lesson:best:")).map(D=>D.key.slice(19)),O=D=>Math.max(g.naehe(p,D),I.naehe(p,D)),q=[...m.themen()],ce=(q.length>0?q:g.aehnlichste(p,500).map(D=>D.topic)).map(D=>({t:D,n:O(D)})).sort((D,ne)=>ne.n-D.n||(D.t<ne.t?-1:D.t>ne.t?1:0)).slice(0,$s).map(D=>D.t),ge=[...new Set([...Z,...ce])],ye=ce.slice(0,3).map(D=>g.rohvektor(D)).filter(Boolean),me=ye.length?to(p,ye):p,oe=ps(l),fe=m.statistik,ve=ge.map(D=>{const ne=new Set([...ps(m.textVon(D))].map(so));return{naeheText:g.naehe(p,D),naeheThema:I.naehe(p,D),naeheRueckkopplung:g.naehe(me,D),seltenheitsDeckung:fe?fe.deckung(oe,ne):0,besterZeuge:fe?fe.besterZeuge(oe,ne):0}});let N=eo(ve,no);{const D=[...N].sort((ne,be)=>be-ne);h=D.length>1?D[0]-D[1]:null}if(d.groesse>0){const D=ge.map(be=>{const Ne=d.besteNaehe(p,be);return Ne>=Mo?Ne:-2}),ne=ms(D);N=N.map((be,Ne)=>be+Ro*ne[Ne])}if(B){const D=await B;if(D?.length){const ne=ms(ge.map(be=>x.naehe(D,be)));N=N.map((be,Ne)=>be+$o*ne[Ne])}}let V=ge.map((D,ne)=>({t:D,p:N[ne]})).sort((D,ne)=>ne.p-D.p).map(D=>D.t);if(Ln(n)&&V.length>1){const D=V.slice(0,ws),ne=V.slice(ws),be=new Map(ge.map((Ae,et)=>[Ae,N[et]]));xe("smart_recall: Leser Anfang");const Ne=await Bn(l,D.map(Ae=>m.leserTextVon(Ae)),{instanceId:n});xe(`smart_recall: Leser ${Ne?"fertig":"ohne Ergebnis"}`),Ne&&(V=[...On(D.map(et=>be.get(et)??0),Ne).map(et=>D[et]),...ne])}const le=new Map(ee.map(D=>[D.key,D])),se=V.map(D=>`cachly:lesson:best:${D}`).filter(D=>!le.has(D)),G=new Map;if(se.length>0){const D=await e.mget(...se).catch(()=>[]);se.forEach((ne,be)=>G.set(ne,D[be]??null))}const U=[];for(const D of V){const ne=`cachly:lesson:best:${D}`,be=le.get(ne);if(be){U.push(be),le.delete(ne);continue}const Ne=G.get(ne)??null;Ne&&U.push({key:ne,content:Ne,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return U.push(...le.values()),wo&&go({frage:l.slice(0,200),themen:ge,ausWortsuche:Z.length,ausSinnsuche:ce.length,obergrenze:$s,gezeigt:V.slice(0,10)}),we=!0,U}catch(p){return await tt(e,ln,`search by meaning stopped (${p instanceof Error?p.message:String(p)}) - this search used words only`),ee}})();xe("smart_recall: Bedeutungspfad fertig"),jt(e),Ot(e,String(l??""),Date.now()-c);{const p=W.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));if(p.length>0){const y={ts:new Date().toISOString(),themen:p},B=ae(e,hs(n));Nt(e,B)&&(async()=>{await e.lpush(B,JSON.stringify(y)),await e.ltrim(B,0,Zn-1)})().catch(()=>{})}{const y={ts:new Date().toISOString(),frage:l.slice(0,200),geliefert:p};(async()=>{const B=ae(e,Bt(n));await e.lpush(B,JSON.stringify(y)),await e.ltrim(B,0,ds-1)})().catch(()=>{})}}if(Fe()&&!St()&&!qe(e)){const p=W.filter(y=>y.key.startsWith("cachly:lesson:best:")).slice(0,3).map(y=>y.key.slice(19));Gn(e,l,p,Be).catch(()=>{})}const te=W.filter(p=>p.key.startsWith("cachly:lesson:best:"));let X=0,Y=0;const Q=qe(e),ie=[];for(const p of te.slice(0,5)){const y=await e.get(p.key).catch(()=>null);if(y){const B=F(y,null);if(B?.state==="archived")continue;if(B){const Z=new Date().toISOString(),O={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:Z};Q?ie.push(p.key.slice(19)):St()||e.set(p.key,JSON.stringify(O)).catch(()=>{});const q=Zt(B)?Yt(B):0;if(q>0&&e.incrbyfloat(`cachly:stats:time_saved_mins:${n}`,q).catch(()=>{}),B.author&&o&&B.author!==o&&(X++,e.sadd(ae(e,`cachly:stats:reuse_pairs:${n}`),`${o}<-${B.author}`).catch(()=>{}),!Q)){const ce=`person:${Se(o)}`,ge=`person:${Se(B.author)}`;Ee(e,ce,"collaborates",ge,!0).catch(()=>{}),Ee(e,ge,"collaborates",ce,!0).catch(()=>{})}B.outcome==="success"&&Y++}}}Q&&ie.length>0&&!St()&&ns(j,n,ie),Y>0&&e.set(`cachly:stats:first_recall_at:${n}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),te.length>0&&(e.incr(`cachly:stats:recalls_total:${n}`).catch(()=>{}),X>0&&e.incr(`cachly:stats:cross_author_recalls:${n}`).catch(()=>{})),xe("smart_recall: Treffer gezaehlt");const{semHits:pe}=await r;xe("smart_recall: Tarif abgefragt");const $e=W.map(p=>p.score),f=$e.length?Math.min(...$e):0,T=$e.length&&Math.max(...$e)-f||1,v=p=>(p-f)/T,L=new Map,C=we?Fn(W.map(p=>v(p.score))):null,$=new Map;for(const[p,y]of W.entries()){const B=v(y.score),Z=C?C[p]:B;C&&L.set(y.key,p),$.set(y.key,{key:y.key,content:y.content,bm25Score:B,hausWert:Z,hybridScore:Z*(pe.length>0?.7:1),matchedWords:y.matchedWords,matchType:"keyword",subQuery:y.subQuery,wortBelege:y.wortBelege})}for(const p of pe){const y=$.get(p.key);y?(y.semScore=p.similarity,y.hybridScore=(y.hausWert??0)*.6+p.similarity*.4,y.matchType="hybrid"):$.set(p.key,{key:p.key,content:p.content,semScore:p.similarity,hybridScore:p.similarity*.5,matchType:"semantic"})}try{const p=await P,y=new Set;for(const{kante:B,inhalt:Z}of p??[]){if(B.edgeType!=="fixes"||B.confidence<.35||y.has(B.from))continue;y.add(B.from);const O=`cachly:lesson:best:${B.from}`,q=$.get(O);if(q)q.ckgScore=Math.max(q.ckgScore??0,B.confidence),q.hybridScore=q.hybridScore*.88+B.confidence*.12,q.matchType==="keyword"&&(q.matchType="hybrid");else{if(!Z)continue;$.set(O,{key:O,content:Z,ckgScore:B.confidence,hybridScore:B.confidence*.3,matchType:"ckg"})}}}catch{}if(xe("smart_recall: Sinn-Dienst und CKG fertig"),A.length>0){const p=new Set(A.map(y=>y.replace(/\\/g,"/")));for(const y of $.values()){if(!y.key.startsWith("cachly:lesson:best:"))continue;const B=F(y.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(O=>typeof O=="string").map(O=>O.replace(/\\/g,"/")):[]).some(O=>p.has(O))&&(y.hybridScore*=1.15,y.contextBoost=!0)}}for(const p of $.values()){if(p.matchType!=="semantic"&&p.matchType!=="ckg")continue;const y=Rn({key:p.key,content:p.content});y&&(p.hybridScore*=Mn(y))}const K=[...$.values()].filter(p=>{if(!p.key.startsWith("cachly:lesson:best:"))return!0;const y=je(p.content);return!(!yt(y)||!st(y?.group,s,_))}),E=C?Wn(K,L):K.sort((p,y)=>y.hybridScore-p.hybridScore),H=[];for(const p of E){if(!p.key.startsWith("cachly:lesson:best:"))continue;const y=F(p.content,{});y.gilt_bis&&Date.parse(String(y.gilt_bis))<Date.now()&&H.push(`\u23F3 \`${p.key.replace("cachly:lesson:best:","")}\` was valid until ${String(y.gilt_bis).slice(0,10)} \u2014 history, not a current fact.`);const B=F(p.content,{});if(B.pruefung_gefallen_am){const Z=p.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_gefallen_am).slice(0,10),q=String(B.pruefung_befund??"").trim().slice(0,200);H.push(`\u274C \`${Z}\` \u2014 Pruefung am ${O} FEHLGESCHLAGEN`+(q?`: ${q}`:""))}else if(B.pruefung_umgebung_am){const Z=p.key.replace("cachly:lesson:best:",""),O=String(B.pruefung_umgebung_am).slice(0,10),q=String(B.pruefung_umgebung_befund??"").trim().slice(0,120);H.push(`\u2139\uFE0F \`${Z}\` \u2014 Pruefung am ${O} an der Umgebung gescheitert, sagt nichts ueber die Lektion`+(q?`: ${q}`:""))}}{const p=new Set(E.map(y=>y.key));for(let y=E.length-1;y>=0;y--){const B=E[y];if(!B.key.startsWith("cachly:lesson:best:"))continue;const Z=F(B.content,{});if(!Z.ersetzt_durch)continue;const O=String(Z.ersetzt_grund??"").trim(),q=B.key.replace("cachly:lesson:best:","");if(p.has(`cachly:lesson:best:${Z.ersetzt_durch}`))E.splice(y,1),H.push(`\u21B7 \`${q}\` hidden \u2014 replaced by \`${Z.ersetzt_durch}\`${Z.ersetzt_am?` on ${Z.ersetzt_am.slice(0,10)}`:""}${O?` \u2014 reason: ${O}`:" \u2014 no reason recorded"}`);else if(await e.get(`cachly:lesson:best:${Z.ersetzt_durch}`)){const ce=je(await e.get(`cachly:lesson:best:${Z.ersetzt_durch}`));!yt(ce)||!st(ce.group,s,_)?H.push(`\u21B7 \`${q}\`: replaced by a version that is not visible to the team \u2014 this version stays the best visible answer.`):H.push(`\u26A0\uFE0F \`${q}\` is replaced by \`${Z.ersetzt_durch}\` (not in this list) \u2014 the current answer: \`recall_best_solution(topic="${Z.ersetzt_durch}")\``)}else H.push(`\u21A9\uFE0F \`${q}\` was replaced by \`${Z.ersetzt_durch}\` \u2014 the successor was deleted, so this version applies again (confirm it when you can).`)}}const he=gt()?new Map:Vn(E,A),ke=[];{await g.aktualisiere(e).catch(()=>{});const p=E.slice(0,8).filter(y=>y.key.startsWith("cachly:lesson:best:"));for(let y=0;y<p.length;y++)for(let B=y+1;B<p.length;B++){const Z=p[y].key.replace("cachly:lesson:best:",""),O=p[B].key.replace("cachly:lesson:best:",""),q=g.rohvektor(Z),ce=g.rohvektor(O);if(!q||!ce)continue;let ge=0,ye=0,me=0;for(let ve=0;ve<q.length;ve++)ge+=q[ve]*ce[ve],ye+=q[ve]*q[ve],me+=ce[ve]*ce[ve];if((ye>0&&me>0?ge/(Math.sqrt(ye)*Math.sqrt(me)):0)<ko)continue;const fe=ve=>{const N=F(ve??"",{});return String(N.verified_at??N.ts??"").slice(0,10)||"no date"};ke.push(`\u26A0\uFE0F \`${Z}\` (${fe(p[y].content)}) und \`${O}\` (${fe(p[B].content)}) say almost the same \u2014 check which version fits your case; the newer one is not automatically right.`)}ke.length>3&&(ke.length=3)}if(H.push(...ke),E.length>=2){const p=E[0].hybridScore,y=E[Math.min(4,E.length-1)].hybridScore,B=Math.max(0,p-y);(async()=>{try{await e.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:E.length})),await e.ltrim("cachly:recall:spread",0,199)}catch{}})()}const ue=hn();let _e="",Te=null;if(ue!==null){_e=un();const p=E[0]?.hybridScore??0,y=dn(E.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),_e,ue,p);y.weggelassenesThema!==void 0?E.splice(0,1):y.markierungGesetzt&&E[0]&&y.treffer[0]&&(E[0]={...E[0],content:y.treffer[0].content}),Te={frage:l,hoechstePunktzahl:p,themen:[],zulassungsfaehig:y.zulassungsfaehig,zulassungsGrund:y.zulassungsGrund,zuteilung:y.zuteilung,weggelassenesThema:y.weggelassenesThema,markierungGesetzt:y.markierungGesetzt}}xe("smart_recall: Notizen und Duplikate fertig");const Ce=await js(n,j);xe("smart_recall: Abruf-Grenze abgefragt");const de=Ce.reached,Ie=ks({ueberLimit:de,gesamt:E.length,volleTiefe:i??Oo}),Me=process.env.CACHLY_RECALL_COMPACT==="1",rt=(()=>{const p=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(p)?Math.min(20,Math.max(1,p)):5})(),ze=Me?Math.min(rt,Ie.sichtbar):Ie.sichtbar,J=[`\u{1F9E0} **Smart Recall** for: _"${l}"_
|
|
29
|
+
`];Ce.goodwillMessage&&J.push(`${Ce.goodwillMessage}
|
|
30
|
+
`),X>0&&J.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${X} of these lesson${X!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
|
|
31
|
+
`);const Pe=E.filter(p=>p.contextBoost).length;Pe>0&&J.push(`> \u{1F4C1} **Personalized** \u2014 ${Pe} lesson${Pe!==1?"s":""} boosted because ${Pe!==1?"they match":"it matches"} your current file context (${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})
|
|
32
|
+
`);const Re=xn(l);Re.length>1&&J.push(`_Detected ${Re.length} sub-topics:_ ${Re.map((p,y)=>`${y+1}. "${p}"`).join(", ")}
|
|
33
|
+
`);const Oe=on(E.map(p=>({wortBelege:p.wortBelege,semScore:p.semScore,ckgScore:p.ckgScore})));if(Oe.schweigen)return Wt(e,n,"schweigen"),J.push(sn(Oe)),J.push(...await Ls(e,l)),J.join(`
|
|
34
|
+
`);const Ve=oo(h);if(Ve&&J.push(Ve,""),Wt(e,n,Ve?"knapp":"beantwortet"),E.length>0){const p=E.some(O=>O.ckgScore!==void 0),y=we||pe.length>0,B=y&&p?"keyword + semantic + CKG hybrid":y?"keyword + semantic hybrid":p?"keyword + CKG hybrid":"keyword",Z=Math.min(ze,E.length);if(J.push(`### \u{1F50D} Results (${Z<E.length&&Re.length<=1?`showing ${Z} of ${E.length}`:E.length} \u2014 ${B})
|
|
35
|
+
`),Oe.belegte<E.length){const O=[];for(const ce of E){if(!ce.key.startsWith("cachly:lesson:best:")||!Xt({wortBelege:ce.wortBelege,semScore:ce.semScore,ckgScore:ce.ckgScore}))continue;const ge=F(ce.content,{}),ye=Date.parse(ge.verified_at??ge.ts??"");Number.isFinite(ye)&&O.push(Math.floor((Date.now()-ye)/864e5))}const q=nn(O);J.push(`> \u{1F4CA} ${Oe.belegte} of ${E.length} backed by evidence (at least one matching word, close meaning or a graph link). The rest are only the nearest entries, not evidence.`+(q?` \u23F3 ${q}`:"")+`
|
|
36
|
+
`)}if(H.push(...Jn(E.slice(0,ze),he)),H.length>0&&J.push(...H.map(O=>`> ${O}`),""),Re.length>1){const O=new Map,q=ks({ueberLimit:de,gesamt:E.length,volleTiefe:i??Do});for(const ye of E.slice(0,q.sichtbar)){const me=ye.subQuery??l;O.has(me)||O.set(me,[]),O.get(me).push(ye)}for(const[ye,me]of O){J.push(`**Topic: "${ye}"** (${me.length} results)
|
|
37
|
+
`);for(const oe of me.slice(0,Me?2:i??4)){const fe=os(e,oe.key).replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} "),ve=oe.matchType==="ckg"?`CKG: ${(oe.ckgScore??0).toFixed(2)}, \u{1F578}\uFE0F causal graph`:oe.ckgScore!==void 0&&oe.bm25Score!==void 0?`BM25: ${oe.bm25Score.toFixed(2)}, CKG: ${oe.ckgScore.toFixed(2)}, \u{1F500} hybrid`:oe.matchType==="hybrid"?`BM25: ${(oe.bm25Score??0).toFixed(2)}, sem: ${((oe.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:oe.matchType==="semantic"?`sem: ${((oe.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(oe.bm25Score??0).toFixed(2)}, matched: ${oe.matchedWords?.join(", ")}`,N=Me?vt(oe.key,oe.content,300):vt(oe.key,oe.content,Qt,300);if(J.push(Me?` **${fe}**`:` **${fe}** _(${ve})_`),oe.key.startsWith("cachly:lesson:best:")){const V=await e.get(oe.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await e.get(oe.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),le=V?F(V,{}):{};le.title&&J.push(` \u{1F4D6} **${le.title}** \u2014 ${le.summary??""}`)}{const V=oe.key.startsWith("cachly:lesson:best:")?xs(oe.content):"";V&&J.push(` ${V}`)}for(const V of N)J.push(` > ${V}`);J.push("")}}const ce=[...O.keys()],ge=Re.filter(ye=>!ce.includes(ye));ge.length>0&&J.push(`
|
|
38
|
+
\u26A0\uFE0F **No results for:** ${ge.map(ye=>`"${ye}"`).join(", ")}`)}else for(const O of E.slice(0,ze)){const q=os(e,O.key).replace("cachly:ctx:","\u{1F4DD} ").replace("cachly:lesson:best:","\u{1F4A1} ").replace("cachly:idx:","\u{1F4C2} ");let ce="";if(O.key.startsWith("cachly:lesson:best:")){const fe=F(O.content,{});fe.author&&(ce=` \xB7 \u{1F464} ${fe.author}`)}const ge=O.contextBoost?" \xB7 \u{1F4C1} context match":"",ye=O.matchType==="hybrid"?`BM25: ${(O.bm25Score??0).toFixed(2)}, sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F500} hybrid`:O.matchType==="semantic"?`sem: ${((O.semScore??0)*100).toFixed(0)}%, \u{1F3AF} semantic`:`BM25: ${(O.bm25Score??0).toFixed(2)}, matched: ${O.matchedWords?.join(", ")}`,me=vt(O.key,O.content,Me?es:Qt,es),oe=Oe.belegte>0&&Oe.belegte<E.length&&!Xt({wortBelege:O.wortBelege,semScore:O.semScore,ckgScore:O.ckgScore})?" \xB7 \u26A0\uFE0F no evidence":"";J.push(Me?`**${q}**${oe}`:`**${q}**${ce}${ge} _(${ye})_${oe}`);{const fe=F(O.content??"",{});fe.entscheidung?.gegen&&J.push(fs({gegen:fe.entscheidung.gegen,grund:fe.entscheidung.grund??null}))}if(O.key.startsWith("cachly:lesson:best:")){const fe=await e.get(O.key.replace("lesson:best:","lesson:human:")).catch(()=>null)??await e.get(O.key.replace("cachly:lesson:best:","lesson:human:")).catch(()=>null),ve=fe?F(fe,{}):{};ve.title&&J.push(`\u{1F4D6} **${ve.title}** \u2014 ${ve.summary??""}`)}{const fe=O.key.startsWith("cachly:lesson:best:")?xs(O.content):"";fe&&J.push(fe)}for(const fe of me)J.push(`> ${fe}`);J.push("")}if(de&&Ie.zurueckgehalten>0){const O=Ie.zurueckgehalten;J.push(`\u{1F512} **Free recall limit reached** (${Ce.used}/${Ce.limit} this month). Showing your top match; ${O} further relevant lesson${O!==1?"s are":" is"} withheld. Your limit resets next month, or unlock your full Brain now \u2192 ${Sa}
|
|
39
|
+
`)}}else{J.push(`\u26A0\uFE0F No matches found for: "${l}"`),H.length>0&&J.push("",...H.map(B=>`> ${B}`));const p=Et(l),y=[];if(is.size>0&&p.length>0)for(const B of p.slice(0,3)){if(B.length<4)continue;let Z=3,O="";for(const q of is){if(q.length<3||Math.abs(q.length-B.length)>4)continue;const ce=Tn(B,q);ce>0&&ce<Z&&(Z=ce,O=q)}O&&y.push(`"${O}" (instead of "${B}")`)}y.length>0?J.push(`\u{1F4A1} **Did you mean:** ${y.join(", ")}?`):(J.push(`
|
|
40
|
+
\u{1F4A1} Tips:`),J.push(" \u2022 Try different keywords"),J.push(" \u2022 Use `list_remembered` to see available context"),J.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!Me&&E.length>0){J.push(""),J.push('\u21A9\uFE0E Did one of these help? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` (not in your tool list? use `cachly_tool(tool="recall_feedback", arguments={\u2026})`) \u2014 and if the right lesson was **not** in the list: the same call with `rank=0`. That is the only number that improves the ranking.');const p=E.filter(B=>B.key.startsWith("cachly:lesson:best:")).map(B=>B.key.slice(19)),y=ae(e,`cachly:letzter-recall:${n}`);if(p.length>0&&Nt(e,y))try{await e.setex(y,7200,JSON.stringify({frage:l,themen:p}))}catch{}}if(J.push(...await Ls(e,l)),Me&&E.length>0){const p=Us();p&&(J.push(""),J.push(p))}if(ue!==null&&Te){const p=E.slice(0,ze).filter(y=>y.key.startsWith("cachly:lesson:best:")).map(y=>y.key.slice(19));return fn(e,_e,{...Te,themen:p},J.join(`
|
|
41
|
+
`))}return J.join(`
|
|
42
|
+
`)}case"session_start":{const{instance_id:c,focus:n="",author:a="",provider:u="",workspace_path:o=""}=w;if(await rs(c,j))return M(c).then(async f=>{await zs(f),await Ps(f,n,u),await f.set("cachly:mcp:version:last_seen",it,"EX",365*86400)}).catch(()=>{}),xe("session_start: neues Brain startet noch \u2014 sofort geantwortet"),En({instanzId:c,provider:u,...await It(c)});const t=await M(c),S=[],l=t.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((f,T)=>{l.on("data",v=>S.push(...v)),l.on("end",f),l.on("error",T)});const i=[];let A=0;const e=await ut(t,c,a),g=new Set;if(S.length>0){const f=await t.mget(...S);for(const T of f){const v=F(T??null,null);if(v&&We(v,e)){if(g.add(v.topic),Ss(v)){A++;continue}Ns(v.topic)||i.push(v)}}}i.sort((f,T)=>new Date(T.ts).getTime()-new Date(f.ts).getTime());let I=0;const x=t.scanStream({match:ae(t,"cachly:ctx:*"),count:1e3});await new Promise((f,T)=>{x.on("data",v=>{I+=v.filter(L=>!L.endsWith(":meta")).length}),x.on("end",f),x.on("error",T)});const d=await t.get(ae(t,"cachly:session:last")),m=F(d,null),s=n.toLowerCase().split(/\s+/).filter(Boolean),_=s.length>0?i.filter(f=>s.some(T=>f.topic.toLowerCase().includes(T)||(f.tags??[]).some(v=>v.toLowerCase().includes(T)))):[],{tage:b,rekord:R}=await zs(t);let z="";b>=7?z=`\u{1F525} **${b}-day streak!** ${b===R?" New record!":`Best: ${R}d`}`:b>1&&(z=`\u{1F525} ${b}-day streak`),await Ps(t,n,u);const r=[`\u{1F9E0} **Session Briefing**${u?` \xB7 ${u}`:""}`,""];z&&r.push(z,""),r.push(...await Bs(t));const re=await js(c,j),ee=Lo({used:re.used,limit:re.limit});if(ee&&r.push(ee,""),re.notice&&!Ms.has(c)&&(Ms.add(c),r.push(re.notice,"")),m?.ts){const f=new Date(m.ts).getTime(),T=Math.floor((Date.now()-f)/864e5);if(T>=7&&!Number.isNaN(f)){const v=i.filter(L=>{const C=new Date(L.ts).getTime();return!Number.isNaN(C)&&C>f});if(r.push(`\u{1F44B} **Welcome back** \u2014 it's been ${T} days since your last session.`),v.length>0){const L=v.slice(0,3).map(C=>`\`${C.topic}\``).join(", ");r.push(` \u{1F331} Your Brain grew by **${v.length} lesson${v.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${L}${v.length>3?", \u2026":""}`)}else r.push(` \u{1F9E0} ${i.length} lesson${i.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);r.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await t.get("cachly:mcp:version:last_seen")!==it){await t.set("cachly:mcp:version:last_seen",it,"EX",365*86400);const T=va[it];if(T){r.push(...T,"");const v=ka();v&&r.push(`\u{1F4CA} ${v} MCP tools`,"")}}}catch{}const we=!m&&i.length===0&&A===0&&I===0;we&&(r.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),o?(r.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),r.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(r.push("It learns from your work automatically. After your first session it will look like this:",""),r.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),r.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),r.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),r.push(""),r.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),r.push("")),r.push("**Your brain grows automatically:**"),r.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),r.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),r.push(""),r.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),r.push(" `smart_recall` returns a hit instead of nothing:"),r.push(` \`brain_seed_starter(instance_id="${c}")\``),r.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),r.push(""),r.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),r.push(""));const h=_.slice(0,4),W=new Set(h.map(f=>f.topic));if(a&&!we)try{const f=qe(t)?ae(t,`cachly:session:first_briefing:${a}`):`cachly:team:first_briefing:${a}`;if(!await t.get(f)){const v=i.filter(L=>L.author&&L.author!==a&&!W.has(L.topic));if(v.length>0){await t.set(f,"1","EX",365*86400);const L=new Map;for(const C of v){const $=C.author;L.has($)||L.set($,[]),L.get($).push(C)}r.push(""),r.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"),r.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),r.push(""),r.push("Your teammates have already solved problems you're about to hit:"),r.push("");for(const[C,$]of L){r.push(` \u{1F464} **${C}** fixed ${$.length} thing${$.length>1?"s":""}:`);for(const K of $.slice(0,2)){const E=K.outcome==="success"?"\u2705":"\u26A0\uFE0F";r.push(` ${E} \`${K.topic}\` \u2014 ${K.what_worked.slice(0,90)}`),W.add(K.topic)}$.length>2&&r.push(` \u2026 and ${$.length-2} more lessons`)}r.push(""),r.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),r.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"),r.push("")}}}catch{}const te=await t.get(ae(t,"cachly:session:handoff"));if(te)try{const f=JSON.parse(te),T=Math.round((Date.now()-new Date(f.ts).getTime())/6e4),v=T<60?`${T}m ago`:T<1440?`${Math.round(T/60)}h ago`:`${Math.round(T/1440)}d ago`;if(r.push(`\u{1F91D} **Handoff from previous window** (${v}):`),f.context_summary&&r.push(` ${f.context_summary}`),f.remaining_tasks.length>0){r.push(" \u23F3 **Remaining tasks:**");for(const C of f.remaining_tasks)r.push(` - ${C}`)}f.completed_tasks.length>0&&r.push(` \u2705 **Already done:** ${f.completed_tasks.join(", ")}`);const L=(f.files_changed??[]).filter(C=>C.status==="broken"||C.status==="partial");L.length>0&&r.push(` \u26A0\uFE0F **Needs fix:** ${L.map(C=>`\`${C.path}\` (${C.status}${C.description?": "+C.description:""})`).join(", ")}`),f.blocked_on&&r.push(` \u{1F6AB} **Blocked on:** ${f.blocked_on}`),f.instructions&&r.push(` \u{1F4DD} **Instructions:** ${f.instructions}`),r.push("")}catch{}const X=await t.get(ae(t,"cachly:session:checkpoint"));if(X)try{const f=JSON.parse(X),T=new Date(f.ts).getTime(),v=m?new Date(m.ts).getTime():0;if(T>v){const L=Math.round((Date.now()-T)/6e4),C=L<60?`${L}m ago`:L<1440?`${Math.round(L/60)}h ago`:`${Math.round(L/1440)}d ago`,$=f.provider?` [${f.provider}]`:"";r.push(`\u{1F4CC} **Last checkpoint**${$} (${C}): ${f.task}`),f.files_touched.length>0&&r.push(` Files: ${f.files_touched.slice(0,5).map(K=>`\`${K}\``).join(", ")}`),f.next_step&&r.push(` \u{1F4CD} Next step was: ${f.next_step}`),(!m||T-v>3e5)&&r.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),r.push("")}}catch{}const Y=m?null:pt(o);if(Y)try{const f=Je(Y,["log","--oneline","--format=%h %s","-15"]).trim();let T;try{T=Je(Y,["diff","--stat","HEAD~3"]).trim()}catch{T=Je(Y,["diff","--stat"]).trim()}if(f){r.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const v of f.split(`
|
|
43
|
+
`).slice(0,8))r.push(` ${v}`);if(T){const v=T.split(`
|
|
44
|
+
`).filter(L=>L.includes("|")||L.includes("changed"));if(v.length>0){r.push(" **Recent changes:**");for(const L of v.slice(0,5))r.push(` ${L.trim()}`)}}r.push("")}}catch{}if(m){const f=Math.round((Date.now()-new Date(m.ts).getTime())/6e4),T=f<60?`${f}m ago`:f<1440?`${Math.round(f/60)}h ago`:`${Math.round(f/1440)}d ago`;r.push(`\u{1F4C5} **Last session** (${T}): ${m.summary}`),m.duration_min&&r.push(` Duration: ${m.duration_min} min`),(m.files_changed??[]).length>0&&r.push(` Files: ${(m.files_changed??[]).slice(0,5).map(v=>`\`${v}\``).join(", ")}`),r.push("")}r.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${I} context entries`,""),A>0&&r.push(`\u26A0 ${A} lesson(s) were flagged as suspicious when saved and are not in this briefing. You can still fetch them explicitly with recall_best_solution (with a warning line); check them or save them again.`,"");{const T=await t.lrange(ae(t,`cachly:wirkung:${c}`),0,-1).catch(()=>[]),v=po(T.map($=>F($,null)).filter(Boolean)),L=$=>v.get($)??{geholfen:0,geoeffnet:0},C=i.filter($=>!en($)).filter($=>{if($.outcome!=="success")return!1;const K=L($.topic);return K.geholfen>=1||K.geoeffnet>=2}).filter($=>!W.has($.topic)).sort(($,K)=>{const E=L($.topic),H=L(K.topic);return H.geholfen-E.geholfen||H.geoeffnet-E.geoeffnet||(K.recall_count??0)-($.recall_count??0)}).slice(0,5);if(C.length>0){r.push("\u{1F4CC} **Confirmed lessons** (reported helpful, or opened after a search \u2014 being shown does not count):");for(const $ of C){W.add($.topic);const K=$.severity==="critical"?"\u{1F534}":$.severity==="major"?"\u{1F7E1}":"",E=L($.topic),H=[E.geholfen>0?`reported helpful ${E.geholfen}\xD7`:"",E.geoeffnet>0?`opened ${E.geoeffnet}\xD7 after a search`:""].filter(Boolean).join(" \xB7 "),he=ct($);r.push(` \u2705${K} \`${$.topic}\` _(${H})_ \u2014 ${he[0]??""}`,...he.slice(1))}r.push("")}}try{const f=[],T=t.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((v,L)=>{T.on("data",C=>f.push(...C)),T.on("end",v),T.on("error",L)}),f.length>0){r.push(`\u26A1 **Active belief conflicts (${f.length}):**`);for(const v of f.slice(0,3)){const L=await t.get(v);if(!L)continue;const C=F(L,null);C&&(!g.has(C.topic)&&await t.exists(`cachly:lesson:best:${C.topic}`)||r.push(` \u26A0\uFE0F \`${C.topic}\` \u2014 previously confirmed fix (${(C.fix_confidence*100).toFixed(0)}%, n=${C.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${Se(C.topic)}")\``))}r.push("")}}catch{}if(h.length>0){r.push(`\u{1F3AF} **Relevant for "${n}":**`);for(const f of h){const T=f.outcome==="success"?"\u2705":f.outcome==="partial"?"\u26A0\uFE0F":"\u274C",v=f.severity==="critical"?"\u{1F534}":f.severity==="major"?"\u{1F7E1}":"",L=ct(f);r.push(` ${T}${v} \`${f.topic}\` \u2014 ${L[0]??""}`,...L.slice(1))}r.push("")}if(i.length>0){const f=(_.length>0?i.filter(T=>!_.includes(T)):i).filter(T=>!W.has(T.topic)).slice(0,_.length>0?3:4);if(f.length>0){r.push("\u{1F550} **Recent lessons:**");for(const T of f){W.add(T.topic);const v=T.outcome==="success"?"\u2705":T.outcome==="partial"?"\u26A0\uFE0F":"\u274C",L=T.severity==="critical"?"\u{1F534}":T.severity==="major"?"\u{1F7E1}":"",C=ct(T);r.push(` ${v}${L} \`${T.topic}\` \u2014 ${C[0]??""}`,...C.slice(1))}r.push("")}}else r.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some(T=>T.author)||(r.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),r.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Q=await So(t,i);if(Q.length>0){r.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const f of Q.slice(0,3))r.push(` \`${f.neu}\` \u2248 \`${f.alt}\` (${f.naehe.toFixed(2)})`);r.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),r.push("")}const ie=m;if(ie?.decision_log?.length){const f=ie.decision_log,T=f.filter((C,$)=>!W.has(C.topic)&&f.findIndex(K=>K.topic===C.topic)===$),v=T.filter(C=>C.outcome==="success"),L=T.filter(C=>C.outcome==="failure");if(v.length>0||L.length>0){r.push(`\u{1F3AC} **Last session decisions** (${f.length} lessons stored):`),v.length>0&&r.push(` \u2705 Worked: ${v.slice(0,3).map(C=>`\`${C.topic}\``).join(", ")}`),L.length>0&&r.push(` \u274C Failed: ${L.slice(0,3).map(C=>`\`${C.topic}\``).join(", ")}`),r.push("");for(const C of[...v.slice(0,3),...L.slice(0,3)])W.add(C.topic)}}{const f=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"]),T=$=>{const K=new Set;for(const E of $)for(const H of E.toLowerCase().split(/[/\\._-]/))H.length>3&&!f.has(H)&&K.add(H);return[...K]};let v=s,L=n,C=!1;if(v.length===0&&m){const $=T(m.files_changed??[]),K=(m.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(E=>E.length>3&&!f.has(E));v=[...new Set([...$,...K])],L="where you left off last session",C=!0}if(v.length>0){const $=i.filter(K=>{if(K.outcome==="success")return!1;const E=K.topic.split(":")[0];return v.some(H=>K.topic.toLowerCase().includes(H)||E===H||(K.tags??[]).some(he=>he.toLowerCase()===H))});if($.length>=1){const E=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",C?` You're likely to continue **${L}** \u2014 ${$.length} known pitfall${$.length>1?"s":""} there:`:` Known pitfalls for **"${L}"** (${$.length} past failure${$.length>1?"s":""}):`,...$.slice(0,3).map(H=>` \u274C \`${H.topic}\` \u2014 ${(H.what_failed??H.what_worked).slice(0,80)}`),""];r.splice(2,0,...E)}}}if(a){const f=Date.now()-6048e5,T=i.filter(v=>v.author&&v.author!==a&&new Date(v.ts).getTime()>f&&!W.has(v.topic));if(T.length>0){const v=new Map;for(const L of T){const C=L.author;v.has(C)||v.set(C,[]),v.get(C).push(L)}r.push(`\u{1F465} **Team this week** (${T.length} lesson${T.length>1?"s":""} from teammates):`);for(const[L,C]of v){r.push(` \u{1F464} **${L}**:`);for(const $ of C.slice(0,3)){const K=$.outcome==="success"?"\u2705":$.outcome==="partial"?"\u26A0\uFE0F":"\u274C";r.push(` ${K} \`${$.topic}\` \u2014 ${$.what_worked.slice(0,80)}`),W.add($.topic)}C.length>3&&r.push(` \u2026 and ${C.length-3} more`)}r.push("")}}try{const f=await t.get("cachly:crystal:latest");if(f){const T=F(f,null);if(T&&Math.round((Date.now()-new Date(T.ts).getTime())/864e5)<=90){r.push(`\u{1F48E} **Memory Crystal** (${T.label} \xB7 ${T.session_count} sessions compressed):`);for(const L of T.top_patterns.slice(0,3))r.push(` \u2022 **${L.category}** (${L.count}\xD7): ${L.insight.slice(0,90)}`);r.push("")}}}catch{}try{const f=await t.hgetall(`cachly:roadmap:${c}`);if(f&&Object.keys(f).length>0){const T={critical:0,high:1,medium:2,low:3},v={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},L=new Set(["planned","in-progress","blocked"]),C=Object.values(f).flatMap(E=>{const H=F(E,null);return H?[H]:[]}),$=C.filter(E=>L.has(E.status)).sort((E,H)=>E.status==="in-progress"&&H.status!=="in-progress"?-1:H.status==="in-progress"&&E.status!=="in-progress"?1:(T[E.priority]??99)-(T[H.priority]??99)),K=C.filter(E=>E.status==="done").length;if($.length>0){r.push(At(t)?`\u{1F5FA}\uFE0F **Team roadmap** (${$.length} open \xB7 ${K} done \xB7 every member can edit):`:`\u{1F5FA}\uFE0F **Roadmap** (${$.length} open \xB7 ${K} done):`);for(const E of $.slice(0,5)){const H=E.status==="in-progress"?"\u26A1":E.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";r.push(` ${H} ${v[E.priority]??"\u26AA"} \`${E.id}\` **${E.title}**`)}$.length>5&&r.push(` \u2026 and ${$.length-5} more`),r.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),r.push("")}}}catch{}try{const f=await t.get("cachly:mcm:calibration:last"),T=F(f,null)?.ts??0;if((Date.now()-T)/864e5>=30&&i.length>=5){const L=i.filter($=>$.outcome==="success"&&($.recall_count??0)>0),C=i.filter($=>($.recall_count??0)>0);if(C.length>=3){const $=C.length>0?L.length/C.length:1,K=[],E=new Map;for(const H of C){const he=H.topic.split(":")[0]??"other";E.has(he)||E.set(he,{success:0,total:0});const ke=E.get(he);ke.total++,H.outcome==="success"&&ke.success++}for(const[H,he]of E)he.total>=2&&he.success/he.total<.6&&K.push(H);await t.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:$,recalled:C.length,low_precision_domains:K})),(K.length>0||$<.7)&&(r.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${C.length} recalled lessons):`),r.push(` Overall precision: **${($*100).toFixed(0)}%** recalled lessons actually worked`),K.length>0&&r.push(` \u26A0\uFE0F Low-precision domains: ${K.map(H=>`\`${H}\``).join(", ")} \u2014 consider revisiting these lessons`),r.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),r.push(""))}await t.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const pe=i.filter(f=>f.outcome==="failure"||f.outcome==="partial").length,$e=i.filter(f=>f.outcome==="success"&&Vt(f)<Js).length;if(i.length===0||pe>0||$e>0){const f=[];i.length===0&&f.push("brain is empty"),pe>0&&f.push(`${pe} open failure${pe>1?"s":""}`),$e>0&&f.push(`${$e} stale lesson${$e>1?"s":""}`),r.push(`\u{1FA7A} _Run \`brain_doctor\` for details: ${f.join(", ")}._`)}try{if(await t.get(`cachly:prefs:auto_changelog:${c}`).catch(()=>null)!=="false"&&m?.ts&&!we){const v=new Date(m.ts).getTime();if(!Number.isNaN(v)){const L=i.filter($=>{const K=new Date($.ts).getTime();return!Number.isNaN(K)&&K>v}),C=L.filter($=>!W.has($.topic));if(C.length>0){const $=Math.round((Date.now()-v)/6e4),K=$<60?`${$}m`:$<1440?`${Math.round($/60)}h`:`${Math.round($/1440)}d`,E=L.length-C.length;r.push(""),r.push(`\u{1F4CB} **${L.length} new lesson${L.length!==1?"s":""} since your last session** (${K} ago${E>0?`, ${E} already listed above`:""}):`);const H=new Map;for(const he of C.slice(0,20)){const ke=he.topic.includes(":")?he.topic.split(":")[0]:"general",ue=H.get(ke)??[];ue.push(he),H.set(ke,ue)}for(const[he,ke]of H){r.push(` **${he}**`);for(const ue of ke){const _e=ue.outcome==="failure"?"\u274C":ue.severity==="critical"?"\u{1F6A8}":ue.severity==="major"?"\u26A0\uFE0F":"\u2705",Te=(ue.outcome==="failure"?ue.what_failed:ue.what_worked)??"";r.push(` ${_e} \`${ue.topic}\`${Te?` \u2014 ${Te.slice(0,80)}`:""}`)}}C.length>20&&r.push(` \u2026 and ${C.length-20} more. Call \`brain_changelog\` for the full list.`),r.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${c}", key="auto_changelog", value="false")\`_`)}}}}catch{}return r.join(`
|
|
45
|
+
`)}case"session_start_summary":{const{instance_id:c,focus:n,top_n:a=10,author:u=""}=w;if(!n||!n.trim())throw new Error("focus is required for session_start_summary");const o=Math.min(Math.max(1,Math.floor(Number(a)||10)),25),t=await M(c),S=[],l=t.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((P,r)=>{l.on("data",re=>S.push(...re)),l.on("end",P),l.on("error",r)});const i=[],A=await ut(t,c,u);if(S.length>0){const P=await t.mget(...S);for(const r of P){const re=F(r??null,null);We(re,A)&&!Ss(re)&&!Ns(re.topic)&&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="${c}")\` to bootstrap with 16 universal lessons.`].join(`
|
|
46
|
+
`);const e=i.length>o,g=n.toLowerCase().split(/\s+/).filter(Boolean),I=Date.now(),x=i.map(P=>{const r=g.filter(ie=>P.topic.toLowerCase().includes(ie)).length,re=g.filter(ie=>(P.tags??[]).some(pe=>pe.toLowerCase().includes(ie))).length,ee=r*2+re,we=Math.max(0,P.recall_count??0),h=Math.min(1.5,Math.log1p(we)/10),W=P.severity==="critical"?1:P.severity==="major"?.5:0,te=(I-new Date(P.verified_at??P.ts).getTime())/864e5,X=te<30?.5*(1-te/30):0,Y=P.outcome==="success"?.5:P.outcome==="partial"?.2:0,Q=ee+h+W+X+Y;return{lesson:P,score:Q}});x.sort((P,r)=>r.score!==P.score?r.score-P.score:new Date(r.lesson.ts).getTime()-new Date(P.lesson.ts).getTime());const d=(e?x.slice(0,o):x).map(P=>P.lesson),m=i.length,s=d.length,R=[e?`\u{1F9E0} Brain Summary \u2014 top ${s} of ${m} 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 P of d){const r=P.severity==="critical"?"\u{1F534}":P.severity==="major"?"\u26A0\uFE0F":"\u2705",re=P.severity?`[${P.severity}] `:"[minor] ",ee=P.recall_count??0,we=ee>0?` (in ${ee} answer${ee===1?"":"s"})`:"",h=P.what_worked.slice(0,110),W=Qo(P.author,u);R.push(`${r} ${re}\`${P.topic}\` \u2014 ${h}${we}${W}`)}R.push("");const z=ea(d,u);return z>0&&R.push(`\u{1F465} ${z} of these ${z===1?"was":"were"} written by a teammate \u2014 the value only a shared brain delivers.`,""),e?R.push(`\u{1F4A1} Showing top ${s} of ${m} lessons \xB7 \`session_start\` for full briefing`):R.push(`\u{1F4A1} All ${s} lesson${s!==1?"s":""} shown \xB7 \`session_start\` for full briefing`),R.push(...await Bs(t)),R.join(`
|
|
47
|
+
`)}case"session_end":{const{instance_id:c,summary:n,files_changed:a=[],lessons_learned:u,workspace_path:o=""}=w,t=Ge({summary:n,files_changed:a}),S=t.felder.summary,l=t.felder.files_changed,i=await M(c),A=new Date;let e;const g=await Na(i),I=g.started,x=!I;if(I){const ee=A.getTime()-new Date(I).getTime();Number.isFinite(ee)&&(e=Math.round(ee/6e4))}const d=[];try{const ee=ae(i,"cachly:session:decision-log"),we=await i.lrange(ee,0,-1);for(const h of we){const W=F(h,null);W&&!qt(W.sid)||(await i.lrem(ee,1,h),W&&d.push({ts:W.ts,topic:W.topic,outcome:W.outcome,what_worked:W.what_worked}))}}catch{}const m=Ao(c);Eo(c);const s={ts:A.toISOString(),summary:S,files_changed:l,...m.recalls>0?{memory_cost:m}:{},...t.verdacht.length?{verdacht:t.verdacht}:{},...u!==void 0?{lessons_learned:u}:{},...e!==void 0?{duration_min:e}:{},...d.length>0?{decision_log:d}:{}};await i.set(ae(i,"cachly:session:last"),JSON.stringify(s)),await i.lpush(ae(i,"cachly:session:history"),JSON.stringify(s)),await i.ltrim(ae(i,"cachly:session:history"),0,49),await i.expire(ae(i,"cachly:session:history"),90*86400),await i.del(...g.loeschen);const _=[];try{const ee=/\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,we=S.split(/[.!\n]+/).map(h=>h.trim()).filter(h=>h.length>20&&ee.test(h));for(const h of we.slice(0,6)){const te=h.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(pe=>pe.length>3&&!["that","this","with","from","have","been","were","they","then","when","also","into","will","would","could","should"].includes(pe)).slice(0,4).join("-");if(!te)continue;const X=`auto:${te}`,Y=`cachly:lesson:best:${X}`,Q=await i.get(Y);if(Q)try{if(JSON.parse(Q).outcome==="success")continue}catch{}const ie={topic:X,outcome:"success",what_worked:h,context:`Auto-learned from session summary. Full summary: ${S.slice(0,300)}`,severity:"minor",ts:A.toISOString(),recall_count:0,auto_learned:!0,session_ts:A.toISOString(),version:2,...t.verdacht.length?{tags:[zt]}:{}};await i.set(Y,JSON.stringify(ie)),await i.expire(Y,90*86400),_.push(X)}}catch{}const b=[],R=pt(o);let z=0,P=0;if(R)try{const we=`--since=${(I??"")||"1 hour ago"}`,h=Je(R,["log",we,"--oneline","--format=%H|||%s|||%b|||%ai|||ENDE"]).trim();if(h){const W=/\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,te=h.split("|||ENDE").map(X=>X.trim()).filter(Boolean);for(const X of te.slice(0,10)){const[Y,Q,ie,pe]=X.split("|||"),$e=Ge({msg:Q??"",body:ie??""}),f=$e.felder.msg,T=$e.felder.body;if(Gs(Y))try{const H=Je(R,["diff-tree","--no-commit-id","--name-only","-r","--root",Y]).trim(),ke=H?H.split(`
|
|
48
|
+
`).map(_e=>_e.trim()).filter(Boolean).slice(0,12):[],ue=[];for(const _e of ke)ue.push(await Jt(i,_e));for(let _e=0;_e<ue.length;_e++)for(let Te=_e+1;Te<ue.length;Te++)await Ee(i,ue[_e],"co-occurs",ue[Te],!0),await Ee(i,ue[Te],"co-occurs",ue[_e],!0)}catch{}if(!f||!W.test(f))continue;const v=(T??"").trim();if(v.length<120)continue;const L=f.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(!L)continue;const C=`git:${L}`,$=`cachly:lesson:best:${C}`;if(await i.get($))continue;const E={topic:C,outcome:"success",what_worked:`${f}
|
|
49
49
|
|
|
50
|
-
${v.slice(0,1200)}`,context:`Auto-learned from git commit ${(
|
|
51
|
-
`)}case"session_ping":{const{instance_id:
|
|
52
|
-
\u{1F4CD} **Next step:** ${i}`:"";return[`\u{1F4CC} **Checkpoint saved**${I} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${
|
|
53
|
-
`)}case"session_handoff":{const{instance_id:
|
|
50
|
+
${v.slice(0,1200)}`,context:`Auto-learned from git commit ${(Y??"").slice(0,7)} at ${pe??""} in ${R}`,severity:"minor",ts:A.toISOString(),recall_count:0,auto_learned:!0,source:"ambient-git",version:3,...$e.verdacht.length?{tags:[zt]}:{}};await i.set($,JSON.stringify(E)),await i.expire($,60*86400),b.push(C),$e.geschwaerzt.length&&z++,$e.verdacht.length&&P++}}}catch{}const r=e!==void 0?` \xB7 ${e} min`:"",re=_.length+b.length;return[`\u2705 **Session saved**${r}`,x?"\u2139\uFE0F No session_start marker found for this session (session_start was not called, or the server restarted). Summary saved without duration.":"","",`\u{1F4CB} **Summary:** ${S}`,l.length>0?`\u{1F4C1} **Files changed:** ${l.map(ee=>`\`${ee}\``).join(", ")}`:"",u!==void 0?`\u{1F9E0} **Lessons stored:** ${u}`:"",...Io(m),_.length>0?`\u{1F916} **Auto-learned:** ${_.length} lessons extracted from summary (${_.slice(0,3).map(ee=>`\`${ee}\``).join(", ")}${_.length>3?"\u2026":""})`:"",b.length>0?`\u{1F33F} **Ambient git learning:** ${b.length} commit${b.length>1?"s":""} auto-learned (${b.slice(0,3).map(ee=>`\`${ee}\``).join(", ")}${b.length>3?"\u2026":""})`:"",...Ke(t,"notiz"),...Ts(z,P,`${b.length} git lessons`),re>0?`\u{1F4DA} **Learned this session:** ${re} lesson${re>1?"s":""}`:"","",'\u{1F4A1} Next session: `session_start(focus="...")` to see this summary.'].filter(ee=>ee!=="").join(`
|
|
51
|
+
`)}case"session_ping":{const{instance_id:c,task:n,files_touched:a=[],next_step:u="",provider:o=""}=w,t=Ge({task:n,files_touched:a,next_step:u,provider:o}),{task:S,files_touched:l,next_step:i,provider:A}=t.felder,e=await M(c),g={ts:new Date().toISOString(),task:S,files_touched:l,next_step:i,provider:A,...t.verdacht.length?{verdacht:t.verdacht}:{}};await e.set(ae(e,"cachly:session:checkpoint"),JSON.stringify(g),"EX",86400*3),await e.lpush(ae(e,"cachly:session:checkpoint:log"),JSON.stringify(g)),await e.ltrim(ae(e,"cachly:session:checkpoint:log"),0,19);const I=A?` [${A}]`:"",x=l.length>0?` \xB7 ${l.length} file${l.length>1?"s":""} touched`:"",d=i?`
|
|
52
|
+
\u{1F4CD} **Next step:** ${i}`:"";return[`\u{1F4CC} **Checkpoint saved**${I} \u2014 ${new Date().toLocaleTimeString()}`,`\u{1F528} **Working on:** ${S}${x}`,d,"","\u{1F4A1} If you switch providers, `session_start` will show this checkpoint automatically.",...Ke(t,"notiz")].filter(m=>m!=="").join(`
|
|
53
|
+
`)}case"session_handoff":{const{instance_id:c,completed_tasks:n=[],remaining_tasks:a=[],files_changed:u=[],instructions:o="",context_summary:t="",blocked_on:S=""}=w,l=Ge({completed_tasks:n,remaining_tasks:a,files_changed:u,instructions:o,context_summary:t,blocked_on:S}),{completed_tasks:i,remaining_tasks:A,files_changed:e,instructions:g,context_summary:I,blocked_on:x}=l.felder,d=await M(c),s={ts:new Date().toISOString(),completed_tasks:i,remaining_tasks:A,files_changed:e,instructions:g,context_summary:I,blocked_on:x,...l.verdacht.length?{verdacht:l.verdacht}:{}};await d.set(ae(d,"cachly:session:handoff"),JSON.stringify(s)),await d.lpush(ae(d,"cachly:session:handoff:history"),JSON.stringify(s)),await d.ltrim(ae(d,"cachly:session:handoff:history"),0,19);const _=i.length+A.length,b=_>0?Math.round(i.length/_*100):0,R=e.filter(z=>z.status==="broken"||z.status==="partial");return[`\u{1F91D} **Handoff saved** \u2014 ${i.length}/${_} tasks done (${b}%)`,"",i.length>0?`\u2705 **Completed:**
|
|
54
54
|
${i.map(z=>` - ${z}`).join(`
|
|
55
55
|
`)}`:"",A.length>0?`
|
|
56
56
|
\u23F3 **Remaining for next window:**
|
|
57
57
|
${A.map(z=>` - ${z}`).join(`
|
|
58
|
-
`)}`:"",
|
|
59
|
-
\u26A0\uFE0F **Needs attention:** ${
|
|
60
|
-
\u{1F6AB} **Blocked on:** ${
|
|
61
|
-
\u{1F4DD} **Instructions:** ${
|
|
62
|
-
`)}case"auto_learn_session":{const{instance_id:
|
|
63
|
-
`)}case"brain_who_knows":{const{instance_id:
|
|
64
|
-
`);const A=[...i.entries()].map(([
|
|
65
|
-
`)}case"brain_file_map":{const{instance_id:
|
|
66
|
-
`)}case"team_expertise_map":{const{instance_id:
|
|
67
|
-
`);const o=[];for(const
|
|
68
|
-
`)}case"skill_gaps":{const{instance_id:
|
|
69
|
-
`)}case"brain_coverage":{const{instance_id:
|
|
70
|
-
`).filter(Boolean).length,
|
|
71
|
-
`)}case"brain_metrics":{const{instance_id:
|
|
72
|
-
`),
|
|
73
|
-
`)}case"brain_service_map":{const{instance_id:
|
|
74
|
-
`);const
|
|
75
|
-
`)}case"brain_collab_pairs":{const{instance_id:
|
|
76
|
-
`);const
|
|
77
|
-
`)}case"brain_portability":{const{instance_id:
|
|
78
|
-
`)}case"brain_changelog":{const{instance_id:
|
|
79
|
-
`);const A=new Map;for(const
|
|
80
|
-
`)}case"brain_set_pref":{const{instance_id:
|
|
81
|
-
`)}case"brain_get_pref":{const{instance_id:
|
|
82
|
-
`)}default:return null}}async function
|
|
58
|
+
`)}`:"",R.length>0?`
|
|
59
|
+
\u26A0\uFE0F **Needs attention:** ${R.map(z=>`\`${z.path}\` (${z.status})`).join(", ")}`:"",x?`
|
|
60
|
+
\u{1F6AB} **Blocked on:** ${x}`:"",g?`
|
|
61
|
+
\u{1F4DD} **Instructions:** ${g}`:"","","\u{1F4A1} The next `session_start` will include this handoff automatically.",...Ke(l,"notiz")].filter(z=>z!=="").join(`
|
|
62
|
+
`)}case"auto_learn_session":{const{instance_id:c,observations:n}=w,a=await M(c),u=[],o=[];let t=0,S=0;for(const i of n){const A=Ge(i),e=A.felder,g=e.topic??e.action.toLowerCase().replace(/[^a-z0-9:\-_\s]/g,"").trim().split(/\s+/).slice(0,4).join("-"),I=g.includes(":")?g:`auto:${g}`,x=`cachly:lesson:best:${I}`,d=await a.get(x);if(d&&JSON.parse(d).outcome==="success"&&e.outcome!=="success"){o.push(I);continue}const m={topic:I,outcome:e.outcome,what_worked:e.outcome==="success"?e.action:e.details??e.action,what_failed:e.outcome==="failure"?e.action:void 0,context:e.details,severity:e.severity??"minor",ts:new Date().toISOString(),confidence:1,recall_count:0,auto_learned:!0,version:2,...A.verdacht.length?{tags:[zt]}:{}},s=JSON.stringify(m);A.geschwaerzt.length&&t++,A.verdacht.length&&S++,await a.set(x,s);const _=`cachly:lessons:${I}`;await a.rpush(_,s),await a.ltrim(_,-100,-1),await a.expire(_,90*86400);try{const b=I.split(":")[0]??"auto",R=Se(I);if(await Ue(a,R,b,b),e.outcome==="success"||e.outcome==="partial"){const z=e.details?wt(e.details):null;if(z){const P=Se(`problem:${z}`);await Ue(a,P,"problem","problem"),await Ee(a,R,"fixes",P,e.outcome==="success",e.outcome==="partial")}}}catch{}u.push(`${e.outcome==="success"?"\u2705":e.outcome==="partial"?"\u26A0\uFE0F":"\u274C"} \`${I}\``)}const l=[`\u{1F916} **Auto-learn complete**: ${u.length} stored, ${o.length} skipped`,""];return u.length>0&&l.push("**Stored:**",...u.map(i=>" "+i),""),o.length>0&&l.push(`**Skipped** (better lesson already exists): ${o.map(i=>`\`${i}\``).join(", ")}`),l.push(...Ts(t,S,`${u.length} observations`)),l.join(`
|
|
63
|
+
`)}case"brain_who_knows":{const{instance_id:c,topic:n,limit:a=10}=w;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 u=Math.max(1,Math.min(Number(a)||10,50)),o=await M(c),t=Se(n),S=Et(n).filter(d=>d.length>=3).slice(0,5),l=new Set([t]);for(const d of S.slice(0,3)){const m=o.scanStream({match:`cachly:ckg:node:*${d}*`,count:30});await new Promise((s,_)=>{m.on("data",b=>{for(const R of b.slice(0,10)){const z=R.replace("cachly:ckg:node:","");!z.startsWith("person:")&&!z.startsWith("file:")&&l.add(z)}}),m.on("end",s),m.on("error",_)})}const i=new Map;for(const d of[...l].slice(0,25)){const m=await o.smembers(`cachly:ckg:idx:to:${d}`);for(const s of m){const _=await o.get(s);if(!_)continue;const b=F(_,null);if(!b||b.edgeType!=="authored")continue;const R=await o.get(`cachly:ckg:node:${b.from}`);if(!R)continue;const z=F(R,null);if(!z||z.type!=="person")continue;const P=i.get(b.from);P?(P.lessonCount++,P.totalConfidence+=b.confidence,P.domains.add(z.domain),b.last_updated>P.lastActive&&(P.lastActive=b.last_updated)):i.set(b.from,{handle:z.handle,lessonCount:1,totalConfidence:b.confidence,domains:new Set([z.domain]),lastActive:z.last_active??b.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(`
|
|
64
|
+
`);const A=[...i.entries()].map(([d,m])=>({id:d,handle:m.handle,lessonCount:m.lessonCount,avgConfidence:m.totalConfidence/m.lessonCount,domains:[...m.domains].slice(0,3).join(", "),lastActive:m.lastActive})).sort((d,m)=>m.lessonCount*m.avgConfidence-d.lessonCount*d.avgConfidence).slice(0,u),e=[],g=A[0];if(g)try{const d=await o.smembers(`cachly:ckg:idx:from:${g.id}`),m=[];for(const s of d){const _=await o.get(s);if(!_)continue;const b=F(_,null);if(!b||b.edgeType!=="collaborates")continue;const R=await o.get(`cachly:ckg:node:${b.to}`),z=R?F(R,null):null;z?.handle&&m.push({handle:z.handle,trials:b.trials})}m.sort((s,_)=>_.trials-s.trials);for(const s of m.slice(0,3))e.push(s.handle)}catch{}const I=[`## \u{1F465} Who Knows About \`${n}\`?`,"",`**${A.length}** contributor${A.length!==1?"s":""} with relevant lessons:`,""],x=!!await Tt(c);for(const[d,m]of A.entries()){const s=d===0?"\u{1F947}":d===1?"\u{1F948}":d===2?"\u{1F949}":`${d+1}.`,_=(m.avgConfidence*100).toFixed(0),b=Math.floor((Date.now()-new Date(m.lastActive).getTime())/864e5),R=b<1?"today":b<7?`${b}d ago`:b<30?`${Math.floor(b/7)}w ago`:`${Math.floor(b/30)}mo ago`,z=x?null:await gn(o,c,m.handle).catch(()=>null),P=z?` ${wn[z]}`:"";I.push(`${s} **${m.handle}**${P} \u2014 ${m.lessonCount} lesson${m.lessonCount!==1?"s":""} \xB7 ${_}% confidence \xB7 last active ${R}`,` _domains: ${m.domains}_`,"")}return e.length>0&&g&&I.push(`\u{1F91D} **${g.handle}** frequently works with: ${e.map(d=>`**${d}**`).join(", ")}`," _(ask them together \u2014 they've solved structurally similar things on shared files)_",""),I.push("---",'_Attribution grows with every `learn_from_attempts(author="...", ...)` call._'),I.join(`
|
|
65
|
+
`)}case"brain_file_map":{const{instance_id:c,file_paths:n=[]}=w,a=(Array.isArray(n)?n:[]).filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim());if(!a.length)return'\u26A0\uFE0F Pass at least one file path. Example: `brain_file_map(file_paths=["src/auth/jwt.ts"])`.';const u=await M(c),o=["## \u{1F4C1} File Knowledge Map","","_What cachly knows about the files you're about to touch:_",""];for(const t of a.slice(0,10)){o.push(`### \`${t}\``);const S=`file:${Se(t)}`,l=await u.smembers(`cachly:ckg:idx:to:${S}`),i=[];for(const I of l){const x=await u.get(I);if(!x)continue;const d=F(x,null);if(!d||d.edgeType!=="touched")continue;const m=await u.get(`cachly:ckg:node:${d.from}`);if(!m)continue;const s=F(m,null);!s||s.type!=="person"||i.push({handle:s.handle,touches:d.trials,lastSeen:d.last_updated})}if(i.sort((I,x)=>x.touches-I.touches),i.length>0){const I=i.slice(0,5).map((x,d)=>{const m=d===0?"\u{1F947}":d===1?"\u{1F948}":d===2?"\u{1F949}":`${d+1}.`,s=Math.floor((Date.now()-new Date(x.lastSeen).getTime())/864e5),_=s<1?"today":s<7?`${s}d ago`:`${Math.floor(s/7)}w ago`;return`${m} **${x.handle}** (${x.touches}\xD7 \xB7 ${_})`}).join(" \xB7 ");o.push(`**Experts:** ${I}`)}else o.push("**Experts:** _None yet \u2014 add `author` to `learn_from_attempts` calls_");const e=t.replace(/[^a-z0-9]/gi," ").split(/\s+/).filter(I=>I.length>=4).slice(0,3).join(" "),g=[];if(e)try{const I=await dt(u,["cachly:lesson:best:*"],e,4);for(const x of I){const d=je(x.content);if(!We(d,nt))continue;const m=d.outcome==="success"?"\u2705":d.outcome==="partial"?"\u26A0\uFE0F":"\u274C",s=d.severity==="critical"?" \u{1F534}":d.severity==="major"?" \u{1F7E1}":"",_=d.author?` \xB7 \u{1F464} ${d.author}`:"",b=x.key.replace("cachly:lesson:best:","");g.push(` - ${m} \`${b}\`${s}${_} \u2014 ${(d.what_worked??"").slice(0,100)}`)}}catch{}if(g.length<2){const I=await De(u,"cachly:lesson:best:*",{max:1500});for(const x of I.slice(0,300)){const d=await u.get(x);if(!d)continue;const m=je(d);if(!We(m,nt)||!(m.file_paths??[]).includes(t))continue;const s=x.replace("cachly:lesson:best:","");if(g.some(z=>z.includes(`\`${s}\``)))continue;const _=m.outcome==="success"?"\u2705":m.outcome==="partial"?"\u26A0\uFE0F":"\u274C",b=m.severity==="critical"?" \u{1F534}":m.severity==="major"?" \u{1F7E1}":"",R=m.author?` \xB7 \u{1F464} ${m.author}`:"";g.push(` - ${_} \`${s}\`${b}${R} \u2014 ${(m.what_worked??"").slice(0,100)}`)}}g.length>0?(o.push("**Related lessons:**"),o.push(...g.slice(0,5))):o.push("**Related lessons:** _None yet_"),o.push("")}return o.push("---",'_Attribution builds with `learn_from_attempts(file_paths=[...], author="...")`. Run this before committing to track what changed and why._'),o.join(`
|
|
66
|
+
`)}case"team_expertise_map":{const{instance_id:c,top_n:n=20}=w,a=await M(c),u=await De(a,"cachly:ckg:node:person:*",{max:2e3});if(u.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(`
|
|
67
|
+
`);const o=[];for(const l of u){const i=await a.get(l);if(!i)continue;const A=F(i,null);if(!A||A.type!=="person")continue;const e=await a.smembers(`cachly:ckg:idx:from:${A.id}`),g=new Map;let I=0;for(const x of e){const d=await a.get(x);if(!d)continue;const m=F(d,null);if(!m||m.edgeType!=="authored")continue;I++;const s=m.to.split(":")[0]??"unknown";g.set(s,(g.get(s)??0)+1)}o.push({handle:A.handle,lessonCount:I,domains:g,lastActive:A.last_active})}o.sort((l,i)=>i.lessonCount-l.lessonCount);const t=o.slice(0,n),S=["## \u{1F5FA}\uFE0F Team Expertise Map","",`**${t.length}** contributor${t.length!==1?"s":""} tracked:`,"","| # | Handle | Lessons | Top domains | Last active |","|---|--------|---------|-------------|-------------|"];for(const[l,i]of t.entries()){const A=l===0?"\u{1F947}":l===1?"\u{1F948}":l===2?"\u{1F949}":`${l+1}`,e=Math.floor((Date.now()-new Date(i.lastActive).getTime())/864e5),g=e<1?"today":e<7?`${e}d ago`:e<30?`${Math.floor(e/7)}w ago`:`${Math.floor(e/30)}mo ago`,I=[...i.domains.entries()].sort((x,d)=>d[1]-x[1]).slice(0,3).map(([x,d])=>`${x}(${d})`).join(", ")||"\u2014";S.push(`| ${A} | **${i.handle}** | ${i.lessonCount} | ${I} | ${g} |`)}return S.push("","---",'_Use `brain_who_knows(topic="...")` to find the expert for a specific problem._'),S.join(`
|
|
68
|
+
`)}case"skill_gaps":{const{instance_id:c,min_failures:n=1}=w,a=await M(c),u=await De(a,"cachly:lesson:best:*",{max:3e3}),o=new Map;let t=0,S=0;for(const A of u){const e=await a.get(A);if(!e)continue;const g=je(e);if(g===null)continue;if(!We(g,nt)){S++;continue}const I=(g.topic??"").split(":")[0]??"unknown",x=o.get(I)??{successes:0,failures:0,attributed:0,topics:[]};g.outcome==="success"||g.outcome==="partial"?x.successes++:x.failures++,g.author&&(x.attributed++,t++),x.topics.push(g.topic??""),o.set(I,x)}const l=[];for(const[A,e]of o)e.failures>=n&&e.successes===0&&l.push({domain:A,type:"unresolved failures",severity:e.failures>=3?"\u{1F534} critical":"\u{1F7E1} warn",detail:`${e.failures} failure${e.failures!==1?"s":""}, 0 solutions \u2014 use \`learn_from_attempts\` to store what fixed it`}),e.successes+e.failures>=3&&e.attributed===0&&l.push({domain:A,type:"no attribution",severity:"\u{1F535} info",detail:`${e.successes+e.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","",`**${u.length}** lessons scanned \xB7 **${t}** attributed \xB7 **${l.length}** gap${l.length!==1?"s":""} found`,S>0?`_(${S} private or group-only lessons excluded from gap analysis)_`:"",""].filter(Boolean);if(l.length===0)i.push("\u2705 No significant knowledge gaps detected. All domains with failures have at least one success lesson.");else{const A=[...l.filter(e=>e.severity.includes("critical")),...l.filter(e=>e.severity.includes("warn")),...l.filter(e=>e.severity.includes("info"))];for(const e of A.slice(0,15))i.push(`${e.severity} **\`${e.domain}\`** \u2014 ${e.type}`),i.push(` ${e.detail}`),i.push("");l.length>15&&i.push(`_\u2026and ${l.length-15} more gaps. Fix critical ones first._`)}return i.push("---",`_Fix gaps with \`learn_from_attempts(topic="${l[0]?.domain??"your:topic"}", outcome="success", what_worked="...")\`_`,'_Add `author="name"` to every call to enable `brain_who_knows` + `team_expertise_map`._'),i.join(`
|
|
69
|
+
`)}case"brain_coverage":{const{instance_id:c,repo_path:n="."}=w,a=await M(c),[u,o,t]=await Promise.all([De(a,"cachly:lesson:best:*",{max:5e3}),De(a,"cachly:ckg:node:person:*",{max:2e3}),De(a,"cachly:ckg:node:file:*",{max:5e3})]);let S=0,l="n/a";try{const s=pt(n);if(!s)throw new Error("repo_path ist kein Ordner");S=Je(s,["ls-files"],{timeoutMs:3e4}).trim().split(`
|
|
70
|
+
`).filter(Boolean).length,l=String(S)}catch{}let i=0,A=0,e=0;const g=new Set;for(const s of u){const _=await a.get(s);if(!_)continue;const b=F(_,{});b.outcome==="success"||b.outcome==="partial"?i++:A++,b.author&&e++,g.add((b.topic??"").split(":")[0]??"unknown")}const I=S>0?`${Math.round(t.length/S*100)}% (${t.length}/${S} files)`:`${t.length} files tracked`,x=u.length>0?Math.round(e/u.length*100):0,d=Math.round(Math.min(1,u.length/50)*25+Math.min(1,i/Math.max(1,u.length))*25+Math.min(1,x/100)*25+Math.min(1,o.length/5)*25);return["## \u{1F4CA} Brain Coverage Report","",`${d>=80?"\u{1F7E2}":d>=50?"\u{1F7E1}":"\u{1F534}"} **Overall score: ${d}/100**`,"","| Metric | Value |","|--------|-------|",`| Total lessons | **${u.length}** (${i} success \xB7 ${A} failure) |`,`| Problem domains | **${g.size}** |`,`| Attribution | **${e}/${u.length}** (${x}%) |`,`| Contributors | **${o.length}** tracked in knowledge graph |`,`| File coverage | **${I}** |`,"","**Score breakdown (each 0\u201325):**",`- Lesson volume: **${Math.round(Math.min(1,u.length/50)*25)}/25** _(target: 50+ lessons)_`,`- Success ratio: **${Math.round(Math.min(1,i/Math.max(1,u.length))*25)}/25** _(target: all lessons resolved)_`,`- Attribution: **${Math.round(Math.min(1,x/100)*25)}/25** _(target: 100% attributed)_`,`- Team engagement: **${Math.round(Math.min(1,o.length/5)*25)}/25** _(target: 5+ contributors)_`,"","---","_Boost score: run `brain_from_git` \xB7 add `author` to `learn_from_attempts` \xB7 fix gaps with `skill_gaps`_"].join(`
|
|
71
|
+
`)}case"brain_metrics":{const{instance_id:c}=w,n=await M(c),[a,u,o,t,S,l]=await Promise.all([n.get(`cachly:stats:born_at:${c}`).catch(()=>null),n.get(`cachly:stats:first_recall_at:${c}`).catch(()=>null),n.get(`cachly:stats:recalls_total:${c}`).catch(()=>null),n.get(`cachly:stats:cross_author_recalls:${c}`).catch(()=>null),n.get(`cachly:stats:time_saved_mins:${c}`).catch(()=>null),n.smembers(ae(n,`cachly:stats:reuse_pairs:${c}`)).catch(()=>[])]);let i={};try{i=await n.hgetall(Os(c))??{}}catch{i={}}let A={};try{A=await n.hgetall(us(c))??{}}catch{A={}}const e={widersprochen:0,korrigiert:0,veraltet:0,ohneEreignis:0,lieferungen:0};try{const h=await n.lrange(ae(n,hs(c)),0,499),W=new Map;for(const te of h){const X=F(te,{ts:"",themen:[]});if(!(!X.ts||!Array.isArray(X.themen)))for(const Y of X.themen){if(e.lieferungen++,!W.has(Y)){const ie=await n.get(`cachly:lesson:best:${Y}`).catch(()=>null);W.set(Y,ie?F(ie,{}):null)}const Q=Yn(X.ts,W.get(Y)??null);if(Q.length===0){e.ohneEreignis++;continue}for(const ie of Q)e[ie]++}}}catch{}let g=0,I=0;try{const h=await n.lrange(ae(n,`cachly:wirkung:${c}`),0,-1);for(const W of h){const te=F(W,{});I++,te.geholfen===!0&&g++}}catch{}let x={};try{x=await n.hgetall(Po(c))??{}}catch{x={}}const d=jo(x,10);let m={token:0,abrufe:0,treffer:0};try{const h=await n.get(Ho(c)),W=await n.hgetall(Go(c))??{};m={token:h??0,abrufe:W.abrufe??0,treffer:W.treffer??0}}catch{}const s=Fo(m);let _;if(a&&u){const h=new Date(u).getTime()-new Date(a).getTime(),W=Math.max(0,Math.round(h/6e4)),te=W<1?"<1 min":W<60?`${W} min`:`${(W/60).toFixed(1)} h`,X=h<=2*6e4?"\u{1F7E2} under 2 min target":h<=60*6e4?"\u{1F7E1} over 2 min":"\u{1F534} over 1 h";_=`**${te}** from first lesson \u2192 first proven recall \xB7 ${X}`}else a&&!u?_="\u{1F7E1} Brain has knowledge but no proven recall yet \u2014 try `smart_recall`":_="\u26AA Not enough data yet \u2014 store a lesson, then recall it";const b=["\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(`
|
|
72
|
+
`),R=Number(o??0),z=Number(t??0),P=R>0?Math.round(z/R*100):0,r=P>=30?"\u{1F7E2} above 30 % target":R===0?"\u26AA no recalls yet":"\u{1F7E1} below 30 % target",re=Math.round(Number(S??0)),ee=re<60?`${re} min`:`${(re/60).toFixed(1)} h`;return["## \u{1F4C8} Brain Metrics \u2014 the three that decide everything","","### 1. Time-to-first-recall _(onboarding friction)_",_,"","### 2. Recall-lift _(the moat proof)_",b,"_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)_",`**${P}%** of proven recalls used a teammate's lesson (${z}/${R}) \xB7 ${r}`,l.length>0?`**${l.length}** distinct reuse relationship${l.length!==1?"s":""} ${At(n)?"for your account":"across the team"}`:"","","---","### \u{1F4E6} Aus dem Brain geliefert _(gemessen, nicht gerechnet)_",Wo(s),"",s.abrufe>0?`_Daneben eine **Sch\xE4tzung**: ${ee} 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 ${ee} \u201Enicht neu recherchiert" w\xE4re hier gerechnet, nicht gemessen \u2014 sie erscheint erst, wenn daneben eine gemessene Zahl steht._`,R===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 h=Number(i.beantwortet??0),W=Number(i.knapp??0),te=Number(i.schweigen??0),X=h+W+te;if(X===0)return"\u26AA Noch keine Zaehlung \u2014 die Ausgaenge zaehlen ab dieser Fassung je smart_recall.";const Y=Q=>`${Math.round(100*Q/X)} %`;return`**${X}** Suchen: ${Y(h)} beantwortet \xB7 ${Y(W)} als knapper Sieg markiert \xB7 ${Y(te)} 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 h=Y=>Number(A[Y]??0),W=[["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)"]],te=W.reduce((Y,[Q])=>Y+h(Q),0);if(te===0)return"\u26AA Noch keine Zaehlung \u2014 jeder learn_from_attempts-Fehlschlag wird ab dieser Fassung klassifiziert.";const X=W.filter(([Y])=>Y!=="ohne-vorwissen").sort((Y,Q)=>h(Q[0])-h(Y[0]))[0];return`**${te}** klassifizierte Fehlschlaege: `+W.map(([Y,Q])=>`${h(Y)} ${Q}`).join(" \xB7 ")+`. Die groesste vermeidbare Klasse ist **${X[1]}** (${h(X[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)_",e.lieferungen===0?"\u26AA Noch kein Liefer-Journal \u2014 die Etiketten entstehen ab dieser Fassung je smart_recall.":`**${e.lieferungen}** gelieferte Lektionen (letzte 500 Abrufe): ${e.widersprochen} widersprochen \xB7 ${e.korrigiert} korrigiert \xB7 ${e.veraltet} veraltet \xB7 ${e.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 h=Number(e.widersprochen)+Number(e.veraltet);if(I===0&&h===0)return"\u26AA Noch keine Wirkungs- oder Schadens-Daten \u2014 die Zahl entsteht aus Wirkungsspur und Etiketten.";const W=g-h;return`**${W>=0?"+":""}${W}** = ${g} bestaetigt geholfen (Wirkungsspur, ${I} Eintraege) \u2212 ${h} Schadenslieferungen (${e.widersprochen} spaeter widerlegt + ${e.veraltet} schon ersetzt geliefert). 'korrigiert' zaehlt nicht als Schaden \u2014 eine Nachbesserung ist kein Vorfall.`})(),"","### \u{1F527} Werkzeug-Nutzung _(erst messen, dann zusammenlegen)_",zo(d,Zo.length),...d.spitze.length>0?d.spitze.map((h,W)=>` ${String(W+1).padStart(2)}. \`${h.name}\` \u2014 ${h.aufrufe}\xD7 (${Math.round(h.anteil*100)} %)`):[]].filter(Boolean).join(`
|
|
73
|
+
`)}case"brain_service_map":{const{instance_id:c,service:n}=w;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 a=await M(c),u=`service:${Se(n.trim())}`,o=await a.get(`cachly:ckg:node:${u}`).catch(()=>null),t=o?F(o,null):null,S=await a.smembers(`cachly:ckg:idx:to:${u}`).catch(()=>[]),l=[],i=[],A=[];for(const _ of S){const b=await a.get(_).catch(()=>null);if(!b)continue;const R=F(b,null);if(R)if(R.edgeType==="operates"){const z=await a.get(`cachly:ckg:node:${R.from}`).catch(()=>null),P=z?F(z,null):null;P?.handle&&l.push({handle:P.handle,trials:R.trials})}else if(R.edgeType==="runs_in"){const z=await a.get(`cachly:ckg:node:${R.from}`).catch(()=>null),P=z?F(z,null):null;P?.path&&i.push({path:P.path,trials:R.trials})}else R.edgeType==="affects"&&A.push({id:R.from,confidence:R.confidence})}l.sort((_,b)=>b.trials-_.trials),i.sort((_,b)=>b.trials-_.trials),A.sort((_,b)=>b.confidence-_.confidence);const e=[],g=await De(a,"cachly:lesson:best:*",{max:1500}),I=n.trim().toLowerCase();for(const _ of g.slice(0,400)){const b=await a.get(_).catch(()=>null);if(!b)continue;const R=je(b);We(R,nt)&&(R.service??"").toLowerCase()===I&&e.push({...R,topic:_.replace("cachly:lesson:best:","")})}if(!t&&e.length===0&&l.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(`
|
|
74
|
+
`);const x=t?.kind==="system"?"\u{1F5A5}\uFE0F system":"\u{1F6F0}\uFE0F service",d=[`## ${t?.kind==="system"?"\u{1F5A5}\uFE0F":"\u{1F6F0}\uFE0F"} Service Map \u2014 \`${n}\``,"",t?`_${x} \xB7 ${t.count} lesson${t.count!==1?"s":""} referenced \xB7 domain: ${t.domain}_`:"_No graph node yet \u2014 built from tagged lessons below._",""];if(l.length>0){const _=l.slice(0,5).map((b,R)=>`${R===0?"\u{1F947}":R===1?"\u{1F948}":R===2?"\u{1F949}":`${R+1}.`} **${b.handle}** (${b.trials}\xD7)`).join(" \xB7 ");d.push(`**Operators:** ${_}`,"")}else d.push("**Operators:** _None attributed \u2014 add `author` when learning about this service_","");const m=e.filter(_=>_.outcome==="failure"),s=e.filter(_=>_.outcome!=="failure");if(m.length>0){d.push(`**\u26A0\uFE0F Known failures (${m.length}):**`);for(const _ of m.slice(0,6)){const b=_.severity==="critical"?" \u{1F534}":_.severity==="major"?" \u{1F7E1}":"",R=_.author?` \xB7 \u{1F464} ${_.author}`:"";d.push(` - \u274C \`${_.topic}\`${b}${R} \u2014 ${(_.what_worked??"").slice(0,100)}`)}d.push("")}if(s.length>0){d.push(`**\u2705 Proven fixes (${s.length}):**`);for(const _ of s.slice(0,6)){const b=_.outcome==="partial"?"\u26A0\uFE0F":"\u2705",R=_.author?` \xB7 \u{1F464} ${_.author}`:"";d.push(` - ${b} \`${_.topic}\`${R} \u2014 ${(_.what_worked??"").slice(0,100)}`)}d.push("")}return i.length>0&&d.push(`**Files in this service:** ${i.slice(0,8).map(_=>`\`${_.path}\``).join(", ")}`,""),d.push("---",`_Tag lessons with \`service="${n}"\` to keep this map current. For infra, pass \`service_kind="system"\`._`),d.join(`
|
|
75
|
+
`)}case"brain_collab_pairs":{const{instance_id:c,min_weight:n=1}=w,a=await M(c),u=typeof n=="number"&&n>=1?Math.floor(n):1,o=await De(a,"cachly:ckg:node:person:*",{max:500}),t=new Map;for(const g of o){const I=await a.get(g);if(!I)continue;const x=F(I,null);!x||x.type!=="person"||t.set(x.id,{id:x.id,handle:x.handle,domain:x.domain,count:x.count})}if(t.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(`
|
|
76
|
+
`);const S=new Map;for(const[g,I]of t){const x=await a.smembers(`cachly:ckg:idx:from:${g}`);for(const d of x){const m=await a.get(d);if(!m)continue;const s=F(m,null);if(!s||s.edgeType!=="collaborates")continue;const _=t.get(s.to);if(!_)continue;const[b,R]=g<s.to?[g,s.to]:[s.to,g],z=`${b}||${R}`,P=S.get(z);if(P)P.trials+=s.trials;else{const[r,re]=g<s.to?[I,_]:[_,I];S.set(z,{a:r,b:re,trials:s.trials,confidence:s.confidence})}}}const l=[...S.values()].filter(g=>g.trials>=u).sort((g,I)=>I.trials-g.trials),i=new Set;for(const g of l)i.add(g.a.id),i.add(g.b.id);const A=[...t.values()].filter(g=>!i.has(g.id)),e=["## \u{1F91D} Team Collaboration Graph",""];if(l.length===0)e.push(`No collaboration pairs yet (min weight: ${u}).`,"","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{e.push(`**${l.length} collaboration pair${l.length!==1?"s":""}** across ${i.size} contributor${i.size!==1?"s":""}:`,"");for(const g of l.slice(0,20)){const I=(g.confidence*100).toFixed(0),x=[g.a.domain,g.b.domain].filter((d,m,s)=>d&&s.indexOf(d)===m).map(d=>`\`${d}\``).join(", ");e.push(`### @${g.a.handle} \u2194 @${g.b.handle}`,`- **${g.trials} collaboration event${g.trials!==1?"s":""}** \xB7 ${I}% confidence`,`- Domains: ${x||"_unknown_"}`,`> \u{1F4AC} _"Frag **@${g.a.handle}** und **@${g.b.handle}** \u2014 they've solved problems together in these areas."_`,"")}l.length>20&&e.push(`_...and ${l.length-20} more pairs. Use \`min_weight\` to filter._`,"")}return A.length>0&&e.push("---","### \u26A0\uFE0F Bus Factor Alert \u2014 No Collaborators Yet","",`${A.length} contributor${A.length!==1?"s have":" has"} knowledge that no teammate has recalled or co-touched:`,"",...A.slice(0,10).map(g=>`- **@${g.handle}** \u2014 ${g.count} lesson${g.count!==1?"s":""} \xB7 domain: \`${g.domain}\``),"","_Tip: pair these contributors with teammates on shared files to reduce bus factor._"),e.push("","---","_Collaboration edges build from `learn_from_attempts(author=..., file_paths=[...])` and `smart_recall(requester=...)` cross-author reuse._"),e.join(`
|
|
77
|
+
`)}case"brain_portability":{const{instance_id:c}=w,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:c}}}},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:c}}}},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:c}}}},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:c}}}},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:c}}}},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:c}}}},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:c}}]},null,2)}],a=["## \u{1F310} Brain Portability \u2014 Same Brain, Any Model","",'> _"Bring your own model, keep your brain."_',"",`**Your Brain ID:** \`${c}\``,"","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 u of n)a.push(`#### ${u.icon} ${u.name}`,`Config: \`${u.configPath}\``,"","```json",u.configBlock,"```","");return a.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 \`${c}\` Brain ID pre-filled.`,"","---","_Docs: cachly.dev/docs/model-neutral \u2022 Your Brain, Any Model_"),a.join(`
|
|
78
|
+
`)}case"brain_changelog":{const{instance_id:c,days:n=7,max_lessons:a=30,include_failures:u=!0}=w,o=await M(c),t=Date.now()-Number(n)*864e5,S=await De(o,"cachly:lesson:best:*",{max:4e3,timeoutMs:4e3}),l=[];for(const d of S){const m=await o.get(d).catch(()=>null);if(!m)continue;const s=We(je(m),nt)?F(m,{}):null;if(!s||(s.ts?new Date(s.ts).getTime():0)<t||!u&&s.outcome==="failure")continue;const b=d.replace("cachly:lesson:best:","");l.push({...s,topic:b})}l.sort((d,m)=>{const s=d.ts?new Date(d.ts).getTime():0;return(m.ts?new Date(m.ts).getTime():0)-s});const i=l.slice(0,Number(a));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(`
|
|
79
|
+
`);const A=new Map;for(const d of i){const m=d.topic.includes(":")?d.topic.split(":")[0]:"general",s=A.get(m)??[];s.push(d),A.set(m,s)}const e=d=>d==="critical"?"\u{1F6A8}":d==="major"?"\u26A0\uFE0F":d==="minor"?"\u{1F4A1}":"\u2728",g=d=>d==="failure"?"\u274C":d==="partial"?"\u{1F536}":"\u2705",x=[`## \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 ${A.size} topic area${A.size!==1?"s":""}_`,""];for(const[d,m]of Array.from(A.entries()).sort((s,_)=>_[1].length-s[1].length)){x.push(`### ${d}`),x.push("");for(const s of m){const _=s.outcome==="failure"?g(s.outcome):e(s.severity),b=s.outcome==="failure"?s.what_failed:s.what_worked,R=[];s.author&&R.push(`by **${s.author}**`),s.recall_count&&R.push(`${s.recall_count} recall${s.recall_count!==1?"s":""}`),s.confidence!==void 0&&R.push(`${Math.round(s.confidence*100)}% confidence`),x.push(`- ${_} **${s.topic}**${b?` \u2014 ${b}`:""}`),R.length&&x.push(` _${R.join(" \xB7 ")}_`)}x.push("")}return x.push("---",`_Generated from Brain \`${c}\` \xB7 Share this in your standup or Slack_`),x.join(`
|
|
80
|
+
`)}case"brain_set_pref":{const{instance_id:c,key:n,value:a}=w;if(!n||!n.trim())throw new Error("key is required");const u=Ge({value:String(a)}),o=u.felder.value,t=await M(c),S=`cachly:prefs:${n.trim()}:${c}`;return await t.set(S,o),[`\u2705 Preference \`${n}\` set to \`${o}\` for this Brain instance.`,...Ke(u,"wert")].join(`
|
|
81
|
+
`)}case"brain_get_pref":{const{instance_id:c,key:n}=w,a=await M(c);if(n&&n.trim()){const S=await a.get(`cachly:prefs:${n.trim()}:${c}`).catch(()=>null);return S===null?`\u2139\uFE0F Preference \`${n}\` is not set (using default).`:`\u{1F527} Preference \`${n}\` = \`${S}\``}const u=await De(a,`cachly:prefs:*:${c}`,{max:200,timeoutMs:2e3});if(u.length===0)return"\u2139\uFE0F No preferences set for this Brain instance.";const o=await a.mget(...u),t=["\u{1F527} **Brain preferences:**",""];for(let S=0;S<u.length;S++){const l=u[S].replace("cachly:prefs:","").replace(`:${c}`,"");t.push(`- \`${l}\` = \`${o[S]??"(null)"}\``)}return t.join(`
|
|
82
|
+
`)}default:return null}}async function Ra(k,w){try{if(!Fe()||Le!=="cachly"&&Le!=="ollama")return 0;const{vektor:M,zweit:j}=Dt(k);let c=0;for(const n of M.themen()){if(c>=w)break;if(j.hat(n)||await k.exists(`${Ye}${n}`))continue;const a=await k.get(`cachly:lesson:best:${n}`);if(!a)continue;const u=F(a,{});try{const o=await Be(Ze(u),{geduld:"lang",modell:Qe});o?.length&&(await k.set(`${Ye}${n}`,He(o)),c++)}catch{}}return c}catch{return 0}}async function Ht(k,w,M){try{if(!Fe()||qe(k))return;const j=await k.srandmember(Xe,M),c=Array.isArray(j)?j:j?[j]:[],n=Gt(k);for(const a of c){if(a===w||n.has(a))continue;const u=await k.get(`cachly:lesson:best:${a}`);if(!u){await k.srem(Xe,a);continue}const o=F(u,{});try{const t=await Be(Ze(o),{geduld:"lang"});if(t?.length)await k.set(`${Mt}${a}`,He(t)),await k.srem(Xe,a);else continue;if(Le==="cachly"||Le==="ollama")try{const S=await Be(Ze(o),{geduld:"lang",modell:Qe});S?.length&&(await k.set(`${Ye}${a}`,He(S)),await k.srem(mt,a))}catch{}}catch{}}await Ba(k,M),await Fs(k,ot,ft,w,M,a=>{const u=Rt(a);return u?Be(u,{geduld:"lang"}):Promise.resolve(null)}),(Le==="cachly"||Le==="ollama")&&await Fs(k,mt,Ye,w,M,(a,u)=>Be(Ze(u),{geduld:"lang",modell:Qe}))}catch{}}const La=5*6e4,Ws=new WeakMap;async function Ba(k,w){const M=Ws.get(k)??{liste:[],geprueft:0};if(Ws.set(k,M),M.liste.length===0){if(Date.now()-M.geprueft<La)return;M.geprueft=Date.now();const j=async a=>{const u=new Set;let o="0";do{const[t,S]=await k.scan(o,"MATCH",`${a}*`,"COUNT",500);o=t;for(const l of S)u.add(l.slice(a.length))}while(o!=="0");return u},c=await j(Mt),n=await j(ft);M.liste=[...c].filter(a=>!n.has(a)&&Rt(a))}for(const j of M.liste.splice(0,w))await k.sadd(ot,j).catch(()=>{})}async function Fs(k,w,M,j,c,n){const a=await k.srandmember(w,c),u=Array.isArray(a)?a:a?[a]:[],o=Gt(k);for(const t of u){if(t===j||o.has(t))continue;const S=await k.get(`cachly:lesson:best:${t}`);if(!S){await k.srem(w,t);continue}if(await k.exists(`${M}${t}`)){await k.srem(w,t);continue}try{const l=await n(t,F(S,{}));l===null?await k.srem(w,t):l?.length&&(await k.set(`${M}${t}`,He(l)),await k.srem(w,t))}catch{}}}const Hs=new WeakMap;function Gt(k){let w=Hs.get(k);return w||(w=new Set,Hs.set(k,w)),w}export{Ji as BRAIN_TOOL_NAMES,es as RECALL_ROH_ZEICHEN,Qt as RECALL_VOLLTEXT_ZEICHEN,Dt as bestaendeFuer,js as getRecallGate,Ui as handleBrainTool,St as recallNurLesen,vt as recallVorschau};
|