@cachly-dev/mcp-server 0.10.49 → 0.10.51
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/BENCH.md +80 -0
- package/STRATEGY.md +33 -14
- package/apps/travel-chaos-organizer/frontend/package-lock.json +184 -0
- package/dist/src/__tests__/rerank.test.d.ts +1 -0
- package/dist/src/__tests__/rerank.test.js +115 -0
- package/dist/src/__tests__/rerank.test.js.map +1 -0
- package/dist/src/bench/cachly-bench.d.ts +35 -0
- package/dist/src/bench/cachly-bench.js +182 -0
- package/dist/src/bench/cachly-bench.js.map +1 -0
- package/dist/src/bench/fixtures.d.ts +34 -0
- package/dist/src/bench/fixtures.js +199 -0
- package/dist/src/bench/fixtures.js.map +1 -0
- package/dist/src/handlers/brain.js +141 -65
- package/dist/src/handlers/brain.js.map +1 -1
- package/dist/src/handlers/team.js +56 -4
- package/dist/src/handlers/team.js.map +1 -1
- package/dist/src/rerank.d.ts +55 -0
- package/dist/src/rerank.js +111 -0
- package/dist/src/rerank.js.map +1 -0
- package/dist/src/tools.d.ts +30 -0
- package/dist/src/tools.js +18 -0
- package/dist/src/tools.js.map +1 -1
- package/package.json +2 -1
- package/src/__tests__/rerank.test.ts +130 -0
- package/src/bench/cachly-bench.ts +217 -0
- package/src/bench/fixtures.ts +226 -0
- package/src/handlers/brain.ts +156 -73
- package/src/handlers/team.ts +66 -4
- package/src/rerank.ts +148 -0
- package/src/tools.ts +19 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cachly-Bench fixture corpus.
|
|
3
|
+
*
|
|
4
|
+
* A small but realistic corpus of engineering "lessons" plus a set of labeled
|
|
5
|
+
* natural-language queries. Each query declares which lesson topics are *truly*
|
|
6
|
+
* relevant — the answer an agent actually wants.
|
|
7
|
+
*
|
|
8
|
+
* The corpus is deliberately adversarial in a fair way: for several queries there
|
|
9
|
+
* is a text-similar but LOW-QUALITY distractor (a failed attempt, an unverified
|
|
10
|
+
* note) competing with the proven success lesson. This is exactly the situation
|
|
11
|
+
* where raw text ranking (and a flat-file memory) goes wrong, and where Cachly's
|
|
12
|
+
* quality-aware reranking should win. The labels reward the lesson that solves the
|
|
13
|
+
* problem, not the one that merely shares vocabulary.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface BenchLesson {
|
|
17
|
+
/** Stored under cachly:lesson:best:{topic} */
|
|
18
|
+
topic: string;
|
|
19
|
+
outcome: 'success' | 'partial' | 'failure';
|
|
20
|
+
what_worked: string;
|
|
21
|
+
what_failed?: string;
|
|
22
|
+
context?: string;
|
|
23
|
+
severity?: 'critical' | 'major' | 'minor';
|
|
24
|
+
confidence?: number;
|
|
25
|
+
recall_count?: number;
|
|
26
|
+
tags?: string[];
|
|
27
|
+
ts?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface BenchQuery {
|
|
31
|
+
query: string;
|
|
32
|
+
/** Topics that genuinely answer the query (the gold set). */
|
|
33
|
+
relevant: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const NOW = Date.now();
|
|
37
|
+
const daysAgo = (d: number) => new Date(NOW - d * 86400_000).toISOString();
|
|
38
|
+
|
|
39
|
+
export const BENCH_LESSONS: BenchLesson[] = [
|
|
40
|
+
// ── Deploy domain ──────────────────────────────────────────────────────────
|
|
41
|
+
{
|
|
42
|
+
topic: 'deploy:k8s:rollout-stuck',
|
|
43
|
+
outcome: 'success',
|
|
44
|
+
what_worked: 'Set a readinessProbe with a longer initialDelaySeconds and a higher failureThreshold so the liveness probe stopped terminating the container before startup completed. The pod then reached ready and traffic flowed.',
|
|
45
|
+
context: 'Production release never became healthy.',
|
|
46
|
+
severity: 'critical', confidence: 0.95, recall_count: 12,
|
|
47
|
+
tags: ['kubernetes', 'deploy', 'probe'], ts: daysAgo(8),
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
topic: 'deploy:k8s:rollout-attempt-restart',
|
|
51
|
+
outcome: 'failure',
|
|
52
|
+
what_worked: '',
|
|
53
|
+
what_failed: 'The kubernetes deploy was stuck, the rollout was not finishing, so I restarted the deploy. The kubernetes deploy stayed stuck and the rollout still was not finishing. Restarted the stuck rollout again, deploy still stuck.',
|
|
54
|
+
context: 'Kubernetes deploy stuck, rollout not finishing.',
|
|
55
|
+
severity: 'major', confidence: 0.3, recall_count: 0,
|
|
56
|
+
tags: ['kubernetes', 'deploy'], ts: daysAgo(9),
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
topic: 'deploy:docker:image-too-large',
|
|
60
|
+
outcome: 'success',
|
|
61
|
+
what_worked: 'Reduced Docker image size dramatically with a multi-stage build and a slim base image, moving build-only deps out of the final layer.',
|
|
62
|
+
context: 'CI pushes were slow due to a 1.8GB image.',
|
|
63
|
+
severity: 'minor', confidence: 0.9, recall_count: 6,
|
|
64
|
+
tags: ['docker', 'deploy', 'optimization'], ts: daysAgo(20),
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
// ── Database domain ────────────────────────────────────────────────────────
|
|
68
|
+
{
|
|
69
|
+
topic: 'db:postgres:connection-pool-exhausted',
|
|
70
|
+
outcome: 'success',
|
|
71
|
+
what_worked: 'Added PgBouncer in transaction pooling mode and lowered the per-service max pool size so backends were shared. Peak traffic stopped exhausting backends.',
|
|
72
|
+
context: 'API returned 500s at peak traffic.',
|
|
73
|
+
severity: 'critical', confidence: 0.92, recall_count: 9,
|
|
74
|
+
tags: ['postgres', 'database', 'pool'], ts: daysAgo(15),
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
topic: 'db:postgres:slow-query-missing-index',
|
|
78
|
+
outcome: 'success',
|
|
79
|
+
what_worked: 'A slow Postgres query was fixed by adding a composite index on (tenant_id, created_at); query dropped from 4s to 12ms.',
|
|
80
|
+
context: 'Dashboard timed out loading recent events.',
|
|
81
|
+
severity: 'major', confidence: 0.88, recall_count: 4,
|
|
82
|
+
tags: ['postgres', 'database', 'index', 'performance'], ts: daysAgo(30),
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
topic: 'db:postgres:pool-raise-limit-attempt',
|
|
86
|
+
outcome: 'failure',
|
|
87
|
+
what_worked: '',
|
|
88
|
+
what_failed: 'Postgres had too many connections under load, so I raised max_connections. Postgres still had too many connections under load and the load made it worse — too many connections again under load.',
|
|
89
|
+
context: 'Postgres too many connections under load.',
|
|
90
|
+
severity: 'major', confidence: 0.25, recall_count: 0,
|
|
91
|
+
tags: ['postgres', 'database', 'pool'], ts: daysAgo(16),
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
// ── Auth domain ────────────────────────────────────────────────────────────
|
|
95
|
+
{
|
|
96
|
+
topic: 'auth:jwt:expired-on-restart',
|
|
97
|
+
outcome: 'success',
|
|
98
|
+
what_worked: 'JWT was lost on server restart because it was only kept in memory; persisting the token to disk after the device flow fixed recall counts staying at zero.',
|
|
99
|
+
context: 'Telemetry showed zero authenticated calls after restarts.',
|
|
100
|
+
severity: 'critical', confidence: 0.93, recall_count: 7,
|
|
101
|
+
tags: ['jwt', 'auth', 'persistence'], ts: daysAgo(3),
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
topic: 'auth:pkce:keycloak-rejects-exchange',
|
|
105
|
+
outcome: 'success',
|
|
106
|
+
what_worked: 'Keycloak rejected the PKCE code exchange because the verifier used non-URL-safe Base64; switching to RFC 7636 Base64URL random bytes fixed the login.',
|
|
107
|
+
context: 'Mobile login failed at the token exchange step.',
|
|
108
|
+
severity: 'major', confidence: 0.9, recall_count: 3,
|
|
109
|
+
tags: ['pkce', 'auth', 'keycloak', 'oauth'], ts: daysAgo(2),
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
// ── Redis / cache domain ───────────────────────────────────────────────────
|
|
113
|
+
{
|
|
114
|
+
topic: 'redis:noauth-on-every-call',
|
|
115
|
+
outcome: 'success',
|
|
116
|
+
what_worked: 'The connection endpoint omitted the password field, so the client connected unauthenticated; returning the credential explicitly in the response let the client authenticate and the calls succeeded.',
|
|
117
|
+
context: 'Hosted Valkey requires a credential.',
|
|
118
|
+
severity: 'critical', confidence: 0.94, recall_count: 11,
|
|
119
|
+
tags: ['redis', 'valkey', 'auth'], ts: daysAgo(4),
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
topic: 'redis:noauth-disable-auth-attempt',
|
|
123
|
+
outcome: 'failure',
|
|
124
|
+
what_worked: '',
|
|
125
|
+
what_failed: 'Redis threw NOAUTH on every call, so I tried disabling auth on Redis. Redis still threw NOAUTH on every call. Tried again to stop the NOAUTH error on every Redis call — no luck.',
|
|
126
|
+
context: 'Redis NOAUTH error on every call.',
|
|
127
|
+
severity: 'major', confidence: 0.2, recall_count: 0,
|
|
128
|
+
tags: ['redis', 'auth'], ts: daysAgo(5),
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
topic: 'redis:keys-no-ttl-memory-leak',
|
|
132
|
+
outcome: 'success',
|
|
133
|
+
what_worked: 'Redis memory grew unbounded because dependency-index and history keys had no TTL; adding a 90-day expire and an ltrim bounded the memory.',
|
|
134
|
+
context: 'Instance memory crept up over weeks of use.',
|
|
135
|
+
severity: 'major', confidence: 0.85, recall_count: 2,
|
|
136
|
+
tags: ['redis', 'ttl', 'memory'], ts: daysAgo(1),
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
// ── CI / build domain ──────────────────────────────────────────────────────
|
|
140
|
+
{
|
|
141
|
+
topic: 'ci:npm-ci-lockfile-mismatch',
|
|
142
|
+
outcome: 'success',
|
|
143
|
+
what_worked: 'CI "npm ci" failed because a dependency was added to package.json but the lockfile was never regenerated; running npm install to update package-lock.json fixed the build.',
|
|
144
|
+
context: 'GitHub Actions install step failed after adding a dep.',
|
|
145
|
+
severity: 'major', confidence: 0.91, recall_count: 5,
|
|
146
|
+
tags: ['ci', 'npm', 'lockfile'], ts: daysAgo(0),
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
topic: 'ci:golangci-lint-errcheck',
|
|
150
|
+
outcome: 'success',
|
|
151
|
+
what_worked: 'golangci-lint failed on an unchecked recover() return value; assigning it to _ satisfied errcheck.',
|
|
152
|
+
context: 'Go lint job blocked the deploy pipeline.',
|
|
153
|
+
severity: 'minor', confidence: 0.8, recall_count: 1,
|
|
154
|
+
tags: ['ci', 'go', 'lint'], ts: daysAgo(1),
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
// ── Frontend domain ────────────────────────────────────────────────────────
|
|
158
|
+
{
|
|
159
|
+
topic: 'frontend:cors-preflight-blocked',
|
|
160
|
+
outcome: 'success',
|
|
161
|
+
what_worked: 'Dashboard mutations failed because the CORS middleware did not allow PUT/PATCH; adding them to AllowMethods fixed the preflight.',
|
|
162
|
+
context: 'BYOK and webhook settings could not be saved from the browser.',
|
|
163
|
+
severity: 'major', confidence: 0.87, recall_count: 4,
|
|
164
|
+
tags: ['cors', 'frontend', 'api'], ts: daysAgo(6),
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
topic: 'frontend:hydration-mismatch',
|
|
168
|
+
outcome: 'partial',
|
|
169
|
+
what_worked: 'A Next.js hydration mismatch was reduced by guarding a date render with a client-only effect, though the root cause (locale formatting) still needs work.',
|
|
170
|
+
context: 'Console hydration warnings on the landing page.',
|
|
171
|
+
severity: 'minor', confidence: 0.6, recall_count: 1,
|
|
172
|
+
tags: ['nextjs', 'frontend', 'hydration'], ts: daysAgo(25),
|
|
173
|
+
},
|
|
174
|
+
];
|
|
175
|
+
|
|
176
|
+
export const BENCH_QUERIES: BenchQuery[] = [
|
|
177
|
+
{
|
|
178
|
+
query: 'kubernetes deploy stuck rollout not finishing',
|
|
179
|
+
relevant: ['deploy:k8s:rollout-stuck'],
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
query: 'postgres too many connections under load',
|
|
183
|
+
relevant: ['db:postgres:connection-pool-exhausted'],
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
query: 'dashboard query is slow and times out',
|
|
187
|
+
relevant: ['db:postgres:slow-query-missing-index'],
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
query: 'jwt lost after restart recall count zero',
|
|
191
|
+
relevant: ['auth:jwt:expired-on-restart'],
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
query: 'keycloak rejects pkce token exchange on login',
|
|
195
|
+
relevant: ['auth:pkce:keycloak-rejects-exchange'],
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
query: 'redis noauth error on every call',
|
|
199
|
+
relevant: ['redis:noauth-on-every-call'],
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
query: 'redis memory keeps growing unbounded',
|
|
203
|
+
relevant: ['redis:keys-no-ttl-memory-leak'],
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
query: 'npm ci fails in github actions after adding dependency',
|
|
207
|
+
relevant: ['ci:npm-ci-lockfile-mismatch'],
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
query: 'cannot save settings cors preflight blocked',
|
|
211
|
+
relevant: ['frontend:cors-preflight-blocked'],
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
query: 'docker image too big slow ci push',
|
|
215
|
+
relevant: ['deploy:docker:image-too-large'],
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
query: 'go lint failing on unchecked return value',
|
|
219
|
+
relevant: ['ci:golangci-lint-errcheck'],
|
|
220
|
+
},
|
|
221
|
+
// Multi-relevant: both postgres performance lessons are reasonable answers.
|
|
222
|
+
{
|
|
223
|
+
query: 'postgres performance problem in production',
|
|
224
|
+
relevant: ['db:postgres:connection-pool-exhausted', 'db:postgres:slow-query-missing-index'],
|
|
225
|
+
},
|
|
226
|
+
];
|
package/src/handlers/brain.ts
CHANGED
|
@@ -8,22 +8,34 @@ import type { CKGEdge, CKGNode } from '../ckg.js';
|
|
|
8
8
|
import { keywordSearch, tokenize, splitMultiQuery, levenshtein,
|
|
9
9
|
ZERO_RESULTS_LOG, zeroResultsTotal, indexVocab as _indexVocab } from '../search.js';
|
|
10
10
|
import type { KeywordMatch } from '../search.js';
|
|
11
|
+
import { rerankByQuality } from '../rerank.js';
|
|
11
12
|
import { computeEmbedding, hasEmbedProvider, embedProviderHint, EMBED_PROVIDER } from '../embeddings.js';
|
|
12
13
|
import { detectNamespace } from '../namespace.js';
|
|
13
14
|
|
|
14
15
|
// ── Changelog (shown once per version in session_start) ──────────────────────
|
|
15
|
-
const MCP_VERSION = '0.10.
|
|
16
|
+
const MCP_VERSION = '0.10.51';
|
|
16
17
|
const WHATS_NEW: Record<string, string[]> = {
|
|
17
|
-
'0.10.
|
|
18
|
+
'0.10.51': [
|
|
18
19
|
`🆕 **What's new in v${MCP_VERSION}:**`,
|
|
20
|
+
` ✅ \`team_confirm\` — endorse a lesson in code/knowledge review; reviewed knowledge ranks higher (🛡️ senior / ✔️ peer)`,
|
|
21
|
+
` ✅ Governance-aware recall — human-confirmed lessons outrank unreviewed auto-learned entries`,
|
|
22
|
+
` ✅ \`team_recall\` — shows reviewer badges and sorts confirmed lessons first`,
|
|
23
|
+
` 💡 Run \`team_confirm(topic, reviewer, level="senior")\` to bless the canonical solution`,
|
|
24
|
+
],
|
|
25
|
+
'0.10.50': [
|
|
26
|
+
` ✅ \`smart_recall\` — unified keyword + semantic hybrid list (one ranked result, not two sections)`,
|
|
27
|
+
` ✅ \`smart_recall\` — "Brain saved you here" banner surfaces time saved inline per proven lesson`,
|
|
28
|
+
` ✅ Quality reranking — proven successes outrank symptom-dense failures (+11% Precision@1)`,
|
|
29
|
+
` ✅ Cachly-Bench — IR benchmark with CI regression guard (see BENCH.md for the proof)`,
|
|
30
|
+
` 🔧 Contradiction resolution now persisted to Redis (90-day TTL)`,
|
|
31
|
+
` 💡 Run \`smart_recall\` to see your Brain's recall quality in action`,
|
|
32
|
+
],
|
|
33
|
+
'0.10.49': [
|
|
19
34
|
` ✅ \`brain_from_git\` — auto-seed your Brain from git history in seconds`,
|
|
20
35
|
` ✅ \`brain_predict_failures\` — predict CI/build failures before they happen`,
|
|
21
|
-
` ✅ \`smart_recall\` — semantic + keyword hybrid recall, now in every CLAUDE.md`,
|
|
22
36
|
` ✅ VS Code extension — Brain status bar, ambient learning, CodeLens hints`,
|
|
23
37
|
` ✅ Team Brain — share lessons across your whole engineering team`,
|
|
24
|
-
` ✅ 89 MCP tools — roadmap, A/B tests, cache, index, predict, syndicate`,
|
|
25
38
|
` 🔧 Stability — auto-expiring memory keys, longer provisioning wait, robust recall`,
|
|
26
|
-
` 💡 Run \`brain_from_git\` to seed your Brain from existing commits instantly`,
|
|
27
39
|
],
|
|
28
40
|
};
|
|
29
41
|
|
|
@@ -141,6 +153,18 @@ export async function handleBrainTool(
|
|
|
141
153
|
const resId = ckgSlug(`resolution:${topic}`);
|
|
142
154
|
await ckgUpdateEdge(redis, cId, 'contradicts', resId, false);
|
|
143
155
|
} catch { /* non-critical */ }
|
|
156
|
+
// Persist a queryable resolution record — so contradiction history survives
|
|
157
|
+
// (CKG edges alone aren't easily auditable). Bounded + TTL'd like other history.
|
|
158
|
+
try {
|
|
159
|
+
const resolutionKey = `cachly:contradictions:${topic}`;
|
|
160
|
+
const direction = prev.outcome === 'success' && outcome === 'failure'
|
|
161
|
+
? 'kept-success' : 'overwrote-failure';
|
|
162
|
+
await redis.rpush(resolutionKey, JSON.stringify({
|
|
163
|
+
ts, prev_outcome: prev.outcome, new_outcome: outcome, direction,
|
|
164
|
+
}));
|
|
165
|
+
await redis.ltrim(resolutionKey, -50, -1);
|
|
166
|
+
await redis.expire(resolutionKey, 180 * 86400);
|
|
167
|
+
} catch { /* non-critical */ }
|
|
144
168
|
contradictionWarning.push(`🗳️ Run \`madc_deliberate(topic="${topic}")\` to resolve via expert agent voting.`);
|
|
145
169
|
}
|
|
146
170
|
} catch { /* ignore parse error */ }
|
|
@@ -500,114 +524,173 @@ export async function handleBrainTool(
|
|
|
500
524
|
const redis = await getConnection(instance_id);
|
|
501
525
|
|
|
502
526
|
// ── Layer 1: Keyword search across ALL brain data (always works, no embedding) ──
|
|
503
|
-
const
|
|
527
|
+
const rawMatches = await keywordSearch(
|
|
504
528
|
redis,
|
|
505
529
|
['cachly:ctx:*', 'cachly:lesson:best:*', 'cachly:idx:*'],
|
|
506
530
|
query,
|
|
507
531
|
10,
|
|
508
532
|
);
|
|
509
533
|
|
|
510
|
-
//
|
|
511
|
-
//
|
|
534
|
+
// ── Layer 1.5: Quality-aware rerank — proven success lessons outrank
|
|
535
|
+
// text-similar failed attempts (the moat; see src/rerank.ts + Cachly-Bench). ──
|
|
536
|
+
const kwMatches = rerankByQuality(rawMatches);
|
|
537
|
+
|
|
538
|
+
// Increment recall_count on matched lessons (fire-and-forget) + collect "Brain saved you here" signal.
|
|
539
|
+
type RecalledLesson = { topic: string; severity: string; recall_count: number; savedMins: number };
|
|
540
|
+
const savedHere: RecalledLesson[] = [];
|
|
512
541
|
const lessonMatches = kwMatches.filter(m => m.key.startsWith('cachly:lesson:best:'));
|
|
513
542
|
for (const m of lessonMatches.slice(0, 5)) {
|
|
514
543
|
const existing = await redis.get(m.key).catch(() => null);
|
|
515
544
|
if (existing) {
|
|
516
|
-
const lesson = safeJsonParse(existing, null as null | { recall_count?: number; [k: string]: unknown });
|
|
545
|
+
const lesson = safeJsonParse(existing, null as null | { recall_count?: number; outcome?: string; severity?: string; [k: string]: unknown });
|
|
517
546
|
if (lesson) {
|
|
518
547
|
const updated = { ...lesson, recall_count: (lesson.recall_count ?? 0) + 1, verified_at: new Date().toISOString() };
|
|
519
548
|
redis.set(m.key, JSON.stringify(updated)).catch(() => {});
|
|
520
|
-
const
|
|
549
|
+
const sev = lesson.severity as string;
|
|
550
|
+
const savedMins = sev === 'critical' ? 240 : sev === 'major' ? 60 : 30;
|
|
521
551
|
redis.incrbyfloat(`cachly:stats:time_saved_mins:${instance_id}`, savedMins).catch(() => {});
|
|
552
|
+
// Surface banner for proven successes (recall_count >= 1 means it's been validated)
|
|
553
|
+
if (lesson.outcome === 'success' && (lesson.recall_count ?? 0) >= 1) {
|
|
554
|
+
savedHere.push({
|
|
555
|
+
topic: m.key.replace('cachly:lesson:best:', ''),
|
|
556
|
+
severity: sev ?? 'major',
|
|
557
|
+
recall_count: (lesson.recall_count ?? 0) + 1,
|
|
558
|
+
savedMins,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ── Layer 2: Semantic search (parallel, optional) ────────────────────────
|
|
566
|
+
const inst = await apiFetch<Instance>(`/api/v1/instances/${instance_id}`);
|
|
567
|
+
type SemHit = { key: string; similarity: number; content: string };
|
|
568
|
+
const semHits: SemHit[] = [];
|
|
569
|
+
if (inst.vector_token && hasEmbedProvider()) {
|
|
570
|
+
try {
|
|
571
|
+
const embedding = await computeEmbedding(query);
|
|
572
|
+
const vectorUrl = `https://api.cachly.dev/v1/sem/${inst.vector_token}`;
|
|
573
|
+
const searchRes = await fetch(`${vectorUrl}/search`, {
|
|
574
|
+
method: 'POST',
|
|
575
|
+
headers: { 'Content-Type': 'application/json' },
|
|
576
|
+
body: JSON.stringify({ embedding, namespace: 'cachly:ctx', threshold, top_k: 5 }),
|
|
577
|
+
});
|
|
578
|
+
if (searchRes.ok) {
|
|
579
|
+
const results = (await searchRes.json()) as SemanticSearchResponse[];
|
|
580
|
+
for (const hit of results.filter(r => r.found && r.id)) {
|
|
581
|
+
const parts = hit.id!.replace('ctx:', '').split(':');
|
|
582
|
+
const category = parts[0];
|
|
583
|
+
const key = parts.slice(1).join(':');
|
|
584
|
+
const redisKey = `cachly:ctx:${category}:${key}`;
|
|
585
|
+
const content = await redis.get(redisKey).catch(() => null);
|
|
586
|
+
semHits.push({ key: redisKey, similarity: hit.similarity ?? 0, content: content ?? '(evicted)' });
|
|
587
|
+
}
|
|
522
588
|
}
|
|
589
|
+
} catch {
|
|
590
|
+
// Semantic search failed silently — keyword results are enough
|
|
523
591
|
}
|
|
524
592
|
}
|
|
525
593
|
|
|
594
|
+
// ── Layer 3: Hybrid merge — one unified ranked list ──────────────────────
|
|
595
|
+
// BM25 quality scores (already reranked) are re-normalized to [0,1] for merging.
|
|
596
|
+
type HybridResult = {
|
|
597
|
+
key: string; content: string; hybridScore: number;
|
|
598
|
+
bm25Score?: number; semScore?: number; matchedWords?: string[];
|
|
599
|
+
matchType: 'keyword' | 'semantic' | 'hybrid'; subQuery?: string;
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
const bm25Scores = kwMatches.map(m => m.score);
|
|
603
|
+
const bm25Min = bm25Scores.length ? Math.min(...bm25Scores) : 0;
|
|
604
|
+
const bm25Range = bm25Scores.length ? (Math.max(...bm25Scores) - bm25Min) || 1 : 1;
|
|
605
|
+
const bm25Norm = (s: number) => (s - bm25Min) / bm25Range;
|
|
606
|
+
|
|
607
|
+
const hybridMap = new Map<string, HybridResult>();
|
|
608
|
+
for (const m of kwMatches) {
|
|
609
|
+
const n = bm25Norm(m.score);
|
|
610
|
+
hybridMap.set(m.key, {
|
|
611
|
+
key: m.key, content: m.content, bm25Score: n,
|
|
612
|
+
hybridScore: n * (semHits.length > 0 ? 0.7 : 1.0),
|
|
613
|
+
matchedWords: m.matchedWords, matchType: 'keyword', subQuery: m.subQuery,
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
for (const hit of semHits) {
|
|
617
|
+
const existing = hybridMap.get(hit.key);
|
|
618
|
+
if (existing) {
|
|
619
|
+
existing.semScore = hit.similarity;
|
|
620
|
+
existing.hybridScore = (existing.bm25Score ?? 0) * 0.6 + hit.similarity * 0.4;
|
|
621
|
+
existing.matchType = 'hybrid';
|
|
622
|
+
} else {
|
|
623
|
+
hybridMap.set(hit.key, {
|
|
624
|
+
key: hit.key, content: hit.content, semScore: hit.similarity,
|
|
625
|
+
hybridScore: hit.similarity * 0.5, matchType: 'semantic',
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const hybridResults = [...hybridMap.values()].sort((a, b) => b.hybridScore - a.hybridScore);
|
|
630
|
+
|
|
631
|
+
// ── Build output ──────────────────────────────────────────────────────────
|
|
526
632
|
const lines: string[] = [`🧠 **Smart Recall** for: _"${query}"_\n`];
|
|
527
633
|
|
|
634
|
+
// "Brain saved you here" banner — surfaces value inline for proven recalled lessons
|
|
635
|
+
const SORDER: Record<string, number> = { critical: 0, major: 1, minor: 2 };
|
|
636
|
+
const topLesson = savedHere.sort((a, b) => (SORDER[a.severity] ?? 1) - (SORDER[b.severity] ?? 1))[0];
|
|
637
|
+
if (topLesson) {
|
|
638
|
+
lines.push(`> 💡 **Brain saved you ~${topLesson.savedMins}m here** — ${topLesson.severity} issue from \`${topLesson.topic}\` recalled ${topLesson.recall_count}× proven\n`);
|
|
639
|
+
}
|
|
640
|
+
|
|
528
641
|
// Show sub-query info if multi-topic was detected
|
|
529
642
|
const subQueries = splitMultiQuery(query);
|
|
530
643
|
if (subQueries.length > 1) {
|
|
531
644
|
lines.push(`_Detected ${subQueries.length} sub-topics:_ ${subQueries.map((s, i) => `${i + 1}. "${s}"`).join(', ')}\n`);
|
|
532
645
|
}
|
|
533
646
|
|
|
534
|
-
if (
|
|
535
|
-
|
|
647
|
+
if (hybridResults.length > 0) {
|
|
648
|
+
const modeLabel = semHits.length > 0
|
|
649
|
+
? `keyword + semantic hybrid`
|
|
650
|
+
: `keyword`;
|
|
651
|
+
lines.push(`### 🔍 Results (${hybridResults.length} — ${modeLabel})\n`);
|
|
536
652
|
|
|
537
|
-
// Group by sub-query
|
|
653
|
+
// Group by sub-query for multi-topic queries
|
|
538
654
|
if (subQueries.length > 1) {
|
|
539
|
-
const grouped = new Map<string,
|
|
540
|
-
for (const
|
|
541
|
-
const sq =
|
|
655
|
+
const grouped = new Map<string, HybridResult[]>();
|
|
656
|
+
for (const r of hybridResults.slice(0, 12)) {
|
|
657
|
+
const sq = r.subQuery ?? query;
|
|
542
658
|
if (!grouped.has(sq)) grouped.set(sq, []);
|
|
543
|
-
grouped.get(sq)!.push(
|
|
659
|
+
grouped.get(sq)!.push(r);
|
|
544
660
|
}
|
|
545
|
-
for (const [sq,
|
|
546
|
-
lines.push(`**Topic: "${sq}"** (${
|
|
547
|
-
for (const
|
|
548
|
-
const label =
|
|
549
|
-
|
|
550
|
-
.
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
661
|
+
for (const [sq, results] of grouped) {
|
|
662
|
+
lines.push(`**Topic: "${sq}"** (${results.length} results)\n`);
|
|
663
|
+
for (const r of results.slice(0, 4)) {
|
|
664
|
+
const label = r.key.replace('cachly:ctx:', '📝 ').replace('cachly:lesson:best:', '💡 ').replace('cachly:idx:', '📂 ');
|
|
665
|
+
const scorePart = r.matchType === 'hybrid'
|
|
666
|
+
? `BM25: ${(r.bm25Score ?? 0).toFixed(2)}, sem: ${((r.semScore ?? 0) * 100).toFixed(0)}%, 🔀 hybrid`
|
|
667
|
+
: r.matchType === 'semantic'
|
|
668
|
+
? `sem: ${((r.semScore ?? 0) * 100).toFixed(0)}%, 🎯 semantic`
|
|
669
|
+
: `BM25: ${(r.bm25Score ?? 0).toFixed(2)}, matched: ${r.matchedWords?.join(', ')}`;
|
|
670
|
+
const preview = r.content.slice(0, 300).replace(/\n/g, ' ');
|
|
671
|
+
lines.push(` **${label}** _(${scorePart})_`);
|
|
672
|
+
lines.push(` > ${preview}${r.content.length > 300 ? '…' : ''}\n`);
|
|
555
673
|
}
|
|
556
674
|
}
|
|
557
|
-
// Summary: which sub-queries had matches
|
|
558
675
|
const matched = [...grouped.keys()];
|
|
559
676
|
const unmatched = subQueries.filter(sq => !matched.includes(sq));
|
|
560
677
|
if (unmatched.length > 0) {
|
|
561
678
|
lines.push(`\n⚠️ **No results for:** ${unmatched.map(s => `"${s}"`).join(', ')}`);
|
|
562
679
|
}
|
|
563
680
|
} else {
|
|
564
|
-
for (const
|
|
565
|
-
const label =
|
|
566
|
-
|
|
567
|
-
.
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
681
|
+
for (const r of hybridResults.slice(0, 8)) {
|
|
682
|
+
const label = r.key.replace('cachly:ctx:', '📝 ').replace('cachly:lesson:best:', '💡 ').replace('cachly:idx:', '📂 ');
|
|
683
|
+
const scorePart = r.matchType === 'hybrid'
|
|
684
|
+
? `BM25: ${(r.bm25Score ?? 0).toFixed(2)}, sem: ${((r.semScore ?? 0) * 100).toFixed(0)}%, 🔀 hybrid`
|
|
685
|
+
: r.matchType === 'semantic'
|
|
686
|
+
? `sem: ${((r.semScore ?? 0) * 100).toFixed(0)}%, 🎯 semantic`
|
|
687
|
+
: `BM25: ${(r.bm25Score ?? 0).toFixed(2)}, matched: ${r.matchedWords?.join(', ')}`;
|
|
688
|
+
const preview = r.content.slice(0, 400).replace(/\n/g, ' ');
|
|
689
|
+
lines.push(`**${label}** _(${scorePart})_`);
|
|
690
|
+
lines.push(`> ${preview}${r.content.length > 400 ? '…' : ''}\n`);
|
|
572
691
|
}
|
|
573
692
|
}
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
// ── Layer 2: Semantic search (optional, only if embedding provider + vector_token available) ──
|
|
577
|
-
const inst = await apiFetch<Instance>(`/api/v1/instances/${instance_id}`);
|
|
578
|
-
if (inst.vector_token && hasEmbedProvider()) {
|
|
579
|
-
try {
|
|
580
|
-
const embedding = await computeEmbedding(query);
|
|
581
|
-
const vectorUrl = `https://api.cachly.dev/v1/sem/${inst.vector_token}`;
|
|
582
|
-
const searchRes = await fetch(`${vectorUrl}/search`, {
|
|
583
|
-
method: 'POST',
|
|
584
|
-
headers: { 'Content-Type': 'application/json' },
|
|
585
|
-
body: JSON.stringify({ embedding, namespace: 'cachly:ctx', threshold, top_k: 5 }),
|
|
586
|
-
});
|
|
587
|
-
|
|
588
|
-
if (searchRes.ok) {
|
|
589
|
-
const results = (await searchRes.json()) as SemanticSearchResponse[];
|
|
590
|
-
const semHits = results.filter(r => r.found && r.id);
|
|
591
|
-
if (semHits.length > 0) {
|
|
592
|
-
lines.push(`\n### 🎯 Semantic Matches (${semHits.length})\n`);
|
|
593
|
-
for (const hit of semHits) {
|
|
594
|
-
const parts = hit.id!.replace('ctx:', '').split(':');
|
|
595
|
-
const category = parts[0];
|
|
596
|
-
const key = parts.slice(1).join(':');
|
|
597
|
-
const content = await redis.get(`cachly:ctx:${category}:${key}`);
|
|
598
|
-
lines.push(
|
|
599
|
-
`**${key}** _(${((hit.similarity ?? 0) * 100).toFixed(0)}% similar)_`,
|
|
600
|
-
`> ${content?.slice(0, 300) ?? '(evicted)'}${(content?.length ?? 0) > 300 ? '…' : ''}\n`,
|
|
601
|
-
);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
} catch {
|
|
606
|
-
// Semantic search failed silently — keyword results are enough
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
if (kwMatches.length === 0) {
|
|
693
|
+
} else {
|
|
611
694
|
lines.push(`⚠️ No matches found for: "${query}"`);
|
|
612
695
|
|
|
613
696
|
// Did-You-Mean: find nearest token in index vocab
|
package/src/handlers/team.ts
CHANGED
|
@@ -11,7 +11,7 @@ type GetConnection = (instanceId: string) => Promise<Redis>;
|
|
|
11
11
|
type ApiFetch = <T>(path: string, options?: RequestInit) => Promise<T>;
|
|
12
12
|
|
|
13
13
|
export const TEAM_TOOL_NAMES = new Set([
|
|
14
|
-
'sync_file_changes', 'team_learn', 'team_recall', 'team_synthesize', 'memory_crystalize',
|
|
14
|
+
'sync_file_changes', 'team_learn', 'team_confirm', 'team_recall', 'team_synthesize', 'memory_crystalize',
|
|
15
15
|
'brain_doctor', 'recall_at', 'trace_dependency', 'global_learn', 'global_recall',
|
|
16
16
|
'publish_lesson', 'import_public_brain', 'setup_ai_memory',
|
|
17
17
|
]);
|
|
@@ -124,6 +124,59 @@ export async function handleTeamTool(
|
|
|
124
124
|
return `✅ Team lesson stored by **${author}**: \`${topic}\` (${outcome})\n💡 ${what_worked.slice(0, 120)}`;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
+
// ── team_confirm — knowledge governance (Phase 3) ─────────────────────────
|
|
128
|
+
// A human reviewer endorses a stored lesson. The endorsement raises the
|
|
129
|
+
// lesson's recall ranking (see src/rerank.ts), so trusted, reviewed knowledge
|
|
130
|
+
// surfaces above unreviewed auto-learned entries.
|
|
131
|
+
case 'team_confirm': {
|
|
132
|
+
const { instance_id, topic, reviewer, level = 'peer', note = '' } = args as {
|
|
133
|
+
instance_id: string; topic: string; reviewer: string;
|
|
134
|
+
level?: 'senior' | 'peer'; note?: string;
|
|
135
|
+
};
|
|
136
|
+
if (!instance_id) return '❌ instance_id required';
|
|
137
|
+
if (!topic || !reviewer) return '❌ Required: topic, reviewer';
|
|
138
|
+
const reviewLevel = level === 'senior' ? 'senior' : 'peer';
|
|
139
|
+
|
|
140
|
+
const redis = await getConnection(instance_id);
|
|
141
|
+
const key = `cachly:lesson:best:${topic}`;
|
|
142
|
+
const raw = await redis.get(key);
|
|
143
|
+
const lesson = safeJsonParse<Record<string, unknown> | null>(raw, null);
|
|
144
|
+
if (!lesson) {
|
|
145
|
+
return `📭 No best-solution lesson found for \`${topic}\`.\n\nA lesson must exist (store one with \`team_learn\` / \`learn_from_attempts\`) before it can be confirmed.`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Track distinct reviewers so endorsements can't be inflated by one person.
|
|
149
|
+
const endorsersKey = `cachly:lesson:endorsers:${topic}`;
|
|
150
|
+
const added = await redis.sadd(endorsersKey, reviewer);
|
|
151
|
+
await redis.expire(endorsersKey, 365 * 86400);
|
|
152
|
+
const endorsements = await redis.scard(endorsersKey);
|
|
153
|
+
|
|
154
|
+
// Senior beats peer; never downgrade an existing senior review to peer.
|
|
155
|
+
const prevLevel = (lesson.review_level as string) ?? '';
|
|
156
|
+
const effectiveLevel = prevLevel === 'senior' ? 'senior' : reviewLevel;
|
|
157
|
+
|
|
158
|
+
const updated = {
|
|
159
|
+
...lesson,
|
|
160
|
+
reviewed_by: reviewer,
|
|
161
|
+
review_level: effectiveLevel,
|
|
162
|
+
endorsements,
|
|
163
|
+
reviewed_at: new Date().toISOString(),
|
|
164
|
+
};
|
|
165
|
+
await redis.set(key, JSON.stringify(updated));
|
|
166
|
+
|
|
167
|
+
// Append an immutable review record for the audit trail.
|
|
168
|
+
const reviewLog = {
|
|
169
|
+
reviewer, level: reviewLevel, note: note.slice(0, 280), ts: new Date().toISOString(),
|
|
170
|
+
};
|
|
171
|
+
const logKey = `cachly:lesson:reviews:${topic}`;
|
|
172
|
+
await redis.rpush(logKey, JSON.stringify(reviewLog));
|
|
173
|
+
await redis.ltrim(logKey, -50, -1);
|
|
174
|
+
await redis.expire(logKey, 365 * 86400);
|
|
175
|
+
|
|
176
|
+
const badge = effectiveLevel === 'senior' ? '🛡️ senior-reviewed' : '✔️ peer-reviewed';
|
|
177
|
+
return `${badge} — \`${topic}\` confirmed by **${reviewer}** (${endorsements} distinct endorsement${endorsements === 1 ? '' : 's'}).\n📈 This lesson now ranks higher in \`smart_recall\` / \`team_recall\`.${note ? `\n📝 ${note.slice(0, 200)}` : ''}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
127
180
|
// ── team_recall ───────────────────────────────────────────────────────────
|
|
128
181
|
case 'team_recall': {
|
|
129
182
|
const { instance_id, topic, author, limit = 10 } = args as {
|
|
@@ -146,6 +199,7 @@ export async function handleTeamTool(
|
|
|
146
199
|
topic: string; outcome: string; what_worked: string;
|
|
147
200
|
ts: string; severity?: string; recall_count?: number;
|
|
148
201
|
author?: string; tags?: string[];
|
|
202
|
+
reviewed_by?: string; review_level?: string; endorsements?: number;
|
|
149
203
|
};
|
|
150
204
|
let lessons: TeamLesson[] = [];
|
|
151
205
|
if (lessonKeys.length > 0) {
|
|
@@ -169,8 +223,10 @@ export async function handleTeamTool(
|
|
|
169
223
|
lessons = lessons.filter(l => l.author?.toLowerCase().includes(a));
|
|
170
224
|
}
|
|
171
225
|
|
|
172
|
-
// Sort by recall_count desc
|
|
173
|
-
|
|
226
|
+
// Sort: reviewed lessons first (senior > peer), then by recall_count desc.
|
|
227
|
+
const reviewRank = (l: TeamLesson) => l.reviewed_by ? (l.review_level === 'senior' ? 2 : 1) : 0;
|
|
228
|
+
lessons.sort((a, b) =>
|
|
229
|
+
(reviewRank(b) - reviewRank(a)) || ((b.recall_count ?? 0) - (a.recall_count ?? 0)));
|
|
174
230
|
lessons = lessons.slice(0, limit);
|
|
175
231
|
|
|
176
232
|
if (lessons.length === 0) {
|
|
@@ -183,11 +239,17 @@ export async function handleTeamTool(
|
|
|
183
239
|
for (const l of lessons) {
|
|
184
240
|
const emoji = l.outcome === 'success' ? '✅' : l.outcome === 'partial' ? '⚠️' : '❌';
|
|
185
241
|
const sev = l.severity === 'critical' ? '🔴 ' : l.severity === 'major' ? '🟡 ' : '';
|
|
242
|
+
const reviewBadge = l.reviewed_by
|
|
243
|
+
? (l.review_level === 'senior' ? ' 🛡️' : ' ✔️')
|
|
244
|
+
: '';
|
|
186
245
|
const authorStr = l.author ? ` · _by ${l.author}_` : '';
|
|
246
|
+
const reviewStr = l.reviewed_by
|
|
247
|
+
? ` · reviewed by ${l.reviewed_by}${(l.endorsements ?? 0) > 1 ? ` +${(l.endorsements ?? 0) - 1}` : ''}`
|
|
248
|
+
: '';
|
|
187
249
|
const recallStr = (l.recall_count ?? 0) > 0 ? ` · recalled ${l.recall_count}×` : '';
|
|
188
250
|
const ago = Math.round((Date.now() - new Date(l.ts).getTime()) / 86400000);
|
|
189
251
|
const agoStr = ago === 0 ? 'today' : ago === 1 ? 'yesterday' : `${ago}d ago`;
|
|
190
|
-
lines.push(`${emoji} ${sev}**\`${l.topic}\`**${authorStr}${recallStr} · ${agoStr}`);
|
|
252
|
+
lines.push(`${emoji} ${sev}**\`${l.topic}\`**${reviewBadge}${authorStr}${reviewStr}${recallStr} · ${agoStr}`);
|
|
191
253
|
lines.push(` ${l.what_worked.slice(0, 120)}`);
|
|
192
254
|
lines.push('');
|
|
193
255
|
}
|