@cachly-dev/mcp-server 0.10.221 → 0.10.223
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/abstention.js +2 -2
- package/dist/src/handlers/brain.js +3 -3
- package/dist/src/index.js +44 -42
- package/dist/src/leeres-brain.js +5 -5
- package/dist/src/startwissen.js +19 -19
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +15 -15
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/src/abstention.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CKG_BELEG_SCHWELLE as
|
|
2
|
-
`)}const
|
|
1
|
+
import{CKG_BELEG_SCHWELLE as h,SINN_BELEG_SCHWELLE as c,WORT_BELEG_SCHWELLE as u}from"./rangfolge-stellschrauben.js";const i=e=>typeof e=="number"&&Number.isFinite(e)?e:0;function b(e,t={}){return i(e.wortBelege)>=(t.woerter??u)||i(e.semScore)>=(t.naehe??c)||i(e.ckgScore)>=(t.kante??h)}function m(e,t={}){let r=0,n=0,o=!1,a=0;for(const s of e){const l=i(s.wortBelege),f=i(s.semScore);l>r&&(r=l),f>n&&(n=f),b(s,t)&&(o=!0,a++)}return{schweigen:e.length===0||!o,besteWortBelege:r,besteNaehe:n,geprueft:e.length,belegte:a}}const g="No matches found";function w(e,t={}){if(e.geprueft===0)return`\u{1F50D} **${g}** \u2014 there is no lesson for this question yet.`;const r=t.woerter??u,n=t.naehe??c;return[`\u{1F50D} **${g}.**`,"",`${e.geprueft} candidates checked, none confirmed \u2014 the best contained ${e.besteWortBelege} of the searched words (needed: ${r}), highest semantic similarity ${e.besteNaehe.toFixed(2)} (needed: ${n.toFixed(2)}).`,"They are deliberately NOT shown: a weak match looks like a strong one, and the difference matters.","",'_If the answer should be in the Brain anyway, ask with other words \u2014 or use `recall_best_solution(topic="\u2026")` if you know the topic._'].join(`
|
|
2
|
+
`)}const d=5;function N(e){const t=e.filter(o=>Number.isFinite(o)&&o>=0);if(t.length===0)return null;const r=Math.min(...t),n=Math.max(...t);return r<d?null:t.length===1?`Der belegte Treffer ist ${n} Tage unbest\xE4tigt.`:r===n?`Die belegten Treffer sind ${n} Tage unbest\xE4tigt.`:`Die belegten Treffer sind seit ${r}\u2013${n} Tagen unbest\xE4tigt.`}export{d as ALTER_NENNEN_AB_TAGEN,g as SCHWEIGEN_MARKE,w as abstentionSatz,N as alterssatzFuerBelegte,m as beurteileTreffer,b as istBelegt};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{gitLesen as We,istCommitHash as gs,pruefeOrdner as nt}from"../git-ohne-shell.js";import{createRequire as St}from"node:module";import{calculateConfidence as Ct,confidenceBadge as ms,STRUCTURED_TEMPLATES as ps,CONFIDENCE_WARN_VALUE as ws}from"../confidence.js";import{kurzfassenHinweis as ys}from"../antwort-hinweis.js";import{pruefeMeldung as _s,wendeAn as bs}from"../pruefung-melden.js";import{ckgSlug as ge,extractProblemConcept as ot,ckgUpsertNode as Fe,ckgUpdateEdge as ke,ckgUpsertPersonNode as $s,ckgUpsertFileNode as xt,ckgRecordCollaboration as ks,ckgUpsertServiceNode as vs}from"../ckg.js";import{safeJsonParse as P,scanKeys as Me,leseOderNull as Be,darfHeraus as Ge}from"../utils.js";import{ersparteMinuten as Tt,istStarterLektion as at,zaehltAlsErsparnis as Nt}from"../wertbeitrag.js";import{lessonPreviewLines as Qe,trimTo as Ss}from"../lesson-preview.js";import{normalisiereZeit as it,zaehleZeitangaben as rt}from"../zeit-normalisieren.js";import{abstentionSatz as Cs,alterssatzFuerBelegte as xs,beurteileTreffer as Ts,istBelegt as Ns}from"../abstention.js";import{meldeEinmal as ct,meldeUndVermerke as et,fehlerText as lt,OHNE_VEKTOREN as As,OHNE_DIENST as Es,OHNE_FRAGEVEKTOR as Is,SINNPFAD_ABBRUCH as Ms,OHNE_SCHREIBVEKTOR as ht}from"../aussetzer.js";import{versuchStart as Ls,neueKennung as Rs,wendeZuteilungAn as Ds,schliesseVersuchAb as Bs}from"../versuch.js";function ut(O,R,F,ae=F){if(O.includes("lesson:best:")){const e=P(R,{});if(e&&typeof e=="object"&&(e.what_worked||e.what_failed||e.commands?.length))return Qe(e,{maxChars:F,indent:" "})}const f=Ss(R,ae);return f?[f]:[]}const At=2e3,Et=400;function It(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{getRole as dt,ROLE_BADGE as zs,getScopes as Mt,lessonVisibleToScope as Lt,reviewModeEnabled as Os,storeLessonProposal as Ps}from"./team.js";import{keywordSearch as tt,treffeUeberDateipfad as js,wortindexEntwerten as Rt,tokenize as ft,splitMultiQuery as Ws,levenshtein as Fs,indexVocab as Dt,bestandHolen as Gs}from"../search.js";import{startetNochLeer as Bt,leeresBrainAntwort as zt,startLage as gt,sofortAntwortNeuesBrain as Ks,neuesBrainBriefing as Hs}from"../leeres-brain.js";import{rerankByQuality as Vs,qualityMultiplier as Js,extractLessonQuality as qs}from"../rerank.js";import{computeEmbedding as xe,hasEmbedProvider as ze,EMBED_PROVIDER as Te}from"../embeddings.js";import{leserAktiv as Us,leserPunkte as Ys,mischeMitLeser as Zs}from"../leser.js";import{repariereFelder as Xs}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Ot,NAME_VEKTOR_PRAEFIX as mt,ZWEIT_VEKTOR_PRAEFIX as Ke,packe as Oe,textFuerVektor as He,textFuerNamensVektor as Pt,Vektorbestand as pt,VEKTOR_NACHTRAG as Qs,NAME_VEKTOR_NACHTRAG as wt,ZWEIT_VEKTOR_NACHTRAG as st}from"../bedeutung.js";import{schreibeEingaenge as en,Eingangsbestand as tn}from"../eingaenge.js";import{ordneNachHausordnung as sn,rangWerte as nn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as on}from"../seltenheitsbestand.js";import{spurLegen as an}from"../spuren.js";import{schlageErsetzungVor as rn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as jt,stufeSucheNachProjektversion as cn,versionsNotizen as ln,versionsBanner as hn}from"../gueltigkeit-version.js";const Ve=Qs,un=365;import{etikettenFuer as dn,lieferJournalSchluessel as Wt,JOURNAL_DECKEL as fn}from"../etiketten.js";import{klassifiziereFehlschlag as gn,suchProtokollSchluessel as yt,trichterSchluessel as Ft,SUCH_DECKEL as Gt}from"../recall-trichter.js";import{leiteEntscheidungAb as mn,entscheidungsZeile as Kt}from"../entscheidung-ableiten.js";import{bewerteTopf as pn,spreizeImTopf as Ht,reichereAn as wn,inhaltsWoerter as Vt,grobStamm as yn,GEWICHTE as _n,knapperSiegSatz as bn}from"../rangfolge.js";import{pruefeWirkung as $n,werteAus as kn,lehrwert as vn,leiteAb as Sn}from"../wirkungsspur.js";import{merkeSuchlauf as _t}from"../suchstatistik.js";import{schreibeTopfNotiz as Cn,topfProtokollAktiv as xn}from"../topf-protokoll.js";import{SINN_TOPF as Tn,EINGANG_SCHWELLE as Nn,EINGANG_SORTIER_GEWICHT as An,ZWEIT_MODELL as Ye,ZWEIT_GEWICHT as En,ZWEIT_MINDESTDECKUNG as Jt,NAHDUPLIKAT_SCHWELLE as In,LESER_TIEFE as qt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Ut,quelleZeile as Mn}from"../herkunft.js";import{doppelHinweis as Ln,leseDoppelKandidaten as Rn,mitFrist as Dn,pruefeDoppelung as Bn}from"../doppel-kandidat.js";import{merkeRecall as zn,sitzungsKosten as On,vergissSitzungsKosten as Pn,kostenZeilen as jn}from"../sitzungs-kosten.js";const Yt=new WeakMap;function bt(O){let R=Yt.get(O);return R||(R={vektor:new pt,namen:new pt(6e4,mt),zweit:new pt(6e4,Ke),eingang:new tn,seltenheit:new on},Yt.set(O,R)),R}const Zt=Tn,Wn=Nn,Fn=An;import{upgradeNudge as Gn}from"../upgrade-nudge.js";import{recallTiefe as Xt,verlangteTiefe as Kn,TIEFE_VOLL as Hn,TIEFE_VOLL_MEHRTHEMIG as Vn}from"../recall-tiefe.js";import{nutzungInWorten as Jn,nutzungsSchluessel as qn,verdichte as Un}from"../werkzeug-nutzung.js";import{inWorten as Yn,lieferBild as Zn,lieferSchluessel as Xn,trefferSchluessel as Qn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as eo,autorHinweis as to,coautorAus as so,echterGitLeser as no,ermittleAutor as oo,mitCoautor as ao,nurMensch as Qt}from"../autor.js";import{TOOLS as io}from"../tools.js";import{vorspannHinweis as ro}from"../vorspann.js";import{autorAbzeichen as co,fremdanteil as lo}from"../autor-abzeichen.js";import{cachlyUrl as ho}from"../cachly-url.js";import{belegFuer as uo}from"../schreibbeleg.js";import{schwaerzeFelder as fo}from"../geheimnis-filter.js";import{VERDACHT_TAG as $t,mitVerdachtTag as go,pruefeFelder as mo,verdachtsWarnung as po}from"../tuersteher.js";import{fuerEigenenSpeicher as Pe,hinweise as Je,istMarkiert as es,markiert as wo,markierungsWarnung as ts,markierungsWarnungAusRohwert as ss,zaehlHinweise as ns}from"../schreibtor.js";import{istBlossesThema as os}from"../blosses-thema.js";import{zeitpunkt as _e}from"../zeitmessung.js";const Ze=(()=>{try{const O=St(import.meta.url);for(const R of["../../../package.json","../../package.json"])try{const F=O(R);if(F.name==="@cachly-dev/mcp-server"&&F.version)return F.version}catch{}}catch{}return"0.10.100"})(),yo=()=>{try{return St(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},_o={"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${Ze}:**`," \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"]},Ca=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"]),bo=ho("/billing","upgrade"),as=new Map,is=new Set,$o=1680*60*60;function ko(O=new Date){return`cachly:quota:recalls:${O.toISOString().slice(0,7)}`}async function kt(O){try{const R=ko();await O.incr(R)===1&&await O.expire(R,$o)}catch{}}function rs(O){return`cachly:stats:drei-ausgaenge:${O}`}async function vt(O,R,F){try{await O.hincrby(rs(R),F,1)}catch{}}function cs(O,R,F,ae){kt(O),_t(O,F,ae);const f={ts:new Date().toISOString(),frage:F.slice(0,200),geliefert:[]};(async()=>{const e=yt(R);await O.lpush(e,JSON.stringify(f)),await O.ltrim(e,0,Gt-1)})().catch(()=>{}),vt(O,R,"schweigen")}async function ls(O){const R={tage:0,rekord:0};try{const F=await O.get("cachly:streak:current"),ae=P(F,null),f=new Date().toISOString().slice(0,10);if(ae){const e=ae.last_date,h=new Date(Date.now()-864e5).toISOString().slice(0,10);e===f?(R.tage=ae.days,R.rekord=ae.record):e===h?(R.tage=ae.days+1,R.rekord=Math.max(R.tage,ae.record),await O.set("cachly:streak:current",JSON.stringify({days:R.tage,last_date:f,record:R.rekord}))):(R.tage=1,R.rekord=ae.record,await O.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:R.rekord})))}else R.tage=1,R.rekord=1,await O.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:1}))}catch{}return R}async function hs(O,R,F){await O.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:R,provider:F}),"EX",86400)}async function us(O,R){const F=as.get(O);if(F&&F.expiresAt>Date.now())return F.gate;try{const ae=await R(`/api/v1/instances/${O}/memory`),f=ae?.recall_limit??-1,e=ae?.total_recall_count??0,h={reached:f>0&&e>=f,limit:f,used:e,goodwillMessage:ae?.goodwill_message,notice:ae?.notice};return as.set(O,{gate:h,expiresAt:Date.now()+6e4}),h}catch{return{reached:!1,limit:-1,used:0}}}const vo={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function xa(O,R,F,ae){const f=await So(O,R,F,ae),e=vo[O];if(e&&typeof f=="string")try{zn(String(R.instance_id??""),String(R[e]??""),f.length)}catch{}return f}async function So(O,R,F,ae){switch(O){case"learn_from_attempts":{const f=fo(R),e=mo(f.felder),h=e.length?{...f.felder,tags:go(f.felder.tags)}:f.felder,{instance_id:y,topic:n,outcome:o,what_worked:I,what_failed:b="",context:i="",severity:l="major",file_paths:a=[],commands:s=[],tags:N=[],depends_on:r=[],author:c="",visibility:x="team",service:m="",service_kind:w="service",group:L="",grund:A="",ersetzt:M="",gilt_ab:t="",gilt_fuer:ne}=h,{what_worked:le,what_failed:ue="",context:fe=""}=Xs({what_worked:I,what_failed:b,context:i}),d=await F(y),W=new Date,se=W.toISOString();let K=jt(ne,void 0);const Q=t&&!Number.isNaN(Date.parse(String(t)))?new Date(String(t)):W,J=it(le,Q),X=it(ue,Q),he=it(fe,Q),u=rt(le,Q)+rt(ue,Q)+rt(fe,Q),v=oo({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:no(process.env.CACHLY_WORKSPACE??process.cwd())});let _="";try{_=so(await d.get(`cachly:prefs:${eo}:${y}`))}catch{}const k=ao(v.autor,_),S=to(v);if(x!=="private"&&await Os(d,y))return Ps(d,n,{topic:n,outcome:o,what_worked:J,what_failed:X,context:he,severity:l,file_paths:a,commands:s,tags:N,depends_on:r,...K.angaben.length?{gilt_fuer:K.angaben}:{},...k?{author:k}:{},source:Ut(),...m?{service:m}:{},...L?{group:String(L).toLowerCase().trim()}:{},visibility:x,recall_count:0,ts:se,confidence:1,version:3});const z=n.split(":")[0],E=ps[z],G=[];if(E)for(const $ of E.required)$==="commands"&&s.length===0&&G.push(`\u{1F4CB} ${E.hint}`);let Y=!1,ce=0,me,Z=[];const be=await d.get(`cachly:lesson:best:${n}`),$e=String(A??"").trim();if(be&&!$e)return[`\u270B **Update abgewiesen:** \`${n}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
1
|
+
import{gitLesen as We,istCommitHash as gs,pruefeOrdner as nt}from"../git-ohne-shell.js";import{createRequire as St}from"node:module";import{calculateConfidence as Ct,confidenceBadge as ms,STRUCTURED_TEMPLATES as ps,CONFIDENCE_WARN_VALUE as ws}from"../confidence.js";import{kurzfassenHinweis as ys}from"../antwort-hinweis.js";import{pruefeMeldung as _s,wendeAn as bs}from"../pruefung-melden.js";import{ckgSlug as ge,extractProblemConcept as ot,ckgUpsertNode as Fe,ckgUpdateEdge as ke,ckgUpsertPersonNode as $s,ckgUpsertFileNode as xt,ckgRecordCollaboration as ks,ckgUpsertServiceNode as vs}from"../ckg.js";import{safeJsonParse as P,scanKeys as Me,leseOderNull as Be,darfHeraus as Ge}from"../utils.js";import{ersparteMinuten as Tt,istStarterLektion as at,zaehltAlsErsparnis as Nt}from"../wertbeitrag.js";import{lessonPreviewLines as Qe,trimTo as Ss}from"../lesson-preview.js";import{normalisiereZeit as it,zaehleZeitangaben as rt}from"../zeit-normalisieren.js";import{abstentionSatz as Cs,alterssatzFuerBelegte as xs,beurteileTreffer as Ts,istBelegt as Ns}from"../abstention.js";import{meldeEinmal as ct,meldeUndVermerke as et,fehlerText as lt,OHNE_VEKTOREN as As,OHNE_DIENST as Es,OHNE_FRAGEVEKTOR as Is,SINNPFAD_ABBRUCH as Ms,OHNE_SCHREIBVEKTOR as ht}from"../aussetzer.js";import{versuchStart as Ls,neueKennung as Rs,wendeZuteilungAn as Ds,schliesseVersuchAb as Bs}from"../versuch.js";function ut(O,R,F,ae=F){if(O.includes("lesson:best:")){const e=P(R,{});if(e&&typeof e=="object"&&(e.what_worked||e.what_failed||e.commands?.length))return Qe(e,{maxChars:F,indent:" "})}const f=Ss(R,ae);return f?[f]:[]}const At=2e3,Et=400;function It(){return process.env.CACHLY_RECALL_NUR_LESEN==="1"}import{getRole as dt,ROLE_BADGE as zs,getScopes as Mt,lessonVisibleToScope as Lt,reviewModeEnabled as Os,storeLessonProposal as Ps}from"./team.js";import{keywordSearch as tt,treffeUeberDateipfad as js,wortindexEntwerten as Rt,tokenize as ft,splitMultiQuery as Ws,levenshtein as Fs,indexVocab as Dt,bestandHolen as Gs}from"../search.js";import{startetNochLeer as Bt,leeresBrainAntwort as zt,startLageMitCommits as gt,sofortAntwortNeuesBrain as Ks,neuesBrainBriefing as Hs}from"../leeres-brain.js";import{rerankByQuality as Vs,qualityMultiplier as Js,extractLessonQuality as qs}from"../rerank.js";import{computeEmbedding as xe,hasEmbedProvider as ze,EMBED_PROVIDER as Te}from"../embeddings.js";import{leserAktiv as Us,leserPunkte as Ys,mischeMitLeser as Zs}from"../leser.js";import{repariereFelder as Xs}from"../feldreparatur.js";import{VEKTOR_PRAEFIX as Ot,NAME_VEKTOR_PRAEFIX as mt,ZWEIT_VEKTOR_PRAEFIX as Ke,packe as Oe,textFuerVektor as He,textFuerNamensVektor as Pt,Vektorbestand as pt,VEKTOR_NACHTRAG as Qs,NAME_VEKTOR_NACHTRAG as wt,ZWEIT_VEKTOR_NACHTRAG as st}from"../bedeutung.js";import{schreibeEingaenge as en,Eingangsbestand as tn}from"../eingaenge.js";import{ordneNachHausordnung as sn,rangWerte as nn}from"../ausgabe-ordnung.js";import{Seltenheitsbestand as on}from"../seltenheitsbestand.js";import{spurLegen as an}from"../spuren.js";import{schlageErsetzungVor as rn}from"../ersetzung-vorschlag.js";import{loeseGiltFuerAuf as jt,stufeSucheNachProjektversion as cn,versionsNotizen as ln,versionsBanner as hn}from"../gueltigkeit-version.js";const Ve=Qs,un=365;import{etikettenFuer as dn,lieferJournalSchluessel as Wt,JOURNAL_DECKEL as fn}from"../etiketten.js";import{klassifiziereFehlschlag as gn,suchProtokollSchluessel as yt,trichterSchluessel as Ft,SUCH_DECKEL as Gt}from"../recall-trichter.js";import{leiteEntscheidungAb as mn,entscheidungsZeile as Kt}from"../entscheidung-ableiten.js";import{bewerteTopf as pn,spreizeImTopf as Ht,reichereAn as wn,inhaltsWoerter as Vt,grobStamm as yn,GEWICHTE as _n,knapperSiegSatz as bn}from"../rangfolge.js";import{pruefeWirkung as $n,werteAus as kn,lehrwert as vn,leiteAb as Sn}from"../wirkungsspur.js";import{merkeSuchlauf as _t}from"../suchstatistik.js";import{schreibeTopfNotiz as Cn,topfProtokollAktiv as xn}from"../topf-protokoll.js";import{SINN_TOPF as Tn,EINGANG_SCHWELLE as Nn,EINGANG_SORTIER_GEWICHT as An,ZWEIT_MODELL as Ye,ZWEIT_GEWICHT as En,ZWEIT_MINDESTDECKUNG as Jt,NAHDUPLIKAT_SCHWELLE as In,LESER_TIEFE as qt}from"../rangfolge-stellschrauben.js";import{ermittleQuelle as Ut,quelleZeile as Mn}from"../herkunft.js";import{doppelHinweis as Ln,leseDoppelKandidaten as Rn,mitFrist as Dn,pruefeDoppelung as Bn}from"../doppel-kandidat.js";import{merkeRecall as zn,sitzungsKosten as On,vergissSitzungsKosten as Pn,kostenZeilen as jn}from"../sitzungs-kosten.js";const Yt=new WeakMap;function bt(O){let R=Yt.get(O);return R||(R={vektor:new pt,namen:new pt(6e4,mt),zweit:new pt(6e4,Ke),eingang:new tn,seltenheit:new on},Yt.set(O,R)),R}const Zt=Tn,Wn=Nn,Fn=An;import{upgradeNudge as Gn}from"../upgrade-nudge.js";import{recallTiefe as Xt,verlangteTiefe as Kn,TIEFE_VOLL as Hn,TIEFE_VOLL_MEHRTHEMIG as Vn}from"../recall-tiefe.js";import{nutzungInWorten as Jn,nutzungsSchluessel as qn,verdichte as Un}from"../werkzeug-nutzung.js";import{inWorten as Yn,lieferBild as Zn,lieferSchluessel as Xn,trefferSchluessel as Qn}from"../geliefert.js";import{COAUTHOR_PREF_KEY as eo,autorHinweis as to,coautorAus as so,echterGitLeser as no,ermittleAutor as oo,mitCoautor as ao,nurMensch as Qt}from"../autor.js";import{TOOLS as io}from"../tools.js";import{vorspannHinweis as ro}from"../vorspann.js";import{autorAbzeichen as co,fremdanteil as lo}from"../autor-abzeichen.js";import{cachlyUrl as ho}from"../cachly-url.js";import{belegFuer as uo}from"../schreibbeleg.js";import{schwaerzeFelder as fo}from"../geheimnis-filter.js";import{VERDACHT_TAG as $t,mitVerdachtTag as go,pruefeFelder as mo,verdachtsWarnung as po}from"../tuersteher.js";import{fuerEigenenSpeicher as Pe,hinweise as Je,istMarkiert as es,markiert as wo,markierungsWarnung as ts,markierungsWarnungAusRohwert as ss,zaehlHinweise as ns}from"../schreibtor.js";import{istBlossesThema as os}from"../blosses-thema.js";import{zeitpunkt as _e}from"../zeitmessung.js";const Ze=(()=>{try{const O=St(import.meta.url);for(const R of["../../../package.json","../../package.json"])try{const F=O(R);if(F.name==="@cachly-dev/mcp-server"&&F.version)return F.version}catch{}}catch{}return"0.10.100"})(),yo=()=>{try{return St(import.meta.url)("../../../CACHLY_CAPABILITIES.json").mcp?.total_tools??null}catch{}return null},_o={"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${Ze}:**`," \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"]},Ca=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"]),bo=ho("/billing","upgrade"),as=new Map,is=new Set,$o=1680*60*60;function ko(O=new Date){return`cachly:quota:recalls:${O.toISOString().slice(0,7)}`}async function kt(O){try{const R=ko();await O.incr(R)===1&&await O.expire(R,$o)}catch{}}function rs(O){return`cachly:stats:drei-ausgaenge:${O}`}async function vt(O,R,F){try{await O.hincrby(rs(R),F,1)}catch{}}function cs(O,R,F,ae){kt(O),_t(O,F,ae);const f={ts:new Date().toISOString(),frage:F.slice(0,200),geliefert:[]};(async()=>{const e=yt(R);await O.lpush(e,JSON.stringify(f)),await O.ltrim(e,0,Gt-1)})().catch(()=>{}),vt(O,R,"schweigen")}async function ls(O){const R={tage:0,rekord:0};try{const F=await O.get("cachly:streak:current"),ae=P(F,null),f=new Date().toISOString().slice(0,10);if(ae){const e=ae.last_date,h=new Date(Date.now()-864e5).toISOString().slice(0,10);e===f?(R.tage=ae.days,R.rekord=ae.record):e===h?(R.tage=ae.days+1,R.rekord=Math.max(R.tage,ae.record),await O.set("cachly:streak:current",JSON.stringify({days:R.tage,last_date:f,record:R.rekord}))):(R.tage=1,R.rekord=ae.record,await O.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:R.rekord})))}else R.tage=1,R.rekord=1,await O.set("cachly:streak:current",JSON.stringify({days:1,last_date:f,record:1}))}catch{}return R}async function hs(O,R,F){await O.set("cachly:session:current",JSON.stringify({started:new Date().toISOString(),focus:R,provider:F}),"EX",86400)}async function us(O,R){const F=as.get(O);if(F&&F.expiresAt>Date.now())return F.gate;try{const ae=await R(`/api/v1/instances/${O}/memory`),f=ae?.recall_limit??-1,e=ae?.total_recall_count??0,h={reached:f>0&&e>=f,limit:f,used:e,goodwillMessage:ae?.goodwill_message,notice:ae?.notice};return as.set(O,{gate:h,expiresAt:Date.now()+6e4}),h}catch{return{reached:!1,limit:-1,used:0}}}const vo={smart_recall:"query",recall_best_solution:"topic",causal_trace:"problem"};async function xa(O,R,F,ae){const f=await So(O,R,F,ae),e=vo[O];if(e&&typeof f=="string")try{zn(String(R.instance_id??""),String(R[e]??""),f.length)}catch{}return f}async function So(O,R,F,ae){switch(O){case"learn_from_attempts":{const f=fo(R),e=mo(f.felder),h=e.length?{...f.felder,tags:go(f.felder.tags)}:f.felder,{instance_id:y,topic:n,outcome:o,what_worked:I,what_failed:b="",context:i="",severity:l="major",file_paths:a=[],commands:s=[],tags:N=[],depends_on:r=[],author:c="",visibility:x="team",service:m="",service_kind:w="service",group:L="",grund:A="",ersetzt:M="",gilt_ab:t="",gilt_fuer:ne}=h,{what_worked:le,what_failed:ue="",context:fe=""}=Xs({what_worked:I,what_failed:b,context:i}),d=await F(y),W=new Date,se=W.toISOString();let K=jt(ne,void 0);const Q=t&&!Number.isNaN(Date.parse(String(t)))?new Date(String(t)):W,J=it(le,Q),X=it(ue,Q),he=it(fe,Q),u=rt(le,Q)+rt(ue,Q)+rt(fe,Q),v=oo({uebergeben:c,umgebung:process.env.CACHLY_AUTHOR,git:no(process.env.CACHLY_WORKSPACE??process.cwd())});let _="";try{_=so(await d.get(`cachly:prefs:${eo}:${y}`))}catch{}const k=ao(v.autor,_),S=to(v);if(x!=="private"&&await Os(d,y))return Ps(d,n,{topic:n,outcome:o,what_worked:J,what_failed:X,context:he,severity:l,file_paths:a,commands:s,tags:N,depends_on:r,...K.angaben.length?{gilt_fuer:K.angaben}:{},...k?{author:k}:{},source:Ut(),...m?{service:m}:{},...L?{group:String(L).toLowerCase().trim()}:{},visibility:x,recall_count:0,ts:se,confidence:1,version:3});const z=n.split(":")[0],E=ps[z],G=[];if(E)for(const $ of E.required)$==="commands"&&s.length===0&&G.push(`\u{1F4CB} ${E.hint}`);let Y=!1,ce=0,me,Z=[];const be=await d.get(`cachly:lesson:best:${n}`),$e=String(A??"").trim();if(be&&!$e)return[`\u270B **Update abgewiesen:** \`${n}\` existiert bereits \u2014 eine Aktualisierung braucht das Feld \`grund\`.`,"","Eine Zeile genuegt: WARUM war die bisherige Fassung falsch oder unvollstaendig?",'Beispiel: grund="Die IP stimmte nicht mehr \u2014 node-4 ist seit dem Umzug Peer .7"',"","Der Diff sagt, WAS sich aendert. Die grund-Zeile sagt, warum es vorher falsch war \u2014","und genau sie wird in zwei Monaten gelesen (audit_trail, recall_best_solution)."].filter(Boolean).join(`
|
|
2
2
|
`);if(be)try{const $=JSON.parse(be);K=jt(ne,$.gilt_fuer),ce=$.recall_count??0,me=$.last_recalled_at,Z=$.audit_trail??[],Z.push({ts:se,action:"updated",prev_outcome:$.outcome,grund:$e}),Z.length>20&&(Z=Z.slice(-20)),Y=!0;const C=[];if($.outcome==="success"&&o==="failure"?C.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"&&o==="success"&&C.push("\u2705 **Conflict resolved!** Previous lesson was `failure` \u2014 now overwriting with `success`."),C.length>0){Z[Z.length-1].action="contradiction-resolved";try{const V=ge(n),T=ge(`resolution:${n}`);await ke(d,V,"contradicts",T,!1)}catch{}try{const V=`cachly:contradictions:${n}`,T=$.outcome==="success"&&o==="failure"?"kept-success":"overwrote-failure";await d.rpush(V,JSON.stringify({ts:se,prev_outcome:$.outcome,new_outcome:o,direction:T})),await d.ltrim(V,-50,-1),await d.expire(V,180*86400)}catch{}C.push(`\u{1F5F3}\uFE0F Run \`madc_deliberate(topic="${n}")\` to resolve via expert agent voting.`)}}catch{}else Z=[{ts:se,action:"created"}];const De=[];if(o==="failure"){const $=[],C=d.scanStream({match:"cachly:lesson:best:*",count:100});await new Promise((T,H)=>{C.on("data",q=>$.push(...q)),C.on("end",T),C.on("error",H)});const V=n.split(/[:\-_]/).filter(T=>T.length>2);for(const T of $.slice(0,50)){const H=await d.get(T);if(H)try{const q=JSON.parse(H);if(q.outcome!=="success")continue;const oe=(q.topic??"").split(/[:\-_]/).filter(we=>we.length>2);if(V.filter(we=>oe.includes(we)).length>=1&&q.topic!==n){De.push(`\u26A0\uFE0F **"I Was Wrong"**: lesson \`${q.topic}\` (success, ${q.severity??"major"}) might have prevented this failure.`,` \u2192 Use \`recall_best_solution(topic="${q.topic}")\` before next attempt.`,` \u2192 To mark it critical: \`learn_from_attempts(topic="${q.topic}", ..., severity="critical")\``);break}}catch{}}}for(const $ of r){const C=`cachly:dep:${$}`,V=await d.get(C),T=P(V,[]);T.includes(n)||T.push(n),await d.set(C,JSON.stringify(T),"EX",90*86400)}const pe={topic:n,outcome:o,what_worked:J,what_failed:X,context:he,severity:l,file_paths:a,commands:s,tags:N,depends_on:r,...k?{author:k}:{},source:Ut(),...m?{service:m}:{},...L?{group:String(L).toLowerCase().trim()}:{},visibility:x,recall_count:ce,...me?{last_recalled_at:me}:{},...t&&!Number.isNaN(Date.parse(String(t)))?{gilt_ab:new Date(String(t)).toISOString()}:{},...K.angaben.length?{gilt_fuer:K.angaben}:{},ts:se,verified_at:o==="success"||o==="partial"?se:void 0,confidence:1,audit_trail:Z,version:3},re=String(M??"").trim();let Ae="",Ee=null;re===n&&re?Ae="\u26A0\uFE0F `ersetzt` zeigt auf dasselbe Thema \u2014 fuer Korrekturen im selben Thema reicht das Update samt `grund`. Der Verweis wurde ignoriert.":re&&(Ee=await d.get(`cachly:lesson:best:${re}`),Ee?P(Ee,{}).ersetzt===n?(Ee=null,Ae=`\u26A0\uFE0F \`${re}\` ersetzt bereits \`${n}\` \u2014 zwei Lektionen koennen sich nicht gegenseitig ersetzen. Der Verweis wurde NICHT gespeichert. Wenn diese Fassung die neuere ist: die Kante in \`${re}\` entfernen und danach hier setzen.`):pe.ersetzt=re:Ae=`\u26A0\uFE0F Die zu ersetzende Lektion \`${re}\` existiert nicht \u2014 der Verweis wurde NICHT gespeichert. Themennamen zeigt \`smart_recall\`.`);let ee="";if(!re)try{const $=q=>{const oe=P(q.content,{});return{topic:oe.topic??q.key.slice(19),what_worked:oe.what_worked}},[C,V]=await Promise.all([tt(d,["cachly:lesson:best:*"],`${n} ${J}`.slice(0,300),5),js(d,["cachly:lesson:best:*"],a??[])]),T=new Set,H=[...C,...V].filter(q=>q.key.startsWith("cachly:lesson:best:")).filter(q=>!T.has(q.key)&&T.add(q.key)).map($);ee=rn(n,J,H)??""}catch{}if(o==="failure")try{const C=(await d.lrange(yt(y),0,199)).map(H=>P(H,{ts:"",frage:"",geliefert:[]})).filter(H=>H.ts!==""),V=(await tt(d,["cachly:lesson:best:*"],`${n} ${X||J}`.slice(0,300),5)).filter(H=>H.key.startsWith("cachly:lesson:best:")).map(H=>{const q=P(H.content,{});return{topic:q.topic??H.key.slice(19),what_worked:q.what_worked}}),T=gn(n,String(X||""),C,V);await d.hincrby(Ft(y),T,1)}catch{}const qe=mn([J,X,i].filter(Boolean).join(" ").slice(0,2e3));qe&&(pe.entscheidung=qe);const ve=uo(n,se,J);pe.beleg=ve;const Le=JSON.stringify(pe);d.set(`cachly:stats:born_at:${y}`,se,"EX",365*86400,"NX").catch(()=>{});const Re=`cachly:lessons:${n}`;await d.rpush(Re,Le),await d.ltrim(Re,-100,-1),await d.expire(Re,un*86400);let Ne=!1;if(o==="success"||o==="partial"?(await d.set(`cachly:lesson:best:${n}`,Le),Ne=!0):be||(await d.set(`cachly:lesson:best:${n}`,Le),Ne=!0),Ee&&Ne)try{const $=JSON.parse(Ee);$.ersetzt_durch=n,$.gilt_bis=se,$.ersetzt_am=se,$e&&($.ersetzt_grund=$e.slice(0,200)),await d.set(`cachly:lesson:best:${re}`,JSON.stringify($))}catch{}Ne&&Rt();let Ie=()=>{};const g=new Promise($=>{Ie=$});Ne&&ze()||Ie(null),Ne&&ze()&&(await d.sadd(Ve,n).catch(()=>{}),await d.sadd(wt,n).catch(()=>{}),(Te==="cachly"||Te==="ollama")&&await d.sadd(st,n).catch(()=>{}),(async()=>{const $=P(Le,{});try{const C=await xe(He($),{geduld:"lang"});if(C?.length?(await d.set(`${Ot}${n}`,Oe(C)),await d.srem(Ve,n).catch(()=>{}),Ie(await Bn(d,{...$,topic:n},C,bt(d).vektor))):Ie(null),Te==="cachly"||Te==="ollama")try{const V=await xe(He($),{geduld:"lang",modell:Ye});V?.length&&(await d.set(`${Ke}${n}`,Oe(V)),await d.srem(st,n).catch(()=>{}))}catch{}}catch(C){Ie(null),await d.sadd(Ve,n).catch(()=>{}),await et(d,ht,`Volltext-Vektor nicht geschrieben (${Te}): ${lt(C)} \u2014 die Lektion ist gespeichert, der Bedeutungsabgleich uebergeht sie.`)}try{const C=await xe(Pt(n),{geduld:"lang"});C?.length&&(await d.set(`${mt}${n}`,Oe(C)),await d.srem(wt,n).catch(()=>{}))}catch(C){await et(d,ht,`Namens-Vektor nicht geschrieben (${Te}): ${lt(C)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}try{await en(d,n,$,C=>xe(C,{geduld:"lang"}))}catch(C){await et(d,ht,`Eingaenge nicht geschrieben (${Te}): ${lt(C)} \u2014 siehe oben, die Lektion selbst ist gespeichert.`)}await ds(d,n,3),Ie(null)})());try{const $="cachly:session:decision-log",C=JSON.stringify({ts:se,topic:n,outcome:o,what_worked:J.slice(0,120)});await d.rpush($,C),await d.ltrim($,-50,-1)}catch{}let p=null;try{const $=ge(n),C=n.split(":")[0]??"unknown";await Fe(d,$,C,C);for(const T of N){const H=ge(`tag:${T}`);await Fe(d,H,"tag","tag"),await ke(d,$,"co-occurs",H,o==="success",o==="partial")}for(const T of r){const H=ge(T);await ke(d,$,"requires",H,!0)}if((C==="fix"||C==="debug")&&(o==="success"||o==="partial")){const T=X||he||"",H=T?ot(T):null;if(H){const q=ge(`problem:${H}`);await Fe(d,q,"problem","problem"),await ke(d,$,"fixes",q,o==="success",o==="partial")}}if(o==="failure"&&(X||J)){const H=ot(X||J);if(H){const q=ge(`cause:${H}`);await Fe(d,q,"cause","cause"),await ke(d,$,"causes",q,!1)}}if(o==="failure"){const T=await d.smembers(`cachly:ckg:idx:from:${$}`);for(const H of T){const q=await d.get(H);if(!q)continue;const oe=P(q,null);if(oe&&oe.edgeType==="fixes"&&oe.confidence>.7&&oe.trials>=3){p=`\u26A0\uFE0F **belief_conflict** on \`${n}\`: previously confirmed fix (confidence ${oe.confidence.toFixed(2)}, n=${oe.trials}) now reports failure. Both beliefs retained as \`contested\`. Use \`brain_resolve_conflict(instance_id="...", topic="${n}", winner="success"|"failure")\` to arbitrate, or \`ckg_inspect(concept="${$}")\` to review.`;const ie=`cachly:ckg:conflict:${$}`;await d.set(ie,JSON.stringify({topic:n,concept_id:$,detected_at:new Date().toISOString(),fix_confidence:oe.confidence,fix_trials:oe.trials,failure_outcome:o,reported_by:k||"unknown",what_failed:X||"",resolved:!1}),"EX",3600*24*90)}}}if(o==="success"&&(C==="fix"||C==="debug")){const T=await d.smembers(`cachly:ckg:idx:from:${$}`);for(const H of T.slice(0,10)){const q=await d.get(H);if(!q)continue;const oe=P(q,null);if(!oe||oe.edgeType!=="fixes")continue;const ie=await d.smembers(`cachly:ckg:idx:from:${oe.to}`);for(const we of ie.slice(0,5)){const je=await d.get(we);if(!je)continue;const ye=P(je,null);ye&&ye.edgeType==="co-occurs"&&(ye.successes=(ye.successes||0)+.1,ye.trials=(ye.trials||0)+.1,ye.confidence=(ye.successes+1)/(ye.trials+2),ye.last_updated=new Date().toISOString(),await d.set(we,JSON.stringify(ye)))}}}if(Math.random()<.01){const T=Date.now()-7776e6,H=await d.smembers(`cachly:ckg:idx:from:${$}`);for(const q of H){const oe=await d.get(q);if(!oe)continue;const ie=P(oe,null);ie&&ie.trials<3&&ie.last_updated&&new Date(ie.last_updated).getTime()<T&&(ie.confidence=ie.confidence*.9,ie.last_updated=new Date().toISOString(),await d.set(q,JSON.stringify(ie)))}}}catch{}if(k){d.set(`cachly:agents:active:${k}`,JSON.stringify({author:k,last_topic:n,last_outcome:o,ts:new Date().toISOString()}),"EX",3600).catch(()=>{});try{const $=n.split(":")[0]??"unknown",C=await $s(d,Qt(k),$),V=ge(n);await ke(d,C,"authored",V,o==="success",o==="partial");for(const T of a.slice(0,8)){const H=await xt(d,T);await ke(d,C,"touched",H,!0),await ks(d,H,C)}}catch{}}if(m&&typeof m=="string"&&m.trim())try{const $=n.split(":")[0]??"unknown",C=w==="system"?"system":"service",V=await vs(d,m.trim(),$,C),T=ge(n);if(await ke(d,T,"affects",V,o==="success",o==="partial"),k){const H=`person:${ge(Qt(k))}`;await ke(d,H,"operates",V,!0)}for(const H of a.slice(0,8)){const q=`file:${ge(H)}`;await ke(d,q,"runs_in",V,!0)}}catch{}if(k&&(o==="success"||o==="partial")){const $={topic:n,outcome:o,what_worked:J,what_failed:X??"",severity:l,author:k,file_paths:a,commands:s,tags:[...new Set([...N,"team"])],timestamp:new Date().toISOString(),recall_count:0,version:2,auto_propagated:!0},C=`cachly:lessons:${n}`;d.rpush(C,JSON.stringify($)).catch(()=>{})}const B=o==="success"?"\u2705":o==="partial"?"\u26A0\uFE0F":"\u274C",D=l==="critical"?"\u{1F534}":l==="major"?"\u{1F7E1}":"\u{1F7E2}",te=Y?"updated":"stored",j=await Dn(g);return[`${B} **Lesson ${te}:** \`${n}\` (${o}) ${D} ${l} \xB7 Beleg: \`${ve}\``,f.funde.length?`\u{1F512} **${f.funde.length} Geheimnis(se) geschwaerzt** vor dem Speichern (${f.funde.join("; ")}). Der Wert ist nicht im Brain \u2014 verweise kuenftig auf den Ort (z. B. Infisical-Pfad oder Variablenname).`:"",po(e),p??"","",`**What worked:** ${J}`,X?`**What failed:** ${X}`:"",he?`**Context:** ${he}`:"",a.length>0?`**Files:** ${a.map($=>`\`${$}\``).join(", ")}`:"",s.length>0?`**Commands:** ${s.map($=>`\`${$}\``).join(", ")}`:"",N.length>0?`**Tags:** ${N.map($=>`#${$}`).join(" ")}`:"","",Y?`\u267B\uFE0F Updated (recall count: ${ce} \xB7 audit entries: ${Z.length})`:`\u{1F4A1} Recall later with \`recall_best_solution(topic="${n}")\``,k&&(o==="success"||o==="partial")?`\u{1F465} Auto-shared with team (by _${k}_${v.quelle!=="uebergeben"?` \xB7 aus ${v.quelle}`:""}) \u2014 visible in \`team_recall\``:"",S??"",r.length>0?`\u{1F517} Depends on: ${r.map($=>`\`${$}\``).join(", ")} \u2192 trace with \`trace_dependency\``:"",ee,Ln(j,ee),K.angaben.length?`\u{1F4E6} Gilt fuer ${K.angaben.map($=>`\`${$}\``).join(", ")}${K.uebernommen?" (aus der Vorfassung uebernommen)":""} \u2014 passt das Projekt nicht, steht die Lektion im Abruf hinten und ist markiert.`:"",...K.fehler.map($=>`\u26A0\uFE0F gilt_fuer nicht gespeichert, ${$}. Form: paket@bereich, zum Beispiel next@<15 oder python:fastapi@>=0.100 <0.110.`),Ee&&Ne?$e?`\u21B7 Ersetzt \`${re}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin samt Grund.`:`\u21B7 Ersetzt \`${re}\` \u2014 die alte Fassung wird im Abruf verdraengt und nennt ihre Nachfolgerin. Ohne \`grund\` steht dort 'Grund nicht erfasst' \u2014 eine Zeile (warum die alte falsch war) macht den Verweis pruefbar.`:Ae,...G,...De,u>0?`\u{1F5D3}\uFE0F ${u} relative Zeitangabe${u===1?"":"n"} datiert (z. B. "gestern" \u2192 "gestern (${new Date(W.getTime()-864e5).toISOString().slice(0,10)})") \u2014 der Originaltext bleibt unveraendert, das Datum steht daneben.`:"",ro(J)??""].filter($=>$!=="").join(`
|
|
3
3
|
`)}case"lesson_verified":{const{instance_id:f}=R,e=await F(f),h=new Date().toISOString(),y=R,n=Pe({geprueft_mit:y.geprueft_mit,befund:y.befund}),o=_s({...y,...n.felder},h);if(!o.ok)return[`\u26A0\uFE0F ${o.grund}`,"","Beispiel:","```",'lesson_verified(topic="deploy:bau-hero-node1", haelt=true,',' geprueft_mit="curl -s http://127.0.0.1:3220/bereit")',"```","Bei haelt=false gehoert `befund` dazu: was hast du stattdessen gesehen?"].join(`
|
|
4
4
|
`);const I=o.eintrag,b=`cachly:lesson:best:${I.topic}`,i=await e.get(b);if(!i)return`\u{1F4ED} Keine Lektion \`${I.topic}\` \u2014 nichts zu pruefen. Tippfehler im Themennamen?`;const l=P(i,{}),a=bs(l,I);return await e.set(b,JSON.stringify(n.verdacht.length?{...a,tags:wo(a.tags,n.verdacht)}:a)),Rt(),I.haelt?[`\u2705 \`${I.topic}\` ist wieder frisch \u2014 geprueft am ${h.slice(0,10)}.`,I.geprueft_mit?` geprueft mit: \`${I.geprueft_mit}\``:"","","Das ist die einzige Handlung, die `verified_at` setzt. Ein Abruf tut es nicht.",...Je(n)].filter(Boolean).join(`
|
|
@@ -15,7 +15,7 @@ ${c.join(`
|
|
|
15
15
|
|
|
16
16
|
${a.join(`
|
|
17
17
|
|
|
18
|
-
`)}`}case"smart_recall":{const f=Date.now(),{instance_id:e,query:h,threshold:y=.78,author:n="",context_files:o=[],limit:I}=R,b=Kn(I),i=Array.isArray(o)?o.filter(g=>typeof g=="string"):[];if(_e("smart_recall: Anfang"),await Bt(e,ae)){const g=Date.now()-f;return F(e).then(p=>cs(p,e,String(h??""),g)).catch(()=>{}),_e("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),zt(String(h??""),{startet:!0,...gt(e)})}const l=await F(e);_e("smart_recall: Verbindung steht");const{vektor:a,namen:s,zweit:N,eingang:r,seltenheit:c}=bt(l);ds(l,void 0,2);let x=new Set,m=!1;n&&(x=await Mt(l,e,n).catch(()=>new Set),m=await dt(l,e,n).catch(()=>null)==="admin");const w=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],L=await Gs(l,w);if(!L)return cs(l,e,String(h??""),Date.now()-f),_e("smart_recall: Brain leer \u2014 sofort geantwortet"),zt(String(h??""),{startet:!1,...gt(e)});const A=L.docs.reduce((g,p)=>g+(p.key.startsWith("cachly:lesson:best:")?1:0),0),M=await tt(l,w,h,25);_e(`smart_recall: Wortsuche fertig (${M.length} Treffer)`);const t=Vs(M);let ne=!1,le=null;const ue=await(async()=>{if(!ze())return ct(Es,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),t;try{if(await a.aktualisiere(l),_e(`smart_recall: Vektorbestand geladen (${a.groesse})`),a.groesse===0)return A>0&&ct(As,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),t;const g=await xe(h);if(_e("smart_recall: Frage eingebettet"),!g?.length)return ct(Is,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),t;await s.aktualisiere(l),await r.aktualisiere(l),await c.aktualisiere(l),await N.aktualisiere(l);const p=a.groesse>0?N.groesse/a.groesse:0;p<Jt&&a.groesse>0&&Co(l,3);const B=p>=Jt?xe(h,{modell:Ye}).catch(()=>null):null,D=t.filter(U=>U.key.startsWith("cachly:lesson:best:")).map(U=>U.key.slice(19)),te=U=>Math.max(a.naehe(g,U),s.naehe(g,U)),j=[...c.themen()],$=(j.length>0?j:a.aehnlichste(g,500).map(U=>U.topic)).map(U=>({t:U,n:te(U)})).sort((U,de)=>de.n-U.n).slice(0,Zt).map(U=>U.t),C=[...new Set([...D,...$])],V=$.slice(0,3).map(U=>a.rohvektor(U)).filter(Boolean),T=V.length?wn(g,V):g,H=Vt(h),q=c.statistik,oe=C.map(U=>{const de=new Set([...Vt(c.textVon(U))].map(yn));return{naeheText:a.naehe(g,U),naeheThema:s.naehe(g,U),naeheRueckkopplung:a.naehe(T,U),seltenheitsDeckung:q?q.deckung(H,de):0,besterZeuge:q?q.besterZeuge(H,de):0}});let ie=pn(oe,_n);{const U=[...ie].sort((de,Se)=>Se-de);le=U.length>1?U[0]-U[1]:null}if(r.groesse>0){const U=C.map(Se=>{const Ce=r.besteNaehe(g,Se);return Ce>=Wn?Ce:-2}),de=Ht(U);ie=ie.map((Se,Ce)=>Se+Fn*de[Ce])}if(B){const U=await B;if(U?.length){const de=Ht(C.map(Se=>N.naehe(U,Se)));ie=ie.map((Se,Ce)=>Se+En*de[Ce])}}let we=C.map((U,de)=>({t:U,p:ie[de]})).sort((U,de)=>de.p-U.p).map(U=>U.t);if(Us(e)&&we.length>1){const U=we.slice(0,qt),de=we.slice(qt),Se=new Map(C.map((Xe,Ue)=>[Xe,ie[Ue]]));_e("smart_recall: Leser Anfang");const Ce=await Ys(h,U.map(Xe=>c.leserTextVon(Xe)),{instanceId:e});_e(`smart_recall: Leser ${Ce?"fertig":"ohne Ergebnis"}`),Ce&&(we=[...Zs(U.map(Ue=>Se.get(Ue)??0),Ce).map(Ue=>U[Ue]),...de])}const je=new Map(t.map(U=>[U.key,U])),ye=[];for(const U of we){const de=`cachly:lesson:best:${U}`,Se=je.get(de);if(Se){ye.push(Se),je.delete(de);continue}const Ce=await l.get(de).catch(()=>null);Ce&&ye.push({key:de,content:Ce,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return ye.push(...je.values()),xn&&Cn({frage:h.slice(0,200),themen:C,ausWortsuche:D.length,ausSinnsuche:$.length,obergrenze:Zt,gezeigt:we.slice(0,10)}),ne=!0,ye}catch(g){return await et(l,Ms,`der Bedeutungspfad brach ab (${g instanceof Error?g.message:String(g)}) \u2014 diese Suche lief nur ueber Woerter`),t}})();_e("smart_recall: Bedeutungspfad fertig"),kt(l),_t(l,String(h??""),Date.now()-f);{const g=ue.filter(p=>p.key.startsWith("cachly:lesson:best:")).slice(0,3).map(p=>p.key.slice(19));if(g.length>0){const p={ts:new Date().toISOString(),themen:g};(async()=>{const B=Wt(e);await l.lpush(B,JSON.stringify(p)),await l.ltrim(B,0,fn-1)})().catch(()=>{})}{const p={ts:new Date().toISOString(),frage:h.slice(0,200),geliefert:g};(async()=>{const B=yt(e);await l.lpush(B,JSON.stringify(p)),await l.ltrim(B,0,Gt-1)})().catch(()=>{})}}if(ze()&&!It()){const g=ue.filter(p=>p.key.startsWith("cachly:lesson:best:")).slice(0,3).map(p=>p.key.slice(19));an(l,h,g,xe).catch(()=>{})}const fe=[],d=ue.filter(g=>g.key.startsWith("cachly:lesson:best:"));let W=0,se=0;for(const g of d.slice(0,5)){const p=await l.get(g.key).catch(()=>null);if(p){const B=P(p,null);if(B?.state==="archived")continue;if(B){const D=new Date().toISOString(),te={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:D};It()||l.set(g.key,JSON.stringify(te)).catch(()=>{});const j=Nt(B)?Tt(B):0;if(j>0&&l.incrbyfloat(`cachly:stats:time_saved_mins:${e}`,j).catch(()=>{}),B.author&&n&&B.author!==n){W++,l.sadd(`cachly:stats:reuse_pairs:${e}`,`${n}<-${B.author}`).catch(()=>{});const $=`person:${ge(n)}`,C=`person:${ge(B.author)}`;ke(l,$,"collaborates",C,!0).catch(()=>{}),ke(l,C,"collaborates",$,!0).catch(()=>{})}B.outcome==="success"&&se++,B.outcome==="success"&&(B.recall_count??0)>=1&&!at(B)&&fe.push({topic:g.key.replace("cachly:lesson:best:",""),severity:B.severity??"major",recall_count:(B.recall_count??0)+1,savedMins:j,ts:B.ts,author:B.author})}}}se>0&&l.set(`cachly:stats:first_recall_at:${e}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),d.length>0&&(l.incr(`cachly:stats:recalls_total:${e}`).catch(()=>{}),W>0&&l.incr(`cachly:stats:cross_author_recalls:${e}`).catch(()=>{})),_e("smart_recall: Treffer gezaehlt");const K=await ae(`/api/v1/instances/${e}`).catch(()=>null);_e("smart_recall: Tarif abgefragt");const Q=!K?.tier||K.tier.toLowerCase()==="free",J=[];if(!Q&&K?.vector_token&&ze())try{const g=await xe(h),p=`https://api.cachly.dev/v1/sem/${K.vector_token}`,B=await fetch(`${p}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:g,namespace:"cachly:ctx",threshold:y,top_k:5}),signal:AbortSignal.timeout(8e3)});if(B.ok){const D=await B.json();for(const te of D.filter(j=>j.found&&j.id)){const j=te.id.replace("ctx:","").split(":"),$=j[0],C=j.slice(1).join(":"),V=`cachly:ctx:${$}:${C}`,T=await l.get(V).catch(()=>null);J.push({key:V,similarity:te.similarity??0,content:T??"(evicted)"})}}}catch{}const X=ue.map(g=>g.score),he=X.length?Math.min(...X):0,u=X.length&&Math.max(...X)-he||1,v=g=>(g-he)/u,_=new Map,k=ne?nn(ue.map(g=>v(g.score))):null,S=new Map;for(const[g,p]of ue.entries()){const B=v(p.score),D=k?k[g]:B;k&&_.set(p.key,g),S.set(p.key,{key:p.key,content:p.content,bm25Score:B,hausWert:D,hybridScore:D*(J.length>0?.7:1),matchedWords:p.matchedWords,matchType:"keyword",subQuery:p.subQuery,wortBelege:p.wortBelege})}for(const g of J){const p=S.get(g.key);p?(p.semScore=g.similarity,p.hybridScore=(p.hausWert??0)*.6+g.similarity*.4,p.matchType="hybrid"):S.set(g.key,{key:g.key,content:g.content,semScore:g.similarity,hybridScore:g.similarity*.5,matchType:"semantic"})}try{const g=ft(h).filter(D=>D.length>=4).slice(0,4),p=new Set;for(const D of g){const te=l.scanStream({match:`cachly:ckg:node:*${D}*`,count:20});await new Promise((j,$)=>{te.on("data",C=>{for(const V of C.slice(0,5))p.add(V.replace("cachly:ckg:node:",""))}),te.on("end",j),te.on("error",$)})}const B=new Set;for(const D of[...p].slice(0,12)){const te=await l.smembers(`cachly:ckg:idx:to:${D}`);for(const j of te.slice(0,6)){const $=await l.get(j);if(!$)continue;const C=P($,null);if(!C||C.edgeType!=="fixes"||C.confidence<.35||B.has(C.from))continue;B.add(C.from);const V=`cachly:lesson:best:${C.from}`,T=S.get(V);if(T)T.ckgScore=Math.max(T.ckgScore??0,C.confidence),T.hybridScore=T.hybridScore*.88+C.confidence*.12,T.matchType==="keyword"&&(T.matchType="hybrid");else{const H=await l.get(V).catch(()=>null);if(!H)continue;S.set(V,{key:V,content:H,ckgScore:C.confidence,hybridScore:C.confidence*.3,matchType:"ckg"})}}}}catch{}if(_e("smart_recall: Sinn-Dienst und CKG fertig"),i.length>0){const g=new Set(i.map(p=>p.replace(/\\/g,"/")));for(const p of S.values()){if(!p.key.startsWith("cachly:lesson:best:"))continue;const B=P(p.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(te=>typeof te=="string").map(te=>te.replace(/\\/g,"/")):[]).some(te=>g.has(te))&&(p.hybridScore*=1.15,p.contextBoost=!0)}}for(const g of S.values()){if(g.matchType!=="semantic"&&g.matchType!=="ckg")continue;const p=qs({key:g.key,content:g.content});p&&(g.hybridScore*=Js(p))}const z=[...S.values()].filter(g=>{if(!g.key.startsWith("cachly:lesson:best:"))return!0;const p=Be(g.content);return!(!Ge(p)||!Lt(p?.group,x,m))}),E=k?sn(z,_):z.sort((g,p)=>p.hybridScore-g.hybridScore),G=[];for(const g of E){if(!g.key.startsWith("cachly:lesson:best:"))continue;const p=P(g.content,{});p.gilt_bis&&Date.parse(String(p.gilt_bis))<Date.now()&&G.push(`\u23F3 \`${g.key.replace("cachly:lesson:best:","")}\` galt bis ${String(p.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const B=P(g.content,{});if(B.pruefung_gefallen_am){const D=g.key.replace("cachly:lesson:best:",""),te=String(B.pruefung_gefallen_am).slice(0,10),j=String(B.pruefung_befund??"").trim().slice(0,200);G.push(`\u274C \`${D}\` \u2014 Pruefung am ${te} FEHLGESCHLAGEN`+(j?`: ${j}`:""))}}{const g=new Set(E.map(p=>p.key));for(let p=E.length-1;p>=0;p--){const B=E[p];if(!B.key.startsWith("cachly:lesson:best:"))continue;const D=P(B.content,{});if(!D.ersetzt_durch)continue;const te=String(D.ersetzt_grund??"").trim(),j=B.key.replace("cachly:lesson:best:","");if(g.has(`cachly:lesson:best:${D.ersetzt_durch}`))E.splice(p,1),G.push(`\u21B7 \`${j}\` verdraengt \u2014 ersetzt durch \`${D.ersetzt_durch}\`${D.ersetzt_am?` am ${D.ersetzt_am.slice(0,10)}`:""}${te?` \u2014 Grund: ${te}`:" \u2014 Grund nicht erfasst"}`);else if(await l.get(`cachly:lesson:best:${D.ersetzt_durch}`)){const $=Be(await l.get(`cachly:lesson:best:${D.ersetzt_durch}`));Ge($)?G.push(`\u26A0\uFE0F \`${j}\` ist ersetzt durch \`${D.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${D.ersetzt_durch}")\``):G.push(`\u21B7 \`${j}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else G.push(`\u21A9\uFE0F \`${j}\` war ersetzt durch \`${D.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const Y=cn(E,i),ce=[];{await a.aktualisiere(l).catch(()=>{});const g=E.slice(0,8).filter(p=>p.key.startsWith("cachly:lesson:best:"));for(let p=0;p<g.length;p++)for(let B=p+1;B<g.length;B++){const D=g[p].key.replace("cachly:lesson:best:",""),te=g[B].key.replace("cachly:lesson:best:",""),j=a.rohvektor(D),$=a.rohvektor(te);if(!j||!$)continue;let C=0,V=0,T=0;for(let oe=0;oe<j.length;oe++)C+=j[oe]*$[oe],V+=j[oe]*j[oe],T+=$[oe]*$[oe];if((V>0&&T>0?C/(Math.sqrt(V)*Math.sqrt(T)):0)<In)continue;const q=oe=>{const ie=P(oe??"",{});return String(ie.verified_at??ie.ts??"").slice(0,10)||"ohne Datum"};ce.push(`\u26A0\uFE0F \`${D}\` (${q(g[p].content)}) und \`${te}\` (${q(g[B].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}ce.length>3&&(ce.length=3)}if(G.push(...ce),E.length>=2){const g=E[0].hybridScore,p=E[Math.min(4,E.length-1)].hybridScore,B=Math.max(0,g-p);(async()=>{try{await l.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:E.length})),await l.ltrim("cachly:recall:spread",0,199)}catch{}})()}const me=Ls();let Z="",be=null;if(me!==null){Z=Rs();const g=E[0]?.hybridScore??0,p=Ds(E.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),Z,me,g);p.weggelassenesThema!==void 0?E.splice(0,1):p.markierungGesetzt&&E[0]&&p.treffer[0]&&(E[0]={...E[0],content:p.treffer[0].content}),be={frage:h,hoechstePunktzahl:g,themen:[],zulassungsfaehig:p.zulassungsfaehig,zulassungsGrund:p.zulassungsGrund,zuteilung:p.zuteilung,weggelassenesThema:p.weggelassenesThema,markierungGesetzt:p.markierungGesetzt}}_e("smart_recall: Notizen und Duplikate fertig");const $e=await us(e,ae);_e("smart_recall: Abruf-Grenze abgefragt");const De=$e.reached,pe=Xt({ueberLimit:De,gesamt:E.length,volleTiefe:b??Hn}),re=process.env.CACHLY_RECALL_COMPACT==="1",Ae=(()=>{const g=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(g)?Math.min(20,Math.max(1,g)):5})(),Ee=re?Math.min(Ae,pe.sichtbar):pe.sichtbar,ee=[`\u{1F9E0} **Smart Recall** for: _"${h}"_
|
|
18
|
+
`)}`}case"smart_recall":{const f=Date.now(),{instance_id:e,query:h,threshold:y=.78,author:n="",context_files:o=[],limit:I}=R,b=Kn(I),i=Array.isArray(o)?o.filter(g=>typeof g=="string"):[];if(_e("smart_recall: Anfang"),await Bt(e,ae)){const g=Date.now()-f;return F(e).then(p=>cs(p,e,String(h??""),g)).catch(()=>{}),_e("smart_recall: neues Brain startet noch \u2014 sofort geantwortet"),zt(String(h??""),{startet:!0,...await gt(e)})}const l=await F(e);_e("smart_recall: Verbindung steht");const{vektor:a,namen:s,zweit:N,eingang:r,seltenheit:c}=bt(l);ds(l,void 0,2);let x=new Set,m=!1;n&&(x=await Mt(l,e,n).catch(()=>new Set),m=await dt(l,e,n).catch(()=>null)==="admin");const w=["cachly:ctx:*","cachly:lesson:best:*","cachly:idx:*"],L=await Gs(l,w);if(!L)return cs(l,e,String(h??""),Date.now()-f),_e("smart_recall: Brain leer \u2014 sofort geantwortet"),zt(String(h??""),{startet:!1,...await gt(e)});const A=L.docs.reduce((g,p)=>g+(p.key.startsWith("cachly:lesson:best:")?1:0),0),M=await tt(l,w,h,25);_e(`smart_recall: Wortsuche fertig (${M.length} Treffer)`);const t=Vs(M);let ne=!1,le=null;const ue=await(async()=>{if(!ze())return ct(Es,"kein Einbettungsdienst eingerichtet \u2014 die Suche laeuft nur ueber Woerter"),t;try{if(await a.aktualisiere(l),_e(`smart_recall: Vektorbestand geladen (${a.groesse})`),a.groesse===0)return A>0&&ct(As,"keine einzige Lektion hat eine Einbettung \u2014 die Suche laeuft nur ueber Woerter. Nachruesten mit eingaenge-nachruesten, pruefen mit brain_doctor"),t;const g=await xe(h);if(_e("smart_recall: Frage eingebettet"),!g?.length)return ct(Is,"die Frage liess sich nicht einbetten \u2014 diese Suche laeuft nur ueber Woerter"),t;await s.aktualisiere(l),await r.aktualisiere(l),await c.aktualisiere(l),await N.aktualisiere(l);const p=a.groesse>0?N.groesse/a.groesse:0;p<Jt&&a.groesse>0&&Co(l,3);const B=p>=Jt?xe(h,{modell:Ye}).catch(()=>null):null,D=t.filter(U=>U.key.startsWith("cachly:lesson:best:")).map(U=>U.key.slice(19)),te=U=>Math.max(a.naehe(g,U),s.naehe(g,U)),j=[...c.themen()],$=(j.length>0?j:a.aehnlichste(g,500).map(U=>U.topic)).map(U=>({t:U,n:te(U)})).sort((U,de)=>de.n-U.n).slice(0,Zt).map(U=>U.t),C=[...new Set([...D,...$])],V=$.slice(0,3).map(U=>a.rohvektor(U)).filter(Boolean),T=V.length?wn(g,V):g,H=Vt(h),q=c.statistik,oe=C.map(U=>{const de=new Set([...Vt(c.textVon(U))].map(yn));return{naeheText:a.naehe(g,U),naeheThema:s.naehe(g,U),naeheRueckkopplung:a.naehe(T,U),seltenheitsDeckung:q?q.deckung(H,de):0,besterZeuge:q?q.besterZeuge(H,de):0}});let ie=pn(oe,_n);{const U=[...ie].sort((de,Se)=>Se-de);le=U.length>1?U[0]-U[1]:null}if(r.groesse>0){const U=C.map(Se=>{const Ce=r.besteNaehe(g,Se);return Ce>=Wn?Ce:-2}),de=Ht(U);ie=ie.map((Se,Ce)=>Se+Fn*de[Ce])}if(B){const U=await B;if(U?.length){const de=Ht(C.map(Se=>N.naehe(U,Se)));ie=ie.map((Se,Ce)=>Se+En*de[Ce])}}let we=C.map((U,de)=>({t:U,p:ie[de]})).sort((U,de)=>de.p-U.p).map(U=>U.t);if(Us(e)&&we.length>1){const U=we.slice(0,qt),de=we.slice(qt),Se=new Map(C.map((Xe,Ue)=>[Xe,ie[Ue]]));_e("smart_recall: Leser Anfang");const Ce=await Ys(h,U.map(Xe=>c.leserTextVon(Xe)),{instanceId:e});_e(`smart_recall: Leser ${Ce?"fertig":"ohne Ergebnis"}`),Ce&&(we=[...Zs(U.map(Ue=>Se.get(Ue)??0),Ce).map(Ue=>U[Ue]),...de])}const je=new Map(t.map(U=>[U.key,U])),ye=[];for(const U of we){const de=`cachly:lesson:best:${U}`,Se=je.get(de);if(Se){ye.push(Se),je.delete(de);continue}const Ce=await l.get(de).catch(()=>null);Ce&&ye.push({key:de,content:Ce,score:0,matchedWords:[],wortBelege:0,finalScore:0,qualityBoost:1})}return ye.push(...je.values()),xn&&Cn({frage:h.slice(0,200),themen:C,ausWortsuche:D.length,ausSinnsuche:$.length,obergrenze:Zt,gezeigt:we.slice(0,10)}),ne=!0,ye}catch(g){return await et(l,Ms,`der Bedeutungspfad brach ab (${g instanceof Error?g.message:String(g)}) \u2014 diese Suche lief nur ueber Woerter`),t}})();_e("smart_recall: Bedeutungspfad fertig"),kt(l),_t(l,String(h??""),Date.now()-f);{const g=ue.filter(p=>p.key.startsWith("cachly:lesson:best:")).slice(0,3).map(p=>p.key.slice(19));if(g.length>0){const p={ts:new Date().toISOString(),themen:g};(async()=>{const B=Wt(e);await l.lpush(B,JSON.stringify(p)),await l.ltrim(B,0,fn-1)})().catch(()=>{})}{const p={ts:new Date().toISOString(),frage:h.slice(0,200),geliefert:g};(async()=>{const B=yt(e);await l.lpush(B,JSON.stringify(p)),await l.ltrim(B,0,Gt-1)})().catch(()=>{})}}if(ze()&&!It()){const g=ue.filter(p=>p.key.startsWith("cachly:lesson:best:")).slice(0,3).map(p=>p.key.slice(19));an(l,h,g,xe).catch(()=>{})}const fe=[],d=ue.filter(g=>g.key.startsWith("cachly:lesson:best:"));let W=0,se=0;for(const g of d.slice(0,5)){const p=await l.get(g.key).catch(()=>null);if(p){const B=P(p,null);if(B?.state==="archived")continue;if(B){const D=new Date().toISOString(),te={...B,recall_count:(B.recall_count??0)+1,last_recalled_at:D};It()||l.set(g.key,JSON.stringify(te)).catch(()=>{});const j=Nt(B)?Tt(B):0;if(j>0&&l.incrbyfloat(`cachly:stats:time_saved_mins:${e}`,j).catch(()=>{}),B.author&&n&&B.author!==n){W++,l.sadd(`cachly:stats:reuse_pairs:${e}`,`${n}<-${B.author}`).catch(()=>{});const $=`person:${ge(n)}`,C=`person:${ge(B.author)}`;ke(l,$,"collaborates",C,!0).catch(()=>{}),ke(l,C,"collaborates",$,!0).catch(()=>{})}B.outcome==="success"&&se++,B.outcome==="success"&&(B.recall_count??0)>=1&&!at(B)&&fe.push({topic:g.key.replace("cachly:lesson:best:",""),severity:B.severity??"major",recall_count:(B.recall_count??0)+1,savedMins:j,ts:B.ts,author:B.author})}}}se>0&&l.set(`cachly:stats:first_recall_at:${e}`,new Date().toISOString(),"EX",365*86400,"NX").catch(()=>{}),d.length>0&&(l.incr(`cachly:stats:recalls_total:${e}`).catch(()=>{}),W>0&&l.incr(`cachly:stats:cross_author_recalls:${e}`).catch(()=>{})),_e("smart_recall: Treffer gezaehlt");const K=await ae(`/api/v1/instances/${e}`).catch(()=>null);_e("smart_recall: Tarif abgefragt");const Q=!K?.tier||K.tier.toLowerCase()==="free",J=[];if(!Q&&K?.vector_token&&ze())try{const g=await xe(h),p=`https://api.cachly.dev/v1/sem/${K.vector_token}`,B=await fetch(`${p}/search`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedding:g,namespace:"cachly:ctx",threshold:y,top_k:5}),signal:AbortSignal.timeout(8e3)});if(B.ok){const D=await B.json();for(const te of D.filter(j=>j.found&&j.id)){const j=te.id.replace("ctx:","").split(":"),$=j[0],C=j.slice(1).join(":"),V=`cachly:ctx:${$}:${C}`,T=await l.get(V).catch(()=>null);J.push({key:V,similarity:te.similarity??0,content:T??"(evicted)"})}}}catch{}const X=ue.map(g=>g.score),he=X.length?Math.min(...X):0,u=X.length&&Math.max(...X)-he||1,v=g=>(g-he)/u,_=new Map,k=ne?nn(ue.map(g=>v(g.score))):null,S=new Map;for(const[g,p]of ue.entries()){const B=v(p.score),D=k?k[g]:B;k&&_.set(p.key,g),S.set(p.key,{key:p.key,content:p.content,bm25Score:B,hausWert:D,hybridScore:D*(J.length>0?.7:1),matchedWords:p.matchedWords,matchType:"keyword",subQuery:p.subQuery,wortBelege:p.wortBelege})}for(const g of J){const p=S.get(g.key);p?(p.semScore=g.similarity,p.hybridScore=(p.hausWert??0)*.6+g.similarity*.4,p.matchType="hybrid"):S.set(g.key,{key:g.key,content:g.content,semScore:g.similarity,hybridScore:g.similarity*.5,matchType:"semantic"})}try{const g=ft(h).filter(D=>D.length>=4).slice(0,4),p=new Set;for(const D of g){const te=l.scanStream({match:`cachly:ckg:node:*${D}*`,count:20});await new Promise((j,$)=>{te.on("data",C=>{for(const V of C.slice(0,5))p.add(V.replace("cachly:ckg:node:",""))}),te.on("end",j),te.on("error",$)})}const B=new Set;for(const D of[...p].slice(0,12)){const te=await l.smembers(`cachly:ckg:idx:to:${D}`);for(const j of te.slice(0,6)){const $=await l.get(j);if(!$)continue;const C=P($,null);if(!C||C.edgeType!=="fixes"||C.confidence<.35||B.has(C.from))continue;B.add(C.from);const V=`cachly:lesson:best:${C.from}`,T=S.get(V);if(T)T.ckgScore=Math.max(T.ckgScore??0,C.confidence),T.hybridScore=T.hybridScore*.88+C.confidence*.12,T.matchType==="keyword"&&(T.matchType="hybrid");else{const H=await l.get(V).catch(()=>null);if(!H)continue;S.set(V,{key:V,content:H,ckgScore:C.confidence,hybridScore:C.confidence*.3,matchType:"ckg"})}}}}catch{}if(_e("smart_recall: Sinn-Dienst und CKG fertig"),i.length>0){const g=new Set(i.map(p=>p.replace(/\\/g,"/")));for(const p of S.values()){if(!p.key.startsWith("cachly:lesson:best:"))continue;const B=P(p.content,{});(Array.isArray(B.file_paths)?B.file_paths.filter(te=>typeof te=="string").map(te=>te.replace(/\\/g,"/")):[]).some(te=>g.has(te))&&(p.hybridScore*=1.15,p.contextBoost=!0)}}for(const g of S.values()){if(g.matchType!=="semantic"&&g.matchType!=="ckg")continue;const p=qs({key:g.key,content:g.content});p&&(g.hybridScore*=Js(p))}const z=[...S.values()].filter(g=>{if(!g.key.startsWith("cachly:lesson:best:"))return!0;const p=Be(g.content);return!(!Ge(p)||!Lt(p?.group,x,m))}),E=k?sn(z,_):z.sort((g,p)=>p.hybridScore-g.hybridScore),G=[];for(const g of E){if(!g.key.startsWith("cachly:lesson:best:"))continue;const p=P(g.content,{});p.gilt_bis&&Date.parse(String(p.gilt_bis))<Date.now()&&G.push(`\u23F3 \`${g.key.replace("cachly:lesson:best:","")}\` galt bis ${String(p.gilt_bis).slice(0,10)} \u2014 Geschichte, keine aktuelle Tatsache.`);const B=P(g.content,{});if(B.pruefung_gefallen_am){const D=g.key.replace("cachly:lesson:best:",""),te=String(B.pruefung_gefallen_am).slice(0,10),j=String(B.pruefung_befund??"").trim().slice(0,200);G.push(`\u274C \`${D}\` \u2014 Pruefung am ${te} FEHLGESCHLAGEN`+(j?`: ${j}`:""))}}{const g=new Set(E.map(p=>p.key));for(let p=E.length-1;p>=0;p--){const B=E[p];if(!B.key.startsWith("cachly:lesson:best:"))continue;const D=P(B.content,{});if(!D.ersetzt_durch)continue;const te=String(D.ersetzt_grund??"").trim(),j=B.key.replace("cachly:lesson:best:","");if(g.has(`cachly:lesson:best:${D.ersetzt_durch}`))E.splice(p,1),G.push(`\u21B7 \`${j}\` verdraengt \u2014 ersetzt durch \`${D.ersetzt_durch}\`${D.ersetzt_am?` am ${D.ersetzt_am.slice(0,10)}`:""}${te?` \u2014 Grund: ${te}`:" \u2014 Grund nicht erfasst"}`);else if(await l.get(`cachly:lesson:best:${D.ersetzt_durch}`)){const $=Be(await l.get(`cachly:lesson:best:${D.ersetzt_durch}`));Ge($)?G.push(`\u26A0\uFE0F \`${j}\` ist ersetzt durch \`${D.ersetzt_durch}\` (nicht in dieser Liste) \u2014 die gueltige Antwort: \`recall_best_solution(topic="${D.ersetzt_durch}")\``):G.push(`\u21B7 \`${j}\`: von einer nicht team-sichtbaren Fassung ersetzt \u2014 diese Fassung bleibt die beste sichtbare Antwort.`)}else G.push(`\u21A9\uFE0F \`${j}\` war ersetzt durch \`${D.ersetzt_durch}\` \u2014 der Nachfolger wurde geloescht, diese Fassung gilt wieder (bei Gelegenheit neu bestaetigen).`)}}const Y=cn(E,i),ce=[];{await a.aktualisiere(l).catch(()=>{});const g=E.slice(0,8).filter(p=>p.key.startsWith("cachly:lesson:best:"));for(let p=0;p<g.length;p++)for(let B=p+1;B<g.length;B++){const D=g[p].key.replace("cachly:lesson:best:",""),te=g[B].key.replace("cachly:lesson:best:",""),j=a.rohvektor(D),$=a.rohvektor(te);if(!j||!$)continue;let C=0,V=0,T=0;for(let oe=0;oe<j.length;oe++)C+=j[oe]*$[oe],V+=j[oe]*j[oe],T+=$[oe]*$[oe];if((V>0&&T>0?C/(Math.sqrt(V)*Math.sqrt(T)):0)<In)continue;const q=oe=>{const ie=P(oe??"",{});return String(ie.verified_at??ie.ts??"").slice(0,10)||"ohne Datum"};ce.push(`\u26A0\uFE0F \`${D}\` (${q(g[p].content)}) und \`${te}\` (${q(g[B].content)}) sagen fast dasselbe \u2014 prueft, welche Fassung fuer euren Fall gilt; die neuere ist nicht automatisch die richtige.`)}ce.length>3&&(ce.length=3)}if(G.push(...ce),E.length>=2){const g=E[0].hybridScore,p=E[Math.min(4,E.length-1)].hybridScore,B=Math.max(0,g-p);(async()=>{try{await l.lpush("cachly:recall:spread",JSON.stringify({ts:new Date().toISOString(),spread:Number(B.toFixed(4)),n:E.length})),await l.ltrim("cachly:recall:spread",0,199)}catch{}})()}const me=Ls();let Z="",be=null;if(me!==null){Z=Rs();const g=E[0]?.hybridScore??0,p=Ds(E.map(B=>({key:B.key,content:B.content,punktzahl:B.hybridScore})),Z,me,g);p.weggelassenesThema!==void 0?E.splice(0,1):p.markierungGesetzt&&E[0]&&p.treffer[0]&&(E[0]={...E[0],content:p.treffer[0].content}),be={frage:h,hoechstePunktzahl:g,themen:[],zulassungsfaehig:p.zulassungsfaehig,zulassungsGrund:p.zulassungsGrund,zuteilung:p.zuteilung,weggelassenesThema:p.weggelassenesThema,markierungGesetzt:p.markierungGesetzt}}_e("smart_recall: Notizen und Duplikate fertig");const $e=await us(e,ae);_e("smart_recall: Abruf-Grenze abgefragt");const De=$e.reached,pe=Xt({ueberLimit:De,gesamt:E.length,volleTiefe:b??Hn}),re=process.env.CACHLY_RECALL_COMPACT==="1",Ae=(()=>{const g=Number.parseInt(process.env.CACHLY_RECALL_COMPACT_HITS??"",10);return Number.isFinite(g)?Math.min(20,Math.max(1,g)):5})(),Ee=re?Math.min(Ae,pe.sichtbar):pe.sichtbar,ee=[`\u{1F9E0} **Smart Recall** for: _"${h}"_
|
|
19
19
|
`];$e.goodwillMessage&&ee.push(`${$e.goodwillMessage}
|
|
20
20
|
`);const qe={critical:0,major:1,minor:2},ve=fe.sort((g,p)=>(qe[g.severity]??1)-(qe[p.severity]??1))[0];if(ve){const g=j=>j>=60?`${j/60}h`:`${j}min`,p=(()=>{if(!ve.ts)return null;const j=new Date(ve.ts);if(isNaN(j.getTime()))return null;const $=new Date,C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return j.getFullYear()===$.getFullYear()?`${j.getDate()} ${C[j.getMonth()]}`:`${j.getDate()} ${C[j.getMonth()]} ${j.getFullYear()}`})(),B=ve.severity==="critical"?120:ve.severity==="major"?60:20,D=ve.author&&ve.author!==n?` \xB7 by @${ve.author}`:"",te=p?` \xB7 learned ${p} (was a ${g(B)} debug)`:"";ee.push(`> \u{1F4A1} **Brain saved you ~${g(ve.savedMins)} here** \u2014 \`${ve.topic}\`${te} \xB7 recalled ${ve.recall_count}\xD7${D}
|
|
21
21
|
`)}W>0&&ee.push(`> \u{1F465} **Team knowledge reuse** \u2014 ${W} of these lesson${W!==1?"s were":" was"} written by a teammate. This is the value only a shared brain delivers.
|
|
@@ -30,7 +30,7 @@ ${a.join(`
|
|
|
30
30
|
`)}}else{ee.push(`\u26A0\uFE0F No matches found for: "${h}"`),G.length>0&&ee.push("",...G.map(B=>`> ${B}`));const g=ft(h),p=[];if(Dt.size>0&&g.length>0)for(const B of g.slice(0,3)){if(B.length<4)continue;let D=3,te="";for(const j of Dt){if(j.length<3||Math.abs(j.length-B.length)>4)continue;const $=Fs(B,j);$>0&&$<D&&(D=$,te=j)}te&&p.push(`"${te}" (instead of "${B}")`)}p.length>0?ee.push(`\u{1F4A1} **Did you mean:** ${p.join(", ")}?`):(ee.push(`
|
|
31
31
|
\u{1F4A1} Tips:`),ee.push(" \u2022 Try different keywords"),ee.push(" \u2022 Use `list_remembered` to see available context"),ee.push(' \u2022 Use `recall_best_solution("topic")` for exact topic lookup'))}if(!re&&E.length>0){ee.push(""),ee.push("\u21A9\uFE0E Hat eine davon geholfen? `recall_feedback(query=\u2026, topic=\u2026, helped=true, rank=N)` \u2014 und wenn die richtige Lektion **nicht** dabei war: dieselbe Meldung mit `rank=0`. Das ist die einzige Zahl, die die Sortierung besser macht.");const g=E.filter(p=>p.key.startsWith("cachly:lesson:best:")).map(p=>p.key.slice(19));if(g.length>0)try{await l.setex(`cachly:letzter-recall:${e}`,7200,JSON.stringify({frage:h,themen:g}))}catch{}}if(re&&E.length>0){const g=ys();g&&(ee.push(""),ee.push(g))}if(me!==null&&be){const g=E.slice(0,Ee).filter(p=>p.key.startsWith("cachly:lesson:best:")).map(p=>p.key.slice(19));return Bs(l,Z,{...be,themen:g},ee.join(`
|
|
32
32
|
`))}return ee.join(`
|
|
33
|
-
`)}case"session_start":{const{instance_id:f,focus:e="",author:h="",provider:y="",workspace_path:n=""}=R;if(await Bt(f,ae))return F(f).then(async u=>{await ls(u),await hs(u,e,y),await u.set("cachly:mcp:version:last_seen",Ze,"EX",365*86400)}).catch(()=>{}),_e("session_start: neues Brain startet noch \u2014 sofort geantwortet"),Hs({instanzId:f,provider:y,...gt(f)});const o=await F(f),I=[],b=o.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((u,v)=>{b.on("data",_=>I.push(..._)),b.on("end",u),b.on("error",v)});const i=[];let l=0;if(I.length>0){const u=await o.mget(...I);for(const v of u){const _=P(v??null,null);if(_){if(es(_)){l++;continue}os(_.topic)||i.push(_)}}}i.sort((u,v)=>new Date(v.ts).getTime()-new Date(u.ts).getTime());let a=0;const s=o.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((u,v)=>{s.on("data",_=>{a+=_.filter(k=>!k.endsWith(":meta")).length}),s.on("end",u),s.on("error",v)});const N=await o.get("cachly:session:last"),r=P(N,null),c=e.toLowerCase().split(/\s+/).filter(Boolean),x=c.length>0?i.filter(u=>c.some(v=>u.topic.toLowerCase().includes(v)||(u.tags??[]).some(_=>_.toLowerCase().includes(v)))):[],{tage:m,rekord:w}=await ls(o);let L="";m>=7?L=`\u{1F525} **${m}-day streak!** ${m===w?" New record!":`Best: ${w}d`}`:m>1&&(L=`\u{1F525} ${m}-day streak`),await hs(o,e,y);let A=0;try{const u=await o.get(`cachly:stats:time_saved_mins:${f}`);A=parseFloat(u??"0")}catch{}const t=[`\u{1F9E0} **Session Briefing**${y?` \xB7 ${y}`:""}`,""];if(L&&t.push(L,""),A>=30){const u=Math.floor(A/60),v=Math.round(A%60),_=u>0?`${u}h${v>0?` ${v}m`:""}`:`${v}m`,k=i.filter(z=>!at(z)&&(z.recall_count??0)>0).length,S=k>0?` \u2014 ${k} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";t.push(`\u23F1\uFE0F **Brain saved you ~${_} total**${S}`,"")}const ne=await us(f,ae),le=Gn({used:ne.used,limit:ne.limit,savedMins:A});if(le&&t.push(le,""),ne.notice&&!is.has(f)&&(is.add(f),t.push(ne.notice,"")),r?.ts){const u=new Date(r.ts).getTime(),v=Math.floor((Date.now()-u)/864e5);if(v>=7&&!Number.isNaN(u)){const _=i.filter(k=>{const S=new Date(k.ts).getTime();return!Number.isNaN(S)&&S>u});if(t.push(`\u{1F44B} **Welcome back** \u2014 it's been ${v} days since your last session.`),_.length>0){const k=_.slice(0,3).map(S=>`\`${S.topic}\``).join(", ");t.push(` \u{1F331} Your Brain grew by **${_.length} lesson${_.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${k}${_.length>3?", \u2026":""}`)}else t.push(` \u{1F9E0} ${i.length} lesson${i.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);t.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await o.get("cachly:mcp:version:last_seen")!==Ze){await o.set("cachly:mcp:version:last_seen",Ze,"EX",365*86400);const v=_o[Ze];if(v){t.push(...v,"");const _=yo();_&&t.push(`\u{1F4CA} ${_} MCP tools`,"")}}}catch{}const ue=!r&&i.length===0&&l===0&&a===0;ue&&(t.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),n?(t.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),t.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(t.push("It learns from your work automatically. After your first session it will look like this:",""),t.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),t.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),t.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),t.push(""),t.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),t.push("")),t.push("**Your brain grows automatically:**"),t.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),t.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),t.push(""),t.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),t.push(" `smart_recall` returns a hit instead of nothing:"),t.push(` \`brain_seed_starter(instance_id="${f}")\``),t.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),t.push(""),t.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),t.push(""));const fe=x.slice(0,4),d=new Set(fe.map(u=>u.topic));if(h&&!ue)try{const u=`cachly:team:first_briefing:${h}`;if(!await o.get(u)){const _=i.filter(k=>k.author&&k.author!==h&&!d.has(k.topic));if(_.length>0){await o.set(u,"1","EX",365*86400);const k=new Map;for(const S of _){const z=S.author;k.has(z)||k.set(z,[]),k.get(z).push(S)}t.push(""),t.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"),t.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),t.push(""),t.push("Your teammates have already solved problems you're about to hit:"),t.push("");for(const[S,z]of k){t.push(` \u{1F464} **${S}** fixed ${z.length} thing${z.length>1?"s":""}:`);for(const E of z.slice(0,2)){const G=E.outcome==="success"?"\u2705":"\u26A0\uFE0F";t.push(` ${G} \`${E.topic}\` \u2014 ${E.what_worked.slice(0,90)}`),d.add(E.topic)}z.length>2&&t.push(` \u2026 and ${z.length-2} more lessons`)}t.push(""),t.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),t.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"),t.push("")}}}catch{}const W=await o.get("cachly:session:handoff");if(W)try{const u=JSON.parse(W),v=Math.round((Date.now()-new Date(u.ts).getTime())/6e4),_=v<60?`${v}m ago`:v<1440?`${Math.round(v/60)}h ago`:`${Math.round(v/1440)}d ago`;if(t.push(`\u{1F91D} **Handoff from previous window** (${_}):`),u.context_summary&&t.push(` ${u.context_summary}`),u.remaining_tasks.length>0){t.push(" \u23F3 **Remaining tasks:**");for(const S of u.remaining_tasks)t.push(` - ${S}`)}u.completed_tasks.length>0&&t.push(` \u2705 **Already done:** ${u.completed_tasks.join(", ")}`);const k=(u.files_changed??[]).filter(S=>S.status==="broken"||S.status==="partial");k.length>0&&t.push(` \u26A0\uFE0F **Needs fix:** ${k.map(S=>`\`${S.path}\` (${S.status}${S.description?": "+S.description:""})`).join(", ")}`),u.blocked_on&&t.push(` \u{1F6AB} **Blocked on:** ${u.blocked_on}`),u.instructions&&t.push(` \u{1F4DD} **Instructions:** ${u.instructions}`),t.push("")}catch{}const se=await o.get("cachly:session:checkpoint");if(se)try{const u=JSON.parse(se),v=new Date(u.ts).getTime(),_=r?new Date(r.ts).getTime():0;if(v>_){const k=Math.round((Date.now()-v)/6e4),S=k<60?`${k}m ago`:k<1440?`${Math.round(k/60)}h ago`:`${Math.round(k/1440)}d ago`,z=u.provider?` [${u.provider}]`:"";t.push(`\u{1F4CC} **Last checkpoint**${z} (${S}): ${u.task}`),u.files_touched.length>0&&t.push(` Files: ${u.files_touched.slice(0,5).map(E=>`\`${E}\``).join(", ")}`),u.next_step&&t.push(` \u{1F4CD} Next step was: ${u.next_step}`),(!r||v-_>3e5)&&t.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),t.push("")}}catch{}const K=r?null:nt(n);if(K)try{const u=We(K,["log","--oneline","--format=%h %s","-15"]).trim();let v;try{v=We(K,["diff","--stat","HEAD~3"]).trim()}catch{v=We(K,["diff","--stat"]).trim()}if(u){t.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const _ of u.split(`
|
|
33
|
+
`)}case"session_start":{const{instance_id:f,focus:e="",author:h="",provider:y="",workspace_path:n=""}=R;if(await Bt(f,ae))return F(f).then(async u=>{await ls(u),await hs(u,e,y),await u.set("cachly:mcp:version:last_seen",Ze,"EX",365*86400)}).catch(()=>{}),_e("session_start: neues Brain startet noch \u2014 sofort geantwortet"),Hs({instanzId:f,provider:y,...await gt(f)});const o=await F(f),I=[],b=o.scanStream({match:"cachly:lesson:best:*",count:1e3});await new Promise((u,v)=>{b.on("data",_=>I.push(..._)),b.on("end",u),b.on("error",v)});const i=[];let l=0;if(I.length>0){const u=await o.mget(...I);for(const v of u){const _=P(v??null,null);if(_){if(es(_)){l++;continue}os(_.topic)||i.push(_)}}}i.sort((u,v)=>new Date(v.ts).getTime()-new Date(u.ts).getTime());let a=0;const s=o.scanStream({match:"cachly:ctx:*",count:1e3});await new Promise((u,v)=>{s.on("data",_=>{a+=_.filter(k=>!k.endsWith(":meta")).length}),s.on("end",u),s.on("error",v)});const N=await o.get("cachly:session:last"),r=P(N,null),c=e.toLowerCase().split(/\s+/).filter(Boolean),x=c.length>0?i.filter(u=>c.some(v=>u.topic.toLowerCase().includes(v)||(u.tags??[]).some(_=>_.toLowerCase().includes(v)))):[],{tage:m,rekord:w}=await ls(o);let L="";m>=7?L=`\u{1F525} **${m}-day streak!** ${m===w?" New record!":`Best: ${w}d`}`:m>1&&(L=`\u{1F525} ${m}-day streak`),await hs(o,e,y);let A=0;try{const u=await o.get(`cachly:stats:time_saved_mins:${f}`);A=parseFloat(u??"0")}catch{}const t=[`\u{1F9E0} **Session Briefing**${y?` \xB7 ${y}`:""}`,""];if(L&&t.push(L,""),A>=30){const u=Math.floor(A/60),v=Math.round(A%60),_=u>0?`${u}h${v>0?` ${v}m`:""}`:`${v}m`,k=i.filter(z=>!at(z)&&(z.recall_count??0)>0).length,S=k>0?` \u2014 ${k} of your own lessons that already helped, counted once each`:" (time not re-researching known fixes)";t.push(`\u23F1\uFE0F **Brain saved you ~${_} total**${S}`,"")}const ne=await us(f,ae),le=Gn({used:ne.used,limit:ne.limit,savedMins:A});if(le&&t.push(le,""),ne.notice&&!is.has(f)&&(is.add(f),t.push(ne.notice,"")),r?.ts){const u=new Date(r.ts).getTime(),v=Math.floor((Date.now()-u)/864e5);if(v>=7&&!Number.isNaN(u)){const _=i.filter(k=>{const S=new Date(k.ts).getTime();return!Number.isNaN(S)&&S>u});if(t.push(`\u{1F44B} **Welcome back** \u2014 it's been ${v} days since your last session.`),_.length>0){const k=_.slice(0,3).map(S=>`\`${S.topic}\``).join(", ");t.push(` \u{1F331} Your Brain grew by **${_.length} lesson${_.length!==1?"s":""}** while you were gone (git, CI & teammates kept it learning): ${k}${_.length>3?", \u2026":""}`)}else t.push(` \u{1F9E0} ${i.length} lesson${i.length!==1?"s":""} held steady and ready \u2014 recall anything with \`smart_recall\`.`);t.push(" \u{1F4A1} Full breakdown: `npx @cachly-dev/mcp-server@latest digest`","")}}try{if(await o.get("cachly:mcp:version:last_seen")!==Ze){await o.set("cachly:mcp:version:last_seen",Ze,"EX",365*86400);const v=_o[Ze];if(v){t.push(...v,"");const _=yo();_&&t.push(`\u{1F4CA} ${_} MCP tools`,"")}}}catch{}const ue=!r&&i.length===0&&l===0&&a===0;ue&&(t.push("\u{1F389} **Welcome! Your AI Brain is live.**",""),n?(t.push("\u{1F680} **Auto-bootstrapping from your git history...** (this takes a few seconds)"),t.push(" Your brain will learn from your recent commits \u2014 no setup needed.","")):(t.push("It learns from your work automatically. After your first session it will look like this:",""),t.push(" \u2705 `api:auth` \u2014 Bearer token in header, not cookie; 401 on missing scope"),t.push(" \u2705 `database:migrations` \u2014 always run migrations before deploy"),t.push(" \u26A0\uFE0F `docker:build` \u2014 ARG changes bust all subsequent cache layers"),t.push(""),t.push("**Tip:** Pass `workspace_path` to `session_start` to auto-learn from git history instantly."),t.push("")),t.push("**Your brain grows automatically:**"),t.push(' \u2022 End each session \u2192 `session_end(summary="What I did")` \u2014 auto-learns from git commits'),t.push(' \u2022 After fixing bugs \u2192 `learn_from_attempts(topic="...", outcome="success", what_worked="...")`'),t.push(""),t.push("\u{1F331} **Want answers right now?** Seed 16 universal engineering lessons so your first"),t.push(" `smart_recall` returns a hit instead of nothing:"),t.push(` \`brain_seed_starter(instance_id="${f}")\``),t.push(" _(Docker cache, JWT skew, K8s OOM, N+1 queries, cache stampede\u2026 \u2014 never overrides your own lessons.)_"),t.push(""),t.push("\u{1F4A1} Run `brain_doctor` for a health-check and personalised tips."),t.push(""));const fe=x.slice(0,4),d=new Set(fe.map(u=>u.topic));if(h&&!ue)try{const u=`cachly:team:first_briefing:${h}`;if(!await o.get(u)){const _=i.filter(k=>k.author&&k.author!==h&&!d.has(k.topic));if(_.length>0){await o.set(u,"1","EX",365*86400);const k=new Map;for(const S of _){const z=S.author;k.has(z)||k.set(z,[]),k.get(z).push(S)}t.push(""),t.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"),t.push("\u{1F91D} **Your team's AI brain has been briefing you.**"),t.push(""),t.push("Your teammates have already solved problems you're about to hit:"),t.push("");for(const[S,z]of k){t.push(` \u{1F464} **${S}** fixed ${z.length} thing${z.length>1?"s":""}:`);for(const E of z.slice(0,2)){const G=E.outcome==="success"?"\u2705":"\u26A0\uFE0F";t.push(` ${G} \`${E.topic}\` \u2014 ${E.what_worked.slice(0,90)}`),d.add(E.topic)}z.length>2&&t.push(` \u2026 and ${z.length-2} more lessons`)}t.push(""),t.push("\u{1F4A1} Use `team_learn` after your next fix to pay it forward."),t.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"),t.push("")}}}catch{}const W=await o.get("cachly:session:handoff");if(W)try{const u=JSON.parse(W),v=Math.round((Date.now()-new Date(u.ts).getTime())/6e4),_=v<60?`${v}m ago`:v<1440?`${Math.round(v/60)}h ago`:`${Math.round(v/1440)}d ago`;if(t.push(`\u{1F91D} **Handoff from previous window** (${_}):`),u.context_summary&&t.push(` ${u.context_summary}`),u.remaining_tasks.length>0){t.push(" \u23F3 **Remaining tasks:**");for(const S of u.remaining_tasks)t.push(` - ${S}`)}u.completed_tasks.length>0&&t.push(` \u2705 **Already done:** ${u.completed_tasks.join(", ")}`);const k=(u.files_changed??[]).filter(S=>S.status==="broken"||S.status==="partial");k.length>0&&t.push(` \u26A0\uFE0F **Needs fix:** ${k.map(S=>`\`${S.path}\` (${S.status}${S.description?": "+S.description:""})`).join(", ")}`),u.blocked_on&&t.push(` \u{1F6AB} **Blocked on:** ${u.blocked_on}`),u.instructions&&t.push(` \u{1F4DD} **Instructions:** ${u.instructions}`),t.push("")}catch{}const se=await o.get("cachly:session:checkpoint");if(se)try{const u=JSON.parse(se),v=new Date(u.ts).getTime(),_=r?new Date(r.ts).getTime():0;if(v>_){const k=Math.round((Date.now()-v)/6e4),S=k<60?`${k}m ago`:k<1440?`${Math.round(k/60)}h ago`:`${Math.round(k/1440)}d ago`,z=u.provider?` [${u.provider}]`:"";t.push(`\u{1F4CC} **Last checkpoint**${z} (${S}): ${u.task}`),u.files_touched.length>0&&t.push(` Files: ${u.files_touched.slice(0,5).map(E=>`\`${E}\``).join(", ")}`),u.next_step&&t.push(` \u{1F4CD} Next step was: ${u.next_step}`),(!r||v-_>3e5)&&t.push(" \u26A0\uFE0F No `session_end` found \u2014 reconstructed from last checkpoint"),t.push("")}}catch{}const K=r?null:nt(n);if(K)try{const u=We(K,["log","--oneline","--format=%h %s","-15"]).trim();let v;try{v=We(K,["diff","--stat","HEAD~3"]).trim()}catch{v=We(K,["diff","--stat"]).trim()}if(u){t.push("\u{1F50D} **Git reconstruction** (no session_end found \u2014 reconstructed from git):");for(const _ of u.split(`
|
|
34
34
|
`).slice(0,8))t.push(` ${_}`);if(v){const _=v.split(`
|
|
35
35
|
`).filter(k=>k.includes("|")||k.includes("changed"));if(_.length>0){t.push(" **Recent changes:**");for(const k of _.slice(0,5))t.push(` ${k.trim()}`)}}t.push("")}}catch{}if(r){const u=Math.round((Date.now()-new Date(r.ts).getTime())/6e4),v=u<60?`${u}m ago`:u<1440?`${Math.round(u/60)}h ago`:`${Math.round(u/1440)}d ago`;t.push(`\u{1F4C5} **Last session** (${v}): ${r.summary}`),r.duration_min&&t.push(` Duration: ${r.duration_min} min`),(r.files_changed??[]).length>0&&t.push(` Files: ${(r.files_changed??[]).slice(0,5).map(_=>`\`${_}\``).join(", ")}`),t.push("")}t.push(`\u{1F4CA} **Brain:** ${i.length} lessons \xB7 ${a} context entries`,""),l>0&&t.push(`\u26A0 ${l} Lektion(en) wurden beim Speichern als verd\xE4chtig markiert und stehen nicht in diesem Briefing. Ausdr\xFCcklich abrufbar mit recall_best_solution (mit Warnzeile); pr\xFCfen oder neu speichern.`,"");{const v=i.filter(_=>!at(_)).filter(_=>_.outcome==="success"&&(_.pinned===!0||(_.recall_count??0)>=5)).filter(_=>!d.has(_.topic)).sort((_,k)=>(k.recall_count??0)-(_.recall_count??0)).slice(0,5);if(v.length>0){t.push("\u{1F4CC} **Proven Laws** (auto-crystallized \u2014 your most-trusted knowledge):");for(const _ of v){d.add(_.topic);const k=_.severity==="critical"?"\u{1F534}":_.severity==="major"?"\u{1F7E1}":"",S=_.recall_count??0,z=_.pinned===!0?"pinned":`recalled ${S}\xD7`,E=Qe(_);t.push(` \u{1F3C6}${k} \`${_.topic}\` _(${z})_ \u2014 ${E[0]??""}`,...E.slice(1))}t.push("")}}try{const u=[],v=o.scanStream({match:"cachly:ckg:conflict:*",count:1e3});if(await new Promise((_,k)=>{v.on("data",S=>u.push(...S)),v.on("end",_),v.on("error",k)}),u.length>0){t.push(`\u26A1 **Active belief conflicts (${u.length}):**`);for(const _ of u.slice(0,3)){const k=await o.get(_);if(!k)continue;const S=P(k,null);S&&t.push(` \u26A0\uFE0F \`${S.topic}\` \u2014 previously confirmed fix (${(S.fix_confidence*100).toFixed(0)}%, n=${S.fix_trials}) now contradicted. Use \`ckg_inspect(concept="${ge(S.topic)}")\``)}t.push("")}}catch{}if(fe.length>0){t.push(`\u{1F3AF} **Relevant for "${e}":**`);for(const u of fe){const v=u.outcome==="success"?"\u2705":u.outcome==="partial"?"\u26A0\uFE0F":"\u274C",_=u.severity==="critical"?"\u{1F534}":u.severity==="major"?"\u{1F7E1}":"",k=Qe(u);t.push(` ${v}${_} \`${u.topic}\` \u2014 ${k[0]??""}`,...k.slice(1))}t.push("")}if(i.length>0){const u=(x.length>0?i.filter(v=>!x.includes(v)):i).filter(v=>!d.has(v.topic)).slice(0,x.length>0?3:4);if(u.length>0){t.push("\u{1F550} **Recent lessons:**");for(const v of u){d.add(v.topic);const _=v.outcome==="success"?"\u2705":v.outcome==="partial"?"\u26A0\uFE0F":"\u274C",k=v.severity==="critical"?"\u{1F534}":v.severity==="major"?"\u{1F7E1}":"",S=Qe(v);t.push(` ${_}${k} \`${v.topic}\` \u2014 ${S[0]??""}`,...S.slice(1))}t.push("")}}else t.push("\u{1F4ED} No lessons yet. Use `learn_from_attempts` after solving tasks.","");i.length>=10&&(i.some(v=>v.author)||(t.push(`\u{1F91D} **Your Brain has ${i.length} lessons \u2014 your team could benefit instantly.**`),t.push(" Share: **cachly.dev/team** \xB7 or run `team_learn` after the next fix.","")));const Q=await Rn(o,i);if(Q.length>0){t.push("\u267B\uFE0F **Possible duplicates** (same meaning, different topic \u2014 nothing is merged):");for(const u of Q.slice(0,3))t.push(` \`${u.neu}\` \u2248 \`${u.alt}\` (${u.naehe.toFixed(2)})`);t.push(' _If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`._'),t.push("")}const J=r;if(J?.decision_log?.length){const u=J.decision_log,v=u.filter((S,z)=>!d.has(S.topic)&&u.findIndex(E=>E.topic===S.topic)===z),_=v.filter(S=>S.outcome==="success"),k=v.filter(S=>S.outcome==="failure");if(_.length>0||k.length>0){t.push(`\u{1F3AC} **Last session decisions** (${u.length} lessons stored):`),_.length>0&&t.push(` \u2705 Worked: ${_.slice(0,3).map(S=>`\`${S.topic}\``).join(", ")}`),k.length>0&&t.push(` \u274C Failed: ${k.slice(0,3).map(S=>`\`${S.topic}\``).join(", ")}`),t.push("");for(const S of[..._.slice(0,3),...k.slice(0,3)])d.add(S.topic)}}{const u=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"]),v=z=>{const E=new Set;for(const G of z)for(const Y of G.toLowerCase().split(/[/\\._-]/))Y.length>3&&!u.has(Y)&&E.add(Y);return[...E]};let _=c,k=e,S=!1;if(_.length===0&&r){const z=v(r.files_changed??[]),E=(r.summary??"").toLowerCase().replace(/[^a-z0-9\s:_-]/g," ").split(/\s+/).filter(G=>G.length>3&&!u.has(G));_=[...new Set([...z,...E])],k="where you left off last session",S=!0}if(_.length>0){const z=i.filter(E=>{if(E.outcome==="success")return!1;const G=E.topic.split(":")[0];return _.some(Y=>E.topic.toLowerCase().includes(Y)||G===Y||(E.tags??[]).some(ce=>ce.toLowerCase()===Y))});if(z.length>=1){const G=["\u{1F6A8} **PRE-WARNING** \u2014 Read this BEFORE starting:",S?` You're likely to continue **${k}** \u2014 ${z.length} known pitfall${z.length>1?"s":""} there:`:` Known pitfalls for **"${k}"** (${z.length} past failure${z.length>1?"s":""}):`,...z.slice(0,3).map(Y=>` \u274C \`${Y.topic}\` \u2014 ${(Y.what_failed??Y.what_worked).slice(0,80)}`),""];t.splice(2,0,...G)}}}if(h){const u=Date.now()-6048e5,v=i.filter(_=>_.author&&_.author!==h&&new Date(_.ts).getTime()>u&&!d.has(_.topic));if(v.length>0){const _=new Map;for(const k of v){const S=k.author;_.has(S)||_.set(S,[]),_.get(S).push(k)}t.push(`\u{1F465} **Team this week** (${v.length} lesson${v.length>1?"s":""} from teammates):`);for(const[k,S]of _){t.push(` \u{1F464} **${k}**:`);for(const z of S.slice(0,3)){const E=z.outcome==="success"?"\u2705":z.outcome==="partial"?"\u26A0\uFE0F":"\u274C";t.push(` ${E} \`${z.topic}\` \u2014 ${z.what_worked.slice(0,80)}`),d.add(z.topic)}S.length>3&&t.push(` \u2026 and ${S.length-3} more`)}t.push("")}}try{const u=await o.get("cachly:crystal:latest");if(u){const v=P(u,null);if(v&&Math.round((Date.now()-new Date(v.ts).getTime())/864e5)<=90){t.push(`\u{1F48E} **Memory Crystal** (${v.label} \xB7 ${v.session_count} sessions compressed):`);for(const k of v.top_patterns.slice(0,3))t.push(` \u2022 **${k.category}** (${k.count}\xD7): ${k.insight.slice(0,90)}`);t.push("")}}}catch{}try{const u=await o.hgetall(`cachly:roadmap:${f}`);if(u&&Object.keys(u).length>0){const v={critical:0,high:1,medium:2,low:3},_={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F535}"},k=new Set(["planned","in-progress","blocked"]),S=Object.values(u).flatMap(G=>{const Y=P(G,null);return Y?[Y]:[]}),z=S.filter(G=>k.has(G.status)).sort((G,Y)=>G.status==="in-progress"&&Y.status!=="in-progress"?-1:Y.status==="in-progress"&&G.status!=="in-progress"?1:(v[G.priority]??99)-(v[Y.priority]??99)),E=S.filter(G=>G.status==="done").length;if(z.length>0){t.push(`\u{1F5FA}\uFE0F **Roadmap** (${z.length} open \xB7 ${E} done):`);for(const G of z.slice(0,5)){const Y=G.status==="in-progress"?"\u26A1":G.status==="blocked"?"\u{1F6AB}":"\u{1F4CB}";t.push(` ${Y} ${_[G.priority]??"\u26AA"} \`${G.id}\` **${G.title}**`)}z.length>5&&t.push(` \u2026 and ${z.length-5} more`),t.push(" _Use `roadmap_next` for the top priority item \xB7 `roadmap_list` for full view_"),t.push("")}}}catch{}try{const u=await o.get("cachly:mcm:calibration:last"),v=P(u,null)?.ts??0;if((Date.now()-v)/864e5>=30&&i.length>=5){const k=i.filter(z=>z.outcome==="success"&&(z.recall_count??0)>0),S=i.filter(z=>(z.recall_count??0)>0);if(S.length>=3){const z=S.length>0?k.length/S.length:1,E=[],G=new Map;for(const Y of S){const ce=Y.topic.split(":")[0]??"other";G.has(ce)||G.set(ce,{success:0,total:0});const me=G.get(ce);me.total++,Y.outcome==="success"&&me.success++}for(const[Y,ce]of G)ce.total>=2&&ce.success/ce.total<.6&&E.push(Y);await o.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:z,recalled:S.length,low_precision_domains:E})),(E.length>0||z<.7)&&(t.push(`\u{1F4D0} **MCM Calibration** (30-day pass \u2014 ${S.length} recalled lessons):`),t.push(` Overall precision: **${(z*100).toFixed(0)}%** recalled lessons actually worked`),E.length>0&&t.push(` \u26A0\uFE0F Low-precision domains: ${E.map(Y=>`\`${Y}\``).join(", ")} \u2014 consider revisiting these lessons`),t.push(" \u{1F4A1} Use `learn_from_attempts` to update stale lessons and improve accuracy."),t.push(""))}await o.set("cachly:mcm:calibration:last",JSON.stringify({ts:Date.now(),precision:1,recalled:0}),"EX",35*86400)}}catch{}const X=i.filter(u=>u.outcome==="failure"||u.outcome==="partial").length,he=i.filter(u=>u.outcome==="success"&&Ct(u)<ws).length;if(i.length===0||X>0||he>0){const u=[];i.length===0&&u.push("brain is empty"),X>0&&u.push(`${X} open failure${X>1?"s":""}`),he>0&&u.push(`${he} stale lesson${he>1?"s":""}`),t.push(`\u{1FA7A} _Run \`brain_doctor\` to fix: ${u.join(", ")}._`)}try{if(await o.get(`cachly:prefs:auto_changelog:${f}`).catch(()=>null)!=="false"&&r?.ts&&!ue){const _=new Date(r.ts).getTime();if(!Number.isNaN(_)){const k=i.filter(z=>{const E=new Date(z.ts).getTime();return!Number.isNaN(E)&&E>_}),S=k.filter(z=>!d.has(z.topic));if(S.length>0){const z=Math.round((Date.now()-_)/6e4),E=z<60?`${z}m`:z<1440?`${Math.round(z/60)}h`:`${Math.round(z/1440)}d`,G=k.length-S.length;t.push(""),t.push(`\u{1F4CB} **${k.length} new lesson${k.length!==1?"s":""} since your last session** (${E} ago${G>0?`, ${G} already listed above`:""}):`);const Y=new Map;for(const ce of S.slice(0,20)){const me=ce.topic.includes(":")?ce.topic.split(":")[0]:"general",Z=Y.get(me)??[];Z.push(ce),Y.set(me,Z)}for(const[ce,me]of Y){t.push(` **${ce}**`);for(const Z of me){const be=Z.outcome==="failure"?"\u274C":Z.severity==="critical"?"\u{1F6A8}":Z.severity==="major"?"\u26A0\uFE0F":"\u2705",$e=(Z.outcome==="failure"?Z.what_failed:Z.what_worked)??"";t.push(` ${be} \`${Z.topic}\`${$e?` \u2014 ${$e.slice(0,80)}`:""}`)}}S.length>20&&t.push(` \u2026 and ${S.length-20} more. Call \`brain_changelog\` for the full list.`),t.push(` _Disable auto-changelog: \`brain_set_pref(instance_id="${f}", key="auto_changelog", value="false")\`_`)}}}}catch{}return t.join(`
|
|
36
36
|
`)}case"session_start_summary":{const{instance_id:f,focus:e,top_n:h=10,author:y=""}=R;if(!e||!e.trim())throw new Error("focus is required for session_start_summary");const n=Math.min(Math.max(1,Math.floor(Number(h)||10)),25),o=await F(f),I=[],b=o.scanStream({match:"cachly:lesson:best:*",count:200});await new Promise((M,t)=>{b.on("data",ne=>I.push(...ne)),b.on("end",M),b.on("error",t)});const i=[];if(I.length>0){const M=await o.mget(...I);for(const t of M){const ne=P(t??null,null);ne&&!es(ne)&&!os(ne.topic)&&i.push(ne)}}if(i.length===0)return["\u{1F9E0} Brain Summary \u2014 no lessons yet","","Your brain is empty. Use `learn_from_attempts` after solving tasks to build it up.",`\u{1F4A1} Tip: \`brain_seed_starter(instance_id="${f}")\` to bootstrap with 16 universal lessons.`].join(`
|