@mcptoolshop/claude-synergy 1.1.0 → 1.2.0

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.
@@ -0,0 +1,743 @@
1
+ import {
2
+ AppError,
3
+ getEmbeddingDim,
4
+ makeEmbeddingProvider,
5
+ providerTimeoutMs,
6
+ safeErrorBody,
7
+ withRetry
8
+ } from "./chunk-CEIOLMDT.js";
9
+
10
+ // src/query.ts
11
+ function searchChanges(db, query, opts = {}) {
12
+ const limit = opts.limit ?? 20;
13
+ const filters = [];
14
+ const params = { query, limit };
15
+ if (opts.product) {
16
+ filters.push("c.product = @product");
17
+ params.product = opts.product;
18
+ }
19
+ if (opts.since) {
20
+ filters.push("r.released_at >= @since");
21
+ params.since = opts.since;
22
+ }
23
+ if (opts.until) {
24
+ filters.push("r.released_at <= @until");
25
+ params.until = opts.until;
26
+ }
27
+ if (opts.kind) {
28
+ filters.push("c.kind = @kind");
29
+ params.kind = opts.kind;
30
+ }
31
+ const where = filters.length > 0 ? `AND ${filters.join(" AND ")}` : "";
32
+ const sql = `
33
+ SELECT c.product, c.version, r.released_at,
34
+ c.ordinal, c.kind, c.text AS body,
35
+ snippet(changes_fts, 0, '[[', ']]', '\u2026', 16) AS snippet
36
+ FROM changes_fts
37
+ JOIN changes c ON changes_fts.rowid = c.id
38
+ JOIN releases r ON c.product = r.product AND c.version = r.version
39
+ WHERE changes_fts MATCH @query
40
+ ${where}
41
+ ORDER BY r.released_at DESC, c.ordinal ASC
42
+ LIMIT @limit
43
+ `;
44
+ const rows = db.prepare(sql).all(params);
45
+ return rows.map((r) => ({ ...r, text: r.body }));
46
+ }
47
+ function lookupEntity(db, type, value) {
48
+ const sql = `
49
+ SELECT c.product, c.version, r.released_at, c.ordinal, c.kind, c.text,
50
+ '' AS snippet
51
+ FROM entities e
52
+ JOIN changes c ON e.change_id = c.id
53
+ JOIN releases r ON c.product = r.product AND c.version = r.version
54
+ WHERE e.entity_type = ? AND e.entity_value = ?
55
+ ORDER BY r.released_at ASC, c.product
56
+ `;
57
+ return db.prepare(sql).all(type, value);
58
+ }
59
+ function recentReleases(db, product, limit = 20, since) {
60
+ const filters = [];
61
+ const params = { limit };
62
+ if (product) {
63
+ filters.push("r.product = @product");
64
+ params.product = product;
65
+ }
66
+ if (since) {
67
+ filters.push("r.released_at >= @since");
68
+ params.since = since;
69
+ }
70
+ const where = filters.length > 0 ? `WHERE ${filters.join(" AND ")}` : "";
71
+ const sql = `
72
+ SELECT r.product, r.version, r.released_at, COUNT(c.id) AS change_count
73
+ FROM releases r
74
+ LEFT JOIN changes c ON c.product = r.product AND c.version = r.version
75
+ ${where}
76
+ GROUP BY r.product, r.version
77
+ ORDER BY r.released_at DESC
78
+ LIMIT @limit
79
+ `;
80
+ return db.prepare(sql).all(params);
81
+ }
82
+ function listProducts(db) {
83
+ const sql = `
84
+ SELECT p.name, p.display_name,
85
+ COUNT(DISTINCT r.version) AS release_count,
86
+ (SELECT version FROM releases r2 WHERE r2.product = p.name ORDER BY r2.released_at DESC LIMIT 1) AS latest_version,
87
+ (SELECT released_at FROM releases r2 WHERE r2.product = p.name ORDER BY r2.released_at DESC LIMIT 1) AS latest_date
88
+ FROM products p
89
+ LEFT JOIN releases r ON r.product = p.name
90
+ GROUP BY p.name
91
+ ORDER BY release_count DESC
92
+ `;
93
+ return db.prepare(sql).all();
94
+ }
95
+ function getSyncStatus(db, opts = {}) {
96
+ const filters = [];
97
+ const params = {};
98
+ if (opts.product) {
99
+ filters.push("p.name = @product");
100
+ params.product = opts.product;
101
+ }
102
+ const where = filters.length > 0 ? `WHERE ${filters.join(" AND ")}` : "";
103
+ const sql = `
104
+ SELECT p.name AS product,
105
+ p.fetch_strategy AS fetch_strategy,
106
+ m.version AS last_release_at,
107
+ m.updated_at AS last_fetch_attempt,
108
+ CASE WHEN m.updated_at IS NULL THEN NULL
109
+ ELSE ROUND((julianday('now') - julianday(m.updated_at)) * 24.0, 1)
110
+ END AS hours_since_fetch,
111
+ (SELECT COUNT(DISTINCT r.version)
112
+ FROM releases r
113
+ WHERE r.product = p.name) AS releases_ingested
114
+ FROM products p
115
+ LEFT JOIN markers m
116
+ ON m.product = p.name
117
+ AND m.name = 'last_fetched_release_at'
118
+ ${where}
119
+ ORDER BY (hours_since_fetch IS NULL) DESC,
120
+ hours_since_fetch DESC,
121
+ p.name ASC
122
+ `;
123
+ const rows = db.prepare(sql).all(params);
124
+ if (opts.staleOnly) {
125
+ const cutoff = opts.staleHours ?? 24;
126
+ return rows.filter((r) => r.hours_since_fetch === null || r.hours_since_fetch > cutoff);
127
+ }
128
+ return rows;
129
+ }
130
+ function entityFrequency(db, type, limit = 30) {
131
+ const sql = `
132
+ SELECT e.entity_value AS value,
133
+ COUNT(*) AS count,
134
+ MIN(r.released_at) AS first_seen
135
+ FROM entities e
136
+ JOIN changes c ON e.change_id = c.id
137
+ JOIN releases r ON c.product = r.product AND c.version = r.version
138
+ WHERE e.entity_type = ?
139
+ GROUP BY e.entity_value
140
+ ORDER BY count DESC, first_seen ASC
141
+ LIMIT ?
142
+ `;
143
+ return db.prepare(sql).all(type, limit);
144
+ }
145
+ function browseChanges(db, opts = {}) {
146
+ const limit = opts.limit ?? 20;
147
+ const filters = [];
148
+ const params = { limit };
149
+ if (opts.product) {
150
+ filters.push("c.product = @product");
151
+ params.product = opts.product;
152
+ }
153
+ if (opts.since) {
154
+ filters.push("r.released_at >= @since");
155
+ params.since = opts.since;
156
+ }
157
+ if (opts.until) {
158
+ filters.push("r.released_at <= @until");
159
+ params.until = opts.until;
160
+ }
161
+ if (opts.kind) {
162
+ filters.push("c.kind = @kind");
163
+ params.kind = opts.kind;
164
+ }
165
+ const where = filters.length > 0 ? `WHERE ${filters.join(" AND ")}` : "";
166
+ const sql = `
167
+ SELECT c.product, c.version, r.released_at,
168
+ c.ordinal, c.kind, c.text AS body,
169
+ '' AS snippet
170
+ FROM changes c
171
+ JOIN releases r ON c.product = r.product AND c.version = r.version
172
+ ${where}
173
+ ORDER BY r.released_at DESC, c.product, c.ordinal ASC
174
+ LIMIT @limit
175
+ `;
176
+ const rows = db.prepare(sql).all(params);
177
+ return rows.map((r) => ({ ...r, text: r.body }));
178
+ }
179
+ function getChangesSince(db, opts) {
180
+ if (!opts.since) {
181
+ throw new AppError({
182
+ code: "QUERY_SINCE_REQUIRED",
183
+ message: "getChangesSince requires a `since` date",
184
+ hint: 'pass since as YYYY-MM-DD (e.g. "2026-01-01")'
185
+ });
186
+ }
187
+ const limit = opts.limit ?? 200;
188
+ const filters = ["r.released_at >= @since"];
189
+ const params = { since: opts.since };
190
+ if (opts.until) {
191
+ filters.push("r.released_at <= @until");
192
+ params.until = opts.until;
193
+ }
194
+ if (opts.product) {
195
+ filters.push("c.product = @product");
196
+ params.product = opts.product;
197
+ }
198
+ if (opts.kind) {
199
+ filters.push("c.kind = @kind");
200
+ params.kind = opts.kind;
201
+ }
202
+ const where = `WHERE ${filters.join(" AND ")}`;
203
+ const sql = `
204
+ SELECT c.product, c.version, r.released_at, c.ordinal, c.kind, c.text
205
+ FROM changes c
206
+ JOIN releases r ON c.product = r.product AND c.version = r.version
207
+ ${where}
208
+ ORDER BY r.released_at DESC, c.product, c.version, c.ordinal ASC
209
+ `;
210
+ const rows = db.prepare(sql).all(params);
211
+ const grouped = /* @__PURE__ */ new Map();
212
+ let total = 0;
213
+ for (const r of rows) {
214
+ if (total >= limit) break;
215
+ const key = `${r.product}@${r.version}`;
216
+ let bucket = grouped.get(key);
217
+ if (!bucket) {
218
+ bucket = {
219
+ product: r.product,
220
+ version: r.version,
221
+ released_at: r.released_at,
222
+ changes: []
223
+ };
224
+ grouped.set(key, bucket);
225
+ }
226
+ bucket.changes.push({ ordinal: r.ordinal, kind: r.kind, text: r.text });
227
+ total++;
228
+ }
229
+ return Array.from(grouped.values());
230
+ }
231
+ function compareVersions(db, opts) {
232
+ if (!opts.product || !opts.fromVersion || !opts.toVersion) {
233
+ throw new AppError({
234
+ code: "QUERY_COMPARE_ARGS",
235
+ message: "compareVersions requires product, fromVersion, and toVersion",
236
+ hint: 'pass all three as strings, e.g. { product: "claude-code", fromVersion: "2.1.100", toVersion: "2.1.147" }'
237
+ });
238
+ }
239
+ const endpoint = db.prepare(`
240
+ SELECT version, released_at FROM releases
241
+ WHERE product = ? AND version = ?
242
+ `);
243
+ const fromRow = endpoint.get(opts.product, opts.fromVersion);
244
+ const toRow = endpoint.get(opts.product, opts.toVersion);
245
+ if (!fromRow || !toRow) {
246
+ return [];
247
+ }
248
+ if (!fromRow.released_at || !toRow.released_at) {
249
+ throw new AppError({
250
+ code: "QUERY_VERSION_NO_DATE",
251
+ message: `cannot compare versions without released_at on both endpoints (${opts.product}@${opts.fromVersion} or ${opts.toVersion} is missing a date)`,
252
+ hint: "re-ingest the affected product so released_at is populated"
253
+ });
254
+ }
255
+ const sql = `
256
+ SELECT c.product, c.version, r.released_at, c.ordinal, c.kind, c.text
257
+ FROM changes c
258
+ JOIN releases r ON c.product = r.product AND c.version = r.version
259
+ WHERE c.product = @product
260
+ AND r.released_at > @fromDate
261
+ AND r.released_at <= @toDate
262
+ ORDER BY r.released_at DESC, c.version, c.ordinal ASC
263
+ `;
264
+ const rows = db.prepare(sql).all({
265
+ product: opts.product,
266
+ fromDate: fromRow.released_at,
267
+ toDate: toRow.released_at
268
+ });
269
+ const grouped = /* @__PURE__ */ new Map();
270
+ for (const r of rows) {
271
+ const key = `${r.product}@${r.version}`;
272
+ let bucket = grouped.get(key);
273
+ if (!bucket) {
274
+ bucket = {
275
+ product: r.product,
276
+ version: r.version,
277
+ released_at: r.released_at,
278
+ changes: []
279
+ };
280
+ grouped.set(key, bucket);
281
+ }
282
+ bucket.changes.push({ ordinal: r.ordinal, kind: r.kind, text: r.text });
283
+ }
284
+ return Array.from(grouped.values());
285
+ }
286
+ function listSynergies(db, opts = {}) {
287
+ const filters = [];
288
+ const params = {};
289
+ if (opts.product) {
290
+ filters.push("s.id IN (SELECT synergy_id FROM synergy_products WHERE product = @product)");
291
+ params.product = opts.product;
292
+ }
293
+ if (opts.status) {
294
+ filters.push("s.status = @status");
295
+ params.status = opts.status;
296
+ }
297
+ const where = filters.length > 0 ? `WHERE ${filters.join(" AND ")}` : "";
298
+ const limitClause = opts.limit ? "LIMIT @limit" : "";
299
+ if (opts.limit) params.limit = opts.limit;
300
+ const sql = `
301
+ SELECT s.id, s.name, s.title, s.trigger, s.status, s.last_validated, s.notes_path
302
+ FROM synergies s
303
+ ${where}
304
+ ORDER BY s.last_validated DESC, s.name
305
+ ${limitClause}
306
+ `;
307
+ const rows = db.prepare(sql).all(params);
308
+ if (rows.length === 0) return [];
309
+ const ids = rows.map((r) => r.id);
310
+ const productsByIdSql = `
311
+ SELECT synergy_id, product FROM synergy_products
312
+ WHERE synergy_id IN (${ids.map(() => "?").join(",")})
313
+ ORDER BY synergy_id, product
314
+ `;
315
+ const productRows = db.prepare(productsByIdSql).all(...ids);
316
+ const productsById = /* @__PURE__ */ new Map();
317
+ for (const pr of productRows) {
318
+ if (!productsById.has(pr.synergy_id)) productsById.set(pr.synergy_id, []);
319
+ productsById.get(pr.synergy_id).push(pr.product);
320
+ }
321
+ return rows.map((r) => ({ ...r, products: productsById.get(r.id) ?? [] }));
322
+ }
323
+ function getSynergy(db, name) {
324
+ const synergy = db.prepare(`
325
+ SELECT id, name, title, trigger, status, last_validated, notes_path
326
+ FROM synergies WHERE name = ?
327
+ `).get(name);
328
+ if (!synergy) return null;
329
+ const products = db.prepare(`SELECT product FROM synergy_products WHERE synergy_id = ? ORDER BY product`).all(synergy.id).map((r) => r.product);
330
+ const steps = db.prepare(`SELECT ordinal, text FROM synergy_steps WHERE synergy_id = ? ORDER BY ordinal`).all(synergy.id);
331
+ const evidence = db.prepare(`SELECT source_url, quote, source_kind FROM synergy_evidence WHERE synergy_id = ?`).all(synergy.id);
332
+ const change_refs = db.prepare(`
333
+ SELECT scr.change_id, c.product, c.version, c.text
334
+ FROM synergy_change_refs scr
335
+ JOIN changes c ON c.id = scr.change_id
336
+ WHERE scr.synergy_id = ?
337
+ ORDER BY c.product, c.version
338
+ `).all(synergy.id);
339
+ return {
340
+ ...synergy,
341
+ products,
342
+ steps,
343
+ evidence,
344
+ change_refs
345
+ };
346
+ }
347
+
348
+ // src/providers/rerank/ollama-judge.ts
349
+ function providerTimeoutMs2() {
350
+ const raw = process.env.CLAUDE_SYNERGY_PROVIDER_TIMEOUT_MS;
351
+ const n = raw === void 0 ? NaN : parseInt(raw, 10);
352
+ return Number.isFinite(n) && n > 0 ? n : 6e4;
353
+ }
354
+ async function safeErrorBody2(res, max = 200) {
355
+ try {
356
+ const body = await res.text();
357
+ const safe = body.split("\n").filter((l) => !/x-api-key|authorization|bearer|api[-_]?key/i.test(l)).join("\n");
358
+ return safe.slice(0, max);
359
+ } catch {
360
+ return "<unreadable>";
361
+ }
362
+ }
363
+ var OllamaJudgeRerankProvider = class {
364
+ name = "ollama-judge";
365
+ host;
366
+ model;
367
+ constructor(opts = {}) {
368
+ const rawHost = opts.host ?? process.env.OLLAMA_HOST ?? "http://localhost:11434";
369
+ this.host = /^https?:\/\//.test(rawHost) ? rawHost : `http://${rawHost}`;
370
+ this.model = opts.model ?? process.env.OLLAMA_RERANK_MODEL ?? "qwen3:8b";
371
+ }
372
+ async rerank(query, candidates) {
373
+ if (candidates.length === 0) return [];
374
+ const docs = candidates.map((c, i) => `Doc ${i + 1}: ${c.text.slice(0, 400)}`).join("\n\n");
375
+ const prompt = [
376
+ `You are a relevance judge for a Claude changelog search.`,
377
+ `Rate each document 0-10 for how well it answers the user's query.`,
378
+ `Respond with EXACTLY ${candidates.length} integers, one per line, in order. No prose, no explanations, no doc numbers, just one integer per line.`,
379
+ ``,
380
+ `Query: ${query}`,
381
+ ``,
382
+ docs,
383
+ ``,
384
+ `Scores (one integer per line, ${candidates.length} lines total):`
385
+ ].join("\n");
386
+ const timeoutMs = providerTimeoutMs2();
387
+ let res;
388
+ try {
389
+ res = await fetch(`${this.host}/api/generate`, {
390
+ method: "POST",
391
+ headers: { "content-type": "application/json" },
392
+ body: JSON.stringify({
393
+ model: this.model,
394
+ prompt,
395
+ stream: false,
396
+ think: false,
397
+ // for qwen3/o1-style models; harmless on others
398
+ options: { temperature: 0, num_predict: Math.max(120, candidates.length * 4) }
399
+ }),
400
+ signal: AbortSignal.timeout(timeoutMs)
401
+ });
402
+ } catch (e) {
403
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") {
404
+ throw new Error(`Ollama judge rerank timed out after ${timeoutMs}ms \u2014 is the Ollama server responsive?`);
405
+ }
406
+ throw e;
407
+ }
408
+ if (!res.ok) throw new Error(`Ollama judge ${res.status}: ${await safeErrorBody2(res)}`);
409
+ const json = await res.json();
410
+ const scores = parseScores(json.response, candidates.length);
411
+ return candidates.map((c, i) => ({ id: c.id, score: scores[i] ?? 0 }));
412
+ }
413
+ };
414
+ function parseScores(response, n) {
415
+ const lines = response.split(/\r?\n/);
416
+ const out = [];
417
+ for (const line of lines) {
418
+ if (out.length >= n) break;
419
+ const m = line.match(/-?\d+(?:\.\d+)?/);
420
+ if (!m) continue;
421
+ const v = parseFloat(m[0]);
422
+ if (Number.isFinite(v)) out.push(Math.max(0, Math.min(10, v)));
423
+ }
424
+ while (out.length < n) out.push(0);
425
+ return out;
426
+ }
427
+
428
+ // src/providers/rerank/voyage.ts
429
+ var VoyageRerankProvider = class {
430
+ name = "voyage";
431
+ apiKey;
432
+ model;
433
+ /** Accumulated usage across all rerank() calls on this instance. */
434
+ _usage = { tokens: 0, requests: 0 };
435
+ constructor(opts = {}) {
436
+ this.apiKey = opts.apiKey ?? process.env.VOYAGE_API_KEY ?? "";
437
+ this.model = opts.model ?? "rerank-2";
438
+ if (!this.apiKey) {
439
+ throw new Error("voyage rerank provider requires VOYAGE_API_KEY");
440
+ }
441
+ }
442
+ /** Get accumulated usage stats. */
443
+ get usage() {
444
+ return { ...this._usage };
445
+ }
446
+ /** Reset accumulated usage counters. */
447
+ resetUsage() {
448
+ this._usage = { tokens: 0, requests: 0 };
449
+ }
450
+ async rerank(query, candidates, signal) {
451
+ if (candidates.length === 0) return [];
452
+ const timeoutMs = providerTimeoutMs();
453
+ const { data: result } = await withRetry(
454
+ async () => {
455
+ let res;
456
+ try {
457
+ res = await fetch("https://api.voyageai.com/v1/rerank", {
458
+ method: "POST",
459
+ headers: {
460
+ "authorization": `Bearer ${this.apiKey}`,
461
+ "content-type": "application/json"
462
+ },
463
+ body: JSON.stringify({
464
+ model: this.model,
465
+ query,
466
+ documents: candidates.map((c) => c.text),
467
+ top_k: candidates.length
468
+ }),
469
+ signal: signal ?? AbortSignal.timeout(timeoutMs)
470
+ });
471
+ } catch (e) {
472
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") {
473
+ throw new Error(`Voyage rerank request timed out after ${timeoutMs}ms \u2014 is the API responsive?`);
474
+ }
475
+ throw e;
476
+ }
477
+ if (!res.ok) throw new Error(`Voyage rerank ${res.status}: ${await safeErrorBody(res)}`);
478
+ const json = await res.json();
479
+ return json;
480
+ },
481
+ { maxAttempts: 3, signal }
482
+ );
483
+ this._usage.requests++;
484
+ if (result.usage?.total_tokens) {
485
+ this._usage.tokens += result.usage.total_tokens;
486
+ }
487
+ return result.data.map((d) => ({
488
+ id: candidates[d.index].id,
489
+ score: d.relevance_score
490
+ }));
491
+ }
492
+ };
493
+
494
+ // src/providers/rerank/cohere.ts
495
+ var CohereRerankProvider = class {
496
+ name = "cohere";
497
+ apiKey;
498
+ model;
499
+ /** Accumulated usage across all rerank() calls on this instance. */
500
+ _usage = { tokens: 0, requests: 0 };
501
+ constructor(opts = {}) {
502
+ this.apiKey = opts.apiKey ?? process.env.COHERE_API_KEY ?? "";
503
+ this.model = opts.model ?? "rerank-v3.5";
504
+ if (!this.apiKey) {
505
+ throw new Error("cohere rerank provider requires COHERE_API_KEY");
506
+ }
507
+ }
508
+ /** Get accumulated usage stats. */
509
+ get usage() {
510
+ return { ...this._usage };
511
+ }
512
+ /** Reset accumulated usage counters. */
513
+ resetUsage() {
514
+ this._usage = { tokens: 0, requests: 0 };
515
+ }
516
+ async rerank(query, candidates, signal) {
517
+ if (candidates.length === 0) return [];
518
+ const timeoutMs = providerTimeoutMs();
519
+ const { data: result } = await withRetry(
520
+ async () => {
521
+ let res;
522
+ try {
523
+ res = await fetch("https://api.cohere.com/v2/rerank", {
524
+ method: "POST",
525
+ headers: {
526
+ "authorization": `Bearer ${this.apiKey}`,
527
+ "content-type": "application/json"
528
+ },
529
+ body: JSON.stringify({
530
+ model: this.model,
531
+ query,
532
+ documents: candidates.map((c) => c.text),
533
+ top_n: candidates.length
534
+ }),
535
+ signal: signal ?? AbortSignal.timeout(timeoutMs)
536
+ });
537
+ } catch (e) {
538
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") {
539
+ throw new Error(`Cohere rerank request timed out after ${timeoutMs}ms \u2014 is the API responsive?`);
540
+ }
541
+ throw e;
542
+ }
543
+ if (!res.ok) throw new Error(`Cohere rerank ${res.status}: ${await safeErrorBody(res)}`);
544
+ const json = await res.json();
545
+ return json;
546
+ },
547
+ { maxAttempts: 3, signal }
548
+ );
549
+ this._usage.requests++;
550
+ if (result.meta?.billed_units?.search_units) {
551
+ this._usage.tokens += result.meta.billed_units.search_units;
552
+ }
553
+ return result.results.map((r) => ({
554
+ id: candidates[r.index].id,
555
+ score: r.relevance_score
556
+ }));
557
+ }
558
+ };
559
+
560
+ // src/hybrid.ts
561
+ var MAX_LIMIT = 500;
562
+ function clampLimit(value, fallback, name) {
563
+ const v = value ?? fallback;
564
+ if (typeof v !== "number" || !Number.isFinite(v)) {
565
+ throw new Error(`hybridSearch: ${name} must be a finite number (got ${String(v)})`);
566
+ }
567
+ const n = v | 0;
568
+ return Math.max(1, Math.min(n, MAX_LIMIT));
569
+ }
570
+ function hasVecTable(db) {
571
+ const tagged = db;
572
+ if (typeof tagged.__synergyHasVec === "boolean") return tagged.__synergyHasVec;
573
+ try {
574
+ db.prepare("SELECT count(*) FROM chunks_vec LIMIT 0").get();
575
+ tagged.__synergyHasVec = true;
576
+ } catch {
577
+ tagged.__synergyHasVec = false;
578
+ }
579
+ return tagged.__synergyHasVec;
580
+ }
581
+ var warnedNoVec = false;
582
+ async function hybridSearch(db, query, opts = {}) {
583
+ const safeLimit = clampLimit(opts.limit, 20, "limit");
584
+ const safeTopK = clampLimit(opts.topK, 60, "topK");
585
+ const rerankRequested = clampLimit(opts.rerankCandidates, 20, "rerankCandidates");
586
+ const safeRerankN = Math.max(safeLimit, rerankRequested);
587
+ const rrfK = opts.rrfK ?? 60;
588
+ if (typeof rrfK !== "number" || !Number.isFinite(rrfK)) {
589
+ throw new Error(`hybridSearch: rrfK must be a finite number (got ${String(rrfK)})`);
590
+ }
591
+ const embedName = opts.embed ?? opts.embedProviderName ?? "ollama";
592
+ const dbDim = getEmbeddingDim(db) ?? void 0;
593
+ const emb = makeEmbeddingProvider(embedName, { dim: dbDim });
594
+ const filters = [];
595
+ const params = {};
596
+ if (opts.product) {
597
+ filters.push("ch.product = @product");
598
+ params.product = opts.product;
599
+ }
600
+ if (opts.since) {
601
+ filters.push("ch.released_at >= @since");
602
+ params.since = opts.since;
603
+ }
604
+ if (opts.until) {
605
+ filters.push("ch.released_at <= @until");
606
+ params.until = opts.until;
607
+ }
608
+ if (opts.kind) {
609
+ filters.push("EXISTS (SELECT 1 FROM changes c WHERE c.id = ch.change_id AND c.kind = @kind)");
610
+ params.kind = opts.kind;
611
+ }
612
+ const whereClause = filters.length > 0 ? `AND ${filters.join(" AND ")}` : "";
613
+ let fts = [];
614
+ try {
615
+ const ftsSql = `
616
+ SELECT ch.id AS id, row_number() OVER (ORDER BY bm25(chunks_fts)) AS rank_pos
617
+ FROM chunks_fts
618
+ JOIN chunks ch ON chunks_fts.rowid = ch.id
619
+ WHERE chunks_fts MATCH @query
620
+ ${whereClause}
621
+ ORDER BY bm25(chunks_fts)
622
+ LIMIT @topK
623
+ `;
624
+ fts = db.prepare(ftsSql).all({ ...params, query, topK: safeTopK });
625
+ } catch (e) {
626
+ const sanitized = query.replace(/[^A-Za-z0-9 ]/g, " ").trim();
627
+ if (sanitized) {
628
+ const ftsSql = `
629
+ SELECT ch.id AS id, row_number() OVER (ORDER BY bm25(chunks_fts)) AS rank_pos
630
+ FROM chunks_fts
631
+ JOIN chunks ch ON chunks_fts.rowid = ch.id
632
+ WHERE chunks_fts MATCH @query
633
+ ${whereClause}
634
+ ORDER BY bm25(chunks_fts)
635
+ LIMIT @topK
636
+ `;
637
+ fts = db.prepare(ftsSql).all({ ...params, query: sanitized, topK: safeTopK });
638
+ }
639
+ }
640
+ const vecAvailable = hasVecTable(db);
641
+ let vec = [];
642
+ if (vecAvailable) {
643
+ const [qvec] = await emb.embed([query]);
644
+ const vecSql = `
645
+ SELECT ch.id AS id, row_number() OVER (ORDER BY distance) AS rank_pos
646
+ FROM chunks_vec
647
+ JOIN chunks ch ON ch.id = chunks_vec.rowid
648
+ WHERE chunks_vec.embedding MATCH @qvec AND k = @topK
649
+ ${whereClause}
650
+ ORDER BY distance
651
+ `;
652
+ vec = db.prepare(vecSql).all({ ...params, qvec, topK: safeTopK });
653
+ } else if (!warnedNoVec && !process.env.MCP_QUIET && !process.env.CLAUDE_SYNERGY_QUIET) {
654
+ console.warn("[hybrid] sqlite-vec table not found; using BM25-only");
655
+ warnedNoVec = true;
656
+ }
657
+ const scores = /* @__PURE__ */ new Map();
658
+ for (const r of fts) {
659
+ const cur = scores.get(r.id) ?? { bm25: null, vec: null, score: 0 };
660
+ cur.bm25 = r.rank_pos;
661
+ cur.score += 1 / (rrfK + r.rank_pos);
662
+ scores.set(r.id, cur);
663
+ }
664
+ for (const r of vec) {
665
+ const cur = scores.get(r.id) ?? { bm25: null, vec: null, score: 0 };
666
+ cur.vec = r.rank_pos;
667
+ cur.score += 1 / (rrfK + r.rank_pos);
668
+ scores.set(r.id, cur);
669
+ }
670
+ if (scores.size === 0) return [];
671
+ const rrfRanked = Array.from(scores.entries()).sort(([, a], [, b]) => b.score - a.score).slice(0, safeRerankN);
672
+ const candidateIds = rrfRanked.map(([id]) => id);
673
+ const placeholders = candidateIds.map(() => "?").join(",");
674
+ const rowsSql = `
675
+ SELECT ch.id AS chunk_id, ch.change_id, ch.product, ch.release_version AS version,
676
+ ch.released_at, c.kind, c.text, ch.contextualized
677
+ FROM chunks ch
678
+ JOIN changes c ON c.id = ch.change_id
679
+ WHERE ch.id IN (${placeholders})
680
+ `;
681
+ const rows = db.prepare(rowsSql).all(...candidateIds);
682
+ const byId = /* @__PURE__ */ new Map();
683
+ for (const r of rows) byId.set(r.chunk_id, r);
684
+ const rerankProviderName = opts.rerankProviderName ?? (isKnownReranker(opts.rerank) ? opts.rerank : "none");
685
+ let rerankScores = /* @__PURE__ */ new Map();
686
+ if (rerankProviderName !== "none") {
687
+ const reranker = makeRerankProvider(rerankProviderName);
688
+ const candidates = rrfRanked.slice(0, rerankRequested).map(([id]) => ({ id, text: byId.get(id)?.contextualized ?? byId.get(id)?.text ?? "" })).filter((c) => c.text);
689
+ const results = await reranker.rerank(query, candidates);
690
+ for (const r of results) rerankScores.set(r.id, r.score);
691
+ }
692
+ const final = rrfRanked.map(([id, score]) => ({
693
+ id,
694
+ rrf: score.score,
695
+ bm25: score.bm25,
696
+ vec: score.vec,
697
+ rerank: rerankScores.get(id) ?? null
698
+ })).sort((a, b) => {
699
+ if (rerankProviderName !== "none" && a.rerank !== null && b.rerank !== null) {
700
+ return b.rerank - a.rerank;
701
+ }
702
+ return b.rrf - a.rrf;
703
+ }).slice(0, safeLimit);
704
+ return final.map((entry) => {
705
+ const r = byId.get(entry.id);
706
+ if (!r) return null;
707
+ return {
708
+ ...r,
709
+ bm25_rank: entry.bm25,
710
+ vec_rank: entry.vec,
711
+ rrf_score: entry.rrf,
712
+ rerank_score: entry.rerank
713
+ };
714
+ }).filter(Boolean);
715
+ }
716
+ function isKnownReranker(v) {
717
+ return v === "none" || v === "ollama-judge" || v === "voyage" || v === "cohere";
718
+ }
719
+ function makeRerankProvider(name) {
720
+ switch (name) {
721
+ case "ollama-judge":
722
+ return new OllamaJudgeRerankProvider();
723
+ case "voyage":
724
+ return new VoyageRerankProvider();
725
+ case "cohere":
726
+ return new CohereRerankProvider();
727
+ }
728
+ }
729
+
730
+ export {
731
+ searchChanges,
732
+ lookupEntity,
733
+ recentReleases,
734
+ listProducts,
735
+ getSyncStatus,
736
+ entityFrequency,
737
+ browseChanges,
738
+ getChangesSince,
739
+ compareVersions,
740
+ listSynergies,
741
+ getSynergy,
742
+ hybridSearch
743
+ };